language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> //#include <conio.h> # define CHAR_UP 72 # define CHAR_DOWN 80 # define CHAR_LEFT 75 # define CHAR_RIGHT 77 //# define CHAR_DELETE 127 # define CHAR_ENTER 13 # define CHAR_ESC 27 # define MAIN_MENU "\nMENU \ \n------------------\ \n1- New Game\ \nESC | q - Quit\ \nOption: " # define HElPER "\nHELP \ \n---------------------------------------------------------------------------\ \n[ UP | w - Charge ] [ DOWN | s - Uncharge ] [ Left | a - Backward ] [ Right | d - Forward ]\ \nMove: " # define POSITIONS 10 # define MAX_FUEL 7 #define TRUE ~0 #define FALSE 0 typedef struct Truck { int position; int fuel; } Truck; void helper() { printf(HElPER); } void printStatus(Truck* truck, int* fuels) { if (truck == NULL) return; int i; printf("GAME\n["); for (i = 0; i < POSITIONS; i++) { if (truck->position == i) { printf(" [%d] ", fuels[i]); } else { printf(" %d ", fuels[i]); } } printf("]"); printf("\t[ Fuel: %d, Position: %d ]", truck->fuel, truck->position); } int gameOver(Truck* truck) { if ((truck->position == POSITIONS-1) || (truck->fuel <= 0)) { return TRUE; } else { return FALSE; } } void game() { char op;// = CHAR_UP; Truck* truck = (Truck*)malloc(sizeof(Truck)); truck->position = 0; truck->fuel = MAX_FUEL; int* fuels = (int*)malloc(POSITIONS * sizeof(int)); int i; for (i = 0; i < POSITIONS; i++) { fuels[i] = 0; } do { printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); printStatus(truck, fuels); //printf("\n\n%s", STATUS); helper(); fflush(stdin); scanf("%c", &op); switch (op) { case 'a': case CHAR_LEFT: if (truck->position > 0) { truck->position--; truck->fuel--; } break; case 'd': case CHAR_RIGHT: truck->position++; truck->fuel--; break; case 's': case CHAR_DOWN: if (truck->position > 0) { fuels[truck->position]++; truck->fuel--; } break; case 'w': case CHAR_UP: if (truck->fuel + fuels[truck->position] <= MAX_FUEL) { truck->fuel += fuels[truck->position]; fuels[truck->position] = 0; } else { fuels[truck->position] = truck->fuel+fuels[truck->position]-MAX_FUEL; truck->fuel = MAX_FUEL; } break; } if (truck->position == 0) truck->fuel = MAX_FUEL; } while(!gameOver(truck) && op != CHAR_ESC && op != 'q'); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); printStatus(truck, fuels); if (truck->position == POSITIONS-1) { printf("\n\nYOU WIN\n\n"); } else { printf("\n\nGAME OVER\n\n"); } free(truck); fflush(stdin); scanf("%c", &op); } char printMenu(char MsgMenu[]) { char op; printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n%s", MsgMenu); fflush(stdin); scanf("%c", &op); return op; } int main() { while (1) { switch (printMenu(MAIN_MENU)) { case 'q': case CHAR_ESC: exit(0); break; case '1' : game();break; } } return 0; }
C
// SMT-Timer.c // FOSC at 4 MHz, External Oscillator for accuracy // UART at 9600 bps // LED on RD2 // // SMT1 using FOSC/4, Prescaler = 1, period = 16,000,000 us = 16 seconds // WARNING! period must be bigger than expected signal time. // Timer Mode, Timing code execution & non-blocking delay // // Modes input pin // 0 Timer none // 1 Gated Timer SMT1SIG // 2 Period and Duty-Cycle Acquisition SMT1SIG // 3 High and low time measurement SMT1SIG // 6 Time of flight SMT1WIN & SMT1SIG // 7 Capture SMT1WIN // 8 Counter SMT1SIG #include "mcc_generated_files/mcc.h" #include "putty.h" #include <stdbool.h> #include <stdio.h> // has printf() #include <math.h> /* Main application */ void main(void) { // Initialize the device SYSTEM_Initialize(); uint32_t time_1 = 0ul, time_2 = 0ul; float time; unsigned char letter; IO_RD2_SetHigh(); // LED on show capture in progress clearPuTTY(); printf("SMT1 Timer\n\n\r"); printf("SMT Mode = %u (0 is timer)\n\r",SMT1CON1bits.MODE); printf("SMT enabled = %u (0 is no, 1 is yes)\n\r",SMT1CON0bits.EN); printf("SMT timer incrementing = %u (0 is no, 1 is yes)\n\r",SMT1_IsTimerIncrementing()); printf("SMT prescaler setting = %u , N = %u \n\r",SMT1CON0bits.PS,1 << SMT1CON0bits.PS); printf("SMT period %lu \n\n\r",SMT1_GetPeriod()); //codes to control operation. Not needed, set in MCC Easy Setup SMT1CON0bits.EN = 1; // enables SMT peripheral SMT1_DataAcquisitionEnable(); // start SMT peripheral SMT1_SetPeriod(16000000ul); // set period SMT1CON0bits.PS = 0; // set prescaler N = 2^0 = 1 SMT1_ManualTimerReset(); // zero SMT1 counter/timer time_1 = SMT1_GetTimerValue(); // just to check if zeroed DELAY_milliseconds(3100); time_2 = SMT1_GetTimerValue(); printf("SMT start = %lu musec (should be very small number)\n\r", time_1); printf("SMT end = %lu musec\n\r", time_2); time = (float)(time_2 - time_1) * (1 << SMT1CON0bits.PS) * 4.0/_XTAL_FREQ; printf("elapsed time = %f seconds\n\n\r", time); // 16 second non-blocking delay printf("16 s non-blocking delay - type letters please \n\r"); SMT1IF = 0; // clear SMT timer interrupt SMT1_ManualTimerReset(); // clear SMT timer while(!SMT1IF) { if(UART2_DataReady) { letter = UART2_Read(); // read a single character printf(" You have typed {%c}, ascii #%u \n\r",letter, letter); } } printf("\nNon-blocking delay finished\n\r"); IO_RD2_SetLow(); // LED off, timing finished while (1); } /** End of File */
C
#ifndef _LIST_OP_H #define _LIST_OP_H #ifdef __cplusplus extern "C" { #endif #define IN #define OUT typedef struct list_head { struct list_head *next, *prev; }COMMON_LIST_HEAD,*COMMON_P_LIST_HEAD; #define COMMON_LIST_HEAD_INIT(name) { &(name), &(name) } // 定义LIST并静态初始化一个空的通用双向链表 #define COMMON_LIST_HEAD(name) \ COMMON_LIST_HEAD name = COMMON_LIST_HEAD_INIT(name) // 动态初始化一个空的通用双向链表 #define COMMON_INIT_LIST_HEAD(ptr) do { \ (ptr)->next = (ptr); (ptr)->prev = (ptr); \ } while (0) // 动态分配一个包含通用双向链表的结构体 #define COMMON_NEW_LIST_NODE(type, node) \ {\ node = (type *)malloc(sizeof(type));\ } // 释放链表中的所有节点,使该链表成为空链表 #define COMMON_FREE_LIST(type, p, list_name)\ {\ type *posnode;\ while(!common_list_empty(&(p)->list_name)) {\ posnode = common_list_entry((&(p)->list_name)->next, type, list_name);\ common_list_del((&(p)->list_name)->next);\ free(posnode);\ }\ } // 获取链表中第一个节点地址(该地址指向其主结构) #define COMMON_GetFirstNode(type,p,list_name,pGetNode)\ {\ pGetNode = NULL;\ while(!common_list_empty(&(p)->list_name)){\ pGetNode = common_list_entry((&(p)->list_name)->next, type, list_name);\ break;\ }\ } // 从链中删除某节点,并释放该节点所在结构占用的内存 #define COMMON_DeleteNodeAndFree(pDelNode,list_name)\ {\ common_list_del(&(pDelNode->list_name));\ free(pDelNode);\ } // 仅从链中删除某节点 #define COMMON_DeleteNode(pDelNode,list_name)\ {\ common_list_del(&(pDelNode->list_name));\ } // 释放链表内存 #define COMMON_FreeNode(pDelNode)\ {\ free(pDelNode);\ } // 获取包含该通用链表节点的结构体的首址 #define common_list_entry(ptr, type, member) \ ((type *)((char *)(ptr)-(size_t)(&((type *)0)->member))) // 遍历链表 #define common_list_for_each(pos, head) \ for (pos = (head)->next; pos != (head); pos = pos->next) /*********************************************************** *************************variable define******************** ***********************************************************/ /*********************************************************** *************************function define******************** ***********************************************************/ int common_list_empty(IN const COMMON_P_LIST_HEAD pHead); void common_list_add(IN const COMMON_P_LIST_HEAD pNew, IN const COMMON_P_LIST_HEAD pHead); void common_list_add_tail(IN const COMMON_P_LIST_HEAD pNew, IN const COMMON_P_LIST_HEAD pHead); void common_list_splice(IN const COMMON_P_LIST_HEAD pList, IN const COMMON_P_LIST_HEAD pHead); void common_list_del(IN const COMMON_P_LIST_HEAD pEntry); void common_list_del_init(IN const COMMON_P_LIST_HEAD pEntry); #ifdef __cplusplus } #endif /* __cplusplus */ #endif
C
#include <assert.h> /* * Adapted from "Automated Error Diagnosis Using Abductive Inference" by Dillig et al. */ void main(int n, int flag) { assume(n>=0); int k = 1; int m; if(flag) { k = m; assume(k>=0); } int i = 0, j = 0; while(i <= n) { i++; j+=i; } int z = k + i + j; assert(z > 2*n); }
C
#include<stdio.h> int main() { int T,R,i; int arr[4][2]; scanf("%d",&T); while(T--) { scanf("%d",&R); for(i=0;i<3;i++) scanf("%d %d",&arr[i][0],&arr[i][1]); arr[3][0]=arr[0][0]; arr[3][1]=arr[3][1]; int d[3],flag=0; for(i=0;i<3;i++) { d[i]=(arr[i][0]-arr[i+1][0])*(arr[i][0]-arr[i+1][0])+(arr[i][1]-arr[i+1][1])*(arr[i][1]-arr[i+1][1]); if(d[i]<=R*R) flag++; } if(flag>=2) printf("yes\n"); else printf("no\n"); } return 0; }
C
#include "userprog/syscall.h" #include <stdio.h> #include <syscall-nr.h> #include "threads/interrupt.h" #include "threads/thread.h" #include "threads/vaddr.h" #include "userprog/pagedir.h" #include <user/syscall.h> static void syscall_handler (struct intr_frame *); void exit (int status); pid_t exec (const char *cmd_line); int wait (pid_t pid); void syscall_init (void) { intr_register_int (0x30, 3, INTR_ON, syscall_handler, "syscall"); } static void syscall_handler (struct intr_frame *f UNUSED) { int sysnumber = * (int *) f->esp; int * esp = f->esp; // printf("%d\n", sysnumber); switch(sysnumber){ case SYS_WRITE: // second to do { // printf("fd : %d buff: %s size: %d\n", *(esp+1), *(esp+2), * (char*) (esp+3)); if (*(esp+1) == 1) { // printf("\nprintf: %s\nputbuf: ", *(esp+2)); putbuf(*(esp+2), *(esp+3)); } break; } case SYS_EXIT: //first to do { // printf("status: %d %d\n", * (int *) esp, * (int *)(esp + 1)); // bad_ptr((const void *)(esp + 1)); exit(* (int *)(esp + 1)); break; } case SYS_WAIT: { // call wait() here // bad_ptr((int *)(esp + 1)); f->eax = wait(* (int *)(esp + 1)); break; } case SYS_EXEC: { if (is_user_vaddr(*(esp+1)) && pagedir_get_page(thread_current()->pagedir, *(esp+1))){ f->eax = exec((char*) *(esp+1)); } else{ exit(-1); } break; } default: break; } } // void bad_ptr (const void *ptr) // { // if (is_user_vaddr(ptr) && pagedir_get_page(thread_current()->pagedir, ptr)) // { // exit(-1); // } // } void exit (int status) { struct thread *cur = thread_current(); printf ("%s: exit(%d)\n", strtok_r(cur->name, " "), status); cur->exitstatus = status; cur->terminated = true; // struct thread * parent = thread_get_by_tid(cur->parentId); // if(parent != NULL || parent != 0){ // sema_up(&parent->exec_sema); // } thread_exit(); } pid_t exec (const char *cmd_line) { // check validity of pointer before delivering it to critical code, maybe? pid_t pid = process_execute(cmd_line); //TODO // Check if creation was successful otherwise return -1 return pid; } int wait (pid_t pid){ return process_wait(pid); }
C
#include<stdio.h> #include<stdlib.h> void accept(int *); void bubble(int *); void selection(int *); void insertion(int *); void display(int *); int main() { int arr[4]; char ch; insertion(arr); while(1) { printf("Enter accept = a, display=d, selection = s, bubble=b, insertion=i, exit=e \n"); scanf(" %c",&ch); switch(ch) { case'a': accept(arr); break; case'd': display(arr); break; case's': selection(arr); break; case'b': bubble(arr); break; case'i': insertion(arr); break; case'e': exit(0); } } return 0; } void selection(int s[4]) { int iter,ele,temp; for(iter=0;iter<4;iter++) for(ele=iter;ele<=4-iter;ele++) { if(s[iter]>s[ele+1]) { temp = s[ele+1]; s[ele+1]=s[iter]; s[iter]=temp; } } printf("Sort completed \n \n"); } void bubble(int b[4]) { int iter,ele,temp; for(iter=0;iter<4;iter++) for(ele=0;ele<4-iter;ele++) { if(b[ele]>b[ele+1]) { temp = b[ele+1]; b[ele+1]=b[ele]; b[ele]=temp; } } printf("Sort completed \n"); } void insertion(int y[4]) { accept(y); int iter,temp,check; /*for( int i = 0 ;i < n ; i++ ) { int temp = A[ i ]; int j = i; while( j > 0 && temp < A[ j -1]) { // moving the left side element to one position forward. A[ j ] = A[ j-1]; j= j - 1; } // moving current element to its correct position. A[ j ] = temp; }*/ for(iter=1;iter<4;iter++) { for(check=0;check<iter;check++) { if(y[iter]<y[check]) { temp = y[iter]; for(int i=iter;i>check;i--) { y[i]=y[i-1]; } y[check]=temp ; } } } printf("Sort completed \n \n"); display(y); } void accept(int a[4]) { int i; printf("Enter 4 elements \n"); for(i=0;i<4;i++) { scanf("%d",&a[i]); } } void display(int a[4]) { int i; printf("The elements are: \n"); for(i=0;i<4;i++) { printf("\t %d",a[i]); } }
C
#define F_CPU 8000000 #include <math.h> #include "AD.h" #include "ntc_10k.h" long int get_resistence_ntc(double vin) { //Res of NTC (Ohm) = ((VCC + R1)/Vin) - R1 return ((VCC * R1) / vin) - 10000; } double steinhart_hart(unsigned int resistence) { double temperature; /* Temperature (K) = 1 / (a + (b*ln(Rntc) + c.ln(Rntc)*ln(Rntc)*ln(Rntc))) a = 0.0011303 b = 0.0002339 c = 0.00000008863 */ temperature = log(resistence); temperature = 1 / (0.0011303 + (0.0002339 * temperature) + (0.00000008863 * temperature * temperature * temperature)); //Convert in Celsius temperature = temperature - 273.15; return temperature; } double get_temperature(void) { double vin = voltage(CHANNEL); long res_ntc; res_ntc = get_resistence_ntc(vin); return steinhart_hart(res_ntc); }
C
/* ID:lxlenovos1 LANG:C TASK:palsquare */ #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> char palindromes[50]; char result[50]; char map[256]; int get_palindromes(int base, int seq) { int i, num, remainder; if (base < 2 || base > 20) return -1; for (i = 0; ; ++i){ num = seq / base; remainder = seq % base; if (remainder >= 10) palindromes[i] = map[remainder - 10 + '0']; else palindromes[i] = remainder + '0'; seq = num; if (seq == 0) break; } return (i + 1); } void get_result(int base, int seq) { int i, j, num, remainder; char tmp[50]; int length = 0; for (i = 0; ; ++i){ num = seq / base; remainder = seq % base; if (remainder >= 10) tmp[i] = map[remainder - 10 + '0']; else tmp[i] = remainder + '0'; seq = num; if (seq == 0) break; } length = i; for (j = 0; j < length + 1; ++j, --i) result[j] = tmp[i]; } int check_palindromes(int number) { int i; for (i = 0; i < number / 2; ++i) { if (palindromes[i] == palindromes[number - i - 1]){ continue; } else{ return -1; } } return 0; } int main(){ FILE *fin, *fout; int base, i, square, num; map['0'] = 'A'; map['1'] = 'B'; map['2'] = 'C'; map['3'] = 'D'; map['4'] = 'E'; map['5'] = 'F'; map['6'] = 'G'; map['7'] = 'H'; map['8'] = 'I'; map['9'] = 'J'; fin = fopen("palsquare.in", "r"); fout = fopen("palsquare.out", "w"); fscanf(fin, "%d", &base); for (i = 1; i <= 300; ++i){ square = i * i; num = get_palindromes(base, square); if (num > 0){ if (check_palindromes(num) == 0){ get_result(base, i); fprintf(fout, "%s %s\n", result, palindromes); } } } fclose(fin); fclose(fout); exit(0); }
C
#include <stdio.h> int main(void) { int Y[5]; /* Array declaration of 5 elements */ Y[0] = 1; /* Assign 1 to Y[0] */ Y[1] = Y[0] * 2; /* Assign Y[0] * 2 expression to Y[1] */ Y[2] = Y[1] * 3; /* Assign Y[1] * 3 expression to Y[2] */ Y[3] = Y[2] * 4; /* Assign Y[2] * 4 expression to Y[3] */ Y[4] = Y[3] * 5; /* Assign Y[3] * 5 expression to Y[4] */ int i; for (i = 0; i < 5; i++) printf("index [%d] = digit %d\n", i, Y[i]); }
C
/* ** EPITECH PROJECT, 2019 ** cpp_d03_2019 ** File description: ** Created by thomas1.bastien@epitech.eu */ #include <criterion/criterion.h> #include "../string.h" Test(str, copy) { string_t s; char *buff = malloc(sizeof(char) * 7); string_t s2; string_init(&s, "Hello World salut les amis"); string_init(&s2, "Bonsoir les copains"); cr_assert_eq(copy(&s, buff, 7, 20), 7); string_destroy(&s); string_destroy(&s2); } Test(str, copy_buff_null) { string_t s; string_t s2; string_init(&s, "Hello World salut les amis"); string_init(&s2, "Bonsoir les copains"); cr_assert_eq(copy(&s, NULL, 7, 10), 0); string_destroy(&s); string_destroy(&s2); }
C
#include <Arduino.h> #include <Wire.h> #include <LiquidCrystal_I2C.h> #define Volataje_VF1 2 #define Volataje_VF2 3 #define Volataje_VF3 4 LiquidCrystal_I2C lcd(0x27, 16, 2); //config LCD int Valor; const int sensorPin1 = A0; // seleccionar la entrada para el sensor int sensorValue; // variable que almacena el valor raw (0 a 1023) int Valor_Voltaje_VF1; // Variable para testear el voltaje VF1 int Valor_Voltaje_VF2; // Variable para testear el voltaje VF2 int Valor_Voltaje_VF3; // Variable para testear el voltaje VF3 int ValorMaximo = 510; int ValorMinimo = 486; int EstadoCorriente; void setup() { lcd.init(); lcd.backlight(); lcd.clear(); lcd.setCursor(0,0); lcd.print("bienvenidos"); delay(200); pinMode(Volataje_VF1,INPUT_PULLUP); pinMode(Volataje_VF2,INPUT_PULLUP); pinMode(Volataje_VF3,INPUT_PULLUP); Serial.begin(9600); } void loop() { Valor_Voltaje_VF1 = digitalRead(Volataje_VF1); // realizar lectura Valor_Voltaje_VF2 = digitalRead(Volataje_VF2); // realizar lectura Valor_Voltaje_VF3 = digitalRead(Volataje_VF3); // realizar lectura if ((Valor_Voltaje_VF1)&&(Valor_Voltaje_VF2)&&(Valor_Voltaje_VF3)) { lcd.clear(); lcd.setCursor(0,0); lcd.print("Conflicto fase"); lcd.setCursor(0,1); lcd.print("verde"); delay(200); }else { lcd.clear(); lcd.setCursor(0,0); lcd.print("Status Okay"); delay(200); } }
C
// Generates the ASCII table of printable characters. #include <stdio.h> int main(){ const char A[]="* THE ASCII TABLE BY JOSEF ZIEGLER *"; int i = -1, j = 0; while(j < 3) { while(++i < sizeof(A)-1) { // because of the '\0' if(j%2 == 0) putc('*', stdout); else putc(*(A+i), stdout);} putc('\n', stdout); j++; i = -1; } for(i = 33; i < 127; i++){ printf("%.3d ", i); putc(i, stdout); printf(" "); if (i % 8==0) putc(10, stdout); } }
C
#include <wos/gdt.h> #include <wos/asm.h> #include <wos/vga.h> void __put_c(char c, int x) { asm("movw $0x18, %%ax\n\t" "movw %%ax, %%gs\n\t" "movb $0x07, %%ah\n\t" "movb %0, %%al\n\t" "movl %1, %%edi\n\t" "movw %%ax, %%gs:(%%edi)\n\t" ::"m"(c),"m"(x)); } void put_c(char c) { int scr_pos; switch (c) { case '\n': v_scr_x++; if (v_scr_x == 24) { v_scr_x = 23; //screen_clear(); screen_roll(); } v_scr_y = 0; set_cursor(v_scr_x, v_scr_y); break; case '\r': v_scr_y = 0; set_cursor(v_scr_x, v_scr_y); break; case '\t': if (v_scr_y + 8 <= 80) { v_scr_y += 8; } else { v_scr_x++; if (v_scr_x == 24) { v_scr_x = 23; //screen_clear(); screen_roll(); } v_scr_y -= 80; } set_cursor(v_scr_x, v_scr_y); break; default: scr_pos = (v_scr_x * 80 + v_scr_y) * 2; __put_c(c, scr_pos); if (v_scr_y > 80) { v_scr_x++; v_scr_y = 0; if (v_scr_x == 24) { v_scr_x = 23; //screen_clear(); screen_roll(); } } else { v_scr_y++; } set_cursor(v_scr_x, v_scr_y); break; } } void put_s(char *string) { char *s = string; if (!string) return ; while (*s) { put_c(*s); s++; } } void set_cursor(int x, int y) { /* cli(); */ outb(0x0e, 0x3d4); outb(((x * 80 + y) >> 8) & 0xff, 0x3d5); outb(0x0f, 0x3d4); outb((x * 80 + y) & 0xff, 0x3d5); /* sti(); */ } void __screen_roll(int src, int dst) { asm("movl $0x18, %%eax\n\t" "movw %%ax, %%gs\n\t" "movl %0, %%esi\n\t" "movl %1, %%edi\n\t" "movl $80, %%ecx\n\t" "1:\n\t" "movw %%gs:(%%esi), %%ax\n\t" "movw %%ax, %%gs:(%%edi)\n\t" "addl $2, %%esi\n\t" "addl $2, %%edi\n\t" "decl %%ecx\n\t" "test %%ecx, %%ecx\n\t" "jne 1b\n" ::"m"(src), "m"(dst)); } void screen_roll(void) { int src, dst; int i; for (i = 1; i <= 24; i++) { src = i * 80 * 2; dst = (i - 1) * 80 * 2; __screen_roll(src, dst); } /* for (i = 0; i + 2 < 80; i += 2) __put_c(0x0, 23 * 80 * 2 + i); */ set_cursor(24, 0); } void screen_clear(void) { asm("movw $0x18, %%ax\n\t" "movw %%ax, %%gs\n\t" "movw $0x0, %%ax\n\t" "xorl %%ebx, %%ebx\n\t" "1:\n\t" "movw %%ax, %%gs:(%%bx)\n\t" "addl $2, %%ebx\n\t" "cmpl $4000, %%ebx\n\t" "jb 1b\n"::); set_cursor(0, 0); } void init_vga(void) { v_scr_x = v_scr_y = 0; }
C
#include<stdio.h> #include<stdlib.h> #include<conio.h> #include<malloc.h> #include<windows.h> #include<string.h> void close(void) { system("cls"); printf("\n\n\n\t\t THIS WAS C-DATA STRUCTURES MINI PROJECT \n\n\t\t DEVELOPED BY TSEC STUDENTS : - ASHISH GANGWANI \n\t\t - PARTH JANGID\n\n\n"); } struct node { char name[50]; char address[100]; char acc_type[20]; double balance; int acc_no; long long int phone; int age,day,month,year; struct node *next; }; struct node *start=NULL; void fordelay(int j) { int i,k; for(i=0;i<j;i++) k=i; } void new_acc() { system("cls"); int just,i; char nam[50],addr[100],temp,tempo; struct node *ptr,*newacc,*preptr; newacc = (struct node *)malloc(sizeof(struct node)); if(start==NULL) { start = newacc; printf("\n\t\t ENTER NAME : "); gets(nam); strcpy(newacc->name,nam); printf("\n\t\t ENTER ADDRESS : "); scanf("%s",newacc->address); gets(addr); strcpy(newacc->address,addr); printf("\n\t\t ENTER ACCOUNT TYPE :\n\t\t\t\t #--SAVINGS \n\t\t\t\t #--CURRENT\n\t\t ENTER CHOICE : "); scanf("%s",&newacc->acc_type); age : printf("\n\t\t ENTER AGE : "); scanf("%d",&newacc->age); if(newacc->age<18) { printf("\t\t\t ----INVALID AGE----\n"); goto age ; } printf("\n\t\t ENTER PHONE N0. : "); scanf("%lli",&newacc->phone); printf("\n\t\t ENTER BALANCE : "); scanf("%lf",&newacc->balance); date : printf("\n\t\t ENTER TODAY'S DATE(DD/MM/YYYY) : "); scanf("%d/%d/%d",&newacc->day,&newacc->month,&newacc->year); if(newacc->day>31||newacc->day<1 || newacc->month>12 || newacc->month<1 || newacc->year > 2019 || (newacc->day>28&&newacc->month==2) || newacc->year!=2019) { printf("DATE NOT ACCEPTED.......PLEASE RE-ENTER"); goto date ; } printf("\n\t\t ENTER ACCOUNT_NUMBER : "); scanf("%d",&newacc->acc_no); newacc->next=NULL; start =newacc; system("cls"); printf("\n\t\tSUCCESSFULLY RECORDED\n"); } else { system("cls"); re_enter : printf("\n\t\t ENTER NAME : "); gets(nam); strcpy(newacc->name,nam); printf("\n\t\t ENTER ADDRESS : "); //scanf("%s",newacc->address); gets(addr); strcpy(newacc->address,addr); printf("\n\t\t ENTER ACCOUNT TYPE :\n\t\t\t\t #--SAVINGS \n\t\t\t\t #--CURRENT\n\t\t ENTER CHOICE : "); scanf("%s",&newacc->acc_type); age1 : printf("\n\t\t ENTER AGE : "); scanf("%d",&newacc->age); if(newacc->age<18) { printf("\n\t\t\t -----INVALID AGE-----\n"); goto age1 ; } printf("\n\t\t ENTER PHONE N0. : "); scanf("%lli",&newacc->phone); printf("\n\t\t ENTER BALANCE : "); scanf("%lf",&newacc->balance); date1 : printf("\n\t\t ENTER TODAY'S DATE(DD/MM/YYYY) : "); scanf("%d/%d/%d",&newacc->day,&newacc->month,&newacc->year); if(newacc->day>31||newacc->day<1 || newacc->month>12 || newacc->month<1 || newacc->year > 2019 || (newacc->day>28&&newacc->month==2)) { printf("\n\t\t DATE NOT ACCEPTED.......PLEASE RE-ENTER"); goto date1 ; } printf("\n\t\t ENTER ACCOUNT_NO. : "); scanf("%d",&newacc->acc_no); ptr = start; preptr = ptr; while(ptr!=NULL) { if(newacc->acc_no==preptr->acc_no) { printf("\n\t\t ACC_NO. ALREADY TAKEN\n\t\t PLEASE WAIT FORWARDING TO MENU "); for(i=0;i<=6;i++) { fordelay(100000000); printf("."); } menu(); } preptr = ptr ; ptr=ptr->next; } if(preptr->acc_no==newacc->acc_no) { printf("\n\t\t ACC_NO. ALREADY TAKEN\n\t\t PLEASE WAIT FORWARDING TO MENU "); for(i=0;i<=6;i++) { fordelay(100000000); printf("."); } menu(); } else { preptr->next=newacc; newacc->next=NULL; } } system("cls"); printf("\n\n\t\tSUCCESSFULLY RECORDED\n"); printf("\n\n\t\tENTER 1 FOR MAIN MENU || 0 TO EXIT : \n\t\tENTER YOUR CHOICE : "); scanf("%d",&just); if(just==1) { menu(); } if(just==0) { close(); } } void see() { again : system("cls"); struct node *ptr; ptr = start; int noacc,flag=0,todo; printf("\n\t\t Enter ACCOUNT_NUMBER : "); scanf("%d",&noacc); if(start==NULL) { printf("\n\t\t NOTHING TO DISPLAY\n"); } else if(start->next==NULL) { if(noacc==start->acc_no) { printf("\n\t\t ACC DETAILS ARE : \n"); flag=1; printf("NAME\t\tACC_NO\tPHONE N0.\t\tBALANCE\n"); printf("%s\t",ptr->name); printf("%d\t",ptr->acc_no); printf("%lli\t\t",ptr->phone); printf("%lf",ptr->balance); } } else { while(ptr!=NULL) { if(noacc==ptr->acc_no) { flag=1; printf("\n\t\t ACC DETAILS ARE : \n"); printf("NAME\t\tACC_NO\tPHONE N0.\t\tBALANCE\n"); printf("%s\t",ptr->name); printf("%d\t",ptr->acc_no); printf("%lli\t\t",ptr->phone); printf("%lf",ptr->balance); break; } ptr=ptr->next; } } if(flag==0) { printf("\n\t\t NOTHING FOUND REGARDING THAT ACC_NO.!!\n"); } printf("\n\n\nENTER --> 1: FOR THE MENU , 2: TO EXIT , 0: TO TRY AGAIN:: YOUR CHOICE : "); scanf("%d",&todo); if(todo==1) { menu(); } else if(todo==2) { close(); } else if(todo==0) { goto again; } } void transact() { system("cls"); int choice,option,acc,flag=0,i,strength=0,tp=0,let; double amt; struct node *ptr; ptr = start ; printf("\n\t\t WOULD YOU LIKE TO :\n\t\t 1--DEPOSIT\n\t\t 2--WITHDRAW\n\n"); printf("\n\t\t ENTER YOUR CHOICE : "); scanf("%d",&choice); system("cls"); repeat : printf("\n\t\t ENTER YOUR ACC NO : "); scanf("%d",&acc); if(choice==1) { more : printf("\n\t\t ENTER THE AMOUNT YOU WANT TO DEPOSIT : "); scanf("%lf",&amt); if(amt<=0) { printf("\n\t\t THE AMOUNT %lf IS INCORRECT \n",amt); printf("\n\t\t WOULD YOU LIKE TO ENTER AGAIN : \n\n\t1--YES \n\n\t 2-- NO , GO TO MAIN MENU \n"); scanf("%d",&option); if(option==1) { goto more; } if(option==2) { menu(); } } if(start==NULL) { printf("\n\n\t\t NO DATA PRESENT"); printf("\n\t\tPROCEEDING TO MENU PLEASE WAIT "); for(i=0;i<=6;i++) { fordelay(100000000); printf("."); } menu(); strength=1; } if(strength==0) { if(start->acc_no==acc) { //printf("working"); ptr->balance = ( (ptr->balance)+amt ); printf("\n\t\tSUCCESSFULL TRANSACTION \n\t\t PROCEEDING TO MENU PLEASE WAIT "); for(i=0;i<=6;i++) { fordelay(100000000); printf("."); } menu(); tp=1; } if(tp==0) { { //printf("working1"); while(ptr->next!=NULL) { if(ptr->acc_no==acc) { flag=1; break; } ptr=ptr->next; } } if(flag==0) { printf("\n\t\t NO SUCH ACC FOUND\n"); printf("\n\t\t WOULD YOU LIKE TO ENTER AGAIN : 1--YES OR 2-- NO , GO TO MAIN MENU \n \t\tENTER CHOICE : "); scanf("%d",&option); if(option==1) { goto repeat; } if(option==2) { menu(); } } if(flag==1) { //printf("working2"); ptr->balance=((ptr->balance)+amt); printf("\n\n\t\t -----TRANSACTION SUCCESSFULL -----\n"); } } } } if(choice==2) { system("cls"); while(ptr!=NULL) { if(ptr->acc_no=acc) { flag=1; break; } ptr=ptr->next; } if(flag==0) { printf("\n\n\t\tNO RECORDS FOUND . MOVING YOU TO MAIN MENU PLEASE WAIT "); for(i=0;i<=6;i++) { fordelay(100000000); printf("."); } menu(); } if(ptr->balance==0) { printf("\n\t\tYOUR BALANCE IS %lf NOT SUFFICIENT",ptr->balance); printf("\n\t\t PROCEEDING TO MENU PLEASE WAIT "); for(i=0;i<=6;i++) { fordelay(100000000); printf("."); } menu(); } re : printf("\n\t\t ENTER THE AMOUNT TO WITHDRAW : "); scanf("%lf",&amt); if(amt<=0) { printf("\n\t\t ENTER APPROPRIATE AMOUNT \n"); printf("\n\t\t DO YOU WANT TO TRY AGAIN : 1--TRY AGAIN && 2--GO TO MENU\n\n"); printf("\n\t\t ENTER YOUR CHOICE : "); scanf("%d",&let); if(let==1) {goto re;} if(let==2) { menu(); } } else if(amt>ptr->balance) { printf("\n\t\t ( INSUFFICIENT BALANCE ) YOUR BAL = %lf < WITHDRAW AMOUNT = %lf",ptr->balance,amt); printf("\n\t\t DO YOU WANT TO TRY AGAIN : 1--TRY AGAIN && 2--GO TO MENU\n\n"); printf("\n\t\t ENTER YOUR CHOICE : "); scanf("%d",&let); if(let==1) {goto re;} if(let==2) { menu(); } } else { ptr->balance = ((ptr->balance)-amt); printf("\n\t\t -----WITHDRAWAL SUCCESFULL-----"); printf("\n\t\t ENTER : 1-- EXIT OR 2--MAIN MENU\n \t\t CHOICE : "); scanf("%d",&let); if(let==1) {close();} if(let==2) { menu(); } } } } void erase() { system("cls"); int acc,i,flag=0,choice; char del[7]="delete",confirm[7]; struct node *ptr,*preptr; ptr = start ; preptr = start ; if(start==NULL) { printf("\n\n\n\t\t NO RECORDS TO DISPLAY"); printf("\n\n\t\t DIRECTING TOWARDS MENU : KINDLY WAIT "); for(i=0;i<=6;i++) { fordelay(100000000); printf("."); } menu(); } else { once : system("cls"); printf("\n\t\t FOR DELETION : \n"); printf("\n\t\t PLEASE ENTER ACC_NO. : "); scanf("%d",&acc); if(start->acc_no==acc&&start->next==NULL) { printf("\n\t\t ENTER PASSWORD : "); scanf("%s",&confirm); if(strcmp(confirm,del)==0) { printf("\n\t\t DELETING "); for(i=0;i<=6;i++) { fordelay(100000000); printf("."); } start = NULL; printf("\n\t\t PROCEEDING TOWARDS MENU "); for(i=0;i<=6;i++) { fordelay(100000000); printf("."); } menu(); } } else if( (start->acc_no==acc )&& (start->next!=NULL)) { printf("\n\t\t ENTER PASSWORD : "); scanf("%s",&confirm); if(strcmp(confirm,del)==0) { printf("\n\t\t DELETING "); for(i=0;i<=6;i++) { fordelay(100000000); printf("."); } start = start -> next ; printf("\n\t\t PROCEEDING TOWARDS MENU "); for(i=0;i<=6;i++) { fordelay(100000000); printf("."); } menu(); } } else { while(ptr!=NULL) { if(ptr->acc_no==acc) { flag=1; break; } preptr=ptr; ptr=ptr->next; } if(flag==1) { printf("\n\t\t ENTER PASSWORD : "); scanf("%s",&confirm); if(strcmp(confirm,del)==0) { preptr->next=ptr->next; free(ptr); printf("\n\t\t SUCCESSFULLY DELETED"); } printf("\n\t\t PROCEEDING TOWARDS MENU "); for(i=0;i<=6;i++) { fordelay(100000000); printf("."); } menu(); } if(flag==0) { printf("\n\n\t NO SUCH ACC FOUND : \n\n\t\t ENTER : 1 - TRY AGAIN 2 - EXIT 3 - MENU \n"); printf("ENTER CHOICE : "); scanf("%d",&choice); if(choice==3) { menu(); } if(choice==2) { close(); } if(choice==1) { goto once; } } } } } void view_list() { system("cls"); int i,choice; struct node *ptr; ptr = start; if(start == NULL) { printf("\n\t\t NO DATA TO DISPLAY "); printf("\n\n\t\t BACK TO MENU "); for(i=0;i<=6;i++) { fordelay(100000000); printf("."); } menu(); } else { printf("\n\t\t ACC DETAILS ARE : \n\n"); while(ptr!=NULL) { printf("NAME\t\tACC_NO\tPHONE N0.\tBALANCE\n"); printf("%s\t",ptr->name); printf("%d\t",ptr->acc_no); printf("%lli\t\t",ptr->phone); printf("%lf",ptr->balance); ptr=ptr->next; printf("\n"); } printf("\n\n\t\t -----END OF LIST -----\n\n"); printf("\t\tENTER : 1 -- MENU ; 2 -- EXIT\n"); printf("\n\t\tENTER CHOICE : "); scanf("%d",&choice); if(choice==1) { menu(); } if(choice==2) { close(); } } } void menu() { int choice; char temp; system("cls"); system("color E"); printf("\n\t\t BANKING MANAGEMENT SYSTEM\n"); printf("\n\t********** WELCOME TO THE MAIN MENU *********\n"); printf("\n\t\t1.Create new account\n\t\t2.For transactions\n\t\t3.Check the details of existing account\n\t\t4.Removing existing account\n\t\t5.View customer's list\n\t\t6.Exit\n\n\t\tEnter your choice: "); scanf("%d",&choice); scanf("%c",&temp); switch(choice) { case 1:new_acc(); break; case 2:transact(); break; case 3:see(); break; case 4:erase(); break; case 5:view_list(); break; case 6:close(); break; } } void main() { char pass[9],password[9]="justdoit"; int i=0,main_exit; system("color E"); printf("\n\n\t\tEnter the password to login: "); scanf("%s",pass); if (strcmp(pass,password)==0) {printf("\n\nPassword Match!\nLOADING"); for(i=0;i<=6;i++) { fordelay(100000000); printf("."); } menu(); } else { printf("\n\nWrong password!!\a\a\a"); login_try_again: printf("\nEnter 1 to try again and 0 to exit:"); scanf("%d",&main_exit); if (main_exit==1) { main(); } else if (main_exit==0) { close(); } else { printf("\nInvalid!"); fordelay(1000000000); goto login_try_again; } } }
C
/** * \file majPlateau.h * \brief Fonctions gérant la mise à jour du plateau * \author * \version 1.0 * \date */ #ifndef __MAJ_Plateau__ #define __MAJ_Plateau__ #include "position.h" #include "coup.h" #include "plateau.h" #include "placerCoup.h" #include "position.h" #include "pion.h" #include <stdio.h> #include <stdlib.h> #include "couleur.h" /** * \fn void OTH_majPlateau(PL_Plateau *lePlateau, C_Coup leCoup) * \brief Fonction qui renouvelle le plateau après chaque coup * \param PL_Plateau lePlateau l'ancien plateau * \param C_Coup leCoup coup qui vient d'être placé * \return void */ void OTH_majPlateau(PL_Plateau *lePlateau, C_Coup leCoup); /** * \fn void OTH_retournerPion(PL_Plateau *lePlateau, PO_Position positionDuPion) * \brief Fonction qui retourne un pion (conséquence du coup qui vient d'être placé) * \param PL_Plateau lePlateau le plateau * \param PO_Position positionDuPion position du pion qui doit être retourné * \return void */ void OTH_retournerPion(PL_Plateau *lePlateau, PO_Position positionDuPion); void maj (PL_Plateau* plateau,C_Coup coup); #endif
C
#include <stdio.h> void PrintBill(float units,float a[5],float extraCharge,char firstName[100],char lastName[100],int range[8]); int main(){ int i,choice; float units,extraCharge,totalBill,sum=0.0; char firstName[100],lastName[100]; printf("Enter\n1.To Calculate electricity of your own custom values\n2.To use Predefined values\n"); scanf("%d",&choice); switch(choice) { case 1: { int k=0; float a[5]; int range[8]={1,50,51,100,101,200,201,300}; printf("Enter First Name\n"); fflush(stdin); gets(firstName); printf("Enter Last Name\n"); fflush(stdin); gets(lastName); for(i=0; i<5; i++) { if(k<7) printf("Enter Cost/Unit for %d - %d units\n",range[k],range[k+1]); else printf("Enter Cost/Unit for >300 units\n"); scanf("%f",&a[i]); k+=2; } printf("Enter Extra Charge\n"); scanf("%f",&extraCharge); printf("Enter Total Number of Units used/consumed\n"); scanf("%f",&units); PrintBill(units,a,extraCharge,firstName,lastName,range); break; } case 2: { int k=0; int range[8]={1,50,51,100,101,200,201,300}; float a[5]={1.2,3,3.3,4.1,5.2}; extraCharge=3.5; printf("Enter First Name\n"); fflush(stdin); gets(firstName); printf("Enter Last Name\n"); fflush(stdin); gets(lastName); printf("Enter Total Number of Units used/consumed\n"); scanf("%f",&units); PrintBill(units,a,extraCharge,firstName,lastName,range); break; } default: printf("Enter Valid Choice\n"); } return 0; } void PrintBill(float units,float a[5],float extraCharge,char firstName[100],char lastName[100],int range[8]){ float sum=0.0,totalBill; int k,i; if(units>=1 && units<=50) sum=units*a[0]; else if(units>=51 && units<=100) { sum=(50*a[0])+((units-50)*a[1]); printf("sum (50*a[0])+((units-50)*a[1])= %f",(50*a[0])); } else if(units>=101 && units<=200) sum=(50*a[0])+(50*a[1])+((units-100)*a[2]); else if(units>=201 && units<=300) sum=(50*a[0])+(50*a[1])+(100*a[2])+((units-200)*a[3]); else sum=(50*a[0])+(50*a[1])+(100*a[2])+(100*a[3])+((units-300)*a[4]); totalBill=sum+(extraCharge*sum); printf("\n\n******************Hi %s %s*********************\n\n******Your Electricity Bill*********\n",firstName,lastName); printf("\n Unit Range Cost\n"); k=0; for(i=0; i<5; i++) { if(k<7) printf("%9d - %d",range[k],range[k+1]); else printf(" >300 "); if(i!=0 && i!=4) printf("%15.2f\n",a[i]); else printf("%16.2f\n",a[i]); k+=2; } printf("\nSum=%f\n",sum); printf("Collecting Extra Charge of %f on total amount of %f\n",extraCharge,sum); printf("\nTotal Amount Costed=%f\n",totalBill); }
C
#include <stdio.h> #include <stdlib.h> #define TAM 50 #define ES_MAT_IDEN 1 #define NO_ES_MAT_IDEN 0 void mostrarMatriz(int mat[][TAM], int orden); int esMatrizIdentidad(int mat[][TAM], int ff, int cc); /*Desarrollar una funcin que determine si una matriz cuadrada de enteros de orden N es matriz identidad (matriz diagonal, con unos en la diagonal principal y ceros en los restantes).*/ int main() { int mat[][TAM] ={ {1,0,0,0}, {0,1,0,0}, {0,0,1,0}, {0,0,0,1}, }; mostrarMatriz(mat, 4); if(esMatrizIdentidad(mat, 4, 4)) printf("\nEs matriz identidad.\n"); else printf("\nNo es matriz identidad.\n"); puts(""); system("pause"); return 0; } void mostrarMatriz(int mat[][TAM], int orden) { for(int i =0; i<orden; i++) { for(int j=0; j<orden; j++) printf("%d ", mat[i][j]); puts(""); } } int esMatrizIdentidad(int mat[][TAM], int ff, int cc) { //recorro toda la matriz for(int i=0; i<ff; i++) { for( int j = 0; j<cc ; j++) { //ac me fijo en la diagonal, //si algn elemento es distinto de 1, entonces corto el ciclo y hago return if(i==j && mat[i][j]!=1) return NO_ES_MAT_IDEN; //y ac me fijo en los restantes nmeros, es decir fuera de la diagonal //apenas encuentre un elemento distinto de 0, corto el ciclo y salgo if(i!=j && mat[i][j]!=0) return NO_ES_MAT_IDEN; } } //si logr llegar ac, es porque fue exitosamente una matriz identidad return ES_MAT_IDEN; }
C
#include <stdio.h> int main() { int edad;//variable printf("Introduce tu edad: "); scanf("%d",&edad);//lectura de teclado if (edad >17 && edad <35) { printf("Tienes %d anios, eres mayor de edad\n",edad); } else if (edad < 17) { printf("Tienes %d anios, eres menor de edad\n",edad); } else if (edad >= 35 && edad <= 60) { printf("Tienes %d anios, eres chavo-ruco\n",edad); } else { printf("Tienes %d anios, ",edad); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #define BUF_SIZE 1024 void error_handling ( char * msg ); int main ( int argc, char * argv[] ) { int sock; struct sockaddr_in serv_adr; char buf [ BUF_SIZE - 5 ]; char msg [ BUF_SIZE ]; int msg_len, str_len, i; if ( argc != 3 ) { printf ( "Usage: %s <IP> <Port> \n", argv[0] ); exit ( 1 ); } sock = socket ( PF_INET, SOCK_STREAM, 0 ); if ( sock == -1 ) error_handling ( "socket() error" ); memset ( &serv_adr, 0, sizeof ( serv_adr ) ); serv_adr.sin_family = AF_INET; serv_adr.sin_addr.s_addr = inet_addr ( argv[1] ); serv_adr.sin_port = htons ( atoi ( argv[2] ) ); if ( connect ( sock, ( struct sockaddr* ) &serv_adr, sizeof ( serv_adr ) ) == -1 ) error_handling ( "connect() error" ); while ( 1 ) { fputs ( "input message(Quit: q): ", stdout ); fgets ( buf, sizeof ( buf ), stdin ); if ( !strcmp ( buf, "q\n" ) || !strcmp ( buf, "Q\n" ) ) break; str_len = strlen ( buf ) - 1; msg[0] = ( char ) str_len; &msg[4] = buf; write ( sock, msg, BUF_SIZE ); } close ( sock ); return 0; } void error_handling ( char * msg ) { fputs ( msg, stderr ); fputc ( '\n', stderr ); exit ( 1 ); }
C
#include <stdio.h> #include <string.h> int my_strcmp(const char *s1,const char *s2); int main(void) { char str1[80]; char str2[80]; printf("Input String1>"); scanf("%s",str1); printf("Input String2>"); scanf("%s",str2); printf("ref Result : %d\n",strcmp(str1,str2)); printf("Result : %d\n",my_strcmp(str1,str2)); } int my_strcmp(const char *s1,const char *s2) { int i; for(i=0;s1[i]!='\0';i++) { if(s2[i]=='\0'|| s1[i]!=s2[i]) { break; } } return s1[i]-s2[i]; }
C
#include <stdio.h> int main() { int n; int isPrime = 0; scanf_s("%d", &n); for (int i = 2; i < n; i++) { if (n % i == 0) isPrime = 1; } if (isPrime == 1) printf("Not Prime"); else printf("Prime!"); }
C
#include <stdio.h> int main(void) { //code up a switch statement int num1; int num2; int result = 0; printf("Enter two numbers separated by a space: "); scanf("%d %d", &num1, &num2); //fflush(stdin); char selection; printf("Enter a for add or s for subtract:"); //fflush(stdin); while(getchar() != '\n'); scanf("%c", &selection); //selection = getchar(); switch (selection){ case 'a': //stuff to do result = num1 + num2; printf("Operation result is: %d", result); break; case 's': result = num1 - num2; break; default: //if nothing else meets the cases printf("Bad input"); break; } printf("Operation result is: %d", result); printf("You selected the %c operation",selection); return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_4__ TYPE_1__ ; /* Type definitions */ typedef scalar_t__ ut32 ; struct TYPE_4__ {scalar_t__ x; scalar_t__ n; scalar_t__ p; } ; typedef TYPE_1__ buffer ; /* Variables and functions */ int /*<<< orphan*/ buffer_flush (TYPE_1__*) ; int /*<<< orphan*/ memcpy (scalar_t__,char const*,scalar_t__) ; int buffer_putalign(buffer *s, const char *buf, ut32 len) { ut32 n; if (!s || !s->x || !buf) { return 0; } while (len > (n = s->n - s->p)) { memcpy (s->x + s->p, buf, n); s->p += n; buf += n; len -= n; if (!buffer_flush (s)) { return 0; } } /* now len <= s->n - s->p */ memcpy (s->x + s->p, buf, len); s->p += len; return 1; }
C
/* Simple program demonstrates to do simple FILE access with fopen, fwrite, fseek and fread http://manpages.courier-mta.org/htmlman3/fread.3.html */ #include <stdio.h> #include <string.h> int main() { FILE *fp; char c[] = "this is tutorialspoint"; char buffer[100]; /* Open file for both reading and writing */ fp = fopen("file.txt", "w+"); /* Write data to the file */ fwrite(c, 1, strlen(c) + 1, fp); /* Seek to the beginning of the file */ fseek(fp, SEEK_SET, 0); /* Read and display data */ fread(buffer, 1, strlen(c)+1, fp); printf("%s\n", buffer); fclose(fp); return(0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lvergero <lvergero@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/11/09 19:37:11 by lvergero #+# #+# */ /* Updated: 2014/11/09 19:37:13 by lvergero ### ########.fr */ /* */ /* ************************************************************************** */ #include "../test.h" int main(int ac, char **av) { char *my_location; char *sys_location; if (ac == 3 && av[2][1] == '\0') { my_location = ft_strrchr(av[1], av[2][0]); sys_location = strrchr(av[1], av[2][0]); if (my_location == sys_location) { printf("\033[1;33;32mNative strrchr and ft_strrchr both returned the same pointer\033[0m\n"); return (SUCCESS); } printf("\033[1;33;31mNative strrchr returned %s while ft_strrchr returned : %s\033[0m\n", sys_location, my_location); return (FAILURE); } printf("\033[1;33;33mPlease input one string of characters and one character which last occurence will be returned\033[0m\n"); return (FAILURE); }
C
// Compute mean and median temperatures // g++ -g -o vector_sort.exe vector_sort.C 2>&1 | tee tmp.txt //#include "std_lib_facilities.h" #include<iostream> #include<vector> // this is where standard vector is defined #include<algorithm> // this is where sort is defined using namespace std; // if you don't want to type std::vector all the time template<typename C> // requires Container<C>() void sort(C& c) { std::sort(c.begin(), c.end()); } int main () { vector <double> temps; // temperatures cout << "Please enter temperatures. Use Ctr-Z (Windows), Ctr-D (Unix) to terminate input:\n"; for (double temp; cin >> temp;) // read into temp temps.push_back(temp); // put temp into vector // compute mean temperature double sum = 0.0; //for (double x:temps) sum += x; for (int i=0; i<temps.size(); ++i) sum += temps[i]; cout << "Average temperature:" << sum/temps.size() << endl; // compute median temperature: sort (temps); int size = temps.size(); double median; // will put the median value in there if (size & 1) { // odd size, so the value in the middle will be median: [0 1 2]. 1 = 3/2 median = temps[size/2]; } else { // even size, so we average two values that are in the middle: [0 1 2 3] => (1+2)/2 =1.5 median = (temps[size/2] + temps[size/2 - 1]) / 2.0; } cout << "Median temperature: " << median << endl; return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <pthread.h> #include <math.h> #include <sys/time.h> long GB_DATA = 1000000000; int BLOCK_SIZE = 8; int NUMBER_OF_ITERATIONS = 1000; int NUMBER_OF_THREADS =1; char TYPE = 'W'; //To perfrom Sequential Read Write struct sequential_read_write{ char * dstn; char * src; }; void* sequential_read_write(void* arg){ struct sequential_read_write *RW_Seq = (struct sequential_read_write *)arg; for(int i;i<NUMBER_OF_ITERATIONS;i++) { memcpy(RW_Seq -> dstn, RW_Seq -> src, BLOCK_SIZE); } //pthread_exit(NULL); } //To perform Random Read Write struct random_read_write{ char * dstn; char * src; char random_operation; }; void* random_read_write(void* arg){ struct random_read_write *RW_random = (struct random_read_write *)arg; for(int i;i<NUMBER_OF_ITERATIONS;i++) { memcpy(RW_random -> random_operation, RW_random -> src, BLOCK_SIZE); } //pthread_exit(NULL); } void print_result(double total_time, double throughput) { if (TYPE=='W') { if (BLOCK_SIZE==8) { printf("Memory, Latency -> Read write operations, 8B block size, %d thread - %.6lf us\n",NUMBER_OF_THREADS,(total_time/(NUMBER_OF_ITERATIONS*BLOCK_SIZE))*1000000); } else if (BLOCK_SIZE==8192){ printf("Memory, Throughput -> Read write operations, 8KB block size, %d thread - %.2lf MB/sec\n",NUMBER_OF_THREADS,throughput/1048576); } else if (BLOCK_SIZE==8388608) { printf("Memory, Throughput -> Read write operations, 8MB block size, %d thread - %.2lf MB/sec\n",NUMBER_OF_THREADS,throughput/1048576); } else { printf("Memory, Throughput -> Read write operations, 80MB block size, %d thread - %.2lf MB/sec\n",NUMBER_OF_THREADS,throughput/1048576); } } else { if (BLOCK_SIZE==8) { printf("Memory, Latency -> Write random operations, 8B block size, %d thread - %.6lf us\n",NUMBER_OF_THREADS,(total_time/(NUMBER_OF_ITERATIONS*BLOCK_SIZE))*1000000); } else if (BLOCK_SIZE==8192){ printf("Memory, Throughput -> Write random operations, 8KB block size, %d thread - %.2lf MB/sec\n",NUMBER_OF_THREADS,throughput/1048576); } else if (BLOCK_SIZE==8388608) { printf("Memory, Throughput -> Write random operations, 8MB block size, %d thread - %.2lf MB/sec\n",NUMBER_OF_THREADS,throughput/1048576); } else { printf("Memory, Throughput -> Write random operations, 80MB block size, %d thread - %.2lf MB/sec\n",NUMBER_OF_THREADS,throughput/1048576); } } } void calculate_memory_benchmark(){ char * source = (char *)malloc(BLOCK_SIZE*NUMBER_OF_ITERATIONS); char * dest = (char *)malloc(BLOCK_SIZE); memset(source, 2, BLOCK_SIZE*NUMBER_OF_ITERATIONS); memset(dest, 1, BLOCK_SIZE); struct sequential_read_write{ char * dstn; char * src; }; struct random_read_write{ char * dstn; char * src; int random_operation; }; struct timeval start_time, end_time; gettimeofday(&start_time, NULL ); pthread_t thread_id[NUMBER_OF_THREADS]; int thread[NUMBER_OF_THREADS]; int i; if(TYPE == 'W') { struct sequential_read_write *RW_Seq; for (i=0;i<NUMBER_OF_THREADS;i++) { thread[i] = pthread_create(&(thread_id[i]),NULL,sequential_read_write,(void *)&RW_Seq); } } else { struct random_read_write *RW_random; for (i=0;i<NUMBER_OF_THREADS;i++) { thread[i] = pthread_create(&(thread_id[i]),NULL,random_read_write,RW_random); } } for (i=0;i<NUMBER_OF_THREADS;i++) { pthread_join(thread_id[i], NULL); } gettimeofday(&end_time, NULL); double total_time = ((end_time.tv_sec+(end_time.tv_usec/1000000.0))-(start_time.tv_sec+(start_time.tv_usec/1000000.0))); double bytes_accessed = (double) (BLOCK_SIZE*NUMBER_OF_ITERATIONS*NUMBER_OF_THREADS); double throughput = bytes_accessed/total_time; print_result(total_time,throughput); } int main(int argc, char *argv[]){ int arg; printf("\nmsin\n"); //while((arg=getopt(argc, argv, "wsro:t:b:")) != -1) { switch(arg) { case 'w': TYPE='W'; // for sequential read-write break; case 's': TYPE='S'; // for random read write break; //case 'r': //TYPE='R'; // for random write //break; //case 'o': //NUMBER_OF_ITERATIONS=atoi(optarg); //break; //case 't': //THREAD_COUNT=atoi(optarg); // break; //case 'b': //BLOCK=atoi(optarg); //break; default: break; } //printf("The loop is executed \n "); calculate_memory_benchmark(); return 0; }
C
// N-Queens problem to print all possible solutions. // Place n number of queens in n x n chessBoard so that no 2 queens attack. // Note: Using Backtracking // @author Mohammed Ataaur Rahaman // School: Dayananda Sagar // Date: 22 April, 2018 #include<conio.h> #include<stdio.h> int N, vector[100]; int i, count = 0; int place(int cur) { for(i = 1; i <= cur - 1; i++) { if(vector[i] == vector[cur]) return 0; else if(abs(vector[i] - vector[cur]) == abs(i - cur)) return 0; } return 1; } void N_Queen() { int cur = 1; vector[cur] = 0; while(cur != 0) { vector[cur] += 1; //place at the first place. while(vector[cur] <= N && place(cur) == 0) //if cant be placed.. then increment. vector[cur] += 1; if(vector[cur] <= N) { if(cur == N) { count++; printf("\nSolution %d --> ",count); for(i = 1; i <= N; i++) printf("%d ",vector[i]); } else //next queen { cur++; vector[cur] = 0; } } else //previous queen cur--; } } void main() { printf("Enter Number of Queens(N): "); scanf("%d",&N); if(N < 4) printf("Solution Does't exists."); else { printf("Solution: \n"); N_Queen(); } }
C
#include <stdio.h> #include<math.h> int main() { float x1,x2,y1,y2,dist; printf("enter the point (x1,y1)\n"); scanf("%f%f",&x1,&y1); printf("enter the point (x2,y2)\n"); scanf("%f%f",&x2,&y2); dist=(y2-y1)/(x2-x1); printf("the distance between the two points is %f",dist); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include<ctype.h> char oper[500], ident[500][50], integer[500][50], real[500][50], keyword[500][50], invalid[500][50]; int oplen, idenlen, intlen, reallen, keylen, invlen; bool isDelimiter(char ch){ if (ch == '+' || ch == '-' || ch == '*' ||ch == '/' || ch == ' ' ||ch == ',' || ch == ';' || ch == '>' || ch == '<' || ch == '=' || ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '{' || ch == '}' ||ch=='&' ||ch=='|') return (true); return (false); } bool isOperator(char ch){ if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '>' || ch == '<' || ch == '=' || ch=='|' || ch=='&') return (true); return (false); } bool validIdentifier(char* str){ if ((str[0] >= '0' && str[0]<='9') || str[0] == '#' || str[0]=='"' || str[0]=='%' || str[0]=='&' || isDelimiter(str[0]) == true) return (false); int len = strlen(str), i; for(i=1;i<len;i++){ if(str[i]=='_' || str[i]=='$' || isalnum(str[i])) continue; return 0; } return (true); } bool isKeyword(char* str){ if (!strcmp(str, "if") || !strcmp(str, "else") || !strcmp(str, "while") || !strcmp(str, "do") || !strcmp(str, "break") || !strcmp(str, "continue") || !strcmp(str, "int") || !strcmp(str, "double") || !strcmp(str, "float") || !strcmp(str, "return") || !strcmp(str, "char") || !strcmp(str, "case") || !strcmp(str, "char") || !strcmp(str, "sizeof") || !strcmp(str, "long") || !strcmp(str, "short") || !strcmp(str, "typedef") || !strcmp(str, "switch") || !strcmp(str, "unsigned") || !strcmp(str, "void") || !strcmp(str, "static") || !strcmp(str, "struct") || !strcmp(str, "goto")) return (true); return (false); } bool isInteger(char* str){ int i, len = strlen(str); if (len == 0) return (false); for (i = 0; i < len; i++){ if (str[i] != '0' && str[i] != '1' && str[i] != '2' && str[i] != '3' && str[i] != '4' && str[i] != '5' && str[i] != '6' && str[i] != '7' && str[i] != '8' && str[i] != '9' || (str[i] == '-' && i > 0)) return (false); } return (true); } bool isRealNumber(char* str){ int i, len = strlen(str); bool hasDecimal = false; if (len == 0) return (false); for (i = 0; i < len; i++) { if (str[i] != '0' && str[i] != '1' && str[i] != '2' && str[i] != '3' && str[i] != '4' && str[i] != '5' && str[i] != '6' && str[i] != '7' && str[i] != '8' && str[i] != '9' && str[i] != '.' || (str[i] == '-' && i > 0)) return (false); if (str[i] == '.') hasDecimal = true; } return (hasDecimal); } char* subString(char* str, int left, int right){ int i; char* subStr = (char*)malloc( sizeof(char) * (right - left + 2)); //char subStr[right-left+2]; for (i = left; i <= right; i++) subStr[i - left] = str[i]; subStr[right - left + 1] = '\0'; return (subStr); } void parse(char str[]){ int left = 0, right = 0; int len = strlen(str); while (right <= len && left <= right) { if (isDelimiter(str[right]) == false) right++; if (isDelimiter(str[right]) == true && left == right) { if (isOperator(str[right]) == true){ oper[oplen++] = str[right]; /*printf("%c is an operator.\n", str[right]);*/ } right++; left = right; } else if (isDelimiter(str[right]) == true && left != right || (right == len && left != right)) { char* subStr = subString(str, left, right - 1); if (isKeyword(subStr) == true){ /*printf("%s is a keyword.\n", subStr);*/ strcpy(keyword[keylen++], subStr); } else if (isInteger(subStr) == true){ /*printf("%s is an integer.\n", subStr);*/ strcpy(integer[intlen++], subStr); } else if (isRealNumber(subStr) == true){ /*printf("%s is a real number.\n", subStr);*/ strcpy(real[reallen++], subStr); } else if (validIdentifier(subStr) == true && isDelimiter(str[right - 1]) == false){ /*printf("%s is a valid identifier.\n", subStr);*/ strcpy(ident[idenlen++], subStr); } else if (validIdentifier(subStr) == false && isDelimiter(str[right - 1]) == false){ /*printf("%s is not a valid identifier.\n", subStr);*/ strcpy(invalid[invlen++], subStr); } left = right; } } return; } int main(){ FILE *file =freopen("file.txt","r+",stdin); if (file != NULL ){ char str[200]; while(fgets(str,sizeof str, file )!= NULL ){ /* read a line */ if(strlen(str)==0) continue; int i = 0, ch = 0; while(str[i]!='\n'){ if(str[i]!=' ') ch++; i++; } if(ch==0) continue; str[i] = '\0'; parse(str); } int i; printf("List of identifiers in the program:\n"); for(i=0;i<idenlen;i++) printf("%s ", ident[i]); printf("\n\n"); printf("List of keywords in the program:\n"); for(i=0;i<keylen;i++) printf("%s ", keyword[i]); printf("\n\n"); printf("List of integer number in the program:\n"); for(i=0;i<intlen;i++) printf("%s ", integer[i]); printf("\n\n"); printf("List of real numbers in the program:\n"); for(i=0;i<reallen;i++) printf("%s ", real[i]); printf("\n\n"); printf("List of real operators in the program:\n"); for(i=0;i<oplen;i++) printf("%c ", oper[i]); printf("\n\n"); fclose (file); } }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> void main() { char str[100]; int i,j,n; printf("Input please:"); gets(str); n=strlen(str); for(i=0;i<=n;i++) { for(j=0;j<=i;j++) { if(str[i]==str[j]) { break; } } if(j==i) { printf("%c",str[j]); } } }
C
#include "rtc.h" #include "kheap.h" #include "common.h" static RTC *rtc = 0; #define CMOS_ADDRESS 0x70 #define CMOS_DATA 0x71 #define SECONDS_KEY 0x00 #define MINUTES_KEY 0x02 #define HOURS_KEY 0x04 #define DAYS_KEY 0x08 #define MONTHS_KEY 0x07 #define YEARS_KEY 0x09 #define CENTURIES_KEY 0x32 static u8int __rtc_checkIfUpdateIsInProgress(void) { __asm__ __volatile__ ("cli"); outb(CMOS_ADDRESS, 0x0A); u8int ret = inb(CMOS_DATA) & 0x80; __asm__ __volatile__ ("sti"); return ret; } static u8int __rtc_getRegisterValue(u8int reg) { __asm__ __volatile__ ("cli"); while (__rtc_checkIfUpdateIsInProgress()); outb(CMOS_ADDRESS, reg); u8int ret = inb(CMOS_DATA); __asm__ __volatile__ ("sti"); return ret; } void rtc_init(void) { rtc = (RTC*)kalloc(sizeof(RTC)); rtc_read(); } void rtc_read(void) { if (rtc == 0) return; rtc->seconds = __rtc_getRegisterValue(SECONDS_KEY); rtc->minutes = __rtc_getRegisterValue(MINUTES_KEY); rtc->hours = __rtc_getRegisterValue(HOURS_KEY); rtc->days = __rtc_getRegisterValue(DAYS_KEY); rtc->months = __rtc_getRegisterValue(MONTHS_KEY); rtc->years = __rtc_getRegisterValue(YEARS_KEY); rtc->centuries = __rtc_getRegisterValue(CENTURIES_KEY); u8int registerB = __rtc_getRegisterValue(0x0B); if (!(registerB & 0x04)) { rtc->hours = (rtc->hours & 0x0F) + (rtc->hours / 16) * 10; rtc->seconds = (rtc->seconds & 0x0F) + (rtc->seconds / 16) * 10; rtc->minutes = (rtc->minutes & 0x0F) + (rtc->minutes / 16) * 10; rtc->days = (rtc->days & 0x0F) + (rtc->days / 16) * 10; rtc->months = (rtc->months & 0x0F) + (rtc->months / 16) * 10; rtc->years = (rtc->years & 0x0F) + (rtc->years / 16) * 10; rtc->centuries = (rtc->centuries & 0x0F) + (rtc->centuries / 16) * 10; } if (!(registerB & 0x02) && (rtc->hours & 0x80)) rtc->hours = ((rtc->hours & 0x7F) + 14) % 24; } RTC* rtc_getRTC(void) { return rtc; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> int main(void) { int i,j,x, aleatorio, condicao, maxLinha, maxColum, intervaloAleatorio, numTotal, maior, menor, lMaior, lMenor,Total; int sorteio[5000][6]; int listQDN[59]; //QDN Quantidade de Numero int listSUP[59]; //Lista Suporte maxLinha = 5000; maxColum = 6; intervaloAleatorio = 60; condicao = 1; srand( (unsigned)time(NULL) ); printf("TRABALHO DOS ALUNOS:/n"); printf("THIAGO KIM NAKAMURA RA:3018200068/n"); printf("MATHEUS DA FONSECA SOBRAL RA:3018201165/n"); printf("CAIO FELLIPE DA SILVA BARROS RA:3018200619/n"); printf("HENRIQUE DECARLI TAVARES RA:3018201113/n"); printf("VANESSA CAMBUY PEREIRA RA:3019113022/n"); printf("THAIS NUNES CARLOS RA:3018200367/n"); printf("RAQUEL MASSAROPE RA:/n"); printf("\n\n1) Gerando os sorteios aleatorios cada um com 6 numeros unicos:\n"); printf("Pressione qualquer tecla para continuar.\n\n"); getch(); for( i = 0; i < maxLinha; i++ ){ printf("%05d -- ",i+1); for( j = 0; j < maxColum; j++ ){ aleatorio=1+(rand() % intervaloAleatorio); for( x = j+1; x > -1; x--){ if( aleatorio == sorteio[i][x]){ aleatorio = 1 + (rand() % intervaloAleatorio); x = j; } } sorteio[i][j] = aleatorio; printf("%02d ", sorteio[i][j]); } printf("\n"); } printf("\n\n2.a) Quantidade de vezes que cada numero saiu nos sorteios: \n\n"); printf("Pressione qualquer tecla para continuar.\n\n"); getch(); numTotal =0; for(x=1;x<=60;x++){ for( i = 0; i < maxLinha; i++ ){ for( j = 0; j < maxColum; j++ ){ if(sorteio[i][j] == x){ numTotal = numTotal+1; } } } printf("Numero %02d = %02d\n",x,numTotal); listQDN[x-1]=numTotal; numTotal = 0; } printf("\n\n2.b) 15 duplas que mais sairam nos sorteios: \n\n"); printf("Pressione qualquer tecla para continuar.\n\n"); getch(); for(x=0;x<=59;x++){ listSUP[x] = listQDN[x]; } maior=0; menor=0; for(x=1;x<=15;x++){ for(i=0;i<=59;i++){ if(listSUP[i]>maior && lMaior != i){ maior = listSUP[i]; lMaior = i; i=0; } else{ if(listSUP[i]>menor && lMaior != i){ menor = listSUP[i]; lMenor = i; i=0; } } } listSUP[lMaior] = 0; listSUP[lMenor] = 0; Total = maior + menor; printf("\nDupla %02d - Numeros %02d,%02d = %02d vezes\n",x,lMaior+1, lMenor+1,Total); maior=0; menor=0; } printf("\n\n2.c) 15 numeros unicos que mais sairam nos sorteios: \n\n"); printf("Pressione qualquer tecla para continuar.\n\n"); getch(); for(x=0;x<=59;x++){ listSUP[x] = listQDN[x]; } maior=0; for(x=1;x<=15;x++){ for(i=0;i<=59;i++){ if(listSUP[i]>maior){ maior = listSUP[i]; lMaior = i; } } listSUP[lMaior] = 0; printf("\n%02d - Numero %02d = %02d vezes\n",x,lMaior+1, maior); maior=0; } printf("\n\n2.d) Listando a quantidade de jogadas desde a ultima vez que o numero foi sorteado:\n"); printf("Pressione qualquer tecla para continuar.\n\n"); getch(); condicao = 0; numTotal = 0; for(x=1;x<=60;x++){ for( i = 0; i < maxLinha; i++ ){ for( j = 0; j < maxColum; j++ ){ if(sorteio[i][j] == x){ condicao = 1; } } if(condicao == 1){ numTotal = 0; condicao = 0; } else{ numTotal++; } } printf("Numero %02d, nao sai a %02d sorteios seguidos\n",x,numTotal); numTotal = 0; condicao = 0; } printf("\n\n3) Simular uma jogada para 3 usuarios diferentes:\n"); printf("Pressione qualquer tecla para continuar.\n\n"); getch(); int tamanho; //apostador 1 char nome1[50]; char cpf1[20]; int aposta1[5]; condicao = 0; printf("\n\n------------- PRIMEIRO APOSTADOR -------------\n"); printf("\nDigite o nome do primeiro apostador:\n"); fflush(stdin); gets(nome1); while(condicao == 0){ printf("\n\nDigite o CPF primeiro apostador, sem pontos ou tracos:\n"); scanf("%s", cpf1); tamanho = strlen(cpf1); if(tamanho == 11){ condicao = 1; printf("CPF registrado com SUCESSO !!!\n"); } else{ printf("CPF INVALIDO !!!\n"); } } printf("\n\n-------- VAMOS AS APOSTAS, NUMEROS TEM QUE SER DE 0 A 60 SEM REPETIR --------\n"); printf("BOA SORTE !!!\n"); for(x=0;x<=5;x++){ printf("\nDigite o numero %d\n", x+1); scanf("%d", &aposta1[x]); if(aposta1[x] >=1 && aposta1[x] <=60){ for( i = 0; i <= x; i++){ if(aposta1[x] == aposta1[i-1]){ printf("NUMERO INVALIDO !!!\n"); printf("NAO PODE SER REPETIDO\n"); x--; i=-1; } } } else{ printf("NUMERO INVALIDO !!!\n"); printf("TEM QUE SER ENTRE 1 E 60\n"); x--; } } //apostador 2 char nome2[50]; char cpf2[20]; int aposta2[5]; condicao = 0; printf("\n\n------------- SEGUNDO APOSTADOR -------------\n"); printf("\nDigite o nome do segundo apostador:\n"); fflush(stdin); gets(nome2); while(condicao == 0){ printf("\n\nDigite o CPF segundo apostador, sem pontos ou tracos:\n"); scanf("%s", cpf2); tamanho = strlen(cpf2); if(tamanho == 11){ condicao = 1; printf("CPF registrado com SUCESSO !!!\n"); } else{ printf("CPF INVALIDO !!!\n"); } } printf("\n\n-------- VAMOS AS APOSTAS, NUMEROS TEM QUE SER DE 0 A 60 SEM REPETIR --------\n"); printf("BOA SORTE !!!\n"); for(x=0;x<=5;x++){ printf("\nDigite o numero %d\n", x+1); scanf("%d", &aposta2[x]); if(aposta2[x] >=1 && aposta2[x] <=60){ for( i = 0; i <= x; i++){ if(aposta2[x] == aposta2[i-1]){ printf("NUMERO INVALIDO !!!\n"); printf("NAO PODE SER REPETIDO\n"); x--; i=-1; } } } else{ printf("NUMERO INVALIDO !!!\n"); printf("TEM QUE SER ENTRE 1 E 60\n"); x--; } } //apostador 3 char nome3[50]; char cpf3[20]; int aposta3[5]; condicao = 0; printf("\n\n------------- TERCEIRO APOSTADOR -------------\n"); printf("\nDigite o nome do terceiro apostador:\n"); fflush(stdin); gets(nome3); while(condicao == 0){ printf("\n\nDigite o CPF terceiro apostador, sem pontos ou tracos:\n"); scanf("%s", cpf3); tamanho = strlen(cpf3); if(tamanho == 11){ condicao = 1; printf("CPF registrado com SUCESSO !!!\n"); } else{ printf("CPF INVALIDO !!!\n"); } } printf("\n\n-------- VAMOS AS APOSTAS, NUMEROS TEM QUE SER DE 0 A 60 SEM REPETIR --------\n"); printf("BOA SORTE !!!\n"); for(x=0;x<=5;x++){ printf("\nDigite o numero %d\n", x+1); scanf("%d", &aposta3[x]); if(aposta3[x] >=1 && aposta3[x] <=60){ for( i = 0; i <= x; i++){ if(aposta3[x] == aposta3[i-1]){ printf("NUMERO INVALIDO !!!\n"); printf("NAO PODE SER REPETIDO\n"); x--; i=-1; } } } else{ printf("NUMERO INVALIDO !!!\n"); printf("TEM QUE SER ENTRE 1 E 60\n"); x--; } } printf("\n\n4) Indicando quantos numeros cada usuario acertou:\n"); printf("Pressione qualquer tecla para continuar.\n\n"); getch(); int linha; //apostador 1 linha = 0; maior = 0; menor = 0; for( i = 0; i < maxLinha; i++ ){ for( j = 0; j < maxColum; j++ ){ for(x=0; x<6; x++){ if(sorteio[i][j] == aposta1[x]){ menor++; } } } if(menor>maior){ maior = menor; linha = i+1; } menor = 0; } printf("\n\nPARABENS %s, VOCE ACERTOU %02d NUMEROS! SORTEIO [%02d]\n", nome1, maior, linha); //apostador 2 linha = 0; maior = 0; menor = 0; for( i = 0; i < maxLinha; i++ ){ for( j = 0; j < maxColum; j++ ){ for(x=0; x<6; x++){ if(sorteio[i][j] == aposta2[x]){ menor++; } } } if(menor>maior){ maior = menor; linha = i+1; } menor = 0; } printf("\n\nPARABENS %s, VOCE ACERTOU %02d NUMEROS! SORTEIO [%02d]\n", nome2, maior, linha); //apostador 3 linha = 0; maior = 0; menor = 0; for( i = 0; i < maxLinha; i++ ){ for( j = 0; j < maxColum; j++ ){ for(x=0; x<6; x++){ if(sorteio[i][j] == aposta3[x]){ menor++; } } } if(menor>maior){ maior = menor; linha = i+1; } menor = 0; } printf("\n\nPARABENS %s, VOCE ACERTOU %02d NUMEROS! SORTEIO [%02d]\n", nome3, maior, linha); return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct no No; struct no{ int valor; No* anterior; No* prox; }; typedef struct lista Lista; struct lista{ No* inicio; No* fim; }; Lista* criarLista(){ Lista* l = malloc(sizeof(Lista)); l->inicio=NULL; l->fim=NULL; } void inserirFim(Lista* l,int valor){ No* novo =(No*) malloc(sizeof(No)); novo->valor=valor; No* notemp=l->fim; if(l->fim!=NULL){ notemp->prox=novo; novo->anterior=notemp; novo->prox=NULL; l->fim=novo; }else{ l->inicio=novo; l->fim=novo; novo->prox=NULL; novo->anterior=NULL; } } void destruir_lista(Lista *lis){ No* temp; if(lis->inicio==NULL && lis->fim==NULL){ free(lis); }else{ if(lis->inicio==lis->fim){ No* atual=lis->inicio; free(atual); }else{ No* atual=lis->inicio; while(atual!=lis->fim){ temp=atual; atual=temp->prox; free(temp); } } free(lis); } } int removeOcorrencia(Lista* l, int ocor){ No* ant; No* prox; No* temp; No* atual = l->inicio; int cont=0; while(atual!=l->fim){ if(atual->valor==ocor){ if(atual->anterior==NULL){ prox=atual->prox; temp=atual; l->inicio=prox; prox->anterior=NULL; //free(temp); }else if(atual->prox==NULL){ ant=atual->anterior; temp=atual; l->fim=ant; ant->prox=NULL; //free(temp); }else{ ant=atual->anterior; prox=atual->prox; temp=atual; ant->prox=prox; prox->anterior=ant; } //free(temp); } atual=atual->prox; } if(atual->valor==ocor){ if(atual->prox==NULL){ ant=atual->anterior; temp=atual; l->fim=ant; if(ant!=NULL){ ant->prox=NULL; } } } No* p; for(p=l->inicio; p!=NULL; p=p->prox){ if((p!=NULL && p->prox!=NULL && p->prox->prox!=NULL) && (p->valor==p->prox->valor && p->valor==p->prox->prox->valor)){ return 1; } } return 0; } int main(){ int valor=1,ocorr,tripla=0; Lista* l; while(valor!=-1){ l=criarLista(); while(valor!=0 && valor!=-1){ scanf("%d",&valor); if(valor!=0 && valor!=-1){ inserirFim(l,valor); } } if(valor!=-1){ if(valor==-1){ break; } scanf("%d",&ocorr); tripla=removeOcorrencia(l,ocorr); if(tripla==1){ printf("tripla\n"); }else{ printf("nada\n"); } } if(valor!=-1){ valor=1; } destruir_lista(l); } return 0; }
C
// COMP2521 20T2 Assignment 1 // tw.c ... compute top N most frequent words in file F // Usage: ./tw [Nwords] File #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <assert.h> #include <string.h> #include <ctype.h> #include "Dict.h" #include "WFreq.h" #include "stemmer.h" #define STOPWORDS "stopwords" #define MAXLINE 1000 #define MAXWORD 100 #define STARTING "*** START OF" #define ENDING "*** END OF" #define isWordChar(c) (isalnum(c) || (c) == '\'' || (c) == '-') int main( int argc, char *argv[]) { //////////////////////////////////////////////////////////////////////// // DECLARE VARIABLES FILE *in; // currently open file Dict stopwords; // dictionary of stopwords Dict wfreqs; // dictionary of words from book WFreq *results; // array of top N (word,freq) pairs // (dynamically allocated) char *fileName; // name of file containing book text int nWords; // number of top frequency words to show char line[MAXLINE]; // current input line char word[MAXWORD]; // current word //////////////////////////////////////////////////////////////////////// // PROCESS COMMAND LINE ARGUMENTS switch (argc) { case 2: nWords = 10; fileName = argv[1]; break; case 3: nWords = atoi(argv[1]); if (nWords < 10) nWords = 10; fileName = argv[2]; break; default: fprintf(stderr,"Usage: %s [Nwords] File\n", argv[0]); exit(EXIT_FAILURE); } //////////////////////////////////////////////////////////////////////// // BUILD STOPWORD DICTIONARY stopwords = newDict(); in = fopen(STOPWORDS, "r"); if (in == NULL) { fprintf(stderr, "Can't open stopwords\n"); exit(EXIT_FAILURE); } while(fgets(line, MAXLINE, in) != NULL) { line[strcspn(line, "\n")] = '\0'; DictInsert(stopwords, line); } //////////////////////////////////////////////////////////////////////// // SCAN FILE TO START OF TEXT in = fopen(fileName, "r"); if (in == NULL) { fprintf(stderr, "Can't open %s\n",fileName); exit(EXIT_FAILURE); } // Iterate through everyline untill STARTING line is found while (fgets(line, MAXLINE, in) != NULL) if (strstr(line, STARTING) != NULL) break; // Check where iteration stops // If the next line is NULL then nothing was found / empty text // If the next line exists then it is the first line if (fgets(line, MAXLINE, in) == NULL) { fprintf(stderr, "Not a Project Gutenberg book\n"); exit(EXIT_FAILURE); } //////////////////////////////////////////////////////////////////////// // SCAN FILE READING WORDS AND ACCUMULATING COUNTS // note: line now contains the first line memset(word, 0, strlen(word)); int i = 0, j = 0; wfreqs = newDict(); // processing the first line while (i < strlen(line)) { if (isWordChar(line[i]) == 1) { word[j] = tolower(line[i]); j++; } else { word[j] = '\0'; j= 0; if ((strlen(word) > 1) & (DictFind(stopwords, word) == NULL)) { int ans = stem(word, 0, strlen(word)-1); word[ans + 1] = '\0'; DictInsert(wfreqs, word); } memset(word, 0, strlen(word)); } i++; } // processing to the ENDING line while (fgets(line, MAXLINE, in) != NULL) { if (strstr(line, ENDING) != NULL) break; i = 0; memset(word, 0, strlen(word)); while (i < strlen(line)) { if (isWordChar(line[i]) == 1) { word[j] = tolower(line[i]); j++; } else { word[j] = '\0'; j= 0; if ((strlen(word) > 1) & (DictFind(stopwords, word) == NULL)) { int ans = stem(word, 0, strlen(word)-1); word[ans + 1] = '\0'; DictInsert(wfreqs, word); } memset(word, 0, strlen(word)); } i++; } } //////////////////////////////////////////////////////////////////////// // COMPUTE AND DISPLAY THE TOP N WORDS results = (WFreq *) malloc(nWords*sizeof(WFreq)); findTopN(wfreqs, results, nWords); // displaying result in proper format for (int count = 0; count < nWords; count++) printf("%7d %s\n", results[count].freq, results[count].word); //////////////////////////////////////////////////////////////////////// return EXIT_SUCCESS; }
C
#include "unity.h" #include "angleFiring.h" void setUp(void){ } void tearDown(void){} /* * Given a percentage, convert it to firing times(negativeHalf and positiveHalf). */ void test_computeValueToPutIntoDmaBufferFromTicks_2(void) { int i,y; int negativeHalf = 75; int positiveHalf = 30; int busyFlag = 0; computeValueToPutIntoDmaBufferFromTicks(&negativeHalf,&positiveHalf,&busyFlag); computeValueToPutIntoDmaBufferFromTicks(&negativeHalf,&positiveHalf,&busyFlag); computeValueToPutIntoDmaBufferFromTicks(&negativeHalf,&positiveHalf,&busyFlag); computeValueToPutIntoDmaBufferFromTicks(&negativeHalf,&positiveHalf,&busyFlag); negativeHalf = 80; positiveHalf = 20; computeValueToPutIntoDmaBufferFromTicks(&negativeHalf,&positiveHalf,&busyFlag); for(i=0;i<20;i++){ TEST_ASSERT_EQUAL_INT(75, DMA_Buffer1[i]); TEST_ASSERT_EQUAL_INT(77, DMA_Buffer1[++i]); TEST_ASSERT_EQUAL_INT(30, DMA_Buffer1[++i]); TEST_ASSERT_EQUAL_INT(32, DMA_Buffer1[++i]); } computeValueToPutIntoDmaBufferFromTicks(&negativeHalf,&positiveHalf,&busyFlag); for(y=0;y<DMA_BUFFER_MAX_SIZE;y++){ printf("DMA_Buffer1[%u] = %i\n",y,DMA_Buffer1[y]); } printf("\n\n",y,DMA_Buffer1[y]); for(y=0;y<3;y++){ printf("DMA_Buffer1[%u] = %i\n",y,DMA_Buffer1[y]); } for(i=0;i<4;i++){ TEST_ASSERT_EQUAL_INT(80, DMA_Buffer1[i]); TEST_ASSERT_EQUAL_INT(82, DMA_Buffer1[++i]); TEST_ASSERT_EQUAL_INT(20, DMA_Buffer1[++i]); TEST_ASSERT_EQUAL_INT(22, DMA_Buffer1[++i]); } } // ///* // * If the firing Angle is at the middle, the pulseWidth is default( user Defined as 2) // * // * Buffer // * ________________________________________ // * | 75 | 77 | 30 | 32 | 75 | 77 | 30 | 32 | // * |___ |___ |____|____|____|____|____|____| // */ //void test_dataCopyIntoBuffer_with_default_PulseWidth(void) //{ // int negativeHalf = 75; // int positiveHalf = 30; // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // TEST_ASSERT_EQUAL_INT(75, DMA_Buffer1[0]); // TEST_ASSERT_EQUAL_INT(77, DMA_Buffer1[1]); // TEST_ASSERT_EQUAL_INT(30, DMA_Buffer1[2]); // TEST_ASSERT_EQUAL_INT(32, DMA_Buffer1[3]); // TEST_ASSERT_EQUAL_INT(75, DMA_Buffer1[4]); // TEST_ASSERT_EQUAL_INT(77, DMA_Buffer1[5]); // TEST_ASSERT_EQUAL_INT(30, DMA_Buffer1[6]); // TEST_ASSERT_EQUAL_INT(32, DMA_Buffer1[7]); //} // ///* // * If the firing Angle is less than the minimum limit(negativeHalf = 55, positiveHalf = 5), // * the firing angle will change the value to (negativeHalf = 50-55, positiveHalf = 0-5) // * Buffer // * ___________________________________ // * | 50 | 55 | 0 | 5 | 50 | 55 | 0 | 5 | // * |___ |___ |___|___|____|___|___|____| // */ //void test_dataCopyIntoBuffer_with_minLimit_FiringAngle(void) //{ // int negativeHalf = 52; // int positiveHalf = 2; // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // TEST_ASSERT_EQUAL_INT(50, DMA_Buffer1[0]); // TEST_ASSERT_EQUAL_INT(55, DMA_Buffer1[1]); // TEST_ASSERT_EQUAL_INT(0, DMA_Buffer1[2]); // TEST_ASSERT_EQUAL_INT(5, DMA_Buffer1[3]); // TEST_ASSERT_EQUAL_INT(50, DMA_Buffer1[4]); // TEST_ASSERT_EQUAL_INT(55, DMA_Buffer1[5]); // TEST_ASSERT_EQUAL_INT(0, DMA_Buffer1[6]); // TEST_ASSERT_EQUAL_INT(5, DMA_Buffer1[7]); //} // ///* // * If the firing Angle is more than the maximum limit(negativeHalf = 92, positiveHalf = 42), // * the firing angle will change the value to (negativeHalf = 92-97, positiveHalf = 42-47) // * Buffer // * ________________________________________ // * | 92 | 97 | 42 | 47 | 92 | 97 | 42 | 47 | // * |___ |___ |____|____|____|____|____|____| // */ //void test_dataCopyIntoBuffer_with_maxLimit_FiringAngle(void) //{ // int negativeHalf = 93; // int positiveHalf = 43; // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // TEST_ASSERT_EQUAL_INT(92, DMA_Buffer1[0]); // TEST_ASSERT_EQUAL_INT(97, DMA_Buffer1[1]); // TEST_ASSERT_EQUAL_INT(42, DMA_Buffer1[2]); // TEST_ASSERT_EQUAL_INT(47, DMA_Buffer1[3]); // TEST_ASSERT_EQUAL_INT(92, DMA_Buffer1[4]); // TEST_ASSERT_EQUAL_INT(97, DMA_Buffer1[5]); // TEST_ASSERT_EQUAL_INT(42, DMA_Buffer1[6]); // TEST_ASSERT_EQUAL_INT(47, DMA_Buffer1[7]); //} // ///* // * When the pulse is smaller than the minimum value(positiveHalf = 5,negativeHalf = 55), // * the pulse width is 5. // */ //void test_function_getPulseWidth_MinLimit_expected_equal_5(void){ // int negativeHalf = 50; // int positiveHalf = 0; // int pulseWidth; // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // pulseWidth = getPulseWidth(); // TEST_ASSERT_EQUAL_INT(5,pulseWidth); // pulseWidth = getPulseWidth(); // TEST_ASSERT_EQUAL_INT(5,pulseWidth); //} // //void test_function_getPulseWidth_MinLimit2_expected_equal_5(void){ // int negativeHalf = 55; // int positiveHalf = 5; // int pulseWidth; // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // pulseWidth = getPulseWidth(); // TEST_ASSERT_EQUAL_INT(5,pulseWidth); // pulseWidth = getPulseWidth(); // TEST_ASSERT_EQUAL_INT(5,pulseWidth); //} // ///* // * When the pulse is greater than the maximum value(positiveHalf = 92,negativeHalf = 42), // * the pulse width is 5 // */ //void test_function_getPulseWidth_MaxLimit_expected_equal_5(void){ // int negativeHalf = 92; // int positiveHalf = 42; // int pulseWidth; // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // pulseWidth = getPulseWidth(); // TEST_ASSERT_EQUAL_INT(5,pulseWidth); // pulseWidth = getPulseWidth(); // TEST_ASSERT_EQUAL_INT(5,pulseWidth); //} // //void test_function_getPulseWidth_MaxLimit2_expected_equal_5(void){ // int negativeHalf = 97; // int positiveHalf = 47; // int pulseWidth; // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // pulseWidth = getPulseWidth(); // TEST_ASSERT_EQUAL_INT(5,pulseWidth); // pulseWidth = getPulseWidth(); // TEST_ASSERT_EQUAL_INT(5,pulseWidth); //} // ///* // * When the pulse is greater than the maximum value, and smaller than the minimum value // * the pulse Width is at the default = 2. // */ //void test_function_getPulseWidth_defaultPulseWidth_expected_equal_2(void){ // int negativeHalf = 56; // int positiveHalf = 6; // int pulseWidth; // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // pulseWidth = getPulseWidth(); // TEST_ASSERT_EQUAL_INT(2,pulseWidth); // pulseWidth = getPulseWidth(); // TEST_ASSERT_EQUAL_INT(2,pulseWidth); //} // //void test_function_getPulseWidth_defaultPulseWidth2_expected_equal_2(void){ // int negativeHalf = 91; // int positiveHalf = 41; // int pulseWidth; // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // pulseWidth = getPulseWidth(); // TEST_ASSERT_EQUAL_INT(2,pulseWidth); // pulseWidth = getPulseWidth(); // TEST_ASSERT_EQUAL_INT(2,pulseWidth); //} // ///* // * Given an initial value, run the test by increment the value(0-100). // * So every possible value is being tested (100 tests). // * If the pulse width is larger than 6, then it will fails. // */ //void test_functionality_pulseWidth(void){ // static int negativeHalf = 50; // static int positiveHalf = 0; // int pulseWidth; // static int y=6; // for(int x=1;x<51;x++){ // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // getFiringTimesAndCopyIntoBuffer(&negativeHalf,&positiveHalf); // if(x<6){ // negativeHalf += x; // positiveHalf += x; // } // else{ // if(x==7) // y=1; // // if(x>42){ // negativeHalf = negativeHalf-42+x; // positiveHalf = positiveHalf-42+x; // } // else{ // negativeHalf += y; // positiveHalf += y; // } // } // pulseWidth = getPulseWidth(); // printf("The firing times is %i and the pulse width is %i\n",negativeHalf-1,pulseWidth); // TEST_ASSERT_LESS_THAN_INT(6, pulseWidth); // pulseWidth = getPulseWidth(); // printf("The firing times is %i and the pulse width is %i\n\n",positiveHalf-1,pulseWidth); // TEST_ASSERT_LESS_THAN_INT(6, pulseWidth); // } //}
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include "utils.h" #define MSG_S 60 #define MSG_L 1024 #define PORT_NUM 3655 void main(void) { int server_sockfd, client_sockfd; int server_len, client_len; struct sockaddr_in server_address; struct sockaddr_in client_address; char Msg1[MSG_S] = "You Chose Number [1] -> Check LED!\n"; char Msg2[MSG_L]; char Msg3[MSG_S] = "You Chose Number [3] -> http://192.168.219.104/log.html\n"; // local ip address char Msg4[MSG_S] = "You Chose Number [4] -> End Connection\n"; char Msgd[MSG_S] = "Err - Wrong Number -> Try Again\n"; int strlen; int t, h, d; unlink("server_socket"); server_sockfd = socket(AF_INET, SOCK_STREAM, 0); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = htons(PORT_NUM); server_len = sizeof(server_address); bind(server_sockfd, (struct sockaddr *)&server_address, server_len); listen(server_sockfd, 5); while(1) { char num; printf("Server On!\n"); client_len = sizeof(client_address); client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len); recv(client_sockfd, &num, 1, 0); switch(num) { case '1': use_thread(); send(client_sockfd, Msg1, MSG_S, 0); t = temp_out(); h = humid_out(); d = dust_data; printf("LED LIGHTING\n"); t_led(t); h_led(h); d_led(d); break; case '2': use_thread(); d = dust_data; t = temp_out(); h = humid_out(); sprintf(Msg2, "You Chose Number [2] -> Temperature:%d℃ , Humidity:%d%c, Air Pollution:%d㎍/㎥\n", t, h, '%', d); send(client_sockfd, Msg2, MSG_L, 0); break; case '3': use_thread(); send(client_sockfd, Msg3, MSG_S, 0); t = temp_out(); h = humid_out(); d = dust_data; upload_html(t, h, d); break; case '4': send(client_sockfd, Msg4, MSG_S, 0); printf("Server OFF\n"); exit(0); default: send(client_sockfd, Msgd, MSG_S, 0); } close(client_sockfd); } }
C
/****************************************/ /* Information from password structure */ /* */ /* Author: Tilak S Naik */ /****************************************/ #include <stdio.h> #include <pwd.h> #define B_SIZE 4096 int main() { struct passwd *p; char name[B_SIZE]; printf("Enter the username: "); scanf("%s", name); p = getpwnam(name); if (p == NULL) { printf("Not found\n"); return -1; } printf("Username: %s\nPassword: %s\nUID: %d\nGID: %d\nUser Information: %s\nHome dir: %s\nShell: %s\n", p->pw_name, p->pw_passwd, p->pw_uid, p->pw_gid, p->pw_gecos, p->pw_dir, p->pw_shell); // listed in man 3 getpwnam return 0; }
C
#include "msp430.h" #include "lcd.h" #define SEG_A 0x01 #define SEG_B 0x02 // -A- #define SEG_C 0x04 // F B #define SEG_D 0x08 // -G- #define SEG_E 0x40 // E C #define SEG_F 0x10 // -D- #define SEG_G 0x20 #define SEG_H 0x80 static const char lcd_digits[] = { // shape of digits SEG_A + SEG_B + SEG_C + SEG_D + SEG_E + SEG_F, // "0" SEG_B + SEG_C, // "1" SEG_A + SEG_B + SEG_D + SEG_E + SEG_G, // "2" SEG_A + SEG_B + SEG_C + SEG_D + SEG_G, // "3" SEG_B + SEG_C + SEG_F + SEG_G, // "4" SEG_A + SEG_C + SEG_D + SEG_F + SEG_G, // "5" SEG_A + SEG_C + SEG_D + SEG_E + SEG_F + SEG_G, // "6" SEG_A + SEG_B + SEG_C, // "7" SEG_A + SEG_B + SEG_C + SEG_D + SEG_E + SEG_F + SEG_G, // "8" SEG_A + SEG_B + SEG_C + SEG_D + SEG_F + SEG_G, // "9" }; // LCD Constants #define LCD_NUM_DIGITS 7 // Number of digits on screen #define LCD_MEM_OFFSET 1 // First digit is not LCDMEM[0] void lcd_display_digit(int pos, int digit) { if(pos>LCD_NUM_DIGITS) return; // the first two bytes of lcd controller memory are not mapped to // any item on the lcd screen istelf LCDMEM[LCD_MEM_OFFSET+pos]=lcd_digits[digit]; } void lcd_display_number(unsigned int number) { lcd_clear(); if(number == 0 ) lcd_display_digit(1, 0); int i=1; while(number) { lcd_display_digit(i,number%10); number /= 10; i++; } } /* Initialize the LCD_A controller claims P5.2-P5.4, P8, P9, and P10.0-P10.5 assumes ACLK to be default 32khz (LFXT1) */ void lcd_init() { // our LCD screen is a SBLCDA4 => 4-mux operation (SLAU213 p4) // 4-mux operation needs all 4 common lines (COM0-COM3). COM0 has // a dedicated pin (pin 52, cf SLAS508H p3), but let's claim the // other three. P5DIR |= (BIT4 | BIT3 | BIT2); // pins are output direction P5SEL |= (BIT4 | BIT3 | BIT2); // select 'peripheral' function (VS GPIO) // Configure LCD controller LCDACTL = 0b01011101; // bit 0 turns on the LCD_A module // bit 1 unused // bit 2 enables LCD segments // bits 3-4 set LCD mux rate: 4-mux // bits 5-7 set frequency // Configure port pins // // mappings are detailed on SLAU213 p15: our screen has 22 // segments, wired to MCU pins S4 to S25 (shared with GPIO P8, P9, // and P10.0 to P10.5) LCDAPCTL0 = 0b01111110; // bit 0: MCU S0-S3 => not connected to the screen // bit 1: MCU S4-S7 => screen pins S0-S3 (P$14-P$11) // bit 2: MCU S8-S11 => screen pins S4-S7 (P$10-P$7) // bit 3: MCU S12-S15 => screen pins S8-S11 (P$6 -P$3) // bit 4: MCU S16-S19 => screen pins S12-S15 (P$2, P$1, P$19, P$20) // bit 5: MCU S20-S23 => screen pins S16-S19 (P$21-P$24) // bit 6: MCU S24-S25 => screen pins S20-21 (P$25, P$26) // bit 7: MCU S28-S31 => not connected to the screen LCDAPCTL1 = 0 ; // MCU S32-S39 => not connected to the screen // Note: as we do not intend to support battery-powered operation, // we don't need to mess with charge pumps and such. // clear all LCD memory (cf SLAU056J p. 26-4) int j; for( j=0 ; j<20 ; j++) { LCDMEM[j] = 0x00; } } void lcd_clear() { int j; // clear all the video memory for( j=0 ; j<20 ; j++) { LCDMEM[j] = 0; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf_p.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mcassar <mcassar@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/05/04 00:16:12 by mcassar #+# #+# */ /* Updated: 2017/05/17 22:15:38 by mcassar ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/libftprintf.h" /* ** ft_malloc_size returns the righ malloc size used in ft_printf_hexa. ** Var. int i = Return value. */ static int ft_malloc_size(unsigned long int nb) { int i; i = 0; while (nb > 0) { nb = nb / 16; i++; } return (i); } /* ** ft_printf_hexa converts a given 10 based unsigned long int into its ** hexadecimal value. ** Var. int index = Pointer going through char *hex. ** Var. char *hex = String containing hexadecimal values. ** Var. char *result = String containing the result of the ** hexadecimal convertion. ** Var. int i = Pointer going through char *result. */ static int ft_printf_hexa(unsigned long int nb) { int index; char *hex; char *result; int i; hex = "0123456789abcdef"; i = 0; result = (char*)malloc(sizeof(char*) * ft_malloc_size(nb) + 1); while (nb > 0) { index = nb % 16; result[i] = hex[index]; i++; nb = nb / 16; } while (i >= 0) { ft_putchar(result[i]); i--; } free(result); return (0); } /* ** ft_printf_p treat the p flag, used to print pointer addresses. ** It prints in hexadecimal the void *pointer argument. */ void ft_printf_p(void) { ft_putstr("0x", 0); ft_printf_hexa((unsigned long int)t_v.p); return ; }
C
#define FUSE_USE_VERSION 30 #include <fuse.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <time.h> #include <string.h> #include <stdlib.h> static int sffs_getattr(const char *path, struct stat *st) { printf("getattribute called \n"); printf("Requested %s \n", path); st->st_uid = getuid(); st->st_gid = getgid(); st->st_atime = time(NULL); st->st_mtime = time(NULL); if(strcmp(path, "/") == 0) { st->st_mode = S_IFDIR | 0755; st->st_nlink = 2; } else { st->st_mode = S_IFREG | 0644; st->st_nlink = 1; st->st_size = 1024; } return 0; } static int sffs_readdir(const char *path, void *buffer, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { printf("Getting files of %s", path); filler( buffer, ".", NULL, 0 ); filler( buffer, "..", NULL, 0 ); if ( strcmp( path, "/" ) == 0 ) { filler( buffer, "First_File", NULL, 0 ); filler( buffer, "Second_File", NULL, 0 ); } return 0; } static int sffs_read(const char *path, char *buffer, size_t size, off_t offset, struct fuse_file_info *fi) { printf( "--> Trying to read %s, %li, %zu\n", path, offset, size); char file54Text[] = "Hello World From First File!"; char file349Text[] = "Hello World From Second File!"; char *selectedText = NULL; if ( strcmp( path, "/First_File" ) == 0 ) selectedText = file54Text; else if ( strcmp( path, "/Second_File" ) == 0 ) selectedText = file349Text; else return -1; memcpy( buffer, selectedText + offset, size ); return (int) (strlen(selectedText ) - offset); } static struct fuse_operations operations = { .getattr = sffs_getattr, .readdir = sffs_readdir, .read = sffs_read, }; int main(int argc, char *argv[]) { return fuse_main(argc, argv, &operations, NULL); }
C
/** * \file privtab.h * * \brief Defines a privilege table entry for general use */ #ifndef __PRIVTAB_H #define __PRIVTAB_H #include "copyrite.h" #include "mushtype.h" typedef struct priv_info PRIV; /** Privileges. * This structure represents a privilege and its associated data. * Privileges tables are used to provide a unified way to parse * a string of restrictions into a bitmask. */ struct priv_info { const char *name; /**< Name of the privilege */ char letter; /**< One-letter abbreviation */ privbits bits_to_set; /**< Bitflags required to set this privilege */ privbits bits_to_show; /**< Bitflags required to see this privilege */ }; #define PrivName(x) ((x)->name) /**< Full name of priv */ #define PrivChar(x) ((x)->letter) /**< One-char abbreviation of priv */ #define PrivSetBits(x) \ ((x)->bits_to_set) /**< Bitflags required to set priv \ */ #define PrivShowBits(x) \ ((x)->bits_to_show) /**< Bitflags required to see priv */ privbits string_to_privs(const PRIV *table, const char *str, privbits origprivs); privbits list_to_privs(const PRIV *table, const char *str, privbits origprivs); int string_to_privsets(const PRIV *table, const char *str, privbits *setprivs, privbits *clrprivs); privbits letter_to_privs(const PRIV *table, const char *str, privbits origprivs); extern const char *privs_to_string(const PRIV *table, privbits privs); extern const char *privs_to_letters(const PRIV *table, privbits privs); #endif /* __PRIVTAB_H */
C
#include<stdio.h> #include<unistd.h> #include<fcntl.h> int main(){ int fd = open("temp.txt",O_RDONLY); int fd1 = creat("temp_copy7.txt",0777); char buff[50]; int size = read(fd,buff,50); //read function will return how many byte has been written //printf("%s",buff); write(fd1,buff,size); close(fd); close(fd1); return 0; }
C
//Lista Encadeada Simples #include <stdio.h> #include <stdlib.h> typedef int TipoItem; typedef struct no{ TipoItem info; struct no * prox; }Lista; //Verifica se a cabeça da lista é nula. int VerificaLista(Lista* novo){ return(novo == NULL); } //Insere um elemento na cabeça. Lista* insere(Lista* l,TipoItem info){ Lista* aux = (Lista*) malloc(sizeof(Lista)); aux->info = info; aux->prox = l; //encadeia com a cabeca da lista return aux; // retorna a nova cabeca } //Remove um elemento da lista, seja na cabeça ou no corpo. Lista * retira1(Lista* l,TipoItem info){ Lista * ant = l; // elemento anterior Lista * p = l; // usado para encontrar o elemento // a ser retirado while(p!= NULL && p->info != info) { // localiza o elemento ant = p; p = p->prox; } if(p != NULL) { // elemento encontrado if(p == l) // remoc~ao na cabeca l = l->prox; // atualiza a cabeca else // remoc~ao no meio ant->prox = p->prox; free(p); }else printf("Elemento n~ao encontrado\n"); // libera o no do elemento removido return l; } //Imprime a lista void ShowLista(Lista *l){ Lista *t; t=l; while(t != NULL){ printf("%d\n",t->info); t = t->prox; } } //Recebe uma lista e um valor, conta e retorna quatas vezes aquele elemento apareceu. int ContaOcorrencias(Lista *l, TipoItem n){ Lista *aux = l; int cont=0; while(aux != NULL){ if(aux->info == n) cont ++; aux = aux->prox; } return cont; } //Remove todas as ocorrencias de um valor da lista. Lista * retiraall(Lista* l,TipoItem info){ Lista * ant = l; // elemento anterior Lista * p = l; // usado para encontrar o elemento // a ser retirado int cont=0; int i; cont = ContaOcorrencias(p,info); if(cont != 0) { for(i=0;i<cont;i++){ p = l; while(p->info!= info) { // conta quantas vezes o elemento aparece ant = p; p = p->prox; } if(p == l) // remoc~ao na cabeca l = l->prox; // atualiza a cabeca else // remoc~ao no meio ant->prox = p->prox; free(p); // libera o no do elemento removido } }else printf("Elemento não encontrado\n"); return l; } //Se a lista estiver vazia ele mostra que esta vazia, se nao ele printa a lista. void vazia(Lista *novo){ if(VerificaLista(novo)) printf("Lista vazia\n"); else ShowLista(novo); } Lista* InvertLista(Lista *novo){ Lista *aux = novo; Lista *ant = NULL; //Lista *temp = NULL; //ant = temp; while(aux != NULL){ novo = novo->prox; aux->prox = ant; ant = aux; aux = novo; } return ant; } //Concatena a l2 no final de l1, e retorna a cabeça de l1. Lista* ConcatenaLista(Lista *l1,Lista *l2){ Lista *p = l1->prox; Lista *ant = l1; while(p!=NULL){ ant = p; p = p->prox; } ant->prox = l2; return l1; } //Intercala l1 com l2, e retorna a cabeça de l1. Lista* MergeLista(Lista *l1,Lista *l2){ Lista *ant; Lista *aux1 = l1; Lista *aux2 = l2; while(aux2 != NULL && aux1 != NULL){ //Intercala entre l1 e l2 ate que um dos dois chege em NULL ant = aux1; aux1 = aux1->prox; ant->prox = aux2; ant = aux2; aux2 = aux2->prox; ant->prox = aux1; } //O ultimo elemento da lista é sempre o NULL de l1. if(aux2 != NULL){ //caso l2 for maior que l1 ele concatena o resto de l2 na lista. ant->prox = aux2; } return l1; } //Função que retira uma posição em especifico da lsita. Lista* RetiraElemento(Lista *l,Lista *ant){//recebe a posição a ser tirada, e a posição anterior. Lista *temp = l; l = l->prox; ant->prox = l; free(temp); return l; } //Remove elementos repetidos da Lista Lista* EliminaRepetidos(Lista *l){ Lista *aux = l; Lista *fixo = l; Lista *ant; TipoItem info; while(fixo != NULL){ info = fixo->info; aux = fixo->prox; ant = fixo; while(aux != NULL){ if(aux->info == info) aux = RetiraElemento(aux,ant); else{ aux = aux->prox; ant = ant = ant->prox; } } fixo = fixo->prox; } return l; } int main(){ Lista *novo1; Lista *novo2; TipoItem n=1; novo1=NULL; novo2=NULL; //vazia(novo); printf("Qual valor deseja colocar na lista ?\n"); scanf("%d",&n); while(n!=-1){ novo1 = insere(novo1,n); scanf("%d",&n); } // printf("Qual valor deseja colocar na lista ?\nCaso deseje parar, so digitar (-1)\n"); // scanf("%d",&n); // while(n!=-1){ // novo2 = insere(novo2,n); // scanf("%d",&n); // } system("cls"); //ShowLista(MergeLista(novo1,novo2)); //system("cls"); // vazia(novo); // printf("\n\n"); printf("Qual valor deseja contar?\n"); scanf("%d",&n); system("cls"); ShowLista(novo1); printf("\n\n%d\n\n",ContaOcorrencias(novo1,n)); ShowLista(novo1); //novo1 = EliminaRepetidos(novo1); // novo = InvertLista(novo); // vazia(novo); return 0; } //Lista duplamente encadeada /* #include <stdio.h> #include <stdlib.h> typedef int TipoItem; typedef struct no{ TipoItem info; struct no * prox; struct no * ant; }Lista; //Começa uma lista cujos dois lados apontam para nulo. Lista* NovaLista(Lista* l,TipoItem info){ l->info = info; l->ant = NULL; l->prox = NULL; return l; } //Insere um elemento na cabeça. Lista* insere(Lista* l,TipoItem info){ Lista* aux = (Lista*) malloc(sizeof(Lista)); l->ant = aux; aux->info = info; aux->prox = l; //encadeia com a cabeca da lista return aux;// retorna a nova cabeca } //Remove um elemento da lista, seja na cabeça ou no corpo. Lista * retira(Lista* l,TipoItem info){ Lista * ant = l; // elemento anterior Lista * p = l; // usado para encontrar o elemento // a ser retirado while(p!= NULL && p->info != info) { // localiza o elemento ant = p; p = p->prox; } if(p != NULL){ // elemento encontrado if(p == l) { // remoc~ao na cabeca l = l->prox;// atualiza a cabeca l->ant = NULL; }else{ // remocao no meio ant->prox = p->prox; p->prox->ant = ant; } free(p); // libera o no do elemento removido }else printf("Elemento n~ao encontrado\n"); return l; } void ShowLista(Lista *l){ Lista *t; t=l; while(t != NULL){ printf("%d\n",t->info); t = t->prox; } } int main(){ Lista *novo; TipoItem n=1; printf("Qual o primeiro valor que deseja inserir?\n"); scanf("%d",&n); novo = (Lista*) malloc(sizeof(Lista)); novo = NovaLista(novo,n); printf("Qual valor deseja colocar na lsita ?\nCaso deseje parar, so digitar (-1)\n"); scanf("%d",&n); while(n!=-1){ novo = insere(novo,n); scanf("%d",&n); } system("cls"); ShowLista(novo); printf("Qual valor deseja apagar?\n"); scanf("%d",&n); system("cls"); ShowLista(retira(novo,n)); return 0; } */
C
#include <SDL/SDL_image.h> #include "segmentation.h" #include "utils.h" #include "rotation.h" SDL_Surface *extract_text(char *source_location, int threshold) { SDL_Surface *image; Uint8 r, g, b; // Get the image image = IMG_Load(source_location); show_image(image, -1); // Show the image when it is loaded put_in_black_and_white(image); show_image(image, -1); // Show the image in black and white extern int must_rotate_image; if (must_rotate_image) { double angle = find_angle(image); image = SDL_RotateImage(image, -angle); show_image(image, -1); // Show the image when it is rotating } if (image == NULL) { printf("Fail with loading image"); return NULL; } // Browse all pixels of the image for (int x = 0; x < image->w; ++x) { for (int y = 0; y < image->h; ++y) { // Take the color of the current pixel SDL_GetRGB(get_pixel(image, x, y), image->format, &r, &g, &b); // If the current pixel is not black -> convert white if (!(r <= threshold && g <= threshold && b <= threshold)) { put_pixel(image, x, y, SDL_MapRGBA(image->format, 255, 255, 255, 255)); } } } // Corrects the finishes of pixels extern int must_remove_bg; if (must_remove_bg) image = correct_image(image, 20); return get_all_text(image, threshold); } SDL_Surface *get_all_text(SDL_Surface *image, int Seuil) { // default values int left = image->w; int top = image->h; int bottom = 0; int right = 0; //Find the borders of the text in the image Uint8 r, g, b; // Browse all pixels of the image for (int y = 0; y < image->h; ++y) { for (int x = 0; x < image->w; ++x) { // get the current pixel color SDL_GetRGB(get_pixel(image, x, y), image->format, &r, &g, &b); // take the border of the text if (r <= Seuil && x < left) left = x; if (r <= Seuil && x > right) right = x; if (r <= Seuil && y > bottom) bottom = y; if (r <= Seuil && y < top) top = y; } } //Create a new image with the good scale SDL_Surface *newImage = cut_image(image, left, top, right - left + 1, bottom - top + 1); return newImage; }
C
/* * adc.c * * Created on: Jul 20, 2013 * Author: Nate */ #include "adc.h" int16_t get_temp_raw() { unsigned int temp =0; unsigned int IntDegC =0; int i=0; ADC10CTL0 = 0; ADC10CTL1 = INCH_10 + ADC10DIV_3; // Temp Sensor ADC10CLK/48 ADC10CTL0 = SREF_1 + ADC10SHT_3 + REFON + ADC10ON; while (ADC10CTL1 & BUSY); for(i=0;i<32;i++) { ADC10CTL0 |= ENC + ADC10SC; // Sampling and conversion start while (ADC10CTL1 & BUSY); temp = ADC10MEM; //IntDegC += ((temp - 673) * 423)>>10; IntDegC += (((27069L * temp) - 18169625L) >> 16); } IntDegC>>=5; return IntDegC; } uint16_t get_adc_val() { uint16_t tval =0; uint16_t adc_current=0; uint8_t i=0; ADC10CTL0 = 0; while (ADC10CTL1 & BUSY); ADC10CTL0 = ADC10ON + SREF_0 + ADC10SHT_3; // ADC10ON, interrupt enabled ADC10CTL1 = INCH_3+ ADC10DIV_2 +SHS_0; // input A1 ADC10AE0 |= BIT3; // PA.1 ADC option select while (ADC10CTL1 & BUSY); for(i=0;i<8;i++) { ADC10CTL0 |= ENC + ADC10SC; // Sampling and conversion start while (ADC10CTL1 & BUSY); adc_current = ADC10MEM; //adc_val += (adc_current*3) + (adc_current>>1) + (adc_current>>6) ; tval += adc_current; // 3600/1024 } tval*=3.2227; // convert to mv tval>>=3; // offset average _delay_cycles(1); return tval; }
C
// C program to illustrate pipe system call in C #include <stdio.h> #include <unistd.h> #include <stdlib.h> #define MSGSIZE 16 void msg_pipe() { char* msg1 = "Abhay"; char* msg2 = "Good Morning"; char* msg3 = "hello"; char inbuf[MSGSIZE]; int msg[2], index; if (pipe(msg) < 0) exit(1); /* continued */ /* write pipe */ write(msg[1], msg1, MSGSIZE); write(msg[1], msg2, MSGSIZE); write(msg[1], msg3, MSGSIZE); for (index = 0; index < 3; index++) { /* read pipe */ read(msg[0], inbuf, MSGSIZE); printf("%s\n", inbuf); } }
C
#include<stdio.h> #include<conio.h> #include<stdlib.h> #include<ctype.h> struct node{ struct node *prev; int data; struct node *next; }; struct node *head = NULL; struct node *tail = NULL; struct node *ptr = NULL; struct node *searchPtr; struct node *newNode; struct node *prePtr; void createNode(){ newNode = (struct node*)malloc(sizeof(struct node)); printf("\nEnter the element:\t"); scanf("%d",&newNode->data); newNode->prev = NULL; newNode->next = NULL; } void insert_begin(){ createNode(); if(head == NULL){ head = newNode; tail = newNode; } else{ newNode->next = head; head->prev = newNode; head = newNode; } printf("\n Inserted Successfully"); } void insert_end(){ if(head == NULL){ insert_begin(); } else{ createNode(); newNode->prev = tail; tail->next = newNode; tail = newNode; printf("\n Inserted Successfully"); } } struct node* searchElement(int data){ if(head == NULL){ return NULL; } else{ ptr = head; while(ptr != NULL){ if(ptr->data == data){ return ptr; } ptr = ptr->next; } return NULL; } } void insert(){ if(head == searchPtr){ insert_begin(); } else{ createNode(); newNode->prev = searchPtr->prev; searchPtr->prev->next = newNode; newNode->next = searchPtr; searchPtr->prev = newNode; printf("\n Inserted Successfully"); } } void delete_begin(){ if(head == NULL){ printf("\nThe linked list is empty"); } else if(head->next == NULL){ head = NULL; tail = NULL; printf("\n Deleted Successfully"); } else{ head = head->next; head->prev = NULL; printf("\n Deleted Successfully"); } } void delete_end(){ if(head == NULL){ printf("\n The linked list is empty"); } else if(head->next == NULL){ delete_begin(); } else{ tail = tail->prev; tail->next = NULL; printf("\n Deleted Successfully"); } } void delete(){ if(searchPtr == head){ delete_begin(); } else if(searchPtr == tail){ delete_end(); } else{ searchPtr->prev->next = searchPtr->next; searchPtr->next->prev = searchPtr->prev; searchPtr->next = NULL; searchPtr->prev = NULL; } } void display(){ if(head == NULL){ printf("\nThe linked list is empty"); } else{ printf("\nThe elemnets of the linked list are: "); ptr = head; while(ptr != NULL){ printf("%d ",ptr->data); ptr = ptr->next; } } } void main(){ while(1){ int ch; printf("\n 1. Insert at the beginning"); printf("\n 2. Insert at the end"); printf("\n 3. Insert before a given element"); printf("\n 4. Delete from the beginning"); printf("\n 5. Delete from the end"); printf("\n 6. Delete the given element"); printf("\n 7. Display"); printf("\n 8. Exit!"); printf("\n Enter your choice:\t"); scanf("%d",&ch); int data; switch(ch){ case 1: insert_begin(); break; case 2: insert_end(); break; case 3: printf("\n Enter the element before which you wanna insert:\t"); scanf("%d",&data); searchPtr = searchElement(data); if(searchPtr == NULL){ printf("\nElement not found"); } else{ insert(); } break; case 4: delete_begin(); break; case 5: delete_end(); break; case 6: printf("Enter the element you wanna delete"); scanf("%d",&data); searchPtr = searchElement(data); if(searchPtr == NULL){ printf("Element not found"); } else{ delete(); } break; case 7: display(); break; case 8: exit(0); default: printf("Invalid choice"); } } }
C
#include <stdio.h> int main() { int n=3; printf("n=%d......n+1=%d\n",n,n++); return 0; }
C
#include <msp430g2553.h> #include "game.h" #include "LCD_Driver.h" unsigned char initPlayer() { return 0x80; } void printPlayer(unsigned char PLAYER) { writeCommandByte(PLAYER); writeDataByte('*'); } void clearPlayer(unsigned char PLAYER) { writeCommandByte(PLAYER); writeDataByte(' '); } unsigned char movePlayer(unsigned char PLAYER, unsigned char direction) { switch (direction) { // // update player position based on direction of movement // case UP: PLAYER &= ~BIT6; break; case DOWN: PLAYER |= BIT6; break; case RIGHT: PLAYER++; if (PLAYER > 0x87 & PLAYER < 0xC0) { PLAYER = 0xC0; } break; case LEFT: PLAYER--; if (PLAYER < 0x80) { PLAYER = 0x80; } if (PLAYER < 0xC0 & PLAYER > 0x87) { PLAYER = 0x87; } } return PLAYER; }
C
static int hash_table_enlarge(HashTable *hash_table) { HashTableEntry **old_table; unsigned int old_table_size; unsigned int old_prime_index; HashTableEntry *rover; HashTableEntry *next; unsigned int index; unsigned int i; /* 复制一份旧表结构并存储 */ old_table = hash_table->table; old_table_size = hash_table->table_size; old_prime_index = hash_table->prime_index; /* 给一个新的表分配更大的内存 */ ++hash_table->prime_index; if (!hash_table_allocate_table(hash_table)) { /* 为新表分配内存失败 */ hash_table->table = old_table; hash_table->table_size = old_table_size; hash_table->prime_index = old_prime_index; return 0; } /* 把所有结点链接进新生成的表中 */ for (i=0; i < old_table_size; ++i) { rover = old_table[i]; while (rover != NULL) { next = rover->next; /* 在新的表中找到原关键词对应的链表序号 */ index = hash_table->hash_func(rover->key) % hash_table->table_size; /* 把结点接入序号是index的链表 */ rover->next = hash_table->table[index]; hash_table->table[index] = rover; /* 链表中的下一个 */ rover = next; } } /* 释放旧表的占用的内存 */ free(old_table); return 1; }
C
/* ********************* TEXTO SIN ACENTOS *********************/ // Recuerda documentar tus codigos #include <stdio.h> #include <stdlib.h> #include <math.h> int main(){ int i; float max = RAND_MAX*1.0; for (i=1; i<=4; i++){ printf("%f\n", (float)rand()/max); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* check_flags_di.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amace-ty <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/07 14:55:59 by amace-ty #+# #+# */ /* Updated: 2019/10/12 13:08:34 by amace-ty ### ########.fr */ /* */ /* ************************************************************************** */ #include "../inc/ft_printf.h" char *check_flags_integer_plus_space(char *str, t_print *new) { char *new_str; int i; i = -1; if (new->flag_plus) { new_str = ft_strnew((size_t)ft_strlen(str) + 1); new_str[0] = '+'; while (++i < (int)ft_strlen(str)) new_str[i + 1] = str[i]; free(str); return (new_str); } else if (new->flag_space) { new_str = ft_strnew((size_t)ft_strlen(str) + 1); new_str[0] = ' '; while (++i < (int)ft_strlen(str)) new_str[i + 1] = str[i]; free(str); return (new_str); } return (str); } char *check_flags_integer_width(char *str, t_print *new) { char *new_str; int i; i = -1; if (new->flag_minus || new->flag_null) new_str = ft_width_for_minus_and_zero(str, new); else { new_str = ft_strnew((size_t)new->width); ft_memset(new_str, ' ', (size_t)new->width); while ((int)ft_strlen(str) - ++i >= 0) new_str[new->width - i] = str[ft_strlen(str) - i]; } free(str); return (new_str); } char *ft_integer_accuracy(char *str, t_print *new, int flagi) { int i; char *new_str; char *dlc_str; i = -1; dlc_str = check_flags_integer_plus_space(str, new); new_str = ft_strnew((size_t)new->accuracy + flagi); ft_memset(new_str, '0', (size_t)new->accuracy + flagi); if (flagi) { new_str[0] = dlc_str[0]; while (ft_strlen(dlc_str) - ++i > 0) new_str[ft_strlen(new_str) - i] = dlc_str[ft_strlen(dlc_str) - i]; } else { while ((int)ft_strlen(dlc_str) - ++i >= 0) new_str[new->accuracy - i] = dlc_str[ft_strlen(dlc_str) - i]; } free(dlc_str); return (new_str); } static int ft_integer_print_2(char *str, t_print *new, int flagi) { char *dlc_str; char *new_str; int num; int i; i = 0; if ((!(new->flag_accuracy) || new->accuracy <= (int)ft_strlen(str)) && new->width >= (int)ft_strlen(str)) { dlc_str = check_flags_integer_plus_space(str, new); new_str = check_flags_integer_width(dlc_str, new); ft_putstr(new_str); num = ft_strlen(new_str); } else { FLAG_SPACE; dlc_str = ft_integer_accuracy(str, new, flagi - i); new_str = check_flags_integer_width(dlc_str, new); ft_putstr(new_str); num = ft_strlen(new_str); } free(new_str); return (num); } int ft_integer_print(char *str, t_print *new) { int num; char *new_str; int flagi; flagi = (new->flag_space) + (new->flag_plus) + (new->flag_otr_i); if ((!(new->flag_width) && !(new->flag_accuracy)) || (new->width < (int)ft_strlen(str) && new->accuracy < (int)ft_strlen(str) - flagi)) { new_str = check_flags_integer_plus_space(str, new); ft_putstr(new_str); num = ft_strlen(new_str); } else if (((!(new->flag_width) || new->width < (int)ft_strlen(str)) && new->accuracy > (int)ft_strlen(str) - flagi) || (new->width <= new->accuracy)) { new_str = ft_integer_accuracy(str, new, flagi); ft_putstr(new_str); num = ft_strlen(new_str); } else return (ft_integer_print_2(str, new, flagi)); free(new_str); return (num); }
C
#include <stdio.h> #include <string.h> typedef struct fruit_t { char name[20]; double price; char taste[20]; } Fruit; void fillFruit(Fruit *aFruit, char *name, double price, char *taste) { strcpy(aFruit->name, name); aFruit->price = price; strcpy(aFruit->taste, taste); } void printFruit(Fruit *aFruit) { printf("Fruit name: %s\n", aFruit->name); printf("Price: %lf\n", aFruit->price); printf("Fruit taste: %s\n", aFruit->taste); } void sortArrayByPrice( Fruit theFruits[], int numFruits ) { int i,j; Fruit temp; for (i=0; i<numFruits-1; i++) { for (j=0; j<numFruits-i-1; j++) { if (theFruits[j].price > theFruits[j+1].price) { temp = theFruits[j]; theFruits[j] = theFruits[j+1]; theFruits[j+1] = temp; } } } } int main() { Fruit fruits[4] = {}; Fruit *myFruit = fruits; int sizeOfArray = 0; fillFruit(&fruits[0],"orange", 1.25, "citrus" ); fillFruit(&fruits[1],"banana", 0.75, "yummy"); fillFruit(&fruits[2], "cookie", 0.25, "chocolate"); fruits[3].price = 0.0; for (myFruit = fruits; myFruit->price > 0.0; myFruit++) { printFruit(myFruit); sizeOfArray++; } sortArrayByPrice(fruits, sizeOfArray); for (myFruit = fruits; myFruit->price > 0.0; myFruit++) { printFruit(myFruit); } }
C
#include <stdio.h> #include <stdlib.h> typedef struct treeNode { char key; struct treeNode* left; struct treeNode* right; } treeNode; typedef char element; treeNode* insertNode(treeNode *p, char x) { treeNode *newNode; if (p == NULL) { newNode = (treeNode *)malloc(sizeof(treeNode)); newNode->key = x; newNode->left = NULL; newNode->right = NULL; return newNode; } else if (x < p->key) p->left = insertNode(p->left, x); else if (x > p->key) p->right = insertNode(p->right, x); else { printf("\n 이미 같은 키가 있습니다!\n"); } return p; } void deleteNode(treeNode *root, element key) { treeNode *parent, *p, *succ, *succ_parent; treeNode *child; parent = NULL; p = root; while((p != NULL) && (p->key != key)) { parent = p; if(key < p->key) p = p->left; else { p = p->right; } } if(p == NULL) { printf("\n찾는 키가 이진 트리에 없습니다!\n"); return; } if ((p->left == NULL) && (p->right == NULL)) { if(parent != NULL) { if (parent->left == p) parent->left = NULL; else { parent->right = NULL; } } else root = NULL; } else if((p->left == NULL) || (p->right == NULL)) { if(p->left != NULL) child = p->left; else { child = p->right; } if(parent != NULL) { if(parent->left == p) parent->left = child; else { parent->right = child; } } else { root = child; } } else { succ_parent = p; succ = p->left; while (succ->right != NULL) { succ_parent = succ; succ = succ->right; } if (succ_parent->left == succ) succ_parent->left = succ->left; else { succ_parent->right = succ->left; } p->key = succ->key; } free(succ); printf("a"); } treeNode* searchBST (treeNode *root, char x) { treeNode *p; p = root; while (p != NULL) { if (x<p->key) p = p->left; else if (x == p->key) return p; else { p = p->right; } } printf("\n 찾는 키가 없습니다!"); return p; } void displayInorder (treeNode *root) { if(root) { displayInorder(root->left); printf("%c_", root->key); displayInorder(root->right); } } void menu() { printf("\n*-------------------------------------*"); printf("\nt1 : 트리 출력"); printf("\nt2 : 문자 삽입"); printf("\nt3 : 문자 삭제"); printf("\nt4 : 문자 검색"); printf("\nt5 : 종료"); printf("\n*--------------------------------------*"); printf("\napsbdlqfur >> "); } int main (void) { treeNode* root = NULL; treeNode* foundedNode = NULL; char choice, key; root = insertNode (root, 'G'); insertNode(root, 'I'); insertNode(root, 'H'); insertNode(root, 'D'); insertNode(root, 'B'); insertNode(root, 'M'); insertNode(root, 'N'); insertNode(root, 'A'); insertNode(root, 'J'); insertNode(root, 'E'); insertNode(root, 'Q'); while (1) { menu(); choice = getchar(); getchar(); switch (choice) { case'1': printf("\t[이진트리 출력]"); displayInorder(root); printf("\n"); break; case'2': printf("삽입할 문자를 입력하세요 : "); key = getchar(); getchar(); insertNode(root, key); break; case'3': printf("삭제할 문자를 입력하세요 : "); key = getchar(); getchar(); deleteNode(root, key); break; case'4': printf("찾을 문자를 입력하세요 : "); key = getchar(); getchar(); foundedNode = searchBST(root, key); if(foundedNode != NULL) printf("\n %c 를 찾았습니다! \n", foundedNode->key); else { printf("\n 문자를 찾지 못했습니다.\n"); } break; case'5': return 0; default: printf("없는 메뉴입니다. 메뉴를 다시 선택하세요! \n"); break; } } }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> struct char_print_parms { char character; int count; }; void *char_print (void* parameters) { struct char_print_parms *p = (struct char_print_parms*) parameters; int i; for (i = 0; i < 10; i++) { printf("%d\n", p -> count +i); sleep(1); } return NULL; } int main () { pthread_t thread1_id; struct char_print_parms thread1_args; thread1_args.character = '1'; thread1_args.count = 1; pthread_create (&thread1_id, NULL, &char_print, &thread1_args); pthread_join (thread1_id, NULL); return 0; }
C
// INT31-C: Compliant Solution (Unsigned to Signed) #include <limits.h> void func(void) { unsigned long int u_a = ULONG_MAX; signed char sc; if (u_a <= SCHAR_MAX) { sc = (signed char)u_a; /* Cast eliminates warning */ } else { /* Handle error */ } }
C
#include "renderer.h" #include "shader.h" #include <assert.h> #include <glload/gl_2_0.h> #include <glload/gl_load.h> #include <GL/freeglut.h> #include <stdio.h> static const char *FRAGMENT_SHADER_LOC = "../../glsl/fragment.frag"; static const char *VERTEX_SHADER_LOC = "../../glsl/vertex.vert"; static Shader *fragShader; static Shader *vertexShader; static Program *program; static Attribute *vertPosAttrib; static Attribute *texCoordAttrib; static Uniform *diffuseSamplerUni; static Uniform *colorUni; /*Temporary values, will move to vec4 or color struct*/ static float colorRed; static float colorBlue; static float colorGreen; static float colorAlpha; static Texture *currentTexture; static Texture *whiteTexture; static void (*renderFunction)(); /* Will call render function and then glutPosRedisplay() */ static void do_glut_display() { if (renderFunction) renderFunction(); glutPostRedisplay(); } void init_display(int width, int height, char *name) { int argc = 1; int loadTest; char *myargv[1]; myargv[0] = name; glutInit(&argc, myargv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(100, 100); glutInitWindowSize(width, height); glutCreateWindow(name); loadTest = ogl_LoadFunctions(); if (loadTest == ogl_LOAD_FAILED) { printf("Loading opengl function pointers failed!"); assert(0); } glutDisplayFunc(do_glut_display); } void init_OGL() { //Vars for whiteTexture ImageFormat format; unsigned char data; program = malloc(sizeof(Program)); fragShader = malloc(sizeof(Shader)); vertexShader = malloc(sizeof(Shader)); vertPosAttrib = malloc(sizeof(Attribute)); texCoordAttrib = malloc(sizeof(Attribute)); colorUni = malloc(sizeof(Uniform)); diffuseSamplerUni = malloc(sizeof(Uniform)); init_shader_from_file(fragShader, FRAGMENT_SHADER, FRAGMENT_SHADER_LOC); init_shader_from_file(vertexShader, VERTEX_SHADER, VERTEX_SHADER_LOC); init_program(program, fragShader, vertexShader); init_attribute(vertPosAttrib, program, SVAR_VEC2, "vertPos"); init_attribute(texCoordAttrib, program, SVAR_VEC2, "texCoord"); init_uniform(colorUni, program, SVAR_VEC4, "color"); init_uniform(diffuseSamplerUni, program, SVAR_SAMPLER2D, "diffuse"); //Create white texture whiteTexture = malloc(sizeof(Texture)); format = TEX_FMT_RED; data = 0xFF; //White init_texture(whiteTexture, format, 1, 1, &data); //Set default color to white colorRed = 1; colorGreen = 1; colorBlue = 1; colorAlpha = 1; } void destroy_OGL() { destroy_shader(fragShader); destroy_shader(vertexShader); destroy_program(program); clear_attribute(vertPosAttrib); clear_attribute(texCoordAttrib); clear_uniform(colorUni); clear_uniform(diffuseSamplerUni); destroy_texture(whiteTexture); free(whiteTexture); free(program); free(fragShader); free(vertexShader); free(vertPosAttrib); free(texCoordAttrib); free(colorUni); free(diffuseSamplerUni); } void set_render_function(void (*render)()) { renderFunction = render; } void set_keyboard_function(void (*keyboard)(unsigned char key, int mouseX, int mouseY)) { glutKeyboardFunc(keyboard); } void set_special_key_function(void (*specialKeys)(int key, int mouseX, int mouseY)) { glutSpecialFunc(specialKeys); } void start_main_loop() { glutMainLoop(); } void clear_display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void swap_buffers() { glutSwapBuffers(); } /*----Rendering Functions----*/ void ready_for_rendering() { use_program(program); } void finish_rendering() { unbind_current_program(); } void set_color(float r, float g, float b, float a) { colorRed = r; colorGreen = g; colorBlue = b; colorAlpha = a; } void set_texture(Texture *t) { currentTexture = t; } void render_quad(float x, float y, float width, float height) { GLfloat vertices[] = {x + width, y + height, x, y + height, x, y, x + width, y }; GLfloat texCoords[] = {1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0 }; GLubyte indices[] = {0, 1, 2, 0, 2, 3}; //Set color variable before rendering quad set_uniform_vec4(colorUni, colorRed, colorGreen, colorBlue, colorAlpha); set_uniform_float(diffuseSamplerUni, 0); if (currentTexture != NULL) bind_texture(currentTexture, 0); else bind_texture(whiteTexture, 0); glEnableVertexAttribArray(vertPosAttrib->handle); glEnableVertexAttribArray(texCoordAttrib->handle); glVertexAttribPointer(vertPosAttrib->handle, 2, GL_FLOAT, GL_FALSE, 0, vertices); glVertexAttribPointer(texCoordAttrib->handle, 2, GL_FLOAT, GL_FALSE, 0, texCoords); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices); glDisableVertexAttribArray(vertPosAttrib->handle); glDisableVertexAttribArray(texCoordAttrib->handle); unbind_texture(0); }
C
#include "decs.h" /* diagnostics subroutine */ void diag(call_code) int call_code ; { char dfnam[10] ; int i,j,k ; double rho,v,u,ek,eth,etot,e_fin,m_fin ; FILE *dump_file ; void dump() ; double U[NP],px,py,pz,e,rmed,divb,divbmax ; void primtoU(double *p, double *U) ; static int dump_cnt ; static double e_init,m_init,tdump ; static FILE *ener_file ; static double timage ; char ifnam[50] ; static int im_cnt ; FILE *im_file ; if(call_code==0) { ener_file = fopen("ener.out","w") ; if(ener_file==NULL) { fprintf(stderr,"error opening energy output file\n") ; exit(1) ; } tdump = t + SMALL ; timage = t + SMALL ; dump_cnt = 0 ; im_cnt = 0 ; } /* calculate energies */ px = py = pz = e = rmed = divbmax = 0. ; LOOP { primtoU(p[i][j],U) ; rmed += U[0]*dV ; px += U[UX]*dV ; py += U[UY]*dV ; pz += U[UZ]*dV ; e += U[UU]*dV ; /* flux-ct defn */ divb = fabs( 0.5*(p[i][j][BX] + p[i][j-1][BX] - p[i-1][j][BX] - p[i-1][j-1][BX])/dx + 0.5*(p[i][j][BY] + p[i-1][j][BY] - p[i][j-1][BY] - p[i-1][j-1][BY])/dy) ; if(divb > divbmax) divbmax = divb ; } fprintf(stderr,"divbmax: %g\n",divbmax) ; if(call_code == 0) { e_init = e ; m_init = rmed ; } else if (call_code == 2) { e_fin = e ; m_fin = rmed ; fprintf(stderr,"\n\nEnergy: ini,fin,del: %g %g %g\n", e_init,e_fin,(e_fin-e_init)/e_init) ; fprintf(stderr,"mass: ini,fin,del: %g %g %g\n", m_init,m_fin,(m_fin-m_init)/m_init) ; } else { fprintf(ener_file,"%10.5g %10.5g %10.5g %10.5g %10.5g %10.5g\n", t,rmed,px,py,pz,e) ; fflush(ener_file) ; } /* dump at regular intervals */ if(t >= tdump || call_code == 2 || call_code == 0) { fprintf(stderr,"dumping!") ; /* make regular dump file */ sprintf(dfnam,"dump%03d",dump_cnt) ; dump_file = fopen(dfnam,"w") ; if(dump_file==NULL) { fprintf(stderr,"error opening dump file\n") ; exit(2) ; } dump(dump_file) ; fclose(dump_file) ; dump_cnt++ ; tdump += DTd ; } /* make image of density at regular intervals */ if(t >= timage || call_code == 2) { sprintf(ifnam,"im%04d",im_cnt) ; im_file = fopen(ifnam,"w") ; if(im_file==NULL) { fprintf(stderr,"error opening image file\n") ; exit(2) ; } image(im_file) ; fclose(im_file) ; im_cnt++ ; timage += DTi ; } }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #define DATA_SIZE 32768 static int DATA[DATA_SIZE]; #define ITERATIONS 102400 static const int RAND_MID = RAND_MAX / 2; void initialise(void) { srand(time(NULL)); int i; for (i = 0; i < DATA_SIZE; ++i) DATA[i] = rand(); } static clock_t start; void start_clock() { start = clock(); } void end_clock() { const clock_t end = clock(); const float seconds = (float)(end - start) / CLOCKS_PER_SEC; printf("Runtime: %fs\n", seconds); } int calculate(void) { int sum = 0; int i, j; for (j = 0; j < ITERATIONS; ++j) for (i = 0; i < DATA_SIZE; ++i) if (DATA[i] < RAND_MID) sum += DATA[i]; return sum; } void scenario1(void) { puts("Scenario 1..."); start_clock(); calculate(); end_clock(); } int compare_int(const void *a, const void *b) { const int lhs = *(const int *) a; const int rhs = *(const int *) b; return lhs < rhs ? -1 : lhs > rhs ? 1 : 0; } void scenario2(void) { puts("\nScenario 2..."); start_clock(); qsort(DATA, DATA_SIZE, sizeof(int), compare_int); calculate(); end_clock(); } void run_branch_prediction_exercise(void) { puts("Branch prediction exercise"); puts("------------------------------\n"); initialise(); scenario1(); scenario2(); puts("\n"); }
C
#include "utils.h" #include <stdio.h> #include <string.h> #include <sys/stat.h> static bool str_equals(const char*, const char*); static void drop_newline(char*); bool file_exists(const char* filename) { struct stat st; return stat(filename, &st) == 0; } bool get_yes_or_no_answer(bool default_answer) { char buf[65536]; while (fgets(buf, sizeof(buf), stdin)) { drop_newline(buf); if (buf[0] == '\0') { break; } else if (str_equals(buf, "y") || str_equals(buf, "yes")) { return true; } else if (str_equals(buf, "n") || str_equals(buf, "no")) { return false; } else { fprintf(stderr, "Answer yes or no> "); fflush(stderr); } } return default_answer; } static bool str_equals(const char* a, const char* b) { return strcmp(a, b) == 0; } static void drop_newline(char* str) { size_t len = strlen(str); if (len >= 2 && str[len - 2] == '\r' && str[len - 1] == '\n') { str[len - 2] = '\0'; } else if (len >= 1 && str[len - 1] == '\n') { str[len - 1] = '\0'; } }
C
/** * @file gpex.c * @brief Driver for Generic PCI Express Bridge Emulator. Refer to * http://www.kernel.org/doc/Documentation/devicetree/bindings/pci/host-generic-pci.txt * for more details * * @author Denis Deryugin <deryugin.denis@gmail.com> * @version * @date 14.08.2019 */ #include <assert.h> #include <stdint.h> #include <string.h> #include <drivers/common/memory.h> #include <drivers/pci/pci.h> #include <drivers/pci/pci_chip/pci_utils.h> #include <hal/reg.h> #include <util/log.h> #define GPEX_MMIO_BASE 0x4010000000 #define GPEX_IRQ_BASE 35 #define GPEX_IRQ_NUM 4 /* GPEX_IRQ_BASE + 0, ... GPEX_IRQ_BASE + 3 */ #define PCI_REG_ADDR(bus, physdev, fun, where) \ (((where) & ~3) | ((fun) << 12) | ((physdev) << 15) | ((bus) << 20)) static uint32_t gpex_read_config(uint32_t bus, uint32_t dev_fn, uint32_t where, void *value, size_t size) { uint32_t tmp; uintptr_t addr; assert(value); log_debug("bus=%d dev_fn=%d where=%d size=%d", bus, dev_fn, where, size); addr = PCI_REG_ADDR(bus, dev_fn >> 3, dev_fn & 0x7, where) + GPEX_MMIO_BASE; log_debug("read addr %p", (void *) addr); switch (size) { case 1: tmp = REG8_LOAD(addr); break; case 2: tmp = REG16_LOAD(addr); break; case 4: tmp = REG32_LOAD(addr); break; default: log_error("Wrong PCI config read size: %d", size); } log_debug("value=0x%x", tmp); memcpy(value, &tmp, size); return PCIUTILS_SUCCESS; } uint32_t pci_read_config8(uint32_t bus, uint32_t dev_fn, uint32_t where, uint8_t *value) { return gpex_read_config(bus, dev_fn, where, value, sizeof(uint8_t)); } uint32_t pci_read_config16(uint32_t bus, uint32_t dev_fn, uint32_t where, uint16_t *value) { return gpex_read_config(bus, dev_fn, where, value, sizeof(uint16_t)); } uint32_t pci_read_config32(uint32_t bus, uint32_t dev_fn, uint32_t where, uint32_t *value) { return gpex_read_config(bus, dev_fn, where, value, sizeof(uint32_t)); } static uint32_t gpex_write_config(uint32_t bus, uint32_t dev_fn, uint32_t where, void *value, size_t size) { uintptr_t addr; assert(value); log_debug("bus=%d dev_fn=%d where=%d size=%d", bus, dev_fn, where, size); addr = PCI_REG_ADDR(bus, dev_fn >> 3, dev_fn & 0x7, where) + GPEX_MMIO_BASE; log_debug("write addr %p", (void *) addr); switch (size) { case 1: REG8_STORE(addr, *((uint8_t *) value)); break; case 2: REG16_STORE(addr, *((uint16_t *) value)); break; case 4: REG32_STORE(addr, *((uint32_t *) value)); break; default: log_error("Wrong PCI config read size: %d", size); } return PCIUTILS_SUCCESS; } uint32_t pci_write_config8(uint32_t bus, uint32_t dev_fn, uint32_t where, uint8_t value) { return gpex_write_config(bus, dev_fn, where, &value, sizeof(uint8_t)); } uint32_t pci_write_config16(uint32_t bus, uint32_t dev_fn, uint32_t where, uint16_t value) { return gpex_write_config(bus, dev_fn, where, &value, sizeof(uint16_t)); } uint32_t pci_write_config32(uint32_t bus, uint32_t dev_fn, uint32_t where, uint32_t value) { return gpex_write_config(bus, dev_fn, where, &value, sizeof(uint32_t)); } unsigned int pci_irq_number(struct pci_slot_dev *dev) { return (unsigned int) (GPEX_IRQ_BASE + (dev->irq_pin + 1) % GPEX_IRQ_NUM); } PERIPH_MEMORY_DEFINE(gpex_mmio, GPEX_MMIO_BASE, 0x2EFF0000);
C
#include <stdio.h> #include <unistd.h> #include <signal.h> void catchusr(int); void do_child(int i, int *bpid){ int i,pid; static struct sigaction act; act.sa_handler==catchusr; sigaction(SIGUSR1, &act, NULL); printf("%d-th child is created ... \n", i); // pause(); if(i!=1){ pause(); } pid = getpid(); for(i=0;i<5;i++){ printf("child %d ........\n",pid); sleep(1); } // signal 받으면 process id 3번 출력 if(i!=0){ // sleep(1); kill(bpid, SIGUSR1); } exit(0); } int main(){ int i, k, status; pid_t pid[5]; for(i=0;i<5;i++){ pid[i] = fork(); if(pid[i]==0){ do_chile(i, pid); } } //1초씩 sleep 하면서 child들에게 sigusr1 보내기 // for(i=0;i<5;i++){ // sleep(1); // kill(pid[i], SIGUSR1); // } for(i=0;i<5;i++){ k=wait(&status); printf("child #%d is terminated...\n", k); } exit(0); } void catchusr(int signo){ printf(".................. catch SIGUSR1 : %d\n", signo); }
C
/****************************************************************************** * @author: David Anderson * Question: * Would this code work? * Solution: * No it would not! Notice you are trying to use a pointer on the heap after * you gave it back. You don't own it after you've given it back to the memory * system. ******************************************************************************/ int* pInt = (int*)malloc(sizeof(int)); *pInt = 8; free(pInt ); (*pInt )++; return(EXIT_SUCCESS);
C
/* * Copyright (c) 2017 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include "test_queue.h" #define TIMEOUT K_MSEC(100) #define STACK_SIZE (512 + CONFIG_TEST_EXTRA_STACK_SIZE) #define LIST_LEN 2 static K_THREAD_STACK_DEFINE(tstack, STACK_SIZE); static struct k_thread tdata; K_SEM_DEFINE(sem, 0, 1); /*test cases*/ /** * @brief Test k_queue_get() failure scenario * @ingroup kernel_queue_tests * @see k_queue_get() */ ZTEST(queue_api_1cpu, test_queue_get_fail) { static struct k_queue queue; k_queue_init(&queue); /**TESTPOINT: queue get returns NULL*/ zassert_is_null(k_queue_get(&queue, K_NO_WAIT), NULL); zassert_is_null(k_queue_get(&queue, TIMEOUT), NULL); } /* The sub-thread entry */ static void tThread_entry(void *p1, void *p2, void *p3) { k_sem_give(&sem); /* wait the queue for data */ qdata_t *p = k_queue_get((struct k_queue *)p1, K_FOREVER); zassert_equal(p, p2, "Failed to append a unnormal list"); } /** * @brief Test k_queue_append_list() failure scenario * * @details According to the API k_queue_append_list to * design some error condition to verify error branch of * the API. * 1. Verify that the list's head is empty. * 2. Verify that the list's tail is empty. * 3. Verify that append list to the queue when a * sub-thread is waiting for data. * * @ingroup kernel_queue_tests * * @see k_queue_append_list() */ ZTEST(queue_api, test_queue_append_list_error) { static qdata_t data_l[2]; static struct k_queue queue; static qdata_t *head = NULL, *tail = &data_l[1]; k_queue_init(&queue); memset(data_l, 0, sizeof(data_l)); /* Check if the list of head is equal to null */ zassert_true(k_queue_append_list(&queue, (uint32_t *)head, (uint32_t *)tail) == -EINVAL, "failed to CHECKIF head == NULL"); /* Check if the list of tail is equal to null */ head = &data_l[0]; tail = NULL; zassert_true(k_queue_append_list(&queue, (uint32_t *)head, (uint32_t *)tail) == -EINVAL, "failed to CHECKIF tail == NULL"); /* Initializing the queue for re-using below */ k_queue_init(&queue); /* Append unnormal list(just one node)into the queue for sub-thread */ head = &data_l[0]; head->snode.next = NULL; k_thread_create(&tdata, tstack, STACK_SIZE, tThread_entry, &queue, head, NULL, K_PRIO_PREEMPT(0), 0, K_NO_WAIT); /* Delay for thread initializing */ k_sem_take(&sem, K_FOREVER); k_queue_append_list(&queue, (uint32_t *)head, (uint32_t *)head); k_thread_join(&tdata, K_FOREVER); } /** * @brief Test k_queue_merge_slist() failure scenario * * @details Verify the API k_queue_merge_slist when * a slist is empty or a slist's tail is null. * * @ingroup kernel_queue_tests * * @see k_queue_merge_slist() */ ZTEST(queue_api, test_queue_merge_list_error) { qdata_t data_sl[2]; static struct k_queue queue; sys_slist_t slist; k_queue_init(&queue); sys_slist_init(&slist); memset(data_sl, 0, sizeof(data_sl)); /* Check if the slist is empty */ zassert_true(k_queue_merge_slist(&queue, &slist) == -EINVAL, "Failed to CHECKIF slist is empty"); /* Check if the tail of the slist is null */ sys_slist_append(&slist, (sys_snode_t *)&(data_sl[0].snode)); sys_slist_append(&slist, (sys_snode_t *)&(data_sl[1].snode)); slist.tail = NULL; zassert_true(k_queue_merge_slist(&queue, &slist) != 0, "Failed to CHECKIF the tail of slist == null"); } #ifdef CONFIG_USERSPACE /** * @brief Test k_queue_init() failure scenario * * @details Verify that the parameter of API k_queue_init() is * NULL, what will happen. * * @ingroup kernel_queue_tests * * @see k_queue_init() */ ZTEST_USER(queue_api, test_queue_init_null) { ztest_set_fault_valid(true); k_queue_init(NULL); } /** * @brief Test k_queue_alloc_append() failure scenario * * @details Verify that the parameter of the API is * NULL, what will happen. * * @ingroup kernel_queue_tests * * @see k_queue_alloc_append() */ ZTEST_USER(queue_api, test_queue_alloc_append_null) { qdata_t data; memset(&data, 0, sizeof(data)); ztest_set_fault_valid(true); k_queue_alloc_append(NULL, &data); } /** * @brief Test k_queue_alloc_prepend() failure scenario * * @details Verify that the parameter of the API is * NULL, what will happen. * * @ingroup kernel_queue_tests * * @see k_queue_alloc_prepend() */ ZTEST_USER(queue_api, test_queue_alloc_prepend_null) { qdata_t data; memset(&data, 0, sizeof(data)); ztest_set_fault_valid(true); k_queue_alloc_prepend(NULL, &data); } /** * @brief Test k_queue_get() failure scenario * * @details Verify that the parameter of the API is * NULL, what will happen. * * @ingroup kernel_queue_tests * * @see k_queue_get() */ ZTEST_USER(queue_api, test_queue_get_null) { ztest_set_fault_valid(true); k_queue_get(NULL, K_FOREVER); } /** * @brief Test k_queue_is_empty() failure scenario * * @details Verify that the parameter of the API is * NULL, what will happen. * * @ingroup kernel_queue_tests * * @see k_queue_is_empty() */ ZTEST_USER(queue_api, test_queue_is_empty_null) { ztest_set_fault_valid(true); k_queue_is_empty(NULL); } /** * @brief Test k_queue_peek_head() failure scenario * * @details Verify that the parameter of the API is * NULL, what will happen. * * @ingroup kernel_queue_tests * * @see k_queue_peek_head() */ ZTEST_USER(queue_api, test_queue_peek_head_null) { ztest_set_fault_valid(true); k_queue_peek_head(NULL); } /** * @brief Test k_queue_peek_tail() failure scenario * * @details Verify that the parameter of the API is * NULL, what will happen. * * @ingroup kernel_queue_tests * * @see k_queue_peek_tail() */ ZTEST_USER(queue_api, test_queue_peek_tail_null) { ztest_set_fault_valid(true); k_queue_peek_tail(NULL); } /** * @brief Test k_queue_merge_slist() failure scenario * * @details Verify that the parameter of the API is * NULL, what will happen. * * @ingroup kernel_queue_tests * * @see k_queue_merge_slist() */ ZTEST_USER(queue_api, test_queue_cancel_wait_error) { struct k_queue *q; q = k_object_alloc(K_OBJ_QUEUE); zassert_not_null(q, "no memory for allocated queue object"); k_queue_init(q); /* Check if cancel a qeueu that no thread to wait */ k_queue_cancel_wait(q); /* Check if cancel a null pointer */ ztest_set_fault_valid(true); k_queue_cancel_wait(NULL); } #endif /* CONFIG_USERSPACE */
C
#include <stdio.h> #include "holberton.h" /** * mul - Multiplies two values given as input and displays the product * @a: First integer * @b: Second integer * Return: Success */ int mul(int a, int b) { int product; product = a * b; return (product); }
C
uint8_t ADCV[2]; //!< Cell Voltage conversion command. uint8_t ADAX[2]; // GPIO conversion command. void LTC_wakeup_sleep(){ LTC6804_CS_P &= ~(1<<LTC6804_CS); _delay_ms(1); LTC6804_CS_P |= (1<<LTC6804_CS); } /*!****************************************************************************************************************** \brief Maps global ADC control variables to the appropriate control bytes for each of the different ADC commands @param[in] uint8_t MD The adc conversion mode @param[in] uint8_t DCP Controls if Discharge is permitted during cell conversions @param[in] uint8_t CH Determines which cells are measured during an ADC conversion command @param[in] uint8_t CHG Determines which GPIO channels are measured during Auxiliary conversion command Command Code: \n |command | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | |-----------|-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|-------| |ADCV: | 0 | 1 | MD[1] | MD[2] | 1 | 1 | DCP | 0 | CH[2] | CH[1] | CH[0] | |ADAX: | 1 | 0 | MD[1] | MD[2] | 1 | 1 | DCP | 0 | CHG[2]| CHG[1]| CHG[0]| ******************************************************************************************************************/ void set_adc(uint8_t MD, //ADC Mode uint8_t DCP, //Discharge Permit uint8_t CH, //Cell Channels to be measured uint8_t CHG //GPIO Channels to be measured ) { uint8_t md_bits; md_bits = (MD & 0x02) >> 1; ADCV[0] = md_bits + 0x02; md_bits = (MD & 0x01) << 7; ADCV[1] = md_bits + 0x60 + (DCP<<4) + CH; md_bits = (MD & 0x02) >> 1; ADAX[0] = md_bits + 0x04; md_bits = (MD & 0x01) << 7; ADAX[1] = md_bits + 0x60 + CHG ; } /*!****************************************************************************************************** \brief Start an GPIO Conversion Starts an ADC conversions of the LTC6804 GPIO inputs. The type of ADC conversion done is set using the associated global variables: |Variable|Function | |--------|----------------------------------------------| | MD | Determines the filter corner of the ADC | | CHG | Determines which GPIO channels are converted | *********************************************************************************************************/ void LTC6804_adax() { uint8_t cmd[4]; uint16_t temp_pec; cmd[0] = ADAX[0]; cmd[1] = ADAX[1]; temp_pec = pec15_calc(2, ADAX); cmd[2] = (uint8_t)(temp_pec >> 8); cmd[3] = (uint8_t)(temp_pec); wakeup_idle (); //This will guarantee that the LTC6804 isoSPI port is awake. This command can be removed. LTC6804_CS_P &= ~(1<<LTC6804_CS); spi_write_array(4,cmd); LTC6804_CS_P |= (1<<LTC6804_CS); } /* LTC6804_adax Function sequence: 1. Load adax command into cmd array 2. Calculate adax cmd PEC and load pec into cmd array 3. wakeup isoSPI port, this step can be removed if isoSPI status is previously guaranteed 4. send broadcast adax command to LTC6804 stack */ /* @param[in] uint8_t len: the length of the data array being passed to the function @param[in] uint8_t data[] : the array of data that the PEC will be generated from @return The calculated pec15 as an unsigned int16_t ***********************************************************/ uint16_t pec15_calc(uint8_t len, uint8_t *data) { uint16_t remainder,addr; remainder = 16;//initialize the PEC for(uint8_t i = 0; i<len;i++) // loops for each byte in data array { addr = ((remainder>>7)^data[i])&0xff;//calculate PEC table address remainder = (remainder<<8)^crc15Table[addr]; } return(remainder*2);//The CRC15 has a 0 in the LSB so the remainder must be multiplied by 2 }
C
#include "holberton.h" /** * print_rev - print a string in reverse * @s: the string to print */ void print_rev(char *s) { int length; for (length = 0; *s != '\0'; s++) length++; s--; length--; for (; length >= 0; length--, s--) _putchar(*s); _putchar('\n'); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <winsock.h> #include <ctype.h> #include <winsock2.h> #include <windows.h> #define Len 256 #pragma comment(lib,"ws2_32.lib") //Winsock Library #define bzero(a, b) memset(a, 0, b) #define BUFFER_SIZE 1024 #define FILE_NAME_MAX_SIZE 512 int *get_space(char *); int get_len(int *); char *split_str(char *); int main(int argc, char *argv[]) { //char ** words = split_str("wo shishi you jige kongge hahahaha"); WSADATA wsa; SOCKET client_socket_fd ; printf("\nInitialising Winsock..."); if (WSAStartup(MAKEWORD(2,2),&wsa) != 0) { printf("Failed. Error Code : %d",WSAGetLastError()); return 1; } struct sockaddr_in client_addr; int portno; portno = atoi(argv[2]); bzero(&client_addr, sizeof(client_addr)); client_addr.sin_family = AF_INET; client_addr.sin_addr.s_addr = htons(INADDR_ANY); client_addr.sin_port = htons(0);//ƶ˿Ϊͻ˵Ķ˿ // socketɹsocket client_socket_fd = socket(AF_INET, SOCK_STREAM, 0); if(client_socket_fd < 0) { perror("Create Socket Failed:"); exit(1); } // 󶨿ͻ˵socketͿͻ˵socketַṹ DZ /*if(-1 == (bind(client_socket_fd, (struct sockaddr*)&client_addr, sizeof(client_addr)))) { perror("Client Bind Failed:"); exit(1); }*/ // һ˵socketַṹ÷DZߵIPַ˿ڶгʼں struct sockaddr_in server_addr; bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(portno);//line 56 һipָ server_addr.sin_addr.s_addr = inet_addr(argv[1]); /*if(inet_pton(AF_INET, argv[1], &server_addr.sin_addr) == 0) { perror("Server IP Address Error:"); exit(1); } /*struct hostent *server; server = gethostbyname(argv[1]); bcopy((char *)server -> h_addr, (char *)&server_addr.sin_addr.s_addr, server -> h_length);*/ int server_addr_length = sizeof(server_addr); printf("start to connect %s at port %s\n",argv[1], argv[2]); // ӣӳɹclient_socket_fd˿ͻ˺ͷһsocket if(connect(client_socket_fd, (struct sockaddr*)&server_addr, server_addr_length) < 0) { perror("Can Not Connect To Server IP:"); exit(0); } // ļ ŵbufferеȴ char file_name[FILE_NAME_MAX_SIZE+1]; bzero(file_name, FILE_NAME_MAX_SIZE+1); printf("Please Input File Name On Server:\t"); scanf("%s", file_name); char buffer[BUFFER_SIZE]; unsigned char buff_bin[BUFFER_SIZE];//buffer for binaray transform bzero(buffer, BUFFER_SIZE); strncpy(buffer, file_name, strlen(file_name)>BUFFER_SIZE?BUFFER_SIZE:strlen(file_name)); // bufferе if(send(client_socket_fd, buffer, BUFFER_SIZE, 0) < 0) { perror("Send File Name Failed:"); exit(1); } // ļ׼д FILE *fp = fopen(file_name, "wb"); if(NULL == fp) { printf("File:\t%s Can Not Open To Write\n", file_name); exit(1); } // ӷݵbuffer // ÿһݣ㽫дļУѭֱļ겢дΪֹ bzero(buffer, BUFFER_SIZE); int length = 0; while((length = recv(client_socket_fd, buff_bin, BUFFER_SIZE, 0)) > 0) { if(fwrite(buff_bin, sizeof(unsigned char), length, fp) < length) { printf("File:\t%s Write Failed\n", file_name); break; } bzero(buff_bin, BUFFER_SIZE); } // ճɹ󣬹رļرsocket printf("Receive File:\t%s From Server IP Successful!\n", file_name); fclose(fp); close(client_socket_fd); return 0; } int *get_space(char *buffer)//ȡַոλãֵǴλõ { int i; int blank_num = 1;//blank_pos[0] = 0,㡣 static int blank_pos [Len];//̬һֱͷ memset(blank_pos, -1, sizeof(blank_pos)); //-1 ڼַ for (i = 0; i < strlen(buffer); i ++) { if (isblank(buffer[i])) { printf("the %dth num is %d\n", blank_num, i); blank_pos[blank_num ++] = i; } } return blank_pos; } char * split_str(char *buffer)//ģsplitֳַַ飬ԿոЧ { int *a = get_space(buffer); int len = get_len(a); int last_tail = strlen(buffer); char *words[len + 1];// ά飬洢ִ int i; for (i = 0; i < len ; i ++) { if (i < len -1) { int str_length = a[i+1] - a[i] -1 ; words[i] = (char *)malloc(str_length); strncpy(words[i], buffer,str_length); words[i][str_length] = '\0'; buffer += (str_length + 1); //printf("%s's length is %d\n", words[i], strlen(words[i])); } else { int str_length = last_tail - a[len-1] -1; words[i] = (char *)malloc(str_length); strncpy(words[i], buffer,str_length); words[i][str_length] = '\0'; buffer += (str_length + 1); //printf("%s's length is %d\n", words[i], strlen(words[i])); } } return words; } int get_len(int *a) { int len = 1, i; for (i = 1; a[i] != -1; i ++) len ++; printf("there're %d spaces in the option-code\n",len); return len; }
C
#include <stdio.h> // Function to return the // minimum of two numbers int Min(int Num1, int Num2) { return Num1 >= Num2 ? Num2 : Num1; } // Utility function to calculate LCM // of two numbers using recursion int LCMUtil(int Num1, int Num2, int K) { // If either of the two numbers // is 1, return their product if (Num1 == 1 || Num2 == 1) return Num1 * Num2; // If both the numbers are equal if (Num1 == Num2) return Num1; // If K is smaller than the // minimum of the two numbers if (K <= Min(Num1, Num2)) { // Checks if both numbers are // divisible by K or not if (Num1 % K == 0 && Num2 % K == 0) { // Recursively call LCM() function return K * LCMUtil( Num1 / K, Num2 / K, 2); } // Otherwise else return LCMUtil(Num1, Num2, K + 1); } // If K exceeds minimum else return Num1 * Num2; } // Function to calculate LCM // of two numbers void LCM(int N, int M) { // Stores LCM of two number int lcm = LCMUtil(N, M, 2); // Print LCM printf("%d", lcm); } // Driver Code int main() { // Given N & M int N = 2, M = 4; // Function Call LCM(N, M); return 0; }
C
#include <stdio.h> int main(){ int massa = 0; printf("Informe uma massa em kg \n"); scanf("%d", &massa); printf("A massa convertida em libras eh: %.2lf", (massa / 0.45)); return 0; }
C
#include "fthread.h" #include "stdio.h" /* cleanup when stopping a thread */ void pr (void *text) { while (1) { fprintf (stdout,"%s",(char*)text); ft_thread_cooperate (); } } void cleanup (void *args) { fprintf (stdout,"clean up!!!!!!!!\n"); } void control (void *args) { ft_thread_t t = (ft_thread_t)args; ft_thread_cooperate_n (10); ft_scheduler_stop (t); fprintf (stdout,"stop\n"); ft_thread_join (t); fprintf (stdout,"exit\n"); exit(0); } int main (void) { ft_thread_t ft; ft_scheduler_t sched = ft_scheduler_create (); ft = ft_thread_create (sched,pr,cleanup,"*"); if (ft == NULL) { fprintf (stderr,"error!!!\n"); exit (-1); } ft_thread_create (sched,control,NULL,(void*)ft); ft_scheduler_start (sched); ft_exit (); return 0; } /* result ***********stop clean up!!!!!!!! exit end result */
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define FINISH_FLAG "FILE_TRANSPORT_FINISH" #define MAXLINE 10240 void usage(char *command) { printf("usage :%s portnum filename\n", command); exit(0); } int main(int argc,char **argv) { struct sockaddr_in serv_addr; struct sockaddr_in clie_addr; char buf[MAXLINE]; int sock_id; int recv_len; int clie_addr_len; FILE *fp; if (argc != 3) { usage(argv[0]); } /* Create the the file commented by guoqingbo*/ if ((fp = fopen(argv[2], "w")) == NULL) { perror("Creat file failed"); exit(0); } if ((sock_id = socket(AF_INET,SOCK_DGRAM,0)) < 0) { perror("Create socket failed\n"); exit(0); } /*fill the server sockaddr_in struct commented by guoqingbo*/ memset(&serv_addr,0,sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(atoi(argv[1])); serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sock_id,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0 ) { perror("Bind socket faild\n"); exit(0); } /* server part commented by guoqingbo*/ clie_addr_len = sizeof(clie_addr); bzero(buf, MAXLINE); while (recv_len = recvfrom(sock_id, buf, MAXLINE, 0,(struct sockaddr *)&clie_addr, &clie_addr_len)) { if(recv_len < 0) { printf("Recieve data from client failed!\n"); break; } printf("#%d",recv_len); fflush(stdout); if ( strstr(buf, FINISH_FLAG) != NULL ) { printf("\nFinish receiver finish_flag\n"); break; } int write_length = fwrite(buf, sizeof(char), recv_len, fp); if (write_length < recv_len) { printf("File write failed\n"); break; } bzero(buf, MAXLINE); } printf("Finish recieve\n"); fclose(fp); close(sock_id); return 0; }
C
#include <stdlib.h> #include "digraph.h" /* Construtor do dígrafo */ Digraph *initDigraph(int nV, int nA, List **adjacentes){ Digraph *G; G = malloc(sizeof(Digraph)); G->V = nV; G->A = nA; G->adj = adjacentes; return G; } /* Retorna o vetor de listas de adjacencia do dígrafo */ List **getAdj(Digraph *G){ return G->adj; } /* Libera a memoria utilizada pelo nosso dígrafo */ void freeDigraph(Digraph *G){ int i; for(i = 0; i < G->V; i++) freeList(G->adj[i]); free(G); }
C
// // main.c // 冒泡排序 // // Created by 吴方兵 on 16/8/14. // Copyright © 2016年 吴方兵. All rights reserved. // #include <stdio.h> void Bubblesort(int a[],int n){ int i,j,t; for(i=0;i<n-1;i++){ for(j=i+1;j<n;j++){ if(a[i]>a[j]){ t=a[i]; a[i]=a[j]; a[j]=t; } } } } int main(int argc, const char * argv[]) { int a[7]={2,1,3,4,5,6,0}; int i; Bubblesort(a,7); for(i=0;i<7;i++){ printf("%3d",a[i]); } printf("\n"); }
C
#include <stdio.h> #define N 3 #define M 2 int main() { int a[N][M] = { 1, 2, 3, 4, 5, 6 }; int x = a[1][0]; // sets x to 3 int y = a[2][1]; // sets x to 6 int z = *(*(a + 2) + 1); // equivalent to a[2][1] printf("x: %d, y: %d, z: %d\n", x, y, z); }
C
#include "holberton.h" /** * _atoi - converts a string to an integer, pulls integer and its sign. * @s: string to be evaluated. * Return: integer with its sign */ int _atoi(char *s) { int dash_count = 0; int num_started = 0; int number = 0; int i = 0; for (; s[i] != '\0'; i++) { if (s[i] >= '0' && s[i] <= '9') { num_started = 1; number = number * 10 - (s[i] - '0'); } else { if (num_started == 1) { break; } if (s[i] == '-') { dash_count++; } } } if (dash_count % 2 == 0) { return (-number); } return (number); }
C
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.c * Author: Lewis * * Created on 11 December 2016, 12:24 */ #include <stdio.h> int input(){ int num; printf("Write a number and we'll do stuff to it: "); scanf("%d", num); return num; } void doStuff(int user){ int keep = user; int change = 0; int keep2 = keep * 2; change = (keep + 3)+(change *= 2)+(change -= 4)+(change -= keep2)+(change += 3); /* change = keep + 3; change *= 2; change -= 4; change -= keep2; change += 3; */ printf("Your new number is: %d", change); } int main() { doStuff(input()); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <mcheck.h> int main(int argc, char *argv[]) { char *p; if (mcheck(NULL) != 0) { fprintf(stderr, "mcheck() failed\n"); exit(EXIT_FAILURE); } p = malloc(1000); fprintf(stderr, "About to free\n"); free(p); fprintf(stderr, "\nAbout to free a second time\n"); free(p); exit(EXIT_SUCCESS); }
C
#include <stdio.h> int main (void){ char conta, es; float a,b; int op; while (op<= 10){ system ("cls"); printf("Digite a conta desejada:(+,-) "); scanf("%f %c %f", &a, &conta, &b); if (conta == '+') printf("%.2f %c %.2f = %.2f",a, conta, b, a+b); else if (conta == '-') printf("%.2f %c %.2f = %.2f",a, conta, b, a-b); else printf("Operacao invalida"); printf ("\nDeseja fazer outra conta (s/n)?"); scanf (" %c", &es); if ((es =='s')||(es=='S')) op = 1; else op =+ 20; } return 0; }
C
///input: 1 output: a or A assign number to albabet to print albabet by cooresponded number like 25=z ///the below code does not give output and any error Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' numbers = [3,6,12,1,1,3] letters = Alphabet(numbers) #include <stdio.h> void print(int); int main(void) { int num,n; //printf("enter the number\t"); scanf("%d",&num); num=n; //Base 26 representation from 1 to 26. } void print(int n) { if(n>0) { n--; print(n/26); int a=(n%26)+65; printf("%c",a); } }
C
#include "vfs.h" #include "terminal.h" #include "log.h" #include "common.h" fs_node_t *fs_root = 0; uint32_t read_fs(fs_node_t *node, uint32_t offset, uint32_t size, uint8_t *buffer) { if (node->read != 0) return node->read(node, offset, size, buffer); else return 0; } uint32_t write_fs(fs_node_t *node, uint32_t offset, uint32_t size, uint8_t *buffer) { if (node->write != 0) return node->write(node, offset, size, buffer); else return 0; } void open_fs(fs_node_t *node, uint8_t read, uint8_t write) { if (node->open != 0) return node->open(node); } void close_fs(fs_node_t *node) { if (node->close != 0) return node->close(node); } struct dirent *readdir_fs(fs_node_t *node, uint32_t index) { if ((node->flags&0x7) == FS_DIRECTORY && node->readdir != 0 ) return node->readdir(node, index); else return 0; } fs_node_t *finddir_fs(fs_node_t *node, char *name) { if ((node->flags&0x7) == FS_DIRECTORY && node->finddir != 0 ) return node->finddir(node, name); else return 0; } void list_vfs() { asm("cli"); uint8_t a[0x1000]; for (int i = 0; i < 0x1000; i++) { a[i] = 0x20; } int i = 0; struct dirent *node = 0; while ( (node = readdir_fs(fs_root, i)) != 0) { printk("Found file %s", node->name); log(LOG_INFO, "Found file %s", node->name); fs_node_t *fsnode = finddir_fs(fs_root, node->name); if ((fsnode->flags&0x7) == FS_DIRECTORY) { printk("\n\t(directory)\n"); log(LOG_INFO, "\n\t(directory)\n"); } else { printk("\n\t size: %d Bytes\n", fsnode->length); log(LOG_INFO, "\n\t size: %d Bytes\n", fsnode->length); printk("\tcontents:\n"); log(LOG_INFO, "\tcontents:\n"); char buf[256]; uint32_t sz = read_fs(fsnode, 0, 256, buf); int j; for (j = 0; j < sz; j++) { printk("%c", buf[j]); //log(LOG_NPRE, "%c", buf[j]); } printk("\n"); log(LOG_NPRE, "\n"); } i++; } printk("\n"); log(LOG_NPRE, "\n"); asm("sti"); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_vector_create.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: egoodale <egoodale@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/18 18:05:47 by egoodale #+# #+# */ /* Updated: 2018/10/23 14:20:53 by egoodale ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/libft.h" t_vector **ft_vectorspace_create(size_t init_cap, size_t size) { VAR(size_t, i, -1); VAR(t_vector **, vspace, NULL); if (!(vspace = ft_memalloc(sizeof(t_vector *) * size))) return (NULL); while (++i < size) if ((vspace[i] = ft_vector_create(init_cap))) continue ; else { ft_vectorspace_free(&vspace[0], i); return (NULL); } return (vspace); } t_vector *ft_vector_create(size_t init_cap) { VAR(t_vector *, new_vector, NULL); if (init_cap && (new_vector = ft_memalloc(sizeof(t_vector)))) { new_vector->len = 0; new_vector->cap = init_cap; new_vector->data = ft_memalloc(sizeof(init_cap)); return (new_vector); } return (NULL); } void ft_vectorspace_free(t_vector **vspace, int size) { VAR(int, i, -1); while (++i < size) { free(vspace[i]->data); free(vspace[i]); vspace[i] = NULL; } } void ft_subvector_slide(char *data, char *targ, size_t data_len) { VAR(int, orient, targ >= data ? 1 : -1); VAR(char *, start, ~orient ? data : data + (data_len - 1)); VAR(char *, subt, start + (orient * data_len)); VAR(int, shifts, ~orient ? (targ - subt) : (subt - targ)); if (shifts < (int)(~orient ? data_len : data_len - 1)) return ; while (shifts-- != (~orient ? 0 : -1)) { ft_charswap(start, subt); start += orient; subt += orient; } ft_subvector_slide(start, targ, data_len); }
C
#include "holberton.h" /** * _strlen - Count the maximum number of a array * @s: Input Array * * Return: counter */ int _strlen(char *s) { int cont; cont = 0; while (s[cont]) { cont++; } return (cont); } /** * string_nconcat - concat in s1 n charecters of s2 * @s1: String 1 * @s2: String 2 * @n: # charecters to copy a s1 * * Return: Pointer */ char *string_nconcat(char *s1, char *s2, unsigned int n) { unsigned int num1, num2, i, j; char *p; if (s1 == NULL) { s1 = ""; } if (s2 == NULL) { s2 = ""; } num1 = _strlen(s1); num2 = _strlen(s2); if (n >= num2) { n = num2; } p = malloc(sizeof(char) * (num1 + n + 1)); if (p == NULL) { return (NULL); } for (i = 0; s1[i] != '\0'; i++) { p[i] = s1[i]; } for (j = 0; j < n; j++) { p[num1] = s2[j]; num1++; } p[num1] = '\0'; return (p); }
C
#include "../../lv_examples.h" #if LV_USE_SNAPSHOT && LV_BUILD_EXAMPLES static void event_cb(lv_event_t * e) { lv_obj_t * snapshot_obj = lv_event_get_user_data(e); lv_obj_t * img = lv_event_get_target(e); if(snapshot_obj) { lv_img_dsc_t * snapshot = (void *)lv_img_get_src(snapshot_obj); if(snapshot) { lv_snapshot_free(snapshot); } /*Update the snapshot, we know parent of object is the container.*/ snapshot = lv_snapshot_take(img->parent, LV_COLOR_FORMAT_ARGB8888); if(snapshot == NULL) return; lv_img_set_src(snapshot_obj, snapshot); } } void lv_example_snapshot_1(void) { LV_IMG_DECLARE(img_star); lv_obj_t * root = lv_scr_act(); lv_obj_set_style_bg_color(root, lv_palette_main(LV_PALETTE_LIGHT_BLUE), 0); /*Create an image object to show snapshot*/ lv_obj_t * snapshot_obj = lv_img_create(root); lv_obj_set_style_bg_color(snapshot_obj, lv_palette_main(LV_PALETTE_PURPLE), 0); lv_obj_set_style_bg_opa(snapshot_obj, LV_OPA_100, 0); lv_img_set_zoom(snapshot_obj, 128); lv_img_set_angle(snapshot_obj, 300); /*Create the container and its children*/ lv_obj_t * container = lv_obj_create(root); lv_obj_center(container); lv_obj_set_size(container, 180, 180); lv_obj_set_flex_flow(container, LV_FLEX_FLOW_ROW_WRAP); lv_obj_set_flex_align(container, LV_FLEX_ALIGN_SPACE_EVENLY, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); lv_obj_set_style_radius(container, 50, 0); lv_obj_t * img; int i; for(i = 0; i < 4; i++) { img = lv_img_create(container); lv_img_set_src(img, &img_star); lv_obj_set_style_bg_color(img, lv_color_black(), 0); lv_obj_set_style_bg_opa(img, LV_OPA_COVER, 0); // lv_obj_set_style_transform_zoom(img, 400, LV_STATE_PRESSED); lv_obj_add_flag(img, LV_OBJ_FLAG_CLICKABLE); lv_obj_add_event(img, event_cb, LV_EVENT_PRESSED, snapshot_obj); lv_obj_add_event(img, event_cb, LV_EVENT_RELEASED, snapshot_obj); } } #endif
C
//program to write the result of 1/1!+ 1/2! + 1/3! + ....... +1/n! #include<stdio.h> int main() { int n; float fact =1; float sum = 0; printf("\nEnter the value of n: "); scanf("%d",&n); for(int i=1;i<=n;++i) //repeat for n numbers { for(int j=i;j>=1;--j) //calculate factorial { fact *= j; } sum += (1/fact); fact = 1; //reseting for next use } printf("\nThe sum of the inverse of the factorials upto %d is: %f \n",n,sum); return 0; }
C
#include <stdio.h> int main(void) { int c = 0, aux; float a[3]={1, 2, 3}; //float c, d; for (float i = .0f; i < 2.2f; i+=.2f) { aux = (int)((i - (int)i)*10); for (int j = 0; j < 3; j++){ if(aux == 0){ printf("I=%.0f J=%.0f\n", i, a[j]+i); } else { printf("I=%.1f J=%.1f\n", i, a[j]+i); } } } return 0; }
C
#include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv){ int ssock, csock; struct sockaddr_in saddr; char buf[10000]; char filename[255]; char path[255]; int filesize; char filesizee[255]; int readed=0; int state=0; int total=0; int len=0; FILE *fp; csock=socket(AF_INET, SOCK_STREAM, 0); //make client socket if (csock<0){ printf("Socket Error\n"); exit(0); } bzero((char *)&saddr, sizeof(saddr)); saddr.sin_addr.s_addr=inet_addr("127.0.0.1"); saddr.sin_family=AF_INET; saddr.sin_port=htons(20003); if ( connect(csock, (struct sockaddr *)&saddr, sizeof(saddr)) <0 ) //connet to server socket exit(0); write(csock, argv[3], strlen(argv[3])); // send command .. ls or upload or download if(strncmp(argv[3], "-l", 2)==0){ printf("============This is the list function\n"); printf("Sent command: 1\n"); while(1){ memset(buf, 0, 10000); state=recv(csock, buf, sizeof(buf),0); //receive names of elements if (strncmp(buf, "end\n", 4)==0) // it means the directory doesn't exist break; if (state==0) //it means all the elements were read break; printf("\n"); printf("%s\n", buf); } printf("============End List!\n"); } else if(strncmp(argv[3], "-u", 2)==0){ write(csock, strcat(argv[4],"\0"),strlen(argv[4])+1); // receive name of upload file printf("============This is the upload function\n"); printf("Sent command: 2\n"); printf("Sent filename: %s\n",argv[4]); memset(buf, 0, 10000); memset(filename, 0, 30); if (send(csock, argv[4], strlen(argv[4]), 0)<0) exit(0); sprintf(filename, "./"); strncat(filename,argv[4], strlen(argv[4])); fp=fopen(filename, "rb"); fseek(fp, 0, SEEK_END); //save size of file filesize=ftell(fp); if (send(csock, (char *)&filesize, sizeof(filesize),0)<0) exit(0); rewind(fp); //rewind file pointer to start while(1){ readed = fread(buf, 1, filesize-total, fp); //read the file and send the characters if (readed>0){ if(send(csock, buf, readed, 0)<0) exit(0); memset(buf, 0, 10000); total+=readed; } else if(total==filesize){ fclose(fp); printf("============End Upload!\n"); exit(0); } } printf("============End upload!\n"); } else if(strncmp(argv[3], "-d", 2)==0){ write(csock, strcat(argv[4], "\0"), strlen(argv[4])+1); printf("============This is the download function\n"); printf("Sent command: 3\n"); printf("Sent filename: %s\n",argv[4]); total=0; memset(buf, 0, 255); memset(path, 0, 255); memset(filename, 0,255); if (send(csock, argv[4], strlen(argv[4]), 0)<0){ close(csock); exit(0); } sprintf(filename, "./"); strncat(filename,argv[4], strlen(argv[4])); fp=fopen(filename, "wb"); if(fp==NULL){ close(csock); exit(0); } if (recv(csock, (char *)&filesize, sizeof(filesize),0)<0){ close(csock); exit(0); } while(filesize>0){ readed=recv(csock, buf, filesize, 0); //receive characters and write to new file if(readed<0){ close(csock); exit(0); } else{ fwrite(buf, 1, readed, fp); } filesize-=readed; } fclose(fp); printf("============End Download!\n"); } else printf("Unproper Command\n"); close(csock); exit(0); }
C
#include <stdio.h> int main(void) { printf("Hello\tWorld!\n"); printf("kuruC\ttanoC\n"); printf("%d+%d=%d円\n",200,100,200+100); printf("%f\n", 10.0/3.0); int a = 40; //変数宣言は本来先頭でないと動かないが、C99やC++では動く int b = 13; int division = a / b; // 四捨五入を行うと、商×割る数、の逆計算を行ったときに、 // その結果が、元の割られる数よりも大きいという矛盾が生じ、 // 計算ミスの元となるため、切り捨てにしている。 int quotient = a % b; printf("%d...%d",division,quotient); return 0; }
C
#ifndef LAB_8_C #define LAB_8_C #include "functions.h" void counting_sort (int *arr, int *counters, int len, int min, int max) { int i = 0; for (i = 0; i < len; i++) { counters[arr[i]]++; } int j = 0, k = 0; for (i = min; i < max + 1; i++) { for (j = 0; j < counters[i]; j++) { arr[k] = i; k++; } } } #endif
C
#include <stdarg.h> #include <stdio.h> /** * print_numbers - Prints numbers, followed by a new line. Varying amount of * numbers may be passed. * @separator: The string that will be printed in between numbers. * @n: The numbers of arguments passed after n. * * Return: Void. */ void print_numbers(const char *separator, const unsigned int n, ...) { unsigned int i; va_list nums; if (n == 0) { printf("\n"); return; } va_start(nums, n); for (i = 0; i < n; i++) { printf("%d", va_arg(nums, int)); if (separator && i < n - 1) printf("%s", separator); } printf("\n"); va_end(nums); }
C
/* Group 27 Venkat Nalla Siddartha Reddy 2016A7PS0030P Arnav Sailesh 2016A7PS0054P Gunraj Singh 2016A7PS0085P Aashish Singh 2016A7PS0683P */ #include "interface.h" #include "symbol_table.h" #include "ast.h" #include "error_handler.h" #include <string.h> // Function to initialize symbol table SymbolTable* initializeSymbolTable(int numberSlots, Scope scope) { SymbolTable* st = (SymbolTable*)malloc(sizeof(SymbolTable)); st->SCOPE = scope; st->NUMBER_SLOTS = numberSlots; st->SYMBOL_SLOTS = (SymbolEntry**)malloc(st->NUMBER_SLOTS*sizeof(SymbolEntry)); st->CURRENT_OFFSET = 0; st->parent = NULL; return st; } // Hash function which hashes according to the lexeme int symbolHashFunction(SymbolTable* st ,char* str) { /* Hash function djb2 and mod */ unsigned long hash = 5381; int c; while (c = *str++) hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ return (hash%st->NUMBER_SLOTS); } // Create a symbol entry SymbolEntry* createSymbolEntry(Token* symbolToken,SymbolLabel symbolLabel) { SymbolEntry* symbolEntry = (SymbolEntry*)malloc(sizeof(SymbolEntry)); symbolEntry->SYMBOL_TOKEN = symbolToken; symbolEntry->SYMBOL_LABEL = symbolLabel; symbolEntry->next = NULL; return symbolEntry; } // Function to add a symbol entry to linked list of entires SymbolEntry* addEntryToList(SymbolEntry* list, SymbolEntry* s) { // Case when list is empty if(list == NULL) return s; // Case when list is not empty s->next = list; return s; } // Add symbol entry to symbol table void addSymbolEntry(SymbolTable* st, SymbolEntry* entry,ErrorList* els) { // Check if the entry already exists in the table or not SymbolEntry* existingEntry = lookupSymbolEntry(st,entry->SYMBOL_TOKEN); // Case when the entry exists in the current table, throw error and return if(existingEntry != NULL) { throwMultipleDefinitionsError(entry->SYMBOL_TOKEN,els); return; } // Case when the entry does not exist in the current table else { // If the current table is the global table, then no clashes observed // Continue with installing the entry if(st->parent == NULL) { ; } // If the current table is a scoped table, then check the global table for any clashes else { SymbolEntry* existingGlobalEntry = lookupSymbolEntry(st->parent,entry->SYMBOL_TOKEN); // If there is a global entry, then throw error if(existingGlobalEntry != NULL) { throwClashingGlobalDefinitionError(entry->SYMBOL_TOKEN,els); return; } // No clashes in the global table as well, continue with installing the entry else { ; } } } // To be done in a separate pass // // Set the identifier of the entry to the current identifier // entry->SYMBOL_OFFSET = st->CURRENT_OFFSET; // // Increment current identifier of table // // st->CURRENT_OFFSET++; int hashIndex = symbolHashFunction(st,entry->SYMBOL_TOKEN->LEXEME); st->SYMBOL_SLOTS[hashIndex] = addEntryToList(st->SYMBOL_SLOTS[hashIndex],entry); } // Searches for a symbol entry in the list which has the same lexeme as the token provided SymbolEntry* searchSymbolEntry(SymbolEntry* ls, Token* token) { SymbolEntry* trav = ls; while(trav != NULL) { // If found return pointer to entry if(strcmp(trav->SYMBOL_TOKEN->LEXEME,token->LEXEME) == 0) return trav; trav = trav->next; } // Return NULL otherwise return NULL; } // Searches the symbol table for an entry which has the same lexeme as the provided token // If a match is not found in the current table, it searches the global table SymbolEntry* lookupSymbolEntry(SymbolTable* st, Token* token) { // Hash according to the lexeme present in the token int hashIndex = symbolHashFunction(st,token->LEXEME); // Search in the slot SymbolEntry* entry = searchSymbolEntry(st->SYMBOL_SLOTS[hashIndex],token); // Case when there is no entry found in the table if(entry == NULL) { // Check the global table (if the current table is a scoped table) if(st->parent != NULL) { return lookupSymbolEntry(st->parent,token); } // If the table was itself the global table return NULL else return NULL; } // Case when the entry is found else return entry; } void constructSymbolTableHelper(ASTNode* node, SymbolTable* st,ErrorList* els) { // Case when we have reached NULL if(node == NULL) return; Label nodeLabel = node->LABEL; switch(nodeLabel) { case astProgram: { // Global table is set for astProgram node->SCOPED_TABLE = st; break; } case astFunction: { SymbolEntry* function = createSymbolEntry(node->AST_NODE_TYPE.AST_FUNCTION.FUNCTION_TOKEN,symbolFunction); addSymbolEntry(st,function,els); // Create new table for the function function->SYMBOL_ENTRY_TYPE.FUNCTION_ENTRY.SCOPED_TABLE = initializeSymbolTable(SYMBOL_TABLE_SLOTS,node->AST_NODE_TYPE.AST_FUNCTION.FUNCTION_TOKEN->LEXEME); // Set the scope of the new table as the function function->SYMBOL_ENTRY_TYPE.FUNCTION_ENTRY.SCOPED_TABLE->SCOPE = node->AST_NODE_TYPE.AST_FUNCTION.FUNCTION_TOKEN->LEXEME; // Set the function's scoped symbol table's parent as the main symbol table function->SYMBOL_ENTRY_TYPE.FUNCTION_ENTRY.SCOPED_TABLE->parent = st; // Set the scope of this node to the new table created node->SCOPED_TABLE = function->SYMBOL_ENTRY_TYPE.FUNCTION_ENTRY.SCOPED_TABLE; // For all children under astFunction we should populate the new table st = function->SYMBOL_ENTRY_TYPE.FUNCTION_ENTRY.SCOPED_TABLE; break; } case astInputParams: { // Get the parent function node ASTNode* functionNode = node->parent; // Find the entry of the function definition in the symbol table SymbolEntry* functionEntry = lookupSymbolEntry(st->parent,functionNode->AST_NODE_TYPE.AST_FUNCTION.FUNCTION_TOKEN); functionEntry->SYMBOL_ENTRY_TYPE.FUNCTION_ENTRY.NUMBER_INPUT_PARAMS = node->CHILDREN_COUNT; functionEntry->SYMBOL_ENTRY_TYPE.FUNCTION_ENTRY.INPUT_TYPES = (Token**)malloc(sizeof(Token*)*functionEntry->SYMBOL_ENTRY_TYPE.FUNCTION_ENTRY.NUMBER_INPUT_PARAMS); int index = 0; // Get children (The IDs constituting the input params of the node) ASTNode* trav = node->children; while(trav != NULL) { if(trav->LABEL != astId) { printf("Child of astInputParams detected not be an astIdNode in the symbol table construction phase , not correct\n"); } Token* dataType = trav->AST_NODE_TYPE.AST_ID.DATA_TYPE; Token* variable = trav->AST_NODE_TYPE.AST_ID.ID; // Create entry SymbolEntry* entry = createSymbolEntry(variable,symbolParameter); // Set data type entry->SYMBOL_ENTRY_TYPE.PARAMETER_ENTRY.DATA_TYPE = dataType; // Set input parameter or output parameter entry->SYMBOL_ENTRY_TYPE.PARAMETER_ENTRY.IS_INPUT = 1; addSymbolEntry(st,entry,els); functionEntry->SYMBOL_ENTRY_TYPE.FUNCTION_ENTRY.INPUT_TYPES[index] = dataType; trav = trav->next; index++; } node->SCOPED_TABLE = st; break; } case astOutputParams: { ASTNode* functionNode = node->parent; // Find the entry of the function definition in the symbol table SymbolEntry* functionEntry = lookupSymbolEntry(st->parent,functionNode->AST_NODE_TYPE.AST_FUNCTION.FUNCTION_TOKEN); functionEntry->SYMBOL_ENTRY_TYPE.FUNCTION_ENTRY.NUMBER_OUTPUT_PARAMS = node->CHILDREN_COUNT; functionEntry->SYMBOL_ENTRY_TYPE.FUNCTION_ENTRY.OUTPUT_TYPES = (Token**)malloc(sizeof(Token*)*functionEntry->SYMBOL_ENTRY_TYPE.FUNCTION_ENTRY.NUMBER_OUTPUT_PARAMS); int index = 0; ASTNode* trav = node->children; while(trav != NULL) { if(trav->LABEL != astId) { printf("Child of astOutputParams detected not be an astIdNode in the symbol table construction phase , not correct\n"); } Token* dataType = trav->AST_NODE_TYPE.AST_ID.DATA_TYPE; Token* variable = trav->AST_NODE_TYPE.AST_ID.ID; // Create entry SymbolEntry* entry = createSymbolEntry(variable,symbolParameter); // Set data type entry->SYMBOL_ENTRY_TYPE.PARAMETER_ENTRY.DATA_TYPE = dataType; // Set input parameter or output parameter entry->SYMBOL_ENTRY_TYPE.PARAMETER_ENTRY.IS_INPUT = 0; addSymbolEntry(st,entry,els); functionEntry->SYMBOL_ENTRY_TYPE.FUNCTION_ENTRY.OUTPUT_TYPES[index] = dataType; trav = trav->next; index++; } node->SCOPED_TABLE = st; break; } case astDatatype: { break; } case astStmts: { node->SCOPED_TABLE = st; break; } case astTypeDefintion: { // Create symbolEntry for corresponding RECORDID SymbolEntry* typeDefinition = createSymbolEntry(node->AST_NODE_TYPE.AST_TYPE_DEFINITION.RECORD_ID,symbolRecord); // Get the number of field definitions beneath this type definition node and store it int numberChildren = node->CHILDREN_COUNT; typeDefinition->SYMBOL_ENTRY_TYPE.RECORD_ENTRY.NUMBER_FIELDS = numberChildren; // Allocate space for corresponding number of fields typeDefinition->SYMBOL_ENTRY_TYPE.RECORD_ENTRY.DATA_TYPE = (Token**)malloc(numberChildren*sizeof(Token*)); typeDefinition->SYMBOL_ENTRY_TYPE.RECORD_ENTRY.FIELDS = (Token**)malloc(numberChildren*sizeof(Token*)); // Traverse all children of type definition which should be field definition node ASTNode* trav = node->children; int count = 0; int calculateOffset = 0; while(trav != NULL) { if(trav->LABEL != astFieldDefinition) { printf("Type definition node considering a node other than a field definition, not correct!\n"); } // Construct data type in cartesian representation typeDefinition->SYMBOL_ENTRY_TYPE.RECORD_ENTRY.DATA_TYPE[count] = trav->AST_NODE_TYPE.AST_FIELD_DEFINITION.DATA_TYPE; typeDefinition->SYMBOL_ENTRY_TYPE.RECORD_ENTRY.FIELDS[count] = trav->AST_NODE_TYPE.AST_FIELD_DEFINITION.FIELD_ID; if(typeDefinition->SYMBOL_ENTRY_TYPE.RECORD_ENTRY.DATA_TYPE[count]->TOKEN_NAME == TK_INT) calculateOffset += 2; else if(typeDefinition->SYMBOL_ENTRY_TYPE.RECORD_ENTRY.DATA_TYPE[count]->TOKEN_NAME == TK_REAL) calculateOffset += 4; else { // TODO REPORT ERROR IF IT IS AN ERROR, ASK MA'AM ; } count++; trav = trav->next; } // Set the offset in the entry typeDefinition->SYMBOL_ENTRY_TYPE.RECORD_ENTRY.TOTAL_OFFSET = calculateOffset; // Install entry in the global symbol table addSymbolEntry(st->parent,typeDefinition,els); node->SCOPED_TABLE = st->parent; break; } case astFieldDefinition: { // As field definition will always belong to a record entry which is always in a global table node->SCOPED_TABLE = st->parent; break; } case astDeclaration: { // Create a dummy entry which will be populated in the code below SymbolEntry* variable = createSymbolEntry(NULL,symbolVariable); int isGlobal = node->AST_NODE_TYPE.AST_DECLARATION.IS_GLOBAL; ASTNode* trav = node->children; if(trav != NULL) { // Each child must be an astID node if(trav->LABEL != astId) { printf("Declaration not involving an astId node, not correct\n"); } variable->SYMBOL_ENTRY_TYPE.VARIABLE_ENTRY.DATA_TYPE = trav->AST_NODE_TYPE.AST_ID.DATA_TYPE; variable->SYMBOL_TOKEN = trav->AST_NODE_TYPE.AST_ID.ID; trav = trav->next; } // If it is a global variable , add the entry to the global symbol table if(isGlobal == 1) { addSymbolEntry(st->parent,variable,els); node->SCOPED_TABLE = st->parent; } // Else add the entry to the function's scoped symbol table else { addSymbolEntry(st,variable,els); node->SCOPED_TABLE = st; } break; } case astAssignmentStmt: { node->SCOPED_TABLE = st; break; } case astFunCallStmt: { // Check if the function has been defined prior to being called // Check for a function definition SymbolEntry* functionEntry = lookupSymbolEntry(st->parent,node->AST_NODE_TYPE.AST_FUNCTION.FUNCTION_TOKEN); if(functionEntry == NULL) { throwMissingFunctionDefinitionError(node->AST_NODE_TYPE.AST_FUNCTION.FUNCTION_TOKEN,els); } node->SCOPED_TABLE = st; break; } case astIterativeStmt: { node->SCOPED_TABLE = st; break; } case astConditionalStmt: { node->SCOPED_TABLE = st; break; } case astElsePart: { node->SCOPED_TABLE = st; break; } case astIOStmtRead: { node->SCOPED_TABLE = st; break; } case astIOStmtWrite: { node->SCOPED_TABLE = st; break; } case astReturnStmt: { node->SCOPED_TABLE = st; break; } case astInputArgs: { node->SCOPED_TABLE = st; break; } case astOutputArgs: { node->SCOPED_TABLE = st; break; } case astArithmeticExpression: { // No installation needed beyond this node node->SCOPED_TABLE = st; break; } case astBooleanExpression: { // No installaton needed beyond this node node->SCOPED_TABLE = st; break; } case astId: { // Redundant as we will be handling input and output params at their respective places // In case the ID is part of input parameters or output parameters, it needs to be installed in the symbol table // if(node->parent->LABEL == astInputParams || node->parent->LABEL == astOutputParams) { // // Input and output parameters must be established in this scope // Token* dataType = node->AST_NODE_TYPE.AST_ID.DATA_TYPE; // Token* variable = node->AST_NODE_TYPE.AST_ID.ID; // // Case when the data type is a primitive type // SymbolEntry* entry = createSymbolEntry(variable,symbolParameter); // // Set data type // entry->SYMBOL_ENTRY_TYPE.PARAMETER_ENTRY.DATA_TYPE = dataType; // // Set input parameter or output parameter // entry->SYMBOL_ENTRY_TYPE.PARAMETER_ENTRY.IS_INPUT = ((node->parent->LABEL == astInputParams) ? 1 : 0); // addSymbolEntry(st,entry,els); // } // Adjust scope for this node node->SCOPED_TABLE = st; break; } case astNum: { node->SCOPED_TABLE = st; break; } case astRnum: { node->SCOPED_TABLE = st; break; } } // Inform group members that this code is reachable only if the above swith case does not return, which is the case in some cases // Traverse children ASTNode* trav = node->children; while(trav != NULL) { constructSymbolTableHelper(trav,st,els); trav = trav->next; } } // Creates the symbol table by using the declarations and function definitions to populate slots in the appropriate table // Also populates the scope field of the AST nodes, so that a node's scoped table can directly be referred in the next step SymbolTable* constructSymbolTable(AST* ast,ErrorList* els) { // Initialize symbol table with number of slots and scope as global SymbolTable* st = initializeSymbolTable(SYMBOL_TABLE_SLOTS,"global"); constructSymbolTableHelper(ast->root,st,els); return st; }
C
#include <stdio.h> #include <stdlib.h> // This program sets up the ADC int main(void) { char path[35] = "/sys/devices/bone_capemgr.9/slots"; printf("Setting up ADC..."); FILE *fd = fopen(path, "w"); if (fd == NULL) { fprintf(stderr, "Could not open file: %s\n", path); return EXIT_FAILURE; } fprintf(fd, "%s", "cape-bone-iio"); fclose (fd); printf("done\n"); return EXIT_SUCCESS; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* check_valid.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ahandsom <ahandsom@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/15 16:06:52 by ahandsom #+# #+# */ /* Updated: 2019/11/30 18:00:16 by ahandsom ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" void ft_error(int error) { if (err == 0) ft_putstr("\n"); else if (err == -1) ft_putstr("\n"); else if (err == 1) ft_putstr("\n"); else if (err == 2) ft_putstr("\n"); exit(1); } static int check(char **tetramino, int i, int j) { int start; start = 0; if ((j + 1) < 4) if (tetramino[i][j + 1] == '#') start++; if ((i + 1) < 4) if (tetramino[i + 1][j] == '#') start++; if ((i - 1) >= 0) if (tetramino[i - 1][j] == '#') start++; if ((j - 1) >= 0) if(tetramino[i][j - 1] == '#') start++; return (start); } static void check_tetr(char **tetramino) { int i; int j; int side; i = 0; side = 0; while (i < 4) { j = 0; while (j < 4) { if(tetramino[i][j] == '#') side = side + check(tetramino, i, j); j++; } i++; } if (side != 8 && side != 6) ft_error(1); } static void valid_tetr(char **tetramino) { int i; int j; int start; i = 0; start = 0; while (i < 4) { j = 0; while (j < 4) { if(tetramino[i][j] == '#') start++; if (tetramino[i][j] != '.' && tetramino[i][j] != '#') ft_error(1); j++; } i++; } if (start != 4) ft_error(1); } void check_full_tetr(t_etramino *head) { while (head) { valid_tetr(head->tetramino); check_tetr(head->tetramino); head = head->next; } } /* int countchars(char *buff) { int i; int count; count = 0; i = 0; while(i < 19) { if (buff[i] && buff[i] != '\n' && buff[i] != '.' && buff[i] != '#') return(0); if (buff[i] == '\n' && ((i + 1) % 5 != 0)) return(0); if (buff[i] == '#') count++; i++; } if(!buff[i] || buff[i] != '\n') return(0); return (count); } int valid_tetrominoes(char *buf) { } */
C
#include <stdlib.h> #include <stdio.h> #include "expr.h" // build and print expression objects void main(int argc, char *argv[]) { // create expression 3 + 4 EXPR *e1 = expr_create_num(3); EXPR *e2 = expr_create_num(4); EXPR *e = expr_create_sum(e1, e2); expr_print(e); printf("\n"); // create expression 3 + 4 - 1 // YOUR CODE HERE e1 = expr_create_num(3); e2 = expr_create_num(4); EXPR *e3 = expr_create_num(1); e = expr_create_diff(expr_create_sum(e1, e2), e3); expr_print(e); printf("\n"); exit(EXIT_SUCCESS); }
C
// Cuff: 查拳、燕青拳、太祖長拳、六合拳、少林長拳、八極拳 // Claw: 大擒拿手、小擒拿手、鷹爪功、虎爪手 // Strike:八卦掌、武當綿掌、遊身八卦掌 #include <ansi.h> inherit SKILL; string martialtype() { return "skill"; } mapping *action = ({ ([ "action": "$N單手上抬,一招查拳的「沖天炮」,對準$n的$l猛擊下去", "force" : 420, "attack": 130, "dodge" : 45, "parry" : 45, "damage": 80, "damage_type": "砸傷" ]), ([ "action": "$N一招燕青拳的「白鶴亮翅」,身子已向左轉成弓箭步,兩臂向後成鈎手,呼\n" "的一聲輕響,反擊$n$l", "force" : 512, "attack": 145, "dodge" : 10, "parry" : 75, "damage": 85, "damage_type": "瘀傷" ]), ([ "action": "$N往後一縱,施展小擒拿手的手法,雙手對着$n$l處的關節直直抓去", "force" : 410, "attack": 170, "dodge" : 35, "parry" : 35, "damage": 178, "damage_type": "抓傷" ]), ([ "action": "$N左拳拉開,右拳轉臂回擾,一招少林的少林長拳突然擊出,帶着許許風聲貫向$n", "force" : 460, "attack": 150, "dodge" : 62, "parry" : 60, "damage": 90, "lvl" : 30, "damage_type": "瘀傷" ]), ([ "action": "只見$N運足氣力,使出八極拳中的「八極翻手式」,雙掌對着$n的$l平平攻去", "force" : 480, "attack": 160, "dodge" : 40, "parry" : 40, "damage": 85, "damage_type": "瘀傷" ]), ([ "action": "$N大喝一聲,左手往$n身後一抄,右掌往$n反手擊去,正是八卦掌的招式", "force" : 510, "attack": 155, "dodge" : 30, "parry" : 30, "damage": 95, "damage_type": "瘀傷" ]), ([ "action": "$N提氣遊走,左手護胸,右手一招遊身八卦掌的「遊空探爪」,迅速拍向$n$l", "force" : 510, "attack": 150, "dodge" : 45, "parry" : 45, "damage": 110, "damage_type": "瘀傷" ]), ([ "action": "只見$N拉開架式,雙手將武當派的綿掌使得密不透風,招招不離$n的$l", "force" : 460, "attack": 155, "dodge" : 160, "parry" : 160, "damage": 105, "damage_type": "瘀傷" ]), ([ "action": "$N突然飛身一躍而起,雙手握做爪狀,朝着$n的$l猛然抓去,凜然是鷹爪功的招式", "force" : 470, "attack": 185, "dodge" : 60, "parry" : 60, "damage": 155, "damage_type": "抓傷" ]), ([ "action": "只見$N身形一矮,雙手翻滾,合抱為圈,一招太極拳「雲手」直拿$n的$l", "force" : 350, "attack": 90, "dodge" : 210, "parry" : 230, "damage": 65, "damage_type": "瘀傷" ]), ([ "action": "只見$N跨前一步,左手一記大擒拿手護住上盤,右手順勢一帶,施一招摔碑手擊向$n", "force" : 520, "attack": 155, "dodge" : 41, "parry" : 37, "damage": 103, "damage_type": "瘀傷" ]), ([ "action": "$N一個轉身,趁$n不備,反手將$n牢牢抱住猛的朝地面摔去,竟然是蒙古的摔角招式", "force" : 560, "attack": 185, "dodge" : 75, "parry" : 60, "damage": 125, "damage_type": "摔傷" ]), }); string main_skill() { return "baihua-cuoquan"; } mapping sub_skills = ([ "cha-quan" : 100, // 查拳 "baji-quan" : 100, // 八極拳 "changquan" : 100, // 太祖長拳 "liuhe-quan" : 100, // 六合拳法 "yanqing-quan" : 100, // 燕青拳 "shaolin-quan" : 100, // 少林長拳 "bagua-zhang" : 100, // 八卦掌 "bazhen-zhang" : 100, // 八陣八卦掌 "wudang-zhang" : 100, // 武當棉掌 "huzhao-shou" : 100, // 虎爪手 "yingzhao-shou" : 100, // 鷹爪手 "xiao-qinna" : 100, // 小擒拿手 "da-qinna" : 100, // 大擒拿手 ]); int get_ready(object me) { return 1; } int get_finish(object me) { object ob; if( query("int", me)<28 ) { tell_object(me, "你演練完畢,覺得各種拳法毫無牽連,看來依你的悟" "性,無法貫通百花錯拳。\n"); return 0; } if( query("dex", me)<23 ) { tell_object(me, "你演練完畢,只覺自己的身法靈動性太差,無法貫通" "百花錯拳。\n"); return 0; } if ((int)me->query_skill("unarmed", 1) < 150) { tell_object(me, "你覺得自己的拳腳功夫還有待提高,暫且無法貫通百" "花錯拳。\n"); return 0; } if (me->query_skill("force") < 250) { tell_object(me, "你覺得自己內功火候尚淺,無法貫通百花錯拳。\n"); return 0; } if (me->query_skill("martial-cognize", 1) < 80) { tell_object(me, "你覺得自己武學修養太低,無法貫通百花錯拳。\n"); return 0; } if( query("max_neili", me)<3000 ) { tell_object(me, "你覺得自己真氣不繼,無法貫通百花錯拳。\n"); return 0; } if (random(10) < 7) { tell_object(me, "你覺得有所感悟,或許再演練一次就能融會貫通。\n"); return 0; } tell_object(me, HIY "你一氣呵成,將各家各派的數十種拳法連續施展演練了一" "片,突然間心中頓悟,通曉了百花錯拳的奧\n妙精髓,融" "會貫通各家拳術中的精微之處,匯百家之長而成了這套百" "花錯拳。\n" NOR); return 1; } mapping query_sub_skills() { return sub_skills; } int valid_learn(object me) { if( query_temp("weapon", me) || query_temp("secondary_weapon", me) ) return notify_fail("練百花錯拳必須空手。\n"); if( query("int", me)<28 ) return notify_fail("你的先天悟性太差,無法學習百花錯拳。\n"); if( query("dex", me)<23 ) return notify_fail("你的先天身法孱弱,無法學習百花錯拳。\n"); if( query("max_neili", me)<3000 ) return notify_fail("你的內力修為遠遠不足,難以練習百花錯拳。\n"); if ((int)me->query_skill("force") < 250) return notify_fail("你的內功火候尚淺,無法學習百花錯拳。\n"); if ((int)me->query_skill("unarmed", 1) < 150) return notify_fail("你的拳腳根基有限,無法體會百花錯拳要詣。\n"); if ((int)me->query_skill("cuff", 1) < 100) return notify_fail("你的拳法根基有限,無法體會百花錯拳要詣。\n"); if ((int)me->query_skill("claw", 1) < 100) return notify_fail("你的爪法根基有限,無法體會百花錯拳要詣。\n"); if ((int)me->query_skill("strike", 1) < 100) return notify_fail("你的掌法根基有限,無法體會百花錯拳要詣。\n"); if ((int)me->query_skill("unarmed", 1) < (int)me->query_skill("baihua-cuoquan", 1)) return notify_fail("你的拳腳根基火候不足,無法領會更高深的百花錯拳。\n"); return 1; } int valid_enable(string usage) { return usage=="unarmed" || usage=="parry"; } int valid_combine(string combo) { return combo=="benlei-shou"; } string query_skill_name(int level) { int i; for(i = sizeof(action); i > 0; i--) if(level >= action[i-1]["lvl"]) return action[i-1]["skill_name"]; } mapping query_action(object me, object weapon) { /* d_e=dodge_effect p_e=parry_effect f_e=force_effect m_e=damage_effect */ int d_e1 = 25; int d_e2 = 50; int p_e1 = -30; int p_e2 = -15; int f_e1 = 130; int f_e2 = 280; int i, lvl, seq, ttl = sizeof(action); lvl = (int) me->query_skill("baihua-cuoquan", 1); for(i = ttl; i > 0; i--) if(lvl > action[i-1]["lvl"]) { seq = i; /* 獲得招數序號上限 */ break; } seq = random(seq); /* 選擇出手招數序號 */ return ([ "action" : action[seq]["action"], "dodge" : d_e1 + (d_e2 - d_e1) * seq / ttl, "parry" : p_e1 + (p_e2 - p_e1) * seq / ttl, "force" : f_e1 + (f_e2 - f_e1) * seq / ttl, "damage_type" : "瘀傷", ]); } int learn_bonus() { return 20; } int practice_bonus() { return 15; } int success() { return 15; } int power_point() { return 1.0; } int practice_skill(object me) { if( query("qi", me)<100 ) return notify_fail("你現在手足痠軟,休息一下再練吧。\n"); if( query("neili", me)<150 ) return notify_fail("你的內力不夠了。\n"); me->receive_damage("qi", 80); addn("neili", -120, me); return 1; } /* void skill_improved(object me) { int i; string *sub_skillnames; sub_skillnames = keys(sub_skills); for (i = 0; i < sizeof(sub_skillnames); i++) me->delete_skill(sub_skillnames[i]); } */ mixed hit_ob(object me, object victim, int damage_bonus) { int lvl; mixed result; lvl = me->query_skill("baihua-cuoquan", 1); if (damage_bonus < 150 || lvl < 150) return 0; if (damage_bonus / 6 > victim->query_con()) { victim->receive_wound("qi", (damage_bonus - 100) / 3, me); result = ([ "damage" : damage_bonus ]); result += ([ "msg" : HIR "只聽$n" HIR "前胸「咔嚓」一聲脆響,竟像是" "肋骨斷折的聲音。\n" NOR ]); return result; } } string perform_action_file(string action) { return __DIR__"baihua-cuoquan/" + action; } int help(object me) { write(HIM"\n百花錯拳:"NOR"\n"); write(@HELP 百花錯拳是天池怪俠袁士霄所創。袁士霄痛悔當年錯過大好因緣, 以世上萬物多錯,創出此拳。此拳取眾家之長,往往似是而非,誘敵 入彀,故稱錯拳。 紅花會總舵主陳家洛為袁士霄入室弟子,得傳此拳。 學習要求: 紅花神功20級 內力修為100 HELP ); return 1; }
C
#include"stdio.h" int main(int argc, char *argv[]) { int n; scanf("%d",&n); static num[3]; int a,b,c; int counta=0,countb=0,i; for(i=0;i<n;i++) { scanf("%d %d %d",&a,&b,&c); num[a]++; if(a==1) { counta+=b; } else countb+=b; } if(counta>=(num[1])*5 ) printf("LIVE"); else printf("DEAD"); printf("\n"); if(countb>=(num[2])*5) printf("ALIVE"); else printf("DEAD"); return 0; }
C
#include <stdio.h> void print_r(int a[],int n){ int i; for (i = 0; i < n; ++i) { printf("%d\t",a[i]); } printf("\n"); } void merge(int a[],int temp[], int start, int mid, int end) { int first_end, second_start, temp_pos=0; first_end = mid; second_start = mid + 1; int size = end - start+1; while((start <= first_end) && (second_start <= end)){ if (a[start]<=a[second_start]) { temp[temp_pos] = a[start]; start++; } else{ temp[temp_pos] = a[second_start]; second_start++; } temp_pos++; } while(start <= first_end){ temp[temp_pos]=a[start]; temp_pos++; start++; } while(second_start <= end){ temp[temp_pos]=a[second_start]; temp_pos++; second_start++; } int i; for (i = 0; i < size; ++i) { a[i] = temp[i]; } } void mergesort(int a[], int temp[], int start, int end){ if (end > start) { int mid = (start+end)/2; mergesort(a,temp,0,mid); mergesort(a,temp,mid+1,end); merge(a,temp, 0,mid, end); } } int main(){ int i=0,n, a[100],temp_n, temp[100]; printf("\nEnter the number of elements:\n"); scanf("%d",&n); temp_n = n; printf("Enter the %d elements:\n", n); while(temp_n--){ scanf("%d",&a[i++]); } mergesort(a,temp,0,n-1); printf("\nSorted Array:\n"); print_r(a,n); return 0; }
C
/* * Helper for single-precision routines which calculate exp(x) and do not * need special-case handling * * Copyright (c) 2019-2023, Arm Limited. * SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception */ #ifndef PL_MATH_V_EXPF_INLINE_H #define PL_MATH_V_EXPF_INLINE_H #include "v_math.h" static const struct data { float32x4_t poly[5]; float32x4_t shift, invln2, ln2_hi, ln2_lo; } data = { /* maxerr: 1.45358 +0.5 ulp. */ .poly = { V4 (0x1.0e4020p-7f), V4 (0x1.573e2ep-5f), V4 (0x1.555e66p-3f), V4 (0x1.fffdb6p-2f), V4 (0x1.ffffecp-1f) }, .shift = V4 (0x1.8p23f), .invln2 = V4 (0x1.715476p+0f), .ln2_hi = V4 (0x1.62e4p-1f), .ln2_lo = V4 (0x1.7f7d1cp-20f), }; #define ExponentBias v_u32 (0x3f800000) /* asuint(1.0f). */ #define C(i) d->poly[i] static inline float32x4_t v_expf_inline (float32x4_t x) { const struct data *d = ptr_barrier (&data); /* Helper routine for calculating exp(x). Copied from v_expf.c, with all special-case handling removed - the calling routine should handle special values if required. */ /* exp(x) = 2^n (1 + poly(r)), with 1 + poly(r) in [1/sqrt(2),sqrt(2)] x = ln2*n + r, with r in [-ln2/2, ln2/2]. */ float32x4_t n, r, z; z = vfmaq_f32 (d->shift, x, d->invln2); n = vsubq_f32 (z, d->shift); r = vfmsq_f32 (x, n, d->ln2_hi); r = vfmsq_f32 (r, n, d->ln2_lo); uint32x4_t e = vshlq_n_u32 (vreinterpretq_u32_f32 (z), 23); float32x4_t scale = vreinterpretq_f32_u32 (vaddq_u32 (e, ExponentBias)); /* Custom order-4 Estrin avoids building high order monomial. */ float32x4_t r2 = vmulq_f32 (r, r); float32x4_t p, q, poly; p = vfmaq_f32 (C (1), C (0), r); q = vfmaq_f32 (C (3), C (2), r); q = vfmaq_f32 (q, p, r2); p = vmulq_f32 (C (4), r); poly = vfmaq_f32 (p, q, r2); return vfmaq_f32 (scale, poly, scale); } #endif // PL_MATH_V_EXPF_INLINE_H