问:
Why am I getting a 'public_stream ! = nullptr' error on execution, even though I have successfully used 'fopen_s' to read a file?
I am writing a scheduling algorithm while studying the Operating System.

And 'fopen_s' was used to receive information about the process from a 'txt' file.

First, I checked the function's output with 'errno_t', and it was normal with '0'.

However, if I try to execute it, an error such as an image appears and cannot proceed. Where did the error occur?

This code was written in Visual Studio 2017 using the c language.

This is 'process.txt'. (All are integers.)

```<code>1 1 0 10 3
1 2 0 1 1
1 3 0 2 4
1 4 0 5 2
2 5 0 5 2
2 6 0 4 3
2 7 0 1 2
2 8 0 7 1
3 9 0 5 2
3 10 0 4 3
3 11 0 1 4
3 12 0 6 1
</code>```

This is the core code that causes the error.

```<code>int main()
{
    sem_init(&semaphore, 0, 1);
    q1 = (Process *)malloc(sizeof(Process) * 100);
    q2 = (Process *)malloc(sizeof(Process) * 100);
    q3 = (Process *)malloc(sizeof(Process) * 100);

    FILE *fpp = NULL;
    errno_t err = fopen_s(&fpp, "sample.txt", "r");

    if (fpp = NULL)
    {
        printf("OPEN ERROR\n");
        return 0;
    }

    while (!feof(fpp))
    {
        fscanf_s(fpp, "%d %d %d %d %d",
            &class_num, &sub_id, &sub_arrive_time, &sub_burst, &sub_priority);

        if (class_num == 1)
        {
            q1[i_q1].id = sub_id;
            q1[i_q1].arrive_time = sub_arrive_time;
            q1[i_q1].burst = sub_burst;
            q1[i_q1].priority = sub_priority;
            i_q1++;
        }
        else if (class_num = 2)
        {
            q2[i_q2].id = sub_id;
            q2[i_q2].arrive_time = sub_arrive_time;
            q2[i_q2].burst = sub_burst;
            q2[i_q2].priority = sub_priority;
            i_q2++;
        }
        else if (class_num = 3)
        {
            q3[i_q3].id = sub_id;
            q3[i_q3].arrive_time = sub_arrive_time;
            q3[i_q3].burst = sub_burst;
            q3[i_q3].priority = sub_priority;
            i_q3++;
        }
        p_count++;
    }//초기화 완료

    pthread_create(&thread[idx], NULL, MLQS, NULL);//별도의 함수 만들어서 넣기
    pthread_join(thread[idx], NULL);

    fclose(fpp);
    free(q1);
    free(q2);
    free(q3);
    system("pause");
    return 0;
}
</code>```

This is the full code.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <pthread.h>
#include <semaphore.h>

#define TRUE 1
#define FALSE 0

typedef struct _process {
    int id;
    int arrive_time;
    int waiting_time;
    int return_time;
    int turnaround_time;
    int response_time;
    int burst;
    int priority;
    int completed;
}Process;

//쓰레드 동기화를 동기화를 위한 semaphore
sem_t semaphore;

int process_count = 0;
int p_count = 0;
int i_q1 = 0;
int i_q2 = 0;
int i_q3 = 0;

int class_num;
int sub_id;
int sub_arrive_time;
int sub_burst;
int sub_priority;

Process *q1;
Process *q2;
Process *q3;

int idx = 0;
pthread_t thread[5];

int time_quantum = 2;

//프로세스 초기화
void p_init(Process p[], int length)
{
    int i;

    for (i = 0; i < length; i++)
    {
        p[i].waiting_time = 0;
        p[i].return_time = 0;
        p[i].response_time = 0;
        p[i].completed = FALSE;
    }
}
int all_completed(Process *p1, Process *p2, Process *p3, int q1_len, int q2_len, int q3_len)
{
    int i;
    for (i = 0; i < q1_len; i++)
    {
        if (p1[i].completed == FALSE)
            return FALSE;
    }
    for (i = 0; i < q2_len; i++)
    {
        if (p2[i].completed == FALSE)
            return FALSE;
    }
    for (i = 0; i < q2_len; i++)
    {
        if (p3[i].completed == FALSE)
            return FALSE;
    }
    return TRUE;
}

void print_table(Process p[], int n)
{
    int i;
    // 반복문에서 사용할 변수 선언

    puts("\t+-----+------------+-------------+----------+-------------+-----------------+--------------+-----------------+");
    puts("\t| PID | Burst Time | Arrive Time | Priority | Return Time |  Response Time  | Waiting Time | Turnaround Time |");
    puts("\t+-----+------------+-------------+----------+-------------+-----------------+--------------+-----------------+");

    /* 프로세스 갯수만큼 반복하며 포맷을 맞추어 출력 */
    for (i = 0; i < n; i++)
    {
        printf("\t| %3d |     %3d    |     %3d     |    %3d   |     %3d     |      %3d        |      %3d     |        %3d      |\n",
            p[i].id, p[i].burst, p[i].arrive_time, p[i].priority, p[i].return_time, p[i].response_time, p[i].waiting_time, p[i].turnaround_time);

        puts("\t+-----+------------+-------------+----------+-------------+-----------------+--------------+-----------------+");
    }

    puts("\n");
}

// 반환 시간을 비교하는 함수
int compare_by_return_time(const void *a, const void *b)
{
    Process *pA = (Process *)a;
    Process *pB = (Process *)b;

    /* pA의 반환 시간이 작을 경우 */
    if (pA->return_time < pB->return_time)
        return -1;

    /* ptA의 반환 시간이 클 경우 */
    else if (pA->return_time > pB->return_time)
        return 1;

    /* 반환 시간이 같을 경우 -> 존재 X */
    else
        return 0;
}
// 반환 시간을 퀵 소트 기반으로 정렬한다.
void quick_sort_by_return_time(Process p[], int len)
{
    qsort(p, len, sizeof(Process), compare_by_return_time);
}

// 우선 순위를 비교하는 함수
int compare_by_priority(Process *a, Process *b)
{
    Process *pA = (Process *)a;
    Process *pB = (Process *)b;

    if (a->priority == b->priority) {
        if (a->burst != b->burst) {
            if (a->burst < b->burst)
                return -1;
            else
                return 1;
        }
        else
            return 0;
    }
    else {
        if (a->priority < b->priority)
            return -1;
        else if (a->priority > b->priority)
            return 1;
    }
}

void quick_sort_by_priority_time()
{
    qsort(q1, i_q1, sizeof(Process), compare_by_priority);
}

void gantt_chart(Process p[], int len)
{
    int i, j; // 반복문에 사용할 변수

    printf("\t ");

    for (i = 0; i < len; i++)
    {
        for (j = 0; j < p[i].burst; j++)
            printf("--");

        printf(" ");
    }

    printf("\n\t|");

    for (i = 0; i < len; i++)
    {
        for (j = 0; j < p[i].burst - 1; j++)
            printf(" ");

        printf("%d", p[i].id);

        for (j = 0; j < p[i].burst - 1; j++)
            printf(" ");

        printf("|");
    }

    printf("\n\t ");

    for (i = 0; i < len; i++)
    {
        for (j = 0; j < p[i].burst; j++)
            printf("--");

        printf(" ");
    }

    printf("\n\t");

    printf("0");

    for (i = 0; i < len; i++)
    {
        for (j = 0; j < p[i].burst; j++)
            printf("  ");

        if (p[i].return_time > 9)
            printf("\b");

        printf("%d", p[i].return_time);
    }

    printf("\n");
}
//**************************************************//
// Q1 : Non-preemptive Priority Scheduling Algorithm

// 알고리즘 시간 계산 함수
void Cal_for_npps(Process p[], int len)
{
    int i, j; // 반복문에 사용할 변수
    int check; // 모든 프로세스 완료 여부 확인
    int min; // Priority가 가장 높은 index 저장
    int time = 0; // 현재 시간

    p[0].return_time = p[0].burst;
    p[0].turnaround_time = p[0].return_time - p[0].arrive_time;
    p[0].response_time = 0;
    p[0].completed = TRUE;

    time = p[0].burst;

    while (TRUE)//모든 프로세스 완료 시 종료
    {
        min = INT_MAX;
        check = FALSE;

        for (i = 1; i < len; i++)//Priority가 가장 높은 프로세스 탐색
        {
            if ((p[min].priority > p[i].priority) && (p[i].completed == FALSE))
            {//현재 Priority보다 작은 Priority 가졌지만 실행되지 않았다면 갱신
                min = i;
                check = TRUE;
            }
        }

        if (check == FALSE)//모든 프로세스 완료 시 반복문 탈출
            break;

        p[min].response_time = time - p[min].arrive_time;
        p[min].return_time = time + p[min].burst;
        p[min].turnaround_time = p[min].return_time - p[min].arrive_time;
        p[min].waiting_time = time - p[min].arrive_time;
        p[min].completed = TRUE;

        time += p[min].burst;
    }
}

void *NPPS(void *arg)
{
    int i; // 반복문에 사용할 변수
    int total_waiting_time = 0;
    int total_turnaround_time = 0;
    int total_response_time = 0;

    p_init(q1, i_q1);

    quick_sort_by_priority_time();

    Cal_for_npps(q1, i_q1);

    for (i = 0; i < i_q1; i++)
    {
        total_waiting_time += q1[i].waiting_time;
        total_turnaround_time += q1[i].turnaround_time;
        total_response_time += q1[i].response_time;
    }

    quick_sort_by_return_time(q1, i_q1);

    printf("\tNon-preemptive Priority Scheduling Algorithm\n\n");

    gantt_chart(q1, i_q1);

    printf("\n\tAverage Waiting Time     : %-2.2lf\n", (double)total_waiting_time / (double)i_q1);
    printf("\tAverage Turnaround Time  : %-2.2lf\n", (double)total_turnaround_time / (double)i_q1);
    printf("\tAverage Response Time    : %-2.2lf\n\n", (double)total_response_time / (double)i_q1);

    print_table(q1, i_q1);
}

//**************************************************//
// Q2 : HRN(Highest Response-Ratio Next)

void *HRN(void *arg)
{
    int i, j; // 반복문에 사용할 변수
    int time, locate; // 현재 시간과 프로세스 위치
    int total_burst_time = 0;
    int total_waiting_time = 0;
    int total_turnaround_time = 0;
    int total_response_time = 0;

    float hrr, temp; // 우선순위 저장

    p_init(q2, i_q2);

    for (i = 0; i < i_q2; i++)
    {
        total_burst_time += q2[i].burst;
    }

    for (time = q2[0].arrive_time; time < total_burst_time;)
    {
        hrr = -99999;

        for (i = 0; i < i_q2; i++)// Priority가 가장 높은 프로세스 탐색
        {
            if (q2[i].completed != TRUE)
            {
                temp = (q2[i].burst + (time - q2[i].arrive_time)) / q2[i].burst;

                if (hrr < temp)//우선순위 갱신
                {
                    hrr = temp;
                    locate = i;
                }
            }
        }

        time += q2[locate].burst;

        q2[locate].waiting_time = time - q2[locate].arrive_time - q2[locate].burst;
        q2[locate].turnaround_time = time - q2[locate].arrive_time;
        q2[locate].return_time = q2[locate].turnaround_time + q2[locate].arrive_time;
        q2[locate].response_time = q2[locate].waiting_time;
        q2[locate].completed = TRUE;

        total_waiting_time += q2[locate].waiting_time;
        total_turnaround_time += q2[locate].turnaround_time;
        total_response_time += q2[locate].response_time;
    }
    quick_sort_by_return_time(q2, i_q2);

    printf("\tHighest Response Ratio Next Scheduling Algorithm\n\n");

    gantt_chart(q2, i_q2);

    printf("\n\tAverage Waiting Time     : %-2.2lf\n", (double)total_waiting_time / (double)i_q2);
    printf("\tAverage Turnaround Time  : %-2.2lf\n", (double)total_turnaround_time / (double)i_q2);
    printf("\tAverage Response Time    : %-2.2lf\n\n", (double)total_response_time / (double)i_q2);

    print_table(q2, i_q2);
}

void cal_for_sjf(Process *p, int len)
{
    int i, j; // 반복문에 사용할 변수
    int cur_time = 0; // 현재 시간
    int min = 0; // 최소 시간을 갖는 인덱스 저장

    p[0].completed = TRUE;
    p[0].return_time = p[0].burst;
    p[0].turnaround_time = p[0].burst - p[0].arrive_time;
    p[0].waiting_time = 0;

    cur_time = p[0].burst;

    for (i = 1; i < len; i++)
    {
        for (j = 1; j < len; j++)
        {
            if (p[j].completed == TRUE)
                continue;

            else
            {
                min = j;
                break;
            }
        }

        for (j = 1; j < len; j++)
        {
            if ((p[j].completed == FALSE) && (p[j].burst < p[min].burst))
            {
                min = j;
            }
        }

        p[min].waiting_time = cur_time - p[min].arrive_time;
        p[min].completed = TRUE;
        cur_time += p[min].burst;
        p[min].return_time = cur_time;
        p[min].turnaround_time = p[min].return_time - p[min].arrive_time;
    }
}

void *SJF(void *arg)
{
    int i;
    int total_waiting_time = 0;
    int total_turnaround_time = 0;
    int total_response_time = 0;

    p_init(q3, i_q3);

    cal_for_sjf(q3, i_q3);

    for (i = 0; i < i_q3; i++)
    {
        q3[i].return_time = q3[i].turnaround_time + q3[i].arrive_time;
        q3[i].response_time = q3[i].waiting_time;
        total_waiting_time += q3[i].waiting_time;
        total_turnaround_time += q3[i].turnaround_time;
        total_response_time += q3[i].response_time;
    }

    printf("\tSJF Scheduling Algorithms\n\n");

    quick_sort_by_return_time(q3, i_q3);

    gantt_chart(q3, i_q3);

    printf("\n\tAverage Waiting Time     : %-2.2lf\n", (double)total_waiting_time / (double)i_q3);
    printf("\tAverage Turnaround Time  : %-2.2lf\n", (double)total_turnaround_time / (double)i_q3);
    printf("\tAverage Response Time    : %-2.2lf\n\n", (double)total_response_time / (double)i_q3);

    print_table(q3, i_q3);
}

void *MLQS(void *arg)
{
    idx++;
    while (all_completed(q1, q2, q3, i_q1, i_q2, i_q3)) {
        sem_wait(&semaphore);
        if (idx == 1) {
            pthread_create(&thread[idx], NULL, NPPS, NULL);
            pthread_join(thread[idx], NULL);
        }
        else if (idx == 2) {
            pthread_create(&thread[idx], NULL, HRN, NULL);
            pthread_join(thread[idx], NULL);
        }
        else if (idx == 3) {
            pthread_create(&thread[idx], NULL, SJF, NULL);
            pthread_join(thread[idx], NULL);
        }
        idx++;
        sem_post(&semaphore);
        if (idx > 3)
            idx = 1;
    }
}

int main()
{
    sem_init(&semaphore, 0, 1);
    q1 = (Process *)malloc(sizeof(Process) * 100);
    q2 = (Process *)malloc(sizeof(Process) * 100);
    q3 = (Process *)malloc(sizeof(Process) * 100);

    FILE *fpp = NULL;
    errno_t err = fopen_s(&fpp, "sample.txt", "r");

    if (fpp = NULL)
    {
        printf("OPEN ERROR\n");
        return 0;
    }

    while (!feof(fpp))
    {
        fscanf_s(fpp, "%d %d %d %d %d",
            &class_num, &sub_id, &sub_arrive_time, &sub_burst, &sub_priority);

        if (class_num == 1)
        {
            q1[i_q1].id = sub_id;
            q1[i_q1].arrive_time = sub_arrive_time;
            q1[i_q1].burst = sub_burst;
            q1[i_q1].priority = sub_priority;
            i_q1++;
        }
        else if (class_num = 2)
        {
            q2[i_q2].id = sub_id;
            q2[i_q2].arrive_time = sub_arrive_time;
            q2[i_q2].burst = sub_burst;
            q2[i_q2].priority = sub_priority;
            i_q2++;
        }
        else if (class_num = 3)
        {
            q3[i_q3].id = sub_id;
            q3[i_q3].arrive_time = sub_arrive_time;
            q3[i_q3].burst = sub_burst;
            q3[i_q3].priority = sub_priority;
            i_q3++;
        }
        p_count++;
    }//초기화 완료

    pthread_create(&thread[idx], NULL, MLQS, NULL);//별도의 함수 만들어서 넣기
    pthread_join(thread[idx], NULL);

    fclose(fpp);
    free(q1);
    free(q2);
    free(q3);
    system("pause");
    return 0;
}

</code>```

答:
Beside all the issues mentioned in the comments:

```<code> if (fpp = NULL)
</code>```

assigns NULL to ffp instead of comparing it (and the condition is always false). You mean

```<code>if (fpp == NULL)
</code>```

Body:
I am writing a scheduling algorithm while studying the Operating System.

And 'fopen_s' was used to receive information about the process from a 'txt' file.

First, I checked the function's output with 'errno_t', and it was normal with '0'.

However, if I try to execute it, an error such as an image appears and cannot proceed. Where did the error occur?

This code was written in Visual Studio 2017 using the c language.

This is 'process.txt'. (All are integers.)

1 1 0 10 3
1 2 0 1 1
1 3 0 2 4
1 4 0 5 2
2 5 0 5 2
2 6 0 4 3
2 7 0 1 2
2 8 0 7 1
3 9 0 5 2
3 10 0 4 3
3 11 0 1 4
3 12 0 6 1

This is the core code that causes the error.

int main()
{
    sem_init(&semaphore, 0, 1);
    q1 = (Process *)malloc(sizeof(Process) * 100);
    q2 = (Process *)malloc(sizeof(Process) * 100);
    q3 = (Process *)malloc(sizeof(Process) * 100);

    FILE *fpp = NULL;
    errno_t err = fopen_s(&fpp, "sample.txt", "r");

    if (fpp = NULL)
    {
        printf("OPEN ERROR\n");
        return 0;
    }

    while (!feof(fpp))
    {
        fscanf_s(fpp, "%d %d %d %d %d",
            &class_num, &sub_id, &sub_arrive_time, &sub_burst, &sub_priority);

        if (class_num == 1)
        {
            q1[i_q1].id = sub_id;
            q1[i_q1].arrive_time = sub_arrive_time;
            q1[i_q1].burst = sub_burst;
            q1[i_q1].priority = sub_priority;
            i_q1++;
        }
        else if (class_num = 2)
        {
            q2[i_q2].id = sub_id;
            q2[i_q2].arrive_time = sub_arrive_time;
            q2[i_q2].burst = sub_burst;
            q2[i_q2].priority = sub_priority;
            i_q2++;
        }
        else if (class_num = 3)
        {
            q3[i_q3].id = sub_id;
            q3[i_q3].arrive_time = sub_arrive_time;
            q3[i_q3].burst = sub_burst;
            q3[i_q3].priority = sub_priority;
            i_q3++;
        }
        p_count++;
    }//초기화 완료

    pthread_create(&thread[idx], NULL, MLQS, NULL);//별도의 함수 만들어서 넣기
    pthread_join(thread[idx], NULL);

    fclose(fpp);
    free(q1);
    free(q2);
    free(q3);
    system("pause");
    return 0;
}

This is the full code.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <pthread.h>
#include <semaphore.h>

#define TRUE 1
#define FALSE 0

typedef struct _process {
    int id;
    int arrive_time;
    int waiting_time;
    int return_time;
    int turnaround_time;
    int response_time;
    int burst;
    int priority;
    int completed;
}Process;

//쓰레드 동기화를 동기화를 위한 semaphore
sem_t semaphore;

int process_count = 0;
int p_count = 0;
int i_q1 = 0;
int i_q2 = 0;
int i_q3 = 0;

int class_num;
int sub_id;
int sub_arrive_time;
int sub_burst;
int sub_priority;

Process *q1;
Process *q2;
Process *q3;

int idx = 0;
pthread_t thread[5];

int time_quantum = 2;

//프로세스 초기화
void p_init(Process p[], int length)
{
    int i;

    for (i = 0; i < length; i++)
    {
        p[i].waiting_time = 0;
        p[i].return_time = 0;
        p[i].response_time = 0;
        p[i].completed = FALSE;
    }
}
int all_completed(Process *p1, Process *p2, Process *p3, int q1_len, int q2_len, int q3_len)
{
    int i;
    for (i = 0; i < q1_len; i++)
    {
        if (p1[i].completed == FALSE)
            return FALSE;
    }
    for (i = 0; i < q2_len; i++)
    {
        if (p2[i].completed == FALSE)
            return FALSE;
    }
    for (i = 0; i < q2_len; i++)
    {
        if (p3[i].completed == FALSE)
            return FALSE;
    }
    return TRUE;
}

void print_table(Process p[], int n)
{
    int i;
    // 반복문에서 사용할 변수 선언

    puts("\t+-----+------------+-------------+----------+-------------+-----------------+--------------+-----------------+");
    puts("\t| PID | Burst Time | Arrive Time | Priority | Return Time |  Response Time  | Waiting Time | Turnaround Time |");
    puts("\t+-----+------------+-------------+----------+-------------+-----------------+--------------+-----------------+");

    /* 프로세스 갯수만큼 반복하며 포맷을 맞추어 출력 */
    for (i = 0; i < n; i++)
    {
        printf("\t| %3d |     %3d    |     %3d     |    %3d   |     %3d     |      %3d        |      %3d     |        %3d      |\n",
            p[i].id, p[i].burst, p[i].arrive_time, p[i].priority, p[i].return_time, p[i].response_time, p[i].waiting_time, p[i].turnaround_time);

        puts("\t+-----+------------+-------------+----------+-------------+-----------------+--------------+-----------------+");
    }

    puts("\n");
}

// 반환 시간을 비교하는 함수
int compare_by_return_time(const void *a, const void *b)
{
    Process *pA = (Process *)a;
    Process *pB = (Process *)b;

    /* pA의 반환 시간이 작을 경우 */
    if (pA->return_time < pB->return_time)
        return -1;

    /* ptA의 반환 시간이 클 경우 */
    else if (pA->return_time > pB->return_time)
        return 1;

    /* 반환 시간이 같을 경우 -> 존재 X */
    else
        return 0;
}
// 반환 시간을 퀵 소트 기반으로 정렬한다.
void quick_sort_by_return_time(Process p[], int len)
{
    qsort(p, len, sizeof(Process), compare_by_return_time);
}

// 우선 순위를 비교하는 함수
int compare_by_priority(Process *a, Process *b)
{
    Process *pA = (Process *)a;
    Process *pB = (Process *)b;

    if (a->priority == b->priority) {
        if (a->burst != b->burst) {
            if (a->burst burst)
                return -1;
            else
                return 1;
        }
        else
            return 0;
    }
    else {
        if (a->priority priority)
            return -1;
        else if (a->priority > b->priority)
            return 1;
    }
}

void quick_sort_by_priority_time()
{
    qsort(q1, i_q1, sizeof(Process), compare_by_priority);
}

void gantt_chart(Process p[], int len)
{
    int i, j; // 반복문에 사용할 변수

    printf("\t ");

    for (i = 0; i < len; i++)
    {
        for (j = 0; j < p[i].burst; j++)
            printf("--");

        printf(" ");
    }

    printf("\n\t|");

    for (i = 0; i < len; i++)
    {
        for (j = 0; j < p[i].burst - 1; j++)
            printf(" ");

        printf("%d", p[i].id);

        for (j = 0; j < p[i].burst - 1; j++)
            printf(" ");

        printf("|");
    }

    printf("\n\t ");

    for (i = 0; i < len; i++)
    {
        for (j = 0; j < p[i].burst; j++)
            printf("--");

        printf(" ");
    }

    printf("\n\t");

    printf("0");

    for (i = 0; i < len; i++)
    {
        for (j = 0; j
 9)
            printf("\b");

        printf("%d", p[i].return_time);
    }

    printf("\n");
}
//**************************************************//
// Q1 : Non-preemptive Priority Scheduling Algorithm

// 알고리즘 시간 계산 함수
void Cal_for_npps(Process p[], int len)
{
    int i, j; // 반복문에 사용할 변수
    int check; // 모든 프로세스 완료 여부 확인
    int min; // Priority가 가장 높은 index 저장
    int time = 0; // 현재 시간

    p[0].return_time = p[0].burst;
    p[0].turnaround_time = p[0].return_time - p[0].arrive_time;
    p[0].response_time = 0;
    p[0].completed = TRUE;

    time = p[0].burst;

    while (TRUE)//모든 프로세스 완료 시 종료
    {
        min = INT_MAX;
        check = FALSE;

        for (i = 1; i < len; i++)//Priority가 가장 높은 프로세스 탐색
        {
            if ((p[min].priority > p[i].priority) && (p[i].completed == FALSE))
            {//현재 Priority보다 작은 Priority 가졌지만 실행되지 않았다면 갱신
                min = i;
                check = TRUE;
            }
        }

        if (check == FALSE)//모든 프로세스 완료 시 반복문 탈출
            break;

        p[min].response_time = time - p[min].arrive_time;
        p[min].return_time = time + p[min].burst;
        p[min].turnaround_time = p[min].return_time - p[min].arrive_time;
        p[min].waiting_time = time - p[min].arrive_time;
        p[min].completed = TRUE;

        time += p[min].burst;
    }
}

void *NPPS(void *arg)
{
    int i; // 반복문에 사용할 변수
    int total_waiting_time = 0;
    int total_turnaround_time = 0;
    int total_response_time = 0;

    p_init(q1, i_q1);

    quick_sort_by_priority_time();

    Cal_for_npps(q1, i_q1);

    for (i = 0; i < i_q1; i++)
    {
        total_waiting_time += q1[i].waiting_time;
        total_turnaround_time += q1[i].turnaround_time;
        total_response_time += q1[i].response_time;
    }

    quick_sort_by_return_time(q1, i_q1);

    printf("\tNon-preemptive Priority Scheduling Algorithm\n\n");

    gantt_chart(q1, i_q1);

    printf("\n\tAverage Waiting Time     : %-2.2lf\n", (double)total_waiting_time / (double)i_q1);
    printf("\tAverage Turnaround Time  : %-2.2lf\n", (double)total_turnaround_time / (double)i_q1);
    printf("\tAverage Response Time    : %-2.2lf\n\n", (double)total_response_time / (double)i_q1);

    print_table(q1, i_q1);
}

//**************************************************//
// Q2 : HRN(Highest Response-Ratio Next)

void *HRN(void *arg)
{
    int i, j; // 반복문에 사용할 변수
    int time, locate; // 현재 시간과 프로세스 위치
    int total_burst_time = 0;
    int total_waiting_time = 0;
    int total_turnaround_time = 0;
    int total_response_time = 0;

    float hrr, temp; // 우선순위 저장

    p_init(q2, i_q2);

    for (i = 0; i < i_q2; i++)
    {
        total_burst_time += q2[i].burst;
    }

    for (time = q2[0].arrive_time; time < total_burst_time;)
    {
        hrr = -99999;

        for (i = 0; i < i_q2; i++)// Priority가 가장 높은 프로세스 탐색
        {
            if (q2[i].completed != TRUE)
            {
                temp = (q2[i].burst + (time - q2[i].arrive_time)) / q2[i].burst;

                if (hrr < temp)//우선순위 갱신
                {
                    hrr = temp;
                    locate = i;
                }
            }
        }

        time += q2[locate].burst;

        q2[locate].waiting_time = time - q2[locate].arrive_time - q2[locate].burst;
        q2[locate].turnaround_time = time - q2[locate].arrive_time;
        q2[locate].return_time = q2[locate].turnaround_time + q2[locate].arrive_time;
        q2[locate].response_time = q2[locate].waiting_time;
        q2[locate].completed = TRUE;

        total_waiting_time += q2[locate].waiting_time;
        total_turnaround_time += q2[locate].turnaround_time;
        total_response_time += q2[locate].response_time;
    }
    quick_sort_by_return_time(q2, i_q2);

    printf("\tHighest Response Ratio Next Scheduling Algorithm\n\n");

    gantt_chart(q2, i_q2);

    printf("\n\tAverage Waiting Time     : %-2.2lf\n", (double)total_waiting_time / (double)i_q2);
    printf("\tAverage Turnaround Time  : %-2.2lf\n", (double)total_turnaround_time / (double)i_q2);
    printf("\tAverage Response Time    : %-2.2lf\n\n", (double)total_response_time / (double)i_q2);

    print_table(q2, i_q2);
}

void cal_for_sjf(Process *p, int len)
{
    int i, j; // 반복문에 사용할 변수
    int cur_time = 0; // 현재 시간
    int min = 0; // 최소 시간을 갖는 인덱스 저장

    p[0].completed = TRUE;
    p[0].return_time = p[0].burst;
    p[0].turnaround_time = p[0].burst - p[0].arrive_time;
    p[0].waiting_time = 0;

    cur_time = p[0].burst;

    for (i = 1; i < len; i++)
    {
        for (j = 1; j < len; j++)
        {
            if (p[j].completed == TRUE)
                continue;

            else
            {
                min = j;
                break;
            }
        }

        for (j = 1; j < len; j++)
        {
            if ((p[j].completed == FALSE) && (p[j].burst < p[min].burst))
            {
                min = j;
            }
        }

        p[min].waiting_time = cur_time - p[min].arrive_time;
        p[min].completed = TRUE;
        cur_time += p[min].burst;
        p[min].return_time = cur_time;
        p[min].turnaround_time = p[min].return_time - p[min].arrive_time;
    }
}

void *SJF(void *arg)
{
    int i;
    int total_waiting_time = 0;
    int total_turnaround_time = 0;
    int total_response_time = 0;

    p_init(q3, i_q3);

    cal_for_sjf(q3, i_q3);

    for (i = 0; i < i_q3; i++)
    {
        q3[i].return_time = q3[i].turnaround_time + q3[i].arrive_time;
        q3[i].response_time = q3[i].waiting_time;
        total_waiting_time += q3[i].waiting_time;
        total_turnaround_time += q3[i].turnaround_time;
        total_response_time += q3[i].response_time;
    }

    printf("\tSJF Scheduling Algorithms\n\n");

    quick_sort_by_return_time(q3, i_q3);

    gantt_chart(q3, i_q3);

    printf("\n\tAverage Waiting Time     : %-2.2lf\n", (double)total_waiting_time / (double)i_q3);
    printf("\tAverage Turnaround Time  : %-2.2lf\n", (double)total_turnaround_time / (double)i_q3);
    printf("\tAverage Response Time    : %-2.2lf\n\n", (double)total_response_time / (double)i_q3);

    print_table(q3, i_q3);
}

void *MLQS(void *arg)
{
    idx++;
    while (all_completed(q1, q2, q3, i_q1, i_q2, i_q3)) {
        sem_wait(&semaphore);
        if (idx == 1) {
            pthread_create(&thread[idx], NULL, NPPS, NULL);
            pthread_join(thread[idx], NULL);
        }
        else if (idx == 2) {
            pthread_create(&thread[idx], NULL, HRN, NULL);
            pthread_join(thread[idx], NULL);
        }
        else if (idx == 3) {
            pthread_create(&thread[idx], NULL, SJF, NULL);
            pthread_join(thread[idx], NULL);
        }
        idx++;
        sem_post(&semaphore);
        if (idx > 3)
            idx = 1;
    }
}

int main()
{
    sem_init(&semaphore, 0, 1);
    q1 = (Process *)malloc(sizeof(Process) * 100);
    q2 = (Process *)malloc(sizeof(Process) * 100);
    q3 = (Process *)malloc(sizeof(Process) * 100);

    FILE *fpp = NULL;
    errno_t err = fopen_s(&fpp, "sample.txt", "r");

    if (fpp = NULL)
    {
        printf("OPEN ERROR\n");
        return 0;
    }

    while (!feof(fpp))
    {
        fscanf_s(fpp, "%d %d %d %d %d",
            &class_num, &sub_id, &sub_arrive_time, &sub_burst, &sub_priority);

        if (class_num == 1)
        {
            q1[i_q1].id = sub_id;
            q1[i_q1].arrive_time = sub_arrive_time;
            q1[i_q1].burst = sub_burst;
            q1[i_q1].priority = sub_priority;
            i_q1++;
        }
        else if (class_num = 2)
        {
            q2[i_q2].id = sub_id;
            q2[i_q2].arrive_time = sub_arrive_time;
            q2[i_q2].burst = sub_burst;
            q2[i_q2].priority = sub_priority;
            i_q2++;
        }
        else if (class_num = 3)
        {
            q3[i_q3].id = sub_id;
            q3[i_q3].arrive_time = sub_arrive_time;
            q3[i_q3].burst = sub_burst;
            q3[i_q3].priority = sub_priority;
            i_q3++;
        }
        p_count++;
    }//초기화 완료

    pthread_create(&thread[idx], NULL, MLQS, NULL);//별도의 함수 만들어서 넣기
    pthread_join(thread[idx], NULL);

    fclose(fpp);
    free(q1);
    free(q2);
    free(q3);
    system("pause");
    return 0;
}

Body:
Beside all the issues mentioned in the comments:

 if (fpp = NULL)

assigns NULL to ffp instead of comparing it (and the condition is always false). You mean

if (fpp == NULL)


来源: stackexchange

问:
MatToolbar throws error when using it with Angular 9
Angular version 9.2.0

When I import the MatToolbarModule in a module and use it in the html template, then I get the following error message:

This likely means that the library (@angular/material/toolbar) which declares MatToolbarModule has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.

```<code>8 export declare class MatToolbarModule {
                       ~~~~~~~~~~~~~~~~
src/app/angular-material.module.ts:53:14 - error NG6002: Appears in the NgModule.imports of ComponentsModule, but itself has errors
</code>```

Does anyone face the same issue?

答:
Add below specific configuration in package.json and npm install.

```<code>{
  "scripts": {
    "postinstall": "ngcc"
  }
}
</code>```

Reference: https://angular.io/guide/ivy#speeding-up-ngcc-compilation

ContentLicense: CC BY-SA 4.0

Body:
Angular version 9.2.0

When I import the MatToolbarModule in a module and use it in the html template, then I get the following error message:

This likely means that the library (@angular/material/toolbar) which declares MatToolbarModule has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.

8 export declare class MatToolbarModule {
                       ~~~~~~~~~~~~~~~~
src/app/angular-material.module.ts:53:14 - error NG6002: Appears in the NgModule.imports of ComponentsModule, but itself has errors

Does anyone face the same issue?

Body:
Add below specific configuration in package.json and npm install.

{
  "scripts": {
    "postinstall": "ngcc"
  }
}

Reference: https://angular.io/guide/ivy#speeding-up-ngcc-compilation


问:
Analyzing data in order of column and then row in R
I have a dataset of logged data at 5 minutes intervals that also includes data at 1 minute intervals denoted by _1 - _5 in the header.
Each row represents a 5 minute interval.

```<code>datetime            temp  speed_1  speed_2  speed_3  speed_4  speed_5
20190710 09:00:00   21    13       14       26       29       32
20190710 09:05:00   21    28       28       29       38       12
20190710 09:10:00   20    8        15       29       30       19
20190711 11:12:00   18    6        9        18       51       49
20190711 11:17:00   17    49       48       48       30       10
</code>```

The actual dataset has an additional 25 columns of data logged at 5 minute intervals and consists of approximately 25000 rows.

I'm looking for an efficient way of analyzing the speed for each day.
For example, if I wanted to plot the speed for each day it would take speed_1 to speed_5 from the earliest entry on a particular day, say 09:00:00, then speed_1 to speed_5 from the next time, 09:05:00, and so on for the whole day.

Currently I have created an additional dataframe for the speed that fills in the times to give:

```<code>datetime            speed
20190710 09:00:00   13
20190710 09:01:00   14
20190710 09:02:00   26
20190710 09:03:00   29
20190710 09:04:00   32
</code>```

This results in having a second df of 125000 entries. I was wondering if there was a more memory efficient way of analyzing the original dataset as the datasets may grow considerably in the future.

Edit: Reproducible code added

structure(list(time = structure(1:3, .Label = c("20190710 09-00-00", "20190710 09-05-00", "20190710 09-10-00"), class = "factor"), temp = c(21, 21, 20), speed_1 = c(13, 28, 8), speed_2 = c(14, 28, 15), speed_3 = c(26, 29, 29), speed_4 = c(29, 38, 30), speed_5 = c(32, 12, 19)), .Names = c("time", "temp", "speed_1", "speed_2", "speed_3", "speed_4", "speed_5"), row.names = c(NA, -3L), class = "data.frame")

答:
Some example data and expected output would help a lot. I gave it a shot anyways. You can do this if you simply want a list of all the speeds for every date.

```<code>dataset <- read.table(text='datetime            temp  speed_1  speed_2  speed_3  speed_4  speed_5
"20190710 09:00:00"   21    13       14       26       29       32
"20190710 09:05:00"   21    28       28       29       38       12
"20190710 09:10:00"   20    8        15       29       30       19
"20190711 11:12:00"   18    6        9        18       51       49
"20190711 11:17:00"   17    49       48       48       30       10',header=T)

dataset$datetime <- as.POSIXlt(dataset$datetime,format="%Y%m%d %H:%M:%OS")

lapply(split(dataset,as.Date(dataset$datetime)), function(x) c(t(x[,3:ncol(x)])) )
</code>```

output:

```<code>  $`2019-07-10`
 [1] 13 14 26 29 32 28 28 29 38 12  8 15 29 30 19

$`2019-07-11`
 [1]  6  9 18 51 49 49 48 48 30 10
</code>```

Edit: Updated answer so that the speeds are in the correct order.

Body:
I have a dataset of logged data at 5 minutes intervals that also includes data at 1 minute intervals denoted by _1 - _5 in the header.
Each row represents a 5 minute interval.

datetime            temp  speed_1  speed_2  speed_3  speed_4  speed_5
20190710 09:00:00   21    13       14       26       29       32
20190710 09:05:00   21    28       28       29       38       12
20190710 09:10:00   20    8        15       29       30       19
20190711 11:12:00   18    6        9        18       51       49
20190711 11:17:00   17    49       48       48       30       10

The actual dataset has an additional 25 columns of data logged at 5 minute intervals and consists of approximately 25000 rows.

I'm looking for an efficient way of analyzing the speed for each day.
For example, if I wanted to plot the speed for each day it would take speed_1 to speed_5 from the earliest entry on a particular day, say 09:00:00, then speed_1 to speed_5 from the next time, 09:05:00, and so on for the whole day.

Currently I have created an additional dataframe for the speed that fills in the times to give:

datetime            speed
20190710 09:00:00   13
20190710 09:01:00   14
20190710 09:02:00   26
20190710 09:03:00   29
20190710 09:04:00   32

This results in having a second df of 125000 entries. I was wondering if there was a more memory efficient way of analyzing the original dataset as the datasets may grow considerably in the future.

Edit: Reproducible code added

structure(list(time = structure(1:3, .Label = c("20190710 09-00-00", "20190710 09-05-00", "20190710 09-10-00"), class = "factor"), temp = c(21, 21, 20), speed_1 = c(13, 28, 8), speed_2 = c(14, 28, 15), speed_3 = c(26, 29, 29), speed_4 = c(29, 38, 30), speed_5 = c(32, 12, 19)), .Names = c("time", "temp", "speed_1", "speed_2", "speed_3", "speed_4", "speed_5"), row.names = c(NA, -3L), class = "data.frame")

Body:
Some example data and expected output would help a lot. I gave it a shot anyways. You can do this if you simply want a list of all the speeds for every date.

dataset <- read.table(text='datetime            temp  speed_1  speed_2  speed_3  speed_4  speed_5
"20190710 09:00:00"   21    13       14       26       29       32
"20190710 09:05:00"   21    28       28       29       38       12
"20190710 09:10:00"   20    8        15       29       30       19
"20190711 11:12:00"   18    6        9        18       51       49
"20190711 11:17:00"   17    49       48       48       30       10',header=T)

dataset$datetime <- as.POSIXlt(dataset$datetime,format="%Y%m%d %H:%M:%OS")

lapply(split(dataset,as.Date(dataset$datetime)), function(x) c(t(x[,3:ncol(x)])) )

output:

  $`2019-07-10`
 [1] 13 14 26 29 32 28 28 29 38 12  8 15 29 30 19

$`2019-07-11`
 [1]  6  9 18 51 49 49 48 48 30 10

Edit: Updated answer so that the speeds are in the correct order.


问:
How do I ignore all hidden properties of class being inherited using reflection?
Im having an issue where I need to get all properties from an object, then sort through the properties and send the values of certain properties to another service. Here is an example of the code:

```<code>public class Class1
{
    public string A { get; set; }
    public bool B  { get; set; }
}

public class Class2 : Class1
{
    public new bool? B { get; set; }
    public bool C { get; set; }
}
</code>```

I need to get all the properties of Class2, however when using Class2.GetType().GetProperties(), the result contains B from Class2 AND Class1. This causes my issue as when looping through each property I am sending B twice, one with the default value of false since it was never set, then the other with the proper value that was set by my service. I need the result to contain B from Class2, A from Class1, and C from Class2 but ignore B from Class1 since it has been hidden with the new keyword.

I have tried looking through the binding flags I can use, but it has not helped. The closest flag I can find is the BindingFlags.DeclaredOnly flag, but that excludes A from Class1, so it will not work for me.

How would I go about ignoring the original property if it has been hidden?

答:
A simple LINQ based solution which works in a generic way for all class hierarchies:</p>

```<code>   var propertiesWithoutHiddenOnes = GetProperties(objectToUpdate.GetType())
            .GroupBy(prop => prop.Name)
            .Select(group => group.Aggregate(
                     (mostSpecificProp, other) => mostSpecificProp.DeclaringType.IsSubclassOf(other.DeclaringType) ? mostSpecificProp : other))
</code>```

Body:
Im having an issue where I need to get all properties from an object, then sort through the properties and send the values of certain properties to another service. Here is an example of the code:

public class Class1
{
    public string A { get; set; }
    public bool B  { get; set; }
}

public class Class2 : Class1
{
    public new bool? B { get; set; }
    public bool C { get; set; }
}

I need to get all the properties of Class2, however when using Class2.GetType().GetProperties(), the result contains B from Class2 AND Class1. This causes my issue as when looping through each property I am sending B twice, one with the default value of false since it was never set, then the other with the proper value that was set by my service. I need the result to contain B from Class2, A from Class1, and C from Class2 but ignore B from Class1 since it has been hidden with the new keyword.

I have tried looking through the binding flags I can use, but it has not helped. The closest flag I can find is the BindingFlags.DeclaredOnly flag, but that excludes A from Class1, so it will not work for me.

How would I go about ignoring the original property if it has been hidden?

Body:
A simple LINQ based solution which works in a generic way for all class hierarchies:

   var propertiesWithoutHiddenOnes = GetProperties(objectToUpdate.GetType())
            .GroupBy(prop => prop.Name)
            .Select(group => group.Aggregate(
                     (mostSpecificProp, other) => mostSpecificProp.DeclaringType.IsSubclassOf(other.DeclaringType) ? mostSpecificProp : other))


问:
How use a print statement from a defined function in Python
How can I call this defined function with customized text before each animation, so i can just print it like print(Anim("text"))?

```<code>import time
import sys

animation = "|/-\\"

def Anim(text):
    for i in range(20):
        time.sleep(0.1)
        sys.stdout.write("\r" + animation[i % len(animation)])
        sys.stdout.flush()
</code>```

答:
Answer: thanks to @Matthias

```<code>sys.stdout.write(f"\r{text}" + animation[i % len(animation)])
</code>```

Body:
How can I call this defined function with customized text before each animation, so i can just print it like print(Anim("text"))?

import time
import sys

animation = "|/-\\"

def Anim(text):
    for i in range(20):
        time.sleep(0.1)
        sys.stdout.write("\r" + animation[i % len(animation)])
        sys.stdout.flush()

Body:
Answer: thanks to @Matthias

sys.stdout.write(f"\r{text}" + animation[i % len(animation)])


问:
C# Boxing of valuetypes. Questions on size and type of boxing wrappers and valuetypes
After reading ValueTypes - RefTypes - EricLippert I have 3 questions:

Because say an 'int' derives from System.ValueType which derives from System.Object,

So how much space really does the value type like 'int' take (seeing that it finally derives from System.Object) ?
Is it only size of int or the extra CLR bookkeeping fields used to distinguish it being value type.

Size difference between 'int' and 'object' ?

When 'int' is boxed with a wrapper. so is it the case that the wrapper is just an object type (and that object goes to heap) ? difference between this wrapper object and plain new object() ? how much size/space does that wrapper result to ?

答:
An int is 32 bits, no matter what, because it's a value.

The Object part only comes into play once you box it (for example in C# cast it to an object). Once that happens, a new object is created with everything an object has, and inside that object resides your int.

This is why C# generics are so amazing, compared to say Java, because you don't force value types into objects just to put them in a generic container, so value types are actually value types the whole time (or until the programmer gets lazy and starts throwing object val=... around).

Edit: I can understand the confusion, because of how amazing a job they did with the compiler:

```<code>var s=12.GetType(); // if it looks like an object and walks like an object...
</code>```

But it is not an object, not until the GetType call, at which point the value gets boxed into an object and you invoke the virtual method on it.

It's the same with ValueType being derived from Object. Just some pretty syntactic sugar the compiler ignores and does weird things behind your back :)

edit2: Here's the dissasembled code showing the boxing:

```<code>.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 1
    .locals init (
        [0] class [mscorlib]System.Type s)
    L_0000: nop
    L_0001: ldc.i4.s 12
    L_0003: box int32          // <---
    L_0008: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
    L_000d: stloc.0
    L_000e: ldloc.0
    L_000f: call void [mscorlib]System.Console::WriteLine(object)
    L_0014: nop
    L_0015: ret
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
An int is 32 bits, no matter what, because it's a value.

The Object part only comes into play once you box it (for example in C# cast it to an object). Once that happens, a new object is created with everything an object has, and inside that object resides your int.

This is why C# generics are so amazing, compared to say Java, because you don't force value types into objects just to put them in a generic container, so value types are actually value types the whole time (or until the programmer gets lazy and starts throwing object val=... around).

Edit: I can understand the confusion, because of how amazing a job they did with the compiler:

var s=12.GetType(); // if it looks like an object and walks like an object...

But it is not an object, not until the GetType call, at which point the value gets boxed into an object and you invoke the virtual method on it.

It's the same with ValueType being derived from Object. Just some pretty syntactic sugar the compiler ignores and does weird things behind your back :)

edit2: Here's the dissasembled code showing the boxing:

.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 1
    .locals init (
        [0] class [mscorlib]System.Type s)
    L_0000: nop
    L_0001: ldc.i4.s 12
    L_0003: box int32          // <---
    L_0008: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
    L_000d: stloc.0
    L_000e: ldloc.0
    L_000f: call void [mscorlib]System.Console::WriteLine(object)
    L_0014: nop
    L_0015: ret
}


问:
Reducing the time complexity of the program
I am doing this practice problem where given a string s of lowercase letters, and a position p, I have to print all the occurrences of the letter at position p which occur before the position p.

Eg: If the string is "abaac" and p=3(1 based index) then output is 1 because 'a' occurs one time before the position p.

 There are q queries each giving me a position p. Is there any way to make this code more efficient?
I'm using hashing which is pretty efficient I think? Is there any algorithm that I am not aware of?

```<code>#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    string s;
    cin>>s;
    int q;
    cin>>q;
    while(q--)
    {
        int p;
        cin>>p;
        int freq[26] = {0};
        for(int i = 0; i<(p-1); i++)
            freq[s[i]-'a']++;
        cout<<freq[s[p-1]-'a']<<"\n";
    }

}

</code>```

答:
You can compute solution once from the string before each query.
So each query in O(1).</p>

```<code>std::vector<std::size_t> build_res(const std::string& s)
{
    std::vector<std::size_t> res;
    int freq[26] = {0};

    for (auto c : s) {
        res.push_back(freq[c - 'a']++); // Assuming a-z contiguous (as in ASCII)
    }
    return res;
}

int main()
{
    int n;
    std::cin >> n;
    std::string s;
    std::cin >> s;
    const auto res = build_res(s);
    int q;
    std::cin >> q;
    while (q--)
    {
        int p;
        std::cin >> p;
        std::cout << res[p - 1] << '\n';
    }
}
</code>```

Body:
I am doing this practice problem where given a string s of lowercase letters, and a position p, I have to print all the occurrences of the letter at position p which occur before the position p.

Eg: If the string is "abaac" and p=3(1 based index) then output is 1 because 'a' occurs one time before the position p.

 There are q queries each giving me a position p. Is there any way to make this code more efficient?
I'm using hashing which is pretty efficient I think? Is there any algorithm that I am not aware of?

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    string s;
    cin>>s;
    int q;
    cin>>q;
    while(q--)
    {
        int p;
        cin>>p;
        int freq[26] = {0};
        for(int i = 0; i<(p-1); i++)
            freq[s[i]-'a']++;
        cout<<freq[s[p-1]-'a']<<"\n";
    }

}

Body:
You can compute solution once from the string before each query.
So each query in O(1).

std::vector<std::size_t> build_res(const std::string& s)
{
    std::vector<std::size_t> res;
    int freq[26] = {0};

    for (auto c : s) {
        res.push_back(freq[c - 'a']++); // Assuming a-z contiguous (as in ASCII)
    }
    return res;
}

int main()
{
    int n;
    std::cin >> n;
    std::string s;
    std::cin >> s;
    const auto res = build_res(s);
    int q;
    std::cin >> q;
    while (q--)
    {
        int p;
        std::cin >> p;
        std::cout << res[p - 1] << '\n';
    }
}


问:
Adding first occurence column to groupy dataframe
I have a data frame like this-

```<code>df=pd.DataFrame({'DT':[1,1,1,2,2,2,1,1],'city':['A','A','A','A','A','A','B','B'],'O':[22,33,44,55,66,77,88,99]})
</code>```

Now for each unique city, I want to add up all the values in the O column first occurring in the Dt column.
Output-

```<code>   city  O
0   A   77
1   B   88
</code>```

Explanation-
For the city 'A' the first unique occurring DT is 1 so we add the corresponding O column value that is 22. Next for the same city 'A' the first occurring 2 in the DT column is the 4th row so we add its corresponding O column== 22+55=77. Similarly for city B since only 1 is there in DT column the O will be 88.

答:
You can also extract the first lines and sum with level:

```<code>df.groupby(['DT','city'])['O'].first().sum(level=1)
</code>```

Output:

```<code>city
A    77
B    88
Name: O, dtype: int64
</code>```

Body:
I have a data frame like this-

df=pd.DataFrame({'DT':[1,1,1,2,2,2,1,1],'city':['A','A','A','A','A','A','B','B'],'O':[22,33,44,55,66,77,88,99]})

Now for each unique city, I want to add up all the values in the O column first occurring in the Dt column.
Output-

   city  O
0   A   77
1   B   88

Explanation-
For the city 'A' the first unique occurring DT is 1 so we add the corresponding O column value that is 22. Next for the same city 'A' the first occurring 2 in the DT column is the 4th row so we add its corresponding O column== 22+55=77. Similarly for city B since only 1 is there in DT column the O will be 88.

Body:
You can also extract the first lines and sum with level:

df.groupby(['DT','city'])['O'].first().sum(level=1)

Output:

city
A    77
B    88
Name: O, dtype: int64


问:
Is it a good practice to add names to __all__ using a decorator?
Is this a good practice in Python (from Active State Recipes -- Public Decorator)?

```<code>import sys

def public(f):
  """Use a decorator to avoid retyping function/class names.

  * Based on an idea by Duncan Booth:
  http://groups.google.com/group/comp.lang.python/msg/11cbb03e09611b8a
  * Improved via a suggestion by Dave Angel:
  http://groups.google.com/group/comp.lang.python/msg/3d400fb22d8a42e1
  """
  all = sys.modules[f.__module__].__dict__.setdefault('__all__', [])
  if f.__name__ not in all:  # Prevent duplicates if run from an IDE.
      all.append(f.__name__)
  return f

public(public)  # Emulate decorating ourself
</code>```

The general idea would be to define a decorator that takes a function or class
and adds its name to the __all__ of the current module.

答:
The more idiomatic way to do this in Python is to mark the private functions as private by starting their name with an underscore:

```<code>def public(x):
      ...

def _private_helper(y):
    ...
</code>```

More people will be familiar with this style (which is also supported by the language: _private_helper will not be exported even if you do not use __all__) than with your public decorator.

Body:
Is this a good practice in Python (from Active State Recipes -- Public Decorator)?

import sys

def public(f):
  """Use a decorator to avoid retyping function/class names.

  * Based on an idea by Duncan Booth:
  http://groups.google.com/group/comp.lang.python/msg/11cbb03e09611b8a
  * Improved via a suggestion by Dave Angel:
  http://groups.google.com/group/comp.lang.python/msg/3d400fb22d8a42e1
  """
  all = sys.modules[f.__module__].__dict__.setdefault('__all__', [])
  if f.__name__ not in all:  # Prevent duplicates if run from an IDE.
      all.append(f.__name__)
  return f

public(public)  # Emulate decorating ourself

The general idea would be to define a decorator that takes a function or class
and adds its name to the __all__ of the current module.

Body:
The more idiomatic way to do this in Python is to mark the private functions as private by starting their name with an underscore:

def public(x):
      ...

def _private_helper(y):
    ...

More people will be familiar with this style (which is also supported by the language: _private_helper will not be exported even if you do not use __all__) than with your public decorator.


问:
Uncaught Error: [vue-router] "path" is required in a route configuration
I'm following the official example but I don't know why I get a blank page with this js error

vue-router.esm.js?fe87:10 Uncaught Error: [vue-router] "path" is required in a route configuration.

Here is my two pages:

```<code>/:language/bar                     /:language/foo
+------------------+                  +-----------------+
| +---------+      |                  | +---------+     |
| | header  |      |                  | | header  |     |
| +---------+      |                  | +---------+     |
| +--------------+ |                  | +-------------+ |
| | bar          | |  +------------>  | | foo         | |
| |              | |                  | |             | |
| +--------------+ |                  | +-------------+ |
+------------------+                  +-----------------+
</code>```

And this is how I'm trying to do it.

My entrypoint js file:

```<code>import Vue from 'vue';
import router from './router';

// import some components

let vm = new Vue({
    el: '#app',
    router,
    components: {/*imported components*/},
});

vm.$language.current = vm.$route.params.language;
</code>```

My entrypoint html

```<code><body>
   <div id="app">
       <!-- this is the header, the common part -->
       <navbar fullname=''></navbar>

       <router-view></router-view>
   </div>
</body>
</code>```

My router

```<code>import Vue from 'vue';
import Router from 'vue-router';

// import foo and bar components

Vue.use(Router);

let routes = [
    {
        path: '/:language',
        name: 'homepage',
        children: [
            {
                path: 'foo',
                component: Foo
            },
            {
                path: 'bar',
                component: Bar
            },
        ]
    }
];

export default new Router({routes,});
</code>```

My foo component

```<code><template>
    <div>
        <h1>FOO</h1>
    </div>
</template>

<script>export default {};</script>
</code>```

How do I fix this error?

答:
Note:
 1. try to use local registration for component
 2. For Nested Router :

```<code>const router = new VueRouter({
  routes: [
    { path: '/language/:id',
      component: language,
      children: [
        {
          // Bar will be rendered inside language's <router-view>
          // when /language/:id/bar is matched
          path: 'bar',
          component: Bar
        },
        {
          // Foo will be rendered inside language's <router-view>
          // when /language/:id/foo is matched
          path: 'foo',
          component: Foo
        }
      ]
    }
  ]
})
</code>```

To export component:

```<code>    export default {
      name: "Foo"
    };
</code>```

Body:
I'm following the official example but I don't know why I get a blank page with this js error

vue-router.esm.js?fe87:10 Uncaught Error: [vue-router] "path" is required in a route configuration.

Here is my two pages:

/:language/bar                     /:language/foo
+------------------+                  +-----------------+
| +---------+      |                  | +---------+     |
| | header  |      |                  | | header  |     |
| +---------+      |                  | +---------+     |
| +--------------+ |                  | +-------------+ |
| | bar          | |  +------------>  | | foo         | |
| |              | |                  | |             | |
| +--------------+ |                  | +-------------+ |
+------------------+                  +-----------------+

And this is how I'm trying to do it.

My entrypoint js file:

import Vue from 'vue';
import router from './router';

// import some components

let vm = new Vue({
    el: '#app',
    router,
    components: {/*imported components*/},
});

vm.$language.current = vm.$route.params.language;

My entrypoint html

       <navbar fullname=''></navbar>

       <router-view></router-view>

My router

import Vue from 'vue';
import Router from 'vue-router';

// import foo and bar components

Vue.use(Router);

let routes = [
    {
        path: '/:language',
        name: 'homepage',
        children: [
            {
                path: 'foo',
                component: Foo
            },
            {
                path: 'bar',
                component: Bar
            },
        ]
    }
];

export default new Router({routes,});

My foo component

<template>

FOO

</template>

How do I fix this error?

Body:
Note:
 1. try to use local registration for component
 2. For Nested Router :

const router = new VueRouter({
  routes: [
    { path: '/language/:id',
      component: language,
      children: [
        {
          // Bar will be rendered inside language's <router-view>
          // when /language/:id/bar is matched
          path: 'bar',
          component: Bar
        },
        {
          // Foo will be rendered inside language's <router-view>
          // when /language/:id/foo is matched
          path: 'foo',
          component: Foo
        }
      ]
    }
  ]
})

To export component:

    export default {
      name: "Foo"
    };


问:
UIView title causing constraints problem XIB Xcode
I have one UITabBarController that has 5x child UIViewControllers, each of which is a UINavigationViewController.

For a UIView in any of the UINavigationControllers, If I set the title in viewDidLoad via

```<code>self.title=@"TITLE";
</code>```

Then I get the following unsatisfied constraint error

```<code>2020-05-28 14:21:23.055778+0100 Datum Connect[6515:10336196] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
    (1) look at each constraint and try to figure out which you don't expect;
    (2) find the code that added the unwanted constraint or constraints and fix it.
</code>```

(
    "= UILayoutGuide:0x600001968540'TitleView(0x7fa0a710a390)'.top   (active)>",
    ""
)

There are no constraints set up in my XIB.
This is fairly old (~2013) code so there's probably a deprecation issue somewhere with the autogenerated layouts...?

But if I use

```<code>self.tabBarController.navigationItem.title = @"TITLE";
or
self.navigationController.navigationItem.title=@"TITLE";
or
self.navigationController.title=@"TITLE";
</code>```

There is no the constraints problem, but the TITLE text doesn't appear either, just the empty nav bar.

答:
Im not sure about your issue but if the view has no constraints then there will be no warnings.

Try to add this

```<code>translatesAutoresizingMaskIntoConstraints = NO;
</code>```

to your view.

Body:
I have one UITabBarController that has 5x child UIViewControllers, each of which is a UINavigationViewController.

For a UIView in any of the UINavigationControllers, If I set the title in viewDidLoad via

self.title=@"TITLE";

Then I get the following unsatisfied constraint error

2020-05-28 14:21:23.055778+0100 Datum Connect[6515:10336196] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
    (1) look at each constraint and try to figure out which you don't expect;
    (2) find the code that added the unwanted constraint or constraints and fix it.

(
    "= UILayoutGuide:0x600001968540'TitleView(0x7fa0a710a390)'.top   (active)>",
    ""
)

There are no constraints set up in my XIB.
This is fairly old (~2013) code so there's probably a deprecation issue somewhere with the autogenerated layouts...?

But if I use

self.tabBarController.navigationItem.title = @"TITLE";
or
self.navigationController.navigationItem.title=@"TITLE";
or
self.navigationController.title=@"TITLE";

There is no the constraints problem, but the TITLE text doesn't appear either, just the empty nav bar.

Body:
Im not sure about your issue but if the view has no constraints then there will be no warnings.

Try to add this

translatesAutoresizingMaskIntoConstraints = NO;

to your view.


问:
Trigger an API endpoint when ever a file stored in Azure Blob Storage
I need to trigger an API endpoint when a new file or existing file modified in the Azure Blob storage.

How can I achieve this

答: You could use a Azure Logic App to do this.  It can be triggered when a blob is added/changed and then use the HTTP action to call the api.</p>


问:
I can't switch between tabs on a Bottom Navigation Bar in my App
I am having quite a challenge, i was following some tutorial project but when we reached a point of adding a bottom navigation bar, I have been stuck here for weeks trying to figure out where the problem is.
The activity loads successfully but i can not switch between the different tabs on the bottom navigation bar namely, Home, Add and Logout.

Here is my Code for the activity.

```<code>public class SellerHomeActivity extends AppCompatActivity {

private TextView mTextMessage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_seller_home);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    navView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()) {

                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    return true;

                case R.id.navigation_add:
                    Intent intentCategory = new Intent(SellerHomeActivity.this, SellerProductCategoryActivity.class);
                    startActivity(intentCategory);
                    return true;

                case R.id.navigation_logout:
                    final FirebaseAuth mAuth;
                    mAuth = FirebaseAuth.getInstance();
                    mAuth.signOut();

                    Intent intentMain = new Intent(SellerHomeActivity.this, MainActivity.class);
                    intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intentMain);
                    finish();
                    return true;
            }

            return false;

        }
    });
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_add, R.id.navigation_logout)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
</code>```

//        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
    }

}

Any help rendered will be so helpful to me,
Thanks in advance

答:
First of all bottom navigation should work best with the fragments. try using fragments instead of activity and also I have made minor changes which don't really make a difference but I tried making the same pattern like how I have done it. so my code had fragments instead of activity and everything else is the same. I hope this should help you and it should work.</p>

```<code>    public class SellerHomeActivity extends AppCompatActivity {

    private TextView mTextMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_seller_home);

        BottomNavigationView navView = findViewById(R.id.nav_view);

        navView.setOnNavigationItemSelectedListener(navListner);

        BottomNavigationView.OnNavigationItemSelectedListener navListner = new BottomNavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId()) {

                    case R.id.navigation_home:
                        mTextMessage.setText(R.string.title_home);
                        break;

                    case R.id.navigation_add:
                        Intent intentCategory = new Intent(
                            SellerHomeActivity.this,
                            SellerProductCategoryActivity.class);
                        startActivity(intentCategory);
                        break;

                    case R.id.navigation_logout:
                        final FirebaseAuth mAuth;
                        mAuth = FirebaseAuth.getInstance();
                        mAuth.signOut();

                        Intent intentMain = new Intent(SellerHomeActivity.this, MainActivity.class);
                        intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intentMain);
                        finish();
                        break;
                }
                return true;
            }
        });

    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_add, R.id.navigation_logout
        )
        .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
}
</code>```

Body:
I am having quite a challenge, i was following some tutorial project but when we reached a point of adding a bottom navigation bar, I have been stuck here for weeks trying to figure out where the problem is.
The activity loads successfully but i can not switch between the different tabs on the bottom navigation bar namely, Home, Add and Logout.

Here is my Code for the activity.

public class SellerHomeActivity extends AppCompatActivity {

private TextView mTextMessage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_seller_home);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    navView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()) {

                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    return true;

                case R.id.navigation_add:
                    Intent intentCategory = new Intent(SellerHomeActivity.this, SellerProductCategoryActivity.class);
                    startActivity(intentCategory);
                    return true;

                case R.id.navigation_logout:
                    final FirebaseAuth mAuth;
                    mAuth = FirebaseAuth.getInstance();
                    mAuth.signOut();

                    Intent intentMain = new Intent(SellerHomeActivity.this, MainActivity.class);
                    intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intentMain);
                    finish();
                    return true;
            }

            return false;

        }
    });
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_add, R.id.navigation_logout)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);

//        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
    }

}

Any help rendered will be so helpful to me,
Thanks in advance

Body:
First of all bottom navigation should work best with the fragments. try using fragments instead of activity and also I have made minor changes which don't really make a difference but I tried making the same pattern like how I have done it. so my code had fragments instead of activity and everything else is the same. I hope this should help you and it should work.

    public class SellerHomeActivity extends AppCompatActivity {

    private TextView mTextMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_seller_home);

        BottomNavigationView navView = findViewById(R.id.nav_view);

        navView.setOnNavigationItemSelectedListener(navListner);

        BottomNavigationView.OnNavigationItemSelectedListener navListner = new BottomNavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId()) {

                    case R.id.navigation_home:
                        mTextMessage.setText(R.string.title_home);
                        break;

                    case R.id.navigation_add:
                        Intent intentCategory = new Intent(
                            SellerHomeActivity.this,
                            SellerProductCategoryActivity.class);
                        startActivity(intentCategory);
                        break;

                    case R.id.navigation_logout:
                        final FirebaseAuth mAuth;
                        mAuth = FirebaseAuth.getInstance();
                        mAuth.signOut();

                        Intent intentMain = new Intent(SellerHomeActivity.this, MainActivity.class);
                        intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intentMain);
                        finish();
                        break;
                }
                return true;
            }
        });

    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_add, R.id.navigation_logout
        )
        .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
}


问:
Pandas Multiindex selection criteria alongwith column selection criteria
I need to query a Pandas Dataframe based on multiple criteria on the Index and the Column. Please have a look at my data below. 'Country' and 'Surname' are two separate indices, while 'Name', 'Score', 'Type' are columns.

```<code>y = pd.DataFrame({'Name':['Nikhil', 'Ankit', 'Keval', 'Darpan', 'Rajesh', 'John', 'Lynda'],
                  'Score':[89,92,96,82,95,98,97],
                  'Type':['Fat','Slim','Fat','Slim','Fat','Slim','Slim'],
                  'Country':['India','USA','Denmark','Australia','Italy','China','Israel'],
                  'Surname':['Sharma','Sharma','Patel','Shah','Sharma','Sharma','Sharma']}
                ).set_index('Country').set_index('Surname', append=True)
</code>```

I want to select data which meets following criteria:

Country should neither be India nor be USA

Surname should be Sharma

Score should be equal to or above 90

Type should be Slim

答:
You can use this code:</p>

```<code>df.loc[(~df.index.isin(['India', 'USA'], level='Country'))& (df.index.get_level_values('Surname') == 'Sharma') & (df['Score'] >= 90) & (df['Type'] == 'Slim')]
</code>```

Body:
I need to query a Pandas Dataframe based on multiple criteria on the Index and the Column. Please have a look at my data below. 'Country' and 'Surname' are two separate indices, while 'Name', 'Score', 'Type' are columns.

y = pd.DataFrame({'Name':['Nikhil', 'Ankit', 'Keval', 'Darpan', 'Rajesh', 'John', 'Lynda'],
                  'Score':[89,92,96,82,95,98,97],
                  'Type':['Fat','Slim','Fat','Slim','Fat','Slim','Slim'],
                  'Country':['India','USA','Denmark','Australia','Italy','China','Israel'],
                  'Surname':['Sharma','Sharma','Patel','Shah','Sharma','Sharma','Sharma']}
                ).set_index('Country').set_index('Surname', append=True)

I want to select data which meets following criteria:

Country should neither be India nor be USA

Surname should be Sharma

Score should be equal to or above 90

Type should be Slim

Body:
You can use this code:

df.loc[(~df.index.isin(['India', 'USA'], level='Country'))& (df.index.get_level_values('Surname') == 'Sharma') & (df['Score'] >= 90) & (df['Type'] == 'Slim')]


问:
UserControl Storyboard objects moving out of UserControl
I have a UserControl that have a storyboard that moves a control (within my UserControl) out of the usercontrol (using a TranslateX RenderTransform).

When I move the object out of the control it shows on the parent Page (that hosts my UserControl).  Is there a way to just hide it when it reaches the boundaries of my UserControl?

答: At the end of your storyboard set the animated controls visibility to collapsed/opacity = 0. If that animation is too abrupt for you, animate the opacity to 0 as the storyboard progresses. To detect when the animation goes out of your control would be rather difficult. You're probably best off "guessing" by waiting a few tenths of a second.</p>


问:
Replace 'A' to 1, 'B' to 2, in R dataframe column
We have a column of a dataframe with letters A to Z

```<code>df$Col1 <- c("B", "C", "Q", ... , "A")
</code>```

I want to change those letters to numbers 1-26.

Naturally I could just do the following 26 times, but it isn't efficient nor pretty.

```<code>df$Col1  <- gsub("A","1",df$Col1)
</code>```

What would be the best way to approach this problem?

答:
You can use match and the built-in constant LETTERS:

```<code>Col1 <- c("B", "C", "Q", "A")

as.character(match(Col1, LETTERS))
#> [1] "2"  "3"  "17" "1"
</code>```

Body:
We have a column of a dataframe with letters A to Z

df$Col1 <- c("B", "C", "Q", ... , "A")

I want to change those letters to numbers 1-26.

Naturally I could just do the following 26 times, but it isn't efficient nor pretty.

df$Col1  <- gsub("A","1",df$Col1)

What would be the best way to approach this problem?

Body:
You can use match and the built-in constant LETTERS:

Col1 <- c("B", "C", "Q", "A")

as.character(match(Col1, LETTERS))
#> [1] "2"  "3"  "17" "1"


问:
How to print rupee symbol in Windows console using Python?
I want to add the Indian Rupee Symbol to a program. This is a non GUI program  targeted at Windows and will be run as exe from console. (I would convert it to exe by pyinstaller in the end). I tried using:

```<code>print unicode(u"\u20B9")+"12,500"
</code>```

(As taken from http://www.fileformat.info/info/unicode/char/20b9/index.htm)

It works well in IDLE Interpreter but when I tried running the same code from cmd (Windows 7), it gave error:

```<code>Traceback (most recent call last):
  File "D:\My Programs\Projects\StockExchangeSim.py", line 9, in <module>
    print unicode(u"\u20B9")+"12,500"
  File "C:\Python27\lib\encodings\cp850.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u20b9' in position
 0: character maps to <undefined>
</code>```

Is there a way to handle this? If there is, will it cause issues when used in other windows computers?

答:
Inorder to print 'rupay' using python, we can use its respective unicode representation which is '\u20B9' . In order to Print rupay, we just have to do the following:

```<code>print(u'\u20B9')
</code>```

And you will get 'rupay' symbol. It is irrespective of platform (as the question mentioned windows)

Body:
I want to add the Indian Rupee Symbol to a program. This is a non GUI program  targeted at Windows and will be run as exe from console. (I would convert it to exe by pyinstaller in the end). I tried using:

print unicode(u"\u20B9")+"12,500"

(As taken from http://www.fileformat.info/info/unicode/char/20b9/index.htm)

It works well in IDLE Interpreter but when I tried running the same code from cmd (Windows 7), it gave error:

Traceback (most recent call last):
  File "D:\My Programs\Projects\StockExchangeSim.py", line 9, in <module>
    print unicode(u"\u20B9")+"12,500"
  File "C:\Python27\lib\encodings\cp850.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u20b9' in position
 0: character maps to <undefined>

Is there a way to handle this? If there is, will it cause issues when used in other windows computers?

Body:
Inorder to print 'rupay' using python, we can use its respective unicode representation which is '\u20B9' . In order to Print rupay, we just have to do the following:

print(u'\u20B9')

And you will get 'rupay' symbol. It is irrespective of platform (as the question mentioned windows)


问:
Can't upload file to aws s3 asp.net
```<code> fileTransferUtility = new TransferUtility(s3Client);
        try
        {
            if (file.ContentLength > 0)
            {
                var filePath = Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(file.FileName));
                var fileTransferUtilityRequest = new TransferUtilityUploadRequest
                {
                    BucketName = bucketName,
                    FilePath = filePath,
                    StorageClass = S3StorageClass.StandardInfrequentAccess,
                    PartSize = 6291456, // 6 MB.
                    Key = keyName,
                    CannedACL = S3CannedACL.PublicRead
                };
                fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
                fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
                fileTransferUtility.Upload(fileTransferUtilityRequest);
                fileTransferUtility.Dispose();
            }
</code>```

Im getting this error
The file indicated by the FilePath property does not exist!

I tried changing the path to the actual path of the file to C:\Users\jojo\Downloads but im still getting the same error.

答:
(Based on a comment above indicating that file is an instance of HttpPostedFileBase in a web application...)

I don't know where you got Server.MapPath("~/Files") from, but if file is an HttpPostedFileBase that's been uploaded to this web application code then it's likely in-memory and not on your file system.  Or at best it's on the file system in a temp system folder somewhere.

Since your source (the file variable contents) is a stream, before you try to interact with the file system you should see if the AWS API you're using can accept a stream.  And it looks like it can.

```<code>if (file.ContentLength > 0)
{
    var transferUtility = new TransferUtility(/* constructor params here */);
    transferUtility.Upload(file.InputStream, bucketName, keyName);
}
</code>```

Note that this is entirely free-hand, I'm not really familiar with AWS interactions.  And you'll definitely want to take a look at the constructors on TransferUtility to see which one meets your design.  But the point is that you're currently looking to upload a stream from the file you've already uploaded to your web application, not looking to upload an actual file from the file system.

As a fallback, if you can't get the stream upload to work (and you really should, that's the ideal approach here), then your next option is likely to save the file first and then upload it using the method you have now.  So if you're expecting it to be in Server.MapPath("~/Files") then you'd need to save it to that folder first, for example:

```<code>file.SaveAs(Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(file.FileName)));
</code>```

Of course, over time this folder can become quite full and you'd likely want to clean it out.

Title: Can't upload file to aws s3 asp.net

Body:
 fileTransferUtility = new TransferUtility(s3Client);
        try
        {
            if (file.ContentLength > 0)
            {
                var filePath = Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(file.FileName));
                var fileTransferUtilityRequest = new TransferUtilityUploadRequest
                {
                    BucketName = bucketName,
                    FilePath = filePath,
                    StorageClass = S3StorageClass.StandardInfrequentAccess,
                    PartSize = 6291456, // 6 MB.
                    Key = keyName,
                    CannedACL = S3CannedACL.PublicRead
                };
                fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
                fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
                fileTransferUtility.Upload(fileTransferUtilityRequest);
                fileTransferUtility.Dispose();
            }

Im getting this error
The file indicated by the FilePath property does not exist!

I tried changing the path to the actual path of the file to C:\Users\jojo\Downloads but im still getting the same error.

Body:
(Based on a comment above indicating that file is an instance of HttpPostedFileBase in a web application...)

I don't know where you got Server.MapPath("~/Files") from, but if file is an HttpPostedFileBase that's been uploaded to this web application code then it's likely in-memory and not on your file system.  Or at best it's on the file system in a temp system folder somewhere.

Since your source (the file variable contents) is a stream, before you try to interact with the file system you should see if the AWS API you're using can accept a stream.  And it looks like it can.

if (file.ContentLength > 0)
{
    var transferUtility = new TransferUtility(/* constructor params here */);
    transferUtility.Upload(file.InputStream, bucketName, keyName);
}

Note that this is entirely free-hand, I'm not really familiar with AWS interactions.  And you'll definitely want to take a look at the constructors on TransferUtility to see which one meets your design.  But the point is that you're currently looking to upload a stream from the file you've already uploaded to your web application, not looking to upload an actual file from the file system.

As a fallback, if you can't get the stream upload to work (and you really should, that's the ideal approach here), then your next option is likely to save the file first and then upload it using the method you have now.  So if you're expecting it to be in Server.MapPath("~/Files") then you'd need to save it to that folder first, for example:

file.SaveAs(Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(file.FileName)));

Of course, over time this folder can become quite full and you'd likely want to clean it out.


问:
PHP Header location in IF statement
Im trying to write this script to say if email is valied insert into DB and redirect, else redirect with error message only my redirect isn't working, im not terribly great with php and still reading up on the subject so id appreciate any advice, thanks in advance!

```<code><?php

$userid = $usersClass->userID();
$user_email=$_POST['email_upd'];

if(!filter_var($user_email, FILTER_VALIDATE_EMAIL))
{
header('Location: http://www.mysite.co.uk/mytwitter.php?msg=invalid');
}
else
{
mysql_query(" UPDATE produgg_users SET email='$user_email' where produgg_users.id = ".$usersClass->userID()) or die(mysql_error());
header('Location: http://www.mysite.co.uk/mytwitter.php?msg=success');
}

?>
</code>```

Sorry for not describing what goes wrong, what's happening is my page isnt redirecting back to the page in the header(location)

I've now enabled Error reporting and im still only seeing a white page, heres my entire page code.

```<code><?php

error_reporting(E_ALL);
require 'config.inc.php';

?>

<?php

$userid = $usersClass->userID();
$user_email=$_POST['email_upd'];

if(!filter_var($user_email, FILTER_VALIDATE_EMAIL))
    {
    header('Location: http://www..co.uk/mytwitter.php?msg=invalid');
    }
else
    {
    mysql_query(" UPDATE produgg_users SET email='$user_email' where produgg_users.id = ".$usersClass->userID()) or die(mysql_error());
    header('Location: http://www..co.uk/mytwitter.php?msg=success');
    }

?>
</code>```

答:
Can you please post your complete script? What Senad said is true: if your script writes anything to the output buffer, any header(); won't work anymore. Based on the code you have given, nothing is written to the output buffer (unless you are getting a mysql error, which you are not telling us about, which I assume is not the case).

Also, there is no need to use  and then reopen it with . Just FYI.

Title: PHP Header location in IF statement

Body:
Im trying to write this script to say if email is valied insert into DB and redirect, else redirect with error message only my redirect isn't working, im not terribly great with php and still reading up on the subject so id appreciate any advice, thanks in advance!

<?php

$userid = $usersClass->userID();
$user_email=$_POST['email_upd'];

if(!filter_var($user_email, FILTER_VALIDATE_EMAIL))
{
header('Location: http://www.mysite.co.uk/mytwitter.php?msg=invalid');
}
else
{
mysql_query(" UPDATE produgg_users SET email='$user_email' where produgg_users.id = ".$usersClass->userID()) or die(mysql_error());
header('Location: http://www.mysite.co.uk/mytwitter.php?msg=success');
}

?>

Sorry for not describing what goes wrong, what's happening is my page isnt redirecting back to the page in the header(location)

I've now enabled Error reporting and im still only seeing a white page, heres my entire page code.

<?php

error_reporting(E_ALL);
require 'config.inc.php';

?>

<?php

$userid = $usersClass->userID();
$user_email=$_POST['email_upd'];

if(!filter_var($user_email, FILTER_VALIDATE_EMAIL))
    {
    header('Location: http://www..co.uk/mytwitter.php?msg=invalid');
    }
else
    {
    mysql_query(" UPDATE produgg_users SET email='$user_email' where produgg_users.id = ".$usersClass->userID()) or die(mysql_error());
    header('Location: http://www..co.uk/mytwitter.php?msg=success');
    }

?>


问:
Meaning of "shallowly immutable" in the documentation of Record in Java 14
I am reading the documentation of Records
and don't understand the term "shallowly immutable". What do we mean by shallowly immutable?
And if it's immutable why we need a copy constructor? Why two "Hello Worlds!"?

For all record classes, the following invariant must hold: if a record R's components are c1, c2, ... cn, then if a record instance is copied as follows:

```<code> R copy = new R(r.c1(), r.c2(), ..., r.cn());  // copy constructor ?
</code>```

then it must be the case that r.equals(copy).

答:
If you consider a class as a composite or hierarchy of other classes and primitives (ints, arrays, etc.), shallow immutability refers to the immutability (constant-ness) of just the first level.

It is in contrast to the term 'deep immutability', which refers to the immutability of the whole hierarchy. Most of the tangible benefits that you hear about immutability, such as implicit thread-safety, apply only to something which is deeply immutable.

Consider this class

```<code>class Foo {
    private final MutableBar bar;

    //ctor, getter
}
</code>```

This class is shallowly immutable. It cannot be changed directly, but can be changed indirectly, for example

```<code>foo.getBar().setSomeProperty(5);
</code>```

so it is not deeply immutable.

Another example of shallow immutability, using only primitives

```<code>class Foo {
    private final int[] ints;

    Foo(int[] ints) {
        this.ints = ints;
    }
}
</code>```

This can be mutated like so

```<code>int[] ints = {1};
Foo foo = new Foo(ints);
ints[0] = 2;
</code>```

For a small hierarchy, it is sometimes simple to make a shallowly immutable class deeply immutable. It usually involves defensive copies, or switching mutable classes to immutable variations.

```<code>class Foo {
    private final int[] ints;

    Foo(int[] ints) {
        // copy to protect against the kind of mutation shown above
        this.ints = Arrays.copyOf(ints, ints.length);
    }

    // if you must have a getter for an array, make sure not to return the array itself,
    // otherwise the caller can change it.
    // for performance reasons, consider an immutable List instead - no copy required
    int[] getInts() {
        return Arrays.copyOf(ints, ints.length);
    }
}
</code>```

Body:
I am reading the documentation of Records
and don't understand the term "shallowly immutable". What do we mean by shallowly immutable?
And if it's immutable why we need a copy constructor? Why two "Hello Worlds!"?

For all record classes, the following invariant must hold: if a record R's components are c1, c2, ... cn, then if a record instance is copied as follows:

 R copy = new R(r.c1(), r.c2(), ..., r.cn());  // copy constructor ?

then it must be the case that r.equals(copy).

Body:
If you consider a class as a composite or hierarchy of other classes and primitives (ints, arrays, etc.), shallow immutability refers to the immutability (constant-ness) of just the first level.

It is in contrast to the term 'deep immutability', which refers to the immutability of the whole hierarchy. Most of the tangible benefits that you hear about immutability, such as implicit thread-safety, apply only to something which is deeply immutable.

Consider this class

class Foo {
    private final MutableBar bar;

    //ctor, getter
}

This class is shallowly immutable. It cannot be changed directly, but can be changed indirectly, for example

foo.getBar().setSomeProperty(5);

so it is not deeply immutable.

Another example of shallow immutability, using only primitives

class Foo {
    private final int[] ints;

    Foo(int[] ints) {
        this.ints = ints;
    }
}

This can be mutated like so

int[] ints = {1};
Foo foo = new Foo(ints);
ints[0] = 2;

For a small hierarchy, it is sometimes simple to make a shallowly immutable class deeply immutable. It usually involves defensive copies, or switching mutable classes to immutable variations.

class Foo {
    private final int[] ints;

    Foo(int[] ints) {
        // copy to protect against the kind of mutation shown above
        this.ints = Arrays.copyOf(ints, ints.length);
    }

    // if you must have a getter for an array, make sure not to return the array itself,
    // otherwise the caller can change it.
    // for performance reasons, consider an immutable List instead - no copy required
    int[] getInts() {
        return Arrays.copyOf(ints, ints.length);
    }
}


问:
Eslint Vue Plugin
My project is also using the eslint vue plugin. My rules are as follows.

```<code>"rules": {
        "vue/html-closing-bracket-newline": ["error", {
            "singleline": "never",
            "multiline": "always"
        }],
        "vue/html-closing-bracket-spacing": "error",
        "vue/max-attributes-per-line": ["error", {
            "singleline": 5,
            "multiline": {
                "max": 1,
                "allowFirstLine": false
            }
        }],
        "quotes": ["error", "single"],
        "eqeqeq": ["error", "always"],
        "no-else-return": ["error", { allowElseIf: false }],
        "no-eval": "error",
        "no-script-url": "error",
        "no-useless-return": "error",
        "no-multiple-empty-lines": ["error", { max: 1 }],
        "arrow-body-style": ["error", "as-needed"],
        "no-var": "error",
        "object-shorthand": "error",
        "prefer-arrow-callback": "error",
        "object-curly-spacing": ["error", "always"],
        "vue/no-use-v-if-with-v-for": "warn",
        "vue/padding-line-between-blocks": ["error", "always"],
        "vue/require-direct-export": "error",
        "vue/require-name-property": "warn",
        "vue/v-on-function-call": ["error", "never"],
    }
</code>```

When I run lint-fix according to these rules

this gives errors. But I have corrected both of these problems within my components. What is the reason it still gives these errors?

答:
Those are not eslint issues, those are "no rule found" issue, which is more likely something related to a package not being installed or used.

In your eslint config, you should have something on these lines:

```<code>module.exports = {
  extends: [
    'plugin:vue/recommended',
    '@vue/standard'
  ],
  rules: {
    // examples of vue rule
    'vue/keyword-spacing': 'warn',
  }
}
</code>```

Make sure you have

```<code>"@vue/eslint-config-standard": "^5.1.0",
"eslint-plugin-vue": "^6.2.2"
</code>```

Title: Eslint Vue Plugin

Body:
My project is also using the eslint vue plugin. My rules are as follows.

"rules": {
        "vue/html-closing-bracket-newline": ["error", {
            "singleline": "never",
            "multiline": "always"
        }],
        "vue/html-closing-bracket-spacing": "error",
        "vue/max-attributes-per-line": ["error", {
            "singleline": 5,
            "multiline": {
                "max": 1,
                "allowFirstLine": false
            }
        }],
        "quotes": ["error", "single"],
        "eqeqeq": ["error", "always"],
        "no-else-return": ["error", { allowElseIf: false }],
        "no-eval": "error",
        "no-script-url": "error",
        "no-useless-return": "error",
        "no-multiple-empty-lines": ["error", { max: 1 }],
        "arrow-body-style": ["error", "as-needed"],
        "no-var": "error",
        "object-shorthand": "error",
        "prefer-arrow-callback": "error",
        "object-curly-spacing": ["error", "always"],
        "vue/no-use-v-if-with-v-for": "warn",
        "vue/padding-line-between-blocks": ["error", "always"],
        "vue/require-direct-export": "error",
        "vue/require-name-property": "warn",
        "vue/v-on-function-call": ["error", "never"],
    }

When I run lint-fix according to these rules

this gives errors. But I have corrected both of these problems within my components. What is the reason it still gives these errors?

Body:
Those are not eslint issues, those are "no rule found" issue, which is more likely something related to a package not being installed or used.

In your eslint config, you should have something on these lines:

module.exports = {
  extends: [
    'plugin:vue/recommended',
    '@vue/standard'
  ],
  rules: {
    // examples of vue rule
    'vue/keyword-spacing': 'warn',
  }
}

Make sure you have

"@vue/eslint-config-standard": "^5.1.0",
"eslint-plugin-vue": "^6.2.2"


问:
array reduce accumulator as an empty array, push not working
Why is the accumulator.push  not valid? accumulator is an empty array!? If i use the predefined variable flarArray, things work just fine!! I know that if no initial value is included in the reduce callback, then it will use the first item in the array (which in my case will be an object) to be the accumulator, but if I tell it to start off as an array as the accumulator, what is the problem with that?

```<code>const profiles = [
  {
    id: 1,
    userID: '1',
    favoriteMovieID: '1',
  },
  {
    id: 2,
    userID: '2',
    favoriteMovieID: '1',
  }
];

const users = {
  1: {
    id: 1,
    name: 'Jane Cruz',
    userName: 'coder',
  },
  2: {
    id: 2,
    name: 'Matthew Johnson',
    userName: 'mpage',
  }
};

const movies = {
  1: {
    id: 1,
    name: 'Planet Earth 1',
  },
  2: {
    id: 2,
    name: 'Selma',
  }
};
let flatArray = [];
const flattenedProfiles = profiles.reduce(function(accumulator, currentProfile) {
  return accumulator.push({id: currentProfile.id, name: users[currentProfile.id].name, favoriteMovie: movies[currentProfile.favoriteMovieID].name})
},[]);
</code>```

答:
Array.push returns the new length of the array when inside the return of callback of reduce you are returning the new length on which you can't do next push operation. Use Array.concat instead or after Array.push also return the array.

```<code>const flattenedProfilesPush = profiles.reduce((acc, curr) => {
    acc.push({
        id: curr.id,
    })
    return acc
},[])

const flattenedProfilesConcat = profiles.reduce((acc, curr) =>
    acc.concat({
        id: curr.id,
    }),[]
)
</code>```

Body:
Why is the accumulator.push  not valid? accumulator is an empty array!? If i use the predefined variable flarArray, things work just fine!! I know that if no initial value is included in the reduce callback, then it will use the first item in the array (which in my case will be an object) to be the accumulator, but if I tell it to start off as an array as the accumulator, what is the problem with that?

const profiles = [
  {
    id: 1,
    userID: '1',
    favoriteMovieID: '1',
  },
  {
    id: 2,
    userID: '2',
    favoriteMovieID: '1',
  }
];

const users = {
  1: {
    id: 1,
    name: 'Jane Cruz',
    userName: 'coder',
  },
  2: {
    id: 2,
    name: 'Matthew Johnson',
    userName: 'mpage',
  }
};

const movies = {
  1: {
    id: 1,
    name: 'Planet Earth 1',
  },
  2: {
    id: 2,
    name: 'Selma',
  }
};
let flatArray = [];
const flattenedProfiles = profiles.reduce(function(accumulator, currentProfile) {
  return accumulator.push({id: currentProfile.id, name: users[currentProfile.id].name, favoriteMovie: movies[currentProfile.favoriteMovieID].name})
},[]);

Body:
Array.push returns the new length of the array when inside the return of callback of reduce you are returning the new length on which you can't do next push operation. Use Array.concat instead or after Array.push also return the array.

const flattenedProfilesPush = profiles.reduce((acc, curr) => {
    acc.push({
        id: curr.id,
    })
    return acc
},[])

const flattenedProfilesConcat = profiles.reduce((acc, curr) =>
    acc.concat({
        id: curr.id,
    }),[]
)