language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
unsigned char funx(unsigned char ,int ,int); int compress7(int fo,int count ,int mcount) { int fm,fc,i = 0; unsigned char a,b,c,x,value; char org[count],marray[mcount]; lseek(fo,SEEK_SET,0); fm = open("/home/avtar/project1/mdcproject/masterarrayg.txt",O_RDONLY); fc = open("/home/avtar/project1/mdcproject/compressed_codeg.txt",O_WRONLY |O_TRUNC); read(fo,org,count); org[count] = 0; printf("org in compress is %s\n",org); read(fm,marray,mcount); marray[mcount] = 0; printf("marray in compress is %s\n",marray); for(i = 0;i < count;i++) { x = org[i]; a = fun(x,fm,mcount); a <<= 1; x = org[++i]; b = fun(x,fm,mcount); c = b; b >>= 6; value = a | b; write(fc,&value,1); printf("value is %d\n",value); c <<= 2; x = org[++i]; x = fun(x,fm,mcount); a = x; x >>= 5; value = c | x; write(fc,&value,1); printf("value is %d\n",value); a <<= 3; x = org[++i]; x = fun(x,fm,mcount); b = x; x >>= 4; value = a | x; write(fc,&value,1); printf("value is %d\n",value); b <<= 4; x = org[++i]; x = fun(x,fm,mcount); a = x; x >>= 3; value = b | x; write(fc,&value,1); printf("value is %d\n",value); a <<= 5; x = org[++i]; x = fun(x,fm,mcount); b = x; x >>= 2; value = a | x; write(fc,&value,1); printf("value is %d\n",value); b <<= 6; x = org[++i]; x = fun(x,fm,mcount); c = x; x >>= 1; value = b | x; write(fc,&value,1); printf("value is %d\n",value); c <<= 7; x = org[++i]; x = fun(x,fm,mcount); value = c | x; write(fc,&value,1); printf("value is %d\n",value); } return 1; } unsigned char funx(unsigned char x,int fm,int mcount) { lseek(fm,SEEK_SET,0); unsigned char marray[mcount],z; read(fm,marray,mcount); marray[mcount] = 0; int j; for(j = 0;j < mcount;j++) { if(x == marray[j]) { z = j; break; } else continue; } return z; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { char* text = NULL; if (argc < 3) { printf("Usage: repeater [STRING] [QUANTITY]\n"); exit(1); } int times = atoi(argv[2]); if (times == 0) { exit(0); } char* str = argv[1]; int len = strlen(str); int outlen = (sizeof(char) * len * times) + 2; text = (char*)malloc(outlen); for (int i = 0; i < outlen; i += len) { memcpy(text + i, str, len); } text[outlen - 2] = '\n'; text[outlen - 1] = '\0'; printf("%s", text); free(text); return 0; }
C
// // Created by Jeongho on 2018-01-04. // #include <stdio.h> #include <stdlib.h> int heapSize=-1; int* heapArray; void insertHeap(int num); void deleteHeap(); int main(){ int command_count; scanf("%d",&command_count); //입력할 명령어 수 입력 heapArray=(int*)malloc(sizeof(int)*command_count+1);//명령어 수에 따른 배열 동적 할당 getchar(); // 출력 버퍼 비우기 for(int i=0;i<command_count;i++){ int num; scanf("%d",&num); //공백 포함하여 입력받기 getchar(); //출력 버퍼 비우기 if(num==0){ deleteHeap(); }else if(num>0){ insertHeap(num); } } free(heapArray); //동적 배열에 할당된 메모리 해제 return 0; } void insertHeap(int num){ heapSize++; //힙 확장 int i=heapSize;//임시로 확장한 장소를 가르킴 //부모노드와 비교 하면서 값이 크면 부모노드와 자리를 바꿈 //배열이 0부터시작하므로 (i-1)/2가 부모노드 while( (i!=0) && (num>heapArray[(i-1)/2]) ){ heapArray[i]=heapArray[(i-1)/2]; i=(i-1)/2; } heapArray[i]=num; } void deleteHeap(){ if(heapSize==-1) { printf("%d\n", 0); return; } printf("%d\n",heapArray[0]); int temp=heapArray[heapSize]; //임시로 배열의 끝값을 저장 int root=0; //현재 루트노드 int child=1; //자식노드 while(child<=heapSize){ if(child<heapSize){ if(heapArray[child]<heapArray[child+1]) child=child+1; //자식노드 둘을 비교해서 큰것을 고름 } if(temp>heapArray[child]) break; //만약 맨 끝값이 자식노드들보다 크다면 자리 확정 heapArray[root]=heapArray[child]; root=child; //다음으로 이동 child=child*2+1; //다음 자식노드로 이동 } heapArray[root]=temp; //위의 연산 수행후 나온 root에 배열 끝값 저장 heapSize--; //힙 감소 }
C
// pthread에 구조체 인자 전달 #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <string.h> void *print_structure(void *); typedef struct{ char name[20]; char major[30]; char univ[30]; } thread_args; int main(void) { pthread_t t1, t2; // stu1 구조체 선언 thread_args stu1; strcpy(stu1.name, "Kang Daniel"); strcpy(stu1.major, "Computer Engineering"); strcpy(stu1.univ, "101 Universiry"); // stu2 구조체 선언 thread_args stu2; strcpy(stu2.name, "Kim Da-hyun"); strcpy(stu2.major, "Computer Science"); strcpy(stu2.univ, "TWICE Universiry"); // Pthread 실행 pthread_create(&t1, NULL, print_structure, &stu1); pthread_create(&t2, NULL, print_structure, &stu2); // Pthread join(wait) pthread_join(t1, NULL); pthread_join(t2, NULL); return 0; } // thread 실행 함수 void *print_structure(void *arg) { // void 형태로 전달한 인자를 구조체로 재정의 thread_args *args = (thread_args *) arg; printf("%s\n", args->name); printf("%s\n", args->major); printf("%s\n", args->univ); printf("\n"); return NULL; }
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; bool isSameTree(struct TreeNode *p, struct TreeNode *q) { if (p == NULL && q == NULL) { return true; } if (p == NULL || q == NULL) { return false; } if (isSameTree(p->left, q->left) && isSameTree(p->right, q->right) && p->val == q->val) { return true; } return false; } int main(int argc, char const *argv[]) { struct TreeNode node1, node2, node3; node1.val = 1; node2.val = 2; node3.val = 3; node1.left = &node2; node1.right = &node3; node2.left = NULL; node2.right = NULL; node3.left = NULL; node3.right = NULL; printf("Input: [%d, %d, %d]\n", node1.val, node2.val, node3.val); printf("Output: %s\n", isSameTree(&node1, &node1) ? "true" : "false"); return EXIT_SUCCESS; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* update_env.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: earnaud <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/17 16:12:16 by vfurmane #+# #+# */ /* Updated: 2021/05/28 12:16:57 by vfurmane ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" int ft_update_env(t_config *shell_c) { int i; char *envp_with_equal; t_kvpair *envp_elm; envp_elm = shell_c->envp_list; i = 0; while (shell_c->envp[i]) free(shell_c->envp[i++]); free(shell_c->envp); shell_c->envp = malloc(sizeof(*shell_c->envp) * (ft_lstsize(shell_c->envp_list) + 1)); i = 0; while (envp_elm) { if (envp_elm->value != NULL) { envp_with_equal = ft_strjoin("=", envp_elm->value); shell_c->envp[i++] = ft_strjoin(envp_elm->key, envp_with_equal); free(envp_with_equal); } envp_elm = envp_elm->next; } shell_c->envp[i] = NULL; return (0); } void *ft_del_env_elm(t_config *shell_c, t_kvpair *elm, t_kvpair *previous) { t_kvpair *next; if (previous != NULL) previous->next = elm->next; else shell_c->envp_list = elm->next; free(elm->key); free(elm->value); next = elm->next; free(elm); return (next); } int ft_del_env(t_config *shell_c, char *str) { t_kvpair *previous; t_kvpair *envp_elm; previous = NULL; envp_elm = shell_c->envp_list; while (envp_elm) { if (ft_strcmp(str, envp_elm->key) == 0) envp_elm = ft_del_env_elm(shell_c, envp_elm, previous); else { previous = envp_elm; envp_elm = envp_elm->next; } } ft_update_env(shell_c); return (0); } int ft_check_duplicate_env(t_kvpair *envp_list, const char *str, int equal_pos) { char *new_key; t_kvpair *envp_elm; envp_elm = envp_list; new_key = ft_strcdup(str, '='); while (envp_elm) { if (ft_strcmp(new_key, envp_elm->key) == 0 &&str[equal_pos] == '=') { free(new_key); free(envp_elm->value); envp_elm->value = ft_strdup(&str[equal_pos + 1]); return (1); } else if (ft_strcmp(new_key, envp_elm->key) == 0) { free(new_key); return (1); } envp_elm = envp_elm->next; } free(new_key); return (0); } int ft_add_env(t_config *shell_c, const char *str) { int j; t_kvpair *envp_elm; j = 0; while (str[j] && str[j] != '=') j++; if (!ft_check_duplicate_env(shell_c->envp_list, str, j)) { envp_elm = malloc(sizeof(*envp_elm)); envp_elm->next = NULL; envp_elm->key = ft_strcdup(str, '='); if (str[j++] == '\0') envp_elm->value = NULL; else envp_elm->value = ft_strdup(&str[j]); ft_lstadd_back(&shell_c->envp_list, envp_elm); } ft_update_env(shell_c); return (0); }
C
#include "libs_support.h" #include "util.h" /* -------------------------------- YMD_aGTEb ---------------------------------------- Return true if 'a' id the same date & time as 'b' or later. Handles wildcards; if year or month in 'a' or 'b' is a wildcard then that field in 'a' is NOT greater or equal than that field in 'b'. That is... year or month wildcards are ignored in testing for true. A day wildcard in 'a' or 'b' evaluates to true; it has to because there's no smaller time unit to continue to. So: 2001-2-3 >= 2000-2-3 2001-2-3 >= 2001-2-3 2001-2-3 >= ****-2-3 (years are not compared) ****-2-3 NOT >= 2001-2-3 " " " */ PUBLIC BOOLEAN YMD_aGTEb(S_YMD const *a, S_YMD const *b) { return a->yr != _YMD_AnyYear && b->yr != _YMD_AnyYear && a->yr != b->yr ? (a->yr > b->yr ? true : false) : (a->mnth != _YMD_AnyMnth && b->mnth != _YMD_AnyMnth && a->mnth != b->mnth ? (a->mnth > b->mnth ? true : false) : ( a->day != _YMD_AnyDay && b->day != _YMD_AnyDay ? (DayOfYMD(a) >= DayOfYMD(b) ? true : false) : true )); } // ------------------------------------- eof ---------------------------------------------------
C
#include <stdio.h> #include <unistd.h> #include <pthread.h> #define rozm 4 pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t c = PTHREAD_COND_INITIALIZER; int buf[rozm], poz_zap=0, poz_odcz=0, ile_jest=0; void* prod(void* info) { int i; while(1) { sleep(2); pthread_mutex_lock(&mx); printf("prod zamknal zamek\n"); if (ile_jest == rozm) { printf("prod musi czekac\n"); //pthread_mutex_unlock(&mx); pthread_cond_wait(&c, &mx); printf("prod skonczyl czekanie\n"); } buf[poz_zap] = i; printf("prod umiescil %d na pozycji %d\n", i, poz_zap); poz_zap = (poz_zap+1)%rozm; i++; ile_jest++; if (ile_jest == 1) pthread_cond_signal(&c); pthread_mutex_unlock(&mx); printf("prod otworzyl zamek\n"); } return NULL; } void* kons(void* info) { int i; while(1) { pthread_mutex_lock(&mx); printf("kons zamknal zamek\n"); if (ile_jest == 0) { printf("kons musi czekac\n"); pthread_cond_wait(&c, &mx); printf("kons skonczyl czekanie\n"); } i = buf[poz_odcz]; printf("kons pobral %d z pozycji %d\n", i, poz_odcz); poz_odcz = (poz_odcz+1)%rozm; ile_jest--; if (ile_jest == rozm-1) pthread_cond_signal(&c); pthread_mutex_unlock(&mx); printf("kons otworzyl zamek\n"); sleep(3); } return NULL; } int main() { pthread_t th1, th2; //pthread_mutex_init(&mx, NULL); //pthread_cond_init(&c, NULL); pthread_create(&th1, NULL, prod, NULL); //sleep(5); pthread_create(&th2, NULL, kons, NULL); pthread_join(th1, NULL); pthread_join(th2, NULL); return 0; }
C
#include <mm/pmm.h> #include <mm/vmm.h> #include <kernel/log.h> uintptr_t* pmm_bitmap = NULL; size_t pmm_frames = 0; size_t pmm_framesz() { return vmm_pgsz(); } int pmm_alloc(size_t frame) { size_t off = frame / (sizeof(uintptr_t) * 8); size_t bit = frame % (sizeof(uintptr_t) * 8); if(pmm_bitmap[off] & (1 << bit)) return -1; pmm_bitmap[off] |= 1 << bit; return 0; } void pmm_free(size_t frame) { size_t off = frame / (sizeof(uintptr_t) * 8); size_t bit = frame % (sizeof(uintptr_t) * 8); pmm_bitmap[off] &= ~(1 << bit); } size_t pmm_first_free(size_t sz) { size_t frame = 0; while(frame < pmm_frames) { size_t off = frame / (sizeof(uintptr_t) * 8); if(pmm_bitmap[off] == (uintptr_t)-1) goto next; size_t bit = frame % (sizeof(uintptr_t) * 8); if(!(pmm_bitmap[off] & (1 << bit))) { size_t fail = (size_t) -1; for(size_t i = 0; i < sz; i++) { size_t of2 = (frame + i) / (sizeof(uintptr_t) * 8); if(pmm_bitmap[of2] == (uintptr_t)-1) goto fail; size_t bi2 = (frame + i) % (sizeof(uintptr_t) * 8); if(pmm_bitmap[of2] & (1 << bi2)) { fail: fail = frame + i; break; } } if(fail != (size_t)-1) frame = fail + 1; else return frame; } next: frame++; } kerror("out of memory"); return (size_t) -1; // out of memory }
C
#ifndef BSTlib_h #define BSTlib_h typedef struct node node_t; void insertNode(void *element, node_t **root, int (*cp)(void *A, void *B));///J@Ӹ`IiBST node_t *deleteNode(void *target, node_t **root, int (*cp)(void *A, void *B), void(*print_node)(void*));///RBST node_t *findMinNode(node_t *root);///XBSTȳ̤p node_t *findMaxNode(node_t *root);///XBSTȳ̤j node_t *findNode(void *target, node_t *root, int (*cp)(void *A, void *B));///XBSTŦXȪ`I void inOrder(node_t *root, void(*print_node)(void*));///CLXBSTھڤǰlܪkCӸ`Ie void treeCopy(node_t **new_tree, node_t *root, int struct_node_size);///ƻsBST void treeEqual(node_t *tree1, node_t *tree2, int(*cp)(void *A, void *B), int *flag, void(*print_node)(void*));///BSTO_ۦP #endif
C
/* Based on Task example from "Mastering the FreeRTOST Real Time Kernel: A Hands-On Tutorial Guide" */ /* Kernel includes. */ #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "timers.h" /* Common demo includes. */ #include "blocktim.h" #include "countsem.h" #include "recmutex.h" /* RISCV includes */ #include "arch/syscalls.h" #include "arch/clib.h" static const unsigned mainDELAY_LOOP_COUNT = 10000; void vPrintString(const char *s) { printf(s); } void vTask1(void *pvParameters) { volatile uint32_t ul; for (;;) { printf("task 1 start ticks %d\n", xTaskGetTickCount()); for (ul = 0; ul < mainDELAY_LOOP_COUNT; ul++) { // delay the printing } printf("task 1 end ticks %d\n", xTaskGetTickCount()); } // a task should never return, so either use a non-terminating loop or call the *vTaskDelete* function vTaskDelete( NULL ); } void vTask2(void *pvParameters) { const TickType_t xDelay10ms = pdMS_TO_TICKS( 10 ); printf("xDelay10ms %d\n", xDelay10ms); volatile uint32_t ul; for (;;) { printf("task 2 start ticks %d\n", xTaskGetTickCount()); for (ul = 0; ul < mainDELAY_LOOP_COUNT; ul++) ; printf("task 2 end ticks %d\n", xTaskGetTickCount()); vTaskDelay( xDelay10ms ); } vTaskDelete( NULL ); } void vTask3( void *pvParameters ) { const TickType_t xDelay15ms = pdMS_TO_TICKS( 15 ); TickType_t xLastWakeTime = xTaskGetTickCount(); volatile uint32_t ul; for( ;; ) { printf("task 3 start ticks %d\n", xTaskGetTickCount()); for (ul = 0; ul < mainDELAY_LOOP_COUNT; ul++) ; printf("task 3 end ticks %d\n", xTaskGetTickCount()); vTaskDelayUntil( &xLastWakeTime, xDelay15ms ); } } int main( void ) { xTaskCreate( vTask1, "Task 1", 1000, NULL, 1, NULL ); xTaskCreate( vTask2, "Task 2", 1000, NULL, 2, NULL ); xTaskCreate( vTask3, "Task 3", 1000, NULL, 3, NULL ); vTaskStartScheduler(); return 0; } void vApplicationMallocFailedHook( void ) { taskDISABLE_INTERRUPTS(); for( ;; ); } /*-----------------------------------------------------------*/ void vApplicationIdleHook( void ) { // vApplicationIdleHook() will only be called if configUSE_IDLE_HOOK is set to 1 in FreeRTOSConfig.h } void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName ) { ( void ) pcTaskName; ( void ) pxTask; taskDISABLE_INTERRUPTS(); for( ;; ); }
C
/////////////////////////////////////////////////////////////////////////// //// LCDD.C //// //// Driver for common LCD modules //// //// //// //// lcd_init() Must be called before any other function. //// //// //// //// lcd_putc(c) Will display c on the next position of the LCD. //// //// The following have special meaning: //// //// \f Clear display //// //// \n Go to start of second line //// //// \b Move back one position //// //// //// //// lcd_gotoxy(x,y) Set write position on LCD (upper left is 1,1) //// //// //// //// lcd_getc(x,y) Returns character at position x,y on LCD //// //// //// /////////////////////////////////////////////////////////////////////////// //// (C) Copyright 1996,2007 Custom Computer Services //// //// This source code may only be used by licensed users of the CCS C //// //// compiler. This source code may only be distributed to other //// //// licensed users of the CCS C compiler. No other use, reproduction //// //// or distribution is permitted without written permission. //// //// Derivative programs created using this software in object code //// //// form are not restricted in any way. //// /////////////////////////////////////////////////////////////////////////// // As defined in the following structure the pin connection is as follows: // D0 enable // D1 rs // D2 rw // D4 D4 // D5 D5 // D6 D6 // D7 D7 // // LCD pins D0-D3 are not used and PIC D3 is not used. // Un-comment the following define to use port B // #define use_portb_lcd TRUE #include "LCD.h" #include "board.h" BYTE const LCD_INIT_STRING[4] = {0x20 | (LCD_TYPE << 2), 0xc, 1, 6}; // These bytes need to be sent to the LCD // to start it up. BYTE lcd_read_nibble(void); BYTE lcd_read_byte(void) { BYTE low,high; #if defined(__PCB__) set_tris_lcd(LCD_INPUT_MAP); #else #if (defined(LCD_DATA4) && defined(LCD_DATA5) && defined(LCD_DATA6) && defined(LCD_DATA7)) output_float(LCD_DATA4); output_float(LCD_DATA5); output_float(LCD_DATA6); output_float(LCD_DATA7); #else lcdtris.data = 0xF; #endif #endif lcd_output_rw(1); delay_cycles(1); lcd_output_enable(1); delay_cycles(1); high = lcd_read_nibble(); lcd_output_enable(0); delay_cycles(1); lcd_output_enable(1); delay_us(1); low = lcd_read_nibble(); lcd_output_enable(0); #if defined(__PCB__) set_tris_lcd(LCD_OUTPUT_MAP); #else #if (defined(LCD_DATA4) && defined(LCD_DATA5) && defined(LCD_DATA6) && defined(LCD_DATA7)) output_drive(LCD_DATA4); output_drive(LCD_DATA5); output_drive(LCD_DATA6); output_drive(LCD_DATA7); #else lcdtris.data = 0x0; #endif #endif return( (high<<4) | low); } BYTE lcd_read_nibble(void) { #if (defined(LCD_DATA4) && defined(LCD_DATA5) && defined(LCD_DATA6) && defined(LCD_DATA7)) BYTE n = 0x00; /* Read the data port */ n |= input(LCD_DATA4); n |= input(LCD_DATA5) << 1; n |= input(LCD_DATA6) << 2; n |= input(LCD_DATA7) << 3; return(n); #else return(lcd.data); #endif } void lcd_send_nibble(BYTE n) { #if (defined(LCD_DATA4) && defined(LCD_DATA5) && defined(LCD_DATA6) && defined(LCD_DATA7)) /* Write to the data port */ output_bit(LCD_DATA4, bit_test(n, 0)); output_bit(LCD_DATA5, bit_test(n, 1)); output_bit(LCD_DATA6, bit_test(n, 2)); output_bit(LCD_DATA7, bit_test(n, 3)); #else lcdlat.data = n; #endif delay_cycles(1); lcd_output_enable(1); delay_us(2); lcd_output_enable(0); } void lcd_send_byte(BYTE address, BYTE n) { #if defined(__PCB__) set_tris_lcd(LCD_OUTPUT_MAP); #else lcd_enable_tris(); lcd_rs_tris(); lcd_rw_tris(); #endif lcd_output_rs(0); while ( bit_test(lcd_read_byte(),7) ) ; lcd_output_rs(address); delay_cycles(1); lcd_output_rw(0); delay_cycles(1); lcd_output_enable(0); lcd_send_nibble(n >> 4); lcd_send_nibble(n & 0xf); } #if defined(LCD_EXTENDED_NEWLINE) unsigned int8 g_LcdX, g_LcdY; #endif void lcd_init(void) { BYTE i; #if defined(__PCB__) set_tris_lcd(LCD_OUTPUT_MAP); #else #if (defined(LCD_DATA4) && defined(LCD_DATA5) && defined(LCD_DATA6) && defined(LCD_DATA7)) output_drive(LCD_DATA4); output_drive(LCD_DATA5); output_drive(LCD_DATA6); output_drive(LCD_DATA7); #else lcdtris.data = 0x0; #endif lcd_enable_tris(); lcd_rs_tris(); lcd_rw_tris(); #endif lcd_output_rs(0); lcd_output_rw(0); lcd_output_enable(0); delay_ms(30); for(i=0; i<3; i++) { lcd_send_nibble(3); delay_ms(10); } lcd_send_nibble(2); delay_ms(10); for(i=0; i<4; i++) { lcd_send_byte(0, LCD_INIT_STRING[i]); delay_ms(50); } #if defined(LCD_EXTENDED_NEWLINE) g_LcdX = 0; g_LcdY = 0; #endif } void lcd_gotoxy(BYTE x, BYTE y) { BYTE address; if(y!=1) address=LCD_LINE_TWO; else address=0; address+=x-1; lcd_send_byte(0,0x80|address); #if defined(LCD_EXTENDED_NEWLINE) g_LcdX = x - 1; g_LcdY = y - 1; #endif } void lcd_putc(char c) { switch (c) { case '\a' : lcd_gotoxy(1,1); break; case '\f' : lcd_send_byte(0,1); delay_ms(2); #if defined(LCD_EXTENDED_NEWLINE) g_LcdX = 0; g_LcdY = 0; #endif break; #if defined(LCD_EXTENDED_NEWLINE) case '\r' : lcd_gotoxy(1, g_LcdY+1); break; case '\n' : while (g_LcdX++ < LCD_LINE_LENGTH) { lcd_send_byte(1, ' '); } lcd_gotoxy(1, g_LcdY+2); break; #else case '\n' : lcd_gotoxy(1,2); break; #endif case '\b' : lcd_send_byte(0,0x10); break; #if defined(LCD_EXTENDED_NEWLINE) default : if (g_LcdX < LCD_LINE_LENGTH) { lcd_send_byte(1, c); g_LcdX++; } break; #else default : lcd_send_byte(1,c); break; #endif } } char lcd_getc(BYTE x, BYTE y) { char value; lcd_gotoxy(x,y); while ( bit_test(lcd_read_byte(),7) ); // wait until busy flag is low lcd_output_rs(1); value = lcd_read_byte(); lcd_output_rs(0); return(value); } // write a custom character to the ram // which is 0-7 and specifies which character array we are modifying. // ptr points to an array of 8 bytes, where each byte is the next row of // pixels. only bits 0-4 are used. the last row is the cursor row, and // usually you will want to leave this byte 0x00. void lcd_set_cgram_char(unsigned int8 which, unsigned int8 *ptr) { unsigned int i; which <<= 3; which &= 0x38; lcd_send_byte(0, 0x40 | which); //set cgram address for(i=0; i<8; i++) { lcd_send_byte(1, *ptr++); } #if defined(LCD_EXTENDED_NEWLINE) lcd_gotoxy(g_LcdX+1, g_LcdY+1); //set ddram address #endif } void lcd_cursor_on(int1 on) { if (on) { lcd_send_byte(0,0x0F); //turn LCD cursor ON } else { lcd_send_byte(0,0x0C); //turn LCD cursor OFF } }
C
/* * William Wood cssc1167, Nadim Tahmass cssc1158 * CS570, Summer 2018 * Assignment #2, File Editor * copyFile.c */ //Holds all of our big file copying functions #include "fileEditor.h" //Copy a file into .bak void copyFile(char *nameCpy){ file1 = open(nameCpy, O_RDONLY); if(file1 < 0){ printf("File does not exist returning to main menu.\n"); exit(1); } //Adds .bak extension to the end of file name nameCpy[strlen(nameCpy)] = '.'; nameCpy[strlen(nameCpy)] = 'b'; nameCpy[strlen(nameCpy)] = 'a'; nameCpy[strlen(nameCpy)] = 'k'; remove(nameCpy); file2 = creat(nameCpy, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if(file2 <0){ printf("Shadow file failed to create returning to main menu.\n"); exit(1); } while(1){ in = read(file1, buffer, bufferSize); if (in <= 0){ break; } out = write(file2, buffer, in); if(out <= 0){ break; } } close(file1); close(file2); } //Copy a file into .bak void fileBak(char *nameCpy){ file1 = open(nameCpy, O_RDONLY); if(file1 < 0){ printf("File does not exist returning to main menu.\n"); exit(1); } //Adds .bak extension to the end of file name nameCpy[strlen(nameCpy)-1] = 0; nameCpy[strlen(nameCpy)-1] = 0; nameCpy[strlen(nameCpy)-1] = 0; nameCpy[strlen(nameCpy)-1] = 0; remove(nameCpy); file2 = creat(nameCpy, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if(file2 <0){ printf("Shadow file failed to create returning to main menu.\n"); exit(1); } while(1){ in = read(file1, buffer, bufferSize); if (in <= 0){ break; } out = write(file2, buffer, in); if(out <= 0){ break; } } close(file1); close(file2); }
C
// Copies a BMP file #include <stdio.h> #include <stdlib.h> #include <math.h> #include "bmp.h" int main(int argc, char *argv[]) { // ensure proper usage if (argc != 4) { fprintf(stderr, "Usage: copy infile outfile\n"); return 1; } // get scaleFactor char *tempFactor = argv[1]; int scaleFactor = atoi(tempFactor); if (scaleFactor < 0 || scaleFactor > 100) { fprintf(stderr, "Usage: give proper number\n"); return 1; } // remember filenames char *infile = argv[2]; char *outfile = argv[3]; // open input file FILE *inptr = fopen(infile, "r"); if (inptr == NULL) { fprintf(stderr, "Could not open %s.\n", infile); return 2; } // open output file FILE *outptr = fopen(outfile, "w"); if (outptr == NULL) { fclose(inptr); fprintf(stderr, "Could not create %s.\n", outfile); return 3; } // read infile's BITMAPFILEHEADER BITMAPFILEHEADER bf; fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr); // read infile's BITMAPINFOHEADER BITMAPINFOHEADER bi; fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr); // ensure infile is (likely) a 24-bit uncompressed BMP 4.0 if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 || bi.biBitCount != 24 || bi.biCompression != 0) { fclose(outptr); fclose(inptr); fprintf(stderr, "Unsupported file format.\n"); return 4; } // create output's header info and file, to be scaled... BITMAPFILEHEADER newBF = bf; BITMAPINFOHEADER newBI = bi; printf("%i and %i", bf.bfSize, newBF.bfSize); // scaling the width/height: newBI.biWidth *= scaleFactor; newBI.biHeight *= scaleFactor; // new padding int newPadding = (4 - (newBI.biWidth * sizeof(RGBTRIPLE)) % 4) % 4; // new imageSize etc. newBI.biSizeImage = (((sizeof(RGBTRIPLE) * newBI.biWidth) + newPadding) * abs(newBI.biHeight)); newBF.bfSize = newBI.biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); printf("%i and %i", bf.bfSize, newBF.bfSize); // write outfile's BITMAPFILEHEADER fwrite(&newBF, sizeof(BITMAPFILEHEADER), 1, outptr); // write outfile's BITMAPINFOHEADER fwrite(&newBI, sizeof(BITMAPINFOHEADER), 1, outptr); // determine padding for scanlines int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4; // an experiment: // for each row aka iterating over infile's scanlines: for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++) { // for SF - 1 times: for (int m = 0; m < scaleFactor - 1; m++) { // iterate over pixels in scanline for (int j = 0; j < bi.biWidth; j++) { // temporary storage -> RGBTRIPLE triple; // read RGB triple from infile fread(&triple, sizeof(RGBTRIPLE), 1, inptr); // do this for every scale factor unit... for (int k = 0; k < scaleFactor; k++) { // write RGB triple to outfile -- tested with SF as quantity fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr); } } int negWidth = -bi.biWidth * sizeof(RGBTRIPLE); fseek(inptr, negWidth, SEEK_CUR); for (int k = 0; k < newPadding; k++) // i think this adds padding! { fputc(0x00, outptr); } // fseek -> from current position, back by width, reg input... } // out of loop: also, store and write x SF for each pixel, PLUS Padding && skip input padding via fseek; find this set to be dodgy // iterate over pixels in scanline for (int j = 0; j < bi.biWidth; j++) { // temporary storage RGBTRIPLE triple; // read RGB triple from infile fread(&triple, sizeof(RGBTRIPLE), 1, inptr); // do this for every scale factor unit... for (int k = 0; k < scaleFactor; k++) { // write RGB triple to outfile -- tested with SF as quantity fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr); } } // skip over padding, if any fseek(inptr, padding, SEEK_CUR); // then add it back (to demonstrate how) for (int k = 0; k < newPadding; k++) { fputc(0x00, outptr); } } // close infile fclose(inptr); // close outfile fclose(outptr); // success return 0; }
C
/* This file is written by Lepidum Co., Ltd. Copyright (c) 2005-2006 by Lepidum Co., Ltd. */ /** * @file unix/dir.test.c */ #include <dirent.h> #include "common.h" /** * @testname opendir_closedir_readdir_rewinddir_1 * @testfor opendir * @testfor closedir * @testfor readdir * @testfor rewinddir */ TEST_CASE(opendir_closedir_readdir_rewinddir_1) { DIR *dir = opendir("/"); struct dirent *dent; int found; int i; TEST_FAIL_IF(dir == NULL); for (i = 0; i < 2; i++) { found = 0; while ((dent = readdir(dir)) != NULL){ if (strcmp(dent->d_name, "usr") == 0) found++; if (strcmp(dent->d_name, "etc") == 0) found++; if (strcmp(dent->d_name, "dev") == 0) found++; if (strcmp(dent->d_name, "tmp") == 0) found++; } TEST_FAIL_IF(found != 4); rewinddir(dir); } TEST_FAIL_IF(closedir(dir) != 0); TEST(1); } /** * @testname seekdir_telldir_1 * @testfor seekdir * @testfor telldir */ TEST_CASE(seekdir_telldir_1) { DIR *dir = opendir("/"); struct dirent *dent; int found; int i; long pos; TEST_FAIL_IF(dir == NULL); pos = telldir(dir); for (i = 0; i < 2; i++) { found = 0; while ((dent = readdir(dir)) != NULL){ if (strcmp(dent->d_name, "usr") == 0) found++; if (strcmp(dent->d_name, "etc") == 0) found++; if (strcmp(dent->d_name, "dev") == 0) found++; if (strcmp(dent->d_name, "tmp") == 0) found++; } TEST_FAIL_IF(found != 4); seekdir(dir, 0); } TEST_FAIL_IF(closedir(dir) != 0); TEST(1); }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* print.c :+: :+: */ /* +:+ */ /* By: asulliva <[email protected]> +#+ */ /* +#+ */ /* Created: 2019/07/05 15:20:43 by asulliva #+# #+# */ /* Updated: 2019/08/13 19:37:39 by asulliva ######## odam.nl */ /* */ /* ************************************************************************** */ #include "push_swap.h" void init_print(t_stack *stack) { if (stack->print == 1 || stack->print == 2) { stack->colour ? ft_putstr(RED) : 0; ft_printf("Initial array: "); ft_print_int_array(stack->a, stack->size_a); stack->colour ? ft_putstr(GREEN) : 0; } } void final_print(t_stack *stack) { if (stack->print == 1 || stack->print == 2) { stack->colour ? ft_putstr(RED) : 0; if (stack->size_a) { ft_printf("Final array A: "); ft_print_int_array(stack->a, stack->size_a); } if (stack->size_b) { ft_printf("Final array B: "); ft_print_int_array(stack->b, stack->size_b); } } if (stack->total) { stack->colour ? ft_putstr(YELLOW) : 0; ft_printf("Total operations: %d\n", stack->ops); stack->colour ? ft_putstr(NORMAL) : 0; } } void usage_print(int option) { if (option == 1) ft_printf("Usage:\n./push_swap [-v[s] -t -c][array (no doubles)]\n"); if (option == 0) ft_printf("Usage:\n./checker [-v -t -c][array (no doubles)]\n"); exit(0); } void stack_print(t_stack *stack) { if (stack->slow) { usleep(750000); system("clear"); } ft_printf("A: "); ft_print_int_array(stack->a, stack->size_a); if (stack->size_b) { ft_printf("B: "); ft_print_int_array(stack->b, stack->size_b); } if (stack->slow) { ft_putstr(YELLOW); ft_printf("Total: %d\n", stack->ops); if (stack->colour) ft_putstr(GREEN); else ft_putstr(NORMAL); } }
C
/* Assignment 3 Roll Number: CS19BTECH11026 Name: Naitik Malav */ #include<stdio.h> #include<string.h> #include<stdlib.h> struct node { char numPlate[7]; struct node *left; struct node *right; struct node *parent; }; /* this time I have modified compare function..it is not same as Assignment0 and Assignment1 compare(x,y): 1.now it returns -1 if x>y 2. returns 1 if x<y 3. returns 0 if x=52y */ int compare(char *x, char *y) { if( (*x) < (*y) ) return 1; else if( (*x) > (*y) ) return -1; else { x++; y++; if( *x != '\0' && *y!='\0') return compare(x,y); } return 0; } //creates a node struct node *create(struct node *root, char arr[]) { root = (struct node *)malloc(sizeof(struct node)); char *temp = root->numPlate; temp = strcpy(temp, arr); root->left = NULL; root->right = NULL; return root; } // inserting numberPlate recursively in BST and also linking parent pointer struct node *insert(struct node *root, char arr[]) { if (root == NULL) root = create(root, arr); else { if (compare(root->numPlate, arr) == 1) { //arr > root->numPlate struct node *rightChild = insert(root->right, arr); root->right = rightChild; rightChild->parent = root; //linking parent pointer } else if (compare(root->numPlate, arr) == -1) { //arr < root->numPlate struct node *leftChild = insert(root->left, arr); root->left = leftChild; leftChild->parent = root; //linking parent pointer } } return root; } /* prints path of the arr if it is present in BST */ void Path(struct node *root, char arr[]) { if(root != NULL) { if(compare(root->numPlate, arr) == 0) return; //breaking recursion on successful completion else if(compare(root->numPlate, arr) == -1 ){ printf("L"); Path(root->left, arr); } else if(compare(root->numPlate, arr) == 1 ){ printf("R"); Path(root->right, arr); } } } /*search the passed arr in BST and returns 1 for successful search.*/ int Search(struct node *root, char arr[]) { if(root != NULL) { if(compare(root->numPlate, arr) == 0) return 1; //search successful else if(compare(root->numPlate, arr) == -1 ) Search(root->left, arr); else if(compare(root->numPlate, arr) == 1 ) Search(root->right, arr); } else //if not present in BST return 0; } /*returns address of the node which is just smaller than passed numberPlate 1. I want to point out one info that I found out here - This below function is also an predecessor but in a diff style 2. it returns NULL only in 1 case if your entered arr is less than the minimum of tree*/ struct node *GetImmediateSmall(struct node *root, char arr[]) { if(root == NULL) return NULL; else if(compare(root->numPlate, arr) == 1) { struct node *temp = GetImmediateSmall(root->right, arr); if(temp == NULL) return root; else return temp; } else if(compare(root->numPlate, arr) == -1) return GetImmediateSmall(root->left, arr); } /* return the address of node whose numPlate is same as arr */ struct node *GetAddress(struct node *root, char arr[]) { struct node *temp = NULL; if(root != NULL) { if(compare(root->numPlate, arr) == -1 && root->left!=NULL){ //arr is less than root->numPlate temp = GetAddress(root->left, arr); return temp; } else if(compare(root->numPlate, arr) == 1 && root->right!=NULL){ //arr is greater than root->numPlate temp = GetAddress(root->right, arr); return temp; } return root; } } /* return the address of node whose value is minimum i.e. left most node */ struct node* minimum(struct node *root) { while(root->left != NULL) root = root->left; return root; } /* return the address of node whose value is maximum i.e. right most node */ struct node* maximum(struct node *root) { while(root->right != NULL) root = root->right; return root; } /* return the char ptr to the numPlate which is successor of passed arr */ char *successor(struct node *root, char arr[]) { //if arr is present in BST if(Search(root, arr) == 1) { struct node *NODE = GetAddress(root, arr); //getting address of the node where arr is located in BST struct node *MAX = maximum(root); //getting address of the node which has numberPlate with max ASCII value if(compare(MAX->numPlate, NODE->numPlate) == 0) //in this case successor doesn't not exist return "0"; else if(NODE->right != NULL) //here successor is minimum of right subtree of NODE return minimum(NODE->right)->numPlate; else if(NODE->right == NULL) { //case 2 struct node *Child = NODE; struct node *Parent = NODE->parent; while(1) { //if Parent->left is same as child then in this case Child will be x and and Parent is its parent. if(Parent->left != NULL && compare(Parent->left->numPlate, Child->numPlate) == 0) return Parent->numPlate; //x is left child of Parent, so Parent is successor //if Parent->left and child both are different then set Child to Parent, and Parent to Parent->parent else { Child = Parent; Parent = Parent->parent; } } } } /* if arr is not present in BST then lets find out the immediate smaller numberPlate than the arr, and here successor of immediate smaller plate is also the successor of arr */ else if(Search(root, arr) == 0) { struct node *NODE = GetImmediateSmall(root, arr); successor(root, NODE->numPlate); //calling successor func recursively for immediate smaller numberPlate } } /* prints the value of predecessor of passed numberPlate */ void predecessor(struct node *root, char arr[]) { //if arr is present in BST if(Search(root, arr) == 1) { struct node *NODE = GetAddress(root, arr); //getting its address struct node *MIN = minimum(root); //getting address of smallest element which is left most if(compare(MIN->numPlate, NODE->numPlate) == 0) { /*if smallest element and passed numberPlate both are same then its predecessor cannot exist */ printf("0\n"); return; } else if(NODE->left != NULL) //largest element in its left subtree is successor printf("%s\n", maximum(NODE->left)->numPlate); /* In this case I'm finding out the immediate smaller numberPlate than arr which is it's predecessor with the help of previously wrote func GetImmediateSmall */ else if(NODE->left == NULL) printf("%s\n", GetImmediateSmall(root, arr)->numPlate); } //if it is not present in BST else if(Search(root, arr) == 0) { /*again just find immediate smaller number plate and that will be it's predecessor by definition according to slides */ struct node *NODE = GetImmediateSmall(root, arr); if(NODE != NULL) printf("%s\n", NODE->numPlate); else //NULL if passed arr is smaller than smallest numberPlate printf("0\n"); } } /*return the no. of children in passed BST */ int childCTR(struct node *root) { if(root->left==NULL && root->right==NULL) return 0; else if(root->left==NULL && root->right!=NULL) return 1; else if(root->left!=NULL && root->right==NULL) return 1; else if(root->left!=NULL && root->right!=NULL) return 2; } /*deletes the node */ struct node *delete(struct node *root, char arr[]) { if(root == NULL) //base case return root; if (compare(root->numPlate, arr) == -1) { //if arr is smaller than root->numPlate root->left = delete(root->left, arr); if(root->left != NULL) //linking back parent pointer root->left->parent = root; } else if (compare(root->numPlate, arr) == 1) { //if arr is greater root->right = delete(root->right, arr); if(root->right != NULL) //linking back parent pointer root->right->parent = root; } else { /*node with one child or no child*/ if(root->right==NULL) { struct node *Temp = root->left; free(root); return Temp; } else if (root->left==NULL) { struct node *Temp = root->right; free(root); return Temp; } /*node with 2 child*/ char *Splate = successor(root, arr); //successor's numPlate struct node *S = GetAddress(root, Splate); //sucessor's address // Copying successor's content to this node for(int i=0; i<6; i++, Splate++) root->numPlate[i] = (*Splate); root->numPlate[6] = '\0'; root->right = delete(root->right, root->numPlate); //call delete function for successor if(root->right != NULL) //linking parent pointer back root->right->parent = root; } return root; } /*prints inorder of BST */ void Inorder(struct node* root) { if (root == NULL) return; Inorder(root->left); printf("%s ", root->numPlate); Inorder(root->right); } /*prints Postorder of BST */ void Postorder(struct node *root) { if (root == NULL) return; Postorder(root->left); Postorder(root->right); printf("%s ", root->numPlate); } int main(){ char choice, numberPlate[7]; _Bool requests = 0; struct node *ROOT = NULL; //root of the tree // Fetching till we hit the first request while(scanf("%s",numberPlate)!=-1){ if(!requests){ if(strlen(numberPlate) == 1){ // Detecting start of request lines. choice = numberPlate[0]; requests = 1; } else{ ROOT = insert(ROOT, numberPlate); // *** Call your insert function here with argument numberPlate *** } } else break; // choice and numberPlate have values to be processed!! } do{ // Ugly do-while to process first request line before first scanf. if(choice == 'S'){ //*** Call your search function here with argument numberPlate *** if(Search(ROOT, numberPlate) == 1){ //if numberPlate present in tree if(compare(ROOT->numPlate, numberPlate) == 0) //if it is ROOT then no need to print path printf("1"); else { printf("1 "); Path(ROOT, numberPlate); //otherwise print path } } else if(Search(ROOT, numberPlate) == 0) //if not present in BST printf("0"); //print 0 for unsuccesful search printf("\n"); } else if(choice == '<'){ //*** Call your predecessor function here with argument numberPlate *** predecessor(ROOT, numberPlate); } else if(choice == '>'){ //*** Call your successor function here with argument numberPlate *** printf("%s\n", successor(ROOT, numberPlate)); } else if(choice == '+'){ if(Search(ROOT, numberPlate) == 0) ROOT = insert(ROOT, numberPlate); } else if(choice == '-'){ if (Search(ROOT, numberPlate) == 0) //if not present in BST printf("-1\n"); else { if(childCTR(GetAddress(ROOT, numberPlate)) > 0) { //if children are greater than 0 if(childCTR(GetAddress(ROOT, numberPlate)) == 1) { //in this case it's child is going to replace node if(GetAddress(ROOT, numberPlate)->left == NULL) { printf("%d ", childCTR(GetAddress(ROOT, numberPlate))); //printing no. of children printf("%s\n", GetAddress(ROOT, numberPlate)->right->numPlate); //right child going to replace it ROOT = delete(ROOT, numberPlate); } else if(GetAddress(ROOT, numberPlate)->right == NULL) { printf("%d ", childCTR(GetAddress(ROOT, numberPlate))); //printing no. of children printf("%s\n", GetAddress(ROOT, numberPlate)->left->numPlate); //left child going to replace it ROOT = delete(ROOT, numberPlate); } } else { //if it has 2 child then inorder successor is going to replace it char *Splate = successor(ROOT, numberPlate); //copying successor's plate struct node *S = GetAddress(ROOT, Splate); //getting successor's address printf("%d ", childCTR(GetAddress(ROOT, numberPlate))); //printing no. of children printf("%s\n", Splate); //printing successor ROOT = delete(ROOT, numberPlate); //deleting numberPlate } } else { //if it has 0 children printf("0\n"); ROOT = delete(ROOT, numberPlate); //simply delete the node as it has no successor } } } else if(choice == 'I'){ //printing inorder Inorder(ROOT); printf("\n"); } else if(choice == 'P'){ //printing postorder Postorder(ROOT); printf("\n"); } }while(scanf("%*[\n]%c %6s",&choice, numberPlate)!=-1); return(0); }
C
#define _BSD_SOURCE #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <stddef.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <string.h> #include <errno.h> #include <libgen.h> int ProcessDir(char* prog, char* directory, int from, int to, FILE* fd_output, unsigned long* counter) { errno = 0; DIR *dp = opendir(directory); struct dirent *d; if (dp == NULL && errno != 0) { fprintf(stderr, "%s: %s %s\n", prog, directory, strerror(errno)); return -1; } errno = 0; while ((d = readdir(dp)) != NULL) { struct stat file_stat; char *currentPath = (char *)malloc(strlen(directory) + strlen(d->d_name) + 2); strcpy(currentPath, directory); strcat(currentPath, d->d_name); if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) { free(currentPath); continue; } errno = 0; switch(d->d_type) { case DT_DIR: strcat(currentPath, "/"); ProcessDir(prog, currentPath, from, to, fd_output, counter); break; case DT_REG: if (stat(currentPath, &file_stat) != 0) { fprintf(stderr, "%s: %s %s\n", prog, currentPath, strerror(errno)); return -1; } (*counter)++; if (file_stat.st_size > from && file_stat.st_size < to) { fprintf(fd_output, "%s %s %d\n", currentPath, d->d_name, (int)file_stat.st_size); } break; } free(currentPath); } if (errno != 0) { fprintf(stderr, "%s: %s %s\n", prog, directory, strerror(errno)); return -1; } closedir(dp); if (errno != 0) { fprintf(stderr, "%s: %s %s\n", prog, directory, strerror(errno)); return -1; } return 0; } int main(int argc, char *argv[]) { char* prog = basename(argv[0]); char* directory; FILE* fd_output; DIR* dPtr; int from; int to; unsigned long* counter = (unsigned long*)malloc(sizeof(unsigned long)); if (argc < 5) { fprintf(stderr, "%s: %s\n", prog, "Too few arguments. \nRight syntax: directory_to_check size_from size_to output_file"); return -1; } directory = realpath(argv[1], NULL); if (errno != 0) { fprintf(stderr, "%s: %s\n", prog, strerror(errno)); return -1; } if (strcmp(directory, "/") != 0) { strcat(directory, "/"); } dPtr = opendir(directory); if (errno != 0) { fprintf(stderr, "%s: %s\n", prog, strerror(errno)); return -1; } closedir(dPtr); if (errno != 0) { fprintf(stderr, "%s: %s\n", prog, strerror(errno)); return -1; } from = atoi(argv[2]); to = atoi(argv[3]); if (from > to) { fprintf(stderr, "%s: %s\n", prog, "'TO' must me <= 'FROM'."); return -1; } if (from < 0) { fprintf(stderr, "%s: %s\n", prog, "'FROM' must be >= 0."); return -1; } if (errno != 0) { fprintf(stderr, "%s: %s\n", prog, strerror(errno)); return -1; } fd_output = fopen(argv[4], "w"); if (errno != 0) { fprintf(stderr, "%s: %s\n", prog, strerror(errno)); return -1; } (*counter) = 0; ProcessDir(prog, directory, from, to, fd_output, counter); fclose(fd_output); if (errno != 0) { fprintf(stderr, "%s: %s\n", prog, strerror(errno)); return -1; } printf("%lu\n", *counter); return 0; }
C
#include "map.h" MAP *newMap(int colors, int map_size){ if(colors<=0 || map_size<=0) return NULL; MAP *rt=(MAP *)malloc(sizeof(MAP)); int i; if(rt!=NULL){ rt->headers=(NODE **)malloc(map_size*sizeof(NODE *)); for(i=0;i<map_size;i++){ rt->headers[i]=newNode(); rt->headers[i]->header=HEADER; } rt->colors=colors; rt->map_size=map_size; rt->nEdges=(int *)malloc(map_size*sizeof(int)); } return rt; } void mapStartUp(MAP **tgt, FILE *aux){ int colors, map_size,i,j; map_size=readInt(aux); colors=readInt(aux); NODE *walk; *tgt=newMap(colors, map_size); for(j=0;j<map_size;j++){ (*tgt)->headers[j]->name=readLine(aux); (*tgt)->nEdges[j]=readInt(aux); walk=(*tgt)->headers[j]; for(i=0;i<(*tgt)->nEdges[j];i++){ plugNode(walk, readLine(aux)); walk=walk->nxt; } walk->nxt=(*tgt)->headers[j]; } closeFile(aux); } void printMap(MAP *tgt){ int i; printf("Map_Size: %d\n Colors: %d\n",tgt->map_size, tgt->colors); for(i=0;i<tgt->map_size;i++){ printf("HEADER:\n"); printNode(tgt->headers[i]); printf("EDGES\n"); printAllNodes(tgt->headers[i]->nxt); } } void freeMap(MAP **tgt){ if(tgt==NULL || *tgt==NULL) return; int i=0; NODE *aux=NULL; for(i=0;i<((*tgt)->map_size);i++){ aux=popNode((*tgt)->headers[i]); while(!IsHeader(aux->header)){ freeNode(&aux); aux=popNode((*tgt)->headers[i]); }; freeNode(&aux); } free((*tgt)->nEdges); free((*tgt)->headers); free(*tgt); } void paintRecursive(MAP *tgt, int method){ int i; if(method==0){ } else if(method==1){} else if(method==2){} } void paintMapBruteForce(MAP **tgt){ return paintRecursive(*tgt,0); } void paintMapMVR(MAP **tgt){ return paintRecursive(*tgt,1); } void paintMapLookAhead(MAP **tgt){ return paintRecursive(*tgt,2); }
C
/* Comp 40 - HW6 - memory.h * Reed Kass-Mullet (rkassm01) and Jerry Wang (jwang35) * November 17, 2020 * Purpose: Interface for the Memory Module. This module contains all * the functions needed to initialize, modify, or retrieve * information from UM memory. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stack.h> #include <seq.h> #include <assert.h> typedef struct Memory { Seq_T segments; Stack_T unmapped; uint32_t pos_counter; } *Memory; /* initialize_memory() * Gets: Nothing * Returns: Memory (struct Memory*) * Does: Initializes the Memory structure for UM */ Memory initialize_memory(); /* mem_map_segment * Gets: Memory memory, a Memory struct containing all allocated segments * Uint32_t size, a unsigned int containing the size of the new * segment to be initialized. * Returns: uint32_t representing the index the segment was mapped to * Does: Initializes a new memory segment, sets all values to 0, checks if * there is space to re-use a section by checking the unmapped stack. * If there is nothing on the unmapped stack, it adds a new segment to * the end. If there are indexes on the stack, it pops the index and uses * it as a guide to re-use a section/segment location for the new segment * being mapped. */ uint32_t mem_map_segment(Memory memory, uint32_t size); /* mem_unmap_segment * Gets: Memory memory, a Memory struct containing all allocated segments * uint32_t index, an unsigned int representing the index of the * segment to be unmapped * Returns: Nothing * Does: Unmaps the segment at given index in memory */ void mem_unmap_segment(Memory memory, uint32_t index); /* load_segment * Gets: Memory memory, a Memory struct containing all allocated segments * Uint32_t b, represents the value of register[b]. in this function * it is the value of the segment index being loaded * uint32_t c, represents the value of register[c]. In this function * it is the value of the index of the word in segment * being loaded * Returns: uint32_t representing the index being loaded * Does: Returns the uint32_t word in segment number b and index number c. */ uint32_t load_segment(Memory memory, uint32_t b, uint32_t c); /* store_segment * Gets: Memory memory, a Memory struct containing all allocated segments * uint32_t a, represents the value of register[a]. In this function * it is the index value of the affected memory segment * Uint32_t b, represents the value of register[b]. in this function * it is the word index of the affected memory segment * uint32_t c, represents the value of register[c]. In this function * it is the value being stored in memory. * Returns: nothing * Does: Stores the uint32_t word c in segment number a at index number b. */ void store_segment(Memory memory, uint32_t a, uint32_t b, uint32_t c_value); /* memory_free * Gets: Memory memory, a Memory struct containing all allocated segments * Returns: nothing * Does: Frees all of the heap memory being stored in the memory struct. */ void memory_free(Memory memory);
C
/* * This program checks for a doorbell from a modified * version of the Weever bootloader. * It maps in the Phi's GDDR (low) * memory into host memory, and looks for the value * 0xdeadbeef at a special address. * * Kyle C. Hale 2014 * */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/mman.h> #include <fcntl.h> #define PHI_PATH "/sys/class/mic/mic0/state" //#define PHI_WEEVER "boot:linux:/usr/share/mpss/boot/weever:/usr/share/mpss/boot/initramfs-knightscorner.cpio.gz" #define PHI_WEEVER "boot:linux:/home/joncon/barrelfish/k1om/sbin/weever:/root/micstuff/naut_setup/nautilus.bin" // in secs #define DEFAULT_TIMEOUT 60 #define MAX_TIMEOUT (60*5) // This is where the host kernel has mapped the device's // GDDR memory (8GB) using BARs #define PHI_GDDR_ADDR 0x3fc00000000 // We only need a few megs of it though #define PHI_GDDR_RANGE_SZ (1024*1024*512) #define STATUS_ADDR 0x7a7a70 #define STATUS_OK 0xdeadbeef #define AFTER_LOADER_STATUS_ADDR 0x7a7a74 #define AFTER_LOADER_STATUS_OK 0xdeadbead #define NAUT_STATUS_ADDR 0x7a7a74 #define NAUT_OK 0xfeedfeed // for mapping the Phi's physical memory #define MEM "/dev/mem" static void usage (char * prog) { fprintf(stderr, "Usage: %s [-t <timeout>]\n", prog); exit(0); } /* * this will use Intel's Xeon Phi driver sysfs interface * to initiate a boot on the card using a custom image * */ static int boot_phi (void) { char * buf = PHI_WEEVER; int fd = 0; fd = open(PHI_PATH, O_RDWR); if (fd < 0) { fprintf(stderr, "Couldn't open file %s (%s)\n", PHI_PATH, strerror(errno)); return -1; } if (write(fd, buf, strlen(buf)) < 0) { fprintf(stderr, "Couldnt write file %s (%s)\n", PHI_PATH, strerror(errno)); return -1; } close(fd); return 0; } /* * test our well-known address for the magic * cookie. Return 1 if we find it, 0 otherwise * */ static int pollit (void * base, uint64_t offset, uint32_t doorbell_val) { uint32_t val = 0; int i; val = *(uint32_t*)((char*)base + offset); if (val == doorbell_val) { return 1; } return 0; } static int wait_for_doorbell (void * base, uint64_t offset, uint32_t doorbell_val, uint32_t timeout, const char * ok_msg) { uint8_t ping_recvd = 0; /* need to give the card some time to boot */ while (timeout) { if (pollit(base, offset, doorbell_val)) { ping_recvd = 1; break; } putchar('.'); fflush(stdout); sleep(1); --timeout; } if (ping_recvd) { printf("OK: %s\n", ok_msg); } else { printf("FAIL: timeout\n"); return -1; } return 0; } int main (int argc, char ** argv) { unsigned timeout = DEFAULT_TIMEOUT; int memfd = 0; uint64_t range_sz = PHI_GDDR_RANGE_SZ; void * gddr_addr = (void*)PHI_GDDR_ADDR; if (argc > 1 && strcmp(argv[1], "-h") == 0) { usage(argv[0]); } if (argc > 1 && strcmp(argv[1], "-t") == 0) { if (argc > 2) { timeout = atoi(argv[2]); } if (timeout > MAX_TIMEOUT) { timeout = MAX_TIMEOUT; } } /* what we're doing here is mapping in /dev/mem into this process. * if you're not familiar, /dev/mem is a device file that allows you * to read/write the physical memory of the machine. It just so happens * that some of the *host's* physical memory corresponds to the Phi card's * memory. We're going to leverage that */ if (!(memfd = open(MEM, O_RDONLY))) { fprintf(stderr, "Error opening file %s\n", MEM); return -1; } printf("Mapping MIC 0 MMIO memory range (%u bytes at %p)\n", range_sz, gddr_addr); void * buf = mmap(NULL, range_sz, PROT_READ, MAP_PRIVATE, memfd, (unsigned long long)gddr_addr); if (buf == MAP_FAILED) { fprintf(stderr, "Couldn't map PHI MMIO range\n"); return -1; } printf("Booting PHI with custom image..."); if (!boot_phi()) { printf("OK\n"); } else { printf("FAIL\n"); exit(1); } #if 0 printf("Waiting for doorbell from Weever in GDDR range (timeout=%us)\n", timeout); if (wait_for_doorbell(buf, STATUS_ADDR, STATUS_OK, timeout, "Weever up and running") == -1) { fprintf(stderr, "Exiting\n"); exit(1); } printf("Waiting for doorbell from Weever after it calls the 'loader' function (timeout=%us)\n", timeout); if (wait_for_doorbell(buf, STATUS_ADDR+4, STATUS_OK, timeout, "Weever about to call loader") == -1) { fprintf(stderr, "Exiting\n"); exit(1); } #endif printf("Dump of status prints:\n"); int i = 0; int j = 0; while (1) { unsigned char *o = (unsigned char*) (buf+STATUS_ADDR); printf("------------------------------------------\n"); for (i = 0; i < 512; i+=16) { printf("%04x:\t", i); for (j=i;j<i+16;j++) { printf("%02x",o[j]); } printf("\t"); for (j=i;j<i+16;j++) { if (isprint(o[j])) { putchar(o[j]); } else { putchar('.'); } } printf("\n"); } fflush(stdout); sleep(2); } printf("Waiting for doorbell after loader (timeout=%us)\n", timeout); if (wait_for_doorbell(buf, STATUS_ADDR+8, STATUS_OK, timeout, "Weever after loader running") == -1) { fprintf(stderr, "Exiting\n"); exit(1); } return 0; }
C
#include<stdio.h> #include<math.h> int main (){ float a, b, c, delta, rp, rn; scanf("%f %f %f", &a, &b, &c); if (a == 0){ printf("Impossivel calcular\n"); return 0; } delta = (b * b) -4 * a * c; if (delta < 0){ printf("Impossivel calcular\n"); return 0; } rp = (-b + sqrt(delta))/(2 * a); rn = (-b - sqrt(delta))/(2 * a); printf("R1 = %.5f\nR2 = %.5f\n", rp, rn); return 0; }
C
/* ** EPITECH PROJECT, 2018 ** CPool_Day06_2018 ** File description: ** test_my_strncmp */ #include <criterion/criterion.h> int my_strncmp(char const *s1, char const *s2, int n); Test(my_strncmp, return_value_cut_by_ocurence) { cr_assert_eq(my_strncmp("azzzzz", "zaaaaa", 2), -25); }
C
#include "runtime.h" #include <stdlib.h> #include <string.h> #include <assert.h> static JsObject *dummy; // forward declarations static JsDictEntry* lookdict_string(JsDictObject *mp, JsObject *key, uhash hash); #define EMPTY_TO_MINSIZE(mp) do { \ memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \ (mp)->ma_used = (mp)->ma_fill = 0; \ (mp)->ma_table = (mp)->ma_smalltable; \ (mp)->ma_mask = JsDict_MINSIZE - 1; \ } while(0) // use free list #define JsDict_MAXFREELIST 64 static JsDictObject *free_list[JsDict_MAXFREELIST]; static int numfree; JsObject * JsDict_New(void) { register JsDictObject *mp; if (dummy == NULL) { /* Auto-initialize dummy */ dummy = JsString_FromString("<dummy key>"); } if (numfree) { mp = free_list[--numfree]; _Js_NewReference((JsObject *)mp); } else { mp = Js_Malloc(sizeof(JsDictObject)); JsObject_INIT(mp, &JsDict_Type); } EMPTY_TO_MINSIZE(mp); mp->ma_lookup = lookdict_string; return (JsObject *)mp; } #define PERTURB_SHIFT 5 static JsDictEntry* lookdict_string(JsDictObject *mp, JsObject *key, uhash hash) { register size_t i; register size_t perturb; register JsDictEntry *freeslot; register size_t mask = (size_t)mp->ma_mask; JsDictEntry *ep0 = mp->ma_table; register JsDictEntry *ep; i = hash & mask; ep = &ep0[i]; if (ep->me_key == NULL || ep->me_key == key) return ep; if (ep->me_key == dummy) freeslot = ep; else { if (ep->me_hash == hash && _JsString_Eq(ep->me_key, key)) return ep; freeslot = NULL; } /* In the loop, me_key == dummy is by far (factor of 100s) the least likely outcome, so test for that last. */ for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { i = (i << 2) + i + perturb + 1; ep = &ep0[i & mask]; if (ep->me_key == NULL) return freeslot == NULL ? ep : freeslot; if (ep->me_key == key || (ep->me_hash == hash && ep->me_key != dummy && _JsString_Eq(ep->me_key, key))) return ep; if (ep->me_key == dummy && freeslot == NULL) freeslot = ep; } assert(0); /* NOT REACHED */ return 0; } /* Internal routine to insert a new item into the table. Used both by the internal resize routine and by the public insert routine. Eats a reference to key and one to value. Returns -1 if an error occurred, or 0 on success. */ static int insertdict(JsDictObject *mp, JsObject *key, uhash hash, JsObject *value) { register JsDictEntry *ep; JsObject* old_value; assert(mp->ma_lookup != NULL); ep = mp->ma_lookup(mp, key, hash); if (ep == NULL) { // never reach Js_DECREF(key); Js_DECREF(value); return -1; } if (ep->me_value != NULL) { old_value = ep->me_value; ep->me_value = value; Js_DECREF(old_value); Js_DECREF(key); } else { if (ep->me_key == NULL) // unused state mp->ma_fill++; else { // dummy state assert(ep->me_key == dummy); Js_DECREF(dummy); } ep->me_key = key; ep->me_hash = hash; ep->me_value = value; mp->ma_used++; } return 0; } /* Internal routine used by dictresize() to insert an item which is known to be absent from the dict. This routine also assumes that the dict contains no deleted entries. */ static void insertdict_clean(register JsDictObject *mp, JsObject *key, uhash hash, JsObject *value) { register size_t i; register size_t perturb; register size_t mask = (size_t)mp->ma_mask; JsDictEntry *ep0 = mp->ma_table; register JsDictEntry *ep; i = hash & mask; ep = &ep0[i]; for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) { i = (i << 2) + i + perturb + 1; ep = &ep0[i & mask]; } assert(ep->me_value == NULL); mp->ma_fill++; ep->me_key = key; ep->me_hash = hash; ep->me_value = value; mp->ma_used++; } static int dictresize(JsDictObject *mp, ssize_t minused) { ssize_t newsize; JsDictEntry *oldtable, *newtable, *ep; ssize_t i; int is_oldtable_malloced; JsDictEntry small_copy[JsDict_MINSIZE]; assert(minused >= 0); /* Find the smallest table size > minused. */ for (newsize = JsDict_MINSIZE; newsize <= minused && newsize > 0; newsize <<= 1) ; if (newsize <= 0) { dbgprint("dict resize error"); return -1; } /* Get space for a new table. */ oldtable = mp->ma_table; assert(oldtable != NULL); is_oldtable_malloced = oldtable != mp->ma_smalltable; if (newsize == JsDict_MINSIZE) { /* A large table is shrinking, or we can't get any smaller. */ newtable = mp->ma_smalltable; if (newtable == oldtable) { if (mp->ma_fill == mp->ma_used) { /* No dummies, so no point doing anything. */ return 0; } /* We're not going to resize it, but rebuild the table anyway to purge old dummy entries. Subtle: This is *necessary* if fill==size, as lookdict needs at least one virgin slot to terminate failing searches. If fill < size, it's merely desirable, as dummies slow searches. */ assert(mp->ma_fill > mp->ma_used); memcpy(small_copy, oldtable, sizeof(small_copy)); oldtable = small_copy; } } else { newtable = Js_Malloc(sizeof(JsDictEntry) * newsize); } /* Make the dict empty, using the new table. */ assert(newtable != oldtable); mp->ma_table = newtable; mp->ma_mask = newsize - 1; memset(newtable, 0, sizeof(JsDictEntry) * newsize); mp->ma_used = 0; i = mp->ma_fill; mp->ma_fill = 0; /* Copy the data over; this is refcount-neutral for active entries; dummy entries aren't copied over, of course */ for (ep = oldtable; i > 0; ep++) { if (ep->me_value != NULL) { /* active entry */ --i; insertdict_clean(mp, ep->me_key, (long)ep->me_hash, ep->me_value); } else if (ep->me_key != NULL) { /* dummy entry */ --i; assert(ep->me_key == dummy); Js_DECREF(ep->me_key); } /* else key == value == NULL: nothing to do */ } if (is_oldtable_malloced) Js_Free(oldtable); return 0; } JsObject * JsDict_GetItem(JsObject *op, JsObject *key) { uhash hash; JsDictObject *mp = (JsDictObject *)op; JsDictEntry *ep; if (!JsString_CheckType(key) || (hash = ((JsStringObject *) key)->ob_shash) == 0) { hash = JsObject_Hash(key); //// nullstring // if (hash == 0) { // return NULL; // } } ep = (mp->ma_lookup)(mp, key, hash); if (ep == NULL) { // never reach assert(0); return NULL; } return ep->me_value; } static int dict_set_item_by_hash(JsObject *op, JsObject *key, uhash hash, JsObject *value) { register JsDictObject *mp; register ssize_t n_used; mp = (JsDictObject *)op; assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */ n_used = mp->ma_used; Js_INCREF(value); Js_INCREF(key); if (insertdict(mp, key, hash, value) != 0) return -1; /* If we added a key, we can safely resize. Otherwise just return! * If fill >= 2/3 size, adjust size. Normally, this doubles or * quaduples the size, but it's also possible for the dict to shrink * (if ma_fill is much larger than ma_used, meaning a lot of dict * keys have been * deleted). * * Quadrupling the size improves average dictionary sparseness * (reducing collisions) at the cost of some memory and iteration * speed (which loops over every possible entry). It also halves * the number of expensive resize operations in a growing dictionary. * * Very large dictionaries (over 50K items) use doubling instead. * This may help applications with severe memory constraints. */ if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2)) return 0; return dictresize(mp, (mp->ma_used > 50000 ? 2 : 4) * mp->ma_used); } /* CAUTION: JsDict_SetItem() must guarantee that it won't resize the * dictionary if it's merely replacing the value for an existing key. */ int JsDict_SetItem(JsObject *op, JsObject *key, JsObject *value) { uhash hash; if (!JsDict_CheckType(op)) { return -1; } assert(key); assert(value); if (JsString_CheckType(key)) { hash = ((JsStringObject *)key)->ob_shash; if (hash == 0) hash = JsObject_Hash(key); } else { // never reach hash = JsObject_Hash(key); } return dict_set_item_by_hash(op, key, hash, value); } int JsDict_DelItem(JsObject *op, JsObject *key) { register JsDictObject *mp; register uhash hash; register JsDictEntry *ep; JsObject *old_value, *old_key; if (!JsDict_CheckType(op)) { return -1; } assert(key); if (!JsString_CheckType(key) || (hash = ((JsStringObject *) key)->ob_shash) == 0) { hash = JsObject_Hash(key); } mp = (JsDictObject *)op; ep = (mp->ma_lookup)(mp, key, hash); if (ep == NULL) return -1; if (ep->me_value == NULL) { return -1; } old_key = ep->me_key; Js_INCREF(dummy); ep->me_key = dummy; old_value = ep->me_value; ep->me_value = NULL; mp->ma_used--; Js_DECREF(old_value); Js_DECREF(old_key); return 0; } void JsDict_Clear(JsObject *op) { JsDictObject *mp; JsDictEntry *ep, *table; int table_is_malloced; ssize_t fill; JsDictEntry small_copy[JsDict_MINSIZE]; if (!JsDict_CheckType(op)) return; mp = (JsDictObject *)op; table = mp->ma_table; assert(table != NULL); table_is_malloced = table != mp->ma_smalltable; /* This is delicate. During the process of clearing the dict, * decrefs can cause the dict to mutate. To avoid fatal confusion * (voice of experience), we have to make the dict empty before * clearing the slots, and never refer to anything via mp->xxx while * clearing. */ fill = mp->ma_fill; if (table_is_malloced) EMPTY_TO_MINSIZE(mp); else if (fill > 0) { /* It's a small table with something that needs to be cleared. * Afraid the only safe way is to copy the dict entries into * another small table first. */ memcpy(small_copy, table, sizeof(small_copy)); table = small_copy; EMPTY_TO_MINSIZE(mp); } /* else it's a small table that's already empty */ /* Now we can finally clear things. If C had refcounts, we could * assert that the refcount on table is 1 now, i.e. that this function * has unique access to it, so decref side-effects can't alter it. */ for (ep = table; fill > 0; ++ep) { if (ep->me_key) { --fill; Js_DECREF(ep->me_key); Js_XDECREF(ep->me_value); } } if (table_is_malloced) Js_Free(table); } static JsObject* dict_new(JsTypeObject *type, JsObject *args) { return JsDict_New(); } static void dict_dealloc(JsDictObject* mp) { register JsDictEntry *ep; ssize_t fill = mp->ma_fill; for (ep = mp->ma_table; fill > 0; ep++) { if (ep->me_key) { --fill; Js_DECREF(ep->me_key); Js_XDECREF(ep->me_value); } } if (mp->ma_table != mp->ma_smalltable) { Js_Free(mp->ma_table); } if (numfree < JsDict_MAXFREELIST && Js_Type(mp) == &JsDict_Type) free_list[numfree++] = mp; else Js_Free(mp); } static int dict_print(JsDictObject *v, FILE *fp) { ssize_t i, rec_count = v->ma_used; JsDictEntry* entryPtr = v->ma_table; fputc('{', fp); for (i = 0; i < rec_count; ++i) { while (entryPtr->me_value == NULL) entryPtr++; _Js_PRINTFP(entryPtr->me_key, fp); fputc(':', fp); _Js_PRINTFP(entryPtr->me_value, fp); entryPtr++; if (i != rec_count-1) fputc(',', fp); } fputc('}', fp); return 0; } static JsObject * dict_tostring(JsDictObject *v) { JsObject *string = JsString_FromString("[Object]"); return string; } JsTypeObject JsDict_Type = { JsObject_HEAD_INIT(&JsType_Type) "object", // in Javascript, it's object instead of dict sizeof(JsDictObject), 0, JS_TPFLAGS_DEFAULT, // not a basetype (newfunc)dict_new, /* tp_new, also generate by api.*/ (destructor)dict_dealloc, /* tp_dealloc */ (printfunc)dict_print, /* tp_print */ (tostringfunc)dict_tostring, /* tp_tostr */ NULL, /* tp_compare */ (hashfunc)_Js_HashPointer, /* tp_hash, use the common version */ }; int _JsDict_Init(void) { return 0; } void _JsDict_Deinit(void) { JsDictObject *op; while (numfree) { op = free_list[--numfree]; Js_Free(op); } if (dummy != NULL) { _Js_Dealloc(dummy); } }
C
// wait example, explained in depth #include <unistd.h> #include <wait.h> // contains macros for testing information returned by wait #include <stdio.h> #include <stdlib.h> void run_child_code(); void run_parent_code(); int main() { int fork_rv; printf("Before fork: I am %d\n", getpid() ); // let's fork: fork_rv = fork(); if ( fork_rv == 0 ) run_child_code(); else run_parent_code(); return 0; } void run_child_code() { printf( "I am the child %d - going to sleep now.\n", getpid() ); sleep(30); exit(17); } void run_parent_code() { int wait_exit_value; int wait_rv; printf("This is parent %d, going to wait for child.\n\n\n", getpid() ); // wait returns -1 if error, or pid of the terminating process. // -1 if there are no processes to wait for. // if the argument is not NULL, then wait copies into the argument pointed // to the exit status or signal number. // values can be examined using macros in wait.h wait_rv = wait( &wait_exit_value ); printf("Parent %d done waiting. Child died. It returned %d\n\n\n", getpid(), wait_exit_value ); // for more macros: man wait printf("%d has special meaning. There are many macros", wait_exit_value ); printf("defined in wait.h to help us translate.\n\n\n"); printf("%d in base 10: %d\n\n\n", wait_exit_value, wait_exit_value >> 8 ); printf( "WIFEXITED: %d\n", WIFEXITED( wait_exit_value ) ); printf( "WEXITSTATUS: %d\n", WEXITSTATUS( wait_exit_value ) ); printf( "WTERMSIG: %d\n", WTERMSIG( wait_exit_value ) ); printf( "WCOREDUMP: %d\n", WCOREDUMP( wait_exit_value ) ); }
C
#include <stdio.h> #include <float.h> /************************************************************************/ /* practice 1 */ /************************************************************************/ void p4_1(void) { char first_name[40]; char last_name[40]; printf("What's your first name:"); scanf_s("%s", first_name); printf("What's your last name:"); scanf_s("%s", last_name); getchar(); printf("%*s,%*s\n", first_name, last_name); return; } /************************************************************************/ /* practice 2 */ /************************************************************************/ void p4_2(void) { char first_name[40]; char last_name[40]; int first_name_length = 0; int last_name_lenght = 0; printf("What's your first name:"); scanf_s("%s", first_name); printf("What's your last name:"); scanf_s("%s", last_name); getchar(); first_name_length = strlen(first_name); last_name_lenght = strlen(last_name); printf("a.\"%s,%s\"\n", first_name, last_name); printf("b.\"%20s,%20s\"\n", first_name, last_name); printf("c.\"%-20s,%-20s\"\n", first_name, last_name); printf("d.%*s,%*s\n", first_name_length+3, first_name, last_name_lenght+3, last_name); return; } /************************************************************************/ /* practice 3 */ /************************************************************************/ void p4_3(void) { double input = 0.0; printf("please input the float number:"); scanf_s("%lf", &input); getchar(); printf("%lf\n", input); printf("%e\n", input); } /************************************************************************/ /* practice 4 */ /************************************************************************/ #define CM_PER_INCH (2.54) void p4_4(void) { float height_inch = 0; float height_cm = 0; printf("What's your height:"); scanf_s("%f", &height_inch); getchar(); printf("Dabney, you are %f feet tall\n", height_inch); height_cm = height_inch * CM_PER_INCH; printf("Dabney, you are %f cm tall\n", height_cm); } /************************************************************************/ /* practice 5 */ /************************************************************************/ void p4_5(void) { float network_speed = 0; float file_size = 0; float download_time = 0; printf("How much your network speed:"); scanf_s("%f", &network_speed); getchar(); printf("How much is your download file:"); scanf_s("%f", &file_size); getchar(); download_time = file_size / (network_speed / 8); printf("At %f megabits per secnod, a file of %f magebytes\n download in %f seconds.\n", network_speed, file_size, download_time); } /************************************************************************/ /* practice 6 */ /************************************************************************/ void p4_6(void) { char first_name[40] = { 0 }; char last_name[40] = { 0 }; int first_name_length = 0; int last_name_length = 0; printf("What's your first name:"); scanf_s("%s", first_name); getchar(); printf("What's your last name:"); scanf_s("%s", last_name); getchar(); first_name_length = strlen(first_name); last_name_length = strlen(last_name); printf("%s %s\n", first_name, last_name); printf("%*d %*d\n", first_name_length, first_name_length, last_name_length, last_name_length); printf("%s %s\n", first_name, last_name); printf("%-*d %-*d\n", first_name_length, first_name_length, last_name_length, last_name_length); } /************************************************************************/ /* practice 7 */ /************************************************************************/ void p4_7(void) { double d_value = 1.0 / 3.0; float f_value = 1.0 / 3.0; printf("the value of FLT_DIG:%d, the value of DBL_DIG:%d\n", FLT_DIG, DBL_DIG); printf("the value of double:%.6lf, the value of float:%.6lf\n", d_value, f_value); printf("the value of double:%.12lf, the value of float:%.12lf\n", d_value, f_value); printf("the value of double:%.18lf, the value of float:%.18lf\n", d_value, f_value); } /************************************************************************/ /* practice 8 */ /************************************************************************/ #define KM_PER_MILE (1.609) #define PINT_PER_GALLON (3.785) void p4_8(void) { float driven_distance = 0.0; float gas_consumption = 0.0; float pint_per_hundred_km = 0.0; float mile_per_gallon = 0.0; printf("How much distance have you traveled in kilometer:"); scanf_s("%f", &driven_distance); getchar(); printf("How much gas have you used in pint:"); scanf_s("%f", &gas_consumption); getchar(); pint_per_hundred_km = gas_consumption / driven_distance * 100; mile_per_gallon = (driven_distance / KM_PER_MILE) / (gas_consumption / PINT_PER_GALLON); printf("Fuel consumptions:%f pint/100km or %f mile/gallon\n", pint_per_hundred_km, mile_per_gallon); } int main(int argc, char **argv) { p4_8(); getchar(); }
C
#include "lists.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /** *get_nodeint_at_index - return the pointer to the number node of index say *@head: the head of the node *@index: the number of the node to return *Return: the pointer to the node */ listint_t *get_nodeint_at_index(listint_t *head, unsigned int index) { unsigned int i = 0; while (head != NULL && i < index) { head = head->next; i++; } if (head == NULL && i < index) return (NULL); return (head); }
C
/* * index: associative dictionary * * (c) 1999-2011 IOhannes m zmölnig, forum::für::umläute, institute of electronic music and acoustics (iem) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* (c) 2005:forum::für::umläute:2000 "index" simulates an associative index :: that is : convert a symbol to an index CAVEATS: starts to count at "1" TODO: use "symbol" instead of "char*" : FIXED TODO: "dump" the contents (so we can share between [index]es, ...) FIXED TODO: "compact": move all entries to the beginning of the array FIXED TODO: "sort" FIXED TODO: "add" at a specific position (like "add 10 hallo" of "add hallo 10") (??) FIXED TODO: "delete" from a specific position (like "delete 4" deletes the 4th element) FIXED TODO: get the number of stored entries ("bang") FIXED TODO: resize the array if it gets to small */ #include "zexy.h" #include <string.h> /* ----------------------- index --------------------- */ static t_class *index_class; typedef struct _index { t_object x_obj; int entries, maxentries; int auto_mode; /* 1--add if key doesn't already exist; 0--do not add; */ int auto_resize; /* 1--resize the array if we are running out of slots; 0--don't */ t_symbol **names; } t_index; /************************************ * index_helpers */ /* find the last non-NULL entry in the array * * LATER: shouldn't this return "-1" on failure ? */ static int find_last(t_symbol **names, int maxentries) { /* returns the index of the last entry (0..(maxentries-1)) */ while (maxentries--) if (names[maxentries]) { return maxentries; } return 0; } /* search the array for "key" * if it is not there, return "-1" */ static int find_item(const t_symbol *key, t_symbol **names, int maxentries) { /* returns index (0..[maxentries-1?]) on success; -1 if the item could not be found */ int i=-1; int max = find_last(names, maxentries); while (++i<=max) if (names[i] && key==names[i]) { return i; } return -1; } /* find the first NULL entry in the array * return "-1" if none can be found */ static int find_free(t_symbol **names, int maxentries) { int i=0; while (i<maxentries) { if (!names[i]) { return i; } i++; } return -1; } /************************************ * methods */ static void index_add(t_index *x, t_symbol *s, t_float f); /* look up a symbol in the map */ static void index_symbol(t_index *x, t_symbol *s) { int element; if ( (element = find_item(s, x->names, x->maxentries)+1) ) { outlet_float(x->x_obj.ob_outlet, (t_float)element); } else if (x->auto_mode) { /* not yet stored: add automatically */ index_add(x, s, 0); } else { outlet_float(x->x_obj.ob_outlet, 0.f); /* not yet stored but do not add */ } } /* output the entry at a given index */ static void index_float(t_index *x, t_float findex) { int iindex = (int)findex; if ((iindex > 0) && (iindex <= x->maxentries) && (x->names[iindex-1])) { /* TB: output symbol to outlet */ outlet_symbol (x->x_obj.ob_outlet,x->names[iindex-1]); } } /* add a symbol to the map (if possible) */ static void index_add(t_index *x, t_symbol *s, t_float f) { int newentry=(int)f; if (! (find_item(s, x->names, x->maxentries)+1) ) { if (x->auto_resize && (x->entries==x->maxentries || newentry>=x->maxentries)) { /* do some resizing */ int maxentries=(newentry>x->maxentries)?newentry:(x->maxentries*2); int i; t_symbol**buf=(t_symbol **)getbytes(sizeof(t_symbol *) * maxentries); if(buf!=0) { memcpy(buf, x->names, sizeof(t_symbol *) * x->maxentries); for(i=x->maxentries; i<maxentries; i++) { buf[i]=0; } freebytes(x->names, sizeof(t_symbol *) * x->maxentries); x->names=buf; x->maxentries=maxentries; } } if ( x->entries < x->maxentries ) { if(newentry>0) { newentry--; if(x->names[newentry]) { /* it is already taken! */ z_verbose(1, "index :: couldn't add element '%s' at position %d (already taken)", s->s_name, newentry+1); outlet_float(x->x_obj.ob_outlet, -1.f); return; } } else { newentry=find_free(x->names, x->maxentries); } if (newentry + 1) { x->entries++; x->names[newentry]=s; outlet_float(x->x_obj.ob_outlet, (t_float)newentry+1); return; } else { error("index :: couldn't find any place for new entry"); } } else { error("index :: max number of elements (%d) reached !", x->maxentries); } } else { z_verbose(1, "index :: element '%s' already exists", s->s_name); } /* couldn't add the symbol to our index table */ outlet_float(x->x_obj.ob_outlet, -1.f); } /* delete a symbol from the map (if it is in there) */ static void index_delete(t_index *x, t_symbol* UNUSED(s), int argc, t_atom*argv) { int idx=-1; if(argc!=1) { error("index :: delete what ?"); return; } else { if(argv->a_type==A_FLOAT) { idx=atom_getint(argv)-1; } else if (argv->a_type==A_SYMBOL) { idx=find_item(atom_getsymbol(argv),x->names, x->maxentries); } else { error("index :: delete what ?"); return; } } if ( idx >= 0 && idx < x->maxentries) { x->names[idx]=0; x->entries--; outlet_float(x->x_obj.ob_outlet, 0.0); } else { z_verbose(1, "index :: couldn't find element"); outlet_float(x->x_obj.ob_outlet, -1.0); } } /* delete all symbols from the map */ static void index_reset(t_index *x) { int i=x->maxentries; while (i--) if (x->names[i]) { x->names[i]=0; } x->entries=0; outlet_float(x->x_obj.ob_outlet, 0.f); } /* output the number of entries stored in the array */ static void index_bang(t_index *x) { outlet_float(x->x_obj.ob_outlet, (t_float)x->entries); } /* dump each entry in the format: "list <symbol> <index>" */ static void index_dump(t_index *x) { t_atom ap[2]; int i=0; for(i=0; i<x->maxentries; i++) { if(x->names[i]) { SETSYMBOL(ap, x->names[i]); SETFLOAT(ap+1, i+1); outlet_list(x->x_obj.ob_outlet, 0, 2, ap); } } } /* compact all entries, removing all holes in the map */ static void index_compact(t_index *x) { int i,j; for(i=0; i<x->entries; i++) { if(!x->names[i]) { for(j=i+1; j<x->maxentries; j++) { if(x->names[j]) { x->names[i]=x->names[j]; x->names[j]=0; break; } } } } } /* sort the map alphabetically */ static void index_sort(t_index *x) { int entries=x->entries; int step=entries; int loops=1, n; t_symbol**buf=x->names; index_compact( x); /* couldn't we do it more "in-place", e.g. don't touch empty slots ? */ while(step>1) { int i = loops; step+=step%2; step>>=1; loops+=2; while(i--) { /* there might be some optimization in here */ for (n=0; n<(x->entries-step); n++) { int comp=strcmp(buf[n]->s_name,buf[n+step]->s_name); if (comp>0) { /* compare STRINGS not SYMBOLS */ t_symbol*s_tmp = buf[n]; buf[n] = buf[n+step]; buf[n+step] = s_tmp; } } } } } /* turn on/off auto-adding of elements that are not yet in the map */ static void index_auto(t_index *x, t_float automod) { x->auto_mode = !(!automod); } /* turn on/off auto-resizing of the map if it gets to small */ static void index_resize(t_index *x, t_float automod) { x->auto_resize = !(!automod); } static void *index_new(t_symbol* UNUSED(s), int argc, t_atom *argv) { t_index *x = (t_index *)pd_new(index_class); t_symbol** buf; int maxentries = 0, automod=0; if (argc--) { maxentries = (int)atom_getfloat(argv++); if (argc) { automod = (int)atom_getfloat(argv++); } } if (maxentries<1) { maxentries=128; } buf = (t_symbol **)getbytes(sizeof(t_symbol *) * maxentries); x->entries = 0; x->maxentries = maxentries; x->names = buf; x->auto_mode = !(!automod); x->auto_resize = 1; while (maxentries--) { buf[maxentries]=0; } outlet_new(&x->x_obj, gensym("float")); return (x); } static void index_free(t_index *x) { freebytes(x->names, sizeof(t_symbol *) * x->maxentries); } static void index_helper(t_index *x) { endpost(); post(""HEARTSYMBOL" index :: index symbols to indices"); post("<symbol> : look up the <symbol> in the index and return it's index"); post("<int> : look up the element at index <int> in the index"); post("'add <symbol>' : add a new symbol to the index-map"); post("'add <symbol> <int>' : add a new symbol at the index <int>"); post("'delete <symbol>' : delete a symbol from the index-map"); post("'delete <int>' : delete the entry at index <int> from the index-map"); post("'reset' : delete the whole index-map"); post("'bang' : return the number of entries in the index-map"); post("'dump' : dump each entry in the format \"list <symbol> <index>\""); post("'compact' : remove holes in the index-map"); endpost(); post("'sort' : alphabetically sort the entries"); post("'auto <1/0> : if auto is 1 and a yet unknown symbol is looked up it is\n\t\t\t automatically added to the index-map"); post("'resize <1/0> : if resize is 1 (default), the index-map is resized\n\t\t\t automatically if needed"); post("'help' : view this"); post("outlet : <n> : index of the <symbol>"); post(" <symbol> : entry at <index>"); endpost(); post("creation:\"index [<maxelements> [<auto>]]\": creates a <maxelements> sized index"); } void index_setup(void) { index_class = class_new(gensym("index"), (t_newmethod)index_new, (t_method)index_free, sizeof(t_index), 0, A_GIMME, 0); class_addsymbol(index_class, index_symbol); class_addmethod(index_class, (t_method)index_reset, gensym("reset"), 0); class_addmethod(index_class, (t_method)index_delete, gensym("delete"), A_GIMME, 0); /* class_addmethod(index_class, (t_method)index_add, gensym("add"), A_SYMBOL, 0); */ class_addmethod(index_class, (t_method)index_add, gensym("add"), A_SYMBOL, A_DEFFLOAT, 0); class_addmethod(index_class, (t_method)index_auto, gensym("auto"), A_FLOAT, 0); class_addmethod(index_class, (t_method)index_resize, gensym("resize"), A_FLOAT, 0); class_addfloat(index_class, (t_method)index_float); class_addbang(index_class, (t_method)index_bang); class_addmethod(index_class, (t_method)index_sort, gensym("sort"), 0); class_addmethod(index_class, (t_method)index_compact, gensym("compact"), 0); class_addmethod(index_class, (t_method)index_dump, gensym("dump"), 0); class_addmethod(index_class, (t_method)index_helper, gensym("help"), 0); zexy_register("index"); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #define Gmax 5000 #define error 0.000001 //le ponemos 4 ceros y genera mas rapido #define ranf() ((double)rand()/(1.0+(double)RAND_MAX)) //intervalo uniforme de [0,1) typedef struct dat { double x; double sigma; } x_delt; double *vector(double *,int); double evaluarF(x_delt*); int restriccion(double *); double genGausse(double, double); int buscarMpad(double *,int); void aleatorios(int *, int); void print(x_delt **,double *,int, int); void printMS(x_delt **,double *,int, int); double genGauss(double media, double desE) { double x1,x2,w,y1; static double y2; static int utiliza_ult=0; if(utiliza_ult) { y1=y2; utiliza_ult =0; } else { do{ x1 = 2.0 * ranf() - 1.0; x2 = 2.0 * ranf() - 1.0; w = x1 * x1 + x2 * x2; } while ( w >= 1.0 ); w = sqrt( (-2.0 * log( w ) ) / w ); y1 = x1 * w; y2 = x2 * w; utiliza_ult =1; } return (media + y1 * desE); } double *vector(double *dato,int tam) { dato = (double*)malloc(tam*sizeof(double)); } double evaluarF(x_delt *x) { int i,j,k=500; double res=0.0; int a[2][25]={{-32,-16,0,16,32,-32,-16,0,16,32,-32,-16,0,16,32,-32,-16,0,16,32,-32,-16,0,16,32},{-32,-32,-32,-32,-32,-16,-16,-16,-16,-16,0,0,0,0,0,16,16,16,16,16,32,32,32,32,32}}; //return (-0.75/(1+pow(x[0].x,2))) - (0.65*x[0].x*atan(1/x[0].x))+0.65; //return ((-4*pow(x[0].x,2)) -20*x[0].x -100) + pow(1-x[0].x,4); //return 3*pow(x[0].x,4)+pow(x[0].x,2)-2*x[0].x+1; //return 10+(pow(x[0].x,3))-(2*x[0].x)+(5*exp(x[0].x)); //no tiene minimo //return pow(x[0].x,2) -(10*exp(0.1*x[0].x)); //return pow((10*pow(x[0].x,3)+3*pow(x[0].x,2)+5),2); //return (0.5/sqrt(1+pow(x[0].x,2))) -(sqrt(1+pow(x[0].x,2)))*(1-(0.5/(1+pow(x[0].x,2))))+x[0].x; //no tiene minimo //return exp(x[0].x) -(pow(x[0].x,3)); //return pow((pow(x[0].x,2)-1),3) - (pow((2*x[0].x-5),4)); //return (-4*pow(x[0].x,2)-20*x[0].x-100)+pow((1-x[0].x),4); //return (pow(x[0].x,2)+pow((x[1].x+1),2))*(pow(x[0].x,2)+pow((x[1].x-1),2)); //return pow(pow(x[0].x,2)-x[1].x,2)+pow(x[1].x,2); //return 50*pow((x[1].x-pow(x[0].x,2)),2)+pow((2-x[0].x),2); //return pow((x[0].x + 2*x[1].x -7),2) + pow((2*x[0].x+x[1].x -5),2); //return pow((1.5-x[0].x*(1-x[1].x)),2)+pow((2.25-x[0].x*(1-pow(x[1].x,2))),2)+ pow((2.625-x[0].x*(1-pow(x[1].x,3))),2); //return pow((10*(x[1].x-pow(x[0].x,2))),2) +pow((1-x[0].x),2)+ 90*pow((x[3].x-pow(x[2].x,2)),2)+pow((1-x[2].x),2)+10*pow((x[1].x+x[3].x-2),2)+0.1*(x[1].x-x[3].x); //return (4-2.1*pow(x[0].x,2)+(pow(x[0].x,4)/3))*pow(x[0].x,2)+(x[0].x*x[1].x)+(-4+(4*pow(x[1].x,2)))*pow(x[1].x,2); //return pow((x[0].x+10*x[1].x),2)+(5*pow((x[2].x-x[3].x),2))+pow((x[1].x-2*x[2].x),4)+(10*pow((x[0].x-x[3].x),4));//no tiene minimo /*for(i=0;i<3;i++) { res+=pow(x[i].x,2); } return res;*/ //return 100*(pow((pow(x[0].x,2)-x[1].x),2))+pow((1-x[0].x),2); /*for(i=0;i<5;i++) { res+= floor(x[i].x); } return res;*/ /*for(i=0;i<30;i++) { res+= (i+1)*pow(x[i].x,4); } return res+genGauss(0,1);*/ for(j =0;j<25;j++) { double var; /*aleatorio(-65.536,65.536)*/ for(i=0;i<2;i++) { var +=pow((x[i].x-a[i][j]),6); } res+=1/((j+1)+var); } return 1/((1/k)+res); //return x[0]*x[0]+1000; } int buscarMpad(double *evaluciones,int mu) { double var=0.0; int opt=0,k; var=evaluciones[0]; for(k=0;k<mu;k++) { if (var>evaluciones[k]) { var=evaluciones[k]; opt=k; } } //printf("\nmejor solucion---- %d \n",(opt+1)); return opt; } void printMS(x_delt **matr_Pad,double *evaluciones,int optimo, int tam_v) { int y; printf("\nMejor resultado --- "); for (y=0;y<tam_v;y++) { printf("%f ",matr_Pad[optimo][y].x); } printf(" f(x)=%f\n",evaluciones[optimo]); } void aleatorios(int *num_ale,int mu) { int x,num_1,num_2; do { num_1 = rand()%(mu); num_2 = rand()%(mu); if (num_1 ==num_2) { x=1; } else { x=0; } } while(x==1); num_ale[0]=num_1; num_ale[1]=num_2; } void print(x_delt **matr_Pad,double *evaluciones,int n_d, int tam_v) { int x,y; for (x=0;x<n_d;x++) { for (y=0;y<tam_v;y++) { printf("%d %f ",(x+1),matr_Pad[x][y].x); } printf(" f(x)=%f\n",evaluciones[x]); } } int main() { double **sigma=NULL, *padre=NULL, padreFunc, hijoFunc,num,aprox,*evaluciones=NULL,*eval_H=NULL; double **uv; int t, num_var,i,x,ps,mu,landa,mejorS; t =0; ps =0; num_var =2; srand(time(NULL)); aprox =1; mu= 20; landa =30; //sigma = (double **) malloc (landa*sizeof(double*)); //explorar mas el espacio de busqueda reproduccion //hijos=(double **) malloc (landa*sizeof(double*)); //formando el conjunto de evaluciones evaluciones= vector(evaluciones,mu); eval_H = vector(eval_H,landa); //matr_Pad=(double **) malloc (mu*sizeof(double*)); x_delt **matr_Pad, **hijos; matr_Pad = (x_delt **) malloc (mu*sizeof(x_delt*)); hijos = (x_delt **) malloc (landa*sizeof(x_delt*)); //inicilaizar padre for (x=0;x<mu;x++) { int y; double datosP; matr_Pad[x] = (x_delt*)malloc(num_var*sizeof(x_delt)); for(y=0;y<num_var;y++) { datosP=genGauss(0.0,1.0); matr_Pad[x][y].x = datosP; //se evalua la funcion //se puede poner 10 y tarda mas matr_Pad[x][y].sigma = 0.0; } evaluciones[x]=evaluarF(matr_Pad[x]); } mejorS =buscarMpad(evaluciones,mu); //printf("\nMejor resultado --- %f f(x)=%f\n",matr_Pad[mejorS][0].x,evaluciones[mejorS]); printf("\nMejor resultado --- %f %f f(x)=%f\n",matr_Pad[mejorS][0].x,matr_Pad[mejorS][1].x,evaluciones[mejorS]); while((t<Gmax) && (aprox>error)) { int y,num_ale[2],s,m,nu; double M_hijo=0,var=0.0,tau,tau_p; printf("\n--- Iteracion Numero %d ---\n",t+1); //print(matr_Pad,evaluciones,mu,num_var); printf("\n"); nu =genGauss(0.0,1.0); tau=(1/(4.0*pow(num_var,0.25))); tau_p=(1/(pow(2.0*(num_var),0.5))); for(s=0;s<landa;s++) { /*se esscogen 2 sol aleatorias que no se repiten, LA MU SE PUEDE PONER EN 10 y trabaja mejor*/ aleatorios(num_ale,mu-5); //printf("--%d --%d\n",num_ale[0],num_ale[1]); hijos[s] = (x_delt*)malloc(num_var*sizeof(x_delt)); for(i=0;i<num_var;i++) { double h,d; num=genGauss(0.0,1.0);//semilla de aleatorios //aplicando recombinacion plana h = ((num*matr_Pad[num_ale[0]][i].x)+((1-num)*matr_Pad[num_ale[1]][i].x)); d =((matr_Pad[num_ale[0]][i].sigma+matr_Pad[num_ale[1]][i].sigma)/2)*0.0817; //h = (matr_Pad[num_ale[0]][i]+matr_Pad[num_ale[1]][i])/2; //printf("//%f",h); //aplicando mutacion hijos[s][i].sigma=d*(exp((tau*num)+(tau_p*nu))); //printf("********** %f\n",sigma[s][i]); num =genGauss(0.0,pow(d,2)); h=h+hijos[s][i].sigma*num; //printf(" -- %f \n",h); hijos[s][i].x=h; } eval_H[s]=evaluarF(hijos[s]); //printf("%f\n",evaluarF(hijos[s])); } //print(hijos,eval_H,landa,num_var); m=mejorS; mejorS =buscarMpad(eval_H,landa); //printf("\nMejor resultado --- %f f(x)=%f\n",hijos[mejorS][0].x,eval_H[mejorS]); //printf("\nMejor resultado --- %f %f f(x)=%f\n",hijos[mejorS][0].x,hijos[mejorS][1].x,evaluciones[mejorS]); //printf("\nMejor resultado --- %f %f %f f(x)=%f\n",hijos[mejorS][0].x,hijos[mejorS][1].x,hijos[mejorS][2].x,evaluciones[mejorS]); //printf("\nMejor resultado --- %f %f %f %f f(x)=%f\n",hijos[mejorS][0].x,hijos[mejorS][1].x,hijos[mejorS][2].x,hijos[mejorS][3].x,evaluciones[mejorS]); //printf("\nMejor resultado --- %f %f %f %f %f f(x)=%f\n",hijos[mejorS][0].x,hijos[mejorS][1].x,hijos[mejorS][2].x,hijos[mejorS][3].x,hijos[mejorS][4].x,evaluciones[mejorS]); printMS(hijos,evaluciones,mejorS,num_var); aprox=fabs(evaluciones[m]-eval_H[mejorS]); printf("Error: %f \n",aprox); //ordenamiento por seleccion for(x=0;x<landa;x++) { int y,min,z; double aux; min =x; for(y=(x+1);y<landa;y++) { if (eval_H[y]<eval_H[min]) min=y; } aux = eval_H[x]; eval_H[x] =eval_H[min]; eval_H[min] =aux; for(z=0;z<num_var;z++) { double v_a=hijos[x][z].x; double del=hijos[x][z].sigma; hijos[x][z].x=hijos[min][z].x; hijos[min][z].x=v_a; hijos[x][z].sigma=hijos[min][z].sigma; hijos[min][z].sigma=del; } } //print(matr_Pad,evaluciones,mu,num_var); //sustituyecdo a los padres for (x=0;x<mu;x++) { int y; for(y=0;y<num_var;y++) { matr_Pad[x][y].x = hijos[x][y].x; matr_Pad[x][y].sigma = hijos[x][y].sigma; } evaluciones[x] = eval_H[x]; } t++; } return 0; }
C
#include <sys/types.h> #include <pthread.h> #include <stdlib.h> #include <stdbool.h> #include "buffers.h" typedef struct link_list { job_t *value; struct link_list *next; } link_list_t; link_list_t *scissors_head = NULL; pthread_mutex_t scissors_mutex; link_list_t *drill_head = NULL; pthread_mutex_t drill_mutex; link_list_t *bending_machine_head = NULL; pthread_mutex_t bending_machine_mutex; link_list_t *welder_head = NULL; pthread_mutex_t welder_mutex; link_list_t *painter_head = NULL; pthread_mutex_t painter_mutex; link_list_t *screwdriver_head = NULL; pthread_mutex_t screwdriver_mutex; link_list_t *milling_cutter_head = NULL; pthread_mutex_t milling_cutter_mutex; _Bool contains_job_in_stage(workplace_type workplace_type) { switch (workplace_type) { case SCISSORS: return scissors_head != NULL; case DRILL: return drill_head != NULL; case BENDING_MACHINE: return bending_machine_head != NULL; case WELDER: return welder_head != NULL; case PAINTER: return painter_head != NULL; case SCREWDRIVER: return screwdriver_head != NULL; case MILLING_CUTTER: return milling_cutter_head != NULL; default: return false; } } void free_one_buffer(link_list_t *head) { while (head != NULL) { link_list_t *to_free = head; free(to_free->value); head = head->next; free(to_free); } } void free_buffers() { free_one_buffer(scissors_head); free_one_buffer(drill_head); free_one_buffer(bending_machine_head); free_one_buffer(welder_head); free_one_buffer(painter_head); free_one_buffer(screwdriver_head); free_one_buffer(milling_cutter_head); scissors_head = NULL; drill_head = NULL; bending_machine_head = NULL; welder_head = NULL; painter_head = NULL; screwdriver_head = NULL; milling_cutter_head = NULL; } void buffers_init() { pthread_mutex_init(&scissors_mutex, NULL); pthread_mutex_init(&drill_mutex, NULL); pthread_mutex_init(&bending_machine_mutex, NULL); pthread_mutex_init(&welder_mutex, NULL); pthread_mutex_init(&painter_mutex, NULL); pthread_mutex_init(&screwdriver_mutex, NULL); pthread_mutex_init(&milling_cutter_mutex, NULL); } job_t *get_generic_job(link_list_t **head, pthread_mutex_t *mutex) { if (*head == NULL) { return NULL; } pthread_mutex_lock(mutex); link_list_t *cursor = *head; link_list_t *previous = *head; link_list_t *result = (*head); while (cursor->next != NULL) { if (result->value->step < cursor->next->value->step) { result = cursor->next; previous = cursor; } else if (result->value->step == cursor->next->value->step) { if (result->value->type > cursor->next->value->type) { result = cursor->next; previous = cursor; } } cursor = cursor->next; } if (result == (*head)) { (*head) = (*head)->next; } else if (previous == *head) { (*head)->next = result->next; } else { previous->next = result->next; } job_t *return_value = result->value; free(result); pthread_mutex_unlock(mutex); return return_value; } void add_generic_job(link_list_t **head, job_t *job_to_add, pthread_mutex_t *mutex) { pthread_mutex_lock(mutex); if (*head == NULL) { (*head) = (link_list_t*) malloc(sizeof(link_list_t)); (*head)->value = job_to_add; (*head)->next = NULL; } else { link_list_t *cursor = *head; while (cursor->next != NULL) { cursor = cursor->next; } if (cursor == *head) { link_list_t * next = (link_list_t*)malloc(sizeof(link_list_t)); next->next = NULL; next->value = job_to_add; (*head)->next = next; } else { link_list_t * next = (link_list_t*)malloc(sizeof(link_list_t)); next->next = NULL; next->value = job_to_add; cursor->next = next; } } pthread_mutex_unlock(mutex); } job_t *get_scissors_job() { return get_generic_job(&scissors_head, &scissors_mutex); } void add_scissors_job(job_t *job_to_add) { add_generic_job(&scissors_head, job_to_add, &scissors_mutex); } job_t *get_drill_job() { job_t *result = get_generic_job(&drill_head, &drill_mutex); return result; } void add_drill_job(job_t *job_to_add) { add_generic_job(&drill_head, job_to_add, &drill_mutex); } job_t *get_bending_machine_job() { return get_generic_job(&bending_machine_head, &bending_machine_mutex); } void add_bending_machine_job(job_t *job_to_add) { add_generic_job(&bending_machine_head, job_to_add, &bending_machine_mutex); } job_t *get_welder_job() { return get_generic_job(&welder_head, &welder_mutex); } void add_welder_job(job_t *job_to_add) { add_generic_job(&welder_head, job_to_add, &welder_mutex); } job_t *get_painter_job() { return get_generic_job(&painter_head, &painter_mutex); } void add_painter_job(job_t *job_to_add) { add_generic_job(&painter_head, job_to_add, &painter_mutex); } job_t *get_screwdriver_job() { return get_generic_job(&screwdriver_head, &screwdriver_mutex); } void add_screwdriver_job(job_t *job_to_add) { add_generic_job(&screwdriver_head, job_to_add, &screwdriver_mutex); } job_t *get_milling_job() { return get_generic_job(&milling_cutter_head, &milling_cutter_mutex); } void add_milling_job(job_t *job_to_add) { add_generic_job(&milling_cutter_head, job_to_add, &milling_cutter_mutex); }
C
#include"header.h" int main() { int fd[2]; char s[10],a[10]; char buff[10]; if(pipe(fd)==-1) { perror("pipe"); return 0; } if(fork()==0) { sleep(1); read(fd[0],a,sizeof(a)); printf("in child out put......%s\n",a); } else { printf("enter the string in parent.......\n"); scanf("%s",s); write(fd[1],s,strlen(s)+1); } }
C
#include<stdio.h> //#include<conio.h> #include<ctype.h> #include<stdlib.h> void main() { int i=2,j=0,k=2,k1=0; char ip[10],kk[10]; FILE* fp; //clrscr(); printf("\nEnter the filename of the intermediatecode"); scanf("%s",&kk); fp=fopen(kk,"r"); if(fp==NULL){ printf("\nError in Opening the file"); //getch(); }//clrscr(); while(!feof(fp)) { fscanf(fp,"%s\n",ip); printf("\t\t%s\n",ip); }rewind(fp); printf("\n------------------------------\n"); printf("\tStatement \t\t target code\n"); printf("\n------------------------------\n"); while(!feof(fp)) { fscanf(fp,"%s",ip); printf("\t%s",ip); printf("\t\tMOV %c,R%d\n\t",ip[i+k],j); if(ip[i+1]=='+') printf("\t\tADD"); else printf("\t\tSUB"); if(islower(ip[i])) printf("%c,R%d\n\n",ip[i+k1],j); else printf("%c,%c\n",ip[i],ip[i+2]); j++;k1=2;k=0 ;} printf("\n-------------------------------\n"); //getch(); fclose(fp); }
C
#include <llbmc.h> /* #include <stdlib.h> */ typedef struct _SLL_ENTRY { int Data; struct _SLL_ENTRY *Flink; } SLL_ENTRY, *PSLL_ENTRY; PSLL_ENTRY SLL_create(int length) { int i; PSLL_ENTRY head, tmp; head = NULL; for(i = 0; i < length; i++) { tmp = (PSLL_ENTRY)malloc(sizeof(SLL_ENTRY)); tmp->Flink = head; head = tmp; } return head; } void SLL_destroy_seg(PSLL_ENTRY x, PSLL_ENTRY y) { PSLL_ENTRY t; while(x != y) { t = x; x = x->Flink; free(t); } } void SLL_destroy(PSLL_ENTRY x) { SLL_destroy_seg(x, NULL); } PSLL_ENTRY copy(PSLL_ENTRY a) { PSLL_ENTRY y, x = a; SLL_ENTRY* * z = &y; while(x != NULL) /* listseg(y,*z) * listseg(-,x) * list(x) */ { *z = (SLL_ENTRY*)malloc(sizeof(SLL_ENTRY)); (*z)->Data = x->Data; z = &(*z)->Flink; x = x->Flink; } *z = NULL; return y; } int main() { PSLL_ENTRY x = NULL, y = NULL; int s = __llbmc_nondef_int(); __llbmc_assume(s <= 5); x = SLL_create(s); y = copy(x); SLL_destroy(x); SLL_destroy(y); return 0; }
C
#include<stdio.h> #include<string.h> #define MEDIA 5 typedef struct { char nome[20]; float mediaFinal; int matricula; }Talunos; main(){ Talunos aluno[3],*Paluno,AlunoRp[3],AlunoAp[3],*PAAP,*PARP; Paluno = aluno; PAAP = AlunoAp; PARP = AlunoRp; int i,contAp=0,contRp=0; for (i=0;i<3;i++){ fflush(stdin); printf("Nome: "); gets(Paluno[i].nome); fflush(stdin); printf("Matricula: "); scanf("%d",&Paluno[i].matricula); printf("Media final: "); scanf("%f",&Paluno[i].mediaFinal); //fflush(stdin); if (Paluno[i].mediaFinal >= MEDIA){ strcpy(PAAP[contAp].nome,Paluno[i].nome); PAAP[contAp].matricula = Paluno[i].matricula; PAAP[contAp].mediaFinal = Paluno[i].mediaFinal; printf("Aprovado! %.2f",PAAP[contAp].mediaFinal); contAp++;//tem que atribuir depois, pq ele ta comeando do zero e aqui ele vira um; }else{ // AlunoRp[contRp] = aluno[i]; //pra copiar todos os indices fflush(stdin); strcpy(PARP[contRp].nome,Paluno[i].nome); fflush(stdin); PARP[contRp].matricula = Paluno[i].matricula; PARP[contRp].mediaFinal = Paluno[i].mediaFinal; fflush(stdin); printf("Reprovado! %.2f",PARP[contRp].mediaFinal); contRp++;//tem que atribuir depois, pq ele ta comeando do zero e aqui ele vira um; } printf("\n"); } printf("ContAP: %d\nContRP: %d\n",contAp,contRp); int j; printf("\tAlunos Aprovados: \n"); for(j=0;j<contAp;j++){ // fflush(stdin); printf("Nome: %s\n",PAAP[j].nome); printf("Matricula: %d\n",PAAP[j].matricula); printf("Media Final: %.2f\n",PAAP[j].mediaFinal); printf("\n"); // fflush(stdin); } printf("\n"); printf("\tAlunos Reprovados: \n"); for(j=0;j<contRp;j++){ // fflush(stdin); printf("Nome: %s\n",PARP[j].nome); printf("Matricula: %d\n",PARP[j].matricula); printf("Media Final: %.2f\n",PARP[j].mediaFinal); printf("\n"); // fflush(stdin); } system("PAUSE"); }
C
/* Author: Abida Hassan Filier: SDAD */ #include<stdio.h> void afficherMatriceReelle(double **A,int L,int C){ int i,j; for(i = 1;i<=L;i++){ for(j = 1;j<=C;j++){ printf("%lf ",*(A[i]+j)); } printf("\n"); } }
C
#include <stdio.h> #include <stdlib.h> /*Elabore um programa que faça a leitura de vários números inteiros até que se digite um número negativo. O programa tem de retornar o maior e o menor número lido */ int main(void){ int numUsuario, maiorNum = 0, menorNum = 0, aux = 0; printf("\nDigite um numero inteiro: "); scanf("%d", &numUsuario); while(numUsuario >= 0){ if(numUsuario > aux){ maiorNum = numUsuario; aux = maiorNum; } else{ menorNum = numUsuario; } printf("\nDigite um numero inteiro: "); scanf("%d", &numUsuario); } printf("\nMaior numero: %d", maiorNum); printf("\nMenor numero: %d", menorNum); return(0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> /*Declaracao da variaveis globais de controle...*/ int cont,cont2; float mediaturma; /*Declaraзгo da Struct alunos onde estao guardadas todas a veriaveis ultilizadas no Programa...*/ struct aluno{ char nome[15], sobrenome[15]; int numerousp, turma; float prova1, prova2, prova3, media; }typedef aluno;; /*Funcao para o cadastro*/ void cadastro(aluno *alunos,int cont2){ int cont; for(cont=0;cont < cont2;cont++){ printf("Cadastre o nome: "); fflush(stdin); fgets(alunos[cont].nome, sizeof(alunos[cont].nome), stdin); printf("Cadastre o sobrenome: "); fflush(stdin); fgets(alunos[cont].sobrenome, sizeof(alunos[cont].sobrenome), stdin); printf("Cadastre o numero usp do aluno: "); scanf("%d",&alunos[cont].numerousp); printf("Turma: "); scanf("%d", &alunos[cont].turma); printf("Cadastre a nota da primeira prova:\n "); scanf("%f",&alunos[cont].prova1); printf("Cadastre a nota da segunda prova:\n "); scanf("%f",&alunos[cont].prova2); printf("Cadastre a nota da terceira prova:\n "); scanf("%f",&alunos[cont].prova3); } printf("\n------------------------------------\n"); printf("\nInformacoes cadastradas com sucesso...\n"); printf("\n------------------------------------\n"); system("\npause\n"); } /*Funcao para a formacao da nota...*/ void verifica(aluno *alunos,int cont2){ /*Calculo da media...*/ for(cont=0;cont<cont2;cont++){ alunos[cont].media = ((alunos[cont].prova1 + alunos[cont].prova2 + alunos[cont].prova3)/3); } } /*Funcao responsavel pela busca de um aluno em especifico...*/ void busca(aluno *alunos,int cont2){ int nnumerousp; printf("\n------------------------------------\n"); printf("Sistema de Busca.\n"); printf("\n------------------------------------\n"); printf("Digite a matricula do aluno: \n"); scanf("%d",&nnumerousp); /*For para impressao...*/ for(cont=0;cont<cont2;cont++){ if(nnumerousp==alunos[cont].numerousp){ printf("\n------------------------------------\n"); printf("\nNumero USP: %d\n", alunos[cont].numerousp); printf("Nome: %s", alunos[cont].nome); printf("Sobrenome: %s", alunos[cont].sobrenome); printf("Turma: %d\n", alunos[cont].turma); printf("Media: %.2f\n", alunos[cont].media); printf("\n------------------------------------\n"); } } } /*funcao de buscar turma*/ void buscaturma(aluno *alunos,int cont2){ int nturma; printf("\n------------------------------------\n"); printf("Sistema de Busca.\n"); printf("\n------------------------------------\n"); printf("Digite a turma: \n"); scanf("%d",&nturma); /*For para impressao...*/ for(cont=0;cont<cont2;cont++){ if(nturma==alunos[cont].turma){ printf("\n------------------------------------\n"); printf("\nNumero USP: %d\n", alunos[cont].numerousp); printf("Nome: %s", alunos[cont].nome); printf("Sobrenome: %s", alunos[cont].sobrenome); printf("Turma: %d\n", alunos[cont].turma); printf("Media: %.2f\n", alunos[cont].media); printf("\n------------------------------------\n"); } } } /*funcao de calcular media da turma*/ void turmamedia(aluno *alunos,int cont2){ int nturma; int mediaturma, turmamedia; printf("\n------------------------------------\n"); printf("Media turma.\n"); printf("\n------------------------------------\n"); printf("Digite a turma: \n"); scanf("%d",&nturma); /*For para impressao...*/ for( cont = 0 ;cont<cont2;cont++){ if(nturma==alunos[cont].turma){ mediaturma += alunos[cont].media; turmamedia = mediaturma; printf("\n------------------------------------\n"); printf("Media da turma: %.2f\n", turmamedia); printf("\n------------------------------------\n"); } } } /*funcao para arquivar os dados*/ void file(aluno *alunos, int cont2){ FILE *fp; int nturma; printf("\n------------------------------------\n"); printf("Digite a turma: \n"); scanf("%d",&nturma); fp=fopen("RelatorioTurma.txt","w"); for(cont=0;cont<cont2;cont++){ if(nturma==alunos[cont].turma){ fprintf(fp,"\nNumero USP: %d\n", alunos[cont].numerousp); fprintf(fp,"Nome: %s", alunos[cont].nome); fprintf(fp,"Sobrenome: %s",alunos[cont].sobrenome); fprintf(fp,"Turma: %d\n", alunos[cont].turma); fprintf(fp,"Media: %.2f\n", alunos[cont].media); } } printf("Arquivo RelatorioTurma.txt criado com sucesso\n"); fclose(fp); } /*Funcao para Imprimir o Relatorio Geral dos alunos...*/ void lista(aluno *alunos,int cont2){ int cont; printf("\n------------------------------------\n"); printf("\nRelatorio Completo.\n"); for(cont=0;cont<cont2;cont++){ printf("\nNumero USP: %d\n", alunos[cont].numerousp); printf("Nome: %s", alunos[cont].nome); printf("Sobrenome: %s",alunos[cont].sobrenome); printf("Turma: %d\n", alunos[cont].turma); printf("Media: %.2f\n", alunos[cont].media); } printf("\n------------------------------------\n"); } /*Funcao Principal Responsavel pela chamadas das de mais funcoes...*/ int main(){ int menu; /*Linha para imformar a quantidade de alunos que deseja cadastrar...*/ printf("Digite a quantidade de alunos que deseja cadastrar:\n "); scanf("%d",&cont2); /*instancia da struct no main...*/ aluno alunos[cont2]; /*impressao do Menu...*/ printf("\n------------------------------------\n"); printf("Sistema para Cadastro de alunos e Notas.\n"); printf("\n------------------------------------\n"); while(menu!=7){ printf("Menu:\n|1|- Para Cadastro.\n|2|- Para Buscas.\n|3|- Para buscar por turma.\n|4|- Media da turma\n|5|- Arquivo .txt\n|6|- Relatorio.\n|7|- Para Sair"); printf("\n------------------------------------\n"); scanf("%d",&menu); switch (menu){ case 1 : cadastro(alunos,cont2);/*chamada da funcao cadastro...*/ verifica(alunos,cont2); break; case 2 : busca(alunos,cont2);/*Chamada da funcao busca...*/ break; case 3 : buscaturma(alunos,cont2);/*Chamada da funcao busca pela turma...*/ break; case 4 :turmamedia(alunos, cont2); break; case 5 :file(alunos, cont2); break; case 6 : lista(alunos,cont2);/*Chamada da funcao lista...*/ break; case 7 :printf("\nDesenvolvido por Rodrigo Vernizzi e Gustavo Sandrin\n\n"); printf("Finalizando o Sistema...\n\n\n");/*Finaliza do Programa...*/ break; default: printf("Opeгacao invalida...\n"); break; } } system("pause"); }
C
#include <stdio.h> #include <string.h> void convert(char *str, char *buf) { int i = 0; while (str[i]) { if (str[i] > 'a' && str[i] < 'z') { buf[i] = str[i] - 'a' + 'A'; } else if (str[i] > 'A' && str[i] < 'Z') { buf[i] = str[i] - 'A' + 'a'; } else { // 其他的不变 buf[i] = str[i]; } i++; } // 字符串结尾 buf[i] = '\0'; } // 指针版本 void convert_ptr(char *str, char *buf) { while (*str) { if (*str > 'a' && *str < 'z') { *buf = *str - 'a' + 'A'; // 转化成大写 } else if (*str > 'A' && *str < 'Z') { *buf = *str - 'A' + 'a'; // 转化成小写 } else { *buf = *str; } str++; buf++; } *buf = '\0'; } int main(void) { char str[] = "If we hold onto each other, we'll be better than before. "; char buf[sizeof(str)]; convert(str, buf); printf("%s\n", buf); convert_ptr(buf, buf); printf("%s\n", buf); }
C
#include<stdio.h> #include<conio.h> void main() { int n,i,j,a,b[50]; clrscr(); printf("Enter the number:"); scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&b[i]); } printf("Enter the target number:"); scanf("%d",&a); for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(b[i]+b[j+1]==a) { printf("%d %d",b[i],b[j+1]); } } } getch(); }
C
/*************************************************** * Single Author Info * mghegde Mahendra Hegde * * Group Info * mghegde Mahendra Hegde * ssingh24 Siddharth Singh * skumar23 Sudhendu Kumar ***************************************************/ #include<stdio.h> #include "mymutex.h" int mythread_mutex_init(mythread_mutex_t * mutex, const mythread_mutexattr_t *attr) { *mutex = (mythread_mutex_t) malloc(sizeof(struct mythread_mutex)); (*mutex)->lock =0; (*mutex)->head=NULL; return 0; } int mythread_mutex_lock(mythread_mutex_t *mutex) { return Test_Test_and_Set(mutex); } int mythread_mutex_unlock(mythread_mutex_t *mutex) { //mythread_enter_kernel(); //(*mutex)->lock=0; /*** Release the lock from the current thread And unblock the process which is waiting in the head of the que ***/ if ((*mutex)->head != NULL ) { mythread_enter_kernel(); (*mutex)->lock=0; mythread_unblock(&(*mutex)->head, 1); } else { (*mutex)->lock=0; } // mythread_leave_kernel(); return 0; } int mythread_mutex_destroy(mythread_mutex_t *mutex) { /*** Release the mutex and set the value to NULL ***/ free(*mutex) ; *mutex = NULL; return 0; }
C
/********************************************* *********************************************** SERVER file Name- Kavya Kandhway Adm no. 18JE0408 DD CSE ************************************************ ************************************************ */ #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <unistd.h> //#include <bits/stdc++.h> //using namespace std; int main() { int server_socket; server_socket=socket(AF_INET,SOCK_STREAM,0); if(server_socket<0) { printf("Error1\n"); exit(EXIT_FAILURE); } else { printf("checkpoint1s\n"); } struct sockaddr_in address; int addrlen = sizeof(address); address.sin_family=AF_INET; address.sin_addr.s_addr=INADDR_ANY; address.sin_port=htons(8090); bind(server_socket,(struct sockaddr*)&address,sizeof(address)); listen(server_socket, 3); int new_socket; new_socket = accept(server_socket, (struct sockaddr*)&address, (socklen_t*)&addrlen); if (new_socket < 0) { printf("error2\n"); exit(EXIT_FAILURE); } int valread; char str[100]; valread = read(new_socket, str, sizeof(str)); printf("word received\n"); printf("\nWord entered by the user:%s\n", str); }
C
#include "header.h" subway metro = {NULL, NULL, 0, NULL, 0}; graphlist graph_list = {NULL, 0}; graphmatrix matrix = {NULL, 0}; char init_name(FILE *); char init_lines(FILE *, size_t); char init_stations(FILE *, size_t, RUN_MODE); char init_station_line(FILE*); char init_station_graph(FILE *, size_t, RUN_MODE); // Initialise the whole metro, station, lines and graph included char init_metro(char * filename, RUN_MODE mode){ FILE * file; size_t line_size, station_size; int c; file=fopen(filename, "r"); if(!file){ perror("fopen"); return 0; } count_lines(file); // to jump over the name of the metro line_size = count_lines(file); if(!line_size){ print_error("Invalid subway file, wrong lines format"); fclose(file); return 0; } metro.lines = getmem(line_size, sizeof(line)); if (!metro.lines){ fclose(file); return 0; } station_size = count_lines(file); if(!station_size){ print_error("Invalid subway file, wrong stations format"); fclose(file); return 0; } metro.stations = getmem(station_size, sizeof(station)); if (!metro.stations){ fclose(file); return 0; } while((c = fgetc(file)) != EOF){ if (c != '\n'){ print_error("Invalid subway file format, extra text"); fclose(file); return 0; } } rewind(file); if(!init_name(file) || !init_lines(file, line_size) || !init_stations(file, station_size, mode)){ fclose(file); return 0; } fclose(file); return 1; } // Initialise the name of the metro char init_name(FILE * file){ char buffer [MAX_CHAR_READ]; size_t size; if (!fgets(buffer, MAX_CHAR_READ, file)){ perror("fgets"); return 0; } buffer[MAX_CHAR_READ-1] = '\0'; //to avoid undefined behaviour of strlen size=strlen(buffer); if(buffer[size-1] != '\n'){ print_error("Invalid subway file, name is too long"); return 0; } if(!size){ print_error("Invalid subway file, missing name"); return 0; } metro.name = getmem(size+1, sizeof(char)); if (!metro.name) return 0; strncpy(metro.name, buffer, size+1); if (!fgets(buffer, MAX_CHAR_READ, file)){ perror("fgets"); return 0; } if(buffer[0]!='\n'){ print_error("Invalid subway file, missing carriage return between name and lines"); return 0; } return 1; } // Initialise all the subway lines char init_lines(FILE *file, size_t final_size /* number of lines */){ char buffer [MAX_CHAR_READ]; size_t size; while(fgets(buffer, MAX_CHAR_READ, file) && buffer[0] != '\n' && metro.nli < final_size){ buffer[MAX_CHAR_READ-1] = '\0'; //to avoid undefined behaviour of strlen if((size=strlen(buffer)) < 3 || buffer[1]!='='){ fprintf(stderr, "%s%sError : %s%sInvalid subway file, wrong line format, on line %u%s\n",codeFromStyle(BOLD), codeFromStyle(RED), codeFromStyle(RESET), codeFromStyle(RED), metro.nli+3, codeFromStyle(RESET)); return 0; } if(buffer[size-1] != '\n'){ fprintf(stderr, "%s%sError : %s%sInvalid subway file, line's name is too long, on line %u%s\n",codeFromStyle(BOLD), codeFromStyle(RED), codeFromStyle(RESET), codeFromStyle(RED), metro.nli+3, codeFromStyle(RESET)); return 0; } metro.lines[metro.nli].symbol=buffer[0]; metro.lines[metro.nli].name = getmem(size-1,sizeof(char)); if(!metro.lines[metro.nli].name) return 0; strncpy(metro.lines[metro.nli].name, buffer+2, size-1); metro.lines[metro.nli].name[size-3]='\0'; // remplace le '\n' final metro.nli++; } if (metro.nli != final_size || buffer[0] != '\n'){ perror("fgets"); return 0; } return 1; } // Initialise all stations and the graph char init_stations(FILE *file, size_t final_size /* number of stations */, RUN_MODE mode){ char buffer [MAX_CHAR_READ]; int c, i; switch(mode){ case COMPARE: /* NO BREAK */ case SUCC_LIST: graph_list.noeuds = getmem(final_size, sizeof(noeud)); if (!graph_list.noeuds) return 0; if(mode != COMPARE) break; default: matrix.mat = getmem(final_size*final_size, sizeof(char)); if (!matrix.mat) return 0; memset(matrix.mat, 0, final_size*final_size*sizeof(char)); } while(metro.nsta < final_size){ for(c=fgetc(file), i=0;c != ':';i++, c=fgetc(file)){ if(i>=MAX_CHAR_READ){ fprintf(stderr, "%s%sError : %s%sInvalid subway file, station's name is too long, on line %u%s\n",codeFromStyle(BOLD), codeFromStyle(RED), codeFromStyle(RESET), codeFromStyle(RED), metro.nli+4+metro.nsta, codeFromStyle(RESET)); return 0; } buffer[i]=c; } if (i==0){ fprintf(stderr, "%s%sError : %s%sInvalid subway file, station's name missing, on line %u%s\n",codeFromStyle(BOLD), codeFromStyle(RED), codeFromStyle(RESET), codeFromStyle(RED), metro.nli+4+metro.nsta, codeFromStyle(RESET)); return 0; } buffer[i]='\0'; metro.stations[metro.nsta].name = getmem(i+1,sizeof(char)); if(!metro.stations[metro.nsta].name) return 0; strncpy(metro.stations[metro.nsta].name, buffer, i+1); //rempli metro.stations[metro.nsta]->line if(!init_station_line(file)) return 0; //ajoute elt au graph if(!init_station_graph(file, final_size, mode)) return 0; metro.nsta++; } if((metro.nsta != graph_list.nb && (mode == SUCC_LIST || mode == COMPARE)) || (metro.nsta != matrix.nb && (mode == MATRIX || mode == COMPARE))){ print_error("Incoherence in graph's nodes and stations number"); return 0; } return 1; } // Add all the lines a station belongs to and its number on each line char init_station_line(FILE* file){ unsigned int i=0, max_buff=metro.nli*4, j; char c, *line[metro.nli], buffer[max_buff]; //car une ligne est représenté par 1 lettre, 2 chiffre et 1 séparateur + '\0' final // Récupère la chaîne qui représente toutes les lignes auxquelles appartient une station (ex :"C08/H06/M15") while((c=fgetc(file)) != ' '){ if(i>max_buff-2){ //pour laisser la place pour le '\0' fprintf(stderr, "%s%sError : %s%sInvalid subway file, invalid station's line format, station %s%s\n",codeFromStyle(BOLD), codeFromStyle(RED), codeFromStyle(RESET), codeFromStyle(RED), metro.stations[metro.nsta].name, codeFromStyle(RESET)); return 0; } buffer[i]=c; i++; } buffer[i]='\0'; // Sépare les différentes lignes i=0; line[0] = strtok(buffer, "/"); for(i = 1; line[i-1] != NULL; i++){ if(i>=metro.nli){ fprintf(stderr, "%s%sError : %s%sInvalid subway file, too many lines for one station, station %s%s\n",codeFromStyle(BOLD), codeFromStyle(RED), codeFromStyle(RESET), codeFromStyle(RED), metro.stations[metro.nsta].name, codeFromStyle(RESET)); return 0; } line[i] = strtok(NULL, "/"); } // Ajoute chaque ligne à la liste de lignes de la station en cours de construction metro.stations[metro.nsta].lines = getmem(i-1,sizeof(unsigned int[2])); metro.stations[metro.nsta].nlines = i-1; if (!metro.stations[metro.nsta].lines) return 0; for(i=0;line[i]; i++){ if(!isalpha(line[i][0])){ fprintf(stderr, "%s%sError : %s%sInvalid subway file, wrong station's line format, first character is not a letter, station %s, line %s%s\n",codeFromStyle(BOLD), codeFromStyle(RED), codeFromStyle(RESET), codeFromStyle(RED), metro.stations[metro.nsta].name, line[i], codeFromStyle(RESET)); return 0; } for (j=1; line[i][j]!='\0'; j++) if(!isdigit(line[i][j])){ fprintf(stderr, "%s%sError : %s%sInvalid subway file, wrong station's line format, station's number contain non digit character, station %s, line %s%s\n",codeFromStyle(BOLD), codeFromStyle(RED), codeFromStyle(RESET), codeFromStyle(RED), metro.stations[metro.nsta].name, line[i], codeFromStyle(RESET)); return 0; }; if(j==1){ fprintf(stderr, "%s%sError : %s%sInvalid subway file, wrong station's line format, missing station's number, station %s, line %s%s\n",codeFromStyle(BOLD), codeFromStyle(RED), codeFromStyle(RESET), codeFromStyle(RED), metro.stations[metro.nsta].name, line[i], codeFromStyle(RESET)); return 0; } line[i][0] = toupper(line[i][0]); //for forked lines (like the Marunouchi Line, having a 'M' and 'm' branch for(j=0;j<metro.nli;j++) if(metro.lines[j].symbol == line[i][0]) break;; if(j == metro.nli){ fprintf(stderr, "%s%sError : %s%sInvalid subway file, wrong station's line format, line doesn't exists, station %s, line %s%s\n",codeFromStyle(BOLD), codeFromStyle(RED), codeFromStyle(RESET), codeFromStyle(RED), metro.stations[metro.nsta].name, line[i], codeFromStyle(RESET)); return 0; } metro.stations[metro.nsta].lines[i][0]=j; metro.stations[metro.nsta].lines[i][1]=(unsigned int) strtoul(line[i]+1,NULL,10); } return 1; } // Add a station to the graph with a list of successors char init_station_graph(FILE *file, size_t final_size /* number of stations */, RUN_MODE mode){ unsigned int i = final_size, digits = count_digits_number(final_size), j=0, n; char c; succ * corr = NULL, *temp=NULL; char buffer[digits+1]; // create a buffer which can contain the same number of char as the number of digit of final_size + '\0' if(mode == SUCC_LIST || mode == COMPARE) graph_list.noeuds[metro.nsta].num=metro.nsta; c=fgetc(file); while (c!='\n'){ j++; for(i=0 ; !strchr(" \n",c) ; i++, c=fgetc(file)){ if(!isdigit(c)){ fprintf(stderr, "%s%sError : %s%sInvalid subway file, transfer %d of station %s is not a number%s\n",codeFromStyle(BOLD), codeFromStyle(RED), codeFromStyle(RESET), codeFromStyle(RED), j, metro.stations[metro.nsta].name, codeFromStyle(RESET)); return 0; } if(i>=digits){ fprintf(stderr, "%s%sError : %s%sInvalid subway file, the number of the %d%s transfer of station %s is higher than the number of existing stations%s\n",codeFromStyle(BOLD), codeFromStyle(RED), codeFromStyle(RESET), codeFromStyle(RED), j, ordinal_suffix(j), metro.stations[metro.nsta].name, codeFromStyle(RESET)); return 0; } buffer[i]=c; } buffer[i]='\0'; if(strlen(buffer)!=0){ n = (unsigned int) strtoul(buffer,NULL,10); if(n >= final_size){ fprintf(stderr, "%s%sError : %s%sInvalid subway file, the number of the %d%s transfer of station %s is higher than the number of existing stations%s\n",codeFromStyle(BOLD), codeFromStyle(RED), codeFromStyle(RESET), codeFromStyle(RED), j, ordinal_suffix(j), metro.stations[metro.nsta].name, codeFromStyle(RESET)); return 0; } switch(mode){ case COMPARE: /* NO BREAK */ case SUCC_LIST: corr = getmem(1,sizeof(succ)); if(!corr) return 0; corr->car = graph_list.noeuds + n; corr->cdr = temp; temp = corr; if(mode != COMPARE) break; default: matrix.mat[metro.nsta*final_size+n]=1; } } if(c == ' ') c=fgetc(file); } if(mode == SUCC_LIST || mode == COMPARE){ graph_list.noeuds[metro.nsta].next=corr; graph_list.nb++; } if(mode == MATRIX || mode == COMPARE){ matrix.nb++; } return 1; } /* First try with static arrays char init_metro(char * filename){ char buffer [MAX_CHAR_READ], *test, *tokens[MAX_CHAR_READ], *lines[MAX_CHAR_READ]; size_t buffer_size, name_size; FILE * file; int i, j; file=fopen(filename, "r"); if(!file){ perror("fopen"); return 0; } metro.nli=0; metro.nsta=0; // SUBWAY LINES while(test=fgets(buffer, MAX_CHAR_READ, file) && buffer[0] != '\n'){ if(metro.nli>=MAX_LINES){ fprintf(stderr,"Too many subway lines.\n") return 0; } if(buffer_size=strlen(buffer) < 3 || buffer[1]!='='){ fprintf(stderr, "Invalid subway line, on line %u\n", metro.nli); return 0; } metro.lines[metro.nli].symbol=buffer[0]; name_size = buffer_size-2 > MAX_LINE_NAME ? MAX_LINE_NAME : buffer_size-2; strncpy(metro.lines[metro.nli].name, buffer+2, name_size); metro.lines[metro.nli].name[name_size-1]='\0'; // remplace le '\n' final while(buffer[buffer_size-1] != '\n'){ test=fgets(buffer, MAX_CHAR_READ, file); if (!test){ perror("fgets"); fprintf(stderr, "Unexpected end of parsing, line %u\n", metro.nli); return 0; } buffer_size=strlen(buffer); } metro.nli++; } // SUBWAY STATIONS while(test=fgets(buffer, MAX_CHAR_READ, file)){ if(metro.sta>=MAX_STATIONS){ fprintf(stderr,"Too many subway stations.\n") return 0; } buffer_size=strlen(buffer); name_size = strcspn(buffer, ":"); if (!name_size || name_size == buffer_size || name_size +2 < buffer_size){ fprintf(stderr, "Invalid subway station, on line %u\n", metro.nli+1+metro.nsta); return 0; } tokens[0] = strtok(buffer+name_size+1, " "); for(i = 1; tokens[i-1] != NULL; i++) tokens[i] = strtok(NULL, " "); lines[0] = strtok(tokens[0], "/"); for(i = 1; lines[i-1] != NULL; i++) lines[i] = strtok(NULL, "/"); for(i = 0; lines[i] != NULL; i++){ if(strlen(lines[i])<2){ fprintf(stderr, "Invalid subway station, on line %u\n", metro.nli+1+metro.nsta); return 0; } for (j=0 ; j < metro.nli || metro.lines[j].symbol != lines[i][0] ; j++); if (j == metro.nli){ fprintf(stderr, "Invalid subway station, on line %u, subway line not found\n", metro.nli+1+metro.nsta); return 0; } metro.stations[metro.nsta].lines[i][0] = j; metro.stations[metro.nsta].lines[i][1] = (unsigned char) strtoul(lines[i]+1,NULL,10); } if (name_size>MAX_STATION_NAME) name_size=MAX_STATION_NAME; strncpy(metro.stations[metro.nsta].name, buffer, name_size); metro.nsta++; } } */
C
#include <stdio.h> #include <stdlib.h> int main () { int N, *n; double M, *m; char O, *o; n = &N; m = &M; o = &O; scanf("%d\n", &N); scanf("%lf\n", &M); scanf("%c\n", &O); printf("%d %lu %x\n", N, sizeof(N), n); printf("%lf %x %d\n", M, m, sizeof(M)); printf("%c %x %d\n", O, o, sizeof(O)); return 0; }
C
size_t ft_strlcat(char *dst, const char *src, size_t size) { size_t i; size_t j; i = 0; j = 0; while (dst[i]) i++; if (size) { while ((i + j) < (size - 1) && src[j]) { dst[i + j] = src[j]; j++; } dst[i + j] = '\0'; } while (src[j]) j++; if (i < size) return (i + j); return (size + j); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> #include "state.h" /* Arreglo con patrones de cuatro unos consecutivos */ int masks[8]; /* Arreglo con el complemento de cada patron del arreglo anterior*/ int cMasks[8]; /* Metodo para inicializar el arreglo de mascaras */ void initializeMasks() { masks[0] = 0xF0000000; masks[1] = 0x0F000000; masks[2] = 0x00F00000; masks[3] = 0x000F0000; masks[4] = 0x0000F000; masks[5] = 0x00000F00; masks[6] = 0x000000F0; masks[7] = 0x0000000F; } /* Metodo para inicializar el arreglo de complementos */ void initializeCompMasks() { cMasks[0] = 0x0FFFFFFF; cMasks[1] = 0xF0FFFFFF; cMasks[2] = 0xFF0FFFFF; cMasks[3] = 0xFFF0FFFF; cMasks[4] = 0xFFFF0FFF; cMasks[5] = 0xFFFFF0FF; cMasks[6] = 0xFFFFFF0F; cMasks[7] = 0xFFFFFFF0; } /* FUNCION: make_state * DESC : Funcion para la creacion de un nuevo estado * q1 : Representacion en entero de las primeras 8 casillas * q2 : Representacion en entero de las ultimas 8 casillas * z : Posicion actual del cero * RETORNA: Un nuevo esta con los valores q1 q2 y z */ state make_state(int q1, int q2, int z) { state newState = malloc(sizeof(struct _state)); newState -> quad_1 = q1; newState -> quad_2 = q2; newState -> zero = z; return newState; } /* FUNCION: is_goal * DESC : Verifica si el estado s es un estado final * s : Es el estado que se va a verificar * RETORNA: Devuelve 1 si es goal. 0 En caso contrario */ int is_goal(state s) { int q1; int q2; q1 = 0x01234567; q2 = 0x89ABCDEF; return (q1==s->quad_1)&&(q2==s->quad_2); } /* FUNCION: moveLR * DESC : Devuelve un estado resultado de mover el cero a la izquierda * o a la derecha. El estado s no es alterado * s : Estado a partir del cual se va a mover * d : Desplazamiento hacia la izquierda o derecha del estado s * RETORNA: Un nuevo estado resultado de aplicar el desplazamiento d en s */ state moveLR(state s, int d) { int save; int newq; int zero = s->zero; state nState = NULL; save = 0; newq = 0; if (zero < 8) { // Si estamos en el primer cuadrante save = (s->quad_1)&masks[zero+d]; if ( d < 0 ) { // Si el movimiento es a la izquierda save = save >> 4; save = save&(0x0FFFFFFF); } else { // Si el movimiento es a la derecha save = save << 4; } newq = (s->quad_1)&cMasks[zero+d]; newq = newq | save; nState = make_state(newq,s->quad_2, zero+d); } else { // Si estamos en el segundo cuadrante save = (s->quad_2)&masks[(zero+d)%8]; if ( d < 0 ) { // Si el movimiento es a la izquierda save = save >> 4; save = save&(0x0FFFFFFF); } else { // Si el movimiento es a la derecha save = save << 4; } newq = (s->quad_2)&cMasks[(zero+d)%8]; newq = newq | save; nState = make_state(s->quad_1, newq, zero+d); } return nState; } /* FUNCION: moveUD * DESC : Desplazamientos hacia arriba o abajo desde un estado s * s : Estado a partir del cual hacer el desplazamiento * d : Desplazamiento hacia arriba o hacia abajo a realizar * RETORNA: Un nuevo estado resultado de aplicar el desplazamiento d desde s */ state moveUD(state s, int d) { int save; int newq1; int newq2; int zero = s->zero; state nState = NULL; save = 0; newq1 = 0; newq2 = 0; int caso = zero/4; switch (caso) { case 0: // Estamos en la primera linea del puzzle save = (s->quad_1)&masks[zero+d]; save = save << 16; newq1 = (s->quad_1)&cMasks[zero+d]; newq1 = newq1 | save; nState = make_state(newq1,s->quad_2,zero+d); break; case 1: // Estamos en la segunda linea del puzzle if ( d < 0 ) { // Si el movimiento es arriba save = (s->quad_1)&masks[(zero+d)%8]; save = save >> 16; save = save&(0x0000FFFF); newq1 = (s->quad_1)&cMasks[(zero+d)%8]; newq1 = newq1 | save; nState = make_state(newq1, s->quad_2, zero+d); } else { // Si el movimiento es hacia abajo save = (s->quad_2)&masks[(zero+d)%8]; save = save >> 16; save = save&(0x0000FFFF); newq1 = (s->quad_1) | save; newq2 = (s->quad_2)&cMasks[(zero+d)%8]; nState = make_state(newq1,newq2,zero+d); } break; case 2: // Estamos en la tercera linea del puzzle if ( d < 0 ) { // Si el movimiento es hacia arriba save = (s->quad_1)&masks[(zero+d)%8]; save = save << 16; newq1 = (s->quad_1)&cMasks[(zero+d)%8]; newq2 = (s->quad_2) | save; nState = make_state(newq1,newq2,zero+d); } else { // Si el movimiento es hacia abajo save = (s->quad_2)&masks[(zero+d)%8]; save = save << 16; newq2 = (s->quad_2)&cMasks[(zero+d)%8]; newq2 = newq2 | save; nState = make_state(s->quad_1,newq2,zero+d); } break; case 3: // Estamos en la cuarta linea del puzzle save = (s->quad_2)&masks[(zero+d)%8]; save = save >> 16; save = save&(0x0000FFFF); newq1 = (s->quad_2)&cMasks[(zero+d)%8]; newq1 = newq1 | save; nState = make_state(s->quad_1,newq1,zero+d); break; } } /* FUNCION: transition * DESC : Funcion para calcular la transicion de un estado a otro * s : Estado a partir del cual hacer transicion * a : Accion a realizar: 'l', 'r', 'd', 'u' (En ingles) * RETORNA: Un nuevo estado resultado de aplicar el movimiento a en s\ */ state transition(state s, char a) { int save; int newq; int zero = s->zero; state nState = NULL; save = 0; newq = 0; // Siempre estamos moviendo el cero switch (a) { case 'l': // Movimiento hacia la izquierda if (zero%4 != 0) { nState = moveLR(s,-1); } break; case 'r': // Movimiento hacia la derecha if ((zero+1)%4 != 0) { nState = moveLR(s,1); } break; case 'd': // Movimiento hacia abajo if (zero+4 < 16) { nState = moveUD(s,4); } break; case 'u': // Movimiento hacia arriba if (zero-4 >= 0) { nState = moveUD(s,-4); } break; } return nState; } /* FUNCION: init * DESC : Funcion para la inicializacion y creacion del estado raiz * RETORNA: Un nuevo estado asociado a la configuracion inicial suministrada */ state init(char* input){ /*Inicializacion de las mascaras usadas para computar la representacion * de la cuadricula*/ initializeMasks(); initializeCompMasks(); printf("%s",input); int k[16]; sscanf(input," %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d \n", &k[0],&k[1],&k[2],&k[3],&k[4],&k[5],&k[6],&k[7], &k[8],&k[9],&k[10],&k[11],&k[12],&k[13],&k[14],&k[15]); int quad_index; int quad_1 = 0; /*almacenamiento de la primera mitad de la cuadricula*/ int quad_2 = 0; /*almacenamiento de la segunda mitad de la cuadricula*/ int pos_zero = 0; /*posicion del 0 en la cuadricula*/ for (quad_index=0; quad_index < 8; quad_index++){ int quad_2_index = quad_index+8; /*se recuerda la posicion del 0 en la cuadricula*/ if (k[quad_index]==0) { pos_zero = quad_index; } if (k[quad_2_index]==0) { pos_zero = quad_2_index; } /*desplazamiento de los digitos significados, permiten alojar el nuevo *numero entrante de 4 bits*/ quad_1 = quad_1 << 4; quad_2 = quad_2 << 4; /*se conservan los bits encendidos de la cuadricula, agregando *la representacion binaria del numero entrante en los ultimos 4 bits*/ quad_1 = quad_1 | k[quad_index]; quad_2 = quad_2 | k[quad_2_index]; } return make_state(quad_1,quad_2,pos_zero); } /* FUNCION: get_succ * DESC : Funcion que obtiene todos los sucesores de un estado * s : Estado del cual extraer los sucesores * RETORNA: Un arreglo con los sucesores del estado s */ successors get_succ(state s) { successors res = malloc(sizeof(struct _successors)); res->succ[0] = transition(s,'l'); res->succ[1] = transition(s,'r'); res->succ[2] = transition(s,'u'); res->succ[3] = transition(s,'d'); return res; } /* FUNCION: print_state * DESC : Imprime en pantalla la representacion de un estado * s : Estado que se va a imprimir */ void print_state(state s) { // Si el estado es null, retornar if (s==NULL) return; int i; // Declaramos un d entero para hacer los shift necesarios int d = 28; // Imprimimos el primer cuadrante for (i=0; i<8; i++) { // Salto de linea cada vez que se termina de imprimir una linea if (i%4 == 0) { printf("\n"); } // Imprimimos el valor haciendo los shift correspondientes printf("%2d ", ((s->quad_1)&masks[i])>>d); // Se decrementa la cantidad de bits a mover en la siguiente iteracion d = d-4; } // Reinicializamos el numero de bits a mover d = 28; // Imprimimos el segundo cuadrante for (i=0; i<8; i++) { // Salto de linea cada vez que se termina de imprimir una linea if (i%4 == 0) { printf("\n"); } // Imprimimos el valor haciendo los shift correspondientes printf("%2d ", ((s->quad_2)&masks[i])>>d); // Se decrementa la cantidad de bits a mover en la siguiente iteracion d = d-4; } printf("\n"); } /* FUNCION: free_state * DESC : Libera el espacio reservado por un estado * s : Estado a ser liberado */ void free_state(void *sp) { state s = (state) sp; free(s); }
C
#ifndef GML_PERSPECTIVE_PROJECTION_H #define GML_PERSPECTIVE_PROJECTION_H #include <gml/matrix/matrix4.h> #include <cmath> static void gmlPerspective(float fov, float aspect_ratio, float* left, float* right, float* bottom, float* top, float near){ *top = tan(fov/2)*near; *right = aspect_ratio * (*top); *left = -(*right); *bottom = -(*top); } static void gmlFrustum(gmlMat4* mat, float left, float right, float bottom, float top, float near, float far){ gmlMat4SetElem(mat, 0, 0, (2*near)/(right-left)); gmlMat4SetElem(mat, 0, 3, (-1*near*(right+left))/(right-left)); gmlMat4SetElem(mat, 1, 1, (2*near)/(top-bottom)); gmlMat4SetElem(mat, 1, 3, (-1*near*(top+bottom))/(top-bottom)); gmlMat4SetElem(mat, 2, 2, (-1*(far+near))/(far-near)); gmlMat4SetElem(mat, 2, 3, (2*far*near)/(near-far)); gmlMat4SetElem(mat, 3, 2, -1); gmlMat4SetElem(mat, 3, 3, 0); } #endif //GML_PERSPECTIVE_PROJECTION_H
C
/* glfuncs.h: cs316 lab02 include file Created by: Kevin Sahr, 10/5/17 */ #ifndef GLFUNCS_H #define GLFUNCS_H #include <stdio.h> #include <string.h> /*** GL include files ***/ #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <Glut/glut.h> #else #define GL_GLEXT_PROTOTYPES #include <GL/gl.h> #include <GL/glext.h> #include <GL/glx.h> #include <GL/glu.h> #include <GL/glut.h> #endif /*** constants ***/ #define MAXVERTS 1000 #define MAXSPECS 500 #define MAXLINE 256 #define PI 3.14159265f /*** type definitions ***/ typedef struct { GLfloat x; GLfloat y; } Vec2D; typedef struct { GLuint drawType; GLfloat rotAng; GLfloat scalx; GLfloat scaly; GLfloat tranx; GLfloat trany; GLfloat R; GLfloat G; GLfloat B; GLfloat A; } SpecStruct; /*** function prototypes ***/ void drawVerts(GLuint drawType, const Vec2D verts[], int numVerts); void drawPoints (const Vec2D pts[], int numPts); void drawPolyline (const Vec2D pts[], int numPts); void drawPolygon (const Vec2D pts[], int numPts); int readVertFile (const char* fileName, Vec2D* verts); int readOneVert (FILE* inFile, Vec2D* v); int readOneSpec(FILE* inFile, SpecStruct* spec); int readSpecs(const char* fileName, SpecStruct* specs); #endif
C
/* !!DESCRIPTION!! !!ORIGIN!! testsuite !!LICENCE!! Public Domain !!AUTHOR!! */ #define OUTFILE "cc65080328.out" #define THISFILE "cc65080328" /* always include this _after_ the above macros have been defined */ #include "testsuite.h" /* The following code produces an 'Error: Incompatible pointer types' at the last line when compiling with snapshot-2.11.9.20080316 without optimizations. If I remove the struct inside f() it compiles fine ?!? Best, Oliver */ void f(void){struct{int i;}d;} struct{void(*p)(void);}s={f}; int main(void) { OPENTEST(); fprintf(outfile,"it works :)\n"); CLOSETEST(); /* always return OK */ return (0); }
C
#include <stdio.h> int main(void) { int size; do { printf("Inserisci la dimensione delle aste, dispari e non negativa: "); scanf("%i", &size); } while (size < 0 || size % 2 == 0); int x, y; for (y = 0; y < size; y++) { for (x = 0; x < size; x++) printf("%c", (x == size / 2 || y == size / 2) ? '*' : ' '); printf("\n"); } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include "queue.h" #include "list.h" struct node; struct Queue *queue_create(void) { struct Queue *q = malloc(sizeof(*q)); if (q == NULL) { return NULL; } q->first = NULL; q->last = NULL; return q; } /** * adds an element to the end of the queue. * returns - 0 on success; -1 on failure. */ int queue_enqueue(struct Queue *q, void *e) { struct node *n = malloc(sizeof(*n)); if (n == NULL) { return -1; } n->next = NULL; n->value = e; if (q->first == NULL || q->last == NULL) { q->first = n; q->last = n; } else { q->last->next = n; q->last = n; } return 0; } /** * removes an element from the beginning of the queue */ struct node *queue_dequeue(struct Queue *q) { struct node *n = q->first; if (q->first) q->first = q->first->next; if (q->first == NULL) q->last = NULL; return n; } /** * retrieves the element first in the queue */ struct node *queue_peek(struct Queue *q) { return q->first; } bool queue_is_empty(struct Queue *q) { return q->first == NULL; } int queue_destroy(struct Queue *q) { node *n = queue_dequeue(q); while (n != NULL) { free(n); n = queue_dequeue(q); } free(q); return 0; }
C
/* ** OCTAL ASCII TO INTEGER CONVERSION ** ** The ascii string 'a' which represents an octal number ** is converted to binary and returned. Conversion stops at any ** non-octal digit. ** ** Note that the number may not have a sign, and may not have ** leading blanks. ** ** (Intended for converting the status codes in users(FILE)) */ AA_oatoi(a) register char *a; { register int r; register int c; r = 0; while ((c = *a++) >= '0' && c <= '7') r = (r << 3) | (c &= 7); return (r); }
C
#include<stdio.h> #include<math.h> void raiz4(){ printf("A raiz quadrada de %d é %.0f\n", 4, sqrt(4)); } void raiz9(){ printf("A raiz quadrada de %d é %.0f\n", 9, sqrt(9)); } void raiz25(){ printf("A raiz quadrada de %d é %.0f\n", 25, sqrt(25)); } void raiz41(){ printf("A raiz quadrada de %d é %.0f\n", 41, sqrt(41)); printf("A raiz quadrada de %d é %.4f\n", 41, sqrt(41)); } void raizquadrada(int numero){ printf("A raiz quadrada de %d é %.4f\n", numero, sqrt(numero)); } void raizquadrada2(){ int numero; printf("Digite um número para calcular a raiz quadrada: \n"); scanf("%d", &numero); printf("A raiz quadrada de %d é %.4f\n", numero, sqrt(numero)); } int main(){ // printf("A soma entre %d e %d é: %d\n"); // printf("A soma entre %d e %d é: %d\n", 3, 5, 35); printf("A soma entre %d e %d é: %d\n", 3, 5, 3+5); // printf("A raiz quadrada de %d é %.0f\n", 4, sqrt(4)); // printf("A raiz quadrada de %d é %.0f\n", 9, sqrt(9)); // printf("A raiz quadrada de %d é %.0f\n", 25, sqrt(25)); raiz4(); raiz9(); raiz25(); raiz41(); raizquadrada(81); raizquadrada2(); return 0; } // ## Para compilar com a biblioteca math.h usar -lm ao final da expressão // gcc 20180206.c -o 20180206 -lm // https://www.w3resource.com/c-programming-exercises/basic-declarations-and-expressions/index.php // http://linguagemc.com.br/a-biblioteca-math-h/
C
#include<stdio.h> int main() { long int t,i; scanf("%ld",&t); for(i=1;i<=t;i++) { long long int n, reversedInteger = 0, remainder, originalInteger; scanf("%lld", &n); originalInteger = n; while( n!=0 ) { remainder = n%10; reversedInteger = reversedInteger*10 + remainder; n /= 10; } if (originalInteger == reversedInteger) printf("Case %d:Yes\n",i); else printf("Case %d:No\n",i); } return 0; }
C
#include "map.h" #include <stdlib.h> #include <string.h> /* Based on rxi's type-safe hashmap implementation */ /** * Copyright (c) 2014 rxi * * This library is free software; you can redistribute it and/or modify it * under the terms of the MIT license. See LICENSE for details. */ typedef struct edgex_map_node { unsigned hash; void *value; edgex_map_node *next; } edgex_map_node; static unsigned edgex_hash (const char *str) { unsigned hash = 5381u; while (*str) { hash = ((hash << 5) + hash) ^ *str++; } return hash; } static edgex_map_node *edgex_map_newnode (const char *key, void *value, int vsize) { edgex_map_node *node; int ksize = strlen (key) + 1; int voffset = ksize + ((sizeof (void *) - ksize) % sizeof (void *)); node = malloc (sizeof (*node) + voffset + vsize); if (!node) { return NULL; } memcpy (node + 1, key, ksize); node->hash = edgex_hash (key); node->value = ((char *) (node + 1)) + voffset; memcpy (node->value, value, vsize); return node; } static int edgex_map_bucketidx (edgex_map_base *m, unsigned hash) { /* If the implementation is changed to allow a non-power-of-2 bucket count, * the line below should be changed to use mod instead of AND */ return hash & (m->nbuckets - 1); } static void edgex_map_addnode (edgex_map_base *m, edgex_map_node *node) { int n = edgex_map_bucketidx (m, node->hash); node->next = m->buckets[n]; m->buckets[n] = node; } static int edgex_map_resize (edgex_map_base *m, int nbuckets) { edgex_map_node *nodes, *node, *next; edgex_map_node **buckets; int i; /* Chain all nodes together */ nodes = NULL; i = m->nbuckets; while (i--) { node = (m->buckets)[i]; while (node) { next = node->next; node->next = nodes; nodes = node; node = next; } } /* Reset buckets */ buckets = realloc (m->buckets, sizeof (*m->buckets) * nbuckets); if (buckets != NULL) { m->buckets = buckets; m->nbuckets = nbuckets; } if (m->buckets) { memset (m->buckets, 0, sizeof (*m->buckets) * m->nbuckets); /* Re-add nodes to buckets */ node = nodes; while (node) { next = node->next; edgex_map_addnode (m, node); node = next; } } /* Return error code if realloc() failed */ return (buckets == NULL) ? -1 : 0; } static edgex_map_node **edgex_map_getref (edgex_map_base *m, const char *key) { unsigned hash = edgex_hash (key); if (m->nbuckets > 0) { edgex_map_node **next = &m->buckets[edgex_map_bucketidx (m, hash)]; while (*next) { if ((*next)->hash == hash && !strcmp ((char *) (*next + 1), key)) { return next; } next = &(*next)->next; } } return NULL; } void edgex_map_deinit_ (edgex_map_base *m) { edgex_map_node *next, *node; int i; i = m->nbuckets; while (i--) { node = m->buckets[i]; while (node) { next = node->next; free (node); node = next; } } free (m->buckets); } void *edgex_map_get_ (edgex_map_base *m, const char *key) { edgex_map_node **next = edgex_map_getref (m, key); return next ? (*next)->value : NULL; } int edgex_map_set_ (edgex_map_base *m, const char *key, void *value, int vsize) { int n, err; edgex_map_node **next, *node; /* Find & replace existing node */ next = edgex_map_getref (m, key); if (next) { memcpy ((*next)->value, value, vsize); return 0; } /* Add new node */ node = edgex_map_newnode (key, value, vsize); if (node == NULL) { goto fail; } if (m->nnodes >= m->nbuckets) { n = (m->nbuckets > 0) ? (m->nbuckets << 1) : 1; err = edgex_map_resize (m, n); if (err) { goto fail; } } edgex_map_addnode (m, node); m->nnodes++; return 0; fail: if (node) { free (node); } return -1; } void edgex_map_remove_ (edgex_map_base *m, const char *key) { edgex_map_node **next = edgex_map_getref (m, key); if (next) { edgex_map_node *node = *next; *next = (*next)->next; free (node); m->nnodes--; } } edgex_map_iter edgex_map_iter_ (void) { edgex_map_iter iter; iter.bucketidx = -1; iter.node = NULL; return iter; } const char *edgex_map_next_ (edgex_map_base *m, edgex_map_iter *iter) { if (iter->node) { iter->node = iter->node->next; if (iter->node == NULL) { goto nextBucket; } } else { nextBucket: do { if (++iter->bucketidx >= m->nbuckets) { return NULL; } iter->node = m->buckets[iter->bucketidx]; } while (iter->node == NULL); } return (char *) (iter->node + 1); }
C
#include <stdio.h> /* what is in the function */ struct CharacterSet{ char name[12]; char race[12]; int attack; int defense; }; struct CharacterSet createCharacter(){ struct CharacterSet aCharacter; /* make me a new one */ printf("Enter character's name: "); scanf("%s", aCharacter.name); printf("Enter charactere's race: "); scanf("%s", aCharacter.race); printf("Now choose the strength of our character. Your attack and defense score cannot be greater than 10.\n"); printf("Enter attack: "); scanf("%d", &aCharacter.attack); printf("Enter defense: "); scanf("%d", &aCharacter.defense); printf("%s is %s and has an attack of %d and a defense of %d.\n", aCharacter.name, aCharacter.race, aCharacter.attack, aCharacter.defense); /* Checking the variables before the function */ int sum = aCharacter.attack + aCharacter.defense; while(sum > 10){ printf("Oops. There’s a problem. The sum of your attack and defense points is greater than 10. Please try again.\n"); printf("Enter attack: "); scanf("%d", &aCharacter.attack); printf("Enter defense: "); scanf("%d", &aCharacter.defense); printf("%s is %s and has an attack of %d and a defense of %d.\n", aCharacter.name, aCharacter.race, aCharacter.attack, aCharacter.defense); sum = aCharacter.attack + aCharacter.defense; } return aCharacter; } int main(){ struct CharacterSet aCharacter = createCharacter(); return 0; }
C
/* Copyright (c) 2011-2012 Hiroshi Tsubokawa See LICENSE and README */ #include "Tiler.h" #include "Vector.h" #include "Numeric.h" #include <stdlib.h> #include <assert.h> struct Tiler { int i; int total_ntiles; int xntiles, yntiles; struct Tile *tiles; int xres, yres; int xtile_size, ytile_size; }; struct Tiler *TlrNew(int xres, int yres, int xtile_size, int ytile_size) { struct Tiler *tiler; tiler = (struct Tiler *) malloc(sizeof(struct Tiler)); if (tiler == NULL) return NULL; tiler->i = 0; tiler->total_ntiles = 0; tiler->xntiles = 0; tiler->yntiles = 0; tiler->tiles = NULL; assert(xres > 0); assert(yres > 0); assert(xtile_size > 0); assert(ytile_size > 0); tiler->xres = xres; tiler->yres = yres; tiler->xtile_size = xtile_size; tiler->ytile_size = ytile_size; return tiler; } void TlrFree(struct Tiler *tiler) { if (tiler == NULL) return; if (tiler->tiles != NULL) free(tiler->tiles); free(tiler); } int TlrGetTileCount(const struct Tiler *tiler) { return tiler->total_ntiles; } struct Tile *TlrGetNextTile(struct Tiler *tiler) { struct Tile *t; if (tiler->i >= TlrGetTileCount(tiler)) return NULL; t = tiler->tiles + tiler->i; tiler->i++; return t; } int TlrGenerateTiles(struct Tiler *tiler, int xmin, int ymin, int xmax, int ymax) { int id; int x, y; int xntiles; int yntiles; int total_ntiles; struct Tile *tiles, *tile; const int xres = tiler->xres; const int yres = tiler->yres; const int xtile_size = tiler->xtile_size; const int ytile_size = tiler->ytile_size; const int XMIN = (int) floor(MAX(0, xmin) / (double) xtile_size); const int YMIN = (int) floor(MAX(0, ymin) / (double) ytile_size); const int XMAX = (int) ceil(MIN(xres, xmax) / (double) xtile_size); const int YMAX = (int) ceil(MIN(yres, ymax) / (double) ytile_size); xntiles = XMAX - XMIN; yntiles = YMAX - YMIN; assert(xmin < xmax); assert(ymin < ymax); if (tiler->tiles != NULL) { free(tiler->tiles); } total_ntiles = xntiles * yntiles; tiles = (struct Tile *) malloc(sizeof(struct Tile) * total_ntiles); if (tiles == NULL) { return -1; } tile = tiles; id = 0; for (y = YMIN; y < YMAX; y++) { for (x = XMIN; x < XMAX; x++) { tile->id = id; tile->xmin = x * xtile_size; tile->ymin = y * ytile_size; tile->xmin = MAX(tile->xmin, xmin); tile->ymin = MAX(tile->ymin, ymin); tile->xmax = (x + 1) * xtile_size; tile->ymax = (y + 1) * ytile_size; tile->xmax = MIN(tile->xmax, xmax); tile->ymax = MIN(tile->ymax, ymax); tile++; id++; } } tiler->i = 0; tiler->total_ntiles = total_ntiles; tiler->xntiles = xntiles; tiler->yntiles = yntiles; tiler->tiles = tiles; return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <termios.h> #include <signal.h> #define DEVNAME "/dev/iommap" #define MAPSIZE 0x1000000 #define OFFSET 0x0FFFFF0 int main(int argc, char *argv[]) { int mem_fd,i=0; void *uio; unsigned char *pVaddr; mem_fd=open(DEVNAME,O_RDWR|O_SYNC); if (mem_fd <0) { printf("open device error\n"); return -1; } uio=(unsigned char *)mmap(NULL,MAPSIZE, PROT_READ | PROT_WRITE, MAP_SHARED,mem_fd, 0); if (uio == MAP_FAILED) { printf("iommap == MAP_FAILED \n"); close(mem_fd); exit(-1); } printf("iommap virtual addr = %p \n",uio); pVaddr = (unsigned char*)uio; //memset(uio,0,sizeof(unsigned char)*0xF000); for(i=0; i< 30 ; i++) { printf("iommap offset %02d, value = 0x%02lx \n",i,*(unsigned char*)(pVaddr+i+OFFSET)); } munmap(uio, MAPSIZE); close(mem_fd); return 0; }
C
#include <stdio.h> void main(){ int S; float FA; printf("\nCuantos sonidos por minuto emite su termo-grillo?: "); scanf("%d",&S); FA = S/4+40; printf("\nLa temperatura es de: %4.2f grados farenheit",FA); }
C
/* ** EPITECH PROJECT, 2019 ** my_runner_2019 ** File description: ** map object */ #include "my_runner.h" #include "map.h" extern const int NB_TYPE_BLOCK; extern const int BLOCK_SIZE; static void map_destroy(map_t *map) { map->parallax.destroy(&map->parallax); if (map->buffer != NULL) { free(map->buffer); } for (int i = 0; i < NB_TYPE_BLOCK; i++) { map->type_block[i]->destroy(map->type_block[i]); } free(map->type_block); for (int x = 0; x < map->width; x++) free(map->map[x]); free(map->map); } static map_t *map_display(window_t *w) { w->game.map.parallax.display(&w->game.map.parallax, w->window); map_show_map(w); return (&w->game.map); } map_t *map_reload(window_t *w) { char *file_name = w->game.map.file_name; map_destroy(&w->game.map); map_create(w, file_name); return (&w->game.map); } map_t *map_create(window_t *w, char *file_name) { w->game.map.destroy = &map_destroy; w->game.map.display = &map_display; w->game.map.get_typeblock = &map_get_typeblock; w->game.map.file_name = file_name; w->game.map.block_size = BLOCK_SIZE; w->game.map.buffer = NULL; w->game.map.height = 0; w->game.map.width = 0; w->game.map.nb_disp_cols = w->width / w->game.map.block_size + 1; w->game.map.nb_disp_rows = w->width / w->game.map.block_size + 1; if (map_load_from_file(&w->game.map) == EXIT_ERROR) return NULL; if (w->game.map.width < w->game.map.nb_disp_cols) w->game.map.nb_disp_cols = w->game.map.width; if (w->game.map.height < w->game.map.nb_disp_rows) w->game.map.nb_disp_rows = w->game.map.height; parallax_create(w, &w->game.map.parallax, w->width); return (&w->game.map); }
C
/* poj 1067 取石子游戏 */ #include <stdio.h> #include <math.h> int main() { double _sqrt5 = sqrt(5.0); int a, b, k, ak, bk, ak_1, bk_1; while (2 == scanf("%d %d", &a, &b)) { if (a > b) { k = a; a = b; b = k; /* a = a ^ b; b = a ^ b; a = a ^ b; */ /* a ^= b; b ^= a;a ^= b; */ } k = (int)(a*2/(1+_sqrt5)); ak = (int)(k*(1+_sqrt5)/2); bk = ak + k; ak_1 = (int)((k+1)*(1+_sqrt5)/2); bk_1 = ak_1 + k+1; printf("%d\n", !((a == ak_1 && b == bk_1) || (a == ak && b == bk))); } return 0; }
C
/* This program takes two inputs from the user and checks every value in between those two numbers, including the numbers itself. The program checks whether each value is a semiprime, meaning whether that number is a product of two prime numbers, or not by determining whether the number and its prime factor are both prime numbers. The values that are semiprime are printed onto the screen. partners: ipatel28 */ #include <stdlib.h> #include <stdio.h> /* Declaration of functions */ int is_prime(int number); int print_semiprimes(int a, int b); /* The main function takes two inputs from the user and executes the functions */ int main(){ int a, b; printf("Input two numbers: "); scanf("%d %d", &a, &b); if( a <= 0 || b <= 0 ){ printf("Inputs should be positive integers\n"); return 1; } if( a > b ){ printf("The first number should be smaller than or equal to the second number\n"); return 1; } print_semiprimes(a,b); // TODO: call the print_semiprimes function to print semiprimes in [a,b] (including a and b) } /* * TODO: implement this function to check the number is prime or not. * Input : a number * Return : 0 if the number is not prime, else 1 */ /* Takes an input and calculates whether that integer is a prime integer or not by checking values from 2 to the given integer and calculating their remainders */ int is_prime(int number) { int c; if(number == 2) { c = 1; return c; } if(number == 1 || number == 0) { c = 0; return c; } for(int i = 2; i < number; i++) { if(number % i == 0) { c = 0; break; } else { c = 1; } } return c; } /* * TODO: implement this function to print all semiprimes in [a,b] (including a, b). * Input : a, b (a should be smaller than or equal to b) * Return : 0 if there is no semiprime in [a,b], else 1 */ /* Checks whether the every value between the two input variables to determine whether they are semiprime numbers or not. This is done by calling the is_prime function. */ int print_semiprimes(int a, int b) { int d = 0; for(int n = a; n <= b; n++) { for(int k = 2; k <= n-1; k++) { if(n % k == 0 && is_prime(k) == 1 && is_prime(n/k) == 1) { printf("%d ", n); d = 1; break; } } } return d; }
C
// // main.c // square // // Created by choihyunill on 2016. 3. 26.. // Copyright © 2016년 choihyunill. All rights reserved. // #include <stdio.h> int main(int argc, const char * argv[]) { int n; int i,k; printf("출력 라인의 수"); scanf("%d",&n); for(k=0;k<n; k++) { for(i=0;i<n;i++) { putchar('*'); } putchar('\n'); } return 0; }
C
#include <stdio.h> #include "watchdog.h" static void dump_watchdog_info(struct wdinfo *info) { printf("Device:\t\t%s\n", WATCHDOG_PATHNAME); printf("Identity:\t%s [version %d]\n", info->identity, info->firmware_version); printf("Timeout: \t%d seconds\n", info->timeout); printf("Pre-timeout: \t%d seconds\n", info->pretimeout); printf("Timeleft: \t%d seconds\n", info->timeleft); printf("Last boot: \t%s\n", (info->bootstatus != 0) ? "Watchdog" : "Power-On-Reset"); } int main() { struct wdinfo info; if (wd_getinfo(&info) == -1) { printf("wd_getinfo() failed\n"); return -1; } dump_watchdog_info(&info); return 0; }
C
#ifndef HOLBERTON_H #define HOLBERTON_H #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <math.h> /** * struct complex_t - doubles struct * @rn: real num * @in: img num */ typedef struct complex_t { double rn; double in; } complex; void display_complex_number(complex c); complex conjugate(complex c); double modulus(complex c); double argument(complex c); void addition(complex c1, complex c2, complex *c3); void substraction(complex c1, complex c2, complex *c3); void multiplication(complex c1, complex c2, complex *c3); void division(complex c1, complex c2, complex *c3); void complex_from_mod_arg (double m, double arg, complex *c3); #endif
C
#include <stdio.h> #include<math.h> int main() { double a,b,c,det; double realPart,imagPart; float root1,root2; printf("Enter the coordinates a,b,c : "); scanf("%lf%lf%lf",&a,&b,&c ); det= b*b - 4 * a * c ; if(det<0) { realPart =-b/(2*a); imagPart =sqrt(-det)/(2*a); printf("the roots are imaginary\n"); printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart, imagPart); } else if(det==0) { root1 = -b/2*a; printf("the roots are real and equal=%.2lf",root1); } else { root1=(-b+sqrt(det))/2*a; root2=(-b-sqrt(det))/2*a; printf("roots of the equation = %.2lf and %.2lf",root1,root2); } return 0; }
C
/* Author: Mark Vincent * Partner(s) Name: NA * Lab Section: A01 * Assignment: Lab #6 Exercise #3 * Youtube Link: https://youtu.be/MxQY58C0p2s * Exercise Description: * * Take an old lab an add a timer to it. * * I acknowledge all content contained herein, excluding template or example * code, is my own original work. */ #include <avr/io.h> #ifdef _SIMULATE_ #include "simAVRHeader.h" #include "timer.h" #endif // States ie, {Start, Init, ... etc} enum States{start, init, off, on} state; // Globals unsigned int tmpA = 0x00; unsigned int tmpC = 0x00; unsigned int b1count = 0x00; unsigned int b2count = 0x00; enum Flags{button1, button2, both, stillOn1, stillOn2, stillOn3, none} flag; // tick function void tick() { // READ INPUT tmpA = ~PINA & 0xFF; // Transitions switch(state) { case start: state = init; break; case init: // Check where to go next if (tmpA == 0x00) { // goes to OFF, with flag set to none flag = none; state = off; } else if (tmpA == 0x01) { // goes to ON, with flag set to button1 flag = button1; state = on; // inits b1counter to 0 b1count = 0; } else if (tmpA == 0x02) { // goes to ON, with flag set to button2 flag = button2; state = on; // inits b2counter to 0 b2count = 0; } else if (tmpA == 0x03) { // goes to ON, with flag set to both. flag = both; state = on; } break; case off: // Check where to go next if (tmpA == 0x00) { // goes to OFF, with flag set to none flag = none; state = off; } else if (tmpA == 0x01) { // goes to ON, with flag set to button1 flag = button1; state = on; b1count = 0; } else if (tmpA == 0x02) { // goes to ON, with flag set to button2 flag = button2; state = on; b2count = 0; } else if (tmpA == 0x03) { // goes to ON, with flag set to both. flag = both; state = on; } break; case on: // Check where to go next if (tmpA == 0x00) { // goes to OFF, with flag set to none flag = none; state = off; // resets both counts b1count = 0; b2count = 0; } else if (tmpA == 0x01) { // goes to ON, with flag set to button1 if (flag == stillOn1) { // increment b1count b1count = b1count + 1; } else { flag = button1; state = on; } } else if (tmpA == 0x02) { // goes to ON, with flag set to button2 if (flag == stillOn2) { // nothing b2count = b2count + 1; } else { flag = button2; state = on; } } else if (tmpA == 0x03) { // goes to ON, with flag set to both. if (flag == stillOn3) { // nothing } else { flag = both; state = on; } } break; default: state = start; break; } // Actions switch(state) { case start: break; case init: // Sets output to 7 and writes. tmpC = 0x07; PORTC = tmpC; break; case off: // Decides whether to increment, decrement or nothing if (flag == none) { // Does nothing. } else { // shouldn't be able to get here. } break; case on: // increments or decrements if counts are right values if ((b1count == 10) && (tmpC < 9)) { b1count = 0; tmpC = tmpC + 1; flag = stillOn1; } else if ((b2count == 10) && (tmpC > 0)) { b2count = 0; tmpC = tmpC - 1; flag = stillOn2; } else { // does nothing } // Decides whether to increment, decrement or nothing if (flag == button1) { // Does a increment on PORTC by 1 if PORTC < 9. if (tmpC < 9) { // Does increment tmpC = tmpC + 1; flag = stillOn1; } else { // Does nothing } } else if (flag == button2) { // Does a decrement on PORTC by 1 if PORTC > 0. if (tmpC > 0) { // Does decrement tmpC = tmpC - 1; flag = stillOn2; } else { // Does nothing } } else if (flag == both) { // Resets tmpC to 0x00 tmpC = 0x00; flag = stillOn3; } else { // does nothing } // writes output PORTC = tmpC; break; default: break; } } // Main Function using timer.h header int main(void) { // PORTS DDRA = 0x00; PORTA = 0xFF; // Configure PORTA as input DDRC = 0xFF; PORTC = 0x00; // Configure PORTC as output // Sets timer to 100ms, and on TimerSet(100); TimerOn(); // init state and output state = start; PORTC = 0x00; /* Insert your solution below */ while (1) { // tick tick(); // wait 1 sec while (!TimerFlag); TimerFlag = 0; } return 1; }
C
#include<stdio.h> #pragma warning(disable:4996) typedef struct { int tanka; int suryou; int kingaku; int zeikomi; int zei; }ren02; int main() { ren02 r = {0}; printf("P\n"); scanf("%d", &r.tanka); printf("ʂ\n"); scanf("%d", &r.suryou); r.kingaku = r.tanka*r.suryou; r.zei = r.kingaku*0.08; r.zeikomi = r.kingaku+r.zei; printf("vz:%d\nō݋z:%d\n", r.kingaku, r.zeikomi); return 0; }
C
#include <stdio.h> int main(void) { int average; int grades[3]; grades[0] = 80; grades[1] = 80; grades[2] = 75; average = (grades[0] + grades[1] + grades[2])/3; printf("The average of the 3 grades is: %d", average); return 0; }
C
/* * value_exception.c * Calculator * * Created by Michael Dickens on 7/13/10. * */ #include "value.h" exception exception_init(exception *parent, char *name) { exception res; res.parent = parent; res.name = value_malloc(NULL, strlen(name) + 1); if (res.name) strcpy(res.name, name); res.description = NULL; res.stack_trace = NULL; return res; } value value_throw(exception op, char *description) { value exc; exc.core.u_exc = op; value res = value_set(exc); if (res.core.u_exc.description)value_free(res.core.u_exc.description); res.core.u_exc.description = value_malloc(NULL, strlen(description) + 1); return_if_null(res.core.u_exc.description); strcpy(res.core.u_exc.description, description); return res; }
C
/******************************************************************************************************** * * Title : bubble_sort.c * Description : Bubble Sort ALgorithm * Author : Aniruth Oblah * * * Revision History: * ___________________________________________________________________________________ * * Number Date Name Comment * ___________________________________________________________________________________ * * 1. Feb 3, 2017 Aniruth Oblah Initial * * * ***********************************************************************************************************/ #include <stdio.h> #include <stdbool.h> #define ARRAY_SIZE 10 //Function Declaration void bubble_sort(int []); void display_array(int []); //Main Function int main(){ //Initializing random integer array of size 10 int A[ARRAY_SIZE] = {15,4,6,2,7,8,44,1,9,3}; bubble_sort(A); return 0; } // Bubble sort Function void bubble_sort(int A[]){ //Initializing other integers int temp, i, j = 0; //Initializing boolean character to check if swapping is done bool swapped = false; //Printin the unsorted array printf("Inital Array :\n"); display_array(A); printf("\n"); // Bubble sort mechanism for (i = 0; i < ARRAY_SIZE-1; i++){ swapped = false; for (j = 0; j < ARRAY_SIZE-1-i; j++){ if(A[j] > A[j+1]){ temp = A[j]; A[j] = A[j+1]; A[j+1] = temp; swapped = true; } } // If no swapping is done, it means array is sorted and it breaks out of the loop if (swapped == false){ break; } } //Printin the sorted array printf("Sorted Array :\n"); display_array(A); printf("\n"); } // Display Array void display_array(int A[]){ for (int i = 0; i < ARRAY_SIZE; i++){ printf("%d\t",A[i]); } printf("\n"); }
C
/********************************************************************************************* * Description:一些笔试中会编写的测试程序 * name:merlin time:2017-11-30 * *******************************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> /*brif:删除字符串中的空格,返回空格的数目*/ int strDBlank(char*pStr) { int count = 0; char *ptemp = pStr; while (*pStr != '\0') { if (*pStr != ' '){ *ptemp++ = *pStr; } else{ count++; } ++pStr; } *ptemp = '\0'; return count; } /* brief:冒泡排序(一次比较两个相邻的元素,如果他们的顺序错误就将它们交换过来 n2) */ int bubble_sort(int *data, int n){ int i = 0, j = 0, temp = 0; for(i=0; i<n-1; i++){ for(j=0; j<n-1-i; j++){ if(data[j]>data[j+1]){ temp = data[j]; data[j] = data[j+1]; data[j+1] = temp; } } } return 0; } /* brief:选择排序(从等待排序数据中找到最大或是最小的的那个数放到首位 n2) */ int select_sort(int *data, int n){ int i = 0, j = 0, min = 0, temp = 0; for(i=0; i<n-1; i++){ min = i; for(j=i+1; j<n; j++){ if(data[min]>data[j]){ /*升序*/ //if(data[min]<data[j]){ /*降序*/ min = j; } } if(min!= i){ temp = data[min]; data[min] = data[i]; data[i] = temp; } } return 0; } /*brif:快速排序*/ void first_sort(int *a, int left, int right) { if(left >= right){ return ; } int i = left; int j = right; int key = a[left]; while(i < j) /*控制在当组内寻找一遍*/ { while(i < j && key <= a[j]){ j--; } a[i] = a[j]; while(i < j && key >= a[i]){ i++; } a[j] = a[i]; } a[i] = key; first_sort(a, left, i - 1); first_sort(a, i + 1, right); } /*brief:比较两个字符串,0-相等 1-str1>str2 -1-str1<str2*/ int mystrcmp(unsigned char *str1, unsigned char *str2){ int ret = 0; while(!(ret = (*str1) - (*str2)) && (*str2)){ ++str1; ++str2; } if(0<ret) return 1; else if(0>ret) return -1; else return 0; return 0; } /*brief:找出两个字符串中的公共子串*/ //int getComStr(char *s1, char *s2, char **r1, char **r2){ int getComStr(char *s1, char *s2, char *dest){ int len1 = strlen(s1); int len2 = strlen(s2); int maxlen = 0, i = 0, j = 0; char temp[64] = {0}; printf("len1=%d len2=%d\n", len1, len2); for(i=0; i<len1; i++){ for(j=0; j<len2; j++){ if((s1[i]) == (s2[j])){ int as = i, bs = j, count = 1; while((as+1<len1) && (bs+1<len2) && (s1[++as]==s2[++bs])){ count++; } if(count>maxlen){ maxlen = count; memcpy(temp, &s1[i], count); printf("s1=%s s2=%s temp=%s count=%d \n", s1, s2, temp, count); //*r1 = s1 + i; //*r2 = s2 + j; } } } } return 0; } /*brief:或是一段数据 (二级指针的使用)*/ int getMemmory(char **pDest, int num){ *pDest = (char *)malloc(num*sizeof(char)); if(NULL == (*pDest)){ return -1; } sprintf((*pDest), "%s", "hello world"); return 0; } int main(int argc, const char *argv[]) { #if 1 char *pstr = NULL; int ret = getMemmory(&pstr, 64); printf("ret=%d pstr=%s\n", ret, pstr); free(pstr); sprintf(pstr, "%s", "kkkkkkk"); printf("ret=%d pstr=%s\n", ret, pstr); #endif #if 0 char str1[32] = {"helloAhhhhhhhhhbsdsg"}, str2[32] = {"helloBhhhhhhhhhh"}; char dstr1[32] = {0}, dstr2[32] = {0}; char *p1 = NULL, *p2 = NULL; getComStr(str2, str1, dstr1); printf("str1=%s str2=%s p1=%s p2=%s\n", str1, str2, p1, p2); //printf("ret=%d\n", mystrcmp(str1, str2)); #endif #if 0 int ret = 0; char str[] = {"1 2 3 4 5 6 7"}; printf("[%s]:str=%s line:%d\n", __func__, str, __LINE__); ret = strDBlank(str); printf("[%s]:ret=%d str=%s line:%d\n", __func__, ret, str, __LINE__); #endif #if 0 int i = 0; int data[6] = {6, 1, 5, 3, 1, 2}; //bubble_sort(data, 6); //select_sort(data, 6); first_sort(data, 0, 5); for(i=0; i<6; i++){ printf("%d ", data[i]); } printf("\n"); return 0; #endif return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> int main() { int a; scanf("%d", &a); int i, sum = 0, tmp = a; for (i = 1; i <= 5; ++i) { tmp = tmp * 10 + a; sum += tmp; } printf("%d", sum); system("pause"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_putstr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: msharpe <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/12/05 22:42:31 by msharpe #+# #+# */ /* Updated: 2018/02/05 00:33:06 by msharpe ### ########.fr */ /* */ /* ************************************************************************** */ #include "libftprintf.h" static void p_suite(char const *s, t_inputinfo *info, t_passinfo *pass, int i) { while (s + i != NULL && *(s + i) != '\0' && info->p < info->precision) { ft_putchar(*(s + i)); i++; info->p++; pass->final_count++; } while (i < pass->width - 1) { ft_putchar(' '); i++; pass->final_count++; } } void ft_putstr(char const *s, t_inputinfo *info, t_passinfo *pass) { int i; int q; i = 0; if (s == NULL) { write(1, "(null)", 6); return ; } pass->strlen = ft_strlen(s); info->f = 0; if (info->precision == 0) ft_putstrup(s, info, pass); else if (info->precision > 0) p_suite(s, info, pass, i); if ((q = ft_strstr((info->flag), "-")) && q == 1) ft_flag_minus(*s, info, pass); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> /* 入力した文字列が数値のみで構成されているか確認する*/ int isdigits(char *str){ int result = 0; for(int i = 0; i < strlen(str); i++){ if(isdigit(str[i])){ result++; }else{ result = 0; break; } } return result; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jschotte <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/12/10 12:54:27 by jschotte #+# #+# */ /* Updated: 2015/12/18 15:45:33 by jschotte ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" char *ft_letter(char *str, char c) { int i; i = 0; while (str[i]) { if (str[i] == '#') str[i] = c; i++; } return (str); } char *ft_fillmap(char *map, int nb) { int i; int j; i = 0; j = 0; while (i < nb * nb + nb) { map[i] = '.'; i++; j++; if (j == nb) { map[i] = '\n'; j = 0; i++; } } map[i] = '\0'; return (map); } void ft_printmap(char *map) { int i; i = 0; while (map[i]) { ft_putchar(map[i]); i++; } } char *ft_canplace(char *map, char *piece, int index, int nb) { int i; size_t k; int line; i = 0; k = index; line = 0; while (piece[i]) { if ((map[k] == '.' || (ft_isalpha(map[k]) && piece[i] == '.'))) { i++; k++; if (piece[i] == '\n') { line++; i++; k = index + (nb + 1) * line; } } else return (0); } return (map); } char *ft_place(char *map, char *piece, int index, int nb) { int i; int k; int line; i = 0; k = index; line = 0; while (piece[i] && map[k]) { if (map[k] == '.' || (ft_isalpha(map[k]) && piece[i] == '.')) { if (map[k] == '.') map[k] = piece[i]; i++; k++; if (piece[i] == '\n') { line++; i++; k = index + (nb + 1) * line; } } } return (map); }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include "table.h" struct slot { int id; struct object *obj; int next; }; struct table { int size; int lastfree; struct slot *slot; }; void rehash(struct table *t) { struct slot *oslot = t->slot; int osize = t->size; t->size = 2 * osize; t->lastfree = t->size - 1; t->slot = malloc(t->size * sizeof(struct slot)); int i; for (i = 0; i < t->size; i++) { struct slot *s = &t->slot[i]; s->id = -1; s->obj = NULL; s->next = -1; } for (i = 0; i < osize; i++) { struct slot * s = &oslot[i]; if (s->obj) table_insert(t, s->id, s->obj); } free(oslot); } struct table* table_create() { struct table *t = malloc(sizeof(*t)); t->size = 64; t->lastfree = t->size - 1; t->slot = malloc(t->size * sizeof(struct slot)); int i = 0; for(;i < t->size;++i) { struct slot *s = &t->slot[i]; s->id = -1; s->obj = 0; s->next = -1; } return t; } void table_release(struct table *t) { free(t->slot); free(t); } struct slot* mainposition(struct table *t,int id) { int hash = id & (t->size - 1); return &t->slot[hash]; } void table_insert(struct table *t,int id,struct object *obj) { struct slot *s = mainposition(t,id); if (s->obj == NULL) { s->id = id; s->obj = obj; return; } if (mainposition(t,s->id) != s) { struct slot *last = mainposition(t,s->id); while (last->next != s-t->slot) { last = &t->slot[last->next]; } int temp_id = s->id; struct object *temp_obj = s->obj; last->next = s->next; s->id = id; s->obj = obj; s->next = -1; if (temp_obj) table_insert(t,temp_id,temp_obj); return; } while(t->lastfree >= 0) { struct slot *tmp = &t->slot[t->lastfree--]; if (tmp->id == -1 && tmp->next != -1) { tmp->id = id; tmp->obj = obj; tmp->next = s->next; s->next = (int)(tmp-t->slot); return; } } rehash(t); } struct object* table_delete(struct table *t,int id) { int hash = id & (t->size-1); struct slot *s = &t->slot[hash]; struct slot *next = s; for(;;) { if (next->id == id) { struct object *obj = next->obj; next->obj = NULL; if (next != s) { s->next = next->next; next->next = -1; if (t->lastfree < next - t->slot) t->lastfree = next - t->slot; } else { if (next->next != -1) { struct slot *nextslot = &t->slot[next->next]; next->id = nextslot->id; next->obj = nextslot->obj; next->next = nextslot->next; nextslot->id = 0; nextslot->obj = 0; nextslot->next = -1; } } return obj; } if (next->next < 0) return NULL; s = next; next = &t->slot[next->next]; } return NULL; } struct object* table_find(struct table *t,int id) { struct slot *s = mainposition(t,id); for(;;) { if (s->id == id) return s->obj; if (s->next == -1) break; s = &t->slot[s->next]; } return NULL; }
C
/* This is the main body of the program. It is just a simple skeleton * and should be fleshed out as desired. Mainly what you'll do to flesh * it out is to edit the data structure defined in main.h so that it contains * the information your program needs. Then modify init_display() to create * the interface you want, and then just write the associated callback * routines that are driven by the display. Easy, huh? * * -- This code is under the GNU copyleft -- * * Dominic Giampaolo * [email protected] */ #include <stdio.h> #include <ctype.h> #include <string.h> #include <math.h> #include "libsx.h" /* should come first, defines libsx stuff */ #ifndef _MAIN_H #include "main.h" /* where program specific stuff is defined */ #endif #ifndef _CALLBACK_H #include "callback.h" /* prototypes for callback functions */ #endif Widget drawarea_widget; void main(int argc, char **argv) { MyProgram mydata; InitDatabase(&mydata); GenerateParticleSystem(&mydata, 0); SetupAnimToRun(&mydata); printf("back in main\n"); init_display(argc, argv, &mydata); /* setup the display */ MainLoop(); /* go right into the main loop */ } /* This function sets up the display. For any kind of a real program, * you'll probably want to save the values returned by the MakeXXX calls * so that you have a way to refer to the display objects you have * created (like if you have more than one drawing area, and want to * draw into both of them). */ void init_display(int argc, char **argv, MyProgram *me) { Widget w[MAX_WIDGETS]; if (OpenDisplay(argc, argv) == FALSE) return; /* declare all the widgets */ w[FILE_MENU_IDX] = MakeMenu(" File "); w[CMD_MENU_IDX] = MakeMenu(" Command "); w[OPT_MENU_IDX] = MakeMenu(" Options "); w[VIEW_MENU_IDX] = MakeMenu(" View "); w[ANIM_MENU_IDX] = MakeMenu(" Anim "); w[ZOOM_MENU_IDX] = MakeMenu(" Zoom "); w[LABEL_IDX] = MakeLabel(" Welcome to Particle - ver 1.0"); w[DRAW_AREA_IDX] = MakeDrawArea(SCREEN_X_SIZE, SCREEN_Y_SIZE, redisplay, me); /* add menu items to 'file' menu */ w[FILE_OPEN_IDX] = MakeMenuItem(w[FILE_MENU_IDX], "Open ...", file_open, me); w[FILE_SAVE_IDX] = MakeMenuItem(w[FILE_MENU_IDX], "Save", file_save, me); w[FILE_SAVE_AS_IDX] = MakeMenuItem(w[FILE_MENU_IDX], "Save As ...", file_save_as, me); w[FILE_CLOSE_IDX] = MakeMenuItem(w[FILE_MENU_IDX], "Close", file_close, me); w[FILE_ABOUT_IDX] = MakeMenuItem(w[FILE_MENU_IDX], "About ...", file_about, me); w[FILE_HELP_IDX] = MakeMenuItem(w[FILE_MENU_IDX], "Help ...", file_help, me); w[FILE_QUIT_IDX] = MakeMenuItem(w[FILE_MENU_IDX], "Quit", file_quit, me); /* add menu items to 'command' menu */ w[CMD_SET_SYS_IDX] = MakeMenuItem(w[CMD_MENU_IDX], "Setup Systems ...", cmd_setup_system, me); w[CMD_EDIT_CAMERA_IDX] = MakeMenuItem(w[CMD_MENU_IDX], "Edit Camera ...", cmd_edit_camera, me); w[CMD_EDIT_ANIM_IDX] = MakeMenuItem(w[CMD_MENU_IDX], "Edit Anim ...", cmd_edit_anim, me); /* add menu items to 'options' menu */ w[OPT_DUMP_DATA_IDX] = MakeMenuItem(w[OPT_MENU_IDX], "Dump Database ...", opt_dump_database, me); w[OPT_STATUS_IDX] = MakeMenuItem(w[OPT_MENU_IDX], "Status ...", opt_status, me); /* add menu items to 'view' menu */ w[VIEW_ALL_IDX] = MakeMenuItem(w[VIEW_MENU_IDX], "All", view_all, me); w[VIEW_XY_IDX] = MakeMenuItem(w[VIEW_MENU_IDX], "Ortho XY", view_xy, me); w[VIEW_ZY_IDX] = MakeMenuItem(w[VIEW_MENU_IDX], "Ortho ZY", view_zy, me); w[VIEW_XZ_IDX] = MakeMenuItem(w[VIEW_MENU_IDX], "Ortho XZ", view_xz, me); w[VIEW_CAMERA_IDX] = MakeMenuItem(w[VIEW_MENU_IDX], "Camera", view_camera, me); /* add menu items to 'anim' menu */ w[ANIM_STOP_IDX] = MakeMenuItem(w[ANIM_MENU_IDX], "Stop ", anim_stop, me); w[ANIM_RUN_FOR_IDX] = MakeMenuItem(w[ANIM_MENU_IDX], "Run Forward ", anim_run_forward, me); w[ANIM_RUN_REV_IDX] = MakeMenuItem(w[ANIM_MENU_IDX], "Run Reverse ", anim_run_reverse, me); w[ANIM_LOOP_IDX] = MakeMenuItem(w[ANIM_MENU_IDX], "Loop ", anim_loop, me); w[ANIM_PING_IDX] = MakeMenuItem(w[ANIM_MENU_IDX], "Ping Pong ", anim_ping, me); w[ANIM_STEP_FOR_IDX] = MakeMenuItem(w[ANIM_MENU_IDX], "Step Forward ", anim_step_forward, me); w[ANIM_STEP_REV_IDX] = MakeMenuItem(w[ANIM_MENU_IDX], "Step Reverse ", anim_step_reverse, me); w[ANIM_FIRST_IDX] = MakeMenuItem(w[ANIM_MENU_IDX], "First Frame ", anim_first, me); w[ANIM_LAST_IDX] = MakeMenuItem(w[ANIM_MENU_IDX], "Last Frame ", anim_last, me); /* add menu items to 'zoom' menu */ w[ZOOM_IN_IDX] = MakeMenuItem(w[ZOOM_MENU_IDX], "Zoom In", zoom_in, me); w[ZOOM_NORMAL_IDX] = MakeMenuItem(w[ZOOM_MENU_IDX], "Zoom Normal", zoom_normal, me); w[ZOOM_OUT_IDX] = MakeMenuItem(w[ZOOM_MENU_IDX], "Zoom Out", zoom_out, me); /* callbacks for draw area */ SetButtonDownCB(w[DRAW_AREA_IDX], button_down); SetButtonUpCB(w[DRAW_AREA_IDX], button_up); SetMouseMotionCB(w[DRAW_AREA_IDX], motion); /* SetKeypressCB(w[DRAW_AREA_IDX], keypress); -- not used !!!!! */ /* set all the widgets' positions */ SetWidgetPos(w[CMD_MENU_IDX], PLACE_RIGHT, w[FILE_MENU_IDX], NO_CARE, NULL); SetWidgetPos(w[OPT_MENU_IDX], PLACE_RIGHT, w[CMD_MENU_IDX], NO_CARE, NULL); SetWidgetPos(w[VIEW_MENU_IDX], PLACE_RIGHT, w[OPT_MENU_IDX], NO_CARE, NULL); SetWidgetPos(w[ANIM_MENU_IDX], PLACE_RIGHT, w[VIEW_MENU_IDX], NO_CARE, NULL); SetWidgetPos(w[ZOOM_MENU_IDX], PLACE_RIGHT, w[ANIM_MENU_IDX], NO_CARE, NULL); SetWidgetPos(w[LABEL_IDX], PLACE_RIGHT, w[ZOOM_MENU_IDX], NO_CARE, NULL); SetWidgetPos(w[DRAW_AREA_IDX], PLACE_UNDER, w[FILE_MENU_IDX], NO_CARE, NULL); /* This call actually causes the whole thing to be displayed on the * screen. You have to call this function before doing any drawing * into the window. */ ShowDisplay(); /* Get standard (red, blue, green, yellow, black, white) colors for * drawing stuff. Check libsx.h for more info. */ GetStandardColors(); SetFgColor(w[FILE_MENU_IDX], WHITE); SetBgColor(w[FILE_MENU_IDX], BLUE); SetFgColor(w[CMD_MENU_IDX], WHITE); SetBgColor(w[CMD_MENU_IDX], BLUE); SetFgColor(w[OPT_MENU_IDX], WHITE); SetBgColor(w[OPT_MENU_IDX], BLUE); SetFgColor(w[VIEW_MENU_IDX], WHITE); SetBgColor(w[VIEW_MENU_IDX], BLUE); SetFgColor(w[ANIM_MENU_IDX], WHITE); SetBgColor(w[ANIM_MENU_IDX], BLUE); SetFgColor(w[ZOOM_MENU_IDX], WHITE); SetBgColor(w[ZOOM_MENU_IDX], BLUE); SetFgColor(w[LABEL_IDX], BLACK); SetFgColor(w[DRAW_AREA_IDX], WHITE); SetBgColor(w[DRAW_AREA_IDX], BLACK); SetFgColor(w[FILE_OPEN_IDX], WHITE); SetFgColor(w[FILE_SAVE_IDX], WHITE); SetFgColor(w[FILE_SAVE_AS_IDX], WHITE); SetFgColor(w[FILE_CLOSE_IDX], WHITE); SetFgColor(w[FILE_ABOUT_IDX], WHITE); SetFgColor(w[FILE_HELP_IDX], WHITE); SetFgColor(w[FILE_QUIT_IDX], WHITE); SetBgColor(w[FILE_OPEN_IDX], BLUE); SetFgColor(w[CMD_SET_SYS_IDX], WHITE); SetFgColor(w[CMD_EDIT_CAMERA_IDX], WHITE); SetFgColor(w[CMD_EDIT_ANIM_IDX], WHITE); SetBgColor(w[CMD_SET_SYS_IDX], BLUE); SetFgColor(w[OPT_DUMP_DATA_IDX], WHITE); SetFgColor(w[OPT_STATUS_IDX], WHITE); SetBgColor(w[OPT_DUMP_DATA_IDX], BLUE); SetFgColor(w[VIEW_ALL_IDX], WHITE); SetFgColor(w[VIEW_XY_IDX], WHITE); SetFgColor(w[VIEW_ZY_IDX], WHITE); SetFgColor(w[VIEW_XZ_IDX], WHITE); SetFgColor(w[VIEW_CAMERA_IDX], WHITE); SetBgColor(w[VIEW_ALL_IDX], BLUE); SetFgColor(w[ANIM_STOP_IDX], WHITE); SetFgColor(w[ANIM_RUN_FOR_IDX], WHITE); SetFgColor(w[ANIM_RUN_REV_IDX], WHITE); SetFgColor(w[ANIM_LOOP_IDX], WHITE); SetFgColor(w[ANIM_PING_IDX], WHITE); SetFgColor(w[ANIM_STEP_FOR_IDX], WHITE); SetFgColor(w[ANIM_STEP_REV_IDX], WHITE); SetFgColor(w[ANIM_FIRST_IDX], WHITE); SetFgColor(w[ANIM_LAST_IDX], WHITE); SetBgColor(w[ANIM_STOP_IDX], BLUE); SetFgColor(w[ZOOM_IN_IDX], WHITE); SetFgColor(w[ZOOM_NORMAL_IDX], WHITE); SetFgColor(w[ZOOM_OUT_IDX], WHITE); SetBgColor(w[ZOOM_IN_IDX], BLUE); drawarea_widget = w[DRAW_AREA_IDX]; UpdateDisplay(me); /* If you wanted to get all the colors in the colormap, you'd do the * following : * * GetAllColors(); * SetColorMap(GREY_SCALE_1); * * You can wait to do it till later if you want. There's no need * to do it here if you don't need to (because it wacks out the * colormap). */ }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <unistd.h> void change_password(); struct customer { char username[1000]; char password[100]; char phone_number[20]; double money; }; void clear_screen() { system("clear"); } static char *get_input() { char *input = malloc(32); fgets(input, 32, stdin); return input; } void admin_log_in() { clear_screen(); char password[] = "qwerty123"; printf("Enter your password: "); char *input = get_input(); int counter = 0; while (strcmp(password, input) != 0) { counter++; if (counter == 5) { puts("Maximum invalid tries reached! Please wait 30 seconds"); sleep(30); counter = 0; } printf("Incorrect password!"); printf("Enter your password again: "); free(input); input = get_input(); } puts("Password successfully set"); } void user_log_in() // login to { clear_screen(); char username[1000]; char password[100]; char phone_number[20]; int username_len = strlen(username); int password_len = strlen(password); int phone_number_len = strlen(phone_number); int log_in_choice; printf("Log in with?"); printf("1. Email"); printf("2. Phone Number"); scanf("%d", &log_in_choice); getchar(); if (log_in_choice == 1) { printf("Enter your username (with .com) : "); scanf("%[^\n]*s", username); while (username[username_len - 4] == '.' && username[username_len - 3] == 'c' && username[username_len - 2] == 'o' && username[username_len - 1] == 'm') { printf("Enter a valid username (with .com) : "); scanf("%[^\n]*s", username); } } else if (log_in_choice == 2) { printf("Enter your phone number (starting with 08...): "); scanf("%s", phone_number); while (phone_number[0] != 0 && phone_number[1] != 8) { printf("Invalid phone number! Please enter again: "); scanf("%s", phone_number); } } else { while (log_in_choice != 1 && log_in_choice != 2) { printf("Invalid choice! Plase enter again : "); scanf("%d", &log_in_choice); } } printf("Please enter a strong password (with symbols, numbers, uppercase and lowercase letters)\n"); printf("Enter your password : \n"); scanf("%[^\n]*s", password); int symbols = 0, numbers = 0, uppercase = 0, lowercase = 0; for (int i = 0; i < password_len; i++) { if (password[i] >= 32 && password[i] <= 47) symbols += 1; else if (password[i] >= '0' && password[i] <= '9') numbers += 1; else if (password[i] >= 'a' && password[i] <= 'z') lowercase += 1; else if (password[i] >= 'A' && password[i] <= 'Z') uppercase += 1; } while (symbols < 1 || numbers < 1 || uppercase < 1 || lowercase < 1) { printf("Your password is not strong enough! Please create a new one: "); scanf("%s", password); } if (symbols >= 1 && numbers >= 1 && uppercase >= 1 && lowercase >= 1) { printf("Your password is saved!"); } char forgot; printf("Forgot password? Press 'F' to continue\n"); scanf("%c", &forgot); getchar(); while (forgot != 'F' || forgot != 'f') ; { printf("Invalid input! Please enter again: "); scanf("%c", &forgot); } if (forgot == 'F' || forgot == 'f') { change_password(); } } /* void top_up() // add money { int money_to_add; printf("Enter amount of money you want to add: "); scanf("%lf", &money_to_add); buyer.money += money_to_add; }*/ void profile(char username[], char password[], char phone_number[]) { clear_screen(); struct customer buyer; char greetings[100] = "Morning"; /* kalau jam sekian - sekian good %s if () { strcpy(greetings, "Day"); } else if () { strcpy(greetings, "Afternoon"); } else if () { strcpy(greetings, "Evening"); }*/ printf("Hello and Good %s, %s\n", greetings, username); printf("Your password : %s\n", password); printf("Your phone number : %s", phone_number); // printf("Your amount of money : %lf\n", ); char change_pass; printf("Change password? Enter 'C' : "); scanf("%c", &change_pass); while (change_pass != 'C' && change_pass != 'c') { printf("Invalid input! Please enter again: "); scanf("%c", &change_pass); } if (change_pass == 'C' || change_pass == 'c') { change_password(password); } char add_money; printf("Press '+' to add money: "); scanf("%c", &add_money); while (add_money != '+') { printf("Invalid input! Please enter again : "); scanf("%c", &add_money); } if (add_money == '+') { } } void change_password() { char new_password[100]; char confirm_new_password[100]; printf("Please enter a strong password (with symbols and numbers)\n"); printf("Enter your new password: "); scanf("%s", new_password); printf("Confirm new password: "); scanf("%s", confirm_new_password); int password_len = strlen(new_password); /*while (strcmp(new_password, confirm_new_password) != 0) { printf("Confirmation is invalid! Please enter again: \n"); }*/ int symbols = 0, numbers = 0, lowercase = 0, uppercase = 0; for (int i = 0; i < password_len; i++) { if (new_password[i] >= 32 && new_password[i] <= 47) symbols += 1; else if (new_password[i] >= '0' && new_password[i] <= '9') numbers += 1; else if (new_password[i] >= 'a' && new_password[i] <= 'z') lowercase += 1; else if (new_password[i] >= 'A' && new_password[i] <= 'Z') uppercase += 1; } while (symbols < 1 || numbers < 1 || uppercase < 1 || lowercase < 1) { printf("Your password is not strong enough! Please create a new one: "); scanf("%s", new_password); } if (symbols >= 1 && numbers >= 1 && uppercase >= 1 && lowercase >= 1) { /*strcpy(password, new_password);*/ printf("Your password is saved!"); } }
C
#include<stdio.h> int gcd(int x,int y){ if (y==0) return x; else return gcd(y,x%y); } int main(){ int x,y; puts("请输入x和y"); scanf("%d%d",&x,&y); int k = gcd(x,y); printf("他们最小公约数是%d",k); return 0; }
C
#include <stdio.h> #define MAX 2000000 int H, A[MAX+1]; void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } void maxHeapify(int i) { int l, r, largest; l = 2 * i; r = 2 * i + 1; if (l <= H && A[l] > A[i]) largest = l; else largest = i; if (r <= H && A[r] > A[largest]) largest = r; if (largest != i) { swap(&A[i], &A[largest]); maxHeapify(largest); } } int main(int argc, char const* argv[]) { scanf("%d", &H); for (int i = 1; i <= H; i++) scanf("%d", &A[i]); for (int i = H / 2; i >= 1; i--) maxHeapify(i); for (int i = 1; i <= H; i++) printf(" %d", A[i]); printf("\n"); return 0; }
C
/* Copyright (c) 2013, Linaro Limited * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <odp_coremask.h> #include <odp_debug.h> #include <stdlib.h> #include <string.h> #define MAX_CORE_NUM 64 void odp_coremask_from_str(const char *str, odp_coremask_t *mask) { uint64_t mask_u64; if (strlen(str) > 18) { /* more than 64 bits */ return; } mask_u64 = strtoull(str, NULL, 16); odp_coremask_from_u64(&mask_u64, 1, mask); } void odp_coremask_to_str(char *str, int len, const odp_coremask_t *mask) { int ret; ret = snprintf(str, len, "0x%"PRIx64"", mask->_u64[0]); if (ret >= 0 && ret < len) { /* force trailing zero */ str[len-1] = '\0'; } } void odp_coremask_from_u64(const uint64_t *u64, int num, odp_coremask_t *mask) { int i; if (num > ODP_COREMASK_SIZE_U64) { /* force max size */ num = ODP_COREMASK_SIZE_U64; } for (i = 0; i < num; i++) mask->_u64[0] |= u64[i]; } void odp_coremask_set(int core, odp_coremask_t *mask) { /* should not be more than 63 * core no. should be from 0..63= 64bit */ if (core >= MAX_CORE_NUM) { ODP_ERR("invalid core count\n"); return; } mask->_u64[0] |= (1 << core); } void odp_coremask_clr(int core, odp_coremask_t *mask) { /* should not be more than 63 * core no. should be from 0..63= 64bit */ if (core >= MAX_CORE_NUM) { ODP_ERR("invalid core count\n"); return; } mask->_u64[0] &= ~(1 << core); } int odp_coremask_isset(int core, const odp_coremask_t *mask) { /* should not be more than 63 * core no. should be from 0..63= 64bit */ if (core >= MAX_CORE_NUM) { ODP_ERR("invalid core count\n"); return -1; } return (mask->_u64[0] >> core) & 1; } int odp_coremask_count(const odp_coremask_t *mask) { uint64_t coremask = mask->_u64[0]; int cnt = 0; while (coremask != 0) { coremask >>= 1; if (coremask & 1) cnt++; } return cnt; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int comp( const void* s1, const void* s2 ) { char c1 = * (char*) s1; char c2 = * (char*) s2; return c1 - c2; } /* Sort chars in string then compare */ int anagram( char* str1, char* str2 ) { int max_strlen = (strlen( str1 ) > strlen( str2 ) ) ? strlen( str1 ) : strlen( str2 ); qsort( str1, strlen( str1 ), sizeof( str1[ 0 ] ), comp ); qsort( str2, strlen( str2 ), sizeof( str2[ 0 ] ), comp ); if (strncmp( str1, str2, max_strlen ) == 0) return 1; else return 0; } /* Count occurrence of each char */ int anagram2( char* str1, char* str2 ) { int str1len = strlen( str1 ); int str2len = strlen( str2 ); if (str1len != str2len) return 0; int letters[ 256 ] = { 0 }; int num_unique_chars = 0; int num_completed_str2 = 0; int i; for (i = 0; i < str1len; i++) { if (letters[ str1[ i ] ] == 0) ++num_unique_chars; ++letters[ str1[ i ] ]; } for (i = 0; i < str2len; i++) { if (letters[ str2[ i ] ] == 0) return 0; --letters[ str2[ i ] ]; } return 1; } main() { char str1[] = "dormitory"; char str2[] = "dirtyroom"; puts( str1 ); puts( str2 ); if (anagram( str1, str2 ) ) puts( "They are anagrams" ); else puts( "Not anagrams" ); puts( str1 ); puts( str2 ); int c = anagram2( str1, str2 ); printf( "%d\n", c ); }
C
#ifndef RANDOM_H_ #define RANDOM_H_ /* * Encapsulation of standard C random number generator. * We provide a way to randomize the state of the RNG. */ // Randomize the C RNG with a time-related seed. // Can be called multiple times, it will only randomize on the first call. void randomize(void); // Return a random unsigned integer in the closed-closed interval [min, max]. unsigned int random_in_range(unsigned int min, unsigned int max); #endif
C
#include "helpers.h" #include <math.h> // Convert image to grayscale void grayscale(int height, int width, RGBTRIPLE image[height][width]) { // Make the average of the three color for each pixel // Ensure the result is an integer float avg; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { avg = round((image[i][j].rgbtBlue + image[i][j].rgbtGreen + image[i][j].rgbtRed) / 3.0); image[i][j].rgbtBlue = avg; image[i][j].rgbtGreen = avg; image[i][j].rgbtRed = avg; } } return; } // Reflect image horizontally void reflect(int height, int width, RGBTRIPLE image[height][width]) { // For every row // Swap pixels on horizontally opposite sides. RGBTRIPLE tmp[width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { tmp[j] = image[i][j]; } for (int k = 0; k < width; k++) { image[i][k] = tmp[width - (1 + k)]; } } return; } // Blur image void blur(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE tmp[height][width]; int sumRed, sumGreen, sumBlue; float cpt; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { cpt = 1.0; sumRed = image[i][j].rgbtRed; sumGreen = image[i][j].rgbtGreen; sumBlue = image[i][j].rgbtBlue; if (i - 1 >= 0 && j - 1 >= 0) { sumRed += image[i - 1][j - 1].rgbtRed; sumGreen += image[i - 1][j - 1].rgbtGreen; sumBlue += image[i - 1][j - 1].rgbtBlue; cpt++; } if (i - 1 >= 0) { sumRed += image[i - 1][j].rgbtRed; sumGreen += image[i - 1][j].rgbtGreen; sumBlue += image[i - 1][j].rgbtBlue; cpt++; } if (i - 1 >= 0 && j + 1 < width) { sumRed += image[i - 1][j + 1].rgbtRed; sumGreen += image[i - 1][j + 1].rgbtGreen; sumBlue += image[i - 1][j + 1].rgbtBlue; cpt++; } if (j - 1 >= 0) { sumRed += image[i][j - 1].rgbtRed; sumGreen += image[i][j - 1].rgbtGreen; sumBlue += image[i][j - 1].rgbtBlue; cpt++; } if (j + 1 < width) { sumRed += image[i][j + 1].rgbtRed; sumGreen += image[i][j + 1].rgbtGreen; sumBlue += image[i][j + 1].rgbtBlue; cpt++; } if (i + 1 < height && j - 1 >= 0) { sumRed += image[i + 1][j - 1].rgbtRed; sumGreen += image[i + 1][j - 1].rgbtGreen; sumBlue += image[i + 1][j - 1].rgbtBlue; cpt++; } if (i + 1 < height) { sumRed += image[i + 1][j].rgbtRed; sumGreen += image[i + 1][j].rgbtGreen; sumBlue += image[i + 1][j].rgbtBlue; cpt++; } if (i + 1 < height && j + 1 < width) { sumRed += image[i + 1][j + 1].rgbtRed; sumGreen += image[i + 1][j + 1].rgbtGreen; sumBlue += image[i + 1][j + 1].rgbtBlue; cpt++; } if (round(sumRed / cpt) > 255) { tmp[i][j].rgbtRed = 255; } else { tmp[i][j].rgbtRed = round(sumRed / cpt); } if (round(sumGreen / cpt) > 255) { tmp[i][j].rgbtGreen = 255; } else { tmp[i][j].rgbtGreen = round(sumGreen / cpt); } if (round(sumBlue / cpt) > 255) { tmp[i][j].rgbtBlue = 255; } else { tmp[i][j].rgbtBlue = round(sumBlue / cpt); } } } for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { image[i][j] = tmp[i][j]; } } return; } // Detect edges void edges(int height, int width, RGBTRIPLE image[height][width]) { // For each pixel // compute Gx and Gy for each channel of red, green, and blue // for pixels at the border, treat any pixel past the border as having all 0 values // Compute each new channel value as the square root of Gx² + Gy² RGBTRIPLE tmp[height][width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int GxRed = 0; int GxGreen = 0; int GxBlue = 0; int GyRed = 0; int GyGreen = 0; int GyBlue = 0; int sumRed = 0; int sumGreen = 0; int sumBlue = 0; if (i - 1 >= 0 && j - 1 >= 0) { sumRed += - 1 * image[i - 1][j - 1].rgbtRed; sumGreen += - 1 * image[i - 1][j - 1].rgbtGreen; sumBlue += - 1 * image[i - 1][j - 1].rgbtBlue; } if (i - 1 >= 0) { GyRed += - 2 * image[i - 1][j].rgbtRed; GyGreen += - 2 * image[i - 1][j].rgbtGreen; GyBlue += - 2 * image[i - 1][j].rgbtBlue; } if (i - 1 >= 0 && j + 1 < width) { GxRed += 1 * image[i - 1][j + 1].rgbtRed; GxGreen += 1 * image[i - 1][j + 1].rgbtGreen; GxBlue += 1 * image[i - 1][j + 1].rgbtBlue; GyRed += - 1 * image[i - 1][j + 1].rgbtRed; GyGreen += - 1 * image[i - 1][j + 1].rgbtGreen; GyBlue += - 1 * image[i - 1][j + 1].rgbtBlue; } if (j - 1 >= 0) { GxRed += - 2 * image[i][j - 1].rgbtRed; GxGreen += - 2 * image[i][j - 1].rgbtGreen; GxBlue += - 2 * image[i][j - 1].rgbtBlue; } if (j + 1 < width) { GxRed += 2 * image[i][j + 1].rgbtRed; GxGreen += 2 * image[i][j + 1].rgbtGreen; GxBlue += 2 * image[i][j + 1].rgbtBlue; } if (i + 1 < height && j - 1 >= 0) { GxRed += - 1 * image[i + 1][j - 1].rgbtRed; GxGreen += - 1 * image[i + 1][j - 1].rgbtGreen; GxBlue += - 1 * image[i + 1][j - 1].rgbtBlue; GyRed += 1 * image[i + 1][j - 1].rgbtRed; GyGreen += 1 * image[i + 1][j - 1].rgbtGreen; GyBlue += 1 * image[i + 1][j - 1].rgbtBlue; } if (i + 1 < height) { GyRed += 2 * image[i + 1][j].rgbtRed; GyGreen += 2 * image[i + 1][j].rgbtGreen; GyBlue += 2 * image[i + 1][j].rgbtBlue; } if (i + 1 < height && j + 1 < width) { sumRed += 1 * image[i + 1][j + 1].rgbtRed; sumGreen += 1 * image[i + 1][j + 1].rgbtGreen; sumBlue += 1 * image[i + 1][j + 1].rgbtBlue; } GxRed += sumRed; GxGreen += sumGreen; GxBlue += sumBlue; GyRed += sumRed; GyGreen += sumGreen; GyBlue += sumBlue; float gRed = sqrt((GxRed * GxRed) + (GyRed * GyRed)); float gGreen = sqrt((GxGreen * GxGreen) + (GyGreen * GyGreen)); float gBlue = sqrt((GxBlue * GxBlue) + (GyBlue * GyBlue)); if (gRed > 255) { tmp[i][j].rgbtRed = 255; } else { tmp[i][j].rgbtRed = round(gRed); } if (gGreen > 255) { tmp[i][j].rgbtGreen = 255; } else { tmp[i][j].rgbtGreen = round(gGreen); } if (gBlue > 255) { tmp[i][j].rgbtBlue = 255; } else { tmp[i][j].rgbtBlue = round(gBlue); } } } for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { image[i][j] = tmp[i][j]; } } return; }
C
/* * CS:APP Data Lab * * <Omar Ahmad ID:804801272> * * bits.c - Source file with your solutions to the Lab. * This is the file you will hand in to your instructor. * * WARNING: Do not include the <stdio.h> header; it confuses the dlc * compiler. You can still use printf for debugging without including * <stdio.h>, although you might get a compiler warning. In general, * it's not good practice to ignore compiler warnings, but in this * case it's OK. */ #if 0 /* * Instructions to Students: * * STEP 1: Read the following instructions carefully. */ You will provide your solution to the Data Lab by editing the collection of functions in this source file. INTEGER CODING RULES: Replace the "return" statement in each function with one or more lines of C code that implements the function. Your code must conform to the following style: int Funct(arg1, arg2, ...) { /* brief description of how your implementation works */ int var1 = Expr1; ... int varM = ExprM; varJ = ExprJ; ... varN = ExprN; return ExprR; } Each "Expr" is an expression using ONLY the following: 1. Integer constants 0 through 255 (0xFF), inclusive. You are not allowed to use big constants such as 0xffffffff. 2. Function arguments and local variables (no global variables). 3. Unary integer operations ! ~ 4. Binary integer operations & ^ | + << >> Some of the problems restrict the set of allowed operators even further. Each "Expr" may consist of multiple operators. You are not restricted to one operator per line. You are expressly forbidden to: 1. Use any control constructs such as if, do, while, for, switch, etc. 2. Define or use any macros. 3. Define any additional functions in this file. 4. Call any functions. 5. Use any other operations, such as &&, ||, -, or ?: 6. Use any form of casting. 7. Use any data type other than int. This implies that you cannot use arrays, structs, or unions. You may assume that your machine: 1. Uses 2s complement, 32-bit representations of integers. 2. Performs right shifts arithmetically. 3. Has unpredictable behavior when shifting an integer by more than the word size. EXAMPLES OF ACCEPTABLE CODING STYLE: /* * pow2plus1 - returns 2^x + 1, where 0 <= x <= 31 */ int pow2plus1(int x) { /* exploit ability of shifts to compute powers of 2 */ return (1 << x) + 1; } /* * pow2plus4 - returns 2^x + 4, where 0 <= x <= 31 */ int pow2plus4(int x) { /* exploit ability of shifts to compute powers of 2 */ int result = (1 << x); result += 4; return result; } FLOATING POINT CODING RULES For the problems that require you to implent floating-point operations, the coding rules are less strict. You are allowed to use looping and conditional control. You are allowed to use both ints and unsigneds. You can use arbitrary integer and unsigned constants. You are expressly forbidden to: 1. Define or use any macros. 2. Define any additional functions in this file. 3. Call any functions. 4. Use any form of casting. 5. Use any data type other than int or unsigned. This means that you cannot use arrays, structs, or unions. 6. Use any floating point data types, operations, or constants. NOTES: 1. Use the dlc (data lab checker) compiler (described in the handout) to check the legality of your solutions. 2. Each function has a maximum number of operators (! ~ & ^ | + << >>) that you are allowed to use for your implementation of the function. The max operator count is checked by dlc. Note that '=' is not counted; you may use as many of these as you want without penalty. 3. Use the btest test harness to check your functions for correctness. 4. Use the BDD checker to formally verify your functions 5. The maximum number of ops for each function is given in the header comment for each function. If there are any inconsistencies between the maximum ops in the writeup and in this file, consider this file the authoritative source. /* * STEP 2: Modify the following functions according the coding rules. * * IMPORTANT. TO AVOID GRADING SURPRISES: * 1. Use the dlc compiler to check that your solutions conform * to the coding rules. * 2. Use the BDD checker to formally verify that your solutions produce * the correct answers. */ #endif /* * bang - Compute !x without using ! * Examples: bang(3) = 0, bang(0) = 1 * Legal ops: ~ & ^ | + << >> * Max ops: 12 * Rating: 4 */ int bang(int x) { /* exploits 2's comp rule that msb is sign bit -- ORs x with minus x to cause msb to signal whether x != o. then shifted over and added 1 to make x=0 return 1 and rest return 0 */ int minusx = ~x +1; int m = x | minusx; //msb = 1 iff x!=0 int a = m >>31; int sol = a +1; return sol; } /* * bitCount - returns count of number of 1's in word * Examples: bitCount(5) = 2, bitCount(7) = 3 * Legal ops: ! ~ & ^ | + << >> * Max ops: 40 * Rating: 4 */ int bitCount(int x) { /* adds up bits in each byte of x into the correlating byte in count and then adds up those numbers into sol */ int count = 0; int m = 1|(1<<8)|(1<<16)|(1<<24); //1 in each byte mask int sol = 0; int b1bits = 0; //(count&0xFF); //adding the 4 bytes from count together into sol and returning sol int b2bits = 0; //(count>>8)& 0xFF; int b3bits = 0; //(count>>16)& 0xFF; int b4bits = 0; //(count>>24)& 0xFF; count += m&x; //adding bits in each byte count += m&(x>>1); count += m&(x>>2); count += m&(x>>3); count += m&(x>>4); count += m&(x>>5); count += m&(x>>6); count += m&(x>>7); b1bits = (count&0xFF); //adding the 4 bytes from count together into sol and returning sol b2bits = (count>>8)& 0xFF; b3bits = (count>>16)& 0xFF; b4bits = (count>>24)& 0xFF; sol = b1bits + b2bits + b3bits + b4bits; return sol; /* int b0 = x & 0xff; //b0 is the 1st BYTE of x int b1 = (x>>8) & 0xff; int b2 = (x>>16) & 0xff; int b3 = (x>>24) & 0xff; */ } /* * bitOr - x|y using only ~ and & * Example: bitOr(6, 5) = 7 * Legal ops: ~ & * Max ops: 8 * Rating: 1 */ int bitOr(int x, int y) { /* uses definition of and gate to make or gate */ return ~(~x&~y); } /* * bitRepeat - repeat x's low-order n bits until word is full. * Can assume that 1 <= n <= 32. * Examples: bitRepeat(1, 1) = -1 * bitRepeat(7, 4) = 0x77777777 * bitRepeat(0x13f, 8) = 0x3f3f3f3f * bitRepeat(0xfffe02, 9) = 0x10080402 * bitRepeat(-559038737, 31) = -559038737 * bitRepeat(-559038737, 32) = -559038737 * Legal ops: int and unsigned ! ~ & ^ | + - * / % << >> * (This is more general than the usual integer coding rules.) * Max ops: 40 * Rating: 4 */ int bitRepeat(int x, int n) { /* */ int mask = (1<<n)-1; //mask = 0's w/ n 1's at end int lowern = x&mask; int nminus1 = n-1; int none = !(nminus1); //1 if n=1 and 0 else int n1retval = ~lowern +1; //if n=1, =0's if lsb 0 and 1's if lsb 1 int n1s = none - 1; //0's if n=1 and 1's else int valid = 32-n; int nvalid = !valid - 1; //0's n = 32 and 1's else int sol = lowern; int n1 = lowern << n; int n2 = n1 << n; int n3 = n2 << n; int n4 = n3 << n; int n5 = n4 << n; int n6 = n5 << n; int n7 = n6 << n; int n8 = n7 << n; int n9 = n8 << n; int n10 = n9 << n; int n11 = n10 << n; int n12 = n11 << n; int n13 = n12 << n; int n14 = n13 << n; int n15 = n14 << n; /* int n16 = n15 << n; int n17 = n16 << n; int n18 = n17 << n; int n19 = n18 << n; int n20 = n19 << n; int n21 = n20 << n; int n22 = n21 << n; int n23 = n22 << n; int n24 = n23 << n; int n25 = n24 << n; int n26 = n25 << n; int n27 = n26 << n; int n28 = n27 << n; int n29 = n28 << n; int n30 = n29 << n; int n31 = n30 << n; */ sol = sol+n1+n2+n3+n4+n5+n6+n7+n8+n9+n10+n11+n12+n13+n14+n15; /*//+n16+n17+n18+n19+n20+n21+n22+n23+n24+n25+n26+n27+n28+n29+n30+n31; */ //int temp = !none; //0 if n=1 and 1 else //int n1retval = temp - lowern; //1's if lsb =1 and 0's if lsb = 0 -- ONLY FOR N = 1 !! // int n1s = ~none +1; //1's if n=1 and 0's else // int n1retval = n1s + !lowern; //if n=1, =0's if lsb 0 and 1's if lsb 1 sol = (~n1s & n1retval)|(n1s & sol); return ((~nvalid) & x)|(nvalid & sol); //return sol; } /* * fitsBits - return 1 if x can be represented as an * n-bit, two's complement integer. * 1 <= n <= 32 * Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1 * Legal ops: ! ~ & ^ | + << >> * Max ops: 15 * Rating: 2 */ int fitsBits(int x, int n) { /* exploits the fact that the diff between the max and min values in n bits is 2^(n+1) so if the diff between the max and x is greater than 2^(n+1), then x is too big */ int minus1 = (~1) + 1; int nminus1 = n + minus1; int max = (1<<(nminus1)) + minus1; int diff = max + ~x +1; int mask = minus1<<n; int blah = diff & (mask); int ncheck = 33 + ~n; return (!blah) | (!ncheck); } /* * getByte - Extract byte n from word x * Bytes numbered from 0 (LSB) to 3 (MSB) * Examples: getByte(0x12345678,1) = 0x56 * Legal ops: ! ~ & ^ | + << >> * Max ops: 6 * Rating: 2 */ int getByte(int x, int n) { /* exploits shifting to multiply by 8, and then ands with a mask of 24 0's followed by 8 1's */ int shift = n<<3; int x1 = x>>shift; int sol = x1&0xFF; return sol; } /* * isLessOrEqual - if x <= y then return 1, else return 0 * Example: isLessOrEqual(4,5) = 1. * Legal ops: ! ~ & ^ | + << >> * Max ops: 24 * Rating: 3 */ int isLessOrEqual(int x, int y) { /* ors together conditions in which x is less than y by sign, by magnitude, or x=y and ands with condition where x is greater than y by sign */ int xn = x>>31; int yn = y>>31; int xp = !xn; int yp = !yn; int equal = !(x^y); //equal = 1 if equal 0 otherwise (OR WITH LESSTHAN VALUE AT END) int xnyp = !xp & yp; // =1 iff x neg and y pos (x < y) (or with final val) int xpyn = xp & !yp; // =1 iff x pos and y neg (x !< y) (and ~xpyn w/ final val) int diff = y + ~x +1; //diff = y-x int ds = diff>>31; int posdif = !ds; int lessthan = posdif; // if y-x yields a pos diff, then x is less than y return (equal|xnyp|lessthan)&(~xpyn); } /* * isPositive - return 1 if x > 0, return 0 otherwise * Example: isPositive(-1) = 0. * Legal ops: ! ~ & ^ | + << >> * Max ops: 8 * Rating: 3 */ int isPositive(int x) { /* uses m to see if x non negative and then ands with !!x to filter out x = 0 case */ int m = x>>31; //m = 0 if x>= 0 return (!m)&(!!x);// } /* * logicalShift - shift x to the right by n, using a logical shift * Can assume that 0 <= n <= 31 * Examples: logicalShift(0x87654321,4) = 0x08765432 * Legal ops: ! ~ & ^ | + << >> * Max ops: 20 * Rating: 3 */ int logicalShift(int x, int n) { /* uses a mask, m2, that is all 1's if n is 0 and is n leading 0's followed by 1's otherwise to cut off the added bits from the arithmetic shift */ int a = x>>n; int ds = !n; //ds = 0 if n != 0 and 1 if n=0 int m1 = (!ds)<<(32+~n+1); //creates mask m1 that is all 0's if n is 0 and is a 1 in the nth bit from the left otherwise int m2 = m1 + ~1 +1; //subtracts 1 to creat all 1's if n is 0 and n leading 0's followed by 1's otherwise int sol = a&m2; //ands a with the mask to creat the solution return sol; } /* * tmin - return minimum two's complement integer * Legal ops: ! ~ & ^ | + << >> * Max ops: 4 * Rating: 1 */ int tmin(void) { /* exploits shifting to create INT_MIN */ return (1<<31); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> void strreverse(char* begin, char* end); void itoa_(int value, char *str); int main(){ char buf[BUFSIZ]; int n = 2000; // sprintf(buf,"%d", n); // puts(buf); itoa_(n,buf); int tamano = strlen( buf); printf("%d",tamano); int entero = (int) buf[0]; printf("imprimiendo a entero : %d", entero); return 0; } void strreverse(char* begin, char* end) { char aux; while(end>begin) aux=*end, *end--=*begin, *begin++=aux; } void itoa_(int value, char *str) { char* wstr=str; int sign; //div_t res; if ((sign=value) < 0) value = -value; do { *wstr++ = (value%10)+'0'; }while((value=(value/10))); if(sign<0) *wstr++='-'; *wstr='\0'; strreverse(str,wstr-1); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strjoin.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pdamoune <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/11 21:21:23 by pdamoune #+# #+# */ /* Updated: 2017/03/27 10:26:29 by pdamoune ### ########.fr */ /* */ /* ************************************************************************** */ #include <libft.h> /* ** Alloue (avec malloc(3)) et retourne une chaine de caractères ** “fraiche” terminée par un ’\0’ résultant de la concaténation ** de s1 et s2. Si l’allocation echoue, la fonction renvoie NULL */ char *ft_strjoin(char *str1, const char *str2) { char *s; size_t len; len = ft_strlen(str1) + ft_strlen(str2); if (!(s = (char *)malloc(sizeof(char) * len + 1))) return (NULL); ft_strcpy(s, str1); ft_strcpy(&s[ft_strlen(str1)], str2); s[len] = '\0'; return (s); }
C
/*Exercicio: Ler um numero inteiro e imprimir seu sucessor e antecessor. */ #include<stdio.h> int main() { int num, suc, ant; printf("Insira o numero:" ); scanf("%d", &num); suc = num + 1; ant = ant - 1; printf("O sucessor de ", num); printf("%d", suc); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_6__ TYPE_2__ ; typedef struct TYPE_5__ TYPE_1__ ; /* Type definitions */ struct TYPE_5__ {int /*<<< orphan*/ infinity; int /*<<< orphan*/ y; int /*<<< orphan*/ x; int /*<<< orphan*/ z; } ; typedef TYPE_1__ secp256k1_gej ; struct TYPE_6__ {int /*<<< orphan*/ infinity; int /*<<< orphan*/ y; int /*<<< orphan*/ x; } ; typedef TYPE_2__ secp256k1_ge ; typedef int /*<<< orphan*/ secp256k1_fe ; /* Variables and functions */ int /*<<< orphan*/ random_field_element_test (int /*<<< orphan*/ *) ; int /*<<< orphan*/ secp256k1_fe_is_zero (int /*<<< orphan*/ *) ; int /*<<< orphan*/ secp256k1_fe_mul (int /*<<< orphan*/ *,int /*<<< orphan*/ *,int /*<<< orphan*/ *) ; int /*<<< orphan*/ secp256k1_fe_sqr (int /*<<< orphan*/ *,int /*<<< orphan*/ *) ; void random_group_element_jacobian_test(secp256k1_gej *gej, const secp256k1_ge *ge) { secp256k1_fe z2, z3; do { random_field_element_test(&gej->z); if (!secp256k1_fe_is_zero(&gej->z)) { break; } } while(1); secp256k1_fe_sqr(&z2, &gej->z); secp256k1_fe_mul(&z3, &z2, &gej->z); secp256k1_fe_mul(&gej->x, &ge->x, &z2); secp256k1_fe_mul(&gej->y, &ge->y, &z3); gej->infinity = ge->infinity; }
C
#include <stdio.h> enum colors {red , yellow , blue }; void printfcolors (enum colors c); int main() { enum colors i = 0 ; printf("请输入你想看到的颜色呢:\n"); scanf("%d",&i); printfcolors(i); return 0; } void printfcolors(enum colors c){ printf("是%d色呢\n",c); }
C
#include <stdlib.h> #include <stdio.h> #include <assert.h> #include <string.h> #include "sorting.c" int main() { char* arr[6] = {"Taber", "Brendan", "Gavin", "Nick", "Cheyenne", "Alyssa"}; printf("Unsorted:\n"); for (int i = 0; i < 6; i++) { printf("%s\n", arr[i]); } quicksort(arr, 0, 6); printf("\nQuicksort:\n"); for (int i = 0; i < 6; i++) { printf("%s\n", arr[i]); } //compareSorts(arr, 6); }
C
#include <stdio.h> int main(void) { int Count, Counter; printf("How many natural numbers you want to print?"); scanf("%d", &Count); printf("The first %d natural numbers are", Count); for ( Counter = 1; Counter <= Count; Counter ++ ) { printf(" %d", Counter); } printf("."); return 0; }
C
#include "Controladores/AlDesenhosController.h" ALLEGRO_MUTEX *mutex; typedef struct jogo{ ALLEGRO_BITMAP* fundo; ALLEGRO_DISPLAY *janela; ALLEGRO_FONT *fonte; ALLEGRO_EVENT_QUEUE *filaEventos; ALLEGRO_TIMER *timer; ListaDesenho *listaDesenho; ListaDesenho *listaTiros; ListaDesenho *listaAsteroids; Jogador *jogador; int largura; int altura; int sair; }Jogo; void initJogo(Jogo *novo); Jogo *novoJogo(int w,int h); void finaliza(); void atualiza(); Jogo *novoJogo(int w,int h){ Jogo *novo; novo = (Jogo*) malloc(sizeof(Jogo)); novo->largura = w; novo->altura = h; novo->sair = 1; return novo; } void initJogo(Jogo *novo){ al_init(); al_init_image_addon(); al_init_font_addon(); al_init_ttf_addon(); al_install_keyboard(); al_install_audio(); al_init_acodec_addon(); al_reserve_samples(2); novo->timer = al_create_timer(1.0/60); novo->listaDesenho = initListaDesenho(10); novo->listaTiros = initListaDesenho(5); novo->listaAsteroids = initListaDesenho(500); novo->janela = al_create_display(novo->largura,novo->altura); novo->filaEventos = al_create_event_queue(); novo->fonte = al_load_font("Fontes/ARCADE_I.TTF", 20, 0); al_register_event_source(novo->filaEventos, al_get_keyboard_event_source()); al_register_event_source(novo->filaEventos, al_get_display_event_source(novo->janela)); al_register_event_source(novo->filaEventos, al_get_timer_event_source(novo->timer)); al_set_window_title(novo->janela, "Asteroids"); novo->fundo = al_load_bitmap("Sprites/bg.jpeg"); al_draw_bitmap(novo->fundo, 0, 0, 0); al_flip_display(); al_start_timer(novo->timer); } void finaliza(Jogo *jogo){ al_lock_mutex(mutex); if(jogo->listaDesenho->qt > 0){ destroyDesenho(jogo->listaDesenho); }if(jogo->listaTiros->qt > 0){ destroyDesenho(jogo->listaTiros); }if(jogo->listaAsteroids->qt > 0 ){ destroyDesenho(jogo->listaAsteroids); } al_destroy_font(jogo->fonte); al_destroy_event_queue(jogo->filaEventos); al_destroy_display(jogo->janela); al_unlock_mutex(mutex); al_destroy_mutex(mutex); al_destroy_timer(jogo->timer); free(jogo); } void atualiza(){ al_flip_display(); }
C
/******************** ** ⲿԴѹ ** һλЧС ************************/ #include <stdio.h> #include <string.h> #include "FreeRTOS.h" #include "data_type.h" #include "fr_drv_adc.h" #include "fr_drv_gpio.h" #define AD_CH_NUM 3 static unsigned int AdcValueTmp[AD_CH_NUM][5]; static unsigned int AdcValueSum[AD_CH_NUM]; static unsigned char AdcCounter; static struct in_info_str in_info; // struct run_data_str run_data; //е /************************* ** **************************/ void process_in(void) { unsigned char i,j; for(i = 0;i < AD_CH_NUM;i++) { AdcValueTmp[i][AdcCounter] = fr_read_adc_value(i); } AdcCounter++; if(AdcCounter >= 5) AdcCounter = 0; for(i =0;i < AD_CH_NUM;i++) { for(j = 0;j < 5;j++) AdcValueSum[i] += AdcValueTmp[i][j]; } AdcValueSum[0] = AdcValueSum[0] / 5; //Դѹ AdcValueSum[1] = AdcValueSum[1] / 5; //Ƭ¶ AdcValueSum[2] = AdcValueSum[2] / 5; //صѹ in_info.power_vol = AdcValueSum[0] * 3.3 / 4095.0 * 480; //ⲿѹ in_info.battery_vol = AdcValueSum[1] * 3.3 / 4095.0 * 20; //صѹ in_info.mcu_temp = AdcValueSum[2]; //Ƭ¶ in_info.acc_state = fr_read_gpio_state(PORT_GPIO_ACC, PIN_GPIO_ACC); in_info.shell_state = 0; in_info.gnss_ant_state = 0; memset((unsigned char *)&AdcValueSum,0,sizeof(AdcValueSum)); } /******************** ** ⲿԴѹ ** һλЧС ************************/ unsigned short int read_power_vol(void) { return in_info.power_vol; } /******************** ** صصѹ ** һλЧС ************************/ unsigned short int read_batter_vol(void) { return in_info.battery_vol; } /******************** ** ACC״̬ ************************/ unsigned char read_acc_state(void) { return in_info.acc_state; } /******************** ** ״̬ ********************/ unsigned char read_shell_state(void) { return in_info.shell_state; } /******************** ** ״̬ ************************/ unsigned char read_ant_state(void) { return in_info.gnss_ant_state; } /******************** ** صصѹ ** һλЧС ************************/ void task_in(void *data) { data = data; fr_init_adc(); for(;;) { process_in(); vTaskDelay(10); } } /*************************** ** ****************************/ void task_(void *data) { data = data; for(;;) { } }
C
#import <stdio.h> /*Ejercico de Nota por medio de switch*/ int main(){ char nota; printf(" Digite su nota:\n "); scanf("%c",&nota); switch(nota){ case 'A': printf("\nExcelente"); break; case 'B': printf("\nNotable"); break; case 'C': printf("\nPasable"); break; case 'F': printf("\nReprobado"); break; default: printf("\nNota no reconocida"); break; } return 0; }
C
#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv; int main(int argc, char *argv[]) { // 変数宣言 Mat img; // カメラのキャプチャ VideoCapture cap(0); // キャプチャのエラー処理 if (!cap.isOpened()) return -1; while (1) { // カメラ映像の取得 cap >> img; // 映像の表示 namedWindow("Camera", CV_WINDOW_AUTOSIZE | CV_WINDOW_FREERATIO); imshow("Camera", img); // キー入力があれば終了 if (waitKey(30) >= 0) break; } return 0; }
C
#include <stdio.h> #include <string.h> struct Drivers { char name[23]; char route[12]; int dlNo; int kms; } d1, d2, d3; int main() { printf("Enter the name of first dirver\n"); scanf("%s", &d1.name); printf("Enter the dlNo of first dirver\n"); scanf("%d", &d1.dlNo); printf("Enter the route of first dirver\n"); scanf("%s", &d1.route); printf("Enter the kms of first dirver's ride in bus\n"); scanf("%d", &d1.kms); printf("Enter the name of second dirver\n"); scanf("%s", &d2.name); printf("Enter the dlNo of second dirver\n"); scanf("%d", &d2.dlNo); printf("Enter the route of second dirver\n"); scanf("%s", &d2.route); printf("Enter the kms of second dirver's ride in bus\n"); scanf("%d", &d2.kms); printf("Enter the name of third dirver\n"); scanf("%s", &d3.name); printf("Enter the dlNo of third dirver\n"); scanf("%d", &d3.dlNo); printf("Enter the route of third dirver\n"); scanf("%s", &d3.route); printf("Enter the kms of third dirver's ride in bus\n"); scanf("%d", &d3.kms); printf("Here is the information of all the drives\n\n"); printf("The name of the first driver is %s\n", d1.name); printf("The dlNo of the first driver is %d\n", d1.dlNo); printf("The route of the first driver is %s\n", d1.route); printf("The kms are ride the first driver is %d\n\n", d1.kms); printf("The name of the second driver is %s\n", d2.name); printf("The name of the second driver is %d\n", d2.dlNo); printf("The name of the second driver is %s\n", d2.route); printf("The kms are ride the first driver is %d\n\n", d2.kms); printf("The name of the third driver is %s\n", d3.name); printf("The name of the third driver is %d\n", d3.dlNo); printf("The name of the third driver is %s\n", d3.route); printf("The kms are ride the first driver is %d\n\n", d3.kms); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: adompe <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/05/25 15:19:39 by adompe #+# #+# */ /* Updated: 2016/05/25 15:19:50 by adompe ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef PUSH_SWAP_H # define PUSH_SWAP_H # include <stdlib.h> # include <stdio.h> # include "libft.h" # include "ft_printf.h" # include "limits.h" # define FALSE 0 # define TRUE 1 # define HORIZONTAL ' ' # define VERTICAL '\n' typedef struct s_stack { int content; struct s_stack *next; struct s_stack *prev; } t_stack; typedef unsigned char t_bool; typedef unsigned char t_orientation; typedef enum e_operation { SA, SB, SS, PA, PB, RA, RB, RR, RRA, RRB, RRR } t_operation; typedef struct s_push_swap { int nb_operations; int nb_elem; t_stack *stack_a; t_stack *stack_b; int nb_a; int nb_b; t_bool option_v; t_bool option_n; t_bool option_r; t_bool option_m; int sa; int sb; int ss; int pa; int pb; int ra; int rb; int rr; int rra; int rrb; int rrr; } t_push_swap; t_stack *ft_check_arg(char **argv, int argc, t_push_swap *data); t_stack *lst_new(int val); void lst_add(t_stack **alst, t_stack *new); t_bool ft_is_sorted(t_stack *stack); t_bool ft_is_prev_sorted(t_stack *stack); int ft_get_min(t_stack *stack); int ft_get_max(t_stack *stack); int ft_get_min_pos(t_stack *stack); int *ft_get_3_elems(t_push_swap *data); t_bool ft_needs_swap_top(t_push_swap *data); t_bool ft_needs_swap_bottom(t_push_swap *data); void ft_swap_bottom(t_push_swap *data); void ft_normal_sort(t_push_swap *data); void ft_handle_three_elems(t_push_swap *data); t_bool ft_is_special_case(t_push_swap *data); void ft_swap(t_stack **stack); void ft_push(t_stack **stack_src, t_stack **stack_dest); void ft_rotate(t_stack **stack); void ft_reverse(t_stack **stack); void ft_sa(t_push_swap *data); void ft_sb(t_push_swap *data); void ft_ss(t_push_swap *data); void ft_pa(t_push_swap *data); void ft_pb(t_push_swap *data); void ft_ra(t_push_swap *data); void ft_rb(t_push_swap *data); void ft_rr(t_push_swap *data); void ft_rra(t_push_swap *data); void ft_rrb(t_push_swap *data); void ft_rrr(t_push_swap *data); void ft_print_stack(t_stack *stack, char stack_letter, int nb_elem, t_orientation or); void ft_print_nb_operations(t_push_swap *data); void ft_print_operation(t_operation operation); void ft_print_separator(t_push_swap *data); void ft_report(t_push_swap *data); #endif
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "monty.h" /** * analize - analize the code * @stack: the stack * @line_number: number of the line * Return: 0 on failure, else 1 **/ int analize(stack_t **stack, unsigned int line_number) { int type_i; instruction_t type[] = { {"push", push_func}, {"pall", pall_func}, {"pint", pint_func}, {"pop", pop_func}, {"swap", swap_func}, {"add", add_func}, {"nop", nop_func}, {"sub", sub_func}, {"div", div_func}, {"mul", mul_func}, {"mod", mod_func}, {NULL, NULL} }; for (type_i = 0; type[type_i].opcode != NULL; type_i++)/*Recorro type*/ { if (strcmp(code[0], type[type_i].opcode) == 0) { type[type_i].f(stack, line_number); break; } } if (type[type_i].opcode == NULL) { return (0); } return (1); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<signal.h> #include<sys/wait.h> #include<sys/socket.h> #include<arpa/inet.h> #define BUF_SIZE 30 void read_childproc(int sig) { pid_t pid; int status; pid = waitpid(-1, &status, WNOHANG); printf("removed proc id: %d \n",pid); } int main(int argc,char* argv[]) { int serv_sock,clnt_sock; struct sockaddr_in serv_adr,clnt_adr; pid_t pid; struct sigaction act; socklen_t adr_sz; int str_len,state; char buf[BUF_SIZE]; if(argc != 2) { printf("Usage: %s <port>\n",argv[0]); exit(-1); } act.sa_handler = read_childproc; sigemptyset( &act.sa_mask ); act.sa_flags = 0; state = sigaction( SIGCHLD, &act, 0 ); serv_sock = socket(AF_INET, SOCK_STREAM, 0); if(-1 == serv_sock) { perror("socket"); exit(-1); } bzero(&serv_adr,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) { perror("bind"); exit(-1); } if(listen(serv_sock, 5) == -1) { perror("listen"); exit(-1); } while(1) { adr_sz = sizeof(clnt_adr); clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr, &adr_sz); if(-1 == clnt_sock) { continue; } else puts("new clinet connected ...."); pid = fork(); if(-1 == pid) { close(clnt_sock); continue; } //子程序运行区 if(0 == pid) { close(serv_sock); while( (str_len=read(clnt_sock, buf, BUF_SIZE)) != 0) { write(clnt_sock,buf,str_len); } close(clnt_sock); puts("client disconnected..."); return 0; } //父进程运行区 else { close(clnt_sock); } } close(serv_sock); return 0; }