language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/** Validation functions * * Validation functions validate a null-terminated string or the start of one, * and they all have similar signatures and work in the same way. * * The functions are passed a pointer `cur` (in)to a string to validate by * reference. They are also passed a pointer to a pointer `next` to optionally * return the location of the first character after the validated portion of the * string in. If `next` is NULL, validation is only successful if the entire * string matches (i.e. after matching, we have reached the end of the string). * * On success, if `next` is not NULL then the `*next` is set to point to the * first character after the validated portion of the string. The function then * returns 0; * * If validation fails, the return value will be nonzero and `*next` will be * unchanged. * * @param cur Pointer to the first character to validate (in). * @param next Pointer to set to the next character (out). * @return 0 on success, 1 on error. */ #pragma once #include <stddef.h> #include <stdint.h> /** At end of buffer. * * This validates that we are at the end of the buffer. * */ int validate_end(const char * cur); /** Validate a specified literal character. * * Checks that the string starts with the given character. * * See validation functions above. */ int validate_literal(char c, const char * cur, const char ** next); /** Validate an ASCII lower- or uppercase letter. * * See validation functions above. */ int validate_letter(const char * cur, const char ** next); /** Validate an ASCII digit. * * See validation functions above. */ int validate_digit(const char * cur, const char ** next); /** Validate a number. * * This validates a simple positive decimal number of at most `max_digits` * digits. `max_digits` must be at least one. * * See validation functions above. */ int validate_number(ptrdiff_t max_digits, const char * cur, const char ** next); /** Validate a network device name. * * Network device names (eth0, tun1, etc.) must start with a lower- or * uppercase ASCII letter, optionally followed by lower- or uppercase * ASCII letters or digits. * * See validation functions above. */ int validate_dev(const char * cur, const char ** next); /** Validate an IPv4 address in dotted-decimal notation. * * See validation functions above. */ int validate_ip(const char * cur, const char ** next); /** Validate a network address range. * * This is an IPv4 address in dotted-decimal notation, followed by a slash and a * netmask expressed as a single integer. * * See validation functions above. */ int validate_network(const char * cur, const char ** next); /** Validate an endpoint. * * This is an IPv4 address in dotted-decimal notation, followed by a colon and a * port expressed as a single integer. * * See validation functions above. */ int validate_endpoint(const char * cur, const char ** next); /** Validate a WireGuard key. * * This is a 43-character Base-64 string, followed by an = literal. * * See validatefunctions above. */ int validate_wireguard_key(const char * cur, const char ** next);
C
#include <stdlib.h> #include <sys/unistd.h> #include <stdio.h> int main(int argc, char * argv[]) { int fd; char template[] = "/tmp/somestringXXXXXX"; fd = mktemp(template); if (fd == -1) { printf("error to open file!"); exit(1); } printf("open file is: %s\n", template); unlink(template); if (close(fd) == -1) { printf("error to close file!"); exit(1); } return 0; }
C
/* * File: pageframe.c * ***************************************************************************** * Copyright 2020-2021 Scott Maday * Check the LICENSE file that came with this program for licensing terms */ #include "bootloader.h" #include "bitmap.h" #include "x86_64/atomic.h" #include "memory.h" #include "paging.h" #include "pageframe.h" // Atomic lock and unlock functions using [bit] for the mutex static inline void _pageframe_spinlock(enum PageframeMutexBit bit); static inline void _pageframe_unlock(enum PageframeMutexBit bit); // Total size of memory space (bytes), regardless of whether it's usable or not static size_t s_memory_total_size = 0; // Size of memory space (bytes) used by paging static size_t s_memory_used_size = 0; // Size of memory space (bytes) used by reserved paging static size_t s_memory_reserved_size = 0; // Bitmap of usable memory space // A bit will be 1 if it's in-use, else 0 if it's free static struct Bitmap s_pageframemap; // Holds current bitmap index to help optimize paging static size_t s_current_index = 0; // Pageframe mutex static uint64_t s_mutex = 0; static inline void _pageframe_spinlock(enum PageframeMutexBit bit) { atomic_spinlock(&s_mutex, bit); } static inline void _pageframe_unlock(enum PageframeMutexBit bit) { atomic_unlock(&s_mutex, bit); } void pageframe_init() { struct MemoryMap* memorymap = bootloader_get_info()->memorymap; size_t entries_num = memorymap->entries_num; struct MemoryMapEntry* largest_primary = NULL; // Find largest primary memory region for(size_t i = 0; i < entries_num; i++) { struct MemoryMapEntry* memorymap_entry = memorymap->entries + i; if(memorymap_entry->type == MEMORY_TYPE_USABLE && (largest_primary == NULL || memorymap_entry->num_pages > largest_primary->num_pages)){ largest_primary = memorymap_entry; } s_memory_total_size += memorymap_entry->num_pages * MEMORY_PAGE_SIZE; } // Assign bitmap bitmap_initialize(&s_pageframemap, largest_primary->physical_base, s_memory_total_size / MEMORY_PAGE_SIZE / BITMAP_SCALE); // Reserve all pages pageframe_reserve(0, s_memory_total_size / MEMORY_PAGE_SIZE); // Unreserve unusable memory segments for(size_t i = 0; i < entries_num; i++) { struct MemoryMapEntry* memorymap_entry = memorymap->entries + i; if(memorymap_entry->type != MEMORY_TYPE_USABLE){ continue; } size_t reserved_size = memorymap_entry->num_pages * MEMORY_PAGE_SIZE; pageframe_unreserve(memorymap_entry->physical_base, reserved_size / MEMORY_PAGE_SIZE); } // Lock the s_pageframemap itself size_t pageframemap_pages = NEAREST_PAGE(s_pageframemap.size); pageframe_lock(s_pageframemap.buffer, pageframemap_pages); // Lock kernel space size_t kernel_size = (size_t)&_kernel_end - (size_t)&_kernel_start; size_t kernel_pages = NEAREST_PAGE(kernel_size); pageframe_lock(KERNEL_PHYSICAL_ADDRESS(&_kernel_start), kernel_pages); // Reserve first 256 pages pageframe_reserve(0, PAGEFRAME_INITIAL_RESERVE_PAGES); } bool pageframe_manipulate(uint64_t index, bool state) { if(bitmap_get(&s_pageframemap, index) == state){ return true; // already in state } return bitmap_set(&s_pageframemap, index, state); } void* pageframe_request() { _pageframe_spinlock(PAGEFRAME_MUTEX_REQUEST); for(; s_current_index < bitmap_adjusted_size(&s_pageframemap); s_current_index++){ if(bitmap_get(&s_pageframemap, s_current_index) == true){ continue; // not free } void* page = (void*)(s_current_index * MEMORY_PAGE_SIZE); // transform the index into the page address s_current_index++; pageframe_lock(page, 1); _pageframe_unlock(PAGEFRAME_MUTEX_REQUEST); return page; } // TODO Page frame swap to file _pageframe_unlock(PAGEFRAME_MUTEX_REQUEST); return NULL; } void* pageframe_request_pages(size_t pages) { _pageframe_spinlock(PAGEFRAME_MUTEX_REQUEST); size_t bitmap_size = bitmap_adjusted_size(&s_pageframemap); while(s_current_index < bitmap_size) { for(size_t j = 0; j < pages; j++) { if(bitmap_get(&s_pageframemap, s_current_index + j) == true) { s_current_index += j + 1; goto not_free; } } goto exit; not_free: continue; exit: { void* page = (void*)(s_current_index * MEMORY_PAGE_SIZE); // transform the index into the physical page address s_current_index += pages; pageframe_lock(page, pages); _pageframe_unlock(PAGEFRAME_MUTEX_REQUEST); return page; } } _pageframe_unlock(PAGEFRAME_MUTEX_REQUEST); return NULL; } void pageframe_free(void* physical_address, size_t pages) { _pageframe_spinlock(PAGEFRAME_MUTEX_FREE); uint64_t start = (uint64_t)physical_address / MEMORY_PAGE_SIZE; for(uint64_t i = start; i < start + pages; i++){ if(pageframe_manipulate(i, false)){ if(s_memory_used_size >= MEMORY_PAGE_SIZE) { // prevent overflow s_memory_used_size -= MEMORY_PAGE_SIZE; } if(s_current_index > i) { s_current_index = i; } } } _pageframe_unlock(PAGEFRAME_MUTEX_FREE); } void pageframe_lock(void* physical_address, size_t pages) { _pageframe_spinlock(PAGEFRAME_MUTEX_LOCK); uint64_t start = (uint64_t)physical_address / MEMORY_PAGE_SIZE; for(uint64_t i = start; i < start + pages; i++){ if(pageframe_manipulate(i, true)){ s_memory_used_size += MEMORY_PAGE_SIZE; } } _pageframe_unlock(PAGEFRAME_MUTEX_LOCK); } void pageframe_unreserve(void* physical_address, size_t pages) { _pageframe_spinlock(PAGEFRAME_MUTEX_FREE); uint64_t start = (uint64_t)physical_address / MEMORY_PAGE_SIZE; for(uint64_t i = start; i < start + pages; i++){ if(pageframe_manipulate(i, false)){ if(s_memory_reserved_size >= MEMORY_PAGE_SIZE) { // prevent overflow s_memory_reserved_size -= MEMORY_PAGE_SIZE; } if(s_current_index > i) { s_current_index = i; } } } _pageframe_unlock(PAGEFRAME_MUTEX_FREE); } void pageframe_reserve(void* physical_address, size_t pages) { _pageframe_spinlock(PAGEFRAME_MUTEX_LOCK); uint64_t start = (uint64_t)physical_address / MEMORY_PAGE_SIZE; for(uint64_t i = start; i < start + pages; i++){ if(pageframe_manipulate(i, true)){ s_memory_reserved_size += MEMORY_PAGE_SIZE; } } _pageframe_unlock(PAGEFRAME_MUTEX_LOCK); } void pageframe_reserve_size(void* physical_address, size_t size) { pageframe_reserve(physical_address, NEAREST_PAGE(size)); } size_t memory_get_total_size() { return s_memory_total_size; } size_t memory_get_used_size() { return s_memory_used_size; } size_t memory_get_reserved_size() { return s_memory_reserved_size; } size_t memory_get_free() { return s_memory_total_size - s_memory_used_size - s_memory_reserved_size; }
C
#include <stdio.h> void sort2 (int *n1, int *n2) { if (*n1 > *n2) { int tmp = *n1; *n1 = *n2; *n2 = tmp; } } int main () { int x, y; printf("x = "); scanf("%d", &x); printf("y = "); scanf("%d", &y); printf("x = %d, y = %d\n||\n|| swapping... \n\\/\n", x, y); sort2(&x, &y); printf("x = %d, y = %d\n", x, y); }
C
void sr(char** b, int r, int c, int x, int y) { if (b[x][y] == 'O') { b[x][y] = 'o'; if (x) sr(b, r, c, x - 1, y); if (x != r - 1) sr(b, r, c, x + 1, y); if (y) sr(b, r, c, x, y - 1); if (y != c - 1) sr(b, r, c, x, y + 1); } } void solve(char** b, int boardRowSize, int boardColSize) { if (boardRowSize <= 2 || boardColSize <= 2) return; for (int i = 0; i < boardColSize; i ++) { if (b[0][i] == 'O') sr(b, boardRowSize, boardColSize, 0, i); if (b[boardRowSize - 1][i] == 'O') sr(b, boardRowSize, boardColSize, boardRowSize - 1, i); } for (int i = 1; i < boardRowSize - 1; i ++) { if (b[i][0] == 'O') sr(b, boardRowSize, boardColSize, i, 0); if (b[i][boardColSize - 1] == 'O') sr(b, boardRowSize, boardColSize, i, boardColSize - 1); } for (int i = 0; i < boardRowSize; i ++) for (int j = 0; j < boardColSize; j ++) { if (b[i][j] == 'o') b[i][j] = 'O'; else if (b[i][j] == 'O') b[i][j] = 'X'; } return; }
C
#ifndef __SLINKLIST_ #define __SLINKLIST_ #include "dsheader.h" /* * Static Linked List * Use a header * */ #define MAXSIZE 12 //only for test typedef char ElemType; typedef int Position; typedef struct { ElemType data; Position cur; }component, SLinkList[MAXSIZE]; void InitList_SL(SLinkList space); void ClearList_SL(SLinkList space, Position *pHead); int ListEmpty_SL(SLinkList space, Position head); int ListLength_SL(SLinkList space, Position head); Status GetElem(SLinkList space, Position head, Position i, ElemType *pe); //Get the ith node value Position LocateElem_SL(SLinkList space, Position head, ElemType e, int (*compare)(ElemType, ElemType e)); Status PriorElem_SL(SLinkList space, ElemType e, ElemType *pe); Status NextElem_SL(SLinkList space, ElemType e, ElemType *pe); Status ListInsertAfter_SL(SLinkList space, Position head, Position p, ElemType e); void ListDelete_SL(SLinkList space, Position head, ElemType e, int (*compare)(ElemType, ElemType )); Status ListTraverse_SL(SLinkList space, Position head, int (*visit)(ElemType)); Position FindPrevious_SL(SLinkList space, Position head, ElemType e, int (*cmp)(ElemType, ElemType)); #endif
C
#include <stdlib.h> #include <string.h> #include "Pract6_aan.h" int prueba_predeterminada(float *e){ char *imagenes[]={"clara1.bmp","oscura1.bmp","oscura2.bmp","oscura3.bmp", "pla1.bmp","porto7.bmp","pp1.bmp","roja1.bmp","roja2.bmp"}; int i; printf("\n\n\nPruebas Predeterminadas:\n\n"); for (i=0; i<9; i++){ aan_ecualizador(imagenes[i],e); system("Imagen_Ecualizada.bmp"); } return 1; } int tus_pruebas(float *e){ char name[200]; int i; //Leer Imagen: printf("\n\n\nElija imagen: "); fgets(name, 200, stdin); fflush (stdin); for (i=strlen(name); (i>=0) && (name[i-1]=='\n'); i--){ name[i-1]=name[i]; } printf("\n\nImagen --> %s\n\n", name); if (aan_ecualizador(name,e)){ system("Imagen_Ecualizada.bmp"); } else { printf("\n\nERROR en el ecualizado de una imagen\n\n"); } return 1; } //Programa Principal: int main(){ printf("******************MENU*********************\n"); printf("* *\n"); printf("* ECUALIZACION DE *\n"); printf("* HISTOGRAMAS *\n"); printf("* *\n"); printf("* Elija pruebas: *\n"); printf("* *\n"); printf("* 1. PRUEBAS PREDETERMINADAS *\n"); printf("* *\n"); printf("* 2. TUS PRUEBAS *\n"); printf("* *\n"); printf("* 0. SALIR *\n"); printf("* *\n"); printf("* Opciones: 1. e[i] = 1./256 *\n"); printf("* 2. e[i] = *\n"); printf("* [0..127] --> (1/512)..(1/128) *\n"); printf("* [128..255]--> (1/128)..(1/512) *\n"); printf("* *\n"); printf("*******************************************\n"); int op,op_tp,cont,i; float e[256]; op = -1; op_tp = -1; cont = 0; while (op != 0){ printf("\n\nMENU Opcion: "); scanf("%d",&op); fflush (stdin); if (op > 0 && op < 3){ printf("\n\nElija opciones, [1-2] --> "); scanf("%d",&op_tp); fflush (stdin); while ((op_tp < 1) || (op_tp > 2)){ printf("\n\nElija una respuesta valida: "); scanf("%d",&op_tp); fflush (stdin); } switch (op_tp){ case 1: //opcion 1: for (i=0; i<256; i++){ e[i] = 1.0/256.0; } break; case 2: //opcion 2: for (i=0; i<127; i++){ e[i] = 1.0/512.0 + (1.0/128.0 - 1.0/512.0)*i/127.0; } for (i=0; i<127; i++){ e[128+i] = e[127-i]; } break; } } switch (op){ case 0: op = 0; break; case 1: printf("\n\nEsta prueba se ejecuta una sola vez,\n"); printf("y finaliza su ejecucion.\n"); printf("Desea continuar: 1. SI 2.NO\n"); scanf("%d",&cont); fflush (stdin); while ((cont < 1) || (cont > 2)){ printf("\n\nElija una respuesta valida: "); scanf("%d",&cont); fflush (stdin); } if (cont == 1){ prueba_predeterminada(e); op = 0; } break; case 2: printf("\n\nTUS PRUEBAS: "); tus_pruebas(e); break; default: printf("\n\nElija una opcion valida\n"); break; } } printf("\n\n\nFIN\n\n"); system("PAUSE"); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> long long factorial(long long n) { long long r = 1; for(long long i = 1; i <= n; i++) { printf("r: %lld i = %lld\n", r, i); r = r * i; } return r; } int main(int argc, char **argv) { long long cnt = 0; long long thing1 = 0; long long thing2 = 0; if(argc == 2){ long long d = atoi(argv[1]); printf("arguement: %lld\n", d); thing1 = factorial(2 * d); printf("fact(2 * d): %lld\n", thing1); thing2 = factorial(d) * factorial(d); printf("fact(d) * fact(d): %lld\n", thing2); cnt = thing1 / thing2; printf("paths for n * n matrix = %lld\n", cnt);} else{ printf("wtf r u doing? pls enter valid dimension scalar integer when running findPaths.c");} return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { //OR IS USED WHEN WE NEED ONLY ONE CONDITION OUT OF ALL char word; printf("which is best place to live, inside earth or outside of earth? (i/o)\n"); scanf(" %c", &word); if((word=='i')||(word=='o')) { printf("wow you are a genius!!"); }else{ printf("answer with in or out , you asshole"); } return 0; }
C
/* Non-Volatile Memory (NVM) is a reprogrammable Flash memory that retains program and data storage even with power off. The NVM Controller (NVMCTRL) connects to the AHB and APB bus interfaces for system access to the NVM block. The AHB interface is used for reads and writes to the NVM block, while the APB interface is used for commands and configuration. The NVM embeds a main array and a separate smaller array intended for EEPROM emulation (RWWEE) that can be programmed while reading the main array. The NVM is organized into rows, where each ROW contains 4 PAGES. A single row erase will erase all four pages in the row. Four write operations are used to write the complete row. MEMORY START ADDRESS SAML21x18 SAML21x17 SAML21x16 SAML21E15 Embedded Flash 0x00000000 256kB 128kB 64kB 32kB Embedded RWW section 0x00400000 8kB 4kB 2kB 1kB FLASH MEMORY Device Flash size Number of pages Page size Last Row Start Last Page Start Last Byte SAML21x18 256kB 4096 64B 0x0003FF00 0x0003FFC0 0x0003FFFF SAML21x17 128kB 2048 64B 0x0001FF00 0x0001FFC0 0x0001FFFF SAML21x16 64kB 1024 64B 0x0000FF00 0x0000FFC0 0x0000FFFF SAML21E15 32kB 512 64B 0x00007F00 0x00007FC0 0x00007FFF RWW SECTION Device Flash size Number of pages Page size SAML21x18 8kB 128 64B SAML21x17 4kB 64 64B SAML21x16 2kB 32 64B SAML21E15 1kB 16 64B */ #ifndef L21_NVM_H #define L21_NVM_H #include "stdint.h" // Functions void NVM_wait_states(uint8_t rws); void NVM_flash_read(uint8_t * buffer, uint16_t * address, uint32_t num); void NVM_flash_erase_row(uint32_t address); void NVM_flash_write(uint8_t * buffer, uint32_t address, uint8_t num); void NVM_clear_page_buffer(void); #endif // L21_NVM_H_
C
#include <stdio.h> #include <stdlib.h> #include "epblas/epblas.h" #define N 10000 Vector_t v2N = NULL; Vector_t v1N_1 = NULL; Vector_t v1N_2 = NULL; float one=1.; void testAppendOneByOne(){ newInitializedCPUVector(&v1N_1, "vector 100-1", N, matrixInitFixed, &one, NULL); for(size_t i = 0; i < N; ++i) { EPARSE_CHECK_RETURN(vappend(&v1N_2, memoryCPU, "vector100-2",one)); } check(vequal(v1N_1, v1N_2), "%s != %s",v1N_1->identifier, v1N_2->identifier); deleteVector(v1N_1); deleteVector(v1N_2); return; error: exit(EXIT_FAILURE); } void testAppendOneByOne_2(){ log_info("Initializing Vector"); newInitializedGPUVector(&v1N_1, "vector 100-1", N, matrixInitFixed, &one, NULL); log_info("Appending into Vector"); for(size_t i = 0; i < N; ++i) { EPARSE_CHECK_RETURN(vappend(&v1N_2, memoryGPU, "vector100-2",one)); } log_info("Checking v1 and v2 for equality"); check(vequal(v1N_1, v1N_2), "%s != %s",v1N_1->identifier, v1N_2->identifier); deleteVector(v1N_1); deleteVector(v1N_2); return; error: exit(EXIT_FAILURE); } void testNMore(){ v2N = NULL; v1N_1 = NULL; newInitializedCPUVector(&v2N, "vector 200", 2 * N, matrixInitFixed, &one, NULL); newInitializedCPUVector(&v1N_1, "vector 100-1", N, matrixInitFixed, &one, NULL); for(size_t i = 0; i < N; ++i) { EPARSE_CHECK_RETURN(vappend(&v1N_1, memoryCPU, "vector 100-1",one)); } check(vequal(v1N_1, v2N), "%s != %s",v1N_1->identifier, v2N->identifier); deleteVector(v1N_1); deleteVector(v2N); return; error: exit(EXIT_FAILURE); } void testNMore_2(){ v2N = NULL; v1N_1 = NULL; newInitializedGPUVector(&v2N, "vector 200", 2 * N, matrixInitFixed, &one, NULL); newInitializedGPUVector(&v1N_1, "vector 100-1", N, matrixInitFixed, &one, NULL); for(size_t i = 0; i < N; ++i) { EPARSE_CHECK_RETURN(vappend(&v1N_1, memoryGPU, "vector 100-1",one)); } check(vequal(v1N_1, v2N), "%s != %s",v1N_1->identifier, v2N->identifier); deleteVector(v1N_1); deleteVector(v2N); return; error: exit(EXIT_FAILURE); } void testNMoreBatchVector(){ v2N = NULL; v1N_1 = NULL; v1N_2 = NULL; newInitializedCPUVector(&v2N, "vector 200", 2*N, matrixInitFixed, &one, NULL); newInitializedCPUVector(&v1N_1, "vector 100-1", N, matrixInitFixed, &one, NULL); EPARSE_CHECK_RETURN(vappend_vector(&v1N_2, memoryCPU,"vector 100-2",v1N_1)) EPARSE_CHECK_RETURN(vappend_vector(&v1N_2, memoryCPU,"vector 100-2",v1N_1)) check(vequal(v1N_2, v2N), "%s != %s",v1N_2->identifier, v2N->identifier); deleteVector(v1N_1); deleteVector(v1N_2); deleteVector(v2N); return; error: exit(EXIT_FAILURE); } void testNMoreBatchVector_2(){ v2N = NULL; v1N_1 = NULL; v1N_2 = NULL; newInitializedCPUVector(&v2N, "vector 200", 2*N, matrixInitFixed, &one, NULL); newInitializedCPUVector(&v1N_1, "vector 100-1", N, matrixInitFixed, &one, NULL); EPARSE_CHECK_RETURN(vappend_vector(&v1N_2, memoryGPU,"vector 100-2",v1N_1)) EPARSE_CHECK_RETURN(vappend_vector(&v1N_2, memoryGPU,"vector 100-2",v1N_1)) check(vequal(v1N_2, v2N), "%s != %s",v1N_2->identifier, v2N->identifier); deleteVector(v1N_1); deleteVector(v1N_2); deleteVector(v2N); return; error: exit(EXIT_FAILURE); } void testNMoreBatchArray(){ v2N = NULL; v1N_2 = NULL; float *arr = (float*)malloc(sizeof(float) * N); check(arr != NULL,"Memory allocation problem"); for(size_t i = 0; i < N; ++i) { arr[i] = one; } newInitializedCPUVector(&v2N, "vector 200", 2*N, matrixInitFixed, &one, NULL); EPARSE_CHECK_RETURN(vappend_array(&v1N_2, memoryCPU,"vector 100-2",N, arr)) EPARSE_CHECK_RETURN(vappend_array(&v1N_2, memoryCPU,"vector 100-2",N, arr)) check(vequal(v1N_2, v2N), "%s != %s",v1N_2->identifier, v2N->identifier); deleteVector(v1N_2); deleteVector(v2N); return; error: exit(EXIT_FAILURE); } void testNMoreBatchArray_2(){ v2N = NULL; v1N_2 = NULL; float *arr = (float*)malloc(sizeof(float) * N); check(arr != NULL,"Memory allocation problem"); for(size_t i = 0; i < N; ++i) { arr[i] = one; } newInitializedCPUVector(&v2N, "vector 200", 2*N, matrixInitFixed, &one, NULL); EPARSE_CHECK_RETURN(vappend_array(&v1N_2, memoryCPU,"vector 100-2",N, arr)) EPARSE_CHECK_RETURN(vappend_array(&v1N_2, memoryCPU,"vector 100-2",N, arr)) check(vequal(v1N_2, v2N), "%s != %s",v1N_2->identifier, v2N->identifier); deleteVector(v1N_2); deleteVector(v2N); return; error: exit(EXIT_FAILURE); } int main() { log_info("Testing testAppendOneByOne()"); testAppendOneByOne(); log_info("Testing testAppendOneByOne()"); testNMore(); log_info("Testing testAppendOneByOne()"); testNMoreBatchVector(); log_info("Testing testAppendOneByOne()"); testNMoreBatchArray(); log_info("Testing testAppendOneByOne()"); testAppendOneByOne_2(); log_info("Testing testAppendOneByOne()"); testNMore_2(); log_info("Testing testAppendOneByOne()"); testNMoreBatchVector_2(); log_info("Testing testAppendOneByOne()"); testNMoreBatchArray_2(); }
C
extern int printValueOfPin(int valueOfPin, int crcCalc) { if (valueOfPin >= 10) { Serial.print("A"); crcCalc += 65; valueOfPin -= 10; int thousands = valueOfPin / 1000; valueOfPin %= 1000; int hundreds = valueOfPin / 100; valueOfPin %= 100; int tens = valueOfPin / 10; valueOfPin %= 10; int unity = valueOfPin; Serial.print(thousands); crcCalc += 48 + thousands; Serial.print(hundreds); crcCalc += 48 + hundreds; Serial.print(tens); crcCalc += 48 + tens; Serial.print(unity); crcCalc += 48 + unity; } else if (valueOfPin < 10) { Serial.print("D"); crcCalc += 68; Serial.print(valueOfPin); crcCalc += valueOfPin + 48; } return crcCalc; }
C
#ifndef WVMCC_STACK_DEF #define WVMCC_STACK_DEF #include <stdlib.h> typedef struct StackNode_ { void* data; struct StackNode_* next; } StackNode; typedef struct { StackNode* head; unsigned int size; } Stack; Stack* stackNew(); void stackPush(Stack* thisStack, void* data); // If success return 0, or return -1 int stackPop(Stack* thisStack, void** dataPtr); int stackTop(Stack* thisStack, void** dataPtr); void stackFree(Stack** thisStackPtr); #endif // !WVMCC_STACK_DEF
C
//Lukasavicus 1132 #include <stdio.h> main(){ int n1, n2, i, sum = 0; scanf ("%d %d", &n1, &n2); int aux; if(n2 < n1){ aux = n1; n1 = n2; n2 = aux; } for(i = n1; i <= n2; i++){ //printf("%d ", i ); if(i % 13 != 0) sum+= i; } printf("%d\n", sum); }
C
#include <config.h> #include <stdlib.h> #include <string.h> #include "backend.h" #include "sdl.h" backend_t *create_backend (void) { /* allocate memory for the instance and zero it */ backend_t *backend = (backend_t *) malloc (sizeof (backend_t)); memset (backend, 0, sizeof (backend_t)); /* initialize the windows vector and the audio callbacks vector */ /* TODO */ /* init sdl since thats the actual backend we are using */ init_sdl (); return backend; } void destroy_backend (backend_t *backend) { /* deinit sdl in corresponding to initing it at creation */ quit_sdl (); /* remove all items from the two vectors */ destroy_all_windows (backend); unregister_all_audio_callbacks (backend); free (backend); } void run_backend (backend_t *backend) { /* TODO: poll events and dispatch them to the interfaces associated with the * source window */ /* TEMP */ SDL_Delay (2000); } void register_audio_callback (backend_t *backend, audio_callback_t *callback, void *data) { /* TODO registered_audio_callback_t registered_callback; registered_callback.callback = callback; registered_callback.data = data; */ /* TODO: push the object to the registered audio callbacks vector */ } void unregister_audio_callback (backend_t *backend, audio_callback_t *callback, void *data) { /* TODO registered_audio_callback_t registered_callback; registered_callback.callback = callback; registered_callback.data = data; */ /* TODO: remove this object from the regestired audio callbacks vector */ } void unregister_all_audio_callbacks (backend_t *backend) { /* TODO: iterate the callbacks vector and call the above function on each */ } window_t *create_window (backend_t *backend, const char *title, int width, int height) { /* allocate memory for the instance and zero it */ window_t *window = (window_t *) malloc (sizeof (window_t)); memset (window, 0, sizeof (window_t)); /* initialize the fields of the struct instance */ window->backend = backend; /* spawn the window via sdl or whatever */ window->sdl_window = create_sdl_window (title, width, height); /* TODO: push this window object to the windows vector */ return window; } void destroy_window (window_t *window) { /* destroy it via sdl or whatever */ destroy_sdl_window (window->sdl_window); /* TODO: remove this window object from the windows vector */ free (window); } void destroy_all_windows (backend_t *backend) { /* TODO: iterate the windows vector and call destroy_window on each */ }
C
#include <stdio.h> int main() { int distance = 100; float power = 2.345f; double super_power = 56789.4532; char initial = 'L'; char first_name[] = "Sergei"; //here we go string char last_name[] = "Miroshnikov"; printf("You are %d miles away .\n", distance); printf("You have %f levels of power .\n", power); printf("You have %f awesome super powers .\n", super_power); printf("Your first name is %s .\n", first_name); printf("Your last name is %s .\n", last_name); printf("My whole name is %s %c. %s. .\n", first_name, initial, last_name); typedef struct wtf { struct wtf *next; } wtf; return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include "fileUtils.h" // for my written functions /*********************************************************************** @author Brendon Murthum @version Fall 2017 This program reads a text file and then outputs anouther text file with all of the text reversed. Assignment https://github.com/irawoodring/343/blob/master/assignments /reverse-file-in-c.md References Tutorialspoint.com https://www.tutorialspoint.com/c_standard_library /c_function_fopen.htm - This is a simple small loop on reading char by char from file ***********************************************************************/ // Use this to output error messages! // fprintf( stderr, "ERROR MESSAGE" ); int main(int argc, char** argv) { /* For handling the allocated memory */ char* buffer; /* Size of input file - This will aid in allocating memory*/ int sizeOfFile; /* Number of characters successfully written to file from memory */ int numberWritten; /* Name of the input file to read from */ char* inputFileString; /* Name of the output file to write to */ char* outputFileString; /* The number of characters read into our dynamic char array */ int numberRead; /* To keep track of if buffer has allocated memory */ int bufferHasMemory = 0; /******************************************************************* This checks to see that the correct number of arguments were passed. On success, it also sets the names of the input and output files. *******************************************************************/ if ( argc == 3 ) { inputFileString = argv[1]; outputFileString = argv[2]; } else { /* ERROR - Wrong number of arguments */ errno = EINVAL; fprintf( stderr, "ERROR: wrong number of arguments!\n" ); return(-1); } /* Read input file into memory */ sizeOfFile = read_file(inputFileString, &buffer); if (sizeOfFile == -2) { /* ERROR - Input file never read to memory */ printf("\nQuitting program due to error!\n"); exit(0); } else if (sizeOfFile == -1) { /* ERROR - Memory was allocated, but inputfile did not close */ printf("\nQuitting program due to error!\n"); free(buffer); exit(0); } else { bufferHasMemory = 1; } /* Write from memory to the file, backwards */ numberWritten = write_file(outputFileString, buffer, sizeOfFile); /* ERROR - Not all characters written to file */ if (numberWritten < sizeOfFile) { fprintf( stderr, "ERROR: not all chars written to file!\n" ); printf("Bytes written backwards to file: %i / %i \n", numberWritten, sizeOfFile); } /* Return memory */ if (bufferHasMemory == 1) { free(buffer); } }
C
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <err.h> typedef struct cs_item_s { char data; int depth; struct cs_item_s *child; struct cs_item_s *sibling; } CSItem; CSItem * csitem_new (char data) { CSItem * it = calloc (1, sizeof (*it)); if (NULL == it) err (EXIT_FAILURE, "csitem_new: calloc"); it->data = data; return it; } CSItem * cstree_parse (CSItem * parent, const char ** spec) { CSItem *child = NULL; while ('\0' != **spec){ if (isspace (**spec)) { ++(*spec); continue; } if (')' == **spec) { if (NULL == child) errx (EXIT_FAILURE, "cstree_parse: empty sibling list"); ++(*spec); return child; } if (isalnum (**spec)) { CSItem *next; if (NULL == parent && NULL != child) errx (EXIT_FAILURE, "cstree_parse: the root cannot have siblings"); next = csitem_new (**spec); next->sibling = child; child = next; if (NULL != parent) parent->child = child; ++(*spec); continue; } if ('(' == **spec) { if (NULL == child) errx (EXIT_FAILURE, "cstree_parse: sibling list without parent"); ++(*spec); cstree_parse (child, spec); continue; } errx (EXIT_FAILURE, "cstree_parse: invalid character `%c'", **spec); } if (NULL == child) errx (EXIT_FAILURE, "cstree_parse: empty root sibling list or unbalanced parenthesis"); return child; } void cstree_compute_depth (CSItem * item, int parent_depth) { item->depth = ++parent_depth; for (item = item->child; NULL != item; item = item->sibling) cstree_compute_depth (item, parent_depth); } void cstree_pre_order (CSItem * item) { int ii; for (ii = 0; ii < item->depth; ++ii) printf (" "); printf ("%c\n", item->data); for (item = item->child; NULL != item; item = item->sibling) cstree_pre_order (item); } void cstree_post_order (CSItem * item) { int ii; CSItem * child; for (child = item->child; NULL != child; child = child->sibling) cstree_post_order (child); for (ii = 0; ii < item->depth; ++ii) printf (" "); printf ("%c\n", item->data); } void cstree_free (CSItem * item) { CSItem * child; for (child = item->child; NULL != child; child = child->sibling) cstree_free (child); free (item); } int main (int argc, char ** argv) { CSItem * root; const char * spec = "A(E(7(zyx))D(6543)CB(21))"; printf ("initializing tree\n"); root = cstree_parse (NULL, &spec); printf ("computing depth\n"); cstree_compute_depth (root, -1); printf ("post-order traversal:\n"); cstree_post_order (root); printf ("pre-order traversal:\n"); cstree_pre_order (root); cstree_free (root); return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct Node Node; struct Node { int page; Node *next; }; Node *head = NULL; Node *last = NULL; int hits = 0; int faluts = 0; int size; int read = 0; int write = 0; int access = 0; void hit(int page) { int isExist = 0; Node *cur = head; Node *bfr = head; int i = 0; while (cur != NULL) { if (i == size) break; if (cur->page == page) { isExist = 1; break; } bfr = cur; cur = cur->next; i++; } if (isExist) { bfr->next = cur->next; hits += 1; free(cur); } else { faluts += 1; } Node *node = (Node *)malloc(sizeof(Node)); node->page = page; node->next = head; head = node; } int main() { scanf("%d", &size); FILE *fp = fopen("access.list", "r"); while (1) { int page; char str[100]; int state = fscanf(fp, "%d %s", &page, str); if (state == EOF) break; if (str[0] == 'r') read++; if (str[0] == 'w') write++; access++; hit(page); } faluts = access - hits; double rate = ((double)faluts / access) * 100; printf("Total number of access: %d\n", access); printf("Total number of read: %d\n", read); printf("Total number of write: %d\n", write); printf("Number of page hits: %d\n", hits); printf("Number of page faults: %d\n", faluts); printf("Page fault rate: %d/%d = %.3lf %%", faluts, access, rate); return 0; }
C
/* Copyright (c) 2020 SoulHarsh007 (Harsh Peshwani) * Contact: [email protected] or [email protected] * GitHub: https://github.com/SoulHarsh007/ */ #include <stdio.h> #include <string.h> int main() { char str[50]; printf("Enter the string: "); fgets(str, 50, stdin); for (int i = 0; i <= (strlen(str) - 2) / 2; i++) { char x = str[i]; str[i] = str[(strlen(str) - (2 + i))]; str[(strlen(str) - (2 + i))] = x; } str[strlen(str)] = '\0'; printf("Output: %s\n", str); }
C
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <mpi.h> int main(void) { int i, num, temp, *arr, *input; int psum = 0; MPI_Comm comm; int comm_sz, my_rank; comm = MPI_COMM_WORLD; MPI_Init(NULL, NULL); MPI_Comm_rank(comm, &my_rank); MPI_Comm_size(comm, &comm_sz); arr = (int*)malloc(comm_sz*sizeof(int)); if (my_rank == 0) { srand(getpid()); input = (int*)malloc(comm_sz*sizeof(int)); printf("Input is:"); for (i = 0; i < comm_sz; i++) { input[i] = rand()%10; printf(" %d", input[i]); } printf("\n"); } MPI_Scatter(input, 1, MPI_INT, &num, 1, MPI_INT, 0, comm); MPI_Gather(&psum, 1, MPI_INT, arr, 1, MPI_INT, 0, comm); if (my_rank == 0) psum = num+num; MPI_Reduce(&num, &temp, 1, MPI_INT, MPI_SUM, 0, comm); MPI_Allreduce(&num, &temp, 1, MPI_INT, MPI_SUM, comm); MPI_Gather(&psum, 1, MPI_INT, arr, 1, MPI_INT, 0, comm); if (my_rank == 0) { for (i = 0; i < comm_sz; i++) printf(" %d", arr[i]); printf("\n"); } free(arr); MPI_Finalize(); }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <errno.h> struct entry_node { struct entry_node *next; char entry_name[256]; }; int main(int argc, char **argv) { char *path = argv[1]; char *path_entry = strtok (path, "/"); struct entry_node *head = NULL; struct entry_node *prev = head; /*construct linked list of path names for convenience*/ while (path_entry != NULL){ struct entry_node new_node; strcpy (new_node.entry_name, path_entry); new_node.next = NULL; if (head == NULL){ head = &new_node; prev = head; }else{ prev->next = &new_node; prev = &new_node; } path_entry = strtok(NULL, "/"); } struct entry_node *curr = head; while (curr != NULL){ printf("%s\n", curr->entry_name); curr = curr->next; } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* mmalloc.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: user42 <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/04/17 12:07:16 by user42 #+# #+# */ /* Updated: 2020/04/17 14:31:55 by user42 ### ########.fr */ /* */ /* ************************************************************************** */ #include "../cub3d.h" t_list *g_all_malloc; void *mmalloc(unsigned int size) { void *new; t_list *list; if (!(new = malloc(size + 1))) { free_all_malloc(); ft_putstr("allocation error"); exit(1); } if (!(list = (t_list *)malloc(sizeof(t_list)))) { free_all_malloc(); ft_putstr("allocation error"); exit(1); } ft_bzero(new, size); list->data = new; list->next = g_all_malloc; g_all_malloc = list; return (new); } int free_all_malloc(void) { t_list *prev; while (g_all_malloc) { free(g_all_malloc->data); prev = g_all_malloc; g_all_malloc = g_all_malloc->next; free(prev); } return (0); } int mfree(void *to_free) { t_list **indir; t_list *f; if (!to_free) return (0); indir = &g_all_malloc; while (*indir && (*indir)->data != to_free) indir = &((*indir)->next); f = *indir; if (f) { *indir = (*indir)->next; free(f->data); } free(f); to_free = NULL; return (0); }
C
#include <stdio.h> #include <stdlib.h> /* * Problem 12. Randomize the Numbers 1...N * * Write a program that enters an integer n and prints the numbers * 1, 2, ..., n in random order. */ int main() { int i; int n; int index; int tempElement; printf("Input n = "); scanf("%d", &n); int *arr = malloc(n * sizeof (int)); for (i = 0; i < n; i++) { arr[i] = i + 1; } for (i = 0; i < n; i++) { srand(time(NULL) + i); index = rand() % n; // swap 2 array elements tempElement = arr[i]; arr[i] = arr[index]; arr[index] = tempElement; } printf("\n| n | randomized numbers 1...n\n"); printf("| %3d | ", n); for (i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); free(arr); return (EXIT_SUCCESS); }
C
/* ** main.c for my_ls in /home/boulat_m/rendu/my_ls ** ** Made by Mickael BOULAT ** Login <[email protected]> ** ** Started on Tue Oct 28 10:06:14 2014 Mickael BOULAT ** Last update Sun Nov 2 21:41:51 2014 Mickael BOULAT */ #include <stdlib.h> #include <sys/types.h> #include <dirent.h> #include "list.h" #include "my.h" #include "myls.h" char *get_options(int argc, char **argv, t_main *config) { int nb_options; nb_options = get_nb_opts(argc, argv); config->options = xmalloc(nb_options + 1); my_memset(config->options, (nb_options + 1)); save_options(argc, argv, config); return (NULL); } int init_config(t_main *config) { config->options = NULL; config->nb_directories = 1; config->enabled_options = my_strdup("lRdrt"); config->directories = xmalloc(sizeof(char*)); config->directories[0] = xmalloc(3 * sizeof(char)); config->directories[0] = my_strcpy(config->directories[0], "./"); return (0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* maxSW.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: iprokofy <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/05/03 12:02:12 by iprokofy #+# #+# */ /* Updated: 2018/05/03 16:49:40 by iprokofy ### ########.fr */ /* */ /* ************************************************************************** */ #include "header.h" #include <stdlib.h> #include <limits.h> #include <stdio.h> struct s_deque *dequeInit(void) { struct s_deque *q = malloc(sizeof(struct s_deque)); if (!q) return NULL; q->first = NULL; q->last = NULL; return q; } void pushFront(struct s_deque *deque, int value) { if (!deque) return; struct s_dequeNode *new = malloc(sizeof(struct s_dequeNode)); if (!new) return; new->value = value; if (!deque->first) { new->next = NULL; new->prev = NULL; deque->first = new; deque->last = new; } else { new->next = deque->first; new->prev = NULL; deque->first->prev = new; deque->first = new; } } void pushBack(struct s_deque *deque, int value) { if (!deque) return; struct s_dequeNode *new = malloc(sizeof(struct s_dequeNode)); if (!new) return; new->value = value; if (!deque->last) { new->next = NULL; new->prev = NULL; deque->last = new; deque->first = new; } else { new->next = NULL; new->prev = deque->last; deque->last->next = new; deque->last = new; } } int popFront(struct s_deque *deque) { struct s_dequeNode *tmp; int value; if (!deque) return INT_MIN; if (!deque->first) return INT_MIN; value = deque->first->value; tmp = deque->first; deque->first = deque->first->next; if (!deque->first) deque->last = NULL; else deque->first->prev = NULL; free(tmp); return value; } int popBack(struct s_deque *deque) { struct s_dequeNode *tmp; int value; if (!deque) return INT_MIN; if (!deque->last) return INT_MIN; value = deque->last->value; tmp = deque->last; deque->last = deque->last->prev; if (!deque->last) deque->first = NULL; else deque->last->next = NULL; free(tmp); return value; } int peekBack(struct s_deque *deque) { if (!deque) return INT_MIN; if (!deque->last) return INT_MIN; return deque->last->value; } int peekFront(struct s_deque *deque) { if (!deque) return INT_MIN; if (!deque->first) return INT_MIN; return deque->first->value; } struct s_max *maxSlidingWindow(int *arr, int n, int k) { if (k > n || k < 0) return NULL; struct s_deque *q = dequeInit(); struct s_max *result = malloc(sizeof(struct s_max)); result->max = malloc(sizeof(int) * (n - k + 1)); result->length = n - k + 1; int i; for (i = 0; i < k; i++) { while (q->last && peekBack(q) != INT_MIN && arr[i] >= arr[peekBack(q)]) popBack(q); pushBack(q, i); } for (i = k; i < n; i++) { result->max[i - k] = arr[peekFront(q)]; while (q->first && peekFront(q) != INT_MIN && peekFront(q) <= i - k) popFront(q); while (q->last && peekBack(q) != INT_MIN && arr[i] >= arr[peekBack(q)]) popBack(q); pushBack(q, i); } result->max[i - k] = arr[peekFront(q)]; return result; }
C
int access(char* pathname, char mode) // mode ='r', 'w', 'x' { int ino; MINODE* mip; // if running is SUPERuser process : return OK; if (running->uid == 0) return 1; // get INODE of pathname into memory; ino = getino(pathname); mip = iget(dev, ino); // if owner : return OK if rwx --- --- mode bit is on if ((mip->INODE.i_mode & 0xF000) == OWNER) { if(mode == 'r' && (mip->INODE.i_mode & S_IRUSR)) return 1; if(mode == 'w' && (mip->INODE.i_mode & S_IWUSR)) return 1; if(mode == 'x' && (mip->INODE.i_mode & S_IXUSR)) return 1; } // if same group : return OK if --- rwx --- mode bit is on else if ((mip->INODE.i_mode & 0xF000) == GROUP) { if (mode == 'r' && (mip->INODE.i_mode & S_IRGRP)) return 1; if (mode == 'w' && (mip->INODE.i_mode & S_IWGRP)) return 1; if (mode == 'x' && (mip->INODE.i_mode & S_IXGRP)) return 1; } // if other : return OK if --- --- rwx mode bit is on else if ((mip->INODE.i_mode & 0xF000) == OTHER) { if (mode == 'r' && (mip->INODE.i_mode & S_IROTH)) return 1; if (mode == 'w' && (mip->INODE.i_mode & S_IWOTH)) return 1; if (mode == 'x' && (mip->INODE.i_mode & S_IXOTH)) return 1; } // return NO; return 0; } int maccess(MINODE* mip, char mode) // mode ='r', 'w', 'x' { // if running is SUPERuser process : return OK; if (running->uid == 0) return 1; // if owner : return OK if rwx --- --- mode bit is on if ((mip->INODE.i_mode & 0xF000) == OWNER) { if (mode == 'r' && (mip->INODE.i_mode & S_IRUSR)) return 1; if (mode == 'w' && (mip->INODE.i_mode & S_IWUSR)) return 1; if (mode == 'x' && (mip->INODE.i_mode & S_IXUSR)) return 1; } // if same group : return OK if --- rwx --- mode bit is on else if ((mip->INODE.i_mode & 0xF000) == GROUP) { if (mode == 'r' && (mip->INODE.i_mode & S_IRGRP)) return 1; if (mode == 'w' && (mip->INODE.i_mode & S_IWGRP)) return 1; if (mode == 'x' && (mip->INODE.i_mode & S_IXGRP)) return 1; } // if other : return OK if --- --- rwx mode bit is on else if ((mip->INODE.i_mode & 0xF000) == OTHER) { if (mode == 'r' && (mip->INODE.i_mode & S_IROTH)) return 1; if (mode == 'w' && (mip->INODE.i_mode & S_IWOTH)) return 1; if (mode == 'x' && (mip->INODE.i_mode & S_IXOTH)) return 1; } // return NO; return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <omp.h> const long long num_steps = 1000000000; double step; int main(int argc, char* argv[]) { printf ("Nazwa programu: %s\n", __FILE__); if (argc>1){ omp_set_num_threads(atoi(argv[1])); printf("Zadana liczba wątków: %s\n", argv[1]); } clock_t start, stop; double pi, sum=0.0, x, real_start, real_stop; step = 1./(double)num_steps; start = clock(); real_start=omp_get_wtime(); int i=0; #pragma omp parallel for private(x) reduction(+:sum) for (i=0; i<num_steps; i++){ x = (i + .5)*step; sum=sum+ 4.0/(1.+ x*x); } //pi= sum/numb_of_steps pi = sum*step; stop = clock(); real_stop=omp_get_wtime(); printf("Wartosc liczby PI wynosi %15.12f\n",pi); printf("Suma czasu przetwarzania wszystkich wątków wynosi %f sekund\n",((double)(stop - start)/1000000.0)); printf("Rzeczywisty czas przetwarzania wynosi %lf sekund\n\n",((double)(real_stop - real_start))); return 0; }
C
#include<stdio.h> void translate(int translate_time) { int copy = translate_time; int day = 0; int hour = 0; int minute = 0; int second = 0; day = copy / 86400; //day hour = (copy % 86400)/3600; // hour . minute = ((copy % 86400) % 3600) / 60; second = ((copy % 86400) % 3600) % 60; printf("Է¹ %dʴ %d %dð %d %dʷ ȯ˴ϴ.\n", translate_time, day, hour, minute, second); } int main() { int translate_time; int after_translate_time; while (1) { printf("ȯ ð Էּ : "); scanf("%d", &translate_time); if (translate_time >= 0 && translate_time <= 1000000) break; printf("ٽ Էּ!\n"); } printf("ȯ (Է¹ ) : %d\n", translate_time); translate(translate_time); }
C
/*Alunos: Ccero Cavalcante de Arajo Murilo Lima de Holanda */ // FILA DINMICA #include <stdio.h> #include <stdlib.h> #include <conio.h> int c=0; //Varivel que indica se a fila j foi criada ou no typedef int TipoT; //Definindo o tipo de contedo da fila dinmica typedef struct cel //Definindo a estrutura clula, que formar a fila { TipoT conteudo; struct cel *prox; }celula; typedef struct //Definindo a estrutura fila { celula *primeiro,*ultimo; }TipoFila; TipoFila* criafila() //Cria uma nova fila { TipoFila* Fila = (TipoFila*) malloc(sizeof(TipoFila)); Fila->primeiro=(celula*) malloc(sizeof(celula)); Fila->ultimo=(celula*) malloc(sizeof(celula)); Fila->ultimo->prox=NULL; Fila->primeiro=Fila->ultimo; return(Fila); } int vazia(TipoFila *Fila) //Verifica se a fila est vazia { return(Fila->primeiro==Fila->ultimo); } void Inserir(TipoT x,TipoFila *Fila) //Insere um elemento na fila { Fila->ultimo->prox=(celula*) malloc(sizeof(celula)); Fila->ultimo=Fila->ultimo->prox; Fila->ultimo->conteudo=x; Fila->ultimo->prox=NULL; } void Remover(TipoFila *Fila) //Remove um elemento da fila { celula *aux; aux=Fila->primeiro; Fila->primeiro=aux->prox; free(aux); //Libera o espao de memria } int Verifica(int x, TipoFila *Fila) //Verifica se um elemento est na fila { int pos=0; int vf=0; celula *aux; aux=Fila->primeiro->prox; while (aux!=NULL) //Percorrendo os elementos da fila { if (aux->conteudo==x) //Caso o elemento esteja na fila { printf("\nO numero %d esta na posicao %d da fila.",x,pos); vf++; } pos++; aux=aux->prox; } if (vf==0) //Caso o elemento no esteja na fila printf("\nO elemento %d nao esta na fila!",x); } void Imprime(TipoFila *Fila) //Imprime a fila { celula *aux; aux=Fila->primeiro->prox; while (aux!=NULL) { printf("%d ",aux->conteudo); aux=aux->prox; } } int menu(TipoFila *Fila) //Menu principal { int n; printf("Digite a opcao desejada:\n"); printf("1- Criar uma nova fila\n"); printf("2- Verificar se a fila esta vazia\n"); printf("3- Inserir elemento no final da fila\n"); printf("4- Remover o primeiro elemento da fila\n"); printf("5- Buscar um elemento na lista\n"); printf("6- Imprimir a fila\n"); printf("0- Sair\n"); scanf("%d",&n); system("cls"); switch(n) { case 0: exit(1); //Saindo do programa break; case 1: Fila=criafila(); //Criando uma nova fila c++; printf("Fila criada!"); break; case 2: if (c==0) printf("A fila nao foi criada!"); else if (vazia(Fila)) //Verificando se a fila est vazia printf("A fila esta vazia!"); else printf("A fila nao esta vazia!"); break; case 3: if (c==0) printf("A fila nao foi criada!"); else { int x; printf("Digite numero a ser adicionado\n"); scanf("%d",&x); Inserir(x,Fila); //Inserindo um elemento na fila printf("\nO numero %d foi adicionado na fila!",x); } break; case 4: if (c==0) printf("A fila nao foi criada!"); else { printf("O primeiro elemento da fila foi removido!\n"); Remover(Fila); //Removendo o primeiro elemento da fila } break; case 5: if (c==0) printf("A fila nao foi criada!"); else { int x; printf("Digite o numero a ser buscado:\n"); scanf("%d",&x); Verifica(x,Fila); //Buscando um elemento na fila } break; case 6: if (c==0) printf("A fila nao foi criada!"); else if (vazia(Fila)) printf("A fila esta vazia!"); else { printf("A fila e:\n\n"); Imprime(Fila);//Imprimindo a fila } break; default: system("cls"); menu(Fila); } getch(); system("cls"); menu(Fila); } int main() { TipoFila *F;//Definindo a fila usada no programa menu(F); //Chamando o menu }
C
#include <stdio.h> int main(){ //ask your age int age; printf("What is your age? "); scanf("%d", &age); //compute allowed to date girls age int girlAge = age/2+7; printf("\nYou are allowed to date %d year old girls or older\n\n", girlAge); //randomly compute the remainder printf("The float result of 30/7 is %f\n", 30.0/7.0); //4.xxxx printf("The int result of 30/7 is %d\n", 30/7); //4 printf("The int remainder of 30/7 is %d\n", 30%7); //2 return 0; }
C
void mostrarArray(int array[], int tam) { int i; for(i=0; i<tam;i++) { printf("%d\n",&array[i]); } } void cargarArray(int array[], int tam) { int i; for (i= 0; i <tam;i++) { printf("INGRESE UN NUMERO: "); scanf("%d",array[i]); } } int buscarValor(int array[], int tam, int valor) { // SI LA FUNCION DEVUELVE UN ENTERO, DECLARO UNA FUNCION Y LO DE DEVUELVO int indice = -1; int i; for(i = 0; i <tam;i++) { if(array[1] == valor) { indice = i; break; } } return indice; }
C
/* Nama file : list_double.h Dibuat oleh : Ali Qornan Jaisyurrahman Tanggal : 22 januari 2018 18:42 WIB Fungsi : Lisensi : https://github.com/qornanali/PendopoTonyAgung-OpenGL-C/blob/master/LICENSE */ #ifndef __LISTDouble_H__ #define __LISTDouble_H__ typedef struct Double * P_Double; typedef struct Double{ char name[15]; double value; P_Double next; } Double; typedef struct LDoubles{ P_Double first; P_Double last; } LDoubles; /* Method fungsi untuk mengalokasikan elemen baru pada memori. */ P_Double allocDouble(); /* Method fungsi untuk mencari satu elemen pada linked list double. */ P_Double getDouble(LDoubles L, char name[]); /* Method prosedur untuk mengubah nilai suatu elemen pada linked list double. */ void setDouble(LDoubles * L, char name[], double value); /* Method prosedur untuk menghapus suatu elemen pada linked list di memori. */ void deAllocDouble (P_Double P); /* Method prosedur untuk menambah satu elemen baru pada linked list double. */ void addDoubleToList(LDoubles * L, P_Double P); /* Method prosedur untuk menghapus satu elemen yang diinginkan pada linked list double. */ void removeDoubleFromList(LDoubles * L, char name[]); /* Method prosedur untuk menginisiasikan struct LDoubles */ void initListDoubles(LDoubles * L); /* Method prosedur untuk menampilkan isi masing-masing elemen yang ada pada linked list double. */ void printListItemDoubles(LDoubles L); /* Method fungsi untuk memasukkan nilai kepada elemen yang sudah dialokasikan pada memori.. */ P_Double createInstanceDouble(char name[], double value); #endif
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #if 0 typedef int bool; #define true 1; #define false 0; typedef struct { int *arr; int size; int capacity; int head; int rear; } MyCircularQueue; /** Initialize your data structure here. Set the size of the queue to be k. */ MyCircularQueue* myCircularQueueCreate(int k) { MyCircularQueue* res = (MyCircularQueue *)malloc(sizeof(MyCircularQueue)); res->arr = (int *)malloc(sizeof(int) * k); res->size = 0; res->capacity = k; res->head = 0; res->rear = 0; return res; } /** Insert an element into the circular queue. Return true if the operation is successful. */ bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) { if (obj->size == obj->capacity) { return false; } obj->arr[obj->rear] = value; obj->rear = (obj->rear + 1) % obj->capacity; obj->size++; return true; } /** Delete an element from the circular queue. Return true if the operation is successful. */ bool myCircularQueueDeQueue(MyCircularQueue* obj) { if (obj->size == 0) { return false; } obj->head = (obj->head + 1) % obj->capacity; obj->size--; return true; } /** Get the front item from the queue. */ int myCircularQueueFront(MyCircularQueue* obj) { if (obj->size == 0) { return -1; } return obj->arr[obj->head]; } /** Get the last item from the queue. */ int myCircularQueueRear(MyCircularQueue* obj) { if (obj->size == 0) { return -1; } return obj->arr[obj->rear == 0 ? obj->capacity - 1 : obj->rear - 1]; } /** Checks whether the circular queue is empty or not. */ bool myCircularQueueIsEmpty(MyCircularQueue* obj) { return obj->size == 0; } /** Checks whether the circular queue is full or not. */ bool myCircularQueueIsFull(MyCircularQueue* obj) { return obj->size == obj->capacity; } void myCircularQueueFree(MyCircularQueue* obj) { } /** * Your MyCircularQueue struct will be instantiated and called as such: * MyCircularQueue* obj = myCircularQueueCreate(k); * bool param_1 = myCircularQueueEnQueue(obj, value); * bool param_2 = myCircularQueueDeQueue(obj); * int param_3 = myCircularQueueFront(obj); * int param_4 = myCircularQueueRear(obj); * bool param_5 = myCircularQueueIsEmpty(obj); * bool param_6 = myCircularQueueIsFull(obj); * myCircularQueueFree(obj); */ int main() { system("pause"); return 0; } #endif
C
#include "stdlib.h" #include "stdio.h" // Creates space for a 9x9 sudoku board unsigned int** CreateBoard() { unsigned int** board = (unsigned int**)malloc(sizeof(unsigned int*) * 9); unsigned int i; for (i = 0; i < 9; i++) board[i] = (unsigned int*)malloc(sizeof(unsigned int) * 9); return board; } // Free the space for 9x9 sudoku board void FreeBoard(unsigned int** board) { unsigned int i; for (i = 0; i < 9; i++) free(board[i]); free(board); } // Output the sudoku board to stdout. void PrintBoard(unsigned int** board) { unsigned int i, j; for (i = 0; i < 9; i ++) { for (j = 0; j <9; j++) printf("%u\t", board[i][j]); printf("\n"); } } // Read a file and populate sudoku board. void ReadBoard(unsigned int** board, char* fileName) { FILE* fp = fopen(fileName, "r"); if (fp == NULL) exit(0); unsigned int i, j; char c; // Initially read as character for (i = 0; i < 9; i++) { for (j = 0; j < 9; j++) { fscanf(fp, " %c", &c); // If c == '-', store 0. Otherwise, store the number. board[i][j] = (c == 45) ? 0 : c - '0'; } } } // returns 1 if the board is sane and okay. // returns 0 if the board is insane, not okay, and doesn't make sence. int CheckSane(unsigned int** board) { unsigned int r, c, r2, c2, boxr, boxc; for (r = 0; r < 9; r++) { for (c = 0; c < 9; c++) { if (board[r][c]) { // Check conflict horizontally for (c2 = 0; c2 < 9; c2++) { if (c != c2 && board[r][c] == board[r][c2]) return 0; } // Check conflict vertically for (r2 = 0; r2 < 9; r2++) { if (r != r2 && board[r][c] == board[r2][c]) return 0; } // Check conflict in the box boxr = r / 3 * 3; // Top of the box boxc = c / 3 * 3; // Leftside of the box for (r2 = boxr; r2 < boxr + 3; r2++) { for (c2 = boxc; c2 < boxc + 3; c2++) { if (r != r2 && c != c2 && board[r][c] == board[r2][c2]) return 0; } } } } } return 1; } // returns 1 if board is solved. // returns 0 if board is not solved. int SolveBoard(unsigned int** board) { // If the board we have is insane, then return 0. if (!CheckSane(board)) return 0; // find an empty slot unsigned int newr, newc, foundEmpty = 0; for (newr = 0; newr < 9; newr++) { for (newc = 0; newc < 9; newc++) { if (!board[newr][newc]) { foundEmpty = 1; break; } } if (foundEmpty) break; } // If there is no empty slot, we've solved the Sudoku! if (!foundEmpty) return 1; // If there is still empty slots, then let's fill it with a random value! unsigned int i; for (i = 1; i <= 9; i++) { board[newr][newc] = i; if (SolveBoard(board)) return 1; } // Backtrack. Reset the slot to empty. board[newr][newc] = 0; return 0; } int main(int argc, char** argv) { unsigned int** board = CreateBoard(); ReadBoard(board, argv[1]); if (!SolveBoard(board)) printf("no-solution\n"); else PrintBoard(board); FreeBoard(board); return 0; }
C
#include <stdio.h> int main() { int n = 13; int cnt=0; for (cnt=0; n; cnt++) n &= n-1; printf("%d\n", cnt); }
C
#include<stdio.h> int main(){ int day = 1; while(day > 0){ printf("请输入天数:"); scanf("%d",&day); printf("%d days are %d weeks,%d days\n",day,day/7,day%7); } return 0; }
C
#include <stdio.h> #include <math.h> int main(int argc, char **argv) { double a,b,c,average,stddev; printf("enter three numbers \n"); scanf("%lf %lf %lf",&a,&b,&c); average=(a+b+c)/3; stddev=(pow((a-average),2)+pow((b-average),2)+pow((c-average),2)/(2)); stddev=(pow(stddev,0.5)); printf("\n This is your average and standard deviation respectivly %lf %lf", average, stddev); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rvagner <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/05/03 19:38:45 by rvagner #+# #+# */ /* Updated: 2015/05/03 22:47:21 by rvagner ### ########.fr */ /* */ /* ************************************************************************** */ #include "arkanoid.h" void get_color(char nb) { if (nb == '1') glColor3f(1.f, 0.f, 0.f); else if (nb == '2') glColor3f(0.f, 1.f, 0.f); else if (nb == '3') glColor3f(0.f, 0.f, 1.f); else if (nb == '4') glColor3f(0.5f, 0.5f, 0.5f); } void draw_barre(float x, float y) { float tx; float ty; tx = 0.25; ty = -0.05; glBegin(GL_POLYGON); glColor3f(0.1f, 0.5f, 0.5f); glVertex2f(x, y); glColor3f(0.5f, 0.8f, 0.5f); glVertex2f(x + tx, y); glColor3f(0.5f, 0.5f, 0.99f); glVertex2f(x + tx, y + ty); glColor3f(0.12f, 0.5f, 0.5f); glVertex2f(x, y + ty); glEnd(); } void draw_circle(t_bal *bal, t_env *e) { float angle; angle = 0.0; glBegin(GL_TRIANGLE_FAN); if (e->lives == 3) glColor3f(0.2, 0.9, 0.6); else if (e->lives == 2) glColor3f(0.9, 0.2, 0.6); else if (e->lives == 1) glColor3f(0.2, 0.6, 0.9); glVertex2f(bal->x1, bal->y1); while (angle <= 2 * 3.14159265) { bal->x2 = bal->x1 + ft_sin(angle) * bal->radius; bal->y2 = bal->y1 + ft_cos(angle) * bal->radius; glVertex2f(bal->x2, bal->y2); angle += 0.005; } glEnd(); } void draw_bricks(t_env *e, t_brick *brick) { init_brick(brick); while (e->map[brick->i]) { brick->x = -0.99; brick->j = 0; while (e->map[brick->i][brick->j]) { if (e->map[brick->i][brick->j] != '0') { glBegin(GL_POLYGON); get_color(e->map[brick->i][brick->j]); glVertex2f(brick->x, brick->y); glVertex2f(brick->x + brick->tx, brick->y); glVertex2f(brick->x + brick->tx, brick->y + brick->ty); glVertex2f(brick->x, brick->y + brick->ty); glEnd(); } brick->x += brick->tx + 0.01; brick->j++; } brick->y += brick->ty - 0.01; brick->i++; } }
C
#include "MyDriver.h" /*++ ʵ麯17ļIJѯ޸ļ --*/ /*++ ȡ޸ļ ȡ޸ļԣȡļСȡ޸ļָ λáȡ޸ļȡ޸ԣֻԡԣ ȡ޸ļ޸ڵȡDDKṩں˺ZwSetInformationFile ZwQueryInformationлȡ޸ļԡ NTSTATUS ZwSetInformationFile ( IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PVOID FileInformation, IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass ); FileHandle: ļ IoStatusBlocks: õ״̬ FileInformation: FileInformationClassͬͬ ΪϢ Length: FileInformationݵij FileInformationClass: ޸Ե NTSTATUS ZwQueryInformationFile ( IN HANDLE FileHandle, OUT PIO_STATUS)BLOCK IoStatusBlock, OUT PVOID FileInformation, IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass ); FileHandle: ļ IoStatusBlock: õ״̬ FileInformation: FileInformationClassͬͬ ΪϢ Length: FileInformationݵij FileInformationClass: ޸Ե ͬFileInformationClassָ޸Ļ ѯ 1. FileInformationClassFileStandardInformationʱ FILE_STANDARD_INFORMATIONṹ壬ļ ĻϢ typedef struct FILE_STANDARD_INFORMATION { LARGE_INTEGER AllocationSize; // ΪļĴС LARGE_INTEGER EndOfFile; // ļβжֽ ULONG NumberOfLinks; // жٸļ BOOLEAN DeletePending; // Ƿ׼ɾ BOOLEAN Directory; // ǷΪĿ¼ } FILE_STANDARD_INFORMATION, *PFILE_STANDARD_INFORMATION; 2. FileInformationClassFileBasicInformationʱ FILE_BASIC_INFORMATIONṹ壬ļĻ Ϣ typedef struct FILE_BASIC_INFORMATION { LARGE_INTEGER CreationTime; // ļʱ LARGE_INTEGER LastAccessTime; // ʱ LARGE_INTEGER LastWriteTime; // дʱ LARGE_INTEGER ChangeTime; // ޸޸ʱ ULONG FileAttributes; // ļ } FILE_BASIC_INPORMATION, *PFILE_BASIC_INFORMATION; УʱǴһLARGE_INTEGER 1601꾭100ns FileAttributesļԡ FILE_ATTRIBUTE_NORMALһļ FILE_ATTRIBUTE_DIRECTORYĿ¼ FILE_ATTRIBUTE_READONLYļΪֻ FILE_ATTRIBUTE_HIDDENļ FILE_ATTRIBUTE_SYSTEMϵͳļ 3. FileInformationClassFileNameInformationʱ FILE_NAME_INFORMATIONṹ壬ļϢ typedef struct _FILE_NAME_INFORMATION { ULONG FileNameLength; // ļ WCHAR FileName[1]; // ļ } FILE_NAME_INFORMATION, *PFILE_NAME_INFORMATION; 4. FileInformationClassFilePositionInformationʱ FILE_POSITION_INFORMATIONṹ壬ļ Ϣ typedef struct FILE_POSITION_INFORMATION { LARGE_INTEGER CurrentByteOffset; // ǰļָλ } FILE_POSITION_INFORMATION, *PFILE_POSITION_INFORMATION; ʾ --*/ VOID Test17() { KdPrint(("Test17beginning\n")); OBJECT_ATTRIBUTES objectAttributes; IO_STATUS_BLOCK iostatus; HANDLE hfile; UNICODE_STRING logFileUnicodeString; // ʼUNICODE_STRINGַ RtlInitUnicodeString( &logFileUnicodeString, L"\\??\\C:\\1.log" ); // д"\\Device\\HarddiskVolume1\\1.LOG" // ʼobjectAttributes InitializeObjectAttributes( &objectAttributes, &logFileUnicodeString, OBJ_CASE_INSENSITIVE, // ԴСд NULL, NULL ); // ļ NTSTATUS ntStatus = ZwCreateFile( &hfile, GENERIC_READ, &objectAttributes, &iostatus, NULL, FILE_ATTRIBUTE_NORMAL, 0, FILE_OPEN, // ļ򷵻ش FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 ); if (NT_SUCCESS(ntStatus)) { KdPrint(("open file successfully\n")); } FILE_STANDARD_INFORMATION fsi; // ȡļ ntStatus = ZwQueryInformationFile( hfile, &iostatus, &fsi, sizeof(FILE_STANDARD_INFORMATION), FileStandardInformation ); if (NT_SUCCESS(ntStatus)) { KdPrint(("file length:%u\n", fsi.EndOfFile.QuadPart)); } // ޸ĵǰļָ FILE_POSITION_INFORMATION fpi; fpi.CurrentByteOffset.QuadPart = 100i64; ntStatus = ZwSetInformationFile( hfile, &iostatus, &fpi, sizeof(FILE_POSITION_INFORMATION), FilePositionInformation ); if (NT_SUCCESS(ntStatus)) { KdPrint(("update the file pointer successfully!\n")); } // رļ ZwClose(hfile); KdPrint(("Test17finishing\n")); }
C
#include <stdio.h> #include <stdlib.h> void ex () { float I; while(I != 999){ printf("digite a sua ideade\n"); scanf("%f", &I); if(I<16){ printf("nao eleitor\n");} else if(I>=18 && I<65){ printf("eleitor obrigatorio\n");} else { printf("eleitor facutativo\n");} } } int main() { ex(); return 0; }
C
#include<stdio.h> #include<string.h> #include <stddef.h> long long numA[200]; long long numB[200]; long long labA[200]; long long labB[200]; void *new_memcpy(void *destination, const void *source, size_t num); long long max(long long a, long long b) { int first_iteration; if (a > b) return a; return b; } long long min(long long a, long long b) { int first_iteration; if (a < b) return a; return b; } int main() { int first_iteration; int tn; int i; int j; int k; int l; int n; int m; long long total; long long tem; long long MM; long long tempA[200]; long long tempB[200]; scanf("%d", &tn); for (l = 1; l <= tn; l++) { total = 0; scanf("%d%d", &n, &m); for (i = 0; i < n; i++) { scanf("%lld%lld", &numA[i], &labA[i]); } for (i = 0; i < m; i++) { scanf("%lld%lld", &numB[i], &labB[i]); } for (i = 0; i < m; i++) { for (j = i; j < m; j++) { tem = 0; new_memcpy(tempA, numA, sizeof(numA)); new_memcpy(tempB, numB, sizeof(numB)); for (k = 0; k <= i; k++) { if (labB[k] == labA[0]) { MM = min(tempA[0], tempB[k]); tempA[0] -= MM; tempB[k] -= MM; tem += MM; } } if (n > 1) { for (k = i; k <= j; k++) { if (labB[k] == labA[1]) { MM = min(tempA[1], tempB[k]); tempA[1] -= MM; tempB[k] -= MM; tem += MM; } } if (n > 2) { for (k = j; k < m; k++) { if (labB[k] == labA[2]) { MM = min(tempA[2], tempB[k]); tempA[2] -= MM; tempB[k] -= MM; tem += MM; } } } } total = max(total, tem); } } printf("Case #%d: %lld\n", l, total); } return 0; } void *new_memcpy(void *destination, const void *source, size_t num) { int first_iteration; return memcpy(destination, source, num); }
C
#include<stdio.h> #define TRUE 1 #define FALSE 0 #define SIZE 10 void main() { static int lista[SIZE]; int i; int *p, *p2; for(p = &lista[0]; p < lista + SIZE; p++) { printf("Número: "); scanf("%i", p); } for (p = &lista[0]; p < lista + SIZE - 1; p++) { for (p2 = &lista[0]; p2 < lista + SIZE; p2++) { if (*p > *p2) { *p += *p2; *p2 = *p - *p2; *p -= *p2; } } } printf("Array ordenado: "); for (p = lista; p < lista + SIZE; p++) { printf(" %i, ", *p); } printf("\n"); }
C
#include <stdio.h> #include <math.h> #include <stdlib.h> // #include <sndfile.h> /* libsndfile */ #include "wav_reverb.h" #include "convolve.h" /* FFT-based convolution */ #define MODE 2 void process_audio(Buf *ibuf, int iframes, int channels, Buf *rbuf, int rframes, Buf *obuf) { #if (MODE == 1) /* just copy input to output */ int i, j; float *ip, *rp; //printf("processing\n"); ip = (float*)malloc(iframes*sizeof(float)); rp = (float*)malloc(rframes*sizeof(float)); for (i=0; i<channels; i++) { ip = ibuf->buf[i]; rp = rbuf->buf[i]; //printf("ip: %f",ibuf->buf[i]); for (j=0; j<iframes; j++) { //printf("ip[%d]:%f\n",j,ip[j]); obuf->buf[i][j] = ip[j]; } for ( ; j<iframes+rframes-1; j++) { obuf->buf[i][j] = 0; } //printf("processing\n"); } #else #if (MODE == 2) /* do reverberation via time-domain convolution */ int i, j, k, oframes; float *ip, *rp; double v, gain, rms_iv, rms_ov; //float rms_iv, rms_ov; /* set initial values */ rms_iv = 0; rms_ov = 0; ip = (float*)malloc(iframes*sizeof(float)); rp = (float*)malloc(rframes*sizeof(float)); // ToDo: convolve each channel signal with reverb impulse response signal for(i=0;i<channels;i++) { ip = ibuf->buf[i]; rp = rbuf->buf[i]; for(j=0;j<iframes;j++) { obuf->buf[i][j] = 0; //rms_iv = (float)rms_iv + fabs(ip[j]); if(rms_iv < fabs(ip[j])) { rms_iv = fabs(ip[j]); } //printf("ip:%f\n",ip[j]); for(k=0;k<rframes;k++) { if((j-k)>=0) { obuf->buf[i][j] += ip[j-k]*rp[k]; if(rms_ov < fabs(obuf->buf[i][j])) { rms_ov = obuf->buf[i][j]; } //rms_ov = rms_ov + fabs(obuf->buf[i][j]); } } } } //scale to make output rms value be equal to input rms value //rms_iv = sqrt(rms_iv); //rms_ov = sqrt(rms_ov); gain = rms_iv/rms_ov; for(i=0;i<channels;i++) { for(j=0;j<iframes;j++) { obuf->buf[i][j] = obuf->buf[i][j]*gain; } } #else /* (MODE == 3) */ /* do reverberation via frequency-domain convolution */ int i; /* for each channel */ for (i=0; i<channels; i++) { /* convolve channel signal with reverb impulse response signal */ /* frequency domain (FFT) convolution */ convolve(ibuf->buf[i], rbuf->buf[i], iframes, rframes, obuf->buf[i]); } #endif #endif }
C
#include <stdio.h> #include <stdlib.h> int main() { int *p; int a = 10; p = &a; printf("%p\n", p); // 0x7ffff1c233f4 p++; // incrementa... printf("%d %d\n", a, *p); // 10 sabe-se-la-o-que printf("%p\n", p); // 0x7ffff1c233f8 return 0; }
C
/** * syscall.c * * This file holds the implementations of the files declared in syscall.h. */ #include "pcb.h" #include "../fsys/fs.h" #include "../bootinit/paging.h" #include "../keyboard.h" #include "../rtc.h" #include "../x86_desc.h" #include "syscall.h" #include "../terminal.h" #define EIGHT_MB 0x00800000 #define TWELVE_MB 0x00C00000 #define FOUR_MB 0x00400000 #define EIGHT_KB 0x00002000 #define MB_128 0x08000000 #define MB_132 0x08400000 #define NEW_ESP (MB_128 + FOUR_MB - 4) #define PROG_VADDR 0x08048000 /* static definitions of certain file operations */ static fops_t stdin_fops = {&terminal_read, &garbage_write, &terminal_open, &terminal_close}; static fops_t stdout_fops = {&garbage_read, &terminal_write, &terminal_open, &terminal_close}; static fops_t rtc_fops = {&rtc_read, &rtc_write, &rtc_open, &rtc_close}; static fops_t dir_fops = {&dir_read, &dir_write, &dir_open, &dir_close}; static fops_t file_fops = {&file_read, &file_write, &file_open, &file_close}; static fops_t null_fops = {&garbage_read, &garbage_write, &garbage_open, &garbage_close}; /* the magic numbers at the beginning of executables */ static uint8_t ELF[4] = {0x7f, 0x45, 0x4c, 0x46}; /** * run_shell() * * DESCRIPTION: literally runs system_execute with argument "shell" */ int32_t run_shell() { char com[6] = "shell"; return system_execute((uint8_t*)com); } /** * system_execute * * DESCRIPTION: corresponds to system call 2. Executes the given command. * INPUTS: command - the command and arguments to the command, space separated. * OUTPUTS: the return status, if successful. -1 otherwise. */ int32_t system_execute(const uint8_t* command) { if (command == NULL) { return -1; } /***** 1. Parse Command *****/ int8_t filename[MAX_DIRNAME_LEN]; int8_t arguments[MAXBUFFER]; int32_t filename_idx = 0, space_flag = 0; int new_pid = -1; int cmd_len = (int) strlen((int8_t*)command); // skip the leading spaces in command while (command[filename_idx] == ' ') { filename_idx++; } int i; // find the first space for (i = filename_idx; i < cmd_len; i++) { if (command[i] == ' ') { space_flag = 1; break; // finished finding filename } } if ((i - filename_idx) > MAX_DIRNAME_LEN) { return -1; // filename too long } // Initialize arguments to the empty string arguments[0] = '\0'; // copy the info into our local variables if (space_flag) { // copy the filename strncpy(filename, (int8_t*) (command + filename_idx), (i - filename_idx)); filename[i] = '\0'; // null terminate the filename i++; /* put the rest of the arguments into a different string */ strcpy(arguments, (int8_t*)(command + i)); } else { // just copy the filename strcpy(filename, (int8_t*) (command + filename_idx)); } /***** 2. Executable Check *****/ dentry_t dir_entry; /* check if valid file */ if(read_dentry_by_name((uint8_t *) filename, &dir_entry) < 0) return -1; // if file is valid, check if executable by checking first 4 bytes uint8_t buf[4]; read_data(dir_entry.inode_num, 0, buf, 4); if(buf[0] != ELF[0] || buf[1] != ELF[1] || buf[2] != ELF[2] || buf[3] != ELF[3]) return -1; /* find entry point by getting 4-byte unsigned integer in bytes 24-27 */ read_data(dir_entry.inode_num, 24, buf, 4); uint32_t entry_point = *((uint32_t*)buf); /* check PCB array for next process since * we must support up to 6 in kernel */ for (i = 0; i < MAX_PROCS; i++) { if (process_array[i] == 0) { process_array[i] = 1; new_pid = i; break; } } // make sure we found a pid available if (new_pid < 0) return -1; /***** 3. Set Up Program Paging *****/ /* * The program image itself is linked to execute at virtual address * 0x08048000. The way to get this working is to set up a single 4 MB page * directory entry that maps virtual address 0x08000000 (128 MB) to the right * physical memory address (either 8 MB or 12 MB). Then, the program image * must be copied to the correct offset (0x00048000) within that page. */ int32_t phys_addr = EIGHT_MB + (new_pid * FOUR_MB); add_program_page((void*)phys_addr, 1); /***** 4. User-Level Program Loader *****/ /* copy the entire file to memory starting at virtual address 0x08048000 */ read_data(dir_entry.inode_num, 0, (uint8_t*) PROG_VADDR, FOUR_MB); /***** 5. Create Process Control Block (PCB) *****/ // increment the number of processes num_procs++; // each pcb starts at the top of an 8KB block in the kernel pcb_t* new_pcb = (pcb_t*) (EIGHT_MB - (new_pid + 1) * EIGHT_KB); new_pcb->pid = new_pid; // set the pid, indexed at 0 if (executing_initial_shell || curr_pcb == NULL) { // we are executing an initial shell new_pcb->parent_pcb = NULL; new_pcb->term_index = visible_terminal; executing_initial_shell = 0; } else { new_pcb->parent_pcb = curr_pcb; new_pcb->term_index = curr_pcb->term_index; } // save a pointer to the old pcb // pcb_t* old_pcb = curr_pcb; // should never be null // set the current pcb to be the new pcb curr_pcb = new_pcb; // update the tail of the pcb list for this terminal terminal_pcbs[curr_pcb->term_index] = curr_pcb; // copy parsed argument to the buffer in current PCB strcpy((int8_t*) (curr_pcb->arg_buf), arguments); // set the pcb's other data curr_pcb->is_yield = 0; curr_pcb->rtc_freq = 0; curr_pcb->is_yield = 0; /* set up the file descriptor tables */ // first set the stdin/out fops curr_pcb->file_descs[0].fops_table = &stdin_fops; curr_pcb->file_descs[0].inode = dir_entry.inode_num; curr_pcb->file_descs[0].file_position = 0; curr_pcb->file_descs[0].flags = FD_IN_USE; curr_pcb->file_descs[1].fops_table = &stdout_fops; curr_pcb->file_descs[1].inode = dir_entry.inode_num; curr_pcb->file_descs[1].file_position = 0; curr_pcb->file_descs[1].flags = FD_IN_USE; // initialize the rest of the fd tables (starting with entry 2) for(i = 2; i < MAX_FDS; i++) { curr_pcb->file_descs[i].fops_table = &null_fops; curr_pcb->file_descs[i].inode = -1; curr_pcb->file_descs[i].file_position = 0; curr_pcb->file_descs[i].flags = FD_NOT_IN_USE; } /***** 6. Context Switch *****/ // update the tss with the kernel stack info tss.ss0 = KERNEL_DS; tss.esp0 = EIGHT_MB - (curr_pcb->pid) * EIGHT_KB - 4; // save current ebp and esp asm volatile( "movl %%esp, %0;" "movl %%ebp, %1;" :"=g" (curr_pcb->parent_esp), "=g" (curr_pcb->parent_ebp) // outputs : // inputs : "memory" // clobbered registers ); // switch to ring 3. This code is based on code from wiki.osdev.org asm volatile( "cli;" "mov %2, %%ax;" "mov %%ax, %%ds;" "mov %%ax, %%es;" "mov %%ax, %%fs;" "mov %%ax, %%gs;" "pushl %2;" // push user data segment with bottom 2 bits set for ring 3 "pushl %3;" // push user ESP "pushfl;" "popl %%eax;" "orl $0x200, %%eax;" // set IF bit to 1 (bit 9) "pushl %%eax;" // push modified flags "pushl %1;" // push user code segment with bottom 2 bits set for ring 3 "pushl %0;" // push entry point "iret;" : // output : "g" (entry_point), "g" (USER_CS), "g" (USER_DS), "g" (NEW_ESP) // input : "%eax", "memory" // clobbered registers ); return -1; // we should never actually reach this specific return statment } /** * system_halt * * DESCRIPTION: corresponds to system call 1. Halts the program and returns * control the parent. * INPUTS: status - the return status for the program * OUTPUTS: nothing, should jump to execute return. */ int32_t system_halt(uint8_t status) { /* close relevant fds */ int i; for (i = 0; i < MAX_FDS; i++) { // close the halted pcb's fds system_close(i); (curr_pcb->file_descs[i]).fops_table = &null_fops; } /* restore parent data */ int32_t saved_esp = curr_pcb->parent_esp; int32_t saved_ebp = curr_pcb->parent_ebp; process_array[curr_pcb->pid] = 0; terminal_pcbs[curr_pcb->term_index] = curr_pcb->parent_pcb; curr_pcb = curr_pcb->parent_pcb; num_procs--; // if we are trying to exit an initial shell, restart shell if (curr_pcb == NULL || num_procs == 0) { executing_initial_shell = 1; run_shell(); } /* restore parent paging */ int32_t phys_addr = EIGHT_MB + (curr_pcb->pid * FOUR_MB); add_program_page((void*)phys_addr, 1); /* jump to execute return */ // set the tss esp0 to the current pcb's kernel stack tss.esp0 = EIGHT_MB - (curr_pcb->pid) * EIGHT_KB - 4; // restore the saved stack, and perform execute's return asm volatile( "cli;" "movl %2, %%esp;" "movl %1, %%ebp;" "movl %0, %%eax;" "sti;" "leave;" // execute's return "ret;" : // output : "g" ((uint32_t)status), "g" (saved_ebp), "g" (saved_esp) : "%eax" // clobbered registers ); return -1; // we should never get here } /** * system_read * * DESCRIPTION: corresponds to system call 3. Executes the read function of the * specified file descriptor. * INPUTS: fd - the file descriptor to read * buf - the buffer to read to * nbytes - the number of bytes to read. * OUTPUTS: return value of the specific read call if successful, -1 otherwise. */ int32_t system_read(int32_t fd, void* buf, int32_t nbytes) { /* check if the file descriptor is valid */ if (fd < 0 || fd >= MAX_FDS) { // Note that we do not need to check for NULL because some read calls may be // okay with NULL pointers. Let the invidiual read call check for NULL. return -1; } /* check if the fd is in use */ if ((curr_pcb->file_descs[fd]).flags) { /* invoke the correct read call */ return (curr_pcb->file_descs[fd]).fops_table->read(fd, buf, nbytes); } return -1; // if we get here, we return error } /** * system_write * * DESCRIPTION: corresponds to system call 4. Executes the write function of the * specified file descriptor. * INPUTS: fd - the file descriptor to write to * buf - the buffer to write from * nbytes - the number of bytes to write. * OUTPUTS: return value of the specific write call if successful, -1 otherwise. */ int32_t system_write(int32_t fd, const void* buf, int32_t nbytes) { /* check if the file descriptor is valid */ if (fd < 0 || fd >= MAX_FDS) { return -1; } /* check if the fd is in use */ if ((curr_pcb->file_descs[fd]).flags) { /* invoke the correct write call */ return (curr_pcb->file_descs[fd]).fops_table->write(fd, buf, nbytes); } return -1; // if we get here, we return error } /** * system_open * * DESCRIPTION: corresponds to system call 5. Opens the specified file, making * sure to call the open function of the right type of file. * INPUTS: filename - the filename of the file to open * OUTPUTS: the file descriptor allocated to this file */ int32_t system_open(const uint8_t* filename) { // find the correspondingly named file dentry_t dir_entry; if(read_dentry_by_name(filename, &dir_entry) < 0) { return -1; // fail } // allocate an unused file descriptor. make sure to start after stdin/out. int i; for (i = 2; i < MAX_FDS; i++) { if (curr_pcb->file_descs[i].flags == FD_NOT_IN_USE) { // open the file descriptor curr_pcb->file_descs[i].flags = FD_IN_USE; break; } } // make sure we found an empty file descriptor if (i == MAX_FDS) { return -1; } // initialize the file descriptor curr_pcb->file_descs[i].inode = dir_entry.inode_num; curr_pcb->file_descs[i].file_position = 0; // set up the proper jump table and open the file switch(dir_entry.file_type) { case FT_RTC: // rtc if (rtc_open(filename) < 0) { return -1; } curr_pcb->file_descs[i].fops_table = &rtc_fops; break; case FT_DIR: // directory if (dir_open(filename) < 0) { return -1; } curr_pcb->file_descs[i].fops_table = &dir_fops; break; case FT_REG: // file if (file_open(filename) < 0) { return -1; } curr_pcb->file_descs[i].fops_table = &file_fops; break; default: return -1; } return i; // return the file descriptor } /** * system_close * * DESCRIPTION: corresponds to system call 6. Closes the specified file * descriptor. * INPUTS: fd - the file descriptor to close * OUTPUTS: 0 if successful, -1 otherwise */ int32_t system_close(int32_t fd) { /* check if valid file descriptor. note that the user should never be allowed to close the defaults descriptors (0 and 1). */ if (fd < 2 || fd >= MAX_FDS) { return -1; } // check fd table to fd not in use if (curr_pcb->file_descs[fd].flags == FD_NOT_IN_USE) { return -1; // already closed! } // call the close function for that file if (curr_pcb->file_descs[fd].fops_table->close(fd) < 0) { return -1; // the close failed } // close the fd by setting it to not in use curr_pcb->file_descs[fd].flags = FD_NOT_IN_USE; return 0; } /** * system_getargs * * DESCRIPTION: gets program arguments * INPUTS: buf- buffer to copy arguments to * nbytes- bytes to copy * OUTPUTS: 0 if successful, -1 otherwise */ int32_t system_getargs(uint8_t* buf, int32_t nbytes) { // remove leading whitespace int i; for (i = 0; (curr_pcb->arg_buf[i] == ' '); i++); // make sure nbytes is less than the remaining buffer int32_t remaining_buf = MAXBUFFER - i; int32_t bytes_to_copy = nbytes; if (remaining_buf < nbytes) { // copy remaining_buf instead of nbytes bytes_to_copy = remaining_buf; } // copy to the buffer memcpy(buf, &(curr_pcb->arg_buf[i]), bytes_to_copy); buf[bytes_to_copy] = '\0'; return 0; } /** * system_vidmap * * DESCRIPTION: set virtual memory to video memory * INPUTS: screen_start- pointer to starting location in video memorty * OUTPUTS: 0 if successful, -1 otherwise */ int32_t system_vidmap(uint8_t** screen_start) { // Need to check if screen_start is in range if((uint32_t)screen_start > MB_132 || (uint32_t)screen_start <= MB_128){ return -1; } // request from paging what our user-level video memory pointer is uint8_t* vaddr = request_user_video(curr_pcb->term_index); if (vaddr == NULL) { return -1; } // set the screen start address *screen_start = vaddr; return 0; } int32_t system_sethandler(int32_t signum, void* handler_address) { return -1; } int32_t system_sigreturn() { return -1; }
C
#include <stdio.h> #include <stdlib.h> struct std { char name[100]; int roll; float sub1,sub2,sub3; }; int main() { int i;float sum,avg=0.0; struct std s[50]; for(i=0;i<2;i++) { printf("Enter No %d Student Name\n",i); scanf("%s",s[i].name); printf("Enter Roll No\n"); scanf("%d",&s[i].roll); printf("Enter All 3 Subject Marks\n"); scanf("%f%f%f",&s[i].sub1,&s[i].sub2,&s[i].sub3); } for(i=0;i<2;i++) { sum=0.0; sum=s[i].sub1+s[i].sub2+s[i].sub3; printf("Student %d Total Mark Is %.2f\n",i,sum); } for(i=0;i<2;i++) { avg=avg+s[i].sub1+s[i].sub2+s[i].sub3; } printf("Total Average For All Student=%.2f",avg/2); return 0; }
C
#define _GNU_SOURCE #include<stdio.h> #include<stdlib.h> #include<dirent.h> #include<sys/stat.h> void my_readdir(char *pathname) { DIR *pdir; struct dirent *dent; struct stat st; char *tmpstr; fprintf(stdout, "Directory : %s\n", pathname); pdir = opendir(pathname); while((dent = readdir(pdir)) != NULL) { if(dent->d_name[0] == '.') continue; asprintf(&tmpstr, "%s/%s", pathname, dent->d_name); lstat(tmpstr, &st); if(S_ISDIR(st.st_mode)) my_readdir(tmpstr); else fprintf(stdout, "Filename : %s\n", dent->d_name); free(tmpstr); } } int main(int argc, char *argv[]) { char *pathname = "."; if(argc > 1) pathname = argv[1]; my_readdir(pathname); return 0; }
C
#ifndef _F_TYPE_ #define _F_TYPE_ #include "err.h" #include "f_ast.h" #include <stdint.h> #include <stddef.h> #include <stdbool.h> typedef enum type_primitive { TYPE_NONE, /* character types */ TYPE_SCHAR, TYPE_UCHAR, TYPE_CHAR, /* integer types */ TYPE_SHORT_SINT, TYPE_SHORT_UINT, TYPE_SINT, TYPE_UINT, TYPE_LONG_SINT, TYPE_LONG_UINT, TYPE_LONG_LONG_SINT, TYPE_LONG_LONG_UINT, /* floating points */ TYPE_FLOAT, TYPE_DOUBLE, TYPE_LONG_DOUBLE, /* C11 types */ // TYPE_BOOL, /* VOID should properly not be represented a primitive */ TYPE_VOID, _TYPE_PRIMITIVE_COUNT } type_primitive_t; typedef enum type_specifier { /* storage specifiers */ TYPE_EXTERN = 1 << 0, TYPE_STATIC = 1 << 1, TYPE_REGISTER = 1 << 2, /* type qualifiers */ TYPE_CONST = 1 << 3, TYPE_VOLATILE = 1 << 4, /* function qualifier */ TYPE_INLINE = 1 << 5, } type_specifier_t; #define _TYPE_SPECIFIER_COUNT 6 typedef struct type { type_primitive_t primitive : 8; type_specifier_t specifers : 8; uint8_t indirection; } type_t; static const type_t NULL_TYPE = { .primitive = 0, .specifers = 0, .indirection = 0, }; typedef enum type_compatibility { /* if the types are directly compatible */ TYPE_COMPATIBLE, /* if the types are incompatible, but needs conversion/promotion */ TYPE_CONVSERION, /* integer promotion*/ TYPE_INTEGER_PROMOTION, /* if they arent compatible */ TYPE_INCOMPATIBLE, _TYPE_COMPATIBILITY_COUNT } type_compatibility_t; typedef struct expr_type_compatibility { /* represents different things for different * expressions, for instance comparison always produce * an SINT, so in that case it represent the * type we compare */ type_t expr_type; type_compatibility_t left_compatibility : 8; type_compatibility_t right_compatibility : 8; } expr_type_compatibility_t; typedef struct decl_spec decl_spec_t; typedef struct decl_spec { err_location_t err_loc; /* implmented as a linked list for convenience, * however it's properly better to do it as an array */ decl_spec_t* next; enum { DECL_SPEC_NULL = 0, /* to determine primtive type */ DECL_SPEC_VOID, DECL_SPEC_INT, DECL_SPEC_CHAR, DECL_SPEC_SHORT, DECL_SPEC_LONG, DECL_SPEC_LONG_LONG, DECL_SPEC_SIGNED, DECL_SPEC_UNSIGNED, DECL_SPEC_FLOAT, DECL_SPEC_DOUBLE, /* extra specifiers */ DECL_SPEC_CONST, DECL_SPEC_VOLATILE, DECL_SPEC_EXTERN, DECL_SPEC_REGISTER, DECL_SPEC_STATIC, DECL_SPEC_INLINE, _DECL_SPEC_COUNT } spec; } decl_spec_t; type_t f_spec_list_to_type(decl_spec_t* specs); type_t f_get_expr_type(type_t left, type_t right, ast_type_t expr_type, err_location_t* err_loc); uint32_t f_get_type_width(type_t type); void f_print_type(type_t type); void f_print_expr_type_compatibility(expr_type_compatibility_t compat); bool f_is_same_type(type_t a, type_t b); #endif
C
#include "holberton.h" /** *array_range - creates an array of integers. *@min: minimum value. *@max: maximum value. *Return: pointer to array, NULL otherwise. */ int *array_range(int min, int max) { int i, size; int *point; if (min > max) { return (NULL); } size = max - min + 1; point = malloc(sizeof(int) * (size)); if (!point) return (NULL); for (i = 0; i < size; i++) { point[i] = min; min++; } return (point); }
C
#include <stdio.h> int main() { float cp,sp,profit; printf("Enter cost price: "); scanf("%f",&cp); printf("Enter selling price: "); scanf("%f",&sp); profit=sp-cp; if (profit>=0) printf("There was a profit of %0.2f",profit); else printf("There was a loss of %0.2f",-profit); }
C
/* Glidix Shell Utilities Copyright (c) 2014-2017, Madd Games. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/stat.h> #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <dirent.h> const char *progName; int recur = 0; int force = 0; int verbose = 0; /** * The new mode of each file shall be (st_mode & modeAnd | modeOr). */ mode_t modeAnd = 07777; mode_t modeOr = 0; void usage() { fprintf(stderr, "USAGE:\t%s [-Rvf] mode file1 [file2...]\n", progName); fprintf(stderr, "\tChange access modes of files.\n"); fprintf(stderr, "\n\t-R\n"); fprintf(stderr, "\t\tApply changes to directory contents (recursively).\n"); fprintf(stderr, "\n\t-v\n"); fprintf(stderr, "\t\tBe verbose.\n"); fprintf(stderr, "\n\t-f\n"); fprintf(stderr, "\t\tIgnore errors.\n"); }; void processSwitches(const char *sw) { const char *scan; for (scan=&sw[1]; *scan!=0; scan++) { switch (*scan) { case 'R': recur = 1; break; case 'f': force = 1; break; case 'v': verbose = 1; break; default: fprintf(stderr, "%s: unrecognised command-line option: -%c\n", progName, *scan); exit(1); break; }; }; }; void doModeChange(const char *filename); void doModeChangeRecur(const char *name) { DIR *dp = opendir(name); if (dp == NULL) { if ((errno != ENOENT) || (!force)) { perror(name); exit(1); } else { return; }; }; struct dirent *ent; while ((ent = readdir(dp)) != NULL) { if (strcmp(ent->d_name, ".") == 0) { continue; }; if (strcmp(ent->d_name, "..") == 0) { continue; }; char fullpath[256]; strcpy(fullpath, name); if (fullpath[strlen(fullpath)-1] != '/') strcat(fullpath, "/"); strcat(fullpath, ent->d_name); doModeChange(fullpath); }; closedir(dp); }; void doModeChange(const char *filename) { struct stat st; if (stat(filename, &st) != 0) { if ((!force) || (verbose)) { fprintf(stderr, "%s: stat failed on %s: %s\n", progName, filename, strerror(errno)); }; if (!force) { exit(1); }; } else { if (S_ISDIR(st.st_mode)) { if (recur) { doModeChangeRecur(filename); }; }; mode_t newMode = ((st.st_mode & modeAnd) | modeOr) & 07777; if (verbose) { printf("chmod %lo %s\n", newMode, filename); }; if (chmod(filename, newMode) != 0) { if ((!force) || (verbose)) { fprintf(stderr, "%s: chmod failed on %s: %s\n", progName, filename, strerror(errno)); }; if (!force) { exit(1); }; }; }; }; int main(int argc, char *argv[]) { progName = argv[0]; const char *modespec = NULL; const char **files = NULL; int numFiles = 0; int i; for (i=1; i<argc; i++) { if (argv[i][0] == '-') { processSwitches(argv[i]); } else if (modespec == NULL) { modespec = argv[i]; } else { files = realloc(files, sizeof(const char*)*(++numFiles)); files[numFiles-1] = argv[i]; }; }; if (numFiles == 0) // if no mode was specified, there are no files either, so this test is enough. { usage(); return 1; }; mode_t classMask = 07777; char op; // +, - or = mode_t modesToAffect = 0; char c = *modespec; if ((c >= '0') && (c <= '7')) { mode_t newMode; if (sscanf(modespec, "%lo", &newMode) != 1) { usage(); return 1; }; if (newMode > 07777) { usage(); return 1; }; modeAnd = 0; modeOr = newMode; } else { if ((c != '+') && (c != '-') && (c != '=')) { classMask = 0; }; while (((*modespec) != '+') && ((*modespec) != '-') && ((*modespec) != '=')) { switch (*modespec) { case 0: fprintf(stderr, "%s: invalid format for symbolic mode\n", progName); break; case 'u': classMask |= 05700; break; case 'g': classMask |= 03070; break; case 'o': classMask |= 01007; break; case 'a': classMask = 07777; break; default: fprintf(stderr, "%s: unknown reference '%c'\n", progName, *modespec); return 1; break; }; modespec++; }; op = *modespec++; while (*modespec != 0) { switch (*modespec) { case 'r': modesToAffect |= 0444; break; case 'w': modesToAffect |= 0222; break; case 'x': case 'X': modesToAffect |= 0111; break; case 's': modesToAffect |= 06000; break; case 't': modesToAffect |= 01000; break; default: fprintf(stderr, "%s: unknown mode specifier '%c'\n", progName, *modespec); break; }; modespec++; }; switch (op) { case '+': modeAnd = 07777; // keep current modes modeOr = modesToAffect & classMask; // set the specified modes for the specified classes break; case '-': modeAnd = ~(modesToAffect & classMask); // clear all permissions specified modeOr = 0; // set no new permissions break; default: // '=' modeAnd = ~classMask; // clear all current modes for classes we are affecting modeOr = modesToAffect & classMask; // set only the specified modes for the specified classes break; }; }; for (i=0; i<numFiles; i++) { doModeChange(files[i]); }; return 0; };
C
// Write a program that calls `fork()`. Before calling `fork()`, have the main process access a variable // (e.g., x) and set its value to something (e.g., 100). What value is the variable in the child process? // What happens to the variable when both the child and parent change the value of x? /* > What value is the variable in the child process? The value of the variable in the child process is the same in the parent before any reasssignment. > What happens to the variable when both the child and parent change the value of x? The variables appear to be independent. For example, when a `wait()` is placed so that the child comes first, any reassignment in the child process doesn't seem to change the value in the parent process. Conversely, doing a reassignment within the parent doesn't appear to change the value for the child. Would it be accurate to say that these two after the fork are two discrete processes with their own block of memory? */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> int main(void) { // Your code here int hot_var = 100; int rc = fork(); if (rc < 0) { fprintf(stderr, "fork failed\n"); exit(1); } else if (rc == 0) { // hot_var = 0; printf("The value of hot_var is ICE COLD, BRUH! %i DEGREEEES\n", hot_var); } else { hot_var = 69; // waitpid(rc, NULL, 0); printf("The value of hot_var is %i\n", hot_var); } return 0; }
C
#include<stdio.h> #include<string.h> int main() { int n,m,ans=0; scanf("%d%d",&n,&m); int f[n],i,a,b,c; memset(f,0,sizeof(f)); for(i=0;i<m;i++) { scanf("%d%d%d",&a,&b,&c); f[a-1]+=(-1*c); f[b-1]+=c; } for(i=0;i<n;i++) { if(f[i]>0) ans+=f[i]; } printf("%d\n",ans); return 0; }
C
/*e are pushing the operands or the numbers into the stack here. In infix to postfix conversion we pushed the operators into the stack. So here data type of stk will be int whereas in the previous case it was char When an operator is encountered pop 2 numbers,find their result using the operator and push the result back into the stack*/ #include<stdio.h> #include<stdlib.h> #define MAX 100 int stk[MAX],top=-1; char pf[MAX]; int pop(){ return stk[top--]; } void push(int x){ stk[++top]=x; } int evaluate(char op){ int a=pop(),b=pop(); switch(op){ case '+': return b+a; case '-': return b-a; case '*': return b*a; case '/': return b/a; case '^': return b^a; case '%': return b%a; } } int isoperator(char x){ if(x=='+'||x=='-'||x=='*'||x=='/'||x=='%'||x=='^') return 1; return 0; } int main(){ int i,d; printf("\nEnter the postfix expression to be evaluated\n"); scanf("%s",pf); for(i=0;pf[i]!='\0';i++){ if(pf[i]>='0'&&pf[i]<='9') push(pf[i]-48); else if(isoperator(pf[i])) push(evaluate(pf[i]));//Push the result into the stack else{ printf("\nNot a valid expression\n"); return 0; } } if(top==0) printf("\nThe result of the postfix expression is %d\n",stk[top]); else printf("\nNot a valid postfix expression\n"); }
C
#include <stdio.h> #include "PNMwriterCPP.h" using namespace std; void PNMwriter::Write(char *filename){ ofstream outfile (filename); outfile << imagein1->GetMagicNum() << endl; outfile << imagein1->GetWidth() << ' ' << imagein1->GetHeight() << endl; outfile << imagein1->GetMaxVal() << endl; int size = imagein1->GetWidth() * imagein1->GetHeight(); outfile.write((reinterpret_cast<char *>)(imagein1->GetPixels()),size*3); outfile.close(); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <sys/time.h> #ifdef _OPENMP #include <omp.h> #endif // _OPENMP #ifndef VAL_N #define VAL_N 20 #endif int main() { // Problem variables int n = VAL_N , i , k = 2 , me = 0; double a[n]; // Initializing a array for(i=0; i<n; i++) a[i] = 1.; // Print Sequential or Parallel execution int nbThreads = 0; #ifdef _OPENMP nbThreads = omp_get_max_threads(); printf("\n\033[1m Parallel execution with \033[1;31m%d\033[0m\033[1m thread(s) in the team\033[0m\n\n",nbThreads); #else printf("\n\033[1m Sequential execution\033[0m\n\n"); #endif // OpenMP Parallel Region #pragma omp parallel { #pragma omp for schedule(dynamic,2) for(i=0; i<n-k; i++) { a[i] = a[i+k] + 1.; } } // Final Check for(i=0; i<n; i++) printf("a[%3d] = %4.1f\n",i,a[i]); return EXIT_SUCCESS; }
C
#include<unistd.h> #include<stdio.h> #include "funcs.h" int main(void) { //Test 1.2+2.3 == 3.5 printf("%f\n", adder(1.2,2.3)); //Test 5.3-2.1 == 3.2 printf("%f\n", minus(5.3,2.1)); return 0; }
C
/** @file R_z.c * @brief Rotation about z axis utilities code driver. * * This driver contains the code for the rotation about z axis. * * @author Miguel Alonso Angulo. * @bug No know bugs. */ #include "../includes/m_utils.h" #include <stdio.h> #include <stdlib.h> #include <math.h> double **R_z(double angle) { double C, S, **rotmat; C = cos(angle); S = sin(angle); rotmat = m_create(3,3); rotmat[0][0] = C; rotmat[0][1] = S; rotmat[0][2] = 0.0; rotmat[1][0] = -1.0*S; rotmat[1][1] = C; rotmat[1][2] = 0.0; rotmat[2][0] = 0.0; rotmat[2][1] = 0.0; rotmat[2][2] = 1.0; return rotmat; }
C
#include<stdio.h> #include<stdlib.h> long ctoi(char *c) { return (*c - '0'); } long productof(char *p, int n) { long product = 1; for (int i=0; i<n; i++) { product *= ctoi(p); p--; } return product; } int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Must have a arg"); exit(0); } char *p = argv[1]; long product = 1; long max; int max_idx; for (int i=0; i<5; i++) { product *= ctoi(p++); } max = product; for (int i=5; *p; i++) { product = productof(p, 5); if (product > max) { max_idx = i; max = product; } printf("%d\n", product); p++; } printf("Max: %d, Idx: %d\n", max, max_idx); return 0; }
C
#include "stdio.h" #include "ft_printf.h" va_list ap; long long int numberLength(long long int a) { long long int i = 10; long long int len = 0; if ((unsigned long long)a == -9223372036854775808ULL) { return 20; } if (a < 0) { a *= -1; len++; } while (a / i > 0) { len++; i *= 10; } len++; return len; } void printNumber(long long int a) { char arr[21]; int i = 0; int len = 0; len = numberLength(a); arr[len] = '\0'; if ((unsigned long long)a == -9223372036854775808ULL) { ft_putstr("-9223372036854775808"); return ; } if (a < 0) { arr[0] = '-'; a *= -1; } while (i != len) { if (!(arr[0] == '-' && len - i - 1 == 0)) arr[len - i - 1] = a % 10 + '0'; a /= 10; i++; } ft_putstr(&arr[0]); return ; } char checkFinalFlag(char c) { if (c == 's' || c == 'S') return c; if (c == 'p' || c == 'i' || c == 'd' || c == 'D') return c; if (c == 'o' || c == 'O' || c == 'u' || c == 'U') return c; if (c == 'c' || c == 'C' || c == 'x' || c == 'X') return c; if (c == '%') return c; return 0; } int checkInterFlags(char c) { if (c == '#' || c == 0 || c == '-' || c == '+') return 1; if (c == ' ' || c == 'l' || c == 'h' || c == 'j') return 1; if (c == 'z' || c == '.' || (c >= '0' && c <= '9')) return 1; return 0; } void ft_putstr_wchar(const wchar_t *s) { int i; i = 0; if (!s) return ; while (s[i] != '\0') { write(1, &s[i], 1); i++; } } size_t ft_strlen_wchar(const wchar_t *s) { size_t i; i = 0; while (*s != '\0') { i++; s++; } return (i); } flagStruct initializeFlagVars(flagStruct temp) { temp.integerWidth = 0; temp.integerPrecision = 0; temp.zeroFlag = 0; temp.minusFlag = 0; temp.widthExists = 0; temp.precisionExists = 0; temp.counter = 0; temp.index = 1; temp.lFlag = 0; temp.argLen = 0; temp.llFlag = 0; temp.hhFlag = 0; temp.hFlag = 0; temp.sharpFlag = 0; temp.jFlag = 0; temp.zFlag = 0; temp.plusFlag = 0; temp.spaceFlag = 0; temp.isNegative = 0; return temp; } flagStruct sharpFlagChecker(char* flags, flagStruct flagVars) { char *subString; subString = ft_strstr(flags, "#"); if (subString == NULL) return flagVars; else { flagVars.sharpFlag = 1; return flagVars; } } flagStruct llFlagChecker(char* flags, flagStruct flagVars) { char *subString; subString = ft_strstr(flags, "ll"); if (subString == NULL) return flagVars; else { flagVars.llFlag = 1; return flagVars; } } flagStruct hhFlagChecker(char* flags, flagStruct flagVars) { char *subString; subString = ft_strstr(flags, "hh"); if (subString == NULL) return flagVars; else { flagVars.hhFlag = 1; return flagVars; } } flagStruct lFlagChecker(char* flags, flagStruct flagVars) { char *subString; subString = ft_strstr(flags, "l"); if (subString == NULL) return flagVars; else { flagVars.lFlag = 1; return flagVars; } } flagStruct hFlagChecker(char* flags, flagStruct flagVars) { char *subString; subString = ft_strstr(flags, "h"); if (subString == NULL) return flagVars; else { flagVars.hFlag = 1; return flagVars; } } flagStruct jFlagChecker(char* flags, flagStruct flagVars) { char *subString; subString = ft_strstr(flags, "j"); if (subString == NULL) return flagVars; else { flagVars.jFlag = 1; return flagVars; } } flagStruct zFlagChecker(char* flags, flagStruct flagVars) { char *subString; subString = ft_strstr(flags, "z"); if (subString == NULL) return flagVars; else { flagVars.zFlag = 1; return flagVars; } } /* Checks for zero and minus flags in the given temp flag. */ flagStruct zeroAndMinusFlags(char* flags, flagStruct sFlagVars) { while (flags[sFlagVars.index] == '-' || flags[sFlagVars.index] == '0' || flags[sFlagVars.index] == '+' || flags[sFlagVars.index] == ' ') { if (flags[sFlagVars.index] == '0') sFlagVars.zeroFlag = 1; if (flags[sFlagVars.index] == '-') sFlagVars.minusFlag = 1; if (flags[sFlagVars.index] == '+') sFlagVars.plusFlag = 1; if (flags[sFlagVars.index] == ' ') sFlagVars.spaceFlag = 1; sFlagVars.index++; } return sFlagVars; } /* If field width exists, takes its value. */ flagStruct findFieldWidth(char* flags, flagStruct sFlagVars) { while (flags[sFlagVars.index] >= '0' && flags[sFlagVars.index] <= '9') { sFlagVars.charWidth[sFlagVars.counter++] = flags[sFlagVars.index++]; sFlagVars.widthExists = 1; } if (sFlagVars.widthExists) { sFlagVars.integerWidth = ft_atoi(sFlagVars.charWidth); } return sFlagVars; } /* If precision exists, takes its value. */ flagStruct findPrecision(char* flags, flagStruct sFlagVars) { if (flags[sFlagVars.index] == '.') { sFlagVars.index++; sFlagVars.counter = 0; while (flags[sFlagVars.index] >= '0' && flags[sFlagVars.index] <= '9') sFlagVars.charPrecision[sFlagVars.counter++] = flags[sFlagVars.index++]; sFlagVars.precisionExists = 1; sFlagVars.integerPrecision = ft_atoi(sFlagVars.charPrecision); } return sFlagVars; } void ft_putchar_wchar_t(wchar_t c) { write(1, &c, 1); } flagStruct printPadding(flagStruct tempFlagStruct, char padding) { while (tempFlagStruct.integerWidth > tempFlagStruct.argLen) { ft_putchar(padding); tempFlagStruct.integerWidth--; } return tempFlagStruct; } void printArg(flagStruct tempFlagStruct, char finalFlag) { if (finalFlag == 'c') { if (tempFlagStruct.lFlag) ft_putchar(tempFlagStruct.arguments.argumentWideInt); else ft_putchar(tempFlagStruct.arguments.argumentInt); } else if (finalFlag == 's') { if (tempFlagStruct.lFlag) ft_putstr_wchar(tempFlagStruct.arguments.argumentWide); else ft_putstr(tempFlagStruct.arguments.argumentChar); } else if (finalFlag == 'd' || finalFlag == 'i') { if (tempFlagStruct.zFlag) { printNumber(tempFlagStruct.arguments.argumentSSizeT); } else if (tempFlagStruct.llFlag || tempFlagStruct.jFlag) { printNumber(tempFlagStruct.arguments.argumentLLong); } else if (tempFlagStruct.lFlag) { printNumber(tempFlagStruct.arguments.argumentLong); } else if (tempFlagStruct.hhFlag) { printNumber((int)tempFlagStruct.arguments.argumentCharacter); } else if (tempFlagStruct.hFlag) { printNumber(tempFlagStruct.arguments.argumentShort); } else { printNumber(tempFlagStruct.arguments.argumentInt); } } } flagStruct getSFlagArg(flagStruct tempFlagStruct) { char *temp; if (tempFlagStruct.lFlag) { tempFlagStruct.arguments.argumentWide = va_arg(ap, wchar_t*); if (tempFlagStruct.arguments.argumentChar == 0) { ft_putstr("(null)"); } else tempFlagStruct.argLen = ft_strlen_wchar(tempFlagStruct.arguments.argumentWide); } else { tempFlagStruct.arguments.argumentChar = va_arg(ap, char*); if (tempFlagStruct.arguments.argumentChar == 0) { ft_putstr("(null)"); } else { tempFlagStruct.argLen = ft_strlen(tempFlagStruct.arguments.argumentChar); if (tempFlagStruct.precisionExists && tempFlagStruct.integerPrecision < tempFlagStruct.argLen) { temp = ft_strdup(tempFlagStruct.arguments.argumentChar); temp[tempFlagStruct.integerPrecision] = '\0'; tempFlagStruct.arguments.argumentChar = temp; tempFlagStruct.argLen = tempFlagStruct.integerPrecision; } } } return tempFlagStruct; } flagStruct getArg(flagStruct tempFlagStruct, char finalFlag) { if (finalFlag == 'c') { if (!tempFlagStruct.lFlag) tempFlagStruct.arguments.argumentInt = (unsigned char)va_arg(ap, int); else tempFlagStruct.arguments.argumentWideInt = (wchar_t)va_arg(ap, int); } else if (finalFlag == 's') { tempFlagStruct = getSFlagArg(tempFlagStruct); } else if (finalFlag == 'd') { tempFlagStruct = getdFlagArgs(tempFlagStruct); } return tempFlagStruct; } void cFlag(char* flags) { flagStruct cFlagVars; cFlagVars.argLen = 1; cFlagVars = initializeFlagVars(cFlagVars); cFlagVars = zeroAndMinusFlags(flags, cFlagVars); cFlagVars = findFieldWidth(flags, cFlagVars); cFlagVars = findPrecision(flags, cFlagVars); cFlagVars = lFlagChecker(flags, cFlagVars); cFlagVars = getArg(cFlagVars, 'c'); if (cFlagVars.widthExists) { if (cFlagVars.integerWidth > 1) { if (cFlagVars.zeroFlag && !cFlagVars.minusFlag) { cFlagVars = printPadding(cFlagVars, '0'); printArg(cFlagVars, 'c'); } else if (!cFlagVars.zeroFlag && !cFlagVars.minusFlag) { cFlagVars = printPadding(cFlagVars, ' '); printArg(cFlagVars, 'c'); } else if ((!cFlagVars.zeroFlag && cFlagVars.minusFlag) || (cFlagVars.zeroFlag && cFlagVars.minusFlag)) { printArg(cFlagVars, 'c'); cFlagVars = printPadding(cFlagVars, ' '); } } else { printArg(cFlagVars, 'c'); } } else { printArg(cFlagVars, 'c'); } return ; } void sFlag(char* flags) { flagStruct sFlagVars; sFlagVars = initializeFlagVars(sFlagVars); sFlagVars = zeroAndMinusFlags(flags, sFlagVars); sFlagVars = findFieldWidth(flags, sFlagVars); sFlagVars = findPrecision(flags, sFlagVars); sFlagVars = lFlagChecker(flags, sFlagVars); sFlagVars = getArg(sFlagVars, 's'); if (sFlagVars.arguments.argumentChar == 0) { return ; } //prints string with required padding if (!sFlagVars.widthExists && !sFlagVars.precisionExists) { printArg(sFlagVars, 's'); } if (sFlagVars.widthExists && sFlagVars.integerWidth > sFlagVars.argLen) { if ((sFlagVars.zeroFlag && sFlagVars.minusFlag) || (sFlagVars.minusFlag && !sFlagVars.zeroFlag)) { printArg(sFlagVars, 's'); printPadding(sFlagVars, ' '); } else { if (sFlagVars.zeroFlag) printPadding(sFlagVars, '0'); else printPadding(sFlagVars, ' '); printArg(sFlagVars, 's'); } } else if ((sFlagVars.widthExists && sFlagVars.integerWidth <= sFlagVars.argLen) || (sFlagVars.precisionExists && !sFlagVars.widthExists)) { printArg(sFlagVars, 's'); } return ; } flagStruct getdFlagArgs(flagStruct flagVars) { if (flagVars.zFlag) { flagVars.arguments.argumentSSizeT = va_arg(ap, ssize_t); flagVars.argLen = numberLength(flagVars.arguments.argumentSSizeT); } else if (flagVars.llFlag || flagVars.jFlag) { flagVars.arguments.argumentLLong = va_arg(ap, long long int); flagVars.argLen = numberLength(flagVars.arguments.argumentLLong); if (flagVars.arguments.argumentLLong < 0) flagVars.isNegative = 1; } else if (flagVars.lFlag) { flagVars.arguments.argumentLong = va_arg(ap, long int); flagVars.argLen = numberLength(flagVars.arguments.argumentLong); if (flagVars.arguments.argumentLong < 0) flagVars.isNegative = 1; } else if (flagVars.hhFlag) { flagVars.arguments.argumentCharacter = va_arg(ap, int); flagVars.argLen = numberLength(flagVars.arguments.argumentCharacter); if (flagVars.arguments.argumentCharacter < 0) flagVars.isNegative = 1; } else if (flagVars.hFlag) { flagVars.arguments.argumentShort = va_arg(ap, int); flagVars.argLen = numberLength(flagVars.arguments.argumentShort); if (flagVars.arguments.argumentShort < 0) flagVars.isNegative = 1; } else { flagVars.arguments.argumentInt = va_arg(ap, int); flagVars.argLen = numberLength(flagVars.arguments.argumentInt); if (flagVars.arguments.argumentInt < 0) flagVars.isNegative = 1; } return flagVars; } flagStruct getoFlagArgs(flagStruct flagVars) { if (flagVars.zFlag) { flagVars.arguments.argumentSizeT = va_arg(ap, size_t); flagVars.argLen = numberLength(flagVars.arguments.argumentSizeT); } else if (flagVars.llFlag || flagVars.jFlag) { flagVars.arguments.argumentLLong = va_arg(ap, long long int); flagVars.argLen = numberLength(flagVars.arguments.argumentLLong); if (flagVars.arguments.argumentLLong < 0) flagVars.isNegative = 1; } else if (flagVars.lFlag) { flagVars.arguments.argumentLong = va_arg(ap, long int); flagVars.argLen = numberLength(flagVars.arguments.argumentLong); if (flagVars.arguments.argumentLong < 0) flagVars.isNegative = 1; } else if (flagVars.hhFlag) { flagVars.arguments.argumentCharacter = va_arg(ap, int); flagVars.argLen = numberLength(flagVars.arguments.argumentCharacter); if (flagVars.arguments.argumentCharacter < 0) flagVars.isNegative = 1; } else if (flagVars.hFlag) { flagVars.arguments.argumentShort = va_arg(ap, int); flagVars.argLen = numberLength(flagVars.arguments.argumentShort); if (flagVars.arguments.argumentShort < 0) flagVars.isNegative = 1; } else { flagVars.arguments.argumentInt = va_arg(ap, int); flagVars.argLen = numberLength(flagVars.arguments.argumentInt); if (flagVars.arguments.argumentInt < 0) flagVars.isNegative = 1; } return flagVars; } flagStruct makeIntegerArgsNegative(flagStruct tempFlagStruct) { tempFlagStruct.arguments.argumentInt *= -1; tempFlagStruct.arguments.argumentLong *= -1; tempFlagStruct.arguments.argumentLLong *= -1; tempFlagStruct.arguments.argumentShort *= -1; return tempFlagStruct; } void oFlag(char *flags) { flagStruct oFlagVars; oFlagVars = initializeFlagVars(oFlagVars); oFlagVars = zeroAndMinusFlags(flags, oFlagVars); oFlagVars = findFieldWidth(flags, oFlagVars); oFlagVars = findPrecision(flags, oFlagVars); oFlagVars = lFlagChecker(flags, oFlagVars); oFlagVars = llFlagChecker(flags, oFlagVars); oFlagVars = hFlagChecker(flags, oFlagVars); oFlagVars = hhFlagChecker(flags, oFlagVars); oFlagVars = jFlagChecker(flags, oFlagVars); oFlagVars = zFlagChecker(flags, oFlagVars); oFlagVars = sharpFlagChecker(flags, oFlagVars); } void dFlag(char* flags) { flagStruct dFlagVars; dFlagVars = initializeFlagVars(dFlagVars); dFlagVars = zeroAndMinusFlags(flags, dFlagVars); dFlagVars = findFieldWidth(flags, dFlagVars); dFlagVars = findPrecision(flags, dFlagVars); dFlagVars = lFlagChecker(flags, dFlagVars); dFlagVars = llFlagChecker(flags, dFlagVars); dFlagVars = hFlagChecker(flags, dFlagVars); dFlagVars = hhFlagChecker(flags, dFlagVars); dFlagVars = jFlagChecker(flags, dFlagVars); dFlagVars = zFlagChecker(flags, dFlagVars); if (dFlagVars.zeroFlag) if (dFlagVars.precisionExists || dFlagVars.minusFlag) dFlagVars.zeroFlag = 0; if (dFlagVars.plusFlag) if (dFlagVars.spaceFlag) dFlagVars.spaceFlag = 0; dFlagVars = getArg(dFlagVars, 'd'); if (dFlagVars.widthExists && dFlagVars.integerWidth > dFlagVars.argLen) { if (dFlagVars.precisionExists && dFlagVars.integerPrecision > dFlagVars.argLen) { if (dFlagVars.minusFlag) { if (dFlagVars.plusFlag) { if (!dFlagVars.isNegative) { dFlagVars.integerWidth--; ft_putchar('+'); } } if (dFlagVars.spaceFlag) { if (!dFlagVars.isNegative) { dFlagVars.integerWidth--; ft_putchar(' '); } } while (dFlagVars.integerPrecision > dFlagVars.argLen) { ft_putchar('0'); dFlagVars.argLen++; } printArg(dFlagVars, 'd'); printPadding(dFlagVars, ' '); } else { if ((dFlagVars.plusFlag || dFlagVars.spaceFlag) && !dFlagVars.isNegative) { dFlagVars.argLen++; dFlagVars.integerPrecision++; } dFlagVars.counter = dFlagVars.argLen; dFlagVars.argLen = dFlagVars.integerPrecision; printPadding(dFlagVars, ' '); if (!dFlagVars.isNegative) { if (dFlagVars.plusFlag) ft_putchar('+'); if (dFlagVars.spaceFlag) ft_putchar(' '); } while (dFlagVars.integerPrecision > dFlagVars.counter) { ft_putchar('0'); dFlagVars.counter++; } printArg(dFlagVars, 'd'); } } else if (dFlagVars.precisionExists && dFlagVars.integerPrecision == 0) { if (dFlagVars.minusFlag) { if (dFlagVars.plusFlag) { ft_putchar('+'); printPadding(dFlagVars, ' '); } } else if (dFlagVars.plusFlag) { printPadding(dFlagVars, ' '); ft_putchar('+'); } else { dFlagVars.integerWidth++; printPadding(dFlagVars, ' '); } } else { if (dFlagVars.zeroFlag) { if (dFlagVars.plusFlag && !dFlagVars.isNegative) { ft_putchar('+'); dFlagVars.integerWidth--; } else if (dFlagVars.spaceFlag && !dFlagVars.isNegative) { ft_putchar(' '); dFlagVars.integerWidth--; } if (dFlagVars.isNegative) { ft_putchar('-'); printPadding(dFlagVars, '0'); dFlagVars = makeIntegerArgsNegative(dFlagVars); printArg(dFlagVars, 'd'); } else { printPadding(dFlagVars, '0'); printArg(dFlagVars, 'd'); } } else if (dFlagVars.minusFlag) { if (dFlagVars.plusFlag && !dFlagVars.isNegative) { ft_putchar('+'); dFlagVars.integerWidth--; } else if (dFlagVars.spaceFlag && !dFlagVars.isNegative) { ft_putchar(' '); dFlagVars.integerWidth--; } printArg(dFlagVars, 'd'); printPadding(dFlagVars, ' '); } else if (dFlagVars.plusFlag && !dFlagVars.isNegative) { dFlagVars.integerWidth--; printPadding(dFlagVars, ' '); ft_putchar('+'); printArg(dFlagVars, 'd'); } else { printPadding(dFlagVars, ' '); printArg(dFlagVars, 'd'); } } } else { printArg(dFlagVars, 'd'); } } void processTempFlags(char* flags) { int flagsLen; char finalFlag; char* temp; flagsLen = ft_strlen(flags); finalFlag = flags[flagsLen - 1]; if (finalFlag == 's') { sFlag(flags); } else if (finalFlag == 'S') { temp = flags; flags = (char*)ft_memalloc(flagsLen + 1); flags = ft_strcpy(flags, temp); flags[flagsLen - 1] = 'l'; flags[flagsLen] = 's'; flags[flagsLen + 1] = '\0'; flagsLen = ft_strlen(flags); sFlag(flags); } else if (finalFlag == 'c') { cFlag(flags); } else if (finalFlag == 'C') { temp = flags; flags = (char*)ft_memalloc(flagsLen + 1); flags = ft_strcpy(flags, temp); flags[flagsLen - 1] = 'l'; flags[flagsLen] = 'c'; flags[flagsLen + 1] = '\0'; flagsLen = ft_strlen(flags); cFlag(flags); } else if (finalFlag == 'd' || finalFlag == 'i') { dFlag(flags); } else if (finalFlag == 'D') { temp = flags; flags = (char*)ft_memalloc(flagsLen + 1); flags = ft_strcpy(flags, temp); flags[flagsLen - 1] = 'l'; flags[flagsLen] = 'd'; flags[flagsLen + 1] = '\0'; flagsLen = ft_strlen(flags); dFlag(flags); } } int ft_printf(const char* format, ...) { int i; int j; int formatLen; i = 0; formatLen = ft_strlen(format); va_start(ap, format); while (i < formatLen) { if (format[i] == '%') { j = 0; char* tempFlags = (char*)malloc(sizeof(char) * 15); tempFlags[j++] = format[i++]; while (checkInterFlags(format[i]) && i < formatLen) tempFlags[j++] = format[i++]; if (checkFinalFlag(format[i])) tempFlags[j++] = format[i++]; tempFlags[j] = '\0'; //take tempFlags and process and print in respective function processTempFlags(tempFlags); i--; free(tempFlags); } else ft_putchar(format[i]); i++; } va_end(ap); return 0; }
C
/* ============================================================================ Name : Test_Const.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> unsigned int Buffer_Data; unsigned int Buffer_Pointer_Data; void Write_PointerToConstant(unsigned int sendData); void Read_PointerToConstant(const int **readData); void test_PointerToConstant(); void ReadData_func(unsigned int *readData); void WriteData_func(unsigned int sendData); int main(void) { puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */ // Test truyen tham chieu trong C int send_Data = 100; int read_Data = 0; WriteData_func(send_Data); ReadData_func(&read_Data); puts("!!!Truyen tham chieu trong C!!!"); printf("send_Data = %d\n", send_Data); printf("read_Data = %d\n", read_Data); // Test truyen con tro hang(pointer to constant const int *px) trong C puts("!!!pointer to constant - const int *px!!!"); test_PointerToConstant(); // Test truyen vao con tro hang(pointer to constant: const int *px) trong C puts("!!!Test truyen vao con tro hang - const int *p_data!!!"); unsigned int send_Pointer_Data = 789; const int *read_Pointer_Data = 0; Write_PointerToConstant(send_Pointer_Data); Read_PointerToConstant(&read_Pointer_Data); printf("send_Pointer_Data = %d\n", send_Pointer_Data); printf("read_Pointer_Data = %d\n", read_Pointer_Data); return EXIT_SUCCESS; } // Ghi du lieu vao bo dem Buffer_Data void WriteData_func(unsigned int sendData){ Buffer_Data = sendData; } //Doc du lieu vao bo dem Buffer_Data void ReadData_func(unsigned int *readData){ *readData = Buffer_Data; } void test_PointerToConstant(){ int x = 500; int y = 200; const int *px; // khong the sử dụng dereference pointer để thay đổi giá trị của "x" hay "y" px = &x; // => Khong the khai bao *px = 200; duoc printf("px=%p\n", px); printf("*px=%d\n", *px); px = &y; printf("px=%p\n", px); printf("*px=%d\n", *px); } // Ghi du lieu vao bo dem Buffer_Pointer_Data void Write_PointerToConstant(unsigned int sendData){ Buffer_Pointer_Data = sendData; } // Doc du lieu tu bo dem Buffer_Pointer_Data void Read_PointerToConstant(const int **readData){ *readData = Buffer_Pointer_Data; }
C
/*Faa um algoritmo que leia um vetor U[15]. Crie, a seguir, um vetor Primo[15] que conter todos os valores primos do vetor U. Mostre o vetor Primo[15] no final.*/ #include<stdio.h> int main(){ int u[15], primo[15], i, y, div, pos = 0; for(i=0;i<5;i++){ //Armazena os valores no vetor u. printf("Digite a valor da posicao %d do vetor\n",i); scanf("%d",&u[i]); } for (i=0;i<5;i++){ div = 0; for(y=1;y<=u[i];y++){ if(u[i]%y == 0){ div++; } } printf("valor do div %d\n",div); if(div==2){ primo[pos]=u[i]; pos++; } } for(i=0;i<pos;i++){ printf("\n %d",primo[i]); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { char titulo[50]; char genero[50]; int duracion; char descripcion[2000]; int puntaje; char linkImagen[500]; int estado; } eMovie; /** \brief Crea un puntero a estructura. * * \return Puntero a eMovie. * */ eMovie* CreaStruct(); /** \brief Inicializa los estados de las estructuras a 0. * * \param *Peliculas es el puntero a la estructura * \param tam es la cantidad de estructuras a inicializar. * * */ void InicializarEstructura(eMovie* Peliculas, int tam); /** \brief Modifica el tamao de la estructura. * * \param **fron es el puntero a la estructutura. * \param tam tamao del puntero modificado. * \return retorna 0 si se modifico o -1 si no se modifico. * */ int ModificoStruct(eMovie** fron, int tam); /** \brief Pide y guarda los datos para la pelicula. * * \param *Peliculas puntero a la estructura. * \param tam cantidad de peliculas ingresadas. * \return La cantidad de peliculas ingresadas. * */ int AltaPeli(eMovie* Peliculas, int tam); /** \brief Borra los datos de la pelicula en la memoria * * \param *Peliculas puntero a la estructura. * \param tam cantidad de peliculas ingresadas. * * */ int BorrarPeli(eMovie* Peliculas, int tam); /** \brief Modifica los datos de la pelicula en la memoria. * * \param *Peliculas puntero a la estructura. * \param tam cantidad de peliculas ingresadas. * \return la cantidad de peliculas-1. * */ void ModificarPeli(eMovie *Peliculas, int tam); /** \brief Valida si puede ingrersar a opciones especificas. * * \param *Peliculas puntero a la estructura. * \param tam cantidad de peliculas ingresadas. * \return un numero>0 si hay peliculas o 0 si no hay peliculas ingresadas. * */ int PermitirOpciones(eMovie *Peliculas, int tam); /** \brief Tonma la informacion sobre peliculas del archivo.dat. * * \param **Pelis puntero donde se guarda la informacion de peliculas. * \param *cantPelis puntero donde se guarda la cantidad de peliculas. * \return 0 si se tomaron las peliculas o -1 si no se tomaron. * */ int TomarPeliArchivada(eMovie** Pelis, int* cantPelis); /** \brief Agrega una pelicula al archivo binario * * \param *Peliculas la estructura que se agrega al archivo. * \param tam tamao del puntero. * \return 1 si se agrego la pelicula o 0 si no. * */ int AgregoPeli(eMovie* Peliculas, int tam); /** \brief Genera un archivo .html a partir de la informacion de peliculas. * * \param *Peliculas contiene la informacion de las peliculas. * \param name es el nombre que se le pondra al archivo html. * \param tam es la cantidad de peliculas ingresadas. * */ void GenerarWeb(eMovie *Peliculas,char name[], int tam);
C
/* ============================================================================ Name : CS533_Client.c Author : Karthik Uthaman Version : 1.0 Copyright : Published under GNU License. Description : This is the main entry point for the client. It takes user input and starts the requested client by forking a child process. We also create a pipe through which the child process can communicate any status to the parent process. ERROR CONDITIONS HANDLED : 1. Server Crashing 2. Parent process crashing 3. Child process crashing Created on : Sep 21, 2011 ============================================================================ */ #include "CS533_Client.h" #define INVALID_ADDR 53301 #define INVALID_PORT 53302 #define CONNECT_FAILURE 53303 #define FORK_FAILURE 53304 #define MAX_PORT_LEN 32 #define MAX_IP_LEN 16 static sigset_t signal_mask; /*****************FUNCTION DEFINITION**************************** DESCRIPTION : signal_thread is the main thread that will be used to handle signals raised in the process. we mainly use this to handle SIGPIPE AND SIGCHLD. *****************************************************************/ void *signal_thread (void *arg) { int sig_caught; /* signal caught */ int rc; /* returned code */ rc = sigwait (&signal_mask, &sig_caught); if (rc != 0) { /* handle error */ } switch (sig_caught) { #if 0 case SIGINT: /* process SIGINT */ printf("SIGINT RECVD\n"); break; case SIGTERM: /* process SIGTERM */ printf("SIGTERM RECVD\n"); break; #endif case SIGPIPE: printf("\nSTATUS : SIGPIPE RECVD\n"); break; #if 0 case SIGCHLD: printf("\nSTATUS : SIGCHLD RECVD\n"); break; #endif default: /* should normally not happen */ fprintf (stderr, "\nUnexpected signal %d\n", sig_caught); break; } } /*****************FUNCTION DEFINITION*********************************** Description : Main entry point to the client process. Creates the sockets and calls the startClient function. ************************************************************************/ int main(int argc, char* argv[]) { struct hostent hptr; int isServerValid = false, isPortValid = true; int errorcode = EXIT_SUCCESS; int rc; //Check for the no.of cmd line args... if(argc!=2) { printf("usage : ./CS553_Client <ip/hostname> \n"); errorcode = EXIT_FAILURE; } else { #if 0 //add the signals you process needs to handle to the signal set struct. sigemptyset (&signal_mask); //sigaddset (&signal_mask, SIGINT); //sigaddset (&signal_mask, SIGTERM); sigaddset(&signal_mask,SIGCHLD); sigaddset (&signal_mask, SIGPIPE); //Create the signal thread as the first thread so that any thread created //after this will inherit the same signal handling features. rc = pthread_sigmask (SIG_BLOCK, &signal_mask, NULL); if (rc != 0) { /* handle error */ } int sig_thr_id; rc = pthread_create (&sig_thr_id, NULL, signal_thread, NULL); #endif //Start the client process... startClient(argv[1]); } return errorcode; } void startClient(char *hostaddr) { /* Start the client * 1. Create socket and connect to the server. --> NOT DONE * 2. Find the services available with the server. --> NOT DONE * 4. Create sockets * 4. List the services * 5. Take input and fork a child with xterm */ struct sockaddr_in serv_addr; int errcode ; int isConnected_echo = false; int isConnected_daytime = false; int choice = 0; char port[MAX_PORT_LEN]; char ip_addr[MAX_IP_LEN]; char serv_port[10]; int echo_serv_sockfd; int daytime_serv_sockfd; //using validation of ip or host-name is handled inside Getsockaddr. if(Getsockaddr(hostaddr,&serv_addr) < 0) { printf("ERROR : Cannot initialize client...\n"); exit(-1); } char ipstr[20]; memset(ipstr,0,sizeof(ipstr)); inet_ntop(AF_INET, &(serv_addr.sin_addr), ipstr, sizeof(ipstr)); //Establish a test connection to see server is accepting connection... memset(serv_port,0,sizeof(serv_port)); sprintf(serv_port,"%d",ECHO_PORT); memset(serv_port,0,sizeof(serv_port)); sprintf(serv_port,"%d",ECHO_PORT); int pfd[2]; while(1) { if(serv_port && ipstr) { close(echo_serv_sockfd); close(daytime_serv_sockfd); printf("\n------------------------------------------------------------------------------\n"); printf("Services : \n\t1. ECHO CLIENT\n\t2. DAY TIME CLIENT\n\t3. QUIT \nPlease Enter a Service number : "); scanf("%d",&choice); memset(ip_addr,0,sizeof(ip_addr)); strcpy(ip_addr,inet_ntoa(serv_addr.sin_addr)); switch(choice) { case 1: memset(serv_port,0,sizeof(serv_port)); sprintf(serv_port,"%d",ECHO_PORT); invoke_child("/home/stufs1/kuthaman/CS533_Assignment1/bin/echocli",ip_addr,serv_port); break; case 2: memset(serv_port,0,sizeof(serv_port)); sprintf(serv_port,"%d",DAYTIME_PORT); invoke_child("/home/stufs1/kuthaman/CS533_Assignment1/bin/daytimecli",ip_addr,serv_port); break; case 3: exit(0); default: printf("INVALID INPUT : TRY AGAIN ... \n"); break; } } else { err_msg(errno,strerror(errno)); errcode = CONNECT_FAILURE; break; } } } void invoke_child(char *client_name, char *ip_addr, char *port) { int pfd[2]; int pid; int errcode; char buff[1024]; char pfd_str[20]; int status=0; /* * Create a communication pipe that can be used by child to write status back to parent. */ pipe(pfd); /* * create a child process and load the requested client process with xterm. * on the parent side, read the pipe for any status msg and on the death of child process * ask the user to select another service to connect to... */ pid = fork(); switch (pid) { case -1: err_msg(errno,strerror(errno)); errcode=FORK_FAILURE; break; case 0: //CHILD PROCESS close(pfd[0]); memset(pfd_str,0,sizeof(pfd_str)); sprintf(pfd_str,"%d",pfd[1]); //printf("%s %s %s %s\n",client_name,ip_addr,port,pfd_str); execlp("xterm", "xterm", "-e",client_name,ip_addr,port,pfd_str, (char *) 0); //execlp("xterm", "xterm", "-e", "/bin/sh", "-c",client_name,ip_addr,port,pfd_str, (char *) 0); break; default: close(pfd[1]); memset(buff,0,sizeof(buff)); #if 1 while(read(pfd[0],buff,sizeof(buff))) { puts(buff); memset(buff,0,sizeof(buff)); } #endif wait(&status); //Child exits; //handle error; } }
C
#include <stdio.h> void tree (); int bound = 100000000; int arry[100000000]; int main () { tree(); } void tree () { int i; arry[0] = 1; for (i=0; i < bound; i++){ if (2*i+1 < 100000000){ arry[2*i+1] = arry[i]; } if (2*i+2 < 100000000){ arry[2*i+2] = arry[i] + arry[i+1]; } if (i+1 >= bound){ printf("%d/%d\n", arry[i], 1); } else{ printf("%d/%d\n", arry[i], arry[i+1]); } } }
C
#include "AppController.h" #include "AppIO.h" #include "Ban.h" #define MAX_NUMBER_OF_STUDENTS 100 struct AppController{ Ban* _ban; }; AppController* AppController_new(void) { //AppConter ü AppController* _this = NewObject(AppController); _this->_ban = Ban_newWithCapacity(MAX_NUMBER_OF_STUDENTS); return _this; } void AppController_delete(AppController* _this) { //AppCounter ü Ҹ Ban_delete(_this->_ban); free(_this); } void AppController_run(AppController* _this) { //App AppIO_out("<<< ó մϴ>>>\n"); // Է Boolean inputAndStoreWasSuccessful; inputAndStoreWasSuccessful = AppController_inputAndStoreStudents(_this); if (inputAndStoreWasSuccessful) { if (Ban_isEmpty(_this->_ban)) { AppIO_out("[] л Էµ ʾҽϴ.\n"); //հ ̻ л, ְ, Ѵ. } else { // , ׸ Է л . AppController_showStatistics(_this); Ban_sortStudentsByScore(_this->_ban); AppController_showStudentsSortedByScore(_this); } } else { AppIO_out("[] ʾҽϴ."); } AppIO_out("\n<<< ó մϴ>>>\n"); } Boolean AppController_inputAndStoreStudents(AppController* _this) { int score; Boolean storingAStudentWasSuccessful = TRUE; while (storingAStudentWasSuccessful && AppIO_in_doesContinueToInputNextStudent()) { score = AppIO_in_score(); if(Ban_scoresValid(score)) { storingAStudentWasSuccessful = Ban_add(_this->_ban, score); } else { AppIO_out("[] 0 ۰ų 100 Ŀ, ƴմϴ.\n"); } } return storingAStudentWasSuccessful; } void AppController_showStatistics(AppController* _this) { //Ban ü ó ,  Ѵ. //̽ ó Ban ü ִ. AppIO_out_averageScore(Ban_averageScore(_this->_ban)); AppIO_out_numberOfStudentsAboveAverage(Ban_numberOfStudentsAboveAverage(_this->_ban)); AppIO_out_maxScore(Ban_maxScore(_this->_ban)); AppIO_out_minScore(Ban_minScore(_this->_ban)); // л Ban üκ GradeCounter ü · ´. GradeCounter* gradeCounter = Ban_countGrades(_this->_ban); AppIO_out_gradeCountFor('A', GradeCounter_numberOfA(gradeCounter)); AppIO_out_gradeCountFor('B', GradeCounter_numberOfB(gradeCounter)); AppIO_out_gradeCountFor('C', GradeCounter_numberOfC(gradeCounter)); AppIO_out_gradeCountFor('D', GradeCounter_numberOfD(gradeCounter)); AppIO_out_gradeCountFor('F', GradeCounter_numberOfF(gradeCounter)); GradeCounter_delete(gradeCounter); // ̻ ʿ Ƿ ҸŲ } void AppController_showStudentsSortedByScore(AppController* _this) { // AppIO_out("л Դϴ.\n"); int score; char grade; for (int order = 0; order < Ban_size(_this->_ban); order++) { score = Ban_elementAt(_this->_ban, order); grade = Ban_scoreToGrade(score); AppIO_out_studentInfo(score, grade); } }
C
/******************************************************* INCLUDES *******************************************************/ #include "stats.h" /******************************************************* VARIABES & TYPES ********************************************/ int emailAlertCallCount = 0; int ledAlertCallCount = 0; /*************************************************** FUNCTION DEFINITIONS ********************************************/ stats_s compute_statistics(float* numberset, int setlength) { int index, swapIndex; float keyValue = 0, sum = 0; stats_s statisticalData; /* Average of numbers */ for(index=0;index<setlength;index++) { sum += numberset[index]; } statisticalData.average = sum/setlength; /* Sorting range of numbers */ for (index = 1; index < setlength; index++) { keyValue = numberset[index]; swapIndex = index - 1; while (swapIndex >= 0 && numberset[swapIndex] > keyValue) { numberset[swapIndex + 1] = numberset[swapIndex]; swapIndex = swapIndex - 1; } numberset[swapIndex + 1] = keyValue; } statisticalData.min = numberset[0]; statisticalData.max = numberset[setlength-1]; return statisticalData; } void check_and_alert(float maxThreshold, alerter_funcptr alerters[], stats_s computedStats) { if(computedStats.max > maxThreshold) { if(alerters[0] != NULL) { (*alerters[0])(); } if(alerters[1] != NULL) { (*alerters[1])(); } } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_unsigned_nb.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dboyer <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/10 13:03:32 by dboyer #+# #+# */ /* Updated: 2020/05/09 13:55:54 by dboyer ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static inline void ft_display(t_format format, unsigned int arg) { if (format.point && format.max == 0 && arg == 0) return ; ft_putnbr_unsigned(arg); } int ft_print_unsigned_nb(t_format format, va_list *va) { unsigned int arg; int result; arg = va_arg(*va, unsigned int); format = ft_minmax_unsigned_nb(format, arg); if (format.point && format.max == 0 && arg == 0) result = 0; else result = ft_nbrlen_unsigned(arg); result += ft_print_space_before(format); result += ft_print_zero_padding(format); ft_display(format, arg); result += ft_print_space_after(format); return (result); }
C
/* ** my_strdup.c for emacs in /home/jules.spender/CPool_Day08/task01 ** ** Made by Jules Spender ** Login <[email protected]> ** ** Started on Wed Oct 12 08:36:44 2016 Jules Spender ** Last update Wed Mar 15 17:59:31 2017 Jules Spender */ #include <stdlib.h> char *my_strdup(char *src) { int a; char *str; int i; a = 0; i = 0; while (src[a] != '\0') a = a + 1; a = a + 1; if ((str = malloc(sizeof(char) * ((a + 1) * (a + 1)))) == NULL) return (NULL); while (src[i] != '\0') { str[i] = src[i]; i = i + 1; } str[i] = '\0'; return (str); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #define REP(i, n) for (int (i) = 0; (i) < (n); ++(i)) #define INF 0x3f3f3f3f #define MAXN (15) char input[MAXN]; int get_num() { int a = 0; int flg = 0; char *pch = strtok(input, ","); while (pch) { a *= 1000; a += atoi(pch); if (a < 0) { a = -a; flg = 1; } pch = strtok(NULL, ","); } return (flg) ? -a : a; } int main (void) { #ifdef LOCAL freopen("input.txt", "r", stdin); #endif while (scanf("%s", input) != EOF) { int a = get_num(); scanf("%s", input); int b = get_num(); printf("%d\n", a + b); } return 0; }
C
/* ASSUMPTION - INPUT SIZE GREATER THAN 2 - answer becomes after n=92*/ #include<stdio.h> #include<omp.h> #include<stdlib.h> void printFib(long long int *arr,long long int size){ long int i; for(i=0;i<size;i++) printf("%lld ",arr[i]); printf("\n"); } long long int *getFib(long long int n){ long long int *arr=(long long int *)malloc(sizeof(long long int)*n); long long int i; arr[0]=arr[1]=1; for(i=2;i<n;i++) arr[i]=arr[i-1]+arr[i-2]; return arr; } int main(){ long long int n,*arr; double start,end; scanf("%lld",&n); start=omp_get_wtime(); arr=getFib(n); end=omp_get_wtime(); printFib(arr,n); printf("Time: %0.12f\n",(end-start)); return 0; }
C
#include <stdio.h> int main(void) { int n=0; printf("정수 입력: "); scanf("%d", &n); switch(n/10) { case 0: printf("0이상 10미만"); break; case 1: printf("10이상 20미만"); break; case 2: printf("20이상 30미만"); break; default: printf("30이상"); } }
C
#include "patterns.h" #include "color_pattern.h" #define DEFAULT_BACKGROUND CACA_TRANSPARENT color_pattern green_pattern[] = { { .ch='W' , .fcolor=CACA_WHITE, .bcolor=DEFAULT_BACKGROUND }, { .ch='G' , .fcolor=CACA_LIGHTGREEN, .bcolor=DEFAULT_BACKGROUND }, { .ch='D' , .fcolor=CACA_GREEN, .bcolor=DEFAULT_BACKGROUND }, { .ch='B' , .fcolor=CACA_DARKGRAY, .bcolor=DEFAULT_BACKGROUND } }; color_pattern blue_pattern[] = { { .ch='W' , .fcolor=CACA_WHITE, .bcolor=DEFAULT_BACKGROUND }, { .ch='G' , .fcolor=CACA_LIGHTBLUE, .bcolor=DEFAULT_BACKGROUND }, { .ch='D' , .fcolor=CACA_BLUE, .bcolor=DEFAULT_BACKGROUND }, { .ch='B' , .fcolor=CACA_DARKGRAY, .bcolor=DEFAULT_BACKGROUND } }; color_pattern red_pattern[] = { { .ch='W' , .fcolor=CACA_WHITE, .bcolor=DEFAULT_BACKGROUND }, { .ch='G' , .fcolor=CACA_LIGHTRED, .bcolor=DEFAULT_BACKGROUND }, { .ch='D' , .fcolor=CACA_RED, .bcolor=DEFAULT_BACKGROUND }, { .ch='B' , .fcolor=CACA_DARKGRAY, .bcolor=DEFAULT_BACKGROUND } }; color_pattern cyna_pattern[] = { { .ch='W' , .fcolor=CACA_WHITE, .bcolor=DEFAULT_BACKGROUND }, { .ch='G' , .fcolor=CACA_LIGHTCYAN, .bcolor=DEFAULT_BACKGROUND }, { .ch='D' , .fcolor=CACA_CYAN, .bcolor=DEFAULT_BACKGROUND }, { .ch='B' , .fcolor=CACA_DARKGRAY, .bcolor=DEFAULT_BACKGROUND } }; color_pattern* patterns[] = { green_pattern, blue_pattern, red_pattern, cyna_pattern }; int green_pattern_len = sizeof(green_pattern)/sizeof(color_pattern); int blue_pattern_len = sizeof(blue_pattern)/sizeof(color_pattern); int red_pattern_len = sizeof(red_pattern)/sizeof(color_pattern); int cyna_pattern_len = sizeof(cyna_pattern)/sizeof(color_pattern); int patterns_len[] = { sizeof(green_pattern)/sizeof(color_pattern), sizeof(blue_pattern)/sizeof(color_pattern), sizeof(red_pattern)/sizeof(color_pattern), sizeof(cyna_pattern)/sizeof(color_pattern) };
C
#include "index.h" #include "queue.h" #include "stack.h" #include "ConnectedComponents.h" #include "SCC.h" typedef struct graph { Buffer *buffer_inc; //buffer for incoming edges NodeIndex *index_inc; //index for incoming edges Buffer *buffer_out; //buffer for outcoming edges NodeIndex *index_out; //index for outcoming edges CC *components; //CC struct for dynamic graph mode SCC *scc; //SCC struct for static graph mode } Graph; /****************************************** PROTOTYPES ******************************************/ Graph* create_graph (int); //creates and initializes a graph int insertEdge (Graph*, HT_info*, uint32_t, uint32_t, uint32_t, int); //inserts an edge connecting the given nodes //(uses hashtable to indicate if it already existed) int path (Graph*, uint32_t, uint32_t, int*, int*, int*, int, uint32_t, Queue*, Queue*); //find the shortest path between the given nodes //(if there is not a path connecting them, returns -1) int destroy_graph (Graph*); //destroys a graph by deallocating used memory /************************************************************************************************/ typedef struct Arguments { //struct containing all possible arguments a job may need to either run //a path function in a static or dynamic graph struct graph *graph; struct Queue **incQueue; struct Queue **outQueue; struct ht_info *ht_info; uint32_t from_id; uint32_t to_id; int *visited; int **incExplored; int **outExplored; int type; //indicates whether the path that "this" job will call is going to be in a static or a dynamic graph uint32_t version; //version of edge property for the current paths neighbors } Arguments; /****************************************** PROTOTYPES ******************************************/ int job_distributor (void*, int); //takes a struct Arguments pointer and the "ID" of the calling thread //checks what type of graph the job refers to and uses the id of the thread to //indicate which frontier queues and explored info arrays are equivalent to the caller thread //(we have as many frontiers and explored sets as the threads number //given to main from command line arguments). This way multiple threads will run seperate path queries //simultaneously and each uses each own frontier and explored set.
C
#include "boolean.h" #include "mesinkataload.h" #include "mesinkarload.h" #include <stdio.h> LKata CKata; boolean EndKata; boolean EndData; void IgnoreBlank() { /* Mengabaikan BLANK dan newline */ while((CC == BLANK || CC == '\n') && CC != MARK) ADV(); } void STARTKATA() { /* Inisialisasi mesin kata dan salin kata pertama dari pita bila ada */ start_load(); IgnoreBlank(); if(CC == MARK) EndKata = true; else if(CC == '|') { EndData = true; ADV(); IgnoreBlank(); } else { EndKata = false; SalinKata(); } } void ADVKATA() { /* Isi CKata dengan kata sekarang dan buat mesin karakter maju ke kata berikutnya */ if(CC == MARK) EndKata = true; else if(CC == '|') { EndData = true; ADV(); IgnoreBlank(); SalinKata(); } else { IgnoreBlank(); EndData = false; SalinKata(); } IgnoreBlank(); } void SalinKata() { /* Menyalin kata yang sekarang sedang ditunjuk oleh mesin karakter ke dalam CKata */ CKata.length = 0; while(CC != MARK && CC != BLANK && CKata.length < NMax && CC != '|') { CKata.TabKata[CKata.length] = CC; CKata.length += 1; ADV(); } }
C
#include <stdio.h>//ATM simulator using C program int ATM_Transaction();//Prototype of the functions int anotherTransaction,amountToWidthdraw,amountToDeposit,pin;//Global variable double balance = 1000; // Global variable, Initial balance to be 1000 for everyone int main() { printf("******** Welcome to El Banco Corrupto Grande ******** \n"); printf(" Enter your pin number please: \n"); scanf("%d",&pin); if(pin != 1234) { printf("Sorry your pin is wrong, Pls try again with the card"); } else { ATM_Transaction(); // function call } } int ATM_Transaction() { int choice; printf("Enter any option to be served!\n\n"); printf("1. Balance Enquiry \n"); printf("2. Cash Withdraw\n"); printf("3. Deposit Cash\n"); printf("4. Exit \n"); scanf("%d", &choice); switch(choice) { case 1: // BALANCE Enquiry printf("Your bank balance is: %f", balance); printf("\n\nDo you want to perform another transaction?\nPress 1 to proceed and 2 to exit\n\n"); // request for another transaction scanf("%d",&anotherTransaction); if(anotherTransaction == 1) { ATM_Transaction();// call our transaction method here } break; case 2:// Second option should be withdraw printf("Please enter amount to withdraw: "); scanf("%d", &amountToWidthdraw); if(amountToWidthdraw <= balance) //bal = 1000 { printf("Pls collect your cash\n"); balance=balance-amountToWidthdraw;// printf("Your available balance is %lf\n",balance); printf("\n\nDo you want to perform another transaction?\n Press 1 to proceed and 2 to exit\n\n"); scanf("%d", &anotherTransaction); if(anotherTransaction == 1) { ATM_Transaction(); // call our ATM_Transaction method here } } else { printf("Sorry in-sufficient funds in your account"); printf("\n\nDo you want to perform another transaction?\n Press 1 to proceed and 2 to exit\n\n"); scanf("%d", &anotherTransaction); if(anotherTransaction == 1) { ATM_Transaction(); // call our ATM_Transaction method here } } break; case 3:// DEPOSIT printf("Please enter amount to deposit: "); scanf("%d", &amountToDeposit); balance = amountToDeposit + balance; //600+500 printf("Thank you for depositing, your new balance is: %f", balance); printf("\n\nDo you want another transaction?\nPress 1 to proceed and 2 to exit\n\n");// request for another transaction scanf("%d", &anotherTransaction); if(anotherTransaction == 1) { ATM_Transaction(); // call our transaction method here } break; default: printf("Thanks for Using ATM services, See you soon"); } }
C
#include <stdio.h> #define SIZE 30 int upper_to_lower(char arr[]); int main(){ char ip_arr[SIZE]; printf("Please enter array: "); scanf("%s", &ip_arr); upper_to_lower(ip_arr); return 0; } int upper_to_lower(char arr[]){ int i=0, x; x = 'a' - 'A'; while (arr[i] != 0){ if ((arr[i]>='A') &(arr[i]<='Z')){ arr[i] += x; } i++; } printf("The new array is: %s", arr); return 0; }
C
/* Nombre: Juan Carlos Ruiz García Grupo: C2 Año: 2016 NOTA: Compilar con la opcion -w para evitar todos los incomodos warnings gcc -w ejer4.c -o ejer4 */ #include <sys/types.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <dirent.h> //opendir #include <stdio.h> //strlen y strtol #include <string.h> //strcmp #include <ftw.h> //nftw off_t full_size = 0; //Almacenara el tamaño total en bytes de todos los archivos regulares encontrados int n_files = 0; //Almacenara el numero de archivos encontrados const unsigned int D_PERMISOS = 0011; // Permisos de ejecucion para grupo y otros // Busca de forma recursiva dentro de un directorio y sus subdirectorios, archivos regulares // con permisos de ejecucion en el grupo y en otros. int buscar(const char *pathname, const struct stat *stat, int flags, struct FTW *ftw){ // Compruebo que el pathname no sea . ni .. if( pathname != '.' && pathname != '..' ){ // Si es un archivo regular... if ( (stat->st_mode & S_IFMT) == S_IFREG){ // Si tiene permisos de ejecucion para grupos y otros muestro el pathname y el numero de inodo. // Incremento en 1 el contador de ficheros y sumo el tamaño de dicho archivo al contenedor. if ((stat->st_mode & D_PERMISOS) == D_PERMISOS){ printf("\t%s %lu\n",pathname,stat->st_ino); n_files++; full_size += stat->st_size; } } } return 0; } int main(int argc, char const *argv[]) { struct stat atr_dir; int fd_limit = 5; int flags = 10; char *pathname = malloc(sizeof(char) * 254); // assuming the max length of a string is not more than 253 characters if(argc <= 2){ if(argc == 2) strcpy(pathname,argv[1]); else pathname = "./"; // Almaceno los permisos del directorio pasado como primer parametro if(stat(pathname,&atr_dir) < 0) { printf("Error al intentar acceder a los atributos de %s, podria no ser un directorio\n",argv[1]); perror("Error en stat"); exit(EXIT_FAILURE); } //Compruebo que el primer parametro pasado sea realmente un directorio if( (atr_dir.st_mode & S_IFMT) != S_IFDIR){ printf("Error %s no es un directorio.\n",argv[1]); exit(EXIT_FAILURE); } printf("Los inodos son: \n\n"); // nftw recorre todo el arbol de directorios de pathname y para cada directorio/archivo llama a la funcion buscar // con un maximo de 5 files descriptor y con los flags a 10 if( nftw(pathname,buscar,fd_limit,flags) != 0 ){ perror("nftw"); exit(EXIT_FAILURE); } printf("\nExisten %d archivos regulares con permisos x para grupo y otros en el directorio %s\n",n_files,pathname); printf("El tamaño total ocupado por dichos archivos es %ld Bytes = %ld MB aprox.\n", full_size,full_size/(1024*1024)); } else{ printf("Numero de parametros incorrecto\n"); printf("\tFormato: %s <directorio_a_buscar>\n",argv[0]); printf("NOTA : Si no se especifica <directorio_a_buscar> se utilizar ./ por defecto\n"); } return 0; }
C
#ifndef TREE_H #define TREE_H // Structures struct s_node; struct s_list_of_nodes; // typedefying typedef struct s_node* tree; typedef struct s_list_of_nodes* list; // Structure of the doubly linked list of nodes struct s_list_of_nodes { tree node; list next; list prev; }; // Structure of the node, linked to its father, with list of the sons struct s_node { int value; list father; list sons_start_dummy; list sons_end_dummy; }; extern list initialize_dummy(); extern tree initialize_node(int num_node, list father); extern tree initialize_root(); extern void ADD_NODE(tree node, int* n, tree* array_of_addresses); extern int RIGHTMOST_CHILD(tree node); extern void DELETE_SUBTREE(tree node, int* nodes_counter); extern void DELETE_NODE(tree node); extern void SPLIT_NODE(tree father, tree son, int* n,tree* array_of_addresses); #endif /* TREE_H */
C
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #define MAXN 100 int n; double x[MAXN], y[MAXN]; double e[MAXN * MAXN]; int i, j, k; int mark[MAXN * MAXN]; int plan[MAXN]; int vis[MAXN]; double bestLen; int bestPlan[MAXN]; int totCut; int compare(const void* a, const void* b) { return (*(double*)a - *(double*)b); } int getEdgeId(int i, int j) { if (j == i) return -1; if (j < i) { int t = i; i = j; j = t; } return (2*n-i)*(i-1)/2+j-i-1; } void search(int i, double len) { if (i > n) { len = len + e[getEdgeId(plan[1], plan[n])]; if (len < bestLen) { bestLen = len; memcpy(bestPlan, plan, sizeof(plan)); } return; } int v; for (v = 1; v <= n; v ++) { if (!vis[v]) { // heuristic double h = 0; int count = 0; int eId = getEdgeId(plan[i-1], v); for (j = 0; j < n*(n-1)/2 && count < n-i+1; j ++) if (!mark[j] && j != eId) { count ++; h += e[j]; } if (len + e[eId] + h >= bestLen) { totCut ++; continue; } // search vis[v] = 1; mark[eId] = 1; plan[i] = v; search(i + 1, len + e[eId]); mark[eId] = 0; vis[v] = 0; } } } int main() { scanf("%d", &n); for (i = 1; i <= n; i ++) { int id; double a, b; scanf("%d %lf %lf", &id, &a, &b); x[id] = a; y[id] = b; } int id = 0; for (i = 1; i <= n; i ++) for (j = i + 1; j <= n; j ++) e[id++] = sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])); qsort(e, id, sizeof(double), compare); #ifdef DEBUG for (i = 1; i <= n; i ++) { for (j = 1; j <= n; j ++) { int eId = getEdgeId(i, j); if (eId == -1) printf("- "); else printf("%0.3lf ", e[eId]); } printf("\n"); } #endif memset(mark, 0, sizeof(mark)); plan[1] = 1; vis[1] = 1; bestLen = 1e20; totCut = 0; search(2, 0); printf("totCut = %d\n", totCut); printf("bestLen = %0.6lf\n", bestLen); for (i = 1; i <= n; i ++) printf("%d ", bestPlan[i]); printf("\n"); return 0; }
C
#define NMAX 10 //macro per pile /*Questa libreria contiene gli abstact data type visti a lezione. Le definizioni sono commentate poiché si ripetono nella gandolib.h*/ ///////////////////////////////////////////////////////////// /* LISTE */ ///////////////////////////////////////////////////////////// typedef struct nodo { int dato; struct nodo *next; } Nodo; typedef Nodo *Lista; void nuova_lista(Lista *l); int vuota(Lista l); void inserimento_testa(Lista *l, int numero); void inserimento_ordinato(Lista *l, int numero); void inserimento_coda(Lista *l, int numero); void inversa(Lista l1, Lista *l2); int ricerca(Lista l, int numero); void elimina(Lista *l, int numero); int lunghezza(Lista l); void stampa(Lista l); void svuota(Lista *l); void concatena(Lista *l1, Lista l2); void somma(Lista l1, Lista l2, Lista *l3); void somma_efficiente(Lista l1, Lista l2, Lista *l3); ///////////////////////////////////////////////////////////// /* QUEUE */ ///////////////////////////////////////////////////////////// // typedef struct nodo // { // char dato[21]; // struct nodo *next; // } Nodo; typedef struct { Nodo *first; Nodo *last; } Coda; int isEmptyQueue(Coda c); Coda newQueue(); void enqueue(Coda *c, char *s); void dequeue(Coda *c, char *s); void print(Coda c); ///////////////////////////////////////////////////////////// /* PILA */ ///////////////////////////////////////////////////////////// typedef struct { float dati[NMAX]; int nElem; } Pila; void nuova_Pila(Pila *p); int vuota_Pila(Pila p); int piena_Pila(Pila p); void push(Pila *p, float elemento); float pop(Pila *p);
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int /*<<< orphan*/ FDSet ; /* Variables and functions */ int /*<<< orphan*/ F_DUPFD_CLOEXEC ; int /*<<< orphan*/ assert (int) ; int errno ; int fcntl (int,int /*<<< orphan*/ ,int) ; int fdset_put (int /*<<< orphan*/ *,int) ; int /*<<< orphan*/ safe_close (int) ; int fdset_put_dup(FDSet *s, int fd) { int copy, r; assert(s); assert(fd >= 0); copy = fcntl(fd, F_DUPFD_CLOEXEC, 3); if (copy < 0) return -errno; r = fdset_put(s, copy); if (r < 0) { safe_close(copy); return r; } return copy; }
C
#include <stdio.h> #include <time.h> #include <stdlib.h> #include "array_print.h" #include "move_array.h" #include "init_array.h" void random_create_2(int array_2048[4][4]) { int count = 0, r1, l1, r2 = -1, l2 = -1; srand(time(0)); while (1) { r1 = rand() % 4; l1 = rand() % 4; if (2 == count) break; if (r1 == r2 && l1 == l2) continue; if (0 == array_2048[r1][l1]) { array_2048[r1][l1] = 2; count++; r2 = r1; l2 = l1; } else continue; } } void main() { int array_2048[4][4] = { 0 }; char user_input; int i, j, success = 0; init_array(array_2048); array_print(array_2048); while (1) { scanf("%c", &user_input); switch (user_input) { case 'w': { move_up(array_2048); random_create_2(array_2048); array_print(array_2048); break; } case 'a': { move_left(array_2048); random_create_2(array_2048); array_print(array_2048); break; } case 's': { move_down(array_2048); random_create_2(array_2048); array_print(array_2048); break; } case 'd': { move_right(array_2048); random_create_2(array_2048); array_print(array_2048); break; } default: break; } for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { if (2048 == array_2048[i][j]) { success = 1; break; } } if (success) break; } if (success) { printf("Successful!!!\n"); break; } } }
C
#include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "bitmap.h" #include "util.h" bitmap_t *bitmap_new(int width, int height) { size_t bytes = sizeof(bitmap_t) + DIV_ROUND_UP(width, 8) * height; bitmap_t *bitmap = calloc(1, bytes); assert(bitmap != NULL); bitmap->width = width; bitmap->height = height; return bitmap; } void bitmap_free(bitmap_t *bitmap) { free(bitmap); } void bitmap_set_pixel(uint8_t *byte, uint8_t shift, uint8_t bit) { *byte |= bit << shift; } void bitmap_clear_pixel(uint8_t *byte, uint8_t shift, uint8_t bit) { *byte &= ~(bit << shift); } void bitmap_xor_pixel(uint8_t *byte, uint8_t shift, uint8_t bit) { *byte ^= bit << shift; } void bitmap_plot(bitmap_t *bitmap, bitmap_draw_fn draw_fn, int x, int y) { size_t n = y * DIV_ROUND_UP(bitmap->width, 8) + x / 8; draw_fn(&bitmap->data[n], 7 - (x & 7), 1); } void bitmap_line(bitmap_t *bitmap, bitmap_draw_fn draw_fn, int x1, int y1, int x2, int y2) { uint16_t stride = DIV_ROUND_UP(bitmap->width, 8); int dx = abs(x2 - x1); int sx = x1 < x2 ? 1 : -1; int dy = -abs(y2 - y1); int sy = y1 < y2 ? 1 : -1; int err = dx + dy; while (true) { size_t n = y1 * stride + x1 / 8; draw_fn(&bitmap->data[n], 7 - (x1 & 7), 1); if (x1 == x2 && y1 == y2) { break; } int e2 = err * 2; if (e2 >= dy) { err += dy; x1 += sx; } if (e2 <= dx) { err += dx; y1 += sy; } } } void bitmap_invert(bitmap_t *bitmap) { uint8_t stride = DIV_ROUND_UP(bitmap->width, 8); uint8_t numbytes = bitmap->height * stride; for (int n = 0; n < numbytes; n++) { bitmap->data[n] ^= 0xFF; } } void bitmap_blit(bitmap_t *dst, const bitmap_t *src, int dst_x, int dst_y, int src_x, int src_y, int width, int height) { int src_n, dst_n; int src_shift, dst_shift; width = width ? width : src->width; height = height ? height : src->height; if (dst_x < 0) { src_x += dst_x; width += dst_x; dst_x = 0; } else if (dst_x > dst->width) { width = dst->width - dst_x; } if (dst_y < 0) { src_y += dst_y; height += dst_y; dst_y = 0; } else if (dst_y > dst->height) { height = dst->height - dst_y; } if (width < 0) { return; } if (height < 0) { return; } int src_stride = DIV_ROUND_UP(src->width, 8); int dst_stride = DIV_ROUND_UP(dst->width, 8); for (int y = 0; y < height; y++) { src_n = (src_y + y) * src_stride + src_x / 8; src_shift = 7 - (src_x % 8); dst_n = (dst_y + y) * dst_stride + dst_x / 8; dst_shift = 7 - (dst_x % 8); for (int x = 0; x < width; x++) { uint8_t bit = (src->data[src_n] >> src_shift) & 1; if (bit) { dst->data[dst_n] |= bit << dst_shift; } else { dst->data[dst_n] &= ~(bit << dst_shift); } if (src_shift-- == 0) { src_shift = 7; src_n++; } if (dst_shift-- == 0) { dst_shift = 7; dst_n++; } } } } void bitmap_blit2(bitmap_t *dst, const bitmap_t *src, bitmap_draw_fn draw_fn, int dst_x, int dst_y, int src_x, int src_y, int width, int height) { int src_n, dst_n; int src_shift, dst_shift; width = width ? width : src->width; height = height ? height : src->height; if (dst_x < 0) { src_x += dst_x; width += dst_x; dst_x = 0; } else if (dst_x > dst->width) { width = dst->width - dst_x; } if (dst_y < 0) { src_y += dst_y; height += dst_y; dst_y = 0; } else if (dst_y > dst->height) { height = dst->height - dst_y; } if (width < 0) { return; } if (height < 0) { return; } int src_stride = DIV_ROUND_UP(src->width, 8); int dst_stride = DIV_ROUND_UP(dst->width, 8); for (int y = 0; y < height; y++) { src_n = (src_y + y) * src_stride + src_x / 8; src_shift = 7 - (src_x % 8); dst_n = (dst_y + y) * dst_stride + dst_x / 8; dst_shift = 7 - (dst_x % 8); for (int x = 0; x < width; x++) { uint8_t bit = (src->data[src_n] >> src_shift) & 1; draw_fn(&dst->data[dst_n], dst_shift, bit); if (src_shift-- == 0) { src_shift = 7; src_n++; } if (dst_shift-- == 0) { dst_shift = 7; dst_n++; } } } }
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char **argv){ FILE *file; file = fopen(argv[1], "r"); char arr[100][50]; int i = 0; while (1){ char r = (char)fgetc(file); int k = 0; while(!feof(file)){ arr[i][k++] = r; r = (char)fgetc(file) } arr[i][k]=0; if(feof(file)){ break; } i++; } int j; for(j=0; j<=i,j++){ printf("%s\n",arr[j]); } return 0; }
C
#ifndef COMMON_H #define COMMON_H #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <stddef.h> #include <stdio.h> #include <limits.h> #define NUMBER_OF_CHAR 256 #define SEPARATOR -2 #define EMPTY_CHAR -3 //The buffer size is the amount of characters that will be held in memory. #define BUFFER_SIZE 8192 #define BYTE_LENGTH 8 /* Sets the k-th bit in array arr to 1. */ void set_bit(unsigned char* arr, int k); /* Sets the k-th bit in array arr to 0. */ void clear_bit(unsigned char* arr, int k); /* Returns the value of the bit at position k in the array. */ int test_bit(unsigned char* arr, int k); /* Returns the value of the bit at position k in the character. */ int test_bit_in_char(unsigned char c, int k); /* Sets the bit at position index in the array to the given binary_number (1 or 0). */ void write_bit(unsigned char* buffer, int index, int binary_number); /* Returns an integer that represents the number of bytes in a given file. */ long long get_file_size(FILE* file); #endif
C
/*Filename: Saddle.c Author: Jithu Sunny Blog: http://jithusunnyk.blogspot.com/ Date: 06-03-11 Description: This program finds out the saddle points and their positions in a matrix of any order.*/ /*Change these macros to change the order*/ #define ROWS 3 #define COLUMNS 3 #include <stdio.h> struct saddle { int num; int row, column; }; /*Returns 1 if element at p is the smallest in its row. Returns 0 otherwise*/ int is_min_in_row(int* p, int col) { int *i; int *first_in_row = p - col; int *last_in_row = first_in_row + COLUMNS - 1; for(i = first_in_row; i <= last_in_row; i++) if(*p <= *i) continue; else return 0; return 1; } /*Returns 1 if element at p is the largest in its column. Returns 0 otherwise*/ int is_max_in_col(int* p, int row) { int *i; int *first_in_col = p - (COLUMNS * row); int *last_in_col = first_in_col + COLUMNS * (ROWS - 1); for(i = first_in_col; i <= last_in_col; i += COLUMNS) if(*p >= *i) continue; else return 0; return 1; } /*Returns 1 if element at p is a saddle point. Returns 0 otherwise*/ int is_saddle(int* p, int row, int col) { if((is_min_in_row(p, col)) && (is_max_in_col(p, row))) return 1; return 0; } int main() { int i, j, k = 0; int a[ROWS][COLUMNS]; struct saddle saddles[1000]; printf("Enter the %dx%d matrix:", ROWS, COLUMNS); for(i = 0; i < ROWS; i++) for(j = 0; j < COLUMNS; j++) scanf("%d", &a[i][j]); for(i = 0; i < ROWS; i++) for(j = 0; j < COLUMNS; j++) if(is_saddle(&a[i][j], i, j)) { saddles[k].num = a[i][j]; saddles[k].row = i; saddles[k].column = j; ++k; } for(i = 0; i < k; i++) printf("Saddle point: %d at position %d,%d\n", saddles[i].num, saddles[i].row, saddles[i].column); return 1; }
C
// ads1115 example wiringPi #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <inttypes.h> #include <stdbool.h> #include <wiringPi.h> #include <wiringPiI2C.h> #include <ads1115.h> #define PINBASE 120 // choose PINBASE value arbitrarily #define ADS_ADDR 0x48 int main() { int analog0,analog1,analog2,analog3; int ioerr = wiringPiSetupGpio(); if( ioerr == -1 ) return 1; ads1115Setup (PINBASE, ADS_ADDR); while(true) { analog0 = analogRead(PINBASE+0); // connected to ads1115 A0 printf("analog0 = %d \n", analog0); analog1 = analogRead(PINBASE+1); // connected to ads1115 A1 printf("analog1 = %d \n", analog1); analog2 = analogRead(PINBASE+2); // connected to ads1115 A2 printf("analog2 = %d \n", analog2); analog3 = analogRead(PINBASE+3); // connected to ads1115 A3 printf("analog3 = %d \n", analog3); delay(250); // sample rate 250ms } return 0; }
C
#include<stdio.h> #include<conio.h> #include<stdlib.h> struct node { int info; struct node *link; }; struct node *newnode,*top,*ptr; void push(); int pop(); void disple(); FILE *fp; int main() { top=NULL; int i,n; char ch; fp=fopen("input.txt","r"); if(fp==NULL) printf("file does not exit:\n"); fscanf(fp,"%d",&n); for(i=0;i<n;i++) { newnode=(struct node*)malloc(sizeof(struct node)); if(newnode==NULL) { printf("overflow"); break; } fscanf(fp,"%d",&newnode->info); newnode->link=NULL; if(top==NULL) { top=newnode; ptr=newnode; } else { top->link=newnode; top=newnode; } } do { fscanf(fp,"%c",&ch); switch(ch) { case 'P': push(); break; case 'O': n=pop(); if(n==-1) printf("stack is empty:\n"); else printf("value deleted is:%d\n",n); break; case 'D': disple(); break; case 'E': exit(0); } }while(1); getch(); } void push() { int n; newnode=(struct node*)malloc(sizeof(struct node)); fscanf(fp,"%d",&newnode->info); newnode->link=NULL; if(top==NULL) { top=newnode; } else { top->link=newnode; top=newnode; } printf("value pushed is %d:\n",newnode->info); } int pop() { int n; struct node *temp,*pre; temp=ptr; if(top==NULL) return(-1); while(temp=NULL) { pre=temp; temp=temp->link; } n=temp->info; pre->link=temp->link; free(temp); return(n); } void disple() { struct node *temp; temp=ptr; while(temp!=NULL) { printf("%d\n",temp->info); temp=temp->link; } }
C
/************************************************************************* > File Name: union.c > Author: huang yang > Mail: [email protected] > Created Time: 2016年12月02日 星期五 11时11分01秒 ************************************************************************/ #include<stdio.h> typedef union { char a; int b; }Data; int main() { Data test; test.b=0x12345678; printf("char %0x,int %x\n",test.a,test.b); }
C
//write a program to find out area of two different circle and findout and print smallest circle (in terms of area) #include<stdio.h> #include<conio.h> void main() { int radius1,radius2; float area1,area2; printf("Enter first circle radius"); scanf("%d",&radius1); printf("Enter second circle radius"); scanf("%d",&radius2); area1 = 3.14 * radius1 * radius1; area2 = 3.14 * radius2 * radius2; if(area1==area2) { printf("both circle are same"); } else { if(area1<area2) //< > <= >= == != { printf("first circle is smallest circle and its area is %f",area1); } else { printf("second circle is smalles circle and its area is %f",area2); } } printf("\n good bye"); }
C
#pragma once #include <float.h> /*****************************************************************************/ /* */ /* - Splitter : (DBL_MANT_DIG + 1) >> 1 right bit shift by 1bit */ /* i.e. the number (54) is divided by 2 (27) */ /* : 1 << result left bit shift by result (27) bit */ /* : it results in the number which is represented with 1 in */ /* binary code in the middle of the mantisa of the double */ /* (the 1 is in the 28-th place in binary: ...00100000...0) */ /* */ /*****************************************************************************/ #define EPS (DBL_EPSILON / 2) const double epsilonArithmetic = EPS; const double splitter = (1 << ((DBL_MANT_DIG + 1) >> 1)) + 1.0; const double resultErrorBound = (3.0 + 8.0 * EPS) * EPS; const double orientationErrorBoundA = (3.0 + 16.0 * EPS) * EPS; const double orientationErrorBoundB = (2.0 + 12.0 * EPS) * EPS; const double orientationErrorBoundC = (9.0 + 64.0 * EPS) * EPS * EPS; const double inCircumCircleErrorBoundA = (10.0 + 96.0 * EPS) * EPS; const double inCircumCircleErrorBoundB = (4.0 + 48.0 * EPS) * EPS; const double inCircumCircleErrorBoundC = (26.0 + 288.0 * EPS) * EPS * EPS; /* const double isperrboundA = (16.0 + 224.0 * EPS) * EPS; const double isperrboundB = (5.0 + 72.0 * EPS) * EPS; const double isperrboundC = (71.0 + 1408.0 * EPS) * EPS * EPS; */ inline void Split(double const a, double & ahi, double & alo) { const double c = splitter * a; const double abig = c - a; ahi = c - abig; alo = c - ahi; }; inline double Estimate(int const m, double * e) { double Q = e[0]; for (int i = 1; i < m; i++) Q += e[i]; return Q; }; inline void Fast_Two_Sum_Tail(double const a, double const b, double & x, double & y) { double const bvirtual = x - a; y = b - bvirtual; }; inline void Fast_Two_Sum(double const a, double const b, double & x, double & y) { x = a + b; Fast_Two_Sum_Tail(a, b, x, y); }; inline void Two_Sum_Tail(double const a, double const b, double & x, double & y) { const double bvirtual = x - a; const double avirtual = x - bvirtual; const double broundoff = b - bvirtual; const double aroundoff = a - avirtual; y = aroundoff + broundoff; }; inline void Two_Sum(double const a, double const b, double & x, double & y) { x = a + b; Two_Sum_Tail(a, b, x, y); }; inline void Two_One_Sum(double const a1, double const a0, double const b, double & x2, double & x1, double & x0) { double _i; Two_Sum(a0, b, _i, x0); Two_Sum(a1, _i, x2, x1); }; inline void Two_Two_Sum(double a1, double a0, double b1, double b0, double & x3, double & x2, double & x1, double & x0) { double _j; double _0; Two_One_Sum(a1, a0, b0, _j, _0, x0); Two_One_Sum(_j, _0, b1, x3, x2, x1); }; inline void Two_Diff_Tail(double const a, double const b, double & x, double & y) { const double bvirtual = a - x; const double avirtual = x + bvirtual; const double broundoff = bvirtual - b; const double aroundoff = a - avirtual; y = aroundoff + broundoff; }; inline void Two_Diff(double const a, double const b, double & x, double & y) { x = a - b; Two_Diff_Tail(a, b, x, y); }; inline void Two_One_Diff(double const a1, double const a0, double const b, double & x2, double & x1, double & x0) { double _i; Two_Diff(a0, b, _i, x0); Two_Sum(a1, _i, x2, x1); // There is really Two_Sum. Check this in Shewchuck paper, if there is really this one; }; inline void Two_Two_Diff(double a1, double a0, double b1, double b0, double & x3, double & x2, double & x1, double & x0) { double _j; double _0; Two_One_Diff(a1, a0, b0, _j, _0, x0); Two_One_Diff(_j, _0, b1, x3, x2, x1); }; inline void Two_Product_Tail(double const a, double const b, double & x, double & y) { double ahi; double alo; double bhi; double blo; Split(a, ahi, alo); Split(b, bhi, blo); const double Error1 = x - (ahi * bhi); const double Error2 = Error1 - (alo * bhi); const double Error3 = Error2 - (ahi * blo); y = alo * blo - Error3; }; inline void Two_Product(double const a, double const b, double & x, double & y) { x = a * b; Two_Product_Tail(a, b, x, y); }; inline void Two_Product_Presplit(double const a, double const b, double const bhi, double const blo, double & x, double & y) { x = a * b; double ahi; double alo; Split(a, ahi, alo); const double Error1 = x - (ahi * bhi); const double Error2 = Error1 - (alo * bhi); const double Error3 = Error2 - (ahi * blo); y = (alo * blo) - Error3; }; inline void Square_Tail(double const a, double & x, double & y) { double ahi; double alo; Split(a, ahi, alo); const double Error1 = x - (ahi * ahi); const double Error3 = Error1 - (ahi + ahi) * alo; y = (alo * alo) - Error3; }; inline void Square(double const a, double & x, double & y) { x = a * a; Square_Tail(a, x, y); }; /*****************************************************************************/ /* */ /* fast_expansion_sum_zeroelim() Sum two expansions, eliminating zero */ /* components from the output expansion. */ /* */ /* Sets h = e + f. See the long version of my paper for details. */ /* */ /* If round-to-even is used (as with IEEE 754), maintains the strongly */ /* nonoverlapping property. (That is, if e is strongly nonoverlapping, h */ /* will be also.) Does NOT maintain the nonoverlapping or nonadjacent */ /* properties. */ /* */ /*****************************************************************************/ int Fast_Expansion_Sum_Zero_Eliminiation(int const eLength, double * e, const int fLength, double * f, double * h) { /*****************************************************************************/ /* */ /* - INEXACT == volatile */ /* */ /*****************************************************************************/ double Qnew; double hh; //double bvirt; /*****************************************************************************/ /* */ /* - EXACT == nothing */ /* */ /*****************************************************************************/ double Q; //double avirt, bround, around; double enow, fnow; int eindex, findex, hindex; eindex = 0; findex = 0; hindex = 0; enow = e[0]; fnow = f[0]; if ((fnow > enow) == (fnow > -enow)) { //if (abs(fnow) > abs(enow)) { Q = enow; enow = e[++eindex]; } else { Q = fnow; fnow = f[++findex]; } if ((eindex < eLength) && (findex < fLength)) { if ((fnow > enow) == (fnow > -enow)) { //if (fnow > abs(enow)) { Fast_Two_Sum(enow, Q, Qnew, hh); enow = e[++eindex]; } else { Fast_Two_Sum(fnow, Q, Qnew, hh); fnow = f[++findex]; } Q = Qnew; if (hh != 0.0) h[hindex++] = hh; while (eindex < eLength && findex < fLength) { if ((fnow > enow) == (fnow > -enow)) { //if (fnow > abs(enow)) { Two_Sum(Q, enow, Qnew, hh); enow = e[++eindex]; } else { Two_Sum(Q, fnow, Qnew, hh); fnow = f[++findex]; } Q = Qnew; if (hh != 0.0) h[hindex++] = hh; } } while (eindex < eLength) { Two_Sum(Q, enow, Qnew, hh); enow = e[++eindex]; Q = Qnew; if (hh != 0.0) h[hindex++] = hh; } while (findex < fLength) { Two_Sum(Q, fnow, Qnew, hh); fnow = f[++findex]; Q = Qnew; if (hh != 0.0) h[hindex++] = hh; } if ((Q != 0.0) || (hindex == 0)) h[hindex++] = Q; return hindex; }; /***************************************************************************** / /* */ /* scale_expansion_zeroelim() Multiply an expansion by a scalar, */ /* eliminating zero components from the */ /* output expansion. */ /* */ /* Sets h = b*e. */ /* */ /*****************************************************************************/ int Scale_Expansion_Zero_Elimination(int const elength, double * e, double b, double * h) { /*****************************************************************************/ /* */ /* - INEXACT == volatile */ /* */ /*****************************************************************************/ double Q, sum; double product1; //double bvirt; //double c; //double abig; /*****************************************************************************/ /* */ /* - EXACT == nothing */ /* */ /*****************************************************************************/ double hh; double product0; double enow; //double avirt, bround, around; //double ahi, alo; double bhi, blo; //double error1, error2, error3; int hindex; Split(b, bhi, blo); Two_Product_Presplit(e[0], b, bhi, blo, Q, hh); hindex = 0; if (hh != 0) h[hindex++] = hh; for (int eindex = 1; eindex < elength; eindex++) { enow = e[eindex]; Two_Product_Presplit(enow, b, bhi, blo, product1, product0); Two_Sum(Q, product0, sum, hh); if (hh != 0) h[hindex++] = hh; Fast_Two_Sum(product1, sum, Q, hh); if (hh != 0) h[hindex++] = hh; } if ((Q != 0.0) || (hindex == 0)) h[hindex++] = Q; return hindex; }
C
#include <stdio.h> #include <cs50.h> int validate_input(int input) { if(input<0 || input>23){ return false; } else{ return true; } } int pyramid(int input) { int height = input-1; for(int i = -1; i<height; i++){ printf("%.*s", height-(i+1), " "); printf("%.*s\n", i+3, "#############################"); } return 0; } int main(void) { bool exit = false; while(exit == false){ int input = get_int("Height: "); if(validate_input(input)){ printf("%i is a valid input\n", input); pyramid(input); exit = true; } } }
C
#include <stdio.h> void fun(int a, int b, long *c) { /**********Program**********/ *c=1000*(b%10)+100*(a%10)+10*(b/10)+(a/10); /********** End **********/ } void main() { int a,b; long c; printf("Input a, b:"); scanf("%d %d", &a, &b); fun(a, b, &c); printf("The result is: %ld\n", c); }
C
#include "holberton.h" /** * _strcpy - Copies string pointed to by src, including terminating null byte * @dest: A buffer to copy the string to. * @src: The source string to copy. * * Return: A pointer to the destination string @dest. */ char *_strcpy(char *dest, char *src) { int i = 0; while (src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; return (dest); }
C
// // Created by new on 9/1/19. // #include "../include/DATABASE_message.h" void freeMsgList(MessageList messageList) { for (int i = 0; i < messageList.msgNum; i++) { free((messageList.msgs + i)->msgContent); (messageList.msgs + i)->msgContent = NULL; free((messageList.msgs + i)->msgDateTime); (messageList.msgs + i)->msgDateTime = NULL; } messageList.msgs = NULL; } int insertMsg(Message *msg, MYSQL *connection) { if (connection == NULL) { perror("INSERT MESSAGE: CONNECTION NULL ERROR"); return -1; } char insertMessageSql[200]; MYSQL_RES *res; MYSQL_ROW row; memset(insertMessageSql, '\0', sizeof(insertMessageSql)); mysql_query(connection, "SET names utf8"); sprintf(insertMessageSql, "INSERT INTO linpop.message(msgContent, msgFromId, msgToId, msgDateTime)\n" " VALUES(\'%s\', %d, %d, NOW());", msg->msgContent, msg->msgFromId, msg->msgToId); if(mysql_real_query(connection, insertMessageSql, strlen(insertMessageSql))) { perror("INSERT MESSAGE: QUERY ERROR\n"); return -1; } else { if(mysql_real_query(connection, SQL_SELECT_LAST_ID, strlen(SQL_SELECT_LAST_ID))) { perror("QUERY LAST ID AFTER INSERT MESSAGE: QUERY ERROR\n"); return -1; } else { res = mysql_store_result(connection); if(res) { row = mysql_fetch_row(res); msg->msgId = atoi(row[0]); } return msg->msgId; } } } Status updateMsgStatus(int msgId, MYSQL *connection) { if (connection == NULL) { perror("UPDATE MESSAGE STATUS: CONNECTION NULL ERROR"); return -1; } char updateMsgStatusSql[200]; memset(updateMsgStatusSql, '\0', sizeof(updateMsgStatusSql)); mysql_query(connection, "SET NAMES utf8"); sprintf(updateMsgStatusSql, "UPDATE linpop.message\n" "SET msgStatus = 1\n" "WHERE msgId=%d;", msgId); if(mysql_real_query(connection, updateMsgStatusSql, strlen(updateMsgStatusSql))) { perror("UPDATE MESSAGE STATUS: QUERY ERROR"); return -1; } return 1; } MessageList getMsgList(int userId1, int userId2, MYSQL *connection) { MessageList messageList; messageList.msgs = NULL; messageList.msgNum = 0; if (connection == NULL) { perror("QUERY MESSAGE LIST: CONNECTION NULL ERROR"); return messageList; } MYSQL_RES* res; MYSQL_ROW row; char querySql[200]; mysql_query(connection, "SET NAMES utf8"); sprintf(querySql, "SELECT * FROM linpop.message\n" "WHERE (msgFromId=%d and msgToId=%d) OR (msgFromId=%d and msgToId=%d);", userId1, userId2, userId2, userId1); if(mysql_real_query(connection, querySql, strlen(querySql))) { perror("QUERY MESSAGE LIST: QUERY ERROR\n"); return messageList; } else { mysql_query(connection, "SET NAMES utf8"); res = mysql_store_result(connection); if(res) { messageList.msgNum = mysql_num_rows(res); messageList.msgs = (Message *) malloc(sizeof(Message) * messageList.msgNum); Message *go = messageList.msgs; row = mysql_fetch_row(res); while(row) { // TODO: reference for make message table go->msgContent = (char *) malloc(sizeof(char) * 1000); go->msgDateTime = (char *) malloc(sizeof(char) * 100); go->msgId = atoi(row[0]); strcpy(go->msgContent, row[1]); strcpy(go->msgDateTime, row[2]); go->msgStatus = row[3][0] == '0' ? 0 : 1; go->msgFromId = atoi(row[4]); go->msgToId = atoi(row[5]); go++; row = mysql_fetch_row(res); } } return messageList; } }
C
/*************************************************************************************************** *FileName: *Description: *Author:xsx *Data: ***************************************************************************************************/ /***************************************************************************************************/ /******************************************ͷļ***************************************************/ /***************************************************************************************************/ #include "MyTools.h" #include "Define.h" #include "math.h" #include <string.h> #include "stdio.h" #include "stdlib.h" /***************************************************************************************************/ /**************************************ֲ*************************************************/ /***************************************************************************************************/ /***************************************************************************************************/ /**************************************ֲ*************************************************/ /***************************************************************************************************/ /***************************************************************************************************/ /***************************************************************************************************/ /***********************************************************************************************/ /***************************************************************************************************/ /***************************************************************************************************/ /***************************************************************************************************/ /************************************************************************ ** :CheckStrIsSame ** :ȽַǷͬ ** : ** : ** أ ** ע ** ʱ : ** ߣxsx ************************************************************************/ MyBool CheckStrIsSame(void *str1 , void * str2 , unsigned short len) { unsigned char *p = (unsigned char *)str1; unsigned char *q = (unsigned char *)str2; unsigned short i=0; if((NULL == p) || (NULL == q)) return FALSE; for(i=0; i<len; i++) { if(*q++ != *p++) return FALSE; } return TRUE; } char * MyStrStr(const char *str1 , const char * str2 , unsigned short len) { char *cp = (char *) str1; char *s1, *s2; unsigned short size = len; if ( !*str2 ) return((char *)str1); while (size--) { s1 = cp; s2 = (char *) str2; while ( *s1 && *s2 && !(*s1-*s2) ) s1++, s2++; if (!*s2) return(cp); cp++; } return(NULL); } /*************************************************************************************************** *FunctionName: calculateDataCV *Description: cvֵ *Input: datas -- * len -- ݳ * sum -- ۼӺͣΪ0Ҫ㣬ֱʹ *Output: *Return: *Author: xsx *Date: 201782 14:06:33 ***************************************************************************************************/ float calculateDataCV(unsigned short * datas, unsigned short len, double sum) { double average = 0; double tempV1 = 0; double tempV2 = 0; unsigned short i=0; unsigned short *p = datas; if(sum == 0) { for(i=0; i<len; i++) average += *p++; } else average = sum; average /= len; p = datas; for(i=0; i<len; i++) { tempV1 = *p++; tempV1 -= average; tempV1 *= tempV1; tempV2 += tempV1; } tempV2 /= len; tempV2 = sqrt(tempV2); return tempV2 / average; } void findFeng(unsigned short * datas, unsigned short startIndex, unsigned short midIndex, unsigned short endIndex, Point * myPoint) { unsigned short i=0, j=0; double tempv1 = 0; Point tempPoint; myPoint->x = 0; myPoint->y = 0; if(endIndex > 300) endIndex = 300; for(i=startIndex; i<endIndex-10; i++) { tempPoint.x = 0; tempPoint.y = 0; for(j=i; j<10+i; j++) { tempv1 = datas[j]; if(tempPoint.y < tempv1) { tempPoint.y = tempv1; tempPoint.x = j; } } for(j=0; j<10; j++) { if(datas[tempPoint.x-j] < datas[tempPoint.x-j-1]) break; if(tempPoint.x+j+1 < MaxPointLen) { if(datas[tempPoint.x+j] < datas[tempPoint.x+j+1]) break; } } if(j < 10) { continue; } else { if(tempPoint.y > myPoint->y) { myPoint->x = tempPoint.x; myPoint->y = tempPoint.y; } i = (tempPoint.x + 10); } } } MyState_TypeDef parseIpString(IP_Def * ip, char * ipStr) { char * tempP = NULL; if(ip == NULL || ipStr == NULL) return My_Fail; tempP = strtok(ipStr, "."); if(tempP) { ip->ip_1 = strtol(tempP, NULL, 10); if(ip->ip_1 > 255) return My_Fail; } else return My_Fail; tempP = strtok(NULL, "."); if(tempP) { ip->ip_2 = strtol(tempP, NULL, 10); if(ip->ip_2 > 255) return My_Fail; } else return My_Fail; tempP = strtok(NULL, "."); if(tempP) { ip->ip_3 = strtol(tempP, NULL, 10); if(ip->ip_3 > 255) return My_Fail; } else return My_Fail; tempP = strtok(NULL, "."); if(tempP) { ip->ip_4 = strtol(tempP, NULL, 10); if(ip->ip_4 > 255) return My_Fail; } else return My_Fail; return My_Pass; } MyState_TypeDef parsePortString(unsigned short * port, char * portStr) { if(port == NULL || portStr == NULL) return My_Fail; *port = strtol(portStr, NULL, 10); if(*port > 65535) return My_Fail; return My_Pass; }
C
#include <stdio.h> #include <stdlib.h> #include <mpi.h> #include <math.h> #include "f.h" void main(int argc, char** argv) { int rank, size; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); double t1,t2; int n = 1000, m, i_start, i_end; int M = (int)ceil((double)n/size); long long A[M+1][n]; long long sum, temp, medium; //STEP1: Initialize //m is #rows for each proc if (rank == size-1) { m = n-M*(size-1); } else { m = M; } //define the range need computation if (rank == 0) { i_start = 1; } else { i_start = 0; } if (rank == size -1) { i_end = m - 1; } else { i_end = m; } //initalize data matrix for (int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { A[i][j] = (rank*M + i) + j*n; } } //STEP2: Call barrier and start timing MPI_Barrier(MPI_COMM_WORLD); if(rank == 0) t1 = MPI_Wtime(); //STEP3: Do 10 iterations for (int step = 0; step < 10; step++) { if (rank > 0) { MPI_Send(&A[0], n, MPI_LONG_LONG, rank-1, 0, MPI_COMM_WORLD); } if (rank < size -1) { MPI_Recv(&A[m], n, MPI_LONG_LONG, rank+1, 0, MPI_COMM_WORLD, &status); } for (int i = i_start; i < i_end; i++) { for (int j = 1; j < n-1; j++) { A[i][j] = f(A[i][j], A[i+1][j], A[i][j+1], A[i+1][j+1]); } } } //STEP4: Compute verification values //compute sum of all elements sum = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { sum += A[i][j]; } } //printf("rank:%d, sum: %lld\n",rank,sum); for (int i = 1; i < size; i = i*2) { if(rank % (i*2) == i) { MPI_Send(&sum, 1, MPI_LONG_LONG, rank-i, 1, MPI_COMM_WORLD); //printf("send from %d to %d: %lld\n",rank, rank-i, sum); } if(rank % (i*2) == 0 && rank+i < size) { MPI_Recv(&temp, 1, MPI_LONG_LONG, rank+i, 1, MPI_COMM_WORLD, &status); sum = sum + temp; //printf("%d recieve data from %d: data_receive:%lld, sum:%lld\n",rank,rank+i,temp,sum); } } if (rank == (n/2 + 1)/M) { MPI_Send(&A[n/2-(n/2+1)/M*M][n/2], 1, MPI_LONG_LONG, 0, 2, MPI_COMM_WORLD); } if (rank == 0) { MPI_Recv(&medium, 1, MPI_LONG_LONG, (n/2 + 1)/M, 2, MPI_COMM_WORLD, &status); } //STEP5: Program ends and print out time if(rank == 0) { t2 = MPI_Wtime(); printf("Time: %f\n",t2-t1); printf("Sum of all elements: %lld\n",sum); printf("A[n/2][n/2]: %lld\n", medium); } MPI_Finalize(); }
C
#include <stdio.h> #include <stdlib.h> #include "nn_data_io.h" #ifdef __MSDOS__ #include "dos_fileio.h" #endif typedef unsigned char uchar; int read_mnist_bmp(const char *file_path, uchar **img, IMG_INFO **img_info){ FILE * fp = NULL; BITMAPFILEHEADER pFH; BITMAPINFOHEADER pIH; *img_info =(IMG_INFO*)malloc(sizeof(IMG_INFO)); if((fp=fopen(file_path, "rb")) == NULL){ printf("%sファイルのオープンに失敗\n", file_path); return -1; } #ifdef __MSDOS__ // ファイルポインタを画像データ位置まで移動 // fseek(fp, 1078, SEEK_SET); // IA16_GCC で fseek はなぜかうまく動作しない. uchar img_tmp[1078]; fread(img_tmp, sizeof(uchar), 1078, fp); int img_fp = dos_fopen(file_path); dos_fread(&pFH, sizeof(BITMAPFILEHEADER), 1, img_fp); dos_fread(&pIH, sizeof(BITMAPINFOHEADER), 1, img_fp); dos_fclose(img_fp); #else fread(&pFH, sizeof(BITMAPFILEHEADER), 1, fp); fread(&pIH, sizeof(BITMAPINFOHEADER), 1, fp); #endif // BMPであることを確認 if(pFH.bfType != 0x4d42){ printf("This file is not BMP!\n"); return -2; } (*img_info)->size = pIH.biWidth * pIH.biHeight; (*img_info)->width = pIH.biWidth; (*img_info)->height = pIH.biHeight; *img = (uchar *)malloc(pIH.biWidth * pIH.biHeight * sizeof(uchar)); // ファイルポインタを画像データ位置まで移動 fseek(fp, pFH.bfOffBits, SEEK_SET); // 画像データを逆さに読み込み uchar bufLine[pIH.biWidth]; for(int y = 0; y < pIH.biHeight; y++){ fread(bufLine, 1, pIH.biWidth, fp); for(int x = 0; x < pIH.biWidth; x++){ (*img)[(pIH.biHeight-y-1)*pIH.biWidth + x] = bufLine[x]; } } fclose(fp); return 0; } #ifdef __MSDOS__ int read_bin(char* file_name, float __far **array, long size){ int handle = 0; uint err_code = 0; handle = dos_fopen(file_name); if(handle < 0){ printf("Failed to open file : %04X\n", (handle * -1)); // return -1; } dos_fread((void __far *)*array, sizeof(float), size, handle); err_code = dos_fclose(handle); if(err_code != 0){ printf("Failed to close file : %04X\n", (err_code * -1)); return -1; } return 0; } #else int read_bin(const char* file_name, float **array, int size){ FILE * fp = NULL; if((fp = fopen(file_name, "rb")) == NULL){ printf("ファイルオープン失敗 %s\n", file_name); return -1; }; fread(*array, sizeof(float), size, fp); fclose(fp); return 0; } #endif