language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <assert.h> #include <unistd.h> #include <stdio.h> #include "disastrOS.h" #include "disastrOS_syscalls.h" #include "disastrOS_semaphore.h" #include "disastrOS_semdescriptor.h" void internal_semOpen(){ // do stuff :) int semnum = running->syscall_args[0]; if(semnum < 0){ // semnum non valido disastrOS_debug("id non valido"); running->syscall_retvalue = DSOS_ESEMOPEN; return; } disastrOS_debug("cerco semaforo con id: %d (se esiste)\n", semnum); Semaphore* sem = SemaphoreList_byId(&semaphores_list, semnum); if(sem == NULL){ // il semaforo non esiste e deve essere allocato disastrOS_debug("alloco semaforo con id: %d\n", semnum); sem = Semaphore_alloc(semnum, 1); //controllo se il semaforo è stato correttamente allocato if(sem == NULL) { disastrOS_debug("allocazione del semaforo fallita\n"); running->syscall_retvalue = DSOS_ESEMOPEN; return; } disastrOS_debug("allocazione del semaforo riuscita\n"); List_insert(&semaphores_list, semaphores_list.last, (ListItem*) sem); } disastrOS_debug("allocazione del semaforo riuscita\n"); // alloco il descrittore del semaforo per il processo corrente SemDescriptor* des = SemDescriptor_alloc(running->last_sem_fd, sem, running); if(! des){ running->syscall_retvalue = DSOS_ESEMNOFD; return; } disastrOS_debug("Descrittore correttamente creato\n"); running->last_sem_fd++; SemDescriptorPtr* sem_descptr = SemDescriptorPtr_alloc(des); List_insert(&running->sem_descriptors, running->sem_descriptors.last, (ListItem*) des); //aggiungo descrittore alla struct del semaforo des->ptr=sem_descptr; List_insert(&sem->descriptors, sem->descriptors.last, (ListItem*) sem_descptr); running->syscall_retvalue = semnum; return; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* format_unsigned.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mgrimes <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/12/12 18:38:16 by mgrimes #+# #+# */ /* Updated: 2016/12/12 18:38:19 by mgrimes ### ########.fr */ /* */ /* ************************************************************************** */ #include "libftprintf.h" char *str_toupper(char *str) { int i; i = 0; while (str[i]) { str[i] = ft_toupper(str[i]); i++; } return (str); } char *save_prefix(t_flag flags, char *n) { char *ans; int len; len = 0; if (!ft_strcmp(n, "0") || !flags.hash) return (""); if (flags.type == 'o' || flags.type == 'O' || flags.type == 'x' || flags.type == 'X') len++; if (flags.type == 'x' || flags.type == 'X') len++; ans = ft_strnew(len); if (flags.type == 'o' || flags.type == 'O' || flags.type == 'x' || flags.type == 'X') ans[0] = '0'; if (flags.type == 'x') ans[1] = 'x'; if (flags.type == 'X') ans[1] = 'X'; return (ans); } char *format_unsigned_2(char *str, t_flag flags, char *prefix) { if (flags.zero && !flags.minus) str = pad_and_free(str, flags.width - ft_strlen(prefix), '0'); str = ft_strjoin(prefix, str); if (!flags.zero || flags.minus) { if (!flags.minus) str = pad_and_free(str, flags.width, ' '); else str = pad_on_right(str, flags.width, ' '); } return (str); } char *format_unsigned(char *str, t_flag flags) { char *prefix; prefix = save_prefix(flags, str); if (flags.precision == 0 && !ft_strcmp(str, "0") && ((flags.type != 'o' && flags.type != 'O') || !flags.hash)) str = ""; if (flags.precision > ft_strlen(str)) str = pad_and_free(str, flags.precision, '0'); if (flags.width > ft_strlen(str)) str = format_unsigned_2(str, flags, prefix); else str = ft_strjoin(prefix, str); if (flags.type == 'X') str_toupper(str); return (str); }
C
//Basic Pong #include <xc.h> #include <stdio.h> #include <avr/io.h> #include <avr/interrupt.h> #include <stdlib.h> #include <unistd.h> #ifdef _SIMULATE_ #include "simAVRHeader.h" #endif //Task Struct typedef struct task { int state; unsigned long period; unsigned long elapsedTime; int (*TickFct)(int); } task; task tasks[1]; const unsigned short tasksNum = 1; const unsigned long tasksPeriodGCD = 30; const unsigned long periodMatrix = 30; //-------------------------------------- // LED Matrix Demo SynchSM // Period: 100 ms //-------------------------------------- enum Demo_States {shift}; int Demo_Tick(int state) { // Local Variables static unsigned char pattern = 0x80; // LED pattern - 0: LED off; 1: LED on static unsigned char row = 0xFE; // Row(s) displaying pattern. // 0: display pattern on row // 1: do NOT display pattern on row // Transitions switch (state) { case shift: break; default: state = shift; break; } // Actions switch (state) { case shift: if (row == 0xEF && pattern == 0x01) { // Reset demo pattern = 0x80; row = 0xFE; } else if (pattern == 0x01) { // Move LED to start of next row pattern = 0x80; row = (row << 1) | 0x01; } else { // Shift LED one spot to the right on current row pattern >>= 1; } break; default: break; } PORTC = pattern; // Pattern to display PORTD = row; // Row(s) displaying pattern return state; } //Timer Initialization volatile unsigned char TimerFlag = 0; void TimerISR() { unsigned char i; for (i = 0; i < tasksNum; ++i) { // Heart of the scheduler code if ( tasks[i].elapsedTime >= tasks[i].period ) { // Ready tasks[i].state = tasks[i].TickFct(tasks[i].state); tasks[i].elapsedTime = 0; } tasks[i].elapsedTime += tasksPeriodGCD; } TimerFlag = 1; } unsigned long _avr_timer_M = 1; unsigned long _avr_timer_cntcurr = 0; void TimerOn() { TCCR1B = 0x0B; OCR1A = 125; TIMSK1 = 0x02; TCNT1 = 0; _avr_timer_cntcurr = _avr_timer_M; SREG |= 0x80; } void TimerOff() { TCCR1B = 0x00; } ISR(TIMER1_COMPA_vect) { _avr_timer_cntcurr--; if (_avr_timer_cntcurr == 0) { TimerISR(); _avr_timer_cntcurr = _avr_timer_M; } } void TimerSet (unsigned long M) { _avr_timer_M = M; _avr_timer_cntcurr = _avr_timer_M; } int main(void) { DDRC = 0xFF; PORTC = 0x00; DDRD = 0xFF; PORTD = 0x00; unsigned char i = 0; tasks[i].state = shift; tasks[i].period = periodMatrix; tasks[i].elapsedTime = tasks[i].period; tasks[i].TickFct = &Demo_Tick; TimerSet(tasksPeriodGCD); TimerOn(); while(1) { while(!TimerFlag); TimerFlag = 0; } return 0; }
C
#include <stdio.h> #include <unistd.h> #include <netinet/in.h> #include "poll.h" #include "debug.h" #include "socket.h" #include "writen.h" #define BUFFSIZE 1024 #define UNUSED_PARAMS(x) (void)x void read_cb(poll_event_t * poll_event, poll_event_element_t * node, struct epoll_event ev) { UNUSED_PARAMS(poll_event); UNUSED_PARAMS(ev); /* NOTE: read is also invoked on accept and connect */ INFO("in read_cb"); char read_buf[BUFFSIZE]; int read_num; read_num = read(node->fd, read_buf, BUFFSIZE - 1); if (read_num > 0) { /* if we actually get data, print it and write back */ read_buf[read_num] = '\0'; /* null terminal */ fprintf(stdout, "received data: %s\n", read_buf); writen(node->fd, read_buf, read_num); } } void close_cb(poll_event_t * poll_event, poll_event_element_t * node, struct epoll_event ev) { UNUSED_PARAMS(ev); INFO("in close_cb"); /* close the socket, we are done with it */ poll_event_remove(poll_event, node->fd); } void accept_cb(poll_event_t * poll_event, poll_event_element_t * node, struct epoll_event ev) { UNUSED_PARAMS(ev); INFO("in accept_cb"); /* accept the connection */ struct sockaddr_in clt_addr; socklen_t clt_len = sizeof(clt_addr); int connfd = socket_accept(node->fd, (struct sockaddr *)&clt_addr, &clt_len); socket_set_non_blocking(connfd); fprintf(stdout, "got the socket %d\n", connfd); /* set flags to check */ uint32_t flags = EPOLLIN | EPOLLRDHUP; poll_event_element_t *p; /* add file descriptor to poll event */ poll_event_add(poll_event, connfd, flags, &p); /* set function callbacks */ p->read_callback = read_cb; p->close_callback = close_cb; } int timeout_cb(poll_event_t * poll_event) { /* just keep a count */ if (!poll_event->data) { /* no count initialised, then initialize it */ INFO("init timeout counter"); poll_event->data = calloc(1, sizeof(int)); } else { /* increment and print the count */ int *value = (int *)poll_event->data; *value += 1; LOG("time out number %d", *value); } return 0; } int main() { int sockfd; /* create tcp socket */ sockfd = socket_create_and_bind("1991"); socket_set_non_blocking(sockfd); socket_start_listening(sockfd); /* create a poll event object, with block indefinitely */ poll_event_t *pe = poll_event_new(-1); /* set timeout callback */ /* pe->timeout_callback = timeout_cb; */ poll_event_element_t *p; /* add sockfd to poll event */ poll_event_add(pe, sockfd, EPOLLIN, &p); /* set callbacks */ p->accept_callback = accept_cb; p->close_callback = close_cb; /* enable accept callback */ p->cb_flags |= ACCEPT_CB; /* start the event loop */ poll_event_loop(pe); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <ctype.h> #include <string.h> int main() { int dice1; int dice2; int try = 0; printf("press any button to roll 2 dice.\n"); srand(time(NULL)); while (1) { getch(); dice1 = (rand() % 6) + 1; dice2 = (rand() % 6) + 1; printf("You rolled %d-%d.\n", dice1, dice2); try++; if (dice1 == dice2){ printf("Grats! A double! "); break; } } printf("You rolled a double dice in %d tries.", try); getch(); return 0; }
C
/* ** EPITECH PROJECT, 2018 ** Test_criterion ** File description: ** Test de my_getfloat */ #include <criterion/criterion.h> #include <lib.h> #include "lib.h" Test(test_my_getfloat, Test_entry_NULL, .timeout = 0.5, .exit_code = 0) { cr_assert_eq(my_getfloat(NULL), 0); } Test(test_my_getfloat, Test_entry_1, .timeout = 0.5, .exit_code = 0) { cr_assert_float_eq(my_getfloat(" 10.02"), 10.02, 0.01); } Test(test_my_getfloat, Test_entry_2, .timeout = 0.5, .exit_code = 0) { cr_assert_float_eq(my_getfloat(" 10123.2123"), 10123.2123, 0.001); } Test(test_my_getfloat, Test_entry_MAX, .timeout = 0.5, .exit_code = 0) { cr_assert_float_eq(my_getfloat("-10123.2123"), -10123.2123, 0.001); }
C
#include <math.h> #include <stdio.h> int main() { float A=1; float s=2; float Prec; while (s>1) { A=A/2; s=1+A; /* printf("s = %12.17f A = %12.17f\n",s,A); */ } Prec = 2*A; /* printf("Precisao = %2.20f\n",Prec); */ printf("Precisao = %f\n",Prec); }
C
#include "types.h" #include "user.h" #include "x86.h" #define PGSIZE 4096 void thread_wrapper(void *arg) { struct thread_obj *obj = (struct thread_obj*)arg; (obj->func)(obj->arg); free(obj); exit(); } int thread_create(void (*start_routine)(void*), void* arg) { void *stack = malloc(PGSIZE * 2); if (!stack) return -1; if ((uint)stack % PGSIZE) { stack += PGSIZE - (uint)stack % PGSIZE; } struct thread_obj *obj = malloc(sizeof(struct thread_obj)); obj->func = start_routine; obj->arg = arg; return clone(thread_wrapper, obj, stack); } int thread_join(int pid) { int ustack = getustack(pid); if (ustack < 0) return -1; int ret_pid = join(pid); free((void*)ustack); return ret_pid; } void lock_init(lock_t* lock) { lock->locked = 0; } void lock_acquire(lock_t* lock) { // if (lock->locked) { // printf(1, "lock have been acuqired!"); // return; // } while(xchg(&lock->locked, 1) != 0) ; } void lock_release(lock_t* lock) { // if (!lock->locked) { // printf(1, "lock have been released!"); // return; // } xchg(&lock->locked, 0); } int holding(lock_t* lock) { return lock->locked; } void cv_wait(cond_t* conditionVariable, lock_t* lock) { // while (!holding(lock)) { // lock_acquire(lock); // } //do { // printf(1, "wait on 0x%x----%d, lock: %d\n", conditionVariable, *conditionVariable, lock->locked); // printf(1, "lock %p %d\n", lock, lock->locked); csleep(conditionVariable, lock); //} while(xchg(conditionVariable, 0) == 0); // printf(1, "end wait\n"); } void cv_signal(cond_t* conditionVariable) { // printf(1, "wake on 0x%x----%d\n", conditionVariable, *conditionVariable); // xchg(conditionVariable, 1); // printf(1, "wake now 0x%x----%d\n", conditionVariable, *conditionVariable); cwake(conditionVariable); // printf(1, "wake now 0x%x----%d\n", conditionVariable, *conditionVariable); }
C
#ifndef __ZA__ #define __ZA__ /* Providing aliases for the data type to be used in the program */ typedef int INT; typedef unsigned int UINT; typedef char CHAR; /* Defining macros for the format specifiers to be used in the program */ #define INT_FS "%d" #define UINT_FS "%u" #define CHAR_FS "%c" #define STR_FS "%s" /* Creating an enum for the LMK scheme */ typedef enum scheme { VARIANT, KEYBLOCK } lmk_scheme_t; /* Defining macros to provide the constants to be used in the program */ #define PIN_LEN 2 #define SALT_LEN 16 #define LMK_ID_LEN 2 #define LMK_SCHEME KEYBLOCK #define ATTEMPTS 3 /* Defining macros to provide functionality in the program */ #define STROUT(str) fprintf(stdout, str) #define STRERR(str) fprintf(stderr, str) #define STRIN(var) fgets(var, sizeof(var), stdin) #define OUT(format, var) fprintf(stdout, format, var) #define NL() fprintf(stdout, "\n") #define FLUSH() fflush(stdin) #define CHECK_DEFAULT_PIN_FMT(pin_format) pin_format == "\n" #define CHECK_VALID_PIN_FMT(pin_format) pin_format == '0' || pin_format == '1' || pin_format == '7' #define CHECK_VALID_PIN_LEN_0(pin_length) pin_length >= 6 && pin_length <= 16 #define CHECK_VALID_PIN_LEN_1(pin_length) pin_length >= 6 && pin_length <= 20 #define CHECK_VALID_PIN_LEN_7(pin_length) pin_length >= 6 && pin_length <= 30 #define CHECK_PIN_SALT(pin_salt) strlen(pin_salt) == SALT_LEN || strlen(pin_salt) == 0 /* Creating a structure for the ZA command message */ typedef struct za_req { lmk_scheme_t lmk_scheme; CHAR an_pin_format; UINT block_size; CHAR an_pin_length[PIN_LEN + 1]; CHAR *an_pin; CHAR an_pin_salt[SALT_LEN + 1]; CHAR delimiter; CHAR lmk_identifier[LMK_ID_LEN + 1]; } za_req_t; /* ---------- Function Prototypes ---------- */ // Function to terminate the process void terminate(CHAR* msg, INT code); // Function to create a za command request structure za_req_t* create_za_request(); // Function to initialize pin format and block size after taking input of pin format void initialize_pin_fomat(za_req_t *za_request); // Function to initialize pin length and create pin field after taking input of pin length void initialize_pin_length(za_req_t *za_request); // Function to initialize rest of the fields with the inputs taken from the user void initialize_fields(za_req_t *za_request); // Function to generate an alphanumeric pin void generate_an_pin(za_req_t *za_request); // Function to encrypt the pin using lmk void encrypt_pin(za_req_t *za_request); /* ---------- Utility Function Prototypes ---------- */ // Function to take input pin format as well check for the validation void input_pin_format(za_req_t *za_request); // Function to take input pin length as well check for the validation void input_pin_length(za_req_t *za_request); // Function to take input pin salt as well check for the validation void input_pin_salt(za_req_t *za_request); // Function to take input delimeter as well check for the validation // void input_delimiter(za_req_t *za_request); // Function to take input lmk identifier as well check for the validation // void input_lmk_identifier(za_req_t *za_request); #endif
C
/* ** my_put_nbr.c for emacs in /home/Johanne-Franck/CPE_2016_matchstick ** ** Made by Johanne-Franck NGBOKOLI ** Login <[email protected]> ** ** Started on Thu Feb 16 18:30:20 2017 Johanne-Franck NGBOKOLI ** Last update Sun Feb 26 16:16:53 2017 Johanne-Franck NGBOKOLI */ #include "lib.h" int my_put_nbr(int nb) { int neg; int i; i = 0; neg = 0; if (nb == 0) return (0); if (nb < 0) { my_putchar('-'); i++; nb = nb * -1; } if (nb >= 10) my_put_nbr(nb / 10); if (neg == 1) { neg = 0; my_putchar(nb % 10 + '1'); } else my_putchar(nb % 10 + '0'); i++; return (i); }
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "dsi_packing.h" /* For this, see http://www.dsi-lifeboat.com/viewtopic.php?f=13&t=17 */ #include "pcm_proc.h" /* For this, see http://www.dsi-lifeboat.com/viewtopic.php?f=13&t=130 */ #define PCM_MAX 176400 #define EVOLVER_ID 0x20 /* All Evolvers */ #define EVOLVER_SAMPLE_SIZE 128 int main(int argc, char *argv[]) { /* The waveshape number is expected as a command-line argument */ if (argc < 2) { printf("\nusage: %s waveshape_number\n\n", argv[0]); return -1; } int waveshape_number = atoi(argv[1]); if (waveshape_number > 128 || waveshape_number < 97) { printf("\nwaveshape number out of range (97-128)\n\n"); return -1; } waveshape_number--; /* Because waveshape numbers are zero-indexed to the Evolver */ /* Get the RAW file from standard input */ signed int raw[PCM_MAX]; /* Entire RAW file */ unsigned long int size = 0; /* RAW file size */ for (;;) { int lb = getchar(); /* Low byte */ int hb = getchar(); /* High byte */ if (hb == EOF || size == PCM_MAX) break; raw[size++] = (hb << 8) + lb; } /* Use pcm_proc tools to convert the RAW pcm into 16-bit, mono, 128-word PCM */ PCMData pcm = new_PCMData(); set_pcm_data(&pcm, 128, raw); pcm_change_resolution(&pcm, 16); pcm_change_size(&pcm, EVOLVER_SAMPLE_SIZE); pcm = pcm_from_channel(&pcm, PCM_PROC_CHANNEL_LEFT); /* PCM data is signed, while the dsi_packing tools require data to be unsigned. So, * conversion must be done. First, I cast each sample to an int16_t to guarantee that * it's a 16-bit signed integer. Then, I divide the 16-bit word into bytes and * place them, little-endian, into an evolver data array. */ unsigned int evolver_data[PCM_MAX]; unsigned long int i; /* i is the index within the PCM data */ unsigned long int dx = 0; /* dx is the index within the evolver data */ for (i = 0; i < pcm.size; i++) { int16_t sample = (int16_t)pcm.data[i]; /* Convert the signed 16-bit sample into a high and low byte */ evolver_data[dx++] = (sample) & 0xff; /* Low byte */ evolver_data[dx++] = (sample) >> 8; /* High byte */ } /* Use dsi_packing tools to convert the sample data into DSI's packed format */ UnpackedVoice evolver_waveform; set_voice_data(&evolver_waveform, dx, evolver_data); PackedVoice evolver_sysex = pack_voice(evolver_waveform); /* Send the actual SysEx to standard output */ putchar(0xf0); /* Start SysEx */ putchar(0x01); /* DSI */ putchar(EVOLVER_ID); putchar(0x01); /* File version */ putchar(0x0a); /* Waveshape Data */ putchar(waveshape_number); dump_voice(evolver_sysex); putchar(0xf7); /* End SysEx */ return 0; }
C
#include <stdio.h> int main(int argc, char const *argv[]) { int a = 30000, b = 10000; long c; char str[] = "========================="; c = (long) a + b; //c = a + b; printf("c = %ld\n",c ); printf("sizeof \n" ); printf("%s\n", str ); printf("char : %d\n", sizeof(char)); printf("short int : %d\n", sizeof(short int)); printf("int : %d\n", sizeof(int)); printf("long : %d\n", sizeof(long)); printf("long int : %d\n", sizeof(long int)); printf("float : %d\n", sizeof(float)); printf("double : %d\n", sizeof(double)); printf("long double: %d\n", sizeof(long double)); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <math.h> #include <omp.h> #define N 255 const double epsilon = 0.000456; double *matrixMulVect(const double *matrix, const double *vector) { double *res = (double *) calloc(N, sizeof(double)); #pragma omp parallel for for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { res[i] += matrix[i * N + j] * vector[j]; } } return res; } void calcNextYn(double *A, double *xn, const double *B, double *yn) { double *A_xn = matrixMulVect(A, xn); #pragma omp parallel for for (int i = 0; i < N; ++i) { yn[i] = A_xn[i] - B[i]; } free(A_xn); } double scalarVectMul(const double *v1, const double *v2) { double scalarMulRes = 0; #pragma omp parallel for reduction(+:scalarMulRes) for (int i = 0; i < N; ++i) { scalarMulRes += v1[i] * v2[i]; } return scalarMulRes; } double calcNextTau(double *A, double *yn) { double *A_yn = matrixMulVect(A, yn); double numerator = scalarVectMul(yn, A_yn); double denominator = scalarVectMul(A_yn, A_yn); free(A_yn); return numerator / denominator; } void calcNextX(double *prevX, double tau, const double *yn) { #pragma omp parallel for for (int i = 0; i < N; ++i) { prevX[i] -= tau * yn[i]; } } double calcVectLen(double *v) { return sqrt(scalarVectMul(v, v)); } double bLen; int canFinish(double *A, double *xn, const double *B) { double *numerator = matrixMulVect(A, xn); #pragma omp parallel for for (int i = 0; i < N; ++i) { numerator[i] -= B[i]; } int flag = (calcVectLen(numerator) / bLen) < epsilon; free(numerator); return flag; } void calcX(double *A, double *B, double *xn) { double *yn = (double *) malloc(N * sizeof(double)); double tau; while (!canFinish(A, xn, B)) { calcNextYn(A, xn, B, yn); tau = calcNextTau(A, yn); calcNextX(xn, tau, yn); } free(yn); } void loadData(double *A, double *B, double *X) { srand(1); for (int i = 0; i < N; ++i) { X[i] = (double)(rand() % 18 - 9); for (int j = 0; j < N; ++j) { A[i * N + j] = i == j ? (double)(rand() % 18 - 9) : 0.0009; } } for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { B[i] += A[i * N + j] * X[j]; } } for (int i = 0; i < 13; ++i) { printf("%f ", X[i]); } printf("\n\n"); for (int i = 0; i < N; ++i) { X[i] = 0; } } int main(int argc, char **argv) { double *A = (double *) malloc(N * N * sizeof(double)); double *B = (double *) calloc(N, sizeof(double)); double *X = (double *) malloc(N * sizeof(double)); loadData(A, B, X); bLen = calcVectLen(B); calcX(A, B, X); free(A); free(B); printf("ans\n"); for (int i = 0; i < 13; ++i) { printf("%f ", X[i]); } printf("\n"); free(X); }
C
#include <stdio.h> #include <stdlib.h> #include "DLinkNode.h" DLinkNode* CreateDNode(DLinkType value) { DLinkNode* ptr = (DLinkNode*)malloc(sizeof(DLinkNode)); ptr->data = value; ptr->next = ptr; ptr->prev = ptr; return ptr; } void Destroy(DLinkNode* ptr) { free(ptr); } void DLinkListInit(DLinkNode** head) { if (head == NULL) { return; } *head = CreateDNode(0); } DLinkNode* DLinkListPushBack(DLinkNode* head, DLinkType value) { if (head == NULL) { return NULL; } DLinkNode* cur = CreateDNode(value); DLinkNode* cur_next = head; DLinkNode* cur_prev = head->prev; cur->next = cur_next; cur_next->prev = cur; cur->prev = cur_prev; cur_prev->next = cur; return cur; } void DLinkListPopBack(DLinkNode* head) { if (head == NULL) { return; } if (head->next == head) { return; } DLinkNode* to_delete = head->prev; DLinkNode* to_delete_prev = to_delete->prev; DLinkNode* to_delete_next = head; to_delete_prev->next = to_delete_next; to_delete_next->prev = to_delete_prev; Destroy(to_delete); } void DLinkListPushFront(DLinkNode* head, DLinkType value) { if (head == NULL) { return; } DLinkNode* cur =CreateDNode(value); DLinkNode* cur_prev = head; DLinkNode* cur_next = head->next; cur_prev->next = cur; cur->prev = cur_prev; cur_next->prev = cur; cur->next = cur_next; } void DLinkListPopFront(DLinkNode* head) { if (head == NULL) { return; } if (head->next == head) { return; } DLinkNode* cur = head->next; DLinkNode* cur_prev = head; DLinkNode* cur_next = cur->next; cur_prev->next = cur_next; cur_next->prev = cur_prev; Destroy(cur); } DLinkNode* DLinkListFind(DLinkNode* head, DLinkType to_find) { if (head == NULL) { return NULL; } DLinkNode* cur = head->next; for (; cur != head; cur = cur->next) { if (cur->data == to_find) { return cur; } } return NULL; } void DLinkListInsert(DLinkNode* pos, DLinkType value) { if (pos == NULL) { return; } DLinkNode* to_insert = CreateDNode(value); DLinkNode* to_insert_prev = pos->prev; DLinkNode* to_insert_next = pos; to_insert->next = to_insert_next; to_insert_next->prev = to_insert; to_insert->prev = to_insert_prev; to_insert_prev->next = to_insert; } void DLinkListInsertAfter(DLinkNode* pos, DLinkType value) { if (pos == NULL) { return; } DLinkNode* to_insert = CreateDNode(value); DLinkNode* to_insert_prev = pos; DLinkNode* to_insert_next = pos->next; to_insert->next = to_insert_next; to_insert_next->prev = to_insert; to_insert->prev = to_insert_prev; to_insert_prev->next = to_insert; } ///////////////////////////////////////// // 以下为测试代码 ///////////////////////////////////////// #if 1 void DLinkListPrint(DLinkNode* head, char* str) { printf("%s\n",str); printf("[head]"); DLinkNode* cur = head->next; for(; cur != head; cur = cur->next) { printf(" -> [%c-%p]", cur->data, cur); } printf("\n[head]"); for(cur = head->prev; cur != head; cur = cur->prev) { printf(" <- [%c-%p]", cur->data, cur); } printf("\n"); } void TestPushBack() { TEST_HEADER; DLinkNode* head; DLinkListInit(&head); DLinkListPushBack(head, 'a'); DLinkListPushBack(head, 'b'); DLinkListPushBack(head, 'c'); DLinkListPushBack(head, 'd'); DLinkListPrint(head,"尾插四个元素"); } void TestPopBack() { TEST_HEADER; DLinkNode* head; DLinkListInit(&head); DLinkListPushBack(head, 'a'); DLinkListPushBack(head, 'b'); DLinkListPushBack(head, 'c'); DLinkListPushBack(head, 'd'); DLinkListPrint(head,"尾插四个元素"); DLinkListPopBack(head); DLinkListPopBack(head); DLinkListPrint(head,"尾删两个元素"); DLinkListPopBack(head); DLinkListPopBack(head); DLinkListPrint(head,"再尾删两个元素"); DLinkListPopBack(head); DLinkListPrint(head,"尝试对空链表尾删"); } void TestPushFront() { TEST_HEADER; DLinkNode* head; DLinkListInit(&head); DLinkListPushFront(head, 'a'); DLinkListPushFront(head, 'b'); DLinkListPushFront(head, 'c'); DLinkListPushFront(head, 'd'); DLinkListPrint(head,"头插四个元素"); } void TestPopFront() { TEST_HEADER; DLinkNode* head; DLinkListInit(&head); DLinkListPushBack(head, 'a'); DLinkListPushBack(head, 'b'); DLinkListPushBack(head, 'c'); DLinkListPushBack(head, 'd'); DLinkListPrint(head,"尾插四个元素"); DLinkListPopFront(head); DLinkListPopFront(head); DLinkListPrint(head,"头删两个元素"); DLinkListPopFront(head); DLinkListPopFront(head); DLinkListPrint(head,"再头删两个元素"); DLinkListPopFront(head); DLinkListPopFront(head); DLinkListPrint(head,"尝试对空链表头删"); } void TestFind() { TEST_HEADER; DLinkNode* head; DLinkListInit(&head); DLinkListPushBack(head, 'a'); DLinkNode* pos_b = DLinkListPushBack(head, 'b'); DLinkListPushBack(head, 'c'); DLinkListPushBack(head, 'd'); DLinkListPrint(head,"尾插四个元素"); DLinkNode* ptr = DLinkListFind(head, 'x'); printf("查找不存在的元素 expert:NULL actual:%p\n", ptr); ptr = DLinkListFind(head, 'b'); printf("查找b expert:%p actual:%p\n", pos_b, ptr); } void TestInsert() { TEST_HEADER; DLinkNode* head; DLinkListInit(&head); DLinkListPushBack(head, 'a'); DLinkNode* pos_b = DLinkListPushBack(head, 'b'); DLinkListPushBack(head, 'c'); DLinkListPushBack(head, 'd'); DLinkListPrint(head,"尾插四个元素"); DLinkListInsert(pos_b, 'x'); DLinkListPrint(head,"在b前面插入x"); } void TestInsertAfter() { TEST_HEADER; DLinkNode* head; DLinkListInit(&head); DLinkListPushBack(head, 'a'); DLinkNode* pos_b = DLinkListPushBack(head, 'b'); DLinkListPushBack(head, 'c'); DLinkListPushBack(head, 'd'); DLinkListPrint(head,"尾插四个元素"); DLinkListInsertAfter(pos_b, 'x'); DLinkListPrint(head,"在b后面插入x"); } int main() { system("clear"); TestPushBack(); TestPopBack(); TestPushFront(); TestPopFront(); TestFind(); TestInsert(); TestInsertAfter(); return 0; } #endif
C
#include <stdio.h> #include <stdlib.h> int main() { int i,product=1,sum=0; for (i=1; i<=5; i++) { product=product*i; sum=sum+i; } printf("product %d\n",product); printf("sum %d\n",sum); return 0; }
C
#include <stdio.h> int main(void) { int a; printf("Please set case (1,2,3)\n"); scanf("%d",&a); switch (a) { case 1: printf("Case was set to 1\n"); break; case 2: printf("Case was set to 2\n"); break; case 3: printf("Case was set to 3\n"); break; default: printf("Case was set to default value\n"); break; } }
C
/* Author: Joseph DiCarlantonio * Partner(s) Name: Brandon Tran * Lab Section: * Assignment: Lab # Exercise # * Exercise Description: [optional - include for your own benefit] * * I acknowledge all content contained herein, excluding template or example * code, is my own original work. */ #include "../header/time.h" #include "../header/io.h" #ifdef _SIMULATE_ #include "simAVRHeader.h" #endif #define button (~PINA & 0x01) #define out PORTB #define period 200 char score = 0; enum Scored { FALSE, // 0 TRUE, // 1 NO_SCORE } scored; enum States { START, LED1, LED2, LED3, BUTTON_PRESS, BUTTON_RELEASE, RESTART } state; void gameSM() { // transitions switch(state) { case START: state = LED1; break; case LED1: { if(button) { state = BUTTON_PRESS; } else { state = LED2; } break; } case LED2: { if(button) { state = BUTTON_PRESS; } else { state = LED3; } break; } case LED3: { if(button) { state = BUTTON_PRESS; } else { state = LED1; } break; } case BUTTON_PRESS: { if(button) { state = BUTTON_PRESS; } else { state = BUTTON_RELEASE; } break; } case BUTTON_RELEASE: { if(button) { if(score >= 9) { score = 0; LCD_DisplayString(1, "Score:"); LCD_Cursor(7); LCD_WriteData(score + '0'); } state = RESTART; } else { state = BUTTON_RELEASE; } break; } case RESTART: { if(button) { state = RESTART; } else { state = LED1; } } } // actions switch(state) { case START: case LED1: { out = 0x01; scored = FALSE; break; } case LED2: { out = 0x02; scored = TRUE; break; } case LED3: { out = 0x04; scored = FALSE; break; } case BUTTON_PRESS: { if(scored == TRUE) { score++; scored = NO_SCORE; } if(scored == FALSE) { score--; if(score <= 0) score = 0; scored = NO_SCORE; } break; } case BUTTON_RELEASE: { if(score >= 9) { LCD_ClearScreen(); LCD_DisplayString(1, "You Won!!!"); } break; } case RESTART: break; } } int main(void) { DDRA = 0x00; PORTA = 0xFF; DDRB = 0xFF; PORTB = 0x00; DDRD = 0xFF; PORTD = 0x00; DDRC = 0xFF; PORTC = 0x00; TimerSet(period); TimerOn(); LCD_init(); LCD_DisplayString(1, "Score:"); state = START; while (1) { gameSM(); if(score < 9) { LCD_Cursor(7); LCD_WriteData(score + '0'); } while(!TimerFlag); TimerFlag = 0; } return 1; }
C
#include <stdio.h> #include <stdlib.h> int main() { float valor,taxa,tempo,prest; printf("insira o valor, taxa e tempo:\n"); scanf("%f%f%f",&valor,&taxa,&tempo); prest = valor +(valor*(taxa/100)*tempo); printf("valor da prestacao: %f",prest); return 0; }
C
#include <stdio.h> // Exercise 7.6 from King // By Max Parisi // finished 1/13/2019 int main(void) { printf("sizeof(int) == %zu\nsizeof(short) == %zu\nsizeof(long) == %zu\n", sizeof(int), sizeof(short), sizeof(long)); printf("sizeof(float) == %zu\nsizeof(double) == %zu\nsizeof(long double) == %zu\n", sizeof(float), sizeof(double), sizeof(long double)); return 0; }
C
/* ** EPITECH PROJECT, 2020 ** CleanSFMl ** File description: ** Header file for the create functions */ #ifndef INC_H_ #define INC_H_ #include "header.h" /** * \brief Create functions: * \brief It return a complete sfRenderWindow *. * Parameters: * @param width is the width of the sfRenderWindow *. * @param height is the height of the sfRenderWindow *. * By default, the bits per pixel is 32. * @param title is the title (the name) of the sfRenderWindow *. */ sfRenderWindow *create_window(unsigned int width, unsigned int height, char const *title); /** * \brief Create functions: * \brief It return a complete sfSprite create from an image. * Parameters: * @param path is the image's path which refers to the sprite. * @param size is an the scaling factor of the sprite. To set it to default put (sfVector2f){1, 1}. */ sfSprite *create_sprite(char const *path, sfVector2f size); /** * \brief Create functions: * \brief It return a sfText *. * Parameters: * @param string is the caracters in the sfText. * @param police is the path to the font files. * @param pos is the position where you want to place the text in the sfRenderWindow. * @param size is the font's size. * By default, the color of the text is set to white. */ sfText *create_text(char *string, char *police, sfVector2f pos, unsigned int size); /** * Create functions: * It return a sfSound *. * Parameters: * @param buffer is a reference to a sfSoundBuffer. You can handle it by this way. * @param path is the filepath to the sound's file. * @param float is the volume. * @param play: true is you want to play the sound directly at its creation, false if not. * @param loop: true if you want a direct looping, false if not. */ sfSound *create_sound(sfSoundBuffer **buffer, char *path, float volume, bool play, bool loop); #endif /* !INC_H_ */
C
#include <stdint.h> #include "stm32f0xx.h" #include "ili9341.h" #define DC (2) #define RST (3) #define CS (4) #define SCK (5) #define MOSI (7) #define CLR_RS (GPIOA->ODR &= ~(1 << DC)) #define SET_RS (GPIOA->ODR |= 1 << DC) #define CLR_CS (GPIOA->ODR &= ~(1 << CS), SPI1->CR1 &= ~(SPI_CR1_SSI)) #define SET_CS (GPIOA->ODR |= (1 << CS), SPI1->CR1 |= SPI_CR1_SSI) #define MS 1000000 #define US 1000 int lastX0 = -1; int lastX1 = -1; int lastY0 = -1; int lastY1 = -1; extern void nano_wait(uint32_t n); static inline void delay(uint32_t ms) { nano_wait(ms * MS); } static void _reset(void) { GPIOA->ODR &= ~(1 << RST); delay(10); GPIOA->ODR |= 1 << RST; delay(150); } static void _setupSPI(void) { RCC->AHBENR |= RCC_AHBENR_GPIOAEN; RCC->APB2ENR |= RCC_APB2ENR_SPI1EN; GPIOA->MODER |= (0x1 << (2*RST)) + (0x2 << (2*MOSI)) + (0x2 << (2*SCK)) + (0x1 << (2*CS)) + (0x1 << (2*DC)); SET_CS; SPI1->CR1 |= SPI_CR1_BIDIMODE + SPI_CR1_BIDIOE + SPI_CR1_MSTR + SPI_CR1_SSM + SPI_CR1_SSI; SPI1->CR2 |= SPI_CR2_SSOE; SPI1->CR1 |= SPI_CR1_SPE; } static void _sendCommand(uint8_t command) { CLR_RS; CLR_CS; while ((SPI1->SR & SPI_SR_BSY)); *((uint8_t*)&SPI1->DR) = (uint8_t) command; while ((SPI1->SR & SPI_SR_BSY)); SET_CS; } static void _sendData(uint8_t data) { SET_RS; CLR_CS; while ((SPI1->SR & SPI_SR_BSY)); *((uint8_t*)&SPI1->DR) = (uint8_t) data; while ((SPI1->SR & SPI_SR_BSY)); SET_CS; } void ili9341_setDisplayWindow(int x0, int y0, int x1, int y1) { if (x0 == lastX0+1 && x1 == lastX1+1 && y0 == lastY0 && y1 == lastY1) { return; } lastX0 = x0; lastX1 = x1; lastY0 = y0; lastY1 = y1; _sendCommand(ILI9341_CASET); // Column Address Set _sendData(x0>>8); // X address start: _sendData(x0); // 0 <= XS <= X _sendData(x1>>8); // X address end: _sendData(x1); // S <= XE <= X _sendCommand(ILI9341_RASET); //Row address set _sendData(y0>>8); // Y address start: _sendData(y0); // 0 <= YS <= Y _sendData(y1>>8); // Y address start: _sendData(y1); // S <= YE <= Y _sendCommand(ILI9341_RAMWR); //write data } void ili9341_exitSleep(void) { _sendCommand(ILI9341_SLPOUT); // Exit Sleep Mode delay(120); _sendCommand(ILI9341_DISPON); // Display on } void ili9341_enterSleep(void) { _sendCommand(ILI9341_SLPIN); delay(120); _sendCommand(ILI9341_DLPOFFSAVE); // Display on } void ili9341_init(void) { _setupSPI(); _reset(); //-----------------------------Display setting-------------------------------- _sendCommand(ILI9341_MADCTL); //Page 215 _sendData(0xE0); //DEFAULT // _sendData(0x20); //Address control _sendCommand(ILI9341_COLMOD); //Interface pixel format Pg 224 _sendData(0x55); _sendCommand(ILI9341_INVOFF); ili9341_setDisplayWindow(0, 0, WIDTH, HEIGHT); ili9341_exitSleep(); } void ili9341_fillLCD(uint16_t color) { register int h, w; ili9341_setDisplayWindow(0, 0, WIDTH, HEIGHT); for (h = 0; h < HEIGHT; h++) { for (w = 0; w < WIDTH; w++) { ili9341_writePixel(color); } } } void ili9341_writePixel(uint16_t color) { _sendData(color >> 8); _sendData(color & 0xFF); } void ili9341_writePixelAtPoint(uint16_t x, uint16_t y, uint16_t color) { ili9341_setDisplayWindow(x, y, WIDTH, HEIGHT); ili9341_writePixel(color); } void ili9341_setBrightness(uint16_t bright) { _sendCommand(ILI9341_WRDISBV); _sendData(bright); }
C
#include <stdio.h> void printArray(int a[], int size) { //based on stack working it will work so writing acc to recursion function for (int i =0; i<size;i++) { printf("%d ", a[i]); } printf("\n"); } void merge(int a[], int left, int mid, int right) { int l,r,m ; // current index for the left, right and merged array int leftSize = mid - left + 1 ; int rightSize = right - mid ; int la[leftSize] , ra[rightSize] ; // two temporary array to store the data to merge back to array a for (int i = 0; i < leftSize ; i++) { la[i] = a[left+i]; } for (int i = 0 ; i < rightSize ; i++) { ra[i] = a[mid+1+i] ; } // current index of left, right and merged arrays l = r = 0; m = left; while (l < leftSize && r < rightSize) { if (la[l] < ra[r]) a[m++] = la[l++] ; else a[m++] = ra[r++] ; } // copy the remaining element while (l < leftSize) { a[m++] = la[l++] ; } while (r < rightSize) { a[m++] = ra[r++] ; } } void mergeSort(int a[], int left, int right) { if (left < right) { // divide the array into two halves int mid = (left+right)/2; // left mergeSort(a, left, mid) ; // right mergeSort(a, mid+1, right) ; // merge now the left and right merge(a, left, mid , right) ; } } int main() { int a[10] = {1,5,2,67,23,38,45,8,3,12} ; printArray(a,10) ; mergeSort(a,0,9); printArray(a,10); }
C
#include <Python.h> static PyObject* say_hello(PyObject* self, PyObject* args) { const char* name; if (!PyArg_ParseTuple(args, "s", &name)) return NULL; printf("Hello %s!\n", name); Py_RETURN_NONE; } static PyMethodDef HelloMethods[] = { {"say_hello", say_hello, METH_VARARGS, "Greet somebody."}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef hellomodule = { PyModuleDef_HEAD_INIT, "hello", /* name of module */ "some test here", /* module documentation, may be NULL */ -1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */ HelloMethods }; PyMODINIT_FUNC PyInit_hello(void) { //(void) Py_Initialize("hello", HelloMethods); return PyModule_Create(&hellomodule); }
C
// convert int to string- GfG #include <stdio.h> int main() {int a=10; char *x; x=(char)a; printf("%s",x); return 0; }
C
#include "lStack.h" int main(int argc ,char **argv){ Stack *stack = (Stack *)malloc(sizeof(Stack)); initStack(stack); push(stack , 3); push(stack , 4); push(stack , 5); push(stack , 6); push(stack , 7); printf("The length:%d\n",getLength(stack)); disp(stack); pop(stack); printf("The length:%d\n" ,getLength(stack) ); disp(stack); pop(stack); disp(stack); push(stack , 9); disp(stack); printf("The length:%d\n" ,getLength(stack) ); Stack *stack1 = (Stack *)malloc(sizeof(Stack)); initStack(stack1); conversion(stack1); disp(stack1); printf("输入要计算的g式子:"); operation(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "../include/linked_list.h" void insertItem( ListNodePtr *headPtr, int value ) { /* Create list walker */ ListNodePtr previousPtr = NULL; ListNodePtr currentPtr = *headPtr; /* Create the new node */ ListNodePtr newNode = malloc(sizeof(ListNode)); /* Should memory allocation succeed */ if ( newNode != NULL ) { newNode->data = value; newNode->nextPtr = NULL; /* Walk through the list */ while ( currentPtr != NULL && newNode->data > currentPtr->data ) { /* If input value is greater skip current node */ previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } /* CASE 1: Insert at head of list */ if (previousPtr == NULL ){ newNode->nextPtr = *headPtr; *headPtr = newNode; } else { /* CASE 2: Insert new node into correct postion */ newNode->nextPtr = currentPtr; previousPtr->nextPtr = newNode; } printf("Inserted\n"); } else { printf("\nUnable to to allocate memory for insertion. Free memory space\n"); } }
C
#include "Nano100Series.h" // Device header #include "step_motor.h" int step_motor_max = 0, step_motor_count = 0; void step_motor_init(int max){ GPIO_SetMode(PE, BIT7 | BIT8 | BIT9 | BIT10, GPIO_PMD_OUTPUT); step_motor_max = max; } void step_motor(int n){ short q = 0; PE7 = PE8 = PE9 = PE10 = 0; switch(n & 7){ case 0: q = 1 << 7; // 0001 break; case 1: q = 3 << 7; // 0011 break; case 2: q = 2 << 7; // 0010 break; case 3: q = 6 << 7; // 0110 break; case 4: q = 4 << 7; // 0100 break; case 5: q = 12 << 7; // 1100 break; case 6: q = 8 << 7; // 1000 break; case 7: q = 9 << 7; // 1001 break; } PE->DOUT |= q; } void step_motor_running(void){ if(step_motor_count == step_motor_max){ PE7 = PE8 = PE9 = PE10 = 0; } else { if(step_motor_count > step_motor_max) step_motor_count--; else if (step_motor_count < step_motor_max) step_motor_count++; step_motor(step_motor_count & 7); } }
C
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the files COPYING and Copyright.html. COPYING can be found at the root * * of the source code distribution tree; Copyright.html can be found at the * * root level of an installed copy of the electronic HDF5 document set and * * is linked from the top-level documents page. It can also be found at * * http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have * * access to either file, you may request a copy from [email protected]. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /*------------------------------------------------------------------------- * * Created: atomic_writer.c * * Purpose: This is the "writer" part of the standalone test to check * atomic read-write operation on a system. * a) atomic_writer.c--the writer (this file) * b) atomic_reader.c--the reader * c) atomic_data--the name of the data file used by writer and reader * *------------------------------------------------------------------------- */ /***********/ /* Headers */ /***********/ #include <assert.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if !defined(WIN32) && !defined(__MINGW32__) #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> /****************/ /* Local Macros */ /****************/ #define FILENAME "atomic_data" /********************/ /* Local Prototypes */ /********************/ static void usage(void); /*------------------------------------------------------------------------- * Function: usage * * Purpose: To print information about the command line options * * Parameters: None * * Return: void * *------------------------------------------------------------------------- */ static void usage(void) { printf("\n"); printf("Usage error!\n"); printf("Usage: atomic_writer -n <number of integers to write> -i <number of iterations for writer>\n"); printf(" Note**The number of integers for option n has to be positive\n"); printf(" Note**The number of integers for option i has to be positive\n"); printf("\n"); } /* usage() */ /*------------------------------------------------------------------------- * Function: main * * Purpose: To write a series of integers to a file for the reader to verify the data. * A write is atomic if the whole amount written in one operation is not interleaved * with data from any other process. * (1) Iterate with i iterations * (2) Write a series of integers (0 to n-1) to the file with this pattern: * offset 0: 0000000000000000000000000000000 * offset 1: 111111111111111111111111111111 * offset 2: 22222222222222222222222222222 * offset 3: 3333333333333333333333333333 * ... * ... * offset n-1: (n-1) * * At the end of the writes, the data in the file will be: * 01234567........(n-1) * * Note: * (a) The # of integers (via -n option) used by the writer and reader should be the same. * (b) The data file used by the writer and reader should be the same. * * Future enhancement: * 1) Provide default values for n and i and allow user to run with either 0 or 1 option * 2) Use HDF library HD<system calls> instead of the system calls * 3) Handle large sized buffer (gigabytes) if needed * * Return: Success: 0 * Failure: -1 * *------------------------------------------------------------------------- */ int main(int argc, char *argv[]) { int fd = -1; /* file descriptor */ ssize_t bytes_wrote; /* the nubmer of bytes written */ unsigned int *buf = NULL; /* buffer to hold written data */ unsigned int n, u, i; /* local index variable */ int temp; /* temporary variable */ unsigned int iterations = 0; /* the input for "-i" */ unsigned int num = 0; /* the input for "-n" */ int opt = 0; /* option char */ /* Ensure the # of arguments is as expected */ if(argc != 5) { usage(); exit(-1); } /* Parse command line options */ while((opt = getopt(argc, argv, "n:i:")) != -1) { switch(opt) { case 'n': if((temp = atoi(optarg)) < 0) { usage(); exit(-1); } num = (unsigned int)temp; break; case 'i': if((temp = atoi(optarg)) < 0) { usage(); exit(-1); } iterations = (unsigned int)temp; break; default: printf("Invalid option encountered\n"); break; } } printf("WRITER: # of integers to write = %u; # of iterations = %d\n", num, iterations); /* Remove existing data file if needed */ if(remove(FILENAME) < 0) { if(errno == ENOENT) printf("WRITER: remove %s--%s\n", FILENAME, strerror(errno)); else { printf("WRITER: error from remove: %d--%s\n", errno, strerror(errno)); goto error; } } else printf("WRITER: %s is removed\n", FILENAME); /* Create the data file */ if((fd = open(FILENAME, O_RDWR|O_TRUNC|O_CREAT, 0664)) < 0) { printf("WRITER: error from open\n"); goto error; } /* Allocate buffer for holding data to be written */ if((buf = (unsigned int *)malloc(num * sizeof(unsigned int))) == NULL) { printf("WRITER: error from malloc\n"); if(fd >= 0 && close(fd) < 0) printf("WRITER: error from close\n"); goto error; } printf("\n"); for(i = 1; i <= iterations; i++) { /* iteration loop */ printf("WRITER: *****start iteration %u*****\n", i); /* Write the series of integers to the file */ for(n = 0; n < num; n++) { /* write loop */ /* Set up data to be written */ for(u=0; u < num; u++) buf[u] = n; /* Position the file to the proper location */ if(lseek(fd, (off_t)(n*sizeof(unsigned int)), SEEK_SET) < 0) { printf("WRITER: error from lseek\n"); goto error; } /* Write the data */ if((bytes_wrote = write(fd, buf, ((num-n) * sizeof(unsigned int)))) < 0) { printf("WRITER: error from write\n"); goto error; } /* Verify the bytes written is correct */ if(bytes_wrote != (ssize_t)((num-n) * sizeof(unsigned int))) { printf("WRITER: error from bytes written\n"); goto error; } } /* end for */ printf("WRITER: *****end iteration %u*****\n\n", i); } /* end for */ /* Close the file */ if(close(fd) < 0) { printf("WRITER: error from close\n"); goto error; } /* Free the buffer */ if(buf) free(buf); return(0); error: return(-1); } /* main() */ #else /* WIN32 / MINGW32 */ int main(void) { printf("Non-POSIX platform. Exiting.\n"); return EXIT_FAILURE; } /* end main() */ #endif /* WIN32 / MINGW32 */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include <sys/wait.h> #include <fcntl.h> #include <sys/types.h> #include <signal.h> #include <time.h> #include <errno.h> void myfunc(int signo) { //打开文件 int fd = open("time.txt",O_RDWR | O_CREAT |O_APPEND, 0755); time_t t; if(fd<0) { return ; } //获取时间 time(&t); //转换 char *p = ctime(&t); //写入 write(fd,p,strlen(p)); close(fd); return ; } int main() { //创建父进程 pid_t pid = fork(); if(pid<0 || pid>0) { exit(1); } //子进程调用setsid函数 //pid_t setsid(void); setsid(); //改变工作目录 //int chdir(const char *path); chdir("/home/systemk1t/linux"); //改变文件掩码 //mode_t umask(mode_t mask); umask(0000); //关闭文件描述符 close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); //核心操作 struct sigaction act; act.sa_handler = myfunc; act.sa_flags = 0; sigemptyset(&act.sa_mask); sigaction(SIGALRM,&act,NULL); //设置时钟 struct itimerval tm; tm.it_interval.tv_sec = 2; tm.it_interval.tv_usec = 0; tm.it_value.tv_sec = 3; tm.it_value.tv_usec = 0; setitimer(ITIMER_REAL,&tm,NULL); while(1) { sleep(1); } return 0; }
C
/* * Copyright (c) 2016 Intel Corporation. * Intel Corporation All Rights Reserved. * * Portions of the source code contained or described herein and all documents related * to portions of the source code ("Material") are owned by Intel Corporation or its * suppliers or licensors. Title to the Material remains with Intel * Corporation or its suppliers and licensors. The Material contains trade * secrets and proprietary and confidential information of Intel or its * suppliers and licensors. The Material is protected by worldwide copyright * and trade secret laws and treaty provisions. No part of the Material may * be used, copied, reproduced, modified, published, uploaded, posted, * transmitted, distributed, or disclosed in any way without Intel's prior * express written permission. * * No license under any patent, copyright, trade secret or other intellectual * property right is granted to or conferred upon you by disclosure or * delivery of the Materials, either expressly, by implication, inducement, * estoppel or otherwise. Any license under such intellectual property rights * must be express and approved by Intel in writing. */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <math.h> const long ARRAY_SIZE=1024*1024; const long SCALE=512; const long ITERATIONS=10; float result(unsigned long i, float a, float b, float c, float x1, float x2) { float result1 = a*x1*x1 + b*x1 + c; float result2 = a*x2*x2 + b*x2 + c; printf("%ld: a=%10.4f, b=%10.4f, c=%10.4f, x1=%10.4f, x2=%10.4f result1=%10.6f, result2=%10.6f\n", i, a, b, c, x1, x2, result1, result2); } void compute_roots(unsigned long vectorSize, float a[], float b[], float c[], float x1[], float x2[]) { unsigned long j = 0, i = 0; for (j=0; j<ITERATIONS; j++) { #pragma vector aligned for (i=0; i<vectorSize; i++) { x1[i] = (- b[i] + sqrtf((b[i]*b[i] - 4.0f *a[i]*c[i])) ) / (2.0f*a[i]); x2[i] = (- b[i] - sqrtf((b[i]*b[i] - 4.0f *a[i]*c[i])) ) / (2.0f*a[i]); } } return; } int main (int argc, char *argv[]) { struct timeval t_Start, t_End; unsigned long time = 0; unsigned long i = 0, j = 0; unsigned long N = 0; unsigned int repetitions = 0; N = SCALE * ARRAY_SIZE; repetitions = ITERATIONS; printf("No. of Elements : %dM\nRepetitions = %d\n", SCALE, repetitions); printf("Start allocating buffers and initializing ....\n"); float *coef_a = (float *)_mm_malloc(N * sizeof(float), 64); float *coef_b = (float *)_mm_malloc(N * sizeof(float), 64); float *coef_c = (float *)_mm_malloc(N * sizeof(float), 64); float *root_x1 = (float *)_mm_malloc(N * sizeof(float), 64); float *root_x2 = (float *)_mm_malloc(N * sizeof(float), 64); // Initialize the arrays #pragma vector aligned for(i=0; i<N; i++) { coef_a[i] = (float)(i % 64) + 1.0f; coef_b[i] = (float)(i % 64) + 101.0f; coef_c[i] = (float)(i % 32) - 33.0f; root_x1[i] = 0.0f; root_x2[i] = 0.0f; } gettimeofday(&t_Start, NULL); compute_roots(N, coef_a, coef_b, coef_c, root_x1, root_x2); gettimeofday(&t_End, NULL); time += ((t_End.tv_sec - t_Start.tv_sec)*1000L +(t_End.tv_usec - t_Start.tv_usec)/1000L); printf("Elapsed time in msec: %ld (after %d iterations)\n", time, ITERATIONS); #ifdef VERIFYING int K = 100; for (i = 0; i < K; i++) result(i, coef_a[i], coef_b[i], coef_c[i], root_x1[i], root_x2[i]); for (i = N-K; i < N; i++) result(i, coef_a[i], coef_b[i], coef_c[i], root_x1[i], root_x2[i]); #endif _mm_free(coef_a); _mm_free(coef_b); _mm_free(coef_c); _mm_free(root_x1); _mm_free(root_x2); return 0; }
C
#include<stdio.h> int main() { int i,m,n; double jg; scanf("%d%d",&m,&n); if(m==0||n==0){ printf("0"); } else if(m<=n){ printf("1"); } else{ jg=m-n+1; for(i=2;i<=n;i++){ jg*=((double)m-n+i)/i; } printf("%d",(int)jg); } return 0; }
C
/* * atenderNodoYFS.c * * Created on: 10/6/2015 * Author: utnso */ #include "variablesGlobales.h" void *atenderNFS(void*arg){ char *mensaje; char *direccion; char *bufferSet; char* paquetito; char* bloqueGet; int offset,tamanioDelPaquetito; int socket= (int)arg; int entero; // handshake para saber quien es: FS(23) int nroDelBloque; int tamanioBloque; int tamanioBloqueExacto; int loQueMande; int variableDelPaquetito = 64*1024; int tamanioReal; char* pmap; if(string_equals_ignore_case(nodo_nuevo,"SI")){ pmap = mapearAMemoriaVirtual(archivo_bin); formatearArchivo(pmap); munmap(pmap,tamanioArchivo_BIN); } tamanioArchivo_BIN= tamanioDelArchivoBIN(); printf("Este es el socket: %i\n",socket); while(1){ //printf("Esto deberia imprimirse una sola vez\n"); if(recv(socket, &entero, sizeof(int),0) > 0){ switch(entero){ //getBloque(numero); case 1: pmap = mapearAMemoriaVirtual(archivo_bin); send(socket,&entero,sizeof(int),0); recv(socket,&nroDelBloque,sizeof(int),0); printf("%i\n",nroDelBloque); tamanioBloque=tamanioEspecifico(pmap,nroDelBloque); printf("Este es el tamaño del bloque por tamanioESP es: %i\n",tamanioBloque); bloqueGet=malloc(tamanioBloque); tamanioBloqueExacto = nroDelBloque * 1024 * 1024* 20; memcpy(bloqueGet,pmap + tamanioBloqueExacto,tamanioBloque); printf("Este es el posta: %i\n",strlen(bloqueGet)); send(socket,&tamanioBloque,sizeof(int),0); recv(socket,&entero,sizeof(int),0); loQueMande = send(socket,bloqueGet,tamanioBloque,0); printf("Lo envie y esto fue el tamaño que envie: %i\n",loQueMande); munmap(pmap,tamanioArchivo_BIN); //ok = 20; //send(socket,&ok, sizeof(int),0); break; //setBloque(numero,[datos]); case 2: pmap = mapearAMemoriaVirtual(archivo_bin); send(socket,&entero,sizeof(int),0); recv(socket,&nroDelBloque,sizeof(int),0); printf("El nro de bloque: %i\n",nroDelBloque); send(socket,&entero,sizeof(int),0); recv(socket,&tamanioBloque,sizeof(int),0); printf("El tamaño del buffer: %i\n",tamanioBloque); send(socket,&entero,sizeof(int),0); bufferSet=malloc(tamanioBloque); offset = 0; while(tamanioBloque != offset){ if((tamanioBloque-offset)<variableDelPaquetito){ tamanioDelPaquetito = tamanioBloque-offset; }else{ tamanioDelPaquetito = variableDelPaquetito; } paquetito = malloc(tamanioDelPaquetito); tamanioReal = recv(socket,paquetito,tamanioDelPaquetito,0); memcpy(bufferSet + offset,paquetito,tamanioReal); offset += tamanioReal; liberar(&paquetito); } printf("Este es el tamaño del buffer set DESPUES: %i\n",strlen(bufferSet)); memcpy(pmap+(1024*1024*20*(nroDelBloque)),bufferSet,tamanioBloque); msync(pmap,tamanioArchivo_BIN,0); printf("se seteo correctamente\n"); liberar(&bufferSet); munmap(pmap,tamanioArchivo_BIN); //ok = 20; //send(socket,&ok, sizeof(int),0); break; //getFileContent(nombre); case 3: printf("antes\n"); getFileContent(socket); //ok = 20; //send(socket,&ok, sizeof(int),0); break; case 4: //FORMATEO pmap = mapearAMemoriaVirtual(archivo_bin); printf("Me mando a formatear el archivo\n"); formatearArchivo(pmap); printf("Se formateo correctamente\n"); munmap(pmap,tamanioArchivo_BIN); break; case 5: //FORMATEO DE BLOQUE pmap = mapearAMemoriaVirtual(archivo_bin); send(socket,&entero,sizeof(int),0); recv(socket,&nroDelBloque,sizeof(int),0); printf("Se esta formateando el bloque...\n"); formatearBloque(pmap,nroDelBloque); printf("Formateo del bloque %i completado\n",nroDelBloque); munmap(pmap,tamanioArchivo_BIN); break; } } } liberar(&mensaje); liberar(&direccion); liberar(&bufferSet); liberar(&paquetito); liberar(&bloqueGet); munmap(pmap,tamanioArchivo_BIN); return NULL; }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> void main() { FILE *in_file,*sym_tab,*op_tab; int op1,start_ad,loc_ctr,o,len,found=0; char la[20],m1[20],op[20],otp[20]; in_file=fopen("input.txt","r"); sym_tab=fopen("symtab.txt","w"); fscanf(in_file,"%s %s %d",la,m1,&op1); if(strcmp(m1,"START")==0) { start_ad=op1; loc_ctr=start_ad; printf("\t%s\t%s\t%d\n",la,m1,op1); } else loc_ctr=0; fscanf(in_file,"%s %s",la,m1); while(!feof(in_file)) { found=0; fscanf(in_file,"%s",op); printf("\n%d\t%s\t%s\t%s\n",loc_ctr,la,m1,op); if(strcmp(la,"-")!=0) fprintf(sym_tab,"\n%d\t%s\n",loc_ctr,la); op_tab=fopen("optab.txt","r"); fscanf(op_tab,"%s %d",otp,&o); while(!feof(op_tab)) { if(strcmp(m1,otp)==0) { loc_ctr=loc_ctr+3; found=1; break; } fscanf(op_tab,"%s %d",otp,&o); } fclose(op_tab); if(strcmp(m1,"WORD")==0) loc_ctr+=3; else if(strcmp(m1,"RESW")==0) { op1=atoi(op); loc_ctr*=op1; } else if(strcmp(m1,"BYTE")==0) { if(op[0]=='X') loc_ctr+=1; else { len=strlen(op)-3; loc_ctr+=len; } } else if(strcmp(m1,"RESB")==0) { op1=atoi(op); loc_ctr+=1; } fscanf(in_file,"%s %s",la,m1); } if(strcmp(m1,"END")==0) printf("Program length = %d",loc_ctr-start_ad); fclose(in_file); fclose(sym_tab); }
C
/* ex7-12-3.c -- ȡֱ0ձż0 ܸƽƽ*/ #include <stdio.h> int main(void) { int num, odd_sum, even_sum; int odd_count, even_count; float odd_average, even_average; odd_sum = even_sum = 0; odd_count = even_count = 0; printf("0"); scanf("%d", &num); while(num != 0) { if(num % 2 == 0) { even_count++; even_sum += num; printf("ʱż%d ƽֵ%d\n", even_count, even_sum); } else { odd_count++; odd_sum += num; printf("ʱ%d ƽֵ%d\n", odd_count, odd_sum); } printf("һ"); scanf("%d", &num); } printf("ż%d ƽƽ%.2f\n", even_count, (float)even_sum/even_count); printf("%d ƽ%.2f\n", odd_count, (float)odd_sum/odd_count); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #include <signal.h> #include <limits.h> void lock(int fd) { } void unlock(int fd) { } #define SEQ_FILE "./file" int main(int argc, char *argv[]) { if (access(SEQ_FILE, F_OK) != 0) { printf("%s not exits !", SEQ_FILE); exit(1); } if (argc != 2) { printf("usage : %s <loops>\n", argv[0]); exit(1); } int loops = atoi(argv[1]); int fd; if ((fd = open(SEQ_FILE, O_RDWR)) < 0) { perror("open error"); exit(1); } struct stat st; if (fstat(fd, &st) < 0) { perror("fstat error"); exit(1); } if (fchmod(fd, (st.st_mode & ~S_IXGRP) | S_ISGID) < 0) { perror("fchmod error"); exit(1); } char buf[1024]; ssize_t n; int seqno = 0; for (int i = 0; i < loops; i++) { lock(fd); if (lseek(fd, 0, SEEK_SET) < 0) { perror("lseek error"); exit(1); } n = read(fd, buf, sizeof(buf)); buf[n] = 0; n = sscanf(buf, "%d\n", &seqno); if (n != 1) { printf("sscanf error"); exit(1); } printf("pid = %ld #seq = %d\n", (long)getpid(), seqno); seqno++; snprintf(buf, sizeof(buf), "%d\n", seqno); n = strlen(buf); if (lseek(fd, 0, SEEK_SET) < 0) { perror("lseek error"); exit(1); } if (write(fd, buf, n) != n) { perror("write error"); exit(1); } unlock(fd); } return 0; }
C
#include "apue.h" #include <errno.h> #include <limits.h> #ifdef PATH_MAX static long pathmax = PATH_MAX; #else static long pathmax=0; #endif static long posix_version =0; static long xsi_version =0; #define PATH_MAX_GUESS 1024 char *path_alloc(size_t *sizep); int main(int argc,char *argv[]) { char *ptr; size_t size; if (chdir(argv[1])<0) err_sys("chdir failed"); ptr=path_alloc(&size); if (getcwd(ptr,size)==NULL) err_sys("getcwd failed"); printf("cwd=%s\n",ptr); exit(0); } char *path_alloc(size_t *sizep) { char *ptr; size_t size; if (posix_version==0) posix_version = sysconf(_SC_VERSION); if (xsi_version == 0) xsi_version = sysconf(_SC_XOPEN_VERSION); if (pathmax==0){ errno=0; if((pathmax=pathconf("/",_PC_PATH_MAX))<0){ if(errno==0) pathmax= PATH_MAX_GUESS; else err_sys("pathconf error for _PC_PATH_MAX"); } else { pathmax++; } } if ((posix_version<200112L)&&(xsi_version<4)) size = pathmax+1; else size = pathmax; if ((ptr = malloc(size))==NULL) err_sys("malloc error for pathname"); if (sizep!=NULL) *sizep=size; return (ptr); }
C
// Sergey Kirgizov's implementation of // Maximilien Danisch's algorithm that finds // maximal subgraph with maximal average degree (MAD) // UWAGA! in this file density means MAD. // We suppose that your graph is so big // that it doesn't fit into the memory. // So we are going to do some hardwork with your hard drive. #include "graph.h" #include <stdio.h> #include <stdlib.h> #define MAX(a,b) (((a)>(b))?(a):(b)) static int* X = NULL; // madmax scores static void madmax_iteration (edge e, edge_count ec) { // UWAGA! uses a global variable X if (X[e.a] <= X[e.b]) { X[e.a]++; } else { X[e.b]++; } } void madmax_score (char* gf, graph_size gs, int max_iter) { // gf is a name of a file that contains an edge list // an edge is a pair of nodes separated by one ' ' // every node is a uint64_t number // edges should be separated by '\n' X = (int*) calloc (gs.nodes, sizeof(int)); // UWAGA! don't forget to free int t; for (t = 0; t < max_iter; t++) { read_graph_iterator (gf, madmax_iteration); } } static node_count* RANK_OF_NODE = NULL; static edge_count* E = NULL; static void madmax_sweep_iteration (edge e, edge_count ec) { node_count m = MAX ( RANK_OF_NODE[e.a], RANK_OF_NODE[e.b]); E[m]++; } static int inderect_compare(const void *a, const void *b) { // pass this to qsort over an array of indexes // argsort node_count i = *(const node_count *)a; node_count j = *(const node_count *)b; /* Avoid return x - y, which can cause undefined behaviour because of signed integer overflow. */ if (X[i] < X[j]) return 1; if (X[i] > X[j]) return -1; return 0; } dens_subgraph madmax_densest_subgraph (char* gf, graph_size gs) { // UWAGA! use of a global variable X, should contain a result of madmax_score // gf is a name of a file that contains an edge list // Returns a list of nodes and corresponding density (MAD) // of an induced subgraph. node_count i; node_count* node_of_rank; node_of_rank = (node_count*) calloc (gs.nodes, sizeof(node_count)); RANK_OF_NODE = (node_count*) calloc (gs.nodes, sizeof(node_count)); E = (edge_count*) calloc (gs.nodes, sizeof(edge_count)); // sort nodes in non decreasing order of X-scores // prepare an array of indexes for (i = 0; i < gs.nodes; i++) node_of_rank[i] = i; // sort this array using a comprator that compares original values qsort (node_of_rank, gs.nodes, sizeof(node_count), inderect_compare); for (i = 0; i < gs.nodes; i++) { RANK_OF_NODE [ node_of_rank[i] ] = i; } read_graph_iterator (gf, madmax_sweep_iteration); node_count size = 0; double tmp_density = 0; double density = 0; edge_count totale = 0; for (i = 0; i < gs.nodes; i++) { totale = totale + E[i]; tmp_density = totale / (i + 1.0); if (tmp_density > density) { density = tmp_density; size = i+1; } } dens_subgraph ds; ds.density = density; ds.size = size; ds.nodes = realloc (node_of_rank, size * sizeof(node_count)); free (RANK_OF_NODE); free (E); return ds; } // only for testing purposes int main (int argc, char** argv) { char* gf = argv[1]; int max_iter = atoi(argv[2]); graph_size gs = get_graph_size(gf); madmax_score(gf, gs, max_iter); printf ("%ld nodes, %ld edges in graph\n", gs.nodes, gs.edges); printf ("Madmax scores:\n"); node_count i; for (i = 0; i < gs.nodes; i++) { printf ("%d <== %lu\n", X[i], i); } dens_subgraph ds = madmax_densest_subgraph (gf, gs); printf ("Subgraph of density %f contais %lu following nodes: ", ds.density, ds.size); for (i = 0; i < ds.size; i++) { printf ("%lu ", ds.nodes[i]); } printf ("\nBye.\n"); free (X); free (ds.nodes); }
C
#include<stdio.h> int main() { int i,t,n,m,a,b; scanf("%d",&t); for(i=0;i<t;i++) { scanf("%d%d",&n,&m); a=m/4; b=m%4; b=b/2; printf("%d %d",a,b); } }
C
/* Find the lowest common ancestor in an unordered binary tree given two values in the tree. Lowest common ancestor : the lowest common ancestor (LCA) of two nodes v and w in a tree or directed acyclic graph (DAG) is the lowest (i.e. deepest) node that has both v and w as descendants. Example : _______3______ / \ ___5__ ___1__ / \ / \ 6 _2_ 0 8 / \ 7 4 For the above tree, the LCA of nodes 5 and 1 is 3. LCA = Lowest common ancestor Please note that LCA for nodes 5 and 4 is 5. You are given 2 values. Find the lowest common ancestor of the two nodes represented by val1 and val2 No guarantee that val1 and val2 exist in the tree. If one value doesn’t exist in the tree then return -1. There are no duplicate values. You can use extra memory, helper functions, and can modify the node struct but, you can’t add a parent pointer. */ /** * Definition for binary tree * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; * * typedef struct TreeNode treenode; * * treenode* treenode_new(int val) { * treenode* node = (treenode *) malloc(sizeof(treenode)); * node->val = val; * node->left = NULL; * node->right = NULL; * return node; * } */ /** * @input A : Root pointer of the tree * @input B : Integer * @input C : Integer * * @Output Integer */ int count=0; int find(treenode* A,int value,int *result) { if(A==NULL) return 0; if(A->val==value){ result[count++]=A->val; return 1; } int left=find(A->left,value,result); if(left==1){ result[count++]=A->val; return 1; } int right=find(A->right,value,result); if(right==1) { result[count++]=A->val; return 1; } return 0; } int lca(treenode* A, int B, int C) { int *temp1=(int*)malloc(sizeof(int*)*100000); int *temp2=(int*)malloc(sizeof(int*)*100000); find(A,B,temp1); int length1=count-1; count=0; find(A,C,temp2); int length2=count-1; int temp=-1; while(length1>=0&&length2>=0) { if(temp1[length1]==temp2[length2]) temp=temp1[length1]; else return temp; length1--; length2--; } return temp; }
C
//Reverse of a linklist till stack has the address void Reverse(){ if(head == NULL) return ; stack<struct Node*> S; Node* temp = head ; while(temp!=NULL) { S.push(temp); temp = temp->next; } temp = S.top(); head = temp; S.pop(); while(!s.empty()){ temp->next = S.top(); S.pop(); temp = tmep->next; } temp ->next = NULL; } Node * temp = S.top(); head = temp; s.pop(); while(!S.empty()){ temp->next = s.top(); s.pop(); temp = temp->next; } temp->next = NULL;
C
//Fibonacci Series using Recursion - Option 1 /* The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …….. In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation. Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1. Write a function int fibonacci(int n) that returns Fn. For example, if n = 0, then fibonacci() should return 0. If n = 1, then it should return 1. For n > 1, it should return Fn-1 + Fn-2 For n = 9 Output:34 */ /* Time Complexity: T(n) = T(n-1) + T(n-2) which is exponential. We can observe that this implementation does a lot of repeated work (see the following recursion tree). So this is a bad implementation for nth Fibonacci number. fib(5) / \ fib(4) fib(3) / \ / \ fib(3) fib(2) fib(2) fib(1) / \ / \ / \ fib(2) fib(1) fib(1) fib(0) fib(1) fib(0) / \ fib(1) fib(0) */ #include<stdio.h> int fibonacci(int n) { if (n <= 1) return n; printf("%d",n); return fibonacci(n-1) + fibonacci(n-2); } int main () { int n = 9; printf("%d", fibonacci(n)); getchar(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "se_fichier.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> int client(int argc,char **argv) { int i,gains=-1,fd=open("tube.fifo",O_WRONLY); if(errno && fd==-1) { printf(" \n\nthere is no onegoing lottery please wait for the next lottery number %d \n\n",(int)getpid()); close(fd); return 2; } else { int k=1; i=(int)getpid(); write(fd,&i,sizeof(int)); i=2; while(i<argc) { k=atoi(argv[i]); write(fd,&k,sizeof(int)); i++; } close(fd); } int fd2=open("gains.fifo",O_RDONLY); if(errno && fd2==-1) { perror("THE CLIENT DIDN T RECEIVE THE MONEY "); close(fd2); close(fd); system("rm *.fifo"); return -1; } read(fd2,&gains,sizeof(int)); if(gains==0) { i=2; while(i<argc) { printf(" %d ",atoi(argv[i])); i++; } printf(" // you have won %d $\n\n",gains); gains=0; } else { printf("You have won %d $ !!! // ",gains); read(fd2,&gains,sizeof(int)); printf("matches %d/%d \n\n",gains,(argc-2)); if(gains==argc-2) gains=1; else gains=0; } close(fd2); close(fd); return gains; } void server(char **argv) { SE_FICHIER F1=SE_ouverture(argv[2],O_RDONLY); int n,i=0,k; SE_lectureEntier(F1,&n); int T[(n*3)+1]; while(i<n*3) { SE_lectureEntier(F1,&k); T[i]=k; i++; } SE_fermeture(F1); printf(" NEW LOTTERY\n\n\nHERE'S THE LUCKY NUMBERS : \n"); for (int j = 0; j < n; ++j) { printf(" %d ",T[j]); } printf("\n\n"); mkfifo("tube.fifo",0644); mkfifo("gains.fifo",0644); int fd2=1,fd=1,B=1; while(B) { fd2=open("tube.fifo",O_RDONLY); if(errno && fd2==-1) { perror("THE SERVER DIDN T RECEIVE THE NUMBERS "); } else { i=0; int j=1; int T2[n+1],nombre=0; read(fd2,&k,sizeof(int)); printf("client %d numbers : ",k); while(j<n+1) { read(fd2,&k,sizeof(int)); T2[j]=k; printf(" %d ",k); if(T2[j]==T[i]) { nombre++; } i++; j++; } printf(" // number of matches : %d/%d ",nombre,n); int gains=0; i=n; while(i<(n*3)-1) { if(T[i]==nombre) { gains=T[i+1]; } i=i+2; } printf("// earnings : %d $\n\n",gains); fd=open("gains.fifo",O_WRONLY); if(errno && fd!=-1) { perror("THE SERVER CAN T SEND THE MONEY EVEN TOUGH THE CLIENT SEND THE NUMBERS "); } else { write(fd,&gains,sizeof(int)); if(gains==T[n+1]) { B=0; } gains=nombre; write(fd,&gains,sizeof(int)); } close(fd); } close(fd2); } unlink("gains.fifo"); unlink("tube.fifo"); } int main(int argc, char **argv) { if(argc<3) { perror("ERREUR : nombre insuffisant d'arguments\n"); return -1; } if(strcmp(argv[1],"client")==0) { int res=client(argc,argv); return res; } else { if(strcmp(argv[1],"server")==0) { server(argv); } else { perror("ERREUR : arguments non valide\n"); return -1; } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> #include <arpa/inet.h> #include <sys/socket.h> #define BUF_SIZE 1024 #define OPSZ 4 #define WORD_STATIS 3 /* 통계 구조체 자료형 정의 */ typedef struct statis { char alphabet; float prob; float succ; float total; int check; } statis_t; void error_handling(char *message); void init(int* count, char* game, char* word, char* src); int hangman(int* count, char* game, char word[], char user, statis_t statis[][26], int word_c); /* 게임 진행 */ void generator(char* game, char word[]); /* 단어 캡슐화 (게임 초기) */ void ranking(float* data, char* str, int n); int main(int argc, char *argv[]) { int serv_sock, clnt_sock; char opinfo[BUF_SIZE], message[BUF_SIZE]; int i, j, user_connect, recv_len; /* Game 변수 */ int end, word_c, count = 0; char word[BUF_SIZE], game[BUF_SIZE], src[20]; FILE *fp = NULL; statis_t statis[WORD_STATIS][26]; // 통계를 위한 구조체 struct sockaddr_in serv_adr, clnt_adr; socklen_t clnt_adr_sz; // sort를 위한 배열 float statis_prob[26]; char statis_alphabet[26]; float statis_succ[5]; // 오름차순 float statis_total[5]; // 오름차순 if(argc != 2) { printf("Usage : %s <port>\n", argv[0]); exit(1); } serv_sock = socket(PF_INET, SOCK_STREAM, 0); if(serv_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 = htonl(INADDR_ANY); serv_adr.sin_port = htons(atoi(argv[1])); if(bind(serv_sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr)) == -1) error_handling("bind() error"); if(listen(serv_sock, 5) == -1) error_handling("listen() error"); clnt_adr_sz = sizeof(clnt_adr); for(user_connect = 0; user_connect < 5; user_connect++) { clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr, &clnt_adr_sz); if(clnt_sock == -1) error_handling("accept() error"); else printf("Connected client %d \n", user_connect+1); // 통계 구조체 init for (i = 0; i < WORD_STATIS; i++) { /* * 0: 3글자 단어 통계 * 1: 4글자 단어 통계 * 2: 5글자 단어 통계 */ for(j = 0; j < 26; j++) { statis[i][j].alphabet = 97 + j; // 알파벳 아스키코드 값으로 넣음 statis[i][j].check = 0; statis[i][j].prob = 0.; statis[i][j].succ = 0.; statis[i][j].total = 0.; } } while ((recv_len = read(clnt_sock, opinfo, BUF_SIZE)) != 0) { switch (opinfo[0]) { case 1: /* * Game Init * 게임 변수 초기화 */ printf("[Server] 게임 시작!\n"); init(&count, game, word, src); word_c = opinfo[1]; srand(time(NULL)); sprintf(src, "word/%d.txt", opinfo[1]); fp = fopen(src, "r"); if (fp != NULL) { char line[255]; char *pStr; int i = 1, key = 0; pStr = fgets(line, sizeof(line), fp); key = rand() % atoi(pStr); while(!feof(fp)) { if (i == key) strcpy(word, pStr); i++; pStr = fgets(line, sizeof(line), fp); } fclose(fp); } generator(game, word); printf("[Server] 단어 생성: %s", word); write(clnt_sock, word, strlen(word)+1); break; case 2: printf("[Client] : %c\n", opinfo[1]); end = hangman(&count, game, word, opinfo[1], statis, word_c); // 1: Success 2: 게임 끝 0: 게임 진행 switch (end) { case 1: case 2: for(i = 0; i < 26; i++) statis[word_c-3][i].check = 0; // Check 리셋 break; } sprintf(message, "%d %d %s", end, count, game); write(clnt_sock, message, strlen(message)); message[0] = 0; // Array Clear break; case 3: printf("[Client] 확인하고 싶은 단어의 글자 수 : %d\n", opinfo[1]); // 초기 값 for(i = 0; i < 26; i++) { statis_prob[i] = statis[opinfo[1]-3][i].prob; statis_alphabet[i] = statis[opinfo[1]-3][i].alphabet; } // 확률 Top 3 - Insertion sort ranking(statis_prob, statis_alphabet, 26); for (i = 0; i < 26; i++) { if (statis[opinfo[1]-3][i].alphabet == statis_alphabet[25]) { statis_succ[4] = statis[opinfo[1]-3][i].succ; statis_total[4] = statis[opinfo[1]-3][i].total; } else if (statis[opinfo[1]-3][i].alphabet == statis_alphabet[24]) { statis_succ[3] = statis[opinfo[1]-3][i].succ; statis_total[3] = statis[opinfo[1]-3][i].total; } else if (statis[opinfo[1]-3][i].alphabet == statis_alphabet[23]) { statis_succ[2] = statis[opinfo[1]-3][i].succ; statis_total[2] = statis[opinfo[1]-3][i].total; } else if (statis[opinfo[1]-3][i].alphabet == statis_alphabet[22]) { statis_succ[1] = statis[opinfo[1]-3][i].succ; statis_total[1] = statis[opinfo[1]-3][i].total; } else if (statis[opinfo[1]-3][i].alphabet == statis_alphabet[21]) { statis_succ[0] = statis[opinfo[1]-3][i].succ; statis_total[0] = statis[opinfo[1]-3][i].total; } } sprintf(message, "1. < %c >\n 확률: %f (맞춘 수: %d 시도: %d)\n2. < %c >\n 확률: %f (맞춘 수: %d 시도: %d)\n3. < %c >\n 확률: %f (맞춘 수: %d 시도: %d)\n4. < %c >\n 확률: %f (맞춘 수: %d 시도: %d)\n5. < %c >\n 확률: %f (맞춘 수: %d 시도: %d)\n", statis_alphabet[25], statis_prob[25], (int)statis_succ[4], (int)statis_total[4], statis_alphabet[24], statis_prob[24], (int)statis_succ[3], (int)statis_total[3], statis_alphabet[23], statis_prob[23], (int)statis_succ[2], (int)statis_total[2], statis_alphabet[22], statis_prob[22], (int)statis_succ[1], (int)statis_total[1], statis_alphabet[21], statis_prob[21], (int)statis_succ[0], (int)statis_total[0]); write(clnt_sock, message, strlen(message)+1); message[0] = 0; // Array Clear break; } } close(clnt_sock); } close(serv_sock); return 0; } void init(int* count, char* game, char* word, char* src) { /* * init * 문자열 배열 초기화 * Game Count 초기화 */ *count = 0; // count reset game[0] = 0; // Array Clear word[0] = 0; // Array Clear word[0] = 0; // Array Clear } void generator(char* game, char word[]) { /* * init * 단어 캡슐화 */ strcpy(game, word); // word 문자열 만큼 game에 복사 (크기 할당) for (int i = 0; i < strlen(word)-1; i++) game[i] = '*'; } void ranking(float* data, char* str, int n) { /* * Insertion Sort 방식 * 오름차순 정렬 */ int i, j; char alphabet; float prob; for (i = 1; i < n; i++) { prob = data[i]; alphabet = str[i]; for (j = i-1; j >= 0 && prob < data[j]; j--) { data[j+1] = data[j]; str[j+1] = str[j]; } data[j+1] = prob; str[j+1] = alphabet; } } int hangman(int* count, char* game, char word[], char user, statis_t statis[][26], int word_c) { /* * hangman * 입력된 문자들이 단어와 일치하는 check 1: 같음 / 0: 다름 * 성공 시 카운트를 내리지 않음 */ int check = 0, conv; conv = user; for (int i = 0; i < strlen(word)-1; i++) { if (word[i] == user) { game[i] = user; check = 1; } } if (!check) // 카운트 *count += 1; if (*count == 10) // 10번 카운트 시 게임 종료 return 2; else { // 통계 계산 if (!statis[word_c-3][conv-97].check) // check가 1이라면 이전에 계산 되었음. { if(check) // 사용자가 단어를 맞췄을 경우. succ + 1 { statis[word_c-3][conv-97].check = 1; statis[word_c-3][conv-97].succ += 1.; statis[word_c-3][conv-97].total += 1.; statis[word_c-3][conv-97].prob = statis[word_c-3][conv-97].succ / statis[word_c-3][conv-97].total; } else { statis[word_c-3][conv-97].check = 1; statis[word_c-3][conv-97].total += 1.; statis[word_c-3][conv-97].prob = statis[word_c-3][conv-97].succ / statis[word_c-3][conv-97].total; } } return !strcmp(game, word); // 비교 후 리턴 } } void error_handling(char *message) { fputs(message, stderr); fputc('\n', stderr); exit(1); }
C
#include<stdio.h> typedef struct node{ int data; struct node *left,*right; }node; void insertBt(node **p,int v){ int ch; printf("Inserting value %d\n",v); if(*p==NULL){ node *newnode; newnode=(node*) malloc(sizeof(node)); newnode->data=v; newnode->left=NULL; newnode->right=NULL; *p=newnode; } else { printf("enter 1 for inserting to left and 2 for right of %d\n",(*p)->data); scanf("%d",&ch); if(ch==1) insertBt(&(*p)->left,v); else insertBt(&(*p)->right,v); } } int isComplete(node *p) { int x,y; if(p==NULL) return 0; if(p->left==NULL&&p->right==NULL) return 1; else { x=isComplete(p->left)+1; y=isComplete(p->right)+1;} if(x==y &&x!=0) return x; else return 0; } //sir's code without pointer int max2(node *p){ if(p==NULL) return 0; else { int x=max2(p->left); int y=max2(p->right); int z=p->data; return x>y?(x>z?x:z):(y>z?y:z); } } //using poiter void maxint(node *p,int *max){ if(p==NULL) return; if(p->data>(*max)) *max=p->data; maxint(p->left,max); maxint(p->right,max); } int searchBt(node *p,int v){ if(p==NULL) return 0; if(p->data==v) return 1; else { int x=searchBt(p->left,v); int y=searchBt(p->right,v); return x||y; } } void prenode(struct node *p) { if(p==NULL) return; else { printf("\n%d\t",p->data); prenode(p->left); prenode(p->right); } } void toCopy(node *from,node **to) { if(from==NULL){ *to=NULL; } else{ *to=(node *)malloc(sizeof(node)); (*to)->data=from->data; toCopy(from->left,&(*to)->left); toCopy(from->right,&(*to)->right); } } void innode(struct node *p) { if(p==NULL) return; else { innode(p->left); printf("\n%d\t",p->data); innode(p->right); } } void toMirror(node *p) { if(p==NULL) return; else { node *t=p->left; p->left=p->right; p->right=t; toMirror(p->left); toMirror(p->right); } } int main() { int max=0; node *root=NULL,*root1=NULL; insertBt(&root,50); insertBt(&root,10); insertBt(&root,40); insertBt(&root,125); insertBt(&root,35); insertBt(&root,47); insertBt(&root,95); maxint(root,&max); printf("largest value is %d",max); //using poiter printf("\nlargest value is %d",max2(root)); //sir's code without pointer printf("\nresult of Searching node 10 is %d",searchBt(root,10)); printf("\nresult of Searching node 100 is %d",searchBt(root,100)); printf("\noriginal tree\n"); innode(root); printf("\nmirror tree\n"); toMirror(root); innode(root); toCopy(root,&root1); printf("\ncopied tree\n"); innode(root1); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Stack { int* key; int top; int max_stack_size; }Stack; Stack* CreateStack(int max) { Stack* S = NULL; S = (Stack*)malloc(sizeof(max)); S->key = (int*)malloc(sizeof(int)*max); S->max_stack_size = max; S->top = -1; return S; } int IsFull(Stack *S) { if(S->top == S->max_stack_size) return 1; else return 0; } void Push(Stack* S, int X) { S->top++; S->key[S->top] = X; } int main(int argc, char* argv[]) { FILE* fi = fopen(argv[1],"r"); Stack* stack; char input_str[101]; int max, i=0, a, b, result; fgets(input_str, 101, fi); max = strlen(input_str); printf("Pushed numbers :\n"); stack = CreateStack(max); while(input_str[i] != '#') { if('0'<=input_str[i]&&input_str[i]<='9') { //if(IsFull(stack)) printf("Stack is full\n"); Push(stack, input_str[i]-'0'); i++; } } for(int n=0;n<stack->top+1;n++) { printf("%d is inserted.\n",stack->key[n]); } }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> int main(int argc, char* argv[]) { int n; sscanf(argv[1], "%d", &n); for (int i = 0; i < n; i++) { for (int j = 0; j < 2 * n - 1; j++) { if (i >= abs(n - 1 - j)) printf("%c", '*'); else printf("%c", ' '); } printf("%c", '\n'); } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/wait.h> #include <signal.h> typedef struct Node{ pid_t pid_process; char pname[100]; int num; struct Node *next; }node; extern node *head; extern pid_t pid; extern int counter; int spawn_proc(char * com,int in, int out) { char *par[1000]; char * Split_temp = strtok(com," "); // strtok to parse the command and storing them in params array for(int i = 0; i < 1000; i++) { par[i] = Split_temp; Split_temp = strtok(NULL," "); if(par[i] == NULL) break; } if ((pid = fork ()) == 0) { if (in != 0) { dup2 (in, 0); close (in); } if (out != 1) { dup2 (out, 1); close (out); } return execvp (par[0], par); } return pid; } int piping(char *comd) { int save_in, save_out; int tempin=dup(0); int tempout=dup(1); save_in = dup(0); save_out = dup(1); int i; int in, fd [2]; char * split; char com[100][100]; if(comd[strlen(comd)-1] == '\n') { comd[strlen(comd)-1] = '\0'; } int temp=0; split = strtok(comd,"|"); //split by "|" while(split) { strcpy(com[temp],split); split = strtok(NULL,"|"); temp++; } in = 0; // initial input stream char *par[1000]; for (i = 0; i < temp-1; ++i) { if(i==0) // because input redirection can only be before the first pipe { parseCmm(com[i],par); setInput(par,tempin); } pipe (fd); spawn_proc(com[i],in, fd [1]); close (fd [1]); in = fd [0]; // input for next piped command setting } // last piped command has to be executed differently parseCmm(com[i],par); // because the output redirection can only be in the last piped command setOutput(par,tempout); pid = fork(); // fork process // Error if (pid == -1) { char* error = strerror(errno); printf("fork: %s\n", error); dup2(save_in, 0); dup2(save_out,1); close(save_in); close(save_out); return 1; } // Child process else if (pid == 0) { // execute execvp if (in != 0) dup2 (in, 0); execvp(par[0], par); dup2(save_in, 0); dup2(save_out,1); close(save_in); close(save_out); // if error occured char* error = strerror(errno); printf("shell: %s: %s\n", par[0], error); return 0; } // Parent process else { int childStatus; waitpid(pid, &childStatus, 0); dup2(save_in, 0); dup2(save_out,1); close(save_in); close(save_out); return 1; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* reverse_rotate_op.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jkasongo <[email protected] +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/08/11 20:33:30 by jkasongo #+# #+# */ /* Updated: 2021/09/21 17:27:40 by jkasongo ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/push_swap.h" bool do_rra(t_stack *stack_a, bool silent) { bool status; status = reverse_rotate(stack_a); if (status && !silent) ft_putendl_fd("rra", 1); return (status); } bool do_rrb(t_stack *stack_b, bool silent) { bool status; status = reverse_rotate(stack_b); if (status && !silent) ft_putendl_fd("rrb", 1); return (status); } bool do_rrr(t_stack *stack_a, t_stack *stack_b, bool silent) { bool status; status = false; if ((stack_a->length > 1) && (stack_b->length > 1)) { if ((reverse_rotate(stack_a) && reverse_rotate(stack_b)) && !silent) { ft_putendl_fd("rrr", 1); status = true; } } else if ((stack_a->length > 1)) status = do_ra(stack_a, silent); else status = do_rb(stack_b, silent); return (status); }
C
#include "../binary_trees.h" /** * main - Entry point * * Return: 0 on success, error code on failure */ int main(void) { binary_tree_t *root; root = binary_tree_node(NULL, 98); root->left = binary_tree_node(root, 64); root->left->left = binary_tree_node(root->left, 32); binary_tree_print(root); printf("Rotate-right %d\n", root->n); root = binary_tree_rotate_right(root); binary_tree_print(root); printf("\n"); root->left->left = binary_tree_node(root->left, 20); root->left->right = binary_tree_node(root->left, 56); binary_tree_print(root); printf("Rotate-right %d\n", root->n); root = binary_tree_rotate_right(root); binary_tree_print(root); return (0); }
C
/* ** set_param.c for zappy in /home/chazot_a/rendu/PSU_2014_zappy/sources/GFX ** ** Made by Jordan Chazottes ** Login <[email protected]> ** ** Started on Sun Jul 5 19:25:22 2015 Jordan Chazottes ** Last update Mon Jul 6 17:39:23 2015 Jordan Chazottes */ #include "gfx.h" int set_player_param(t_player *new, char *token) { char *tok; if ((tok = strtok(token, " ")) == NULL) return (EXIT_FAILURE); if ((tok = strtok(NULL, " ")) == NULL) return (EXIT_FAILURE); new->id = atoi(tok); if ((tok = strtok(NULL, " ")) == NULL) return (EXIT_FAILURE); new->x = atoi(tok); if ((tok = strtok(NULL, " ")) == NULL) return (EXIT_FAILURE); new->y = atoi(tok); if ((tok = strtok(NULL, " ")) == NULL) return (EXIT_FAILURE); new->ori = atoi(tok); if ((tok = strtok(NULL, " ")) == NULL) return (EXIT_FAILURE); new->level = atoi(tok); if ((tok = strtok(NULL, " ")) == NULL) return (EXIT_FAILURE); if ((new->team = strdup(tok)) == NULL) return (EXIT_FAILURE); return (EXIT_SUCCESS); } int set_egg_param(t_player *new, char *token) { char *tok; if ((tok = strtok(token, " ")) == NULL) return (EXIT_FAILURE); if ((tok = strtok(NULL, " ")) == NULL) return (EXIT_FAILURE); if (my_regex(tok, ".0123456789") == EXIT_FAILURE) return (EXIT_FAILURE); new->eId = atoi(tok); if ((tok = strtok(NULL, " ")) == NULL) return (EXIT_FAILURE); if (my_regex(tok, ".0123456789") == EXIT_FAILURE) return (EXIT_FAILURE); new->id = atoi(tok); if ((tok = strtok(NULL, " ")) == NULL) return (EXIT_FAILURE); if (my_regex(tok, ".0123456789") == EXIT_FAILURE) return (EXIT_FAILURE); new->x = atoi(tok); if ((tok = strtok(NULL, " ")) == NULL) return (EXIT_FAILURE); if (my_regex(tok, ".0123456789") == EXIT_FAILURE) return (EXIT_FAILURE); new->y = atoi(tok); return (EXIT_SUCCESS); }
C
//文本文件 #include<stdio.h> #include<string.h> int main(){ char str[] = "1,2,3,4,5"; //字符串字面值初始化数组 FILE *p_file = fopen("a.txt","wb"); if (p_file) { fwrite(str,sizeof(char),strlen(str)/*数出字符个数*/,p_file); fclose(p_file); p_file = NULL; } return 0; }
C
#include <stdio.h> typedef enum State { OUT,IN }State; int main() { State state=OUT; int c; while((c=getchar())!=EOF) { switch(state) { case OUT: switch(c) { case ' ':case '\n':case '\t': break; default: state = IN; putchar(c); break; } break; case IN: switch(c) { case ' ':case '\n':case '\t': state = OUT; putchar('\n'); break; default: putchar(c); break; } break; } } return 0; }
C
/* ** my_printf_utils.c for utils in /home/onillo_l/rendu/PSU/PSU_2015_my_printf/src ** ** Made by Lucas Onillon ** Login <[email protected]> ** ** Started on Fri Nov 6 01:57:42 2015 Lucas Onillon ** Last update Mon Nov 16 23:14:34 2015 Lucas Onillon */ #include "my.h" #include "my_printf.h" /* ** Check if a flag is called in the string passed to my_printf. */ int check_flag_instance(const char *format) { int i; int check; i = check = 0; while (format[i]) { if (format[i] == '%') check++; i++; } if (check == 0) { my_put_str_spec(format); return (0); } else return (check); } /* ** Function used to return the number of character in a 'const string'. */ int my_const_strlen(const char *str) { int i; i = 0; while (str[i]) i++; return (i); } /* ** Version of the my_putchar working with const char as parameter. */ void my_put_const_char(char c, t_printf *prtf) { write(1, &c, 1); prtf->count++; return ; } /* ** This function had the same behavior as the my_putstr function, ** concept for 'const string'. */ void my_put_const_str(const char *format, t_printf *prtf) { int i; i = 0; while (format[i]) { write(1, &format[i], 1); prtf->count++; i++; } return ; } /* ** Just a putstr for const char type, no big deal. */ void my_put_str_spec(const char *format) { int i; i = 0; while (format[i]) { write(1, &format[i], 1); i++; } return ; }
C
#include<stdio.h> #include<stdlib.h> typedef struct ponto{ int x, y; }ponto; void imprime_ponto(ponto point){ printf("x = %d, y = %d", point.x, point.y); } int main(int argc, char const *argv[]) { ponto p1; p1.x = 0; p1.y = 1; imprime_ponto(p1); return 0; }
C
/* * Card Counting Helping Programs * By: Taylor Brazelton * Updated: 2/8/2015 */ #include <stdio.h> #include <stdlib.h> int main(){ bool keepGoing = true; int count = 0; while(keepGoing){ char in[3]; //Put text on screen...then ask for input. puts("Input h = high; l = low; n = neutral...\nPress enter when you are done counting the deck. \nNo need for spaces."); scanf("%1s", in); //Check what the input is.. change the count. if(in[0] == 'h') { count--; } else if(in[0] == 'l') { count++; } else if(in[0] == 'n') { continue; } else { keepGoing = false; } } //Print out the final count. printf("Count: %i", count); return 0; }
C
#include <std.h> inherit ROOM; void create() { ::create(); set_terrain(CITY); set_travel(PAVED_ROAD); set_property("light",1); set_property("indoors",1); set_property("no teleport",1); set_short("%^BLUE%^City street%^RESET%^"); set_long( "%^BLUE%^The city street is made of cobblestones winding through " "the existing structures around you. The wind blows back your " "hair as you wander through the city pathways." " This part of the city lies along the south section of the lake " "surrounding it. To the north a row of barracks begins. Up to the " "northwest lies what appears to be a large metal fence.%^RESET%^" ); set_listen("default", "The wind howls a strangled cry which causes you to feel nervous " "about being here." ); set_smell("default", "The smell of blood hangs thick in the air." ); set_items(([ "cobblestone":"There are numerous cobblestones lining the city " "pathways.", "barracks":"The barracks are merely stone structures. They most " "likely are living quarters for Drow soldiers.", "lake":"The lake is dark, murky and black as the night. You doubt " "even the drow swim in it. You also doubt you will ever " "swim in it either.", "cobblestones":"The city pathway is made up of various colored " "cobblestones which must have been mined in the caverns near here.", "fence":"It's a fence alright. To examine it closer...head northwest.", "street":"The street is made up of cobblestones and winds through " "the buildings.", "pathway":"The pathway winds through the city and is made up of " "cobblestones.", "buildings":"There are buildings lining the city streets." ])); set_exits(([ "east":"/d/dagger/drow/rooms/city3", "west":"/d/dagger/drow/rooms/city21", "north":"/d/dagger/drow/rooms/city5" ])); }
C
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <signal.h> void hander(int sig){ printf("recv sig = %d\n"); exit(EXIT_SUCCESS); } int main(void) { int sock; if((sock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP)) < 0) { perror("socket"); exit(EXIT_FAILURE); } struct sockaddr_in seraddr; memset(&seraddr,0,sizeof(seraddr)); seraddr.sin_family = AF_INET; seraddr.sin_port = htons(5188); //seraddr.sin_addr.s_addr = htonl(INADDR_ANY); seraddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //inet_aton("127.0.0.1",&servaddr.sin_addr); if(connect(sock,(struct sockaddr *)&seraddr,sizeof(seraddr)) < 0) { perror("connect"); exit(EXIT_FAILURE); } pid_t pid = fork(); if(pid < 0){ perror("fork"); exit(EXIT_FAILURE); } if(pid == 0){ char recvbuf[1024] = {0}; while (1) { memset(recvbuf,0,sizeof(recvbuf)); int ret = read(sock,recvbuf,sizeof(recvbuf)); if(ret < 0){ perror("recv"); exit(EXIT_FAILURE); } else if(ret == 0){ printf("peer close"); break; } fputs(recvbuf,stdout); } printf("child process exit\n"); kill(getppid(),SIGUSR1); exit(EXIT_SUCCESS); } else if(pid > 0){ signal(SIGUSR1,hander); char sendbuf[1024] = {0}; while(fgets(sendbuf,sizeof(sendbuf),stdin) != NULL) { write(sock,sendbuf,strlen(sendbuf)); memset(sendbuf,0,sizeof(sendbuf)); } printf("parent process exit\n"); exit(EXIT_SUCCESS); } close(sock); return 0; }
C
#include <stdio.h> #include "queue.h" #define MAX_SIZE 10 int front = 0, rear = 0; int queue[MAX_SIZE]; void enqueue(int data) { if (rear == MAX_SIZE) printf("The queue is full!\n"); else queue[rear++] = data; } int dequeue() { if (front == rear) { printf("The queue is empty!\n"); return -1; } else return queue[front++]; }
C
#include<stdio.h> int main() { int array[10] = { 0,1,2,3,4,5,6,7,8,9 }; int i = 0; for (i = 9; i >= 0; i--) { printf("%d ", array[i]); } printf("\n"); return 0; } //쳲 #include<stdio.h> int main() { int i; int f[20] = { 1,1 };//ǰԪظֵΪ1 for (i = 2; i < 20; i++) f[i] = f[i - 1] + f[i - 2]; for (i = 0; i < 20; i++) { if (i % 5 == 0) printf("\n"); printf("%12d", f[i]); } printf("\n"); return 0; } //жһǷΪ #include<stdio.h> int main() { int a; scanf("%d", &a); if (a % 2 == 1) { printf("aΪ\n"); } else { printf("aΪż\n"); } return 0; } //1-100֮ #include<stdio.h> int main() { int i = 1; for (i = 1; i <= 100; i++) { if (i % 2 == 1) { printf("%d ", i); } } printf("\n"); return 0; } //һάклཻŵһά鵱 #include<stdio.h> int main() { int a[4][2]; int b[2][4]; int i, j; for (i = 0; i < 4; i++) { for (j = 0; j < 2; j++) { printf("a[%d][%d]= ", i, j); scanf("%d ", &a[i][j]); } } printf("ά\n"); for (i = 0; i < 4; i++) { for (j = 0; j < 2; j++) { printf("%d", a[i][j]); } printf("\n"); } for (i = 0; i < 4; i++) { for (j = 0; j < 2; j++) { b[j][i] = a[i][j]; } } for (i = 0; i < 2; i++) { for (j = 0; j < 4; j++) { printf("%d", b[i][j]); } printf("\n"); } return 0; } //һ3*4ľҪдǸԪصֵԼڵкźк #include<stdio.h> int main() { int a[3][4] = { {1,2,3,4},{5,6,7,8},{9,10,11,12} }; int i, j, max; int row, col; max = a[0][0]; for (i = 0; i < 3; i++) { for (j = 0; j < 4; j++) { if (a[i][j] > max) { max = a[i][j]; row = i; col = j; } } } printf("%d %d %d", max, i, j); return 0; } //ַһ #include<stdio.h> int main() { char a[][5] = { {' ',' ','*'},{' ','*',' ','*'},{'*',' ',' ',' ','*'},{' ','*',' ',' ','*'},{' ',' ','*'} }; int i = 0, j = 0; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { printf("%c", a[i][j]); } printf("\n"); } return 0; }
C
#include <stdio.h> #include <errno.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <time.h> #include <arpa/inet.h> #include <dirent.h> #include <sys/types.h> int getDirectory(char *cwd, int sock) { //use stat.h to check if the directory exists struct stat sb; if (!(stat(cwd, &sb) == 0 && S_ISDIR(sb.st_mode)) || cwd[strlen(cwd)-1] == '/') { return 0; } return 1; } //use string tokenizer to split string by delimiter and return string array char ** separateString(char *buffer, const char *separator) { char **result = NULL; int count = 0; char *pch; pch = strtok (buffer,separator); while (pch != NULL) { result = (char**)realloc(result, sizeof(char*)*(count+1)); if (result == NULL) exit (-1); result[count] = (char*)malloc(strlen(pch)+1); strcpy(result[count], pch); count++; pch = strtok (NULL, separator); } return result; } void sendMsg(int sock,char *sentstr,struct sockaddr* saptr, socklen_t flen) { //send request(do we need to handle large files?) if (sendto(sock,sentstr,strlen(sentstr),0, saptr, flen)==-1) { perror("sending failed closing socket and exiting application...\n"); close(sock); exit(EXIT_FAILURE); } } void generateResponse(char **req, int sock, struct sockaddr_in sa, socklen_t flen, char *cwd, char* request) { char response[1024] = {0}; char sentstr[1024]; char* filecontent; long fileSize; char dir[200]; if(req[2] == NULL) { strcpy(response, "HTTP/1.0 400 Bad Request\r\n"); strcpy(sentstr, response); } else { //check format of response if(strcmp(req[2], "HTTP/1.0\r\n\r\n") != 0 || strcmp(req[0], "GET") != 0) { strcpy(response, "HTTP/1.0 400 Bad Request\r\n"); strcpy(sentstr, response); sendMsg(sock,sentstr,(struct sockaddr*)&sa, flen); } else { strcpy(dir, cwd); strcat(dir, req[1]); if(dir[strlen(dir) - 1] == '/') { strcat(dir, "index.html"); } //check if file exists FILE * f = fopen(dir, "rb"); if (f == NULL) { strcpy(response, "HTTP/1.0 404 Not Found\r\n"); strcpy(sentstr, response); sendMsg(sock,sentstr,(struct sockaddr*)&sa, flen); } else { //generate response strcpy(response, "HTTP/1.0 200 OK"); strcpy(sentstr, response); strcat(sentstr, "\n\n"); strcat(response, "; "); strcat(response, dir); strcat(response, "\n\n"); //get file content from file stream fseek(f, 0, SEEK_END); fileSize = ftell(f); rewind(f); filecontent = malloc(fileSize * (sizeof(char))); int filebuffsize = fileSize * (sizeof(char)); fread(filecontent, sizeof(char), fileSize, f); fclose(f); //handle file content depending on file size if((strlen(sentstr) + strlen(filecontent)) <= sizeof(sentstr)) { strcat(sentstr, filecontent); sendMsg(sock,sentstr,(struct sockaddr*)&sa, flen); } else if(strlen(filecontent) <= sizeof(sentstr)) { sendMsg(sock,sentstr,(struct sockaddr*)&sa, flen); sendMsg(sock,filecontent,(struct sockaddr*)&sa, flen); } else { //handle large files sendMsg(sock,sentstr,(struct sockaddr*)&sa, flen); int index = 0; while(index < filebuffsize) { sendto(sock,&filecontent[index],sizeof(sentstr),0, (struct sockaddr*)&sa, flen); index += sizeof(sentstr); } } } } } const char * months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Augt", "Sept", "Oct", "Nov", "Dec"}; time_t t = time(NULL); struct tm tm = *localtime(&t); printf("%s %d %d:%d:%d %s:%d %s; %s", months[tm.tm_mon], tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, inet_ntoa(sa.sin_addr), ntohs(sa.sin_port), request, response); } int main(int argc, char *argv[]) { if(argc != 3){ printf("need program port and directory, incorrect amount of arguments"); return 0; } //initialize socket data int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); struct sockaddr_in sa; memset(&sa,0, sizeof sa); sa.sin_family = AF_INET; sa.sin_addr.s_addr = htonl(INADDR_ANY); sa.sin_port = htons(atoi(argv[1])); socklen_t flen; ssize_t rsize; char buffer[1024]; char cwd[1024]; //construct path from current working directoy and argument getcwd(cwd, sizeof(cwd)); strcat(cwd, argv[2]); flen = sizeof(sa); //sock opt and bind if(-1 == setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &sa, flen)){ perror("Sock options failed closing socket and exiting application...\n"); close(sock); exit(EXIT_FAILURE); } if(-1 == bind(sock, (struct sockaddr *)&sa, sizeof sa)){ perror("binding failed closing socket and exiting application...\n"); close(sock); exit(EXIT_FAILURE); } //check if directory exists if(!getDirectory(cwd, sock)) { perror("directory not found or incorrect format with trailing / ..\n"); close(sock); exit(EXIT_FAILURE); } printf("%s is running on UDP port %s and serving %s\n", argv[0], argv[1], argv[2]); printf("press 'q' to quit ...\n"); //setup select parameters and helper objects fd_set read_fds; char character[80]; FD_ZERO( &read_fds ); FD_SET( STDIN_FILENO, &read_fds ); FD_SET( sock, &read_fds); while(1){ if(select(sock + 1,&read_fds, 0, 0, 0) == -1) { perror("select call failed closing socket and exiting application...\n"); close(sock); exit(EXIT_FAILURE); } if(FD_ISSET(STDIN_FILENO, &read_fds)) { //handle q press scanf("%s", character); if(strcmp(character, "q") == 0) { close(sock); return 0; } else { printf("unrecognized command"); } } if(FD_ISSET(sock, &read_fds)) { rsize = recvfrom(sock, (void*)buffer, sizeof(buffer), 0, (struct sockaddr*)&sa, &flen); if(rsize < 0) { perror("receive from failed closing socket and exiting application...\n"); close(sock); exit(EXIT_FAILURE); } char **result = NULL; result = separateString(buffer, " "); char request[1024]; //build initial request if(result[2] != NULL) { strcpy(request, result[0]); strcat(request, " "); strcat(request, result[1]); strcat(request, " "); strcat(request, result[2]); } else { strcpy(request, buffer); } //parse response log message and send response generateResponse(result, sock, sa, flen, cwd, request); memset(buffer,0 , sizeof(buffer)*sizeof(char)); free(result); result = NULL; } //reset select FD_ZERO( &read_fds ); FD_SET( STDIN_FILENO, &read_fds ); FD_SET( sock, &read_fds); } }
C
/* 2 编写一个程序,提示用户输入名和姓,并执行一下操作: a.打印名和姓,包括双引号; b.在宽度为20的字段右端打印名和姓,包括双引号; c.在宽度为20的字段左端打印名和姓,包括双引号; d.在比姓名宽度宽3的字段中打印名和姓。 */ #include <stdio.h> #include <string.h> #define NAMESIZE 12 int main(int argc, char const *argv[]) { char firstname[NAMESIZE]; char lastname[NAMESIZE]; printf("First name: "); scanf("%s", firstname); printf("Last name: "); scanf("%s", lastname); printf("\"%s, %s\"\n", firstname, lastname); printf("\"%20s, %s\"\n", firstname, lastname); printf("\"%s, %-20s\"\n", firstname, lastname); int width = strlen(firstname) + 3; printf("\"%*s, %s\"\n", width, firstname, lastname); return 0; }
C
#include "stdio.h" struct Employee1 { int roll_number; } emp1; struct Employee2 { int roll_number :32; } emp2; void bit_fields_main() { printf("size of emp1.roll_number:%d\n", sizeof(emp1)); printf("size of emp2.roll_number:%d", sizeof(emp2)); }
C
#include "bbs_mysql.h" #include "common.h" #include "logging.h" #include <arpa/inet.h> #include <errno.h> #include <mysql.h> #include <netinet/in.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <unistd.h> // Maximum number of server connections #define MAX_CONNECTIONS 10 MYSQL *conn; /** * Client connection function * @param sock Client socket * @param sockInfo Client connection information */ static void clientFunc(int sock, struct sockaddr_in *sockInfo); /** * Handles commands from client * @param sock Client socket * @param command Client command */ static void handleCommand(int sock, char *command); /** * Sends string over socket (convenience wrapper around writeMessage) * @param sock Socket over which string is sent * @param str String to be sent */ static void sendString(int sock, const char *str); /** * Format string wrapper around sendString * @param sock Socket over which string is sent * @param fmt Format string * @param ... Format string arguments */ static void sendStringf(int sock, const char *fmt, ...); int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Usage: %s <port>\n", argv[0]); exit(1); } int port = atoi(argv[1]); int servSock = socket(AF_INET, SOCK_STREAM, 0); if (servSock < 0) { perror("Error creating socket"); exit(1); } int reuse = TRUE; int ret; ret = setsockopt(servSock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)); if (ret < 0) { perror("Error setting socket option"); exit(1); } struct sockaddr_in serv; memset(&serv, 0, sizeof(struct sockaddr_in)); serv.sin_family = AF_INET; serv.sin_addr.s_addr = htonl(INADDR_ANY); serv.sin_port = htons(port); ret = bind(servSock, (struct sockaddr *)&serv, sizeof(struct sockaddr_in)); if (ret < 0) { perror("Error binding to socket"); exit(1); } ret = listen(servSock, MAX_CONNECTIONS); if (ret < 0) { perror("Error initiating listen"); exit(1); } LOG("Server listening on port %d\n", port); int running = TRUE; while (running) { struct sockaddr_in clientInfo; socklen_t structSize = sizeof(struct sockaddr_in); int sock = accept(servSock, (struct sockaddr *)&clientInfo, &structSize); // TODO: Move to pthreads int cpid = fork(); if (cpid < 0) { ERR("Error creating child\n"); } else if (cpid == 0) { clientFunc(sock, &clientInfo); } } return 0; } static void clientFunc(int sock, struct sockaddr_in *sockInfo) { char *sa = "SYN/ACK"; char *buff; commandinfo *cinfo; unsigned int ip = ntohl(sockInfo->sin_addr.s_addr); LOG("Client connected at IP %d.%d.%d.%d\n", ip >> 24 & 255, ip >> 16 & 255, ip >> 8 & 255, ip & 255); readMessage(sock, (void *)&buff); LOG("Received \"%s\"\n", buff); cinfo = parseCommand(buff, MSG_INCOMING); free(buff); if (cinfo->command != C_SYN) { fprintf(stderr, "Unknown client protocol\n"); close(sock); exit(1); } writeMessage(sock, (void *)sa, strlen(sa)); readMessage(sock, (void *)&buff); LOG("Received \"%s\"\n", buff); cinfo = parseCommand(buff, MSG_INCOMING); free(buff); if (cinfo->command != C_ACK) { fprintf(stderr, "Unknown client protocol\n"); close(sock); exit(1); } conn = mysql_init(NULL); if (conn == NULL) { ERR("Error: %s\n", mysql_error(conn)); exit(1); } if (mysql_real_connect(conn, "localhost", "root", "linked", "bbs", 0, NULL, 0) == NULL) { ERR("Error: %s\n", mysql_error(conn)); exit(1); } int running = TRUE; int s; while (running) { s = readMessage(sock, (void *)&buff); if (s == 0) { LOG("Client %d.%d.%d.%d disconnected\n", ip >> 24 & 255, ip >> 16 & 255, ip >> 8 & 255, ip & 255); running = FALSE; break; } handleCommand(sock, buff); free(buff); } exit(0); } static void handleCommand(int sock, char *command) { LOG("Received \"%s\"\n", command); commandinfo *cinfo = parseCommand(command, MSG_INCOMING); int id; MYSQL_RES *res; MYSQL_ROW row; char *ret; switch (cinfo->command) { case C_GET: switch (cinfo->param) { case P_POSTS: res = bbs_query(conn, "SELECT `u`.`username`, `p`.`title`, `p`.`id`" " FROM `posts` `p`" " LEFT JOIN `users` `u` ON `p`.`creator_id`=`u`.`id`"); asprintf(&ret, "POSTS"); if (ret == NULL) { ERR("Error allocating memory\n"); exit(1); } while ((row = mysql_fetch_row(res))) { char *user = protocolEscape(row[0]); char *msg = protocolEscape(row[1]); char *r; asprintf(&r, " \"%s\" \"%s\" \"%s\"", user, msg, row[2]); ret = reallocf(ret, (strlen(ret) + strlen(r)) * sizeof(char)); if (ret == NULL) { ERR("Error allocating memory\n"); exit(1); } strcat(ret, r); free(r); free(user); free(msg); } writeMessage(sock, (void *)ret, strlen(ret)); free(ret); mysql_free_result(res); break; case P_POST: if (cinfo->argCount != 3) { sendString(sock, "ERROR"); } else { id = atoi(cinfo->args[2]); res = bbs_queryf(conn, "SELECT `u`.`username`, `p`.`title`," " `p`.`content` FROM `posts` `p` LEFT JOIN `users` `u`" " ON `p`.`creator_id`=`u`.`id` WHERE `p`.`id`=%d", id); row = mysql_fetch_row(res); char *user = protocolEscape(row[0]); char *title = protocolEscape(row[1]); char *content = protocolEscape(row[2]); sendStringf(sock, "POST \"%s\" \"%s\" \"%s\"", user, title, content); free(user); free(title); free(content); mysql_free_result(res); } break; default: sendString(sock, "UNKNOWN"); break; } break; default: sendString(sock, "UNKNOWN"); break; } } static void sendString(int sock, const char *str) { writeMessage(sock, (void *)str, strlen(str)); } static void sendStringf(int sock, const char *fmt, ...) { va_list ap; va_start(ap, fmt); char *msg; int len = vasprintf(&msg, fmt, ap); va_end(ap); if (msg == NULL) { ERR("Error allocating memory\n"); exit(1); } writeMessage(sock, (void *)msg, len); }
C
#include<sys/socket.h> int get_line(int cfd,char* buf,int size){ int i=0; char c='\0'; int n=0; while((i<size-1)&&(c!='\n')){ n=recv(cfd,&c,1,0); if(n>0){ if(c=='\r'){ /*拷贝读一次*/ n=recv(cfd,&c,1,MSG_PEEK); if((n>0)&&(c=='\n')){ recv(cfd,&c,1,0); }else{ c='\n'; } } buf[i]=c; i++; }else{ c='\n'; } } buf[i]='\0'; if(n==-1){ i=n; } return i; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> //----------------------------------------------------------------------------- int main(void) { printf("The real user of this process has ID %d\n",getuid()); printf("The effective user of this process has ID %d\n",geteuid()); printf("The real user group ID for this process is %d\n",getgid()); printf("The effective user group for this process is %d\n",getegid()); return(EXIT_SUCCESS); } //-----------------------------------------------------------------------------
C
#include <stdio.h> #include <string.h> #include <stdbool.h> #include <stdlib.h> // Traits struct Monster { char *name; float size; }; // Constructor void Monster_Constructor(struct Monster* this, char *n, float s) { this->name = n; this->size = s; } // Inheritance struct Zombie { struct Monster monster; float age; }; void Zombie_Constructor(struct Zombie *this, char *n, float s, float a) { // manually call base classes constructors first Monster_Constructor(&this->monster, n, s); // then, additional fields; this->age = a; } int main() { // struct Monster *Frank = (struct Monster *)malloc((int)sizeof(struct Monster)); struct Monster Frank; Monster_Constructor(&Frank, "Frank", 42); printf("%s\n", Frank.name); printf("%f\n", Frank.size); struct Zombie Gordon; Zombie_Constructor(&Gordon, "Gordon", 50, 51); printf("%s\n", Gordon.monster.name); printf("%f\n", Gordon.monster.size); printf("%f\n", Gordon.age); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* printer.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: anorjen <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/09 22:02:12 by anorjen #+# #+# */ /* Updated: 2020/11/22 19:49:35 by anorjen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_select.h" t_arg *get_arg_n(int n) { t_arg *tmp; if (n <= 0 || n > g_select->args_size) return (g_select->args); tmp = g_select->args; while (n--) tmp = tmp->next; return (tmp); } t_arg *get_begin_arg(int w_cols, int w_lines) { int b_pos; int a_col; int a_pos; int w_elems; if (g_select->active_arg->position + 1 > w_cols * w_lines) { a_pos = g_select->active_arg->position; a_col = a_pos % w_cols; w_elems = w_lines * w_cols; b_pos = a_pos - a_col - (w_elems - w_cols); return (get_arg_n(b_pos)); } return (g_select->args); } int count_printed(t_arg *first_arg, int nums) { int first; int size; first = first_arg->position; size = g_select->args_size; return (MIN(size - first, nums)); } static int check_tty(int cmd_cols, int cmd_lines) { if (cmd_cols <= 0 || cmd_lines <= 0) { write(g_tty_fd, "NO SPACE\nPRESS ESC\nTO EXIT", 26); return (1); } return (0); } int print_args(void) { int cmd_cols; int cmd_lines; int i; t_arg *args; int count; tputs(g_term->cl, 1, print_char); cmd_cols = get_colums(g_select->colum_size); cmd_lines = get_lines(); if (check_tty(cmd_cols, cmd_lines) != 0) return (1); args = get_begin_arg(cmd_cols, cmd_lines); count = count_printed(args, cmd_cols * cmd_lines); i = -1; while (++i < count) { print_arg(args, g_select->colum_size); if ((i + 1) % cmd_cols == 0 && i != (count - 1)) write(g_tty_fd, "\n", 1); args = args->next; } return (0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* errors.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: smaccary <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/04 18:30:19 by smaccary #+# #+# */ /* Updated: 2020/08/04 18:30:19 by smaccary ### ########.fr */ /* */ /* ************************************************************************** */ #include "debug.h" int check_file(char *path) { int fd; fd = open(path, O_RDONLY); if (fd <= 0) return (FILE_INVALID_ERROR); return (SUCCESS_CODE); } int error_print(int error) { static char *errors[] = { "NO ERROR", "UNKNOWN ERROR", "FILE INVALID ERROR", "MAP ERROR", "WRONG FILE EXTENSION", "NULL ERROR", "MALLOC ERROR", "CONFIG ERROR", "RESOLUTION_ERROR", "COLOR ERROR", "TEXTURE_ERROR", "MLX_ERROR", 0 }; int i; i = -1; if (error == SUCCESS_CODE) return (SUCCESS_CODE); while (errors[++i]) { if (i == -error) { ft_putendl_fd(errors[-error], STDERR); return (error); } } ft_putendl_fd("UNKNOWN ERROR", STDERR); return (error); }
C
#pragma once #include <inttypes.h> #ifdef __cplusplus extern "C" { #endif /* Begin C API */ struct fastlock; void fastlock_init(struct fastlock *lock); void fastlock_lock(struct fastlock *lock); int fastlock_trylock(struct fastlock *lock, int fWeak); void fastlock_unlock(struct fastlock *lock); void fastlock_free(struct fastlock *lock); int fastlock_unlock_recursive(struct fastlock *lock); void fastlock_lock_recursive(struct fastlock *lock, int nesting); uint64_t fastlock_getlongwaitcount(); // this is a global value /* End C API */ #ifdef __cplusplus } #endif #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" struct ticket { union { struct { uint16_t m_active; uint16_t m_avail; }; unsigned u; }; }; #pragma GCC diagnostic pop struct fastlock { volatile struct ticket m_ticket; volatile int m_pidOwner; volatile int m_depth; unsigned futex; #ifdef __cplusplus fastlock() { fastlock_init(this); } void lock() { fastlock_lock(this); } bool try_lock(bool fWeak = false) { return !!fastlock_trylock(this, fWeak); } void unlock() { fastlock_unlock(this); } int unlock_recursive() { return fastlock_unlock_recursive(this); } void lock_recursive(int nesting) { fastlock_lock_recursive(this, nesting); } bool fOwnLock(); // true if this thread owns the lock, NOTE: not 100% reliable, use for debugging only #endif };
C
int getRandNum() { FILE *fp; if ((fp = fopen("/dev/urandom", "r")) == NULL) { fprintf(stderr, "Error!, Could not open /dev/urandom to read.\n"); return -1; } int result = fgetc(fp); return result; } char *getRandString(size_t len) { const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890,./<>?`~!@#$%^&*()-=_+[]{}|\\'\""; if (len < 2) { fprintf(stderr, "The given length must larger than 1.\n"); return NULL; } char *result = malloc(sizeof(char)*(len+1)); int key; for (int i=0; i<len; i++) { if ((key = getRandNum()) == -1) { fprintf(stderr, "Could not get random number.\n"); return NULL; } key = key % ((int)sizeof(charset)-1); //printf("%d\n", key); result[i] = charset[key]; } result[len] = '\0'; return result; }
C
#include <stdio.h> #include "ImageCompression.h" //#define IMAGESIZE 256 //#define DEBUG struct node{ int i; int j; struct node *nextPtr; }; typedef struct node NODE; typedef NODE *NODEPTR; struct LISnode{ int i; int j; char type; struct LISnode *nextPtr; }; typedef struct LISnode LISNODE; typedef LISNODE *LISNODEPTR; /* void ReadData(unsigned short *buffer,int *ptr,FILE *fp){ int i,bit; unsigned short tmp; fread(&tmp,sizeof(unsigned short),1,fp); for(i=0;i<16;i++){ bit = (tmp>>(15-i))&0x01; *(buffer+(i+*ptr)) = bit; #ifdef DEBUG printf("*(buffer+%d)=%d tmp = %d\n",i+*ptr,*(buffer+(i+*ptr)),tmp); #endif } *ptr = *ptr + 16; } */ int isEmpty(NODEPTR headPtr){ return headPtr == NULL; } int isLISEmpty(LISNODEPTR headPtr){ return headPtr == NULL; } void enqueue(NODEPTR *headPtr, NODEPTR *tailPtr, int ivalue, int jvalue){ NODEPTR newPtr,currentPtr; newPtr = malloc(sizeof(NODE)); if(newPtr != NULL){ newPtr->i = ivalue; newPtr->j = jvalue; newPtr->nextPtr = NULL; if(isEmpty(*headPtr)){ *headPtr = newPtr; } else{ (*tailPtr)->nextPtr = newPtr; } *tailPtr = newPtr; }else{ printf("No memory available.\n"); } } void enlisqueue(LISNODEPTR *headPtr, LISNODEPTR *tailPtr, int ivalue, int jvalue,char type){ LISNODEPTR newPtr,currentPtr; newPtr = malloc(sizeof(LISNODE)); //printf("enque (%d %d)\n",ivalue,jvalue); if(newPtr != NULL){ newPtr->i = ivalue; newPtr->j = jvalue; newPtr->type = type; newPtr->nextPtr = NULL; if(isLISEmpty(*headPtr)){ *headPtr = newPtr; } else{ //printf("enque (%d %d), head=(%d %d), tail=(%d,%d)\n",ivalue,jvalue,(*headPtr)->i,(*headPtr)->j,(*tailPtr)->i,(*tailPtr)->j); (*tailPtr)->nextPtr = newPtr; } *tailPtr = newPtr; }else{ printf("No memory available.\n"); } } int removenode(NODEPTR *headPtr, NODEPTR *tailPtr,int ivalue, int jvalue){ NODEPTR previousPtr, currentPtr, tempPtr; if(ivalue==(*headPtr)->i && jvalue==(*headPtr)->j){ //move node = head if(ivalue==(*tailPtr)->i && jvalue==(*tailPtr)->j){ //&& head = tail *tailPtr = NULL; } tempPtr = *headPtr; *headPtr = (*headPtr)->nextPtr; free(tempPtr); #ifdef DEBUG printf("remove %d %d\n",ivalue,jvalue); #endif return 1; }else{ previousPtr = *headPtr; currentPtr = (*headPtr)->nextPtr; while(currentPtr!=NULL && (currentPtr->i!=ivalue || currentPtr->j!=jvalue)){ previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } if(currentPtr != NULL){ #ifdef DEBUG printf("remove %d %d,ivalue=%d,jvalue=%d\n",currentPtr->i,currentPtr->j,ivalue,jvalue); #endif tempPtr = currentPtr; if(ivalue==(*tailPtr)->i && jvalue==(*tailPtr)->j){ *tailPtr = previousPtr; } previousPtr->nextPtr = currentPtr->nextPtr; free(tempPtr); return 1; } } return 0; } int removeLISnode(LISNODEPTR *headPtr,LISNODEPTR *tailPtr,int ivalue, int jvalue){ LISNODEPTR previousPtr, currentPtr, tempPtr; //if(ivalue==(*tailPtr)->i && jvalue==(*tailPtr)->j){ //printf("remove tail(%d,%d) head = (%d,%d)\n",(*tailPtr)->i,(*tailPtr)->j,(*headPtr)->i,(*headPtr)->j); //} //printf("tail = (%d,%d) head = (%d,%d) remove(%d,%d)\n",(*tailPtr)->i,(*tailPtr)->j,(*headPtr)->i,(*headPtr)->j,ivalue,jvalue); if(ivalue==(*headPtr)->i && jvalue==(*headPtr)->j){ if(ivalue==(*tailPtr)->i && jvalue==(*tailPtr)->j && (*headPtr)->nextPtr == NULL){ *tailPtr = NULL; } tempPtr = *headPtr; *headPtr = (*headPtr)->nextPtr; free(tempPtr); #ifdef DEBUG printf("remove %d %d\n",ivalue,jvalue); #endif return 1; }else{ previousPtr = *headPtr; currentPtr = (*headPtr)->nextPtr; while(currentPtr!=NULL && (currentPtr->i!=ivalue || currentPtr->j!=jvalue)){ //printf("previous = (%d,%d) current = (%d,%d)\n",(previousPtr)->i,(previousPtr)->j,(currentPtr)->i,(currentPtr)->j); previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } if(currentPtr != NULL){ //printf("current = (%d,%d)\n",(currentPtr)->i,(currentPtr)->j); #ifdef DEBUG printf("remove %d %d,ivalue=%d,jvalue=%d\n",currentPtr->i,currentPtr->j,ivalue,jvalue); #endif tempPtr = currentPtr; //if(ivalue==(*tailPtr)->i && jvalue==(*tailPtr)->j){ //printf("tail = (%d,%d)\n",(*tailPtr)->i,(*tailPtr)->j); //} if(ivalue==(*tailPtr)->i && jvalue==(*tailPtr)->j && currentPtr->nextPtr == NULL){ *tailPtr = previousPtr; } previousPtr->nextPtr = currentPtr->nextPtr; free(tempPtr); return 1; } } return 0; } int SnD(unsigned short *img,int i,int j,int n){ int bit; if(i==0 && j==0){ bit = ((*(img+IMAGESIZE*i+j)>>n)&0x01); return bit; } if(i>=IMAGESIZE || j>=IMAGESIZE){ return 0; }else{ bit = ((*(img+IMAGESIZE*i+j)>>n)&0x01); //printf("(%d %d)=%d\n",i,j,bit); if(bit == 1){ return 1; }else{ if(SnD(img,2*i,2*j,n) || SnD(img,2*i+1,2*j,n) || SnD(img,2*i,2*j+1,n) || SnD(img,2*i+1,2*j+1,n)){ return 1; } } } return 0; } int SnL(unsigned short *img,int i,int j,int n){ unsigned short temp[4]; temp[0] = *(img+IMAGESIZE*(2*i)+(2*j)); temp[1] = *(img+IMAGESIZE*(2*i+1)+(2*j)); temp[2] = *(img+IMAGESIZE*(2*i)+(2*j+1)); temp[3] = *(img+IMAGESIZE*(2*i+1)+(2*j+1)); *(img+IMAGESIZE*(2*i)+(2*j)) = 0; *(img+IMAGESIZE*(2*i+1)+(2*j)) = 0; *(img+IMAGESIZE*(2*i)+(2*j+1)) = 0; *(img+IMAGESIZE*(2*i+1)+(2*j+1)) = 0; if(SnD(img,2*i,2*j,n) || SnD(img,2*i+1,2*j,n) || SnD(img,2*i,2*j+1,n) || SnD(img,2*i+1,2*j+1,n)){ *(img+IMAGESIZE*(2*i)+(2*j)) = temp[0]; *(img+IMAGESIZE*(2*i+1)+(2*j)) = temp[1]; *(img+IMAGESIZE*(2*i)+(2*j+1)) = temp[2]; *(img+IMAGESIZE*(2*i+1)+(2*j+1)) = temp[3]; return 1; } *(img+IMAGESIZE*(2*i)+(2*j)) = temp[0]; *(img+IMAGESIZE*(2*i+1)+(2*j)) = temp[1]; *(img+IMAGESIZE*(2*i)+(2*j+1)) = temp[2]; *(img+IMAGESIZE*(2*i+1)+(2*j+1)) = temp[3]; return 0; } main(){ unsigned short *img,*sign,temp; int i,j,n,Snbit,SnDbit,SnLbit,k,l,buffptr,bpt; unsigned int LSPamount,LSPcount,thisLSP,bitcounter,bitrate; unsigned short buff[32] = {0}; float rate; char type; NODEPTR LIPheadPtr=NULL,LIPtailPtr=NULL,LSPheadPtr=NULL,LSPtailPtr=NULL,currentPtr=NULL,previousPtr=NULL; LISNODEPTR LISheadPtr=NULL,LIStailPtr=NULL,currentLISPtr=NULL,previousLISPtr=NULL; FILE *dbg,*Out,*Re; img = calloc((IMAGESIZE)*(IMAGESIZE),sizeof(unsigned short)); sign = calloc((IMAGESIZE)*(IMAGESIZE),sizeof(unsigned short)); dbg = fopen("decdebug.txt","w"); Out = fopen("spihtdata.bin","rb"); buffptr = 0; bpt = 0; for(i=0;i<32;i++){ buff[i] = 0; } for(i=0;i<IMAGESIZE;i++){ for(j=0;j<IMAGESIZE;j++){ *(img+IMAGESIZE*i+j) = 0; *(sign+IMAGESIZE*i+j) = 0; } } //Initional bitcounter = 0; LSPheadPtr = NULL; LSPtailPtr = NULL; LIPheadPtr = NULL; LIPtailPtr = NULL; LISheadPtr = NULL; LIStailPtr = NULL; for(i=0;i<8;i++){ for(j=0;j<8;j++){ enqueue(&LIPheadPtr,&LIPtailPtr,i,j); } } for(i=0;i<8;i++){ for(j=0;j<8;j++){ if(i<4 && j<4){ continue; } enlisqueue(&LISheadPtr,&LIStailPtr,i,j,'A'); } } #ifdef DEBUG currentPtr = LIPheadPtr; while(currentPtr != NULL){ printf(dbg,"%d %d\n",currentPtr->i,currentPtr->j); currentPtr = currentPtr->nextPtr; } currentLISPtr = LISheadPtr; while(currentLISPtr != NULL){ printf("%d %d %c\n",currentLISPtr->i,currentLISPtr->j,currentLISPtr->type); currentLISPtr = currentLISPtr->nextPtr; } #endif //Sort Pass LSPamount = 0; thisLSP = 0; //printf("n ?"); //scanf("%d", &n); n = getc(Out); fscanf(Out,"%f",&rate); printf("rate = %f\n",rate); bitrate = IMAGESIZE*IMAGESIZE*rate; ReadData(buff,&buffptr,Out); for( ;n>=1;n--){ if(bitcounter >= bitrate){ break; } LSPamount = LSPamount + thisLSP; thisLSP = 0; //2.1 currentPtr = LIPheadPtr; while(currentPtr != NULL && bitcounter < bitrate){ i = currentPtr->i; j = currentPtr->j; currentPtr = currentPtr->nextPtr; //2.1.1 output Sn(i,j) if(bpt>=16){ buffptr = 0; bpt = 0; ReadData(buff,&buffptr,Out); } Snbit = buff[bpt]; //printf("buffptr=%d\n",bpt); bpt++; *(img+IMAGESIZE*i+j) = *(img+IMAGESIZE*i+j) + ((Snbit<<n)*1.5); //*(img+IMAGESIZE*i+j) = *(img+IMAGESIZE*i+j) + ((Snbit<<n)); fprintf(dbg,"Sn(%d,%d) = %d\n",i,j,Snbit); bitcounter++; if(bitcounter >= bitrate){ break; } //2.1.2 if(Snbit == 1){ enqueue(&LSPheadPtr,&LSPtailPtr,i,j); thisLSP++; removenode(&LIPheadPtr,&LIPtailPtr,i,j); if(bpt>=16){ buffptr = 0; bpt = 0; ReadData(buff,&buffptr,Out); } *(sign+IMAGESIZE*i+j) = buff[bpt]; fprintf(dbg,"sign[%d][%d] = %d\n",i,j,*(sign+IMAGESIZE*i+j)); bpt++; bitcounter++; if(bitcounter >= bitrate){ break; } } } //2.2 currentLISPtr = LISheadPtr; while(currentLISPtr != NULL && bitcounter < bitrate){ i = currentLISPtr->i; j = currentLISPtr->j; type = currentLISPtr->type; currentLISPtr = currentLISPtr->nextPtr; //2.2.1 if(type == 'A'){ //temp = *(img+IMAGESIZE*i+j); //img[i][j] = 0; if(bpt>=16){ buffptr = 0; bpt = 0; ReadData(buff,&buffptr,Out); } SnDbit = buff[bpt]; bpt++; //SnDbit = SnD(img,i,j,n); //*(img+IMAGESIZE*i+j) = temp; fprintf(dbg,"Sn(D(%d,%d))=%d\n",i,j,SnDbit); bitcounter++; if(bitcounter >= bitrate){ break; } if(SnDbit == 1){ //for each(k,l) in O(i,j) for(k=2*i;k<=2*i+1;k++){ for(l=2*j;l<=2*j+1;l++){ if(bpt>=16){ buffptr = 0; bpt = 0; ReadData(buff,&buffptr,Out); } Snbit = buff[bpt]; bpt++; //*(img+IMAGESIZE*k+l) = *(img+IMAGESIZE*k+l) + (Snbit<<n); *(img+IMAGESIZE*k+l) = *(img+IMAGESIZE*k+l) + ((Snbit<<n)*1.5); //Snbit = ((*(img+IMAGESIZE*k+l)>>n)&0x01); fprintf(dbg,"Sn(%d,%d)=%d\n",k,l,Snbit); //buff[bpt] = Snbit; //buffptr++; bitcounter++; if(bitcounter >= bitrate){ break; } if(Snbit==1){ enqueue(&LSPheadPtr,&LSPtailPtr,k,l); if(bpt>=16){ buffptr = 0; bpt = 0; ReadData(buff,&buffptr,Out); } *(sign+IMAGESIZE*k+l) = buff[bpt]; bpt++; fprintf(dbg,"sign(%d,%d)=%d\n",k,l,*(sign+IMAGESIZE*k+l)); //buff[bpt] = sign[k][l]; //buffptr++; //if(buffptr >= 16){ // WriteData(buff,&buffptr,Out); //} bitcounter++; if(bitcounter >= bitrate){ break; } thisLSP++; }else{ enqueue(&LIPheadPtr,&LIPtailPtr,k,l); } } } //if L(i,j) != empty if(i<=IMAGESIZE/4 && j<=IMAGESIZE/4){ enlisqueue(&LISheadPtr,&LIStailPtr,i,j,'B'); } removeLISnode(&LISheadPtr,&LIStailPtr,i,j); } //2.2.2 }else if(type == 'B'){ if(bpt>=16){ buffptr = 0; bpt = 0; ReadData(buff,&buffptr,Out); } SnLbit = buff[bpt]; bpt++; //SnLbit = SnL(img,i,j,n); fprintf(dbg,"Sn(L(%d,%d))=%d\n",i,j,SnLbit); //buff[bpt] = SnLbit; //buffptr++; //if(buffptr >= 16){ // WriteData(buff,&buffptr,Out); //} bitcounter++; if(bitcounter >= bitrate){ break; } if(SnLbit == 1){ //each (k,l) in O(i,j) for(k=2*i;k<=2*i+1;k++){ for(l=2*j;l<=2*j+1;l++){ enlisqueue(&LISheadPtr,&LIStailPtr,k,l,'A'); } } removeLISnode(&LISheadPtr,&LIStailPtr,i,j); } } } //3 LSPcount = 0; currentPtr = LSPheadPtr; while(currentPtr != NULL && LSPcount<LSPamount && bitcounter < bitrate){ LSPcount++; i = currentPtr->i; j = currentPtr->j; currentPtr = currentPtr->nextPtr; if(bpt>=16){ buffptr = 0; bpt = 0; ReadData(buff,&buffptr,Out); } Snbit = buff[bpt]; bpt++; *(img+IMAGESIZE*i+j) = *(img+IMAGESIZE*i+j) + ((Snbit-0.5)*(1<<n)); //*(img+IMAGESIZE*i+j) = *(img+IMAGESIZE*i+j) + ((Snbit<<n)); //Snbit = ((*(img+IMAGESIZE*i+j)>>n)&0x01); fprintf(dbg,"(%d,%d) = %d\n",i,j,Snbit); //buff[bpt] = Snbit; //buffptr++; //if(buffptr >= 16){ // WriteData(buff,&buffptr,Out); //} bitcounter++; if(bitcounter >= bitrate){ break; } } printf("bitcounter = %d,LSPamount=%d\n",bitcounter,LSPamount); //printf LIP currentPtr = LIPheadPtr; fprintf(dbg,"LIPnode:\n"); while(currentPtr != NULL){ fprintf(dbg,"%d %d\n",currentPtr->i,currentPtr->j); currentPtr = currentPtr->nextPtr; } //printf LIS currentLISPtr = LISheadPtr; fprintf(dbg,"LISnode:\n"); while(currentLISPtr != NULL){ fprintf(dbg,"%d %d %c\n",currentLISPtr->i,currentLISPtr->j,currentLISPtr->type); currentLISPtr = currentLISPtr->nextPtr; } //printf LSP currentPtr = LSPheadPtr; fprintf(dbg,"LSPnode:\n"); while(currentPtr != NULL){ fprintf(dbg,"%d %d\n",currentPtr->i,currentPtr->j); currentPtr = currentPtr->nextPtr; } } Re = fopen("RWT.raw","w"); for(i=0;i<IMAGESIZE;i++){ for(j=0;j<IMAGESIZE;j++){ fprintf(Re," %d",*(img+IMAGESIZE*i+j)*(*(sign+IMAGESIZE*i+j)*2-1)); } fprintf(Re,"\n"); } fclose(Re); fclose(Out); fclose(dbg); free(img); free(sign); printf("End of the problem.\n"); getch(); }
C
#include <string.h> #include <stdlib.h> #include "constants.h" #include "types.h" #include "storage.h" struct Channel *channels_cache[CHANNELS_CACHE_SIZE] = {0}; int tail_index = 0; void cache_add(struct Channel *channel) { if (channels_cache[tail_index]) { delete_channel(channels_cache[tail_index]); } channels_cache[tail_index] = channel; tail_index = (tail_index + 1) % CHANNELS_CACHE_SIZE; } int find_index(int channel_id) { for (int i = 0; i < CHANNELS_CACHE_SIZE; i++) { if (channels_cache[i] && channels_cache[i]->id == channel_id) { return i; } } return -1; } struct Channel *cache_find(int channel_id) { int index = find_index(channel_id); return index != -1 ? channels_cache[index] : 0; } void cache_update(int channel_id, struct Channel *channel) { int index = find_index(channel_id); if (index != -1) { struct Channel *old_channel = channels_cache[index]; free(old_channel->key); delete_posts(old_channel); memcpy(channels_cache[index], channel, sizeof(struct Channel)); free(channel); } else { cache_add(channel); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* builtins.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mery <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/03/04 13:09:33 by mmasson #+# #+# */ /* Updated: 2014/03/18 12:12:55 by mery ### ########.fr */ /* */ /* ************************************************************************** */ #include "42sh.h" char **ft_unsetmyenv(char *var, char **env) { int i; int j; char **newenv; if (!var || !env) return (env); newenv = (char**)malloc(sizeof(newenv) * ft_tablerange(env)); if (newenv) { i = -1; j = 0; while (env[++i]) { if (ft_iskey(env[i], var) == EXIT_SUCCESS) free(env[i]); else { newenv[j] = env[i]; j++; } } newenv[j] = NULL; } free(env); return (newenv); } void ft_setenv(char *var, char *value_to_set) { int i; char *tmp; i = -1; tmp = NULL; if (var == NULL || value_to_set == NULL) { ft_puterror("42sh: Usage <setenv variable value_to_set>\n"); return ; } while (shell->g_myenv[++i] && tmp == NULL) { if (ft_iskey(shell->g_myenv[i], var) == EXIT_SUCCESS) { tmp = ft_create_var(var, value_to_set); if (tmp) { free(shell->g_myenv[i]); shell->g_myenv[i] = tmp; } } } if (tmp == NULL) shell->g_myenv = ft_stock_table(ft_create_var(var, value_to_set), \ shell->g_myenv); } char **ft_setmyenv(char *var, char *value_to_set, char **env) { int i; char *tmp; i = -1; tmp = NULL; if (var == NULL || value_to_set == NULL) return (env); if (env) { while (env[++i] && tmp == NULL) { if (ft_iskey(env[i], var) == EXIT_SUCCESS) { tmp = ft_create_var(var, value_to_set); if (tmp) { free(env[i]); env[i] = tmp; } } } } if (tmp == NULL) return (ft_stock_table(ft_create_var(var, value_to_set), env)); return (env); } char *ft_create_var(char *var, char *value_to_set) { char *tmp; tmp = (char*)malloc(sizeof(tmp) * (ft_strlen(var) + \ ft_strlen(value_to_set) + 2)); if (tmp) { ft_strcpy(tmp, var); ft_strncat(tmp, "=", 1); ft_strncat(tmp, value_to_set, ft_strlen(value_to_set)); } return (tmp); }
C
#include<stdio.h> #include<math.h> int main() { int a,b,c,x; double pow(double x,double y); for(x=100;x<1000;x++) { a=x/100%10; b=x/10%10; c=x/1%10; if(x==pow(a,3)+pow(b,3)+pow(c,3)) { printf("%d\n",x); } } return 0; }
C
/** cju_str.c * Clanjor Utilities Library: String ** * This code is under GPLv3, NO WARRANTY!!! * Copyleft (C) eXerigumo Clanjor, 2010-2011. ** * Coded by eXerigumo Clanjor. */ #include <stdlib.h> #include "cju_str.h" cju_str_t *cju_str_new(void) { return calloc(sizeof(cju_str_t), 1); /* cju_str_t *str; if (str = malloc(sizeof(cju_str_t)) == NULL) return NULL; str->data = NULL; str->used = -1; return str; */ } cju_str_t *cju_str_new_with_cstr(const char *cstr) { cju_str_t *str; if ((str = cju_str_new()) == NULL) return NULL; cju_str_cat_cstr(str, cstr); return str; } void cju_str_free(cju_str_t *str) { free(str->data); free(str); } bool cju_str_append(cju_str_t *str, char ch) { // Allocate memory if (str->used == 0 || (str->used + 1) % CJU_STR_BLOCK_SIZE == 0) { // ^^^^^ +1 is for the 'end of string' (0 of course). str->data = realloc(str->data, str->used + 1 + CJU_STR_BLOCK_SIZE); if (str->data == NULL) return false; } // Append <ch> followed by 0, you know why. str->data[str->used++] = ch; str->data[str->used] = 0; return true; } // TODO: Improve performance. bool cju_str_cat_cstr(cju_str_t *str, const char *src) { while (*src) if (!cju_str_append(str, *src++)) return false; return true; } // NEVER free the cstring returned!!! char *cju_str_get_cstr(cju_str_t *str) { return str->data; }
C
#include "my.h" /* Nicholas Massa * I pledge my honor that I have abided by the Stevens Honor System. * LibMy v1.1 tests: Tests for adding multiple string functionality to LibMy. * Test main returns 0 and displays "All Tests complete" if all tests pass. * If a test fails, my_panic will exit. * */ /* NOTE: string comparison NOT used until it is tested. */ int main() { char* str = "hello"; char* str2 = "This is a longer string."; char* empty = ""; char* dst = "abcdef"; char* test = ""; unsigned int n = -1; my_str("---- 1. my_strdup ----"); my_char('\n'); my_str("Should read hello below:"); test = my_strdup(str); my_str(test); my_char('\n'); /* Returns copy of hello to be printed */ test = ""; my_str("Should read 'This is a longer string' below:"); test = my_strdup(str2); my_str(test); my_char('\n'); my_str("Should read blank below (blank):"); my_char('\n'); test = my_strdup(empty); my_str(test); my_char('\n'); my_str("Should read blank below (blank):"); my_char('\n'); test = my_strdup(NULL); my_str(test); my_char('\n'); my_str("my_strdup tests complete."); my_char('\n'); my_char('\n'); my_str("---- 2. my_strcpy ----"); my_char('\n'); my_str("Should read 'Test' below:"); my_char('\n'); my_str(my_strcpy(str, "Test")); my_char('\n'); my_str("Should read 'Test' below (into empty):"); my_char('\n'); my_str(my_strcpy(empty, "Test")); my_char('\n'); my_str("Should be blank below (empty str):"); my_char('\n'); my_str(my_strcpy(str,"")); my_char('\n'); my_str("Should be blank below (str, NULL):"); my_char('\n'); my_str(my_strcpy(str, NULL)); my_char('\n'); my_str("Should be blank below (NULL, str):"); my_char('\n'); my_str(my_strcpy(NULL, str)); my_char('\n'); my_str("Should be blank below (NULL,NULL):"); my_str(my_strcpy(NULL, NULL)); my_char('\n'); str = "hello"; my_str("my_strcpy tests complete."); my_char('\n'); my_char('\n'); #if 0 my_str("---- 3. my_strncpy ----"); my_char('\n'); my_str("Should read 'Dello' below:"); my_char('\n'); my_str(my_strncpy(str, "DUH", 1)); my_char('\n'); my_str("Should read 'Hellef' below:"); my_char('\n'); my_str(my_strncpy(dst, "Hello", 4); my_char('\n'); my_str("Should read 'Hello' below (large n val):"); my_char('\n'); my_str(my_strncpy(empty, "Hello", 12345); my_char('\n'); my_str("Should read 'This is a longer string' below (str2,NULL,12345):"); my_char('\n'); my_str(my_strncpy(str2, NULL, 12345); my_char('\n'); my_str("Should be blank below (NULL, str, 12345):"); my_char('\n'); my_str(my_strncpy(NULL, str, 12345); my_char('\n'); my_str("Test for max unsigned int:"); my_char('\n'); my_str(mystrncpy(str, "hello", n)); my_char('\n'); str[] = "hello"; str2[] = "This is a longer string"; empty[] = "abcdef"; my_str("my_strncpy tests complete."); my_str("---- 4. my_strcmp ----"); my_char('\n'); if(my_strcmp("Hello","Hello") != 0) my_panic("Equal test failed", 1); if(my_strcmp("Hello","AAAAAAAAAAAA") >= 0) my_panic("strcmp(Hello,AAAAAAA) did not return neg val", 1); if(my_strcmp("AAAAA", "Hello" >= 0)) my_panic("strcmp(AAAAA,Hello) did not return a pos val",1); if(my_strcmp("abc","ab") <= 0) my_panic("(abc,ab) failed should be pos val", 1); if(my_strcmp("ab","abc") >= 0) my_panic("(ab,abc) should be a neg val", 1); if(my_strcmp("","abc") >= 0) my_panic("(,abc) should be a neg val", 1); if(my_strcmp("abc","") <= 0) my_panic("(abc,) should be a pos val", 1); if(my_strcmp("","") != 0) my_panic("(,) should be 0", 1); if(my_strcmp("ab",NULL) <= 0) my_panic("(ab,NULL) should be a pos val", 1); if(my_strcmp(NULL,"abc") >= 0) my_panic("(ab,abc) should be a neg val", 1); if(my_strcmp(NULL, NULL) != 0) my_panic("(NULL, NULL) should be 0", 1); my_str("All my_strcmp tests passed."); my_char('\n'); my_char('\n'); my_str("---- 5. my_strncmp ----"); my_char('\n'); if(my_strncmp("Hello","Hello", 12345) != 0) my_panic("Equal test failed", 1); if(my_strncmp("Hello","AAAAAAAAAAAA", 1) <= 0) my_panic("strcmp(Hello,AAAAAAA, 1) did not return neg val", 1); if(my_strncmp("AAAAA", "Hello", 1) >= 0)) my_panic("strcmp(AAAAA,Hello) did not return a pos val",1); if(my_strncmp("abc","ab", 56) <= 0) my_panic("(abc,ab,56) failed should be pos val", 1); if(my_strncmp("ab","abc", 56) >= 0) my_panic("(ab,abc,56) should be a neg val", 1); if(my_strncmp("","abc", 1) >= 0) my_panic("(,abc,1) should be a neg val", 1); if(my_strncmp("abc","",1) <= 0) my_panic("(abc,,1) should be a pos val", 1); if(my_strncmp("","",2) != 0) my_panic("(,,2) should be 0", 1); if(my_strncmp("ab",NULL,2) <= 0) my_panic("(ab,NULL,2) should be a pos val", 1); if(my_strncmp(NULL,"abc",2) >= 0) my_panic("(ab,abc) should be a neg val", 1); if(my_strncmp(NULL, NULL,2) != 0) my_panic("(NULL, NULL,2) should be 0", 1); if(my_strncmp("abc", "abc", 0) != 0) my_panic("(abc, abc, 0) should be 0", 1); if(my_strncmp("abcd", "a", 0) != 0) my_panic("(abcd, a, 0) should be 0", 1); if(my_strncmp("abc","",n) <= 0) my_panic("(abc,,n) should be a pos val", 1); my_str("All my_strncmp tests passed."); my_char('\n'); my_char('\n'); my_str("---- 6. xmalloc ----"); my_char('\n'); my_str("No tests necessary. Given Function."); my_char('\n'); my_char('\n'); /* Now that strcmp has been tested, we can use that function to test the functions that return a char* */ my_str("---- 7. my_strconcat ----"); my_char('\n'); if(my_strcmp(my_strconcat("",""), "") != 0) my_panic("my_strconcat failed", 1); if(my_strcmp(my_strconcat("abc","def"), "abcdef") != 0) my_panic("my_strconcat failed", 1); if(my_strcmp(my_strconcat("","def"), "def") != 0) my_panic("my_strconcat failed", 1); if(my_strcmp(my_strconcat("",""), "") != 0) my_panic("my_strconcat failed", 1); if(my_strcmp(my_strconcat("abc",""), "abc") != 0) my_panic("my_strconcat failed", 1); if(my_strcmp(my_strconcat(NULL,NULL), NULL) != 0) my_panic("my_strconcat failed", 1); if(my_strcmp(my_strconcat(NULL,"abc"), "abc") != 0) my_panic("my_strconcat failed", 1); if(my_strcmp(my_strconcat("def",NULL), "def") != 0) my_panic("my_strconcat failed", 1); my_str("All my_strconcat tests complete."); my_char('\n'); my_char('\n'); my_str("---- 8. my_strnconcat ----"); my_char('\n'); if(my_strcmp(my_strnconcat("", "", 5), "") != 0) my_panic("my_strnconcat failed", 1); if(my_strcmp(my_strnconcat("abc", "def", 1), "abcde") != 0) my_panic("my_strnconcat failed", 1); if(my_strcmp(my_strnconcat("", "abcdefghijklmnop", 3), "abcd") != 0) my_panic("my_strnconcat failed", 1); if(my_strcmp(my_strnconcat("abcdefghijklmnop","",3), "abcdefghijklmnop") != 0) my_panic("my_strnconcat failed", 1); if(my_strcmp(my_strnconcat(NULL,NULL,5), NULL) != 0) my_panic("my_strnconcat failed", 1); if(my_strcmp(my_strnconcat(NULL,"abc",5), "abc") != 0) my_panic("my_strnconcat failed", 1); if(my_strcmp(my_strnconcat("def",NULL,5), "def") != 0) my_panic("my_strnconcat failed", 1); if(my_strcmp(my_strnconcat("abc", "def", n), "abcde") != 0) my_panic("my_strnconcat failed", 1); my_str("All my_strnconcat tests complete."); my_char('\n'); my_char('\n'); my_str("---- 9. my_strcat ----"); my_char('\n'); if(my_strcmp(my_strcat("",""), "") != 0) my_panic("my_strcat failed", 1); if(my_strcmp(my_strcat("abc","def"), "abcdef") != 0) my_panic("my_strcat failed", 1); if(my_strcmp(my_strcat("","def"), "def") != 0) my_panic("my_strcat failed", 1); if(my_strcmp(my_strcat("",""), "") != 0) my_panic("my_strcat failed", 1); if(my_strcmp(my_strcat("abc",""), "abc") != 0) my_panic("my_strcat failed", 1); if(my_strcmp(my_strcat(NULL,NULL), NULL) != 0) my_panic("my_strcat failed", 1); if(my_strcmp(my_strcat(NULL,"abc"), NULL) != 0) my_panic("my_strcat failed", 1); if(my_strcmp(my_strcat("def",NULL), "def") != 0) my_panic("my_strcat failed", 1); my_str("All my_strcat tests complete."); my_char('\n'); my_char('\n'); my_str("---- 10. my_panic ----"); my_char('\n'); my_str("No tests necessary. Function given in class."); my_char('\n'); my_char('\n'); my_str("---- 11. my_strfind ----"); my_char('\n'); if(my_strcmp(my_strfind("hello",'l'), "llo") != 0) my_panic("my_strfind failed", 1); if(my_strcmp(my_strfind(NULL,'l'), "") != 0) my_panic("my_strfind failed", 1); if(my_strcmp(my_strfind("test",'l'), "") != 0) my_panic("my_strfind failed", 1); if(my_strcmp(my_strfind("",'l'), "") != 0) my_panic("my_strfind failed", 1); my_str("All my_strfind tests complete. "); my_char('\n'); my_char('\n'); my_str("---- 12. my_strrfind ----"); my_char('\n'); if(my_strcmp(my_strrfind("hello",'l'), "lo") != 0) my_panic("my_strrfind failed", 1); if(my_strcmp(my_strrfind(NULL,'l'), "") != 0) my_panic("my_strrfind failed", 1); if(my_strcmp(my_strrfind("test",'l'), "") != 0) my_panic("my_strrfind failed", 1); if(my_strcmp(my_strrfind("",'l'), "") != 0) my_panic("my_strrfind failed", 1); my_str("All my_strrfind tests complete. "); my_char('\n'); my_char('\n'); #endif my_str("~~~~~~~~~ ALL TESTS COMPLETE ~~~~~~~~~"); my_char('\n'); my_char('\n'); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ //文件操作 //参数一:_Filename 文件的来源 //参数二:_Mode 模式r(读) w(写) rb(作为二进制文件的读) wb(作为二进制文件的写) //返回值:FILE 结构体 // fopen(); printf("读取文件\n"); char *fileName = "D:\\ee.txt";//文件的路径 FILE * file = fopen(fileName,"r"); if(!file){ //如果file为null就表示读取失败了 printf("文件打开失败"); exit(0);//退出程序 } printf("读取文件成功\n"); //读取文件的内容,先定义缓冲区 char buffer[10]; //fgets:1:缓冲区 2:长度10 3 :文件 while (fgets(buffer,10,file)){ printf("%s",buffer); } //关闭文件 fclose(file); //文件的写操作 char *fileName2 = "D:\\ee2.txt";//文件的路径 FILE * wfile = fopen(fileName2,"w"); if(!wfile){ printf("打开文件失败"); exit(0); } fputs("写入文件",wfile); //关闭文件 fclose(wfile); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <Windows.h> // Լ ʿ Լ̴. int IF_X(int c, int d); // ˻ Լ int IF_Y(int e, int f); // ˻ Լ int Make_Board(); // Լ int Check(); //ߺ ϱ ˻ Լ int Check_For_Else(); //ߺ 迭 ʱȭ Ű Լ // Լ ÷̸ ϱ ʿ Լ̴. int Playing(); //ڿ ÷̿ ִ Լ int How_To(); //ϴ ڼ ҰǾ ִ Լ int Calibrate(int x, int y); //Էµ ǥ ִ Լ // μ 2 ̻ Լ ȴ. int Dot_Origin = 3;// ũ. Լ ̱ Ѵ. int count = 0; //÷ īƮ Ǵ int Dog_Count = 0; int Duck_Count = 0; int Mouse_Count = 0; // ߰ īƮ 3 ؾ Ѵ. int board[7][7]; // ӿ 2 . Լ ̱ 迭 Ѵ. int main() // Լ { int z, g; // ǥø int categories; while (1) // ɶ { Make_Board(); if (Check() == 26) //26̶ (1 3ũ )+(2 4ũ )+(3 5ũ ) Ѵ. break; // while  else Check_For_Else(); // 쿡 迭 ʱȭ Ű ٽ } /* ¸ Ȯϱ ¸ ʹٸ ּ ּ. for (z = 0; z < 7; z++) { for (g = 0; g < 7; g++) { if (board[g][z] == 0) printf(" 0"); else printf(" X"); } printf("\n"); } */ printf(" ÷ּż մϴ!\n"); Sleep(1000); printf("Dot Com Game / C.Ver\n"); Sleep(1000); printf("Ͻô īװ ڸ ԷϿ ֽʽÿ.\n\n\n"); printf("1. ÷\n\n"); printf("2. ÷ \n\n"); printf("ƹ Ű. \n\n"); scanf_s("%d", &categories); //ڿ īװ ´. if (categories == 1) Playing(); else if (categories == 2) How_To(); else printf("մϴ. ȳ 輼.\n"); return 0; //ڰ Է īװ Լ ȴ. } Make_Board() { int i; //, int x, y; // ǥ int z, g; //Ƿ ¥ int Dot_Com = 3;// 迭ȿ  ϴ Լ int Dot_Size = 5;// ũ⸦ ٷ ִ Լ srand((unsigned)time(NULL)); // Լ for (; Dot_Com < 6; Dot_Com++) { i = rand() % 2; if (i == 0) // η ǰ Ѵ. { x = rand() % Dot_Size; y = rand() % 7; if (IF_X(x, y) == 2) { for (z = 0; z < Dot_Com; z++) board[x + z][y] = -2 + Dot_Com; Dot_Size--; // ϳ ǿ Ǵ ޸ Ѵ. Dot_Origin++; //if 縦 } else Dot_Com--; // ĥ 쿡 ѹ ǵ Ѵ. } else if (i == 1) // η ǰ Ѵ. { x = rand() % 7; y = rand() % Dot_Size; if (IF_Y(x, y) == 2) { for (z = 0; z < Dot_Com; z++) board[x][y + z] = -2 + Dot_Com; Dot_Size--; // ϳ ǿ Ǵ ޸ Ѵ. Dot_Origin++; //if 縦 } else Dot_Com--;// ĥ 쿡 ѹ ǵ Ѵ. } }// Ϸ. } IF_X(int c, int d) // ߺ ϱ ߰ ( ) { int w; //ߺ ˻縦 for (w = 0; w < Dot_Origin; w++) { if (board[c + w][d] != 0) return 1; else continue; } return 2; } IF_Y(int e, int f) // ߺ ϱ ߰ ( ) { int w; //ߺ ˻縦 for (w = 0; w < Dot_Origin; w++) { if (board[e][f + w] != 0) return 1; else continue; } return 2; } Check() //ߺ ϱ ˻ { int v, w; int sum = 0; for (v = 0; v < 7; v++) { for (w = 0; w < 7; w++) sum += board[w][v]; } return sum; } Check_For_Else() //ߺ 迭 ʱȭ Ű Լ { int v, w; for (v = 0; v < 7; v++) { for (w = 0; w < 7; w++) board[v][w] = 0; } return 0; } Playing() { int g; // ݺ char z, x; // + Է ǥ 1 int y; // Է ǥ 2 system("cls"); printf(" մϴ.\n"); while (1) // . { system("cls"); printf(" 1 2 3 4 5 6 7\n"); // ¸ Ȯ ִ. for (z = 'A'; z < 'H'; z++) { printf("%c |", z); for (g = 0; g < 7; g++) { if (board[(int)z - 65][g] == 4) printf(" X"); else if (board[(int)z - 65][g] == 5) printf(" *"); else printf(" 0"); } printf("\n"); } printf("Ͻô ǥ Էּ.\n"); printf(" /ҹڸ + Էֽʽÿ.: "); scanf_s(" %c%d", &x,1, &y); Calibrate(x, y); //ڿ Է ޾ Լ . if (Dog_Count == 3 && Duck_Count == 4 && Mouse_Count == 5) // Ͽ Ż break; } printf(" Ͽϴ. Ǹ ÷̱.\n"); printf(" ÷ īƮ %dԴϴ.\n", count); return 0; // ŻϿ ÷ īƮ µǰ α׷ } Calibrate(int x, int y) //Էµ ǥ ִ Լ { if (x == 'a' || x == 'A') // Էµ xǥ ڷ ȯŰ ̴. x = 0; else if (x == 'b' || x == 'B') x = 1; else if (x == 'c' || x == 'C') x = 2; else if (x == 'd' || x == 'D') x = 3; else if (x == 'e' || x == 'E') x = 4; else if (x == 'f' || x == 'F') x = 5; else if (x == 'g' || x == 'G') x = 6; else //̿ܿ +ڸ Է ޾ īƮ ʰ ǹ Ѵ. { printf("߸ Էϼ̽ϴ. ǥ ٽ Էּ."); Sleep(800); return 0; } if (y > 7 || y < 1) { printf("߸ Էϼ̽ϴ. ǥ ٽ Էּ.\n"); Sleep(800); return 0; } /* ǿ 0 = شǥ ǿ 1 = 3ũ ǥ ǿ 2 = 4ũ ǥ ǿ 3 = 5ũ ǥ ǿ 4 = ̹ ݵ ǥ ԵǴ ǿ 5 = ̹ ݵ ǥ ԵǴ */ if (board[x][y - 1] == 0) //ش ǥ 0 { printf("ش ǥ !!!! ƹ ϵ Ͼ ʾҴ...\n"); board[x][y - 1] = 5; //ش ǥ 5 count++; Sleep(800); } else if (board[x][y - 1] == 1) //ش ǥ 1 { board[x][y - 1] = 4; //ش ǥ 4 printf("߻ Dog.com ǥ Ϻθ ߰!!!!!\n"); count++; Dog_Count++; Sleep(800); if (Dog_Count == 3) { printf("Dog.com . Ǹմϴ.\n"); Sleep(1500); } } else if (board[x][y - 1] == 2) //ش ǥ 2 { board[x][y - 1] = 4; //ش ǥ 4 printf("߻ Duck.com ǥ Ϻθ ߰!!!!!\n"); count++; Duck_Count++; Sleep(800); if (Duck_Count == 4) { printf("Duck.com . Ǹմϴ.\n"); Sleep(1500); } } else if (board[x][y - 1] == 3) //ش ǥ 3 { board[x][y - 1] = 4; //ش ǥ 4 printf("߻ Mouse.com ǥ Ϻθ ߰!!!!!\n"); count++; Mouse_Count++; Sleep(800); if (Mouse_Count == 5) { printf("Mouse.com . Ǹմϴ.\n"); Sleep(1500); } } else if (board[x][y - 1] == 4 || board[x][y - 1] == 5) //ش ǥ 4 Ǵ 5 { printf(" ......\n"); count++; Sleep(800); } return 0; } How_To() //ӿ ڼ ÷ ˷ִ Լ { int a; // Է Ǵ system("cls"); printf(" ӿ ȯմϴ!\n\n\n"); printf("İ ǥ ־ 7*7 ϴ 3 ϴ Դϴ.\n\n"); printf(" ũ 3,4,5̸ ÷̾ ǥ ԷϿ ּ Ƚ ؾ մϴ.\n\n"); printf("-------------------------------------------------\n\n"); printf(" δ A~G, δ 1~7 Ǿ ִ ̸\n\n"); printf("( ǥ)( ǥ) ǥ ֽϴ.\n\n"); printf("̶ ǥ /ҹڸ ʽϴ.\n\n"); printf("-------------------------------------------------\n\n"); printf("ǿ Ƿ 3 Ǿ \n\n"); printf("ڽ Է Ƚ ˴ϴ.\n\n"); printf("-------------------------------------------------\n\n"); printf("ǥ ݹ ǥ 0\n"); printf(" ־ ڸ X\n"); printf("ƹ ݹ ǥ * ǥõ˴ϴ.\n\n\n"); printf("-------------------------------------------------\n\n"); Sleep(5000); printf("ϴ īװ ڸ Էֽʽÿ.\n\n\n"); printf("1. ÷\n\n"); printf("2. ÷ \n\n"); printf("ƹ Ű. \n\n"); scanf_s("%d", &a); if (a == 1) Playing(); else if (a == 2) How_To(); else printf("մϴ. ȳ 輼.\n"); return 0; }
C
#include <stdio.h> void AssignGameMap(char gameMap[30][50]); void FindPlayer(int playerLoc[2], char gameMap[30][50]); void MovePlayer(int playerLoc[2], char gameMap[30][50]); int ExitReached(char gameMap[30][50]); //NOTE: Cannot enter a variable array size for func input so 50col 30 row limit int main(void) { static char gameMap[30][50]; int playerLoc[2]; AssignGameMap(gameMap); /* this is here so movePlayer can be at the top of the for loop, this is important because the final screen needs to be printed after the player moves else it wont look like the exit was reached. */ printf("\e[1;1H\e[2J"); for(int i = 0; i < 15; i++){ printf("%s",gameMap[i]); } do{ FindPlayer(playerLoc, gameMap); MovePlayer(playerLoc, gameMap); printf("\e[1;1H\e[2J"); for(int i = 0; i < 15; i++){ printf("%s",gameMap[i]); } }while(ExitReached(gameMap) == 0); printf("THANKS FOR PLAYING!\n"); return 0; } void AssignGameMap(char gameMap[30][50]){ for(int i = 0; i < 30; i++){ for(int j = 0; j < 50; j++){ gameMap[i][j] = ' '; } } FILE* map = fopen("GameMap.txt","r"); for(int i = 0; i < 30; i++){ fgets(gameMap[i], 50, map); } fclose(map); return; } void MovePlayer(int playerLoc[2], char gameMap[30][50]){ char playerMove; int convertedPlayerMove[2]; int killFunction = 0; char tempChar; printf("\nCONTROL WITH WASD: "); scanf("%c", &playerMove); if(playerMove == 'w'){ convertedPlayerMove[0] = playerLoc[0] - 1; convertedPlayerMove[1] = playerLoc[1]; } else if(playerMove == 'a'){ convertedPlayerMove[1] = playerLoc[1] - 1; convertedPlayerMove[0] = playerLoc[0]; } else if(playerMove == 's'){ convertedPlayerMove[0] = playerLoc[0] + 1; convertedPlayerMove[1] = playerLoc[1]; } else if(playerMove == 'd'){ convertedPlayerMove[1] = playerLoc[1] + 1; convertedPlayerMove[0] = playerLoc[0]; } else{ //anything here is an invalid move killFunction = 1; } tempChar = gameMap[convertedPlayerMove[0]][convertedPlayerMove[1]]; if(tempChar == '|' || tempChar == '-'){ //anything here is out of the game bounds killFunction = 1; } if(killFunction == 0){ gameMap[convertedPlayerMove[0]][convertedPlayerMove[1]] = 'O'; gameMap[playerLoc[0]][playerLoc[1]] = tempChar; } return; } void FindPlayer(int playerLoc[2], char gameMap[30][50]){ for(int i = 0; i < 30; i++){ for(int j = 0; j < 50; j++){ if(gameMap[i][j] == 'O'){ playerLoc[0] = i; playerLoc[1] = j; i = 30; } } } return; } //reusing code from FindPlayer func to find exit and look for player int ExitReached(char gameMap[30][50]){ int exitCheck = 0; for(int i = 0; i < 30; i++){ for(int j = 0; j < 50; j++){ if(gameMap[i][j] == 'E'){ //checking vertical area for player if(gameMap[i-1][j] == 'O' || gameMap[i+1][j] == 'O'){ exitCheck = 1; } //checking horizontal area for player if(gameMap[i][j-1] == 'O' || gameMap[i][j+1] == 'O'){ exitCheck = 1; } i = 30; } } } if(exitCheck == 1){ printf("\nYOU HAVE ESCAPED.\n"); } return exitCheck; }
C
/** * @file VectorCompatibility.h * @brief Provides methods and typedefs for the use of vectors in the code * * @license This file is distributed under the BSD Open Source License. * See LICENSE.TXT for details. **/ #ifndef VECTORCOMPATIBILITY_H #define VECTORCOMPATIBILITY_H #include <immintrin.h> #ifndef __SSE4_2__ #error DEMON requires a processor with SSE 4.2 support. #endif #ifdef __AVX__ #error AVX support is incomplete. #define FLOAT_STRIDE 8 #define DOUBLE_STRIDE 4 typedef __m256d doubleV; typedef __m256 floatV; #else #define FLOAT_STRIDE 4 #define DOUBLE_STRIDE 2 typedef __m128d doubleV; typedef __m128 floatV; #endif /*===- Load/Store ---------------------------------------------------------===*/ static inline void store_pd(double * const a, const doubleV b) { #ifdef __AVX__ return _mm256_store_pd(a, b); #else return _mm_store_pd(a, b); #endif } static inline const doubleV load_pd(double * const a) { #ifdef __AVX__ return _mm256_load_pd(a); #else return _mm_load_pd(a); #endif } /*===- Set ----------------------------------------------------------------===*/ static inline const doubleV set1_pd(const double a) { #ifdef __AVX__ return _mm256_set1_pd(a); #else return _mm_set1_pd(a); #endif } static inline const floatV set1_ps(const float a) { #ifdef __AVX__ return _mm256_set1_ps(a); #else return _mm_set1_ps(a); #endif } static inline const doubleV set0_pd() { #ifdef __AVX__ return _mm256_setzero_pd(); #else return _mm_setzero_pd(); #endif } /*===- Arithmatic ---------------------------------------------------------===*/ static inline void plusEqual_pd(double * const a, const doubleV b) { #ifdef __AVX__ _mm256_store_pd(a, _mm256_load_pd(a) + b); #else _mm_store_pd(a, _mm_add_pd(_mm_load_pd(a), b)); #endif } static inline void minusEqual_pd(double * const a, const doubleV b) { #ifdef __AVX__ _mm256_store_pd(a, _mm256_load_pd(a) - b); #else _mm_store_pd(a, _mm_sub_pd(_mm_load_pd(a), b)); #endif } static inline const doubleV fmadd_pd(const doubleV a, const doubleV b, const doubleV c) { #ifdef __AVX__ return _mm256_fmadd_pd(a, b, c); #else return _mm_add_pd(_mm_mul_pd(a, b), c); #endif } static inline const doubleV add_pd(const doubleV a, const doubleV b) { #ifdef __AVX__ return _mm256_add_pd(a, b); #else return _mm_add_pd(a, b); #endif } static inline const floatV add_ps(const floatV a, const floatV b) { #ifdef __AVX__ return _mm256_add_ps(a, b); #else return _mm_add_ps(a, b); #endif } static inline const doubleV sub_pd(const doubleV a, const doubleV b) { #ifdef __AVX__ return _mm256_sub_pd(a, b); #else return _mm_sub_pd(a, b); #endif } static inline const doubleV sub_pd(const doubleV a, const double b) { #ifdef __AVX__ return _mm256_sub_pd(a, _mm256_set1_pd(b)); #else return _mm_sub_pd(a, _mm_set1_pd(b)); #endif } static inline const floatV sub_ps(const floatV a, const floatV b) { #ifdef __AVX__ return _mm256_sub_ps(a, b); #else return _mm_sub_ps(a, b); #endif } static inline const doubleV mul_pd(const doubleV a, const doubleV b) { #ifdef __AVX__ return _mm256_mul_pd(a, b); #else return _mm_mul_pd(a, b); #endif } static inline const doubleV mul_pd(const doubleV a, const double b) { #ifdef __AVX__ return _mm256_mul_pd(a, _mm256_set1_pd(b)); #else return _mm_mul_pd(a, _mm_set1_pd(b)); #endif } static inline const floatV mul_ps(const floatV a, const floatV b) { #ifdef __AVX__ return _mm256_mul_ps(a, b); #else return _mm_mul_ps(a, b); #endif } static inline const doubleV div_pd(const doubleV a, const doubleV b) { #ifdef __AVX__ return _mm256_div_pd(a, b); #else return _mm_div_pd(a, b); #endif } static inline const doubleV div_pd(const doubleV a, const double b) { #ifdef __AVX__ return _mm256_div_pd(a, _mm256_set1_pd(b)); #else return _mm_div_pd(a, _mm_set1_pd(b)); #endif } static inline const doubleV sqrt_pd(const doubleV a) { #ifdef __AVX__ return _mm256_sqrt_pd(a); #else return _mm_sqrt_pd(a); #endif } static inline const floatV sqrt_ps(const floatV a) { #ifdef __AVX__ return _mm256_sqrt_ps(a); #else return _mm_sqrt_ps(a); #endif } /*===- Comparison ---------------------------------------------------------===*/ static inline const int movemask_pd(const doubleV a) { #ifdef __AVX__ return _mm256_movemask_pd(a); #else return _mm_movemask_pd(a); #endif } static inline const int movemask_ps(const floatV a) { #ifdef __AVX__ return _mm256_movemask_ps(a); #else return _mm_movemask_ps(a); #endif } static inline const floatV cmple_ps(const floatV a, const floatV b) { #ifdef __AVX__ return _mm256_cmp_ps(a, b, LE_OS); #else return _mm_cmple_ps(a, b); #endif } static inline const doubleV cmpgt_pd(const doubleV a, const double b) { #ifdef __AVX__ return _mm256_cmp_pd(a, _mm256_set1_pd(b), LT_OS); #else return _mm_cmpgt_pd(a, _mm_set1_pd(b)); #endif } static inline const doubleV cmplt_pd(const doubleV a, const double b) { #ifdef __AVX__ return _mm256_cmp_pd(a, _mm256_set1_pd(b), GT_OS); #else return _mm_cmplt_pd(a, _mm_set1_pd(b)); #endif } /*===- Logical ------------------------------------------------------------===*/ static inline const doubleV and_pd(const doubleV a, const doubleV b) { #ifdef __AVX__ return _mm256_and_pd(a, b); #else return _mm_and_pd(a, b); #endif } /*===- math functions -----------------------------------------------------===*/ static inline const doubleV exp_pd(const doubleV a) { double b[DOUBLE_STRIDE]; store_pd(b, a); #ifdef __AVX__ return _mm256_set_pd(exp(b[3]), exp(b[2]), exp(b[1]), exp(b[0])); #else return _mm_set_pd(exp(b[1]), exp(b[0])); #endif } static inline const doubleV sin_pd(const doubleV a) { double b[DOUBLE_STRIDE]; store_pd(b, a); #ifdef __AVX__ return _mm256_set_pd(sin(b[3]), sin(b[2]), sin(b[1]), sin(b[0])); #else return _mm_set_pd(sin(b[1]), sin(b[0])); #endif } static inline const doubleV cos_pd(const doubleV a) { double b[DOUBLE_STRIDE]; store_pd(b, a); #ifdef __AVX__ return _mm256_set_pd(cos(b[3]), cos(b[2]), cos(b[1]), cos(b[0])); #else return _mm_set_pd(cos(b[1]), cos(b[0])); #endif } static inline const doubleV length_pd(const doubleV a, const doubleV b) { return sqrt_pd(add_pd(mul_pd(a, a), mul_pd(b, b))); } /*===- Misc ---------------------------------------------------------------===*/ static inline const doubleV select_pd(const int mask, const double trueValue, const double falseValue) { #ifdef __AVX__ return _mm256_set_pd((mask & 8) ? trueValue : falseValue, (mask & 4) ? trueValue : falseValue, (mask & 2) ? trueValue : falseValue, // _mm256_set_pd() is backwards. (mask & 1) ? trueValue : falseValue); #else return _mm_set_pd((mask & 2) ? trueValue : falseValue, // _mm_set_pd() is backwards. (mask & 1) ? trueValue : falseValue); #endif } #endif // VECTORCOMPATIBILITY_H
C
#include<stdio.h> #include<stdlib.h> unsigned char cautarebinara(short int vector[], short int nr_elemente, short int nr_cautat) { int li, lf, k; li = 1; lf = nr_elemente; while (li <= lf) { k = (li + lf) / 2; if (nr_cautat == vector[k]) return 1; else if (nr_cautat < vector[k]) lf = k - 1; else li = k + 1; } return 0; } int main() { short int vector[50], nr_elemente, nr_cautat, rezultat; int i; printf("Dati numarul de elemente:"); scanf("%hd", &nr_elemente); for (i = 0; i < nr_elemente; i++) { printf("vector[%hd]=", i); scanf("%hd", &vector[i]); } printf("vector="); for (i = 0; i < nr_elemente; i++) printf("%hd", vector[i]); printf("\nDati element de cautat:"); scanf("%hd", &nr_cautat); rezultat = cautarebinara(vector, nr_elemente, nr_cautat); if (rezultat == 0)printf("%hd", rezultat); else printf("%hd", rezultat); system("pause"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstdelone.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dalves-p <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/07 17:17:09 by dalves-p #+# #+# */ /* Updated: 2021/06/28 14:29:07 by dalves-p ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" /* ** LIBRARY: N/A ** DESCRIPTION: ** The ft_lstdelone() function takes as a parameter an element and frees ** the memory of the element’s content using the function ’del’ given as a ** parameter and free the element. The memory of ’next’ must not be freed. */ void ft_lstdelone(t_list *lst, void (*del)(void*)) { if (!lst || !del) return ; del(lst->content); free(lst); }
C
#include <stdio.h> #define BUF_SIZE 256 // Read one line from a file, output it on the screen. // ファイルから一行読み込み、画面に出力する int Func(FILE* fp) { char s[BUF_SIZE]; if(fgets(s,BUF_SIZE,fp)) { fputs(s,stdout); return 1; } return 0; } int main() { FILE *fpA, *fpB; fpA = fopen("a.txt","r"); fpB = fopen("b.txt","r"); int i; while(1) { if( !Func(fpA) ) break; if( !Func(fpB) ) break; } fclose(fpA); fclose(fpB); return 0; }
C
/* TASK: Intro04 LANG: C AUTHOR: ~pnw SCHOOL: RYW */ #include<stdio.h> int main() { double a,b,c,d; scanf("%lf %lf %lf %lf", &a, &b, &c, &d); printf("%.2lf\n", a/(c-b)*d); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* tree.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fviolin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/05/24 11:34:48 by fviolin #+# #+# */ /* Updated: 2016/05/24 12:19:11 by fviolin ### ########.fr */ /* */ /* ************************************************************************** */ #include "tree.h" void add_node(t_tree **root, int key) { t_tree *cur; t_tree *tmp; t_tree *new; tmp = *root; if (!(new = (t_tree *)malloc(sizeof(t_tree)))) return ; new->key = key; new->left = NULL; new->right = NULL; if (tmp) { while (tmp) { cur = tmp; if (key > tmp->key) { tmp = tmp->right; if (!tmp) cur->right = new; } else { tmp = tmp->left; if (!tmp) cur->left = new; } } } else *root = new; } int search_node(t_tree *node, int key) { while (node) { if (key == node->key) return (1); if (key > node->key) node = node->right; else node = node->left; } return (0); } void print_tree(t_tree *node) { if (!node) return ; if (node->left) print_tree(node->left); printf("Key = |%d|\n", node->key); if (node->right) print_tree(node->right); } /* new function printing tree, starting on the right */ void print_reverse_tree(t_tree *node) { if (!node) return ; if (node->right) print_reverse_tree(node->right); printf("Key = |%d|\n", node->key); if (node->left) print_reverse_tree(node->left); } void free_tree(t_tree **root) { t_tree *cur; cur = *root; if (!root) return ; if (cur->left) free_tree(&cur->left); if (cur->right) free_tree(&cur->right); free(cur); *root = NULL; }
C
#include<stdio.h> intmain() { int n,a,product=1; scanf("%d",&n); while(n!=0) { a=n%10; product=prodcut*a; n=n/10; } printf("%d",product); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include "sArrList.h" #include "utils.h" sArrList_st *create_sArrList(int list_size, int data_size) { sArrList_st *plist; if((list_size <= 0) || (data_size <= 0)){ return NULL; } plist = malloc(sizeof(sArrList_st) + list_size * data_size); if(plist == NULL){ perror("sArrList_st\n"); exit(-1); } plist->data_size = data_size; plist->count = list_size; return plist; } void destroy_sArrList(sArrList_st *plist) { if(plist == NULL){ return; } free(plist); } void sArrList_traverse(sArrList_st *plist, int (*handler)(void *, void *) , void *arg) { int index; void *pdata = NULL; if((plist == NULL) || (handler == NULL)){ return ; } for(index=0; index<plist->count; index++){ pdata = plist->databuf + index*plist->data_size; if(handler(pdata, arg) != 0){ break; } } } void *sArrList_find(sArrList_st *plist, void *arg, compare_func compare) { int index = -1; void *pdata = NULL; if((plist == NULL) || (compare == NULL)){ return NULL; } for(index=0; index<plist->count; index++){ pdata = plist->databuf + index*plist->data_size; if(compare(pdata, arg) == 0){ break; } } return pdata; } int sArrList_indexof(sArrList_st *plist, void *arg, compare_func compare) { int i, index = -1; void *pdata = NULL; if((plist == NULL) || (compare == NULL)){ return -1; } for(i=0; i<plist->count; i++){ pdata = plist->databuf + i*plist->data_size; if(compare(pdata, arg) == 0){ index = i; break; } } return index; } void *sArrList_get(sArrList_st *plist, int index) { void *pdata = NULL; if(plist == NULL){ return NULL; } if(index < plist->count){ pdata = plist->databuf + index * plist->data_size; } return pdata; } void sArrList_set(sArrList_st *plist, int index, void *pdata) { if(plist == NULL){ return; } if(index < plist->count){ memcpy(plist->databuf + index * plist->data_size, pdata, plist->data_size); } } void sArrList_clear(sArrList_st *plist, int index) { int i; void *pdata; if((plist == NULL) || (index >= plist->count)){ return; } memset(plist->databuf + index*plist->data_size, 0, plist->data_size); } void sArrList_print(sArrList_st *plist, void (*print_func)(void *)) { int i; void *pdata; if((plist == NULL)){ return; } printf("sArrList print : count = %d, datasize = %d \n", plist->count, plist->data_size); for(i=0; i<plist->count; i++){ pdata = plist->databuf + i * plist->data_size; if(print_func){ print_func(pdata); }else{ print_bytes(pdata, plist->data_size); } } }
C
#include <stdio.h> int main(void) { int a, b, c; scanf("%d", &a); scanf("%d", &b); scanf("%d", &c); if (a%111 == 0) { printf("0.%d...\n", a/111); } else if (a < 10) { printf("0.00%d...\n",a); } else if (a < 100) { printf("0.0%d...\n",a); } else { printf("0.%d...\n", a); } if (b % 111 == 0) { printf("0.%d...\n", b/111); } else if (b < 10) { printf("0.00%d...\n",b); } else if (b < 100) { printf("0.0%d...\n",b); } else { printf("0.%d...\n",b); } if (c%111 == 0) { printf("0.%d...\n", c/111); } else if (c < 10) { printf("0.00%d...\n",c); } else if (c < 100) { printf("0.0%d...\n",c); } else { printf("0.%d...\n",c); } }
C
#include "type.h" #include "const.h" #include "string.h" #include "keyboard.h" #include "keymap.h" #include "proto.h" #include "protect.h" #include "process.h" #include "global.h" //私有键盘缓冲区 PRIVATE KB_INPUT kb_in; /*该键盘中断处理逻辑负责从键盘端口中读取数据,并写入缓冲区中*/ PUBLIC void keyboard_handler(int irq){ //键盘控制器(接口)8042只有将数据缓冲器的数据清空后(读取) //才能接受下一个输入扫描码 u8 scan_code = in_byte(KB_DATA); if(kb_in.count < KB_IN_BYTES){//缓冲区未满 *(kb_in.p_header) = scan_code; kb_in.p_header++; //移动到下一个空闲位置 if(kb_in.p_header == kb_in.buf + KB_IN_BYTES){ //当p_header移动到缓冲区末尾,将其移至开头 kb_in.p_header = kb_in.buf; } kb_in.count++; } } //对键盘缓冲区和键盘中断作初始化 PUBLIC void init_keyboard(){ kb_in.count = 0; kb_in.p_header = kb_in.p_tail = kb_in.buf; put_irq_handler(KEYBOARD_IRQ, keyboard_handler); enable_irq(KEYBOARD_IRQ); } //从键盘缓冲区中读取一个扫描码,并显示 PUBLIC void keyboard_read(){ u8 scan_code; char output[2]; int make; //true: make code; false: break code memset(output, 0, 2); //output作为输出字符串,末尾0结束 if(kb_in.count > 0){//当键盘缓冲区为空时,直接返回 disable_int(); //对键盘缓冲区数据结构的操作应该是原子操作 scan_code = *(kb_in.p_tail); kb_in.p_tail++; if(kb_in.p_tail == kb_in.buf + KB_IN_BYTES){ //将p_tail移至缓冲区头 kb_in.p_tail = kb_in.buf; } kb_in.count--; enable_int(); //开中断 //下面开始解析扫描码 if(scan_code == 0xE1){ //双字节扫描码,暂时不作处理 //pass }else if(scan_code == 0xE0){ //双字节扫描码,暂时不作处理 //pass }else {//以下均是单字节扫描码,目前仅处理可打印字符 //首先判断是make code 还是break code //FLAG_BREAK = 0x80,make code与操作为假 make = (scan_code & FLAG_BREAK ? FALSE: TRUE); //如果是make code,就打印,break code先不做处理 if(make){//与0x7F进行与操作,避免数组越界,也可以将break code键变为make code output[0] = keymap[(scan_code & 0x7F) * MAP_COLS]; disp_str(output); } } //disp_int(scan_code); } }
C
#include <stdio.h> // һҪס, Ҫʵδݵʲô, ֻβξͿ // βʱ, ôں޸ββӰ쵽ʵ // β, ôں޸βλӰ쵽ʵ void change1(char ch){ ch = 'T'; } void change2(char ch[]){ ch[0] = 'T'; } void change3(char ch[][3]){ ch[0][0] = 'T'; } int main() { /* * ǰѧϰΪʱ, ֪ĵַ * chs[0]chs[1]Ƕάеһά * chs[0]chs[1]Ҳĵַ chs[0] == &chs[0] * * ֻжά[][]ȡijһΪijһԪصֵ */ char chs[2][3] = {{'l','n','j'}, {'z','q','x'}}; // printf("chs[0][0] = %c\n", chs[0][0]); // l l l //// change1(chs[0][0]); //// change2(chs[0]); //// change3(chs); // printf("chs[0][0] = %c\n", chs[0][0]); // l T T // int nums[] = {1, 3, 5}; // printf("nums = %p\n", nums); // printf("&nums = %p\n", &nums); // printf("chs[0] = %p\n", chs[0]); // printf("&chs[0] = %p\n", &chs[0]); return 0; }
C
// // Created by Steffan Ianigro on 3/06/2016. // #include "mapParams.h" const double GAINMIN = 0; const double GAINMAX = 3; const double BIASMIN = -4; const double BIASMAX = 4; const double WEIGHTMIN = -10; const double WEIGHTMAX = 10; const double TCMIN = 1; const double TCMAX = 3; const double SINECOEFFICIENTMIN = 0; const double SINECOEFFICIENTMAX = 1; const double FREQUENCYMULTIPLIERMIN = 0; const double FREQUENCYMULTIPLIERMAX = 10; double mapGain(double paramValue){ return (paramValue * (GAINMAX - GAINMIN)) + GAINMIN; } double mapBias(double paramValue){ return (paramValue * (BIASMAX - BIASMIN)) + BIASMIN; } double mapWeight(double paramValue){ return (paramValue * (WEIGHTMAX - WEIGHTMIN)) + WEIGHTMIN; } double mapTimeConstant(double paramValue){ return (paramValue * (TCMAX - TCMIN)) + TCMIN; } double mapSineCoefficient(double paramValue){ return (paramValue * (SINECOEFFICIENTMAX - SINECOEFFICIENTMIN)) + SINECOEFFICIENTMIN; } double mapFrequencyMultiplier(double paramValue){ return (paramValue * (FREQUENCYMULTIPLIERMAX - FREQUENCYMULTIPLIERMIN)) + FREQUENCYMULTIPLIERMIN; } double sineTransferFunction(double activation, double sineCoefficient, double frequencyMiltiplier){ return (1 - sineCoefficient) * tanh(activation) + sineCoefficient * sin(frequencyMiltiplier * activation); } double transferFunction(double activation){ return tanh(activation); }
C
//Controls the movement of the agent with a selector switch #include <stdio.h> #include <math.h> #include "selector.h" #include "motors.h" void movement_1(); void movement_2(); int left_v, right_v; int main() { motor_init(); while(1) { //Select mode of operation switch(get_selector()) { case(1): //Forward movement { movement_1(); break; } case(2): //Rotation movement { movement_2(); break; } default: break; } //Set motor velocities left_motor_set_speed(left_v); right_motor_set_speed(right_v); } } void movement_1() { left_v = 500; right_v = 500; } void movement_2() { left_v = -500; right_v = 500; }
C
#include <fits.h> extern char* fitsnum(double x); ftype fits; int main(int argc,char**argv) { int i=1,j,ver=0; char *str; if (argc>=2 && !strcasecmp(argv[1],"-full")) { ver=1; i++; } for (;i<argc;i++) { fclose(readfitsh(argv[i],&fits,0)); if (!ver) { if (fits.img.Z<2) printf("%s: %dx%d",argv[i],fits.img.X,fits.img.Y); else printf("%s: %dx%dx%d",argv[i],fits.img.X,fits.img.Y,fits.img.Z); switch(fits.img.bits) { case -32:printf(" float"); break; case 32:printf(" long"); break; case 16:printf(" short"); break; case 8:printf(" byte"); break; } str=getcardval(&(fits.img),"EXPTIME",0); if (str[0]) printf(", %ss",str); str=getcardval(&(fits.img),"FILTER",0); if (str[0]) printf(", %s",str); str=getcardval(&(fits.img),"OBSTYPE",0); if (str[0]) printf(", type=%s",str); str=getcardval(&(fits.img),"OBJECT",0); if (!str[0]) str=getcardval(&(fits.img),"TARGNAME",0); if (str[0]) printf(", name=%s",str); printf("\n"); } else { printf("SIMPLE = T / Standard FITS format\n"); printf("BITPIX = %20d / Data type\n",fits.img.bits); if (fits.img.Z>1) { printf("NAXIS = 3 / Number of axes\n"); printf("NAXIS1 = %20d /\n",fits.img.X); printf("NAXIS2 = %20d /\n",fits.img.Y); printf("NAXIS3 = %20d /\n",fits.img.Z); } else if (fits.img.Y>1) { printf("NAXIS = 2 / Number of axes\n"); printf("NAXIS1 = %20d /\n",fits.img.X); printf("NAXIS2 = %20d /\n",fits.img.Y); } else if (fits.img.X>0) { printf("NAXIS = 1 / Number of axes\n"); printf("NAXIS1 = %20d /\n",fits.img.X); } else { printf("NAXIS = 0 / Number of axes\n"); } if (fits.Next<=0) {printf("EXTEND = F / There are no standard extensions\n");} else { printf("EXTEND = T / There may be standard extensions\n"); printf("NEXTEND = %14d /\n",fits.Next); } printf("BSCALE = %20s / Image scale\n",fitsnum(fits.img.bscale)); printf("BZERO = %20s / Image zero\n",fitsnum(fits.img.bzero)); for (j=0;j<fits.img.Ncards;j++) printf("%s\n",fits.img.cards[j]); } if (fits.img.Nmax) free(fits.img.cards); } return 0; }
C
#include <stdio.h> #include <unistd.h> #include <sys/wait.h> int main() { int status; int pid1 = fork(); if(pid1 == 0) { printf("\n2 my=%d pid=%d ppid=%d",pid1, getpid(), getppid()); return 0; } else { printf("This goes to buffer"); fflush(stdout); //flush or else child process will have same buffer as parent int pid2 = fork(); if(pid2 == 0) { printf("\n3 my=%d pid=%d ppid=%d",pid2, getpid(), getppid()); return 0; } else { //its usually first, but \n clears buffer and it becomes last :( printf("\n1 my=%d pid=%d ppid=%d",pid2, getpid(), getppid()); waitpid(pid1, &status, 0); waitpid(pid2, &status, 0); } } return 0; }
C
#include "header.h" extern pthread_mutex_t mtx; extern pthread_cond_t cond_empty; extern pthread_cond_t cond_full; extern Queue* workQueue; extern pthread_t *cons; extern int thread_pool_size; extern int flag; Queue* createQueue() { Queue* _queue = (Queue *)malloc( sizeof( Queue ) ); _queue->head = _queue->last = NULL; _queue->_size = 0; return _queue; } QNode* createQNode() { QNode* temp = (QNode *)malloc( sizeof( QNode ) ); // Allocate memory temp->prev = temp->next = NULL; return temp; } int IsQueueEmpty( Queue* _queue ){ return (_queue->_size == 0); } void addNewNode(Queue* _queue,QNode* node){ if ( IsQueueEmpty( _queue ) )// If queue is empty, change both head and last pointers _queue->last = _queue->head = node; else // Else change the last { _queue->last->next = node; node->prev = _queue->last; _queue->last = node; } _queue->_size++; } void perror_exit (char *message) { perror(message); exit(EXIT_FAILURE); } int read_all(int fd ,void* buff,int _size){ int sent,n; for( sent = 0;sent<_size;sent += n ) { if ((n = read(fd,buff + sent,_size - sent)) == -1){ return -1; /* error */ } } return sent ; } int write_all(int fd,void* buff,int _size){ int sent,n; for( sent = 0;sent<_size;sent += n) { if ((n = write(fd,buff + sent,_size - sent)) == -1){ return -1; /* error */ } } return sent ; } void place(Queue* workQueue,QNode* node,int queue_size){ pthread_mutex_lock(&mtx);//protect data by locking the mutex while (workQueue->_size >= queue_size){ //printf(">>WorkQueue is full\n"); pthread_cond_wait(&cond_full,&mtx); } //printf("place to queue\n"); addNewNode(workQueue,node); pthread_mutex_unlock(&mtx); } void *consumer(void * ptr){ QNode* node; int dirlen,err; long pagesize = sysconf(_SC_PAGESIZE); //-------------------------------------------- while(1){ pthread_mutex_lock(&mtx);//protect data by locking the mutex while(workQueue->_size <= 0){ //printf(">>WorkQueue is empty\n"); pthread_cond_wait(&cond_empty,&mtx); if (flag == 1){ pthread_mutex_unlock(&mtx); printf("I am a consumer and i am ready to go!\n"); pthread_exit(NULL); } } node = workQueue->head; workQueue->head = node->next; if(workQueue->_size == 1) workQueue->last = node->next; workQueue->_size--; pthread_mutex_lock(node->clientMutex);//lock the client mute pthread_mutex_unlock(&mtx);//unlock the mutex pthread_cond_broadcast(&cond_full); //1) send the size of the path or ack if (node->buf == NULL) {//if this is the last package to a certain client dirlen = 0; //send ack printf("[Thread: %ld]: Received task:<ACK,%d>\n",pthread_self(),node->client_sock); fflush(stdout); } else dirlen = strlen(node->buf)+1; //send the size of the path if (write_all(node->client_sock,&dirlen,sizeof(int)) != sizeof(int)) perror_exit("write"); if (dirlen != 0){ //if this is not the last pack to a certain client printf("[Thread: %ld]: Received task:<%s,%d>\n",pthread_self(),node->buf,node->client_sock); fflush(stdout); // 2)send the path itself if (write_all(node->client_sock,node->buf,dirlen) != dirlen) perror_exit ("write"); // 3)send the size of the file if (write_all(node->client_sock,&node->sizeInBytes,sizeof(long)) != sizeof(long)) perror_exit("write"); // 4)send the pagesize if (write_all(node->client_sock,&pagesize,sizeof(long)) != sizeof(long)) perror_exit("write"); // 5)send the file itself printf("[Thread: %ld]: About to read file %s\n",pthread_self(),node->buf); fflush(stdout); writeFile(node,pagesize); pthread_mutex_unlock(node->clientMutex); free(node->buf); } else{//if this is the last package to a certain client close(node->client_sock); pthread_mutex_unlock(node->clientMutex); if ( err = pthread_mutex_destroy(node->clientMutex)){ perror2("pthread_mutex_destroy",err); exit(1); } free(node->clientMutex); } free(node); } } void writeFile(QNode* node,long pagesize){ long bytesLeft = node->sizeInBytes; char buffer[pagesize]; int fd; if ( (fd = open(node->buf,O_RDONLY) ) == -1) perror_exit("open"); while (bytesLeft > pagesize){ if (read(fd,buffer,pagesize) < 0) perror_exit("read"); if (write_all(node->client_sock,buffer,pagesize) != pagesize) perror_exit("write_all"); bytesLeft-=pagesize; } if (bytesLeft != 0){ if (read(fd,buffer,bytesLeft) < 0) perror_exit("read"); if (write_all(node->client_sock,buffer,bytesLeft) != bytesLeft) perror_exit("write_all"); } close(fd); } void *connection_handler(void *arg){ int err,length; char* directory; QNode* node; int newsock = ((information*)arg)->newsock; int queue_size = ((information*)arg)->queue_size; pthread_mutex_t *clientMutex = malloc(sizeof(pthread_mutex_t)); //--------------------------------------------- if ( err = pthread_detach(pthread_self())){ perror2("pthread_detach",err); exit(1); } pthread_mutex_init(clientMutex,NULL ) ; /* Initialize client mutex */ if (read_all(newsock,&length,sizeof(int)) != sizeof(int) ) perror_exit("read"); directory = malloc(length); if (read_all(newsock,directory,length) != length) perror_exit("read"); //print directory //printf("directory is: %s\n",directory); printf("[Thread: %ld]: About to scan directory Server\n",pthread_self()); fflush(stdout); findFiles(directory,newsock,queue_size,clientMutex); //create ack node = createQNode(); node->client_sock = newsock; node->buf = NULL; node->clientMutex = clientMutex; place(workQueue,node,queue_size); pthread_cond_broadcast(&cond_empty); pthread_exit(NULL); } //for the functions read_all and write_all i used an internet resource void findFiles(char* directory,int newsock,int queue_size,pthread_mutex_t *clientMutex){ int error; DIR *dirp; struct dirent *ent; struct dirent *dp = malloc(sizeof(struct dirent)); struct stat statbuf; char* path; QNode* node; if ((dirp = opendir(directory)) == NULL){ perror_exit("open directory"); return ; } while ( ( (error = readdir_r(dirp,dp,&ent) )== 0 ) && ent ){ if ( !strcmp(ent->d_name,".") || !strcmp(ent->d_name,"..")) continue; path = malloc(strlen(directory)+strlen(ent->d_name)+2); sprintf(path,"%s/%s",directory,ent->d_name); if (stat(path,&statbuf) == -1) perror_exit("stat"); //check if it is file or directory if ((statbuf.st_mode & S_IFMT) != S_IFDIR ){ //we found a file //create and initialize node printf("[Thread: %ld]: Adding file %s to the queue...\n",pthread_self(),path); fflush(stdout); node = createQNode(); node->client_sock = newsock; node->buf = malloc(strlen(path)+1); node->clientMutex = clientMutex; strcpy(node->buf,path);//buf holds the path of the file node->sizeInBytes = statbuf.st_size;//sizeInBytes holds the size of the file in bytes place(workQueue,node,queue_size); pthread_cond_broadcast(&cond_empty); } else //we found a directory findFiles(path,newsock,queue_size,clientMutex); } if (error) perror_exit("readdir_r"); else closedir(dirp); } void signal_handler(int signum){ int err,i = 0; printf("I am the signal_handler of the Server\n"); flag = 1; pthread_cond_broadcast(&cond_empty); for(i=0;i<thread_pool_size;i++) /* Wait for all consumers termination */ if(err = pthread_join(*(cons + i),NULL)){ perror2("pthread_join",err); exit (1) ; } free(cons); if ( err = pthread_mutex_destroy(&mtx)){ perror2("pthread_mutex _destroy",err); exit(1); } if ( err = pthread_cond_destroy(&cond_empty)){ perror2("pthread_cond_ destroy",err); exit(1); } if ( err = pthread_cond_destroy(&cond_full)){ perror2("pthread_cond_ destroy",err); exit(1); } free(workQueue); printf("Server says:Adios muchachos!\n"); exit(EXIT_SUCCESS); }
C
#include "llist_iter.h" void list_foreach(const llist* lst, void (*iter_fun) (int)) { while (lst != NULL) { iter_fun(lst->el); lst = lst->rest; } } void list_foreach_ctx(const llist* lst, void* context, void (*iter_fun) (int, void*)) { while (lst != NULL) { iter_fun(lst->el, context); lst = lst->rest; } } llist* list_map(const llist* lst, int (*transform_fun) (int)) { llist* new_lst = NULL; while (lst != NULL) { list_add_front(&new_lst, transform_fun(lst->el)); lst = lst->rest; } return new_lst; } void list_map_mut(llist* lst, int (*transform_fun) (int)) { while (lst != NULL) { lst->el = transform_fun(lst->el); lst = lst->rest; } } int list_foldl(const llist* lst, int acc, int (*acc_fun) (int, int)) { while (lst != NULL) { acc = acc_fun(lst->el, acc); lst = lst->rest; } return acc; } llist* list_iterate(int init, int iter_count, int (*iter_fun) (int)) { llist* lst = list_create(init); int acc = init; for (int i = 0; i < iter_count; acc = iter_fun(acc), i++) list_add_back(&lst, acc); return lst; }
C
#include <stdio.h> /* 条件分支语句: 1. if (condition) { statement; } 2.  if (condition) { 满足语句; } else { 否则; } 3. if (condition1) { } else if (condition2) { } else if (condition3) { } else { } 4. switch (常量值/常量表达式) { case value1: statement1; break; // 结束分支 case value2: .... defualt: // else break; } */ int main(void) { int score; printf("请输入您的成绩:"); scanf("%d", &score); if (score < 0 || score > 100) { printf("请输入有效成绩\n"); } else if (score >= 60) { printf("做的好!...\n"); } else { printf("继续努力...\n"); } return 0; }
C
// // Created by dcat on 10/11/17. // #include <env.h> #include <str.h> #include <umem.h> #include <print.h> #include <syscall.h> #include "uexec.h" extern uchar_t *memcpy(void *dest, void *src, int count); int find_in_path(const char *file, char *pathbuff) { const char *path = getenv("PATH"); if (path == NULL) { printf("warning:PATH is not defined.\n"); return -1; } else { int pos = 0, lpos = 0; while (pos >= 0) { pos = strnxtok(path, ':', lpos); if (pos == -1) { strcpy(pathbuff, &path[lpos]); } else { memcpy(pathbuff, &path[lpos], pos - lpos); pathbuff[pos - lpos] = 0; lpos = pos + 1; } int tlen = strlen(pathbuff); if (pathbuff[tlen - 1] != '/') strcat(pathbuff, "/"); strcats(pathbuff, file, 256); int acret = syscall_access(pathbuff, X_OK); printf("finding %s %d\n", pathbuff, acret); if (acret == 0) { return 0; } } } } int execve(const char *path, char *const argv[], char *const envp[]) { int argc = 0; while (argv != NULL && argv[argc] != NULL)argc++; syscall_exec(path, argc, argv, envp); } int execv(const char *path, char *const argv[]) { return execve(path, argv, __getenvp()); } int execvpe(const char *file, char *const argv[], char *const envp[]) { char pathbuff[256]; if (strlen(file) > 0 && file[0] != '/') { if (find_in_path(file, pathbuff) != 0) strcpy(pathbuff, file); } else { strcpy(pathbuff, file); } return execve(pathbuff, argv, envp); } int execvp(const char *file, char *const argv[]) { return execvpe(file, argv, __getenvp()); } int execl(const char *path, const char *arg, ...) { int argc = 1; va_list va; va_start(va, arg); while (va_arg(va, const char*))argc++; char *argv[argc + 1]; va_start(va, arg); for (int x = 1; x < argc; x++) { argv[x] = (char *) va_arg(va, const char*); } argv[0] = (char *) arg; argv[argc] = NULL; va_arg(va, void*); return execv(path, (char *const *) argv); } int execlp(const char *file, const char *arg, ...) { char pathbuff[256]; if (find_in_path(file, pathbuff) != 0) strcpy(pathbuff, file); int argc = 1; va_list va; va_start(va, arg); while (va_arg(va, const char*))argc++; char *argv[argc + 1]; va_start(va, arg); for (int x = 1; x < argc; x++) { argv[x] = (char *) va_arg(va, const char*); } argv[0] = (char *) arg; argv[argc] = NULL; va_arg(va, void*); return execv(pathbuff, (char *const *) argv); } int execle(const char *path, const char *arg, ...) { int argc = 1; va_list va; va_start(va, arg); while (va_arg(va, const char*))argc++; char *argv[argc + 1]; va_start(va, arg); for (int x = 1; x < argc; x++) { argv[x] = (char *) va_arg(va, const char*); } argv[0] = (char *) arg; argv[argc] = NULL; va_arg(va, void*); char *const *envp = va_arg(va, char* const*); return execve(path, (char *const *) argv, envp); }
C
/* send.c - send */ #include <conf.h> #include <kernel.h> #include <proc.h> #include <stdio.h> #include "lab0.h" extern int summarizeProcess; /*------------------------------------------------------------------------ * send -- send a message to another process *------------------------------------------------------------------------ */ SYSCALL send(int pid, WORD msg) { STATWORD ps; struct pentry *pptr; unsigned int timeTaken; unsigned int startTime = ctr1000; if(!summarizeProcess) { globalTableSystemCall[currpid][SEND].systemCallName = "sys_send"; globalTableSystemCall[currpid][SEND].systemCallFrequency = globalTableSystemCall[currpid][SEND].systemCallFrequency + 1; } disable(ps); if (isbadpid(pid) || ( (pptr= &proctab[pid])->pstate == PRFREE) || pptr->phasmsg != 0) { restore(ps); timeTaken = ctr1000 - startTime; globalTableSystemCall[currpid][SEND].systemCallAverageExecTime = globalTableSystemCall[currpid][SEND].systemCallAverageExecTime + timeTaken; return(SYSERR); } pptr->pmsg = msg; pptr->phasmsg = TRUE; if (pptr->pstate == PRRECV) /* if receiver waits, start it */ ready(pid, RESCHYES); else if (pptr->pstate == PRTRECV) { unsleep(pid); ready(pid, RESCHYES); } restore(ps); timeTaken = ctr1000 - startTime; globalTableSystemCall[currpid][SEND].systemCallAverageExecTime = globalTableSystemCall[currpid][SEND].systemCallAverageExecTime + timeTaken; return(OK); }
C
#include <stdio.h> #include <assert.h> int missingNumber0(int* nums, int numsSize) { long long sum = 0; int i; for (i = 0; i < numsSize; i++) { sum += nums[i]; } long long prod = (numsSize + 1) * numsSize / 2; return prod - sum; } int missingNumber(int* nums, int numsSize) { int ans = 0; int i; for (i = 0; i < numsSize; i++) { ans ^= nums[i]; ans ^= i + 1; } return ans; } int main() { int a[] = {0, 1, 3}; assert(missingNumber(a, 3) == 2); int b[] = {1, 0}; assert(missingNumber(b, 2) == 2); printf("all tests passed!\n"); return 0; }