language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* filler.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dsemeryc <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/12/21 19:59:35 by dsemeryc #+# #+# */ /* Updated: 2018/12/24 04:28:46 by dsemeryc ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FILLER_FILLER_H # define FILLER_FILLER_H # define OPP_PLAYER(c) (c == 'X' ? 'O' : 'X') # define ABC(c) (c < 0 ? c * -1 : c) # include <stdlib.h> # include <unistd.h> # include "printf.h" # include "get_next_line.h" typedef struct s_coord { int x; int y; struct s_coord *next; } t_coord; typedef struct s_game { char **map; char **figure; char player; int map_x; int map_y; int figure_x; int figure_y; int coord_x; int coord_y; int init; int edge; int figure_size; } t_game; void add_new(t_coord **coord, t_coord *elem); t_coord *initialize_coord(int x, int y); void make_move(t_game *game); void read_map(t_game *game); void read_figure(t_game *game); t_game *read_info(t_game *game); void initialize_game(t_game *game); void free_str_arr(char **arr, int size); void free_game(t_game *game); void free_lists(t_coord **lst1, t_coord **lst2); void find_edge(t_game *game); void free_lst(t_coord **coord); int count_stars(t_game *game); void assign_coords(t_coord *chosen, t_game *game); #endif
C
#include<stdio.h> int main(void){ char word[] = "abc de fg hijk ablmn"; int two[625][3] = {{0}}, i=0, j=0, DA=0, DB=0; printf("%s\n", word); while(word[i] != 0x00){ if(word[i] >= 'a' && word[i] <= 'z'){ DA=1; } if(word[i+1] >= 'a' && word[i+1] <= 'z'){ DB=1; } if(DA == 1 && DB == 1){ do{ if((two[j][0]==word[i]) && (two[j][1]==word[i+1])){ two[j][2]++; break; } else if(two[j][0]==0){ two[j][0] = word[i]; two[j][1] = word[i+1]; two[j][2]++; break; } }while(two[j++][0] != 0); } j=0; i++; DA=0; DB=0; } i=0; while(two[i][0] != 0){ printf("%c%c : %d\n", two[i][0], two[i][1], two[i][2]); i++; } return 0; }
C
#include <limits.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // ???? #define D_DIGIT_CNT 19 // ?????? #define D_NG_NUM1 4 // NG?? #define D_NG_NUM2 9 // NG?? // ???? static FILE *szpFpI; // ?? // ???? - ???? #ifdef D_TEST static int siRes; static FILE *szpFpA; #endif // OK??? int fGetOKCnt( long long plVal // <I> ? , int piDigit // <I> ? , long long *plpRet // <O> OK? ) { int i; // ????OK?? long long llDiv = 1; long long llOK = 1; for (i = 1; i < piDigit; i++) { llDiv *= 10; llOK *= 8; } // ??????? long long llNum = plVal / llDiv; // ?????? int liNum = (int)(llNum % 10); // OK? - ?????? int liRet = 0; if (piDigit == 1) { if (liNum < D_NG_NUM1) { *plpRet = liNum + 1; } else if (liNum < D_NG_NUM2) { *plpRet = liNum; } else { *plpRet = liNum - 1; } } else { if (liNum < D_NG_NUM1) { *plpRet = liNum; } else if (liNum == D_NG_NUM1) { *plpRet = liNum; liRet = -1; } else if (liNum < D_NG_NUM2) { *plpRet = liNum - 1; } else { *plpRet = liNum - 1; liRet = -1; } *plpRet *= llOK; } return liRet; } // NG??? long long fGetNGCnt( long long plVal // <I> ? ) { int i, liRet; // OK? - ?? long long llOK = 0; for (i = D_DIGIT_CNT; i >= 1; i--) { long long llVal; liRet = fGetOKCnt(plVal, i, &llVal); llOK += llVal; if (liRet != 0) { break; } } return plVal - llOK; } // ????? int fMain( int piTNo // <I> ????? 1? ) { char lc1Buf[1024], lc1Out[1024]; // ?? - ??? #ifdef D_TEST sprintf(lc1Buf, ".\\Test\\T%d.txt", piTNo); szpFpI = fopen(lc1Buf, "r"); sprintf(lc1Buf, ".\\Test\\A%d.txt", piTNo); szpFpA = fopen(lc1Buf, "r"); siRes = 0; #else szpFpI = stdin; #endif // ?? - ?? long long llValS, llValE; fgets(lc1Buf, sizeof(lc1Buf), szpFpI); sscanf(lc1Buf, "%lld%lld", &llValS, &llValE); // NG??? llValS = fGetNGCnt(llValS - 1); llValE = fGetNGCnt(llValE); // ?? - ??? sprintf(lc1Out, "%lld\n", llValE - llValS); // ?? - ?? #ifdef D_TEST fgets(lc1Buf, sizeof(lc1Buf), szpFpA); if (strcmp(lc1Buf, lc1Out)) { siRes = -1; } #else printf("%s", lc1Out); #endif // ??????????? #ifdef D_TEST fclose(szpFpI); fclose(szpFpA); #endif // ????? #ifdef D_TEST if (siRes == 0) { printf("OK %d\n", piTNo); } else { printf("NG %d\n", piTNo); } #endif return 0; } int main() { #ifdef D_TEST int i; for (i = D_TEST_SNO; i <= D_TEST_ENO; i++) { fMain(i); } #else fMain(0); #endif return 0; } ./Main.c: In function fMain: ./Main.c:123:2: warning: ignoring return value of fgets, declared with attribute warn_unused_result [-Wunused-result] fgets(lc1Buf, sizeof(lc1Buf), szpFpI); ^
C
/* ** EPITECH PROJECT, 2021 ** Tek2 ** File description: ** array_emplace_primitive.c */ #include <stdio.h> #include <stdlib.h> #include "../jsnp_header.h" jsnp_value_t *array_emplace_primitive_back(jsnp_value_t *u, int value) { jsnp_value_t *v = malloc(sizeof(jsnp_value_t)); if (!v) return (perror("malloc"), NULL); v->type = JSNP_PRIMITIVE; v->count = 0; v->primitive = value; insert_value_back(u, v); return (v); } jsnp_value_t *array_emplace_primitive_front(jsnp_value_t *u, int value) { jsnp_value_t *v = malloc(sizeof(jsnp_value_t)); if (!v) return (perror("malloc"), NULL); v->type = JSNP_PRIMITIVE; v->count = 0; v->primitive = value; insert_value_front(u, v); return (v); } jsnp_value_t *array_emplace_primitive_at(jsnp_value_t *u, int value, unsigned index) { jsnp_value_t *v = malloc(sizeof(jsnp_value_t)); if (!v) return (perror("malloc"), NULL); v->type = JSNP_PRIMITIVE; v->count = 0; v->primitive = value; insert_value_at(u, v, index); return (v); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* buffer_function.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ythomas <ythomas@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/05 12:07:27 by ythomas #+# #+# */ /* Updated: 2019/09/30 15:59:41 by ldevelle ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/head.h" t_print *init_print(void) { t_print *print; print = ft_memalloc(sizeof(t_print)); return (print); } void print_whole_buffer(t_print *print) { t_print *tmp; tmp = print; while (tmp != NULL) { write(1, tmp->buff, tmp->index); tmp = tmp->next; } } void add_to_buffer(t_print *print, char *str) { int i; t_print *tmp; tmp = print; while (print->next != NULL) print = print->next; if (ft_strlen(str) + print->index > P_BUFF - 5) { print->next = init_print(); print = print->next; } i = 0; while (str[i] != '\0') print->buff[print->index++] = str[i++]; print->buff[print->index++] = '\n'; print = tmp; } void print_buffer_with_refresh(t_print *print) { int i; if (print->index != 0) (print->index)--; print->buff[print->index] = '\n'; (print->index)++; write(1, print->buff, print->index); i = 0; while (i < print->index) print->buff[i++] = '\0'; print->index = 0; } void fill_line_buffer(t_print *print, char *nb, char *name) { int i; int j; print->buff[print->index] = 'L'; (print->index)++; i = 0; while (nb[i] != '\0') { print->buff[print->index] = nb[i++]; (print->index)++; } print->buff[print->index] = '-'; (print->index)++; j = 0; while (name[j] != '\0') { print->buff[print->index] = name[j++]; (print->index)++; } print->buff[print->index] = ' '; (print->index)++; }
C
void hexdump(char *data, unsigned int length){ unsigned int i = 0; while(i < length){ printf("%02x ", (unsigned char)data[i++] & '\xff'); } } frag_hole_t *hole(guint16 start, guint16 end){ // Creates a fragment hole record frag_hole_t *newhole = NULL; newhole=(frag_hole_t*)malloc(sizeof(frag_hole_t)); if(newhole == NULL){ printf("Error allocating memory for fragment hole data!\n"); return(NULL); } newhole->start = start; newhole->end = end; newhole->next = NULL; newhole->prev = NULL; return(newhole); } frame_t *merge_fragment(fragment_detail_t *frag, fragment_list_t *fragmentlist){ // RFC 815 fragment reassembly algorithm. If the fragment provided completes a frame // then it is returned, otherwise the fragment list is updated and NULL returned. frag_hole_t *cur = NULL, *newhole = NULL, *destroyme = NULL; frame_t *frame = NULL; int ihl = (frag->data[0] & '\x0f') * 4; for(cur = fragmentlist->holes; cur != NULL; cur = cur->next){ // step 1 if(frag->start > cur->end) continue; // step 2 - fragment after current hole if(frag->end < cur->start) continue; // step 3 - frament precedes current hole if(fragmentlist->holes == cur){ // step 4 - fragment overlaps hole, delete hole fragmentlist->holes = cur->next; } else { cur->prev->next = cur->next; } if(cur->next != NULL){ cur->next->prev = cur->prev; } destroyme = cur; if(frag->start > cur->start){ // step 5 - fragment not at beginning of hole, create smaller hole before newhole = hole(cur->start, frag->start - 1); newhole->next = fragmentlist->holes; if(fragmentlist->holes != NULL){ fragmentlist->holes->prev = newhole; } fragmentlist->holes = newhole; } if((frag->end < cur->end) && (frag->more == MOREFRAGS)){ // step 6 - fragment not at end of hole and there are more to come, create smaller hole after newhole = hole(frag->end + 1, cur->end); newhole->next = fragmentlist->holes; if(fragmentlist->holes != NULL){ fragmentlist->holes->prev = newhole; } fragmentlist->holes = newhole; } // step 7 - inspect next hole } // If we removed an entry, free the memory if(destroyme != NULL){ free(destroyme); destroyme = NULL; } // Copy data in memcpy(fragmentlist->data + frag->start, frag->data+ihl, frag->end - frag->start); // If this is the first fragment then grab the IP header if(frag->start == 0){ fragmentlist->header = malloc(ihl); if(fragmentlist->header == NULL){ printf("Error, unable to allocate memory for IP header reassembly!\n"); return(NULL); } memcpy(fragmentlist->header, frag->data, ihl); } // If no more fragments then set data size if(frag->more == 0){ fragmentlist->size = frag->end; } // If there are no holes left then our frame is complete // Build up the frame template ready to return if(fragmentlist->holes == NULL){ frame = malloc(sizeof(frame_t)); if(frame == NULL){ printf("Error: could not allocate memory for defragmented frame!\n"); return(NULL); } frame->payload = malloc(ihl+fragmentlist->size); memcpy(frame->payload, fragmentlist->header, ihl); memcpy(frame->payload + ihl, fragmentlist->data, fragmentlist->size); memcpy(frame->payload + 2, &fragmentlist->size, 2); // Adjust total length memcpy(frame->payload + 6, "\x00\x00",2); // Reset fragment info frame->plen = fragmentlist->size + ihl; memcpy(frame->etype, "\x08\x00", 2); frame->fragment = 0; } free(frag->data); free(frag); // Return a frame if we got one or NULL otherwise return(frame); } frame_t *insert_fragment(fragment_detail_t *frag, fragment_list_t **fragments, char *ipinfo){ fragment_list_t *cur = NULL, *prev = NULL; frame_t *frame = NULL; // If no other entries exist, create one and make it the head of the list if(*fragments == NULL){ cur = (fragment_list_t*)malloc(sizeof(fragment_list_t)); if(cur == NULL){ printf("Error: could not allocate memory for fragment list!\n"); return(NULL); } cur->data = (char*)malloc(65535); if(cur->data == NULL){ printf("Error: could not allocate working memory for fragment rebuild!\n"); free(cur->ipinfo); free(cur); return(NULL); } cur->ipinfo = ipinfo; cur->holes = hole(0, 65535); cur->header = NULL; cur->next = NULL; *fragments = cur; return(merge_fragment(frag, cur)); } // Otherwise, look for a fragment entry with the same IP info cur = *fragments; // Work through the list until we find a fragment list with the same IP info while(cur != NULL){ if(memcmp(cur->ipinfo, ipinfo, 6) == 0){ // Found a match, add the frame detail frame = merge_fragment(frag, cur); // If we got a completed frame back... if(frame != NULL){ // Change references to point past this item if(prev == NULL){ *fragments = cur->next; } else { prev->next = cur->next; } // Clean up unreferenced memory free(cur->ipinfo); free(cur->header); free(cur->data); free(cur); } // Return a frame if we got one or NULL otherwise return(frame); } prev = cur; cur = cur->next; } // If we got here then our IP info didn't match anything in the list. // Create a new entry and populate it cur = malloc(sizeof(fragment_list_t)); if(cur == NULL){ printf("Error: could not allocate memory for fragment list!\n"); return(NULL); } cur->ipinfo = ipinfo; cur->data = (char*)malloc(65535); if(cur->data == NULL){ printf("Error: could not allocate working memory for fragment rebuild!\n"); free(cur->ipinfo); free(cur); return(NULL); } cur->holes = hole(0, 65535); cur->header = NULL; cur->next = NULL; // Add this entry to the end of the list prev->next = cur; return(merge_fragment(frag, cur)); } frame_t *handle_ipv4_fragment(char *data, unsigned int length, frame_t *frame, fragment_list_t **fragments){ fragment_detail_t *frag = NULL; int total_length = 0, header_length = 0; char *ipinfo = NULL; // Calculate the lengths from the IPv4 header total_length = (256 * (unsigned char)data[2]) + (unsigned char)data[3]; header_length = 4 * ((unsigned char)data[0] & '\x0f'); // Create the fragment record frag = (fragment_detail_t*)malloc(sizeof(fragment_detail_t)); if(frag == NULL){ printf("Error: could not allocate memory for re-assembly!\n"); return(NULL); } // Populate the fragment record frag->start = 8 * ((256 * ((unsigned char)data[6] & '\x1f')) + (unsigned char)data[7]); frag->end = frag->start + total_length - header_length; frag->data = malloc(total_length); if(frag->data == NULL){ printf("Error: could not allocate memory for fragment mirror\n"); free(frag); return(NULL); } // Sanity check the length field vs. captured data length if(total_length > length){ printf("Error: truncated packet fragment!\n"); free(frag); return(NULL); } // Populate the IP info ipinfo = malloc(10); if(ipinfo == NULL){ printf("Error: unable to allocate memory for IP info\n"); free(frag); return(NULL); } memcpy(ipinfo, data + 4, 2); // IPID memcpy(ipinfo + 2, data + 12, 8); // Source & Destination // Copy the data into the fragment record memcpy(frag->data, data, total_length); // Populate the more fragments indicator frag->more = (data[6] & MOREFRAGS); // Insert this fragment into the list of lists of fragments, if it completes a frame then return it return(insert_fragment(frag, fragments, ipinfo)); } frame_t *reassemble(char *data, unsigned int length, char type, frame_t *frame, fragment_list_t **fragments){ if(type != ETHERNET){ printf("Warning: Trying to re-assemble non-Ethernet type!\n"); return(NULL); } if(length < 14){ printf("Warning: truncated frame discarded!\n"); return(NULL); } if(data == NULL){ printf("Warning: trying to re-assemble null frame data!\n"); return(NULL); } // Populate the frame header and etype frame->ether = data; memcpy(frame->etype, data+12, 2); frame->plen = length - 14; // For non-IP, simply return the frame if(memcmp(data+12, "\x08\x00",2) != 0){ frame->payload = data + 14; return(frame); } // For non-fragments, simply return the frame if(((data[20] & '\x3f') | data[21]) == 0){ frame->payload = data + 14; return(frame); } // For fragments, attempt to re-assemble frame = handle_ipv4_fragment(data+14, length-14, frame, fragments); if(frame != NULL){ frame->ether = data; } return(frame); }
C
//https://blog.noctua-software.com/c-lambda.html #include <stdio.h> void func(int nb, void (*f)(int)){ int i; for(i = 0; i < nb; i ++) f(i); } int main () { void callback(int v){ printf("%d\n", v); } func(4, callback); fprintf (stdout, "====\n"); func(4, ({ void _(int v){ printf("%d\n", v); } _; })); }
C
//wap to input side of a square & calculate its area & parameter// main() { int s,a,p; clrscr(); printf("enter side="); scanf("%d",&s); a=s*s; p=4*s; printf("\n\nArea=%d\n\nparameter=%d",a,p); getch(); }
C
#include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> int random_int() { int fd = open("/dev/random", O_RDONLY); if ( fd == -1) { printf("couldn't open: %s\n", strerror(errno)); return 0; } int rando; if (read(fd, &rando, sizeof(int)) == -1 ) { printf("couldn't read: %s\n", strerror(errno)); } if (close(fd) == -1) { printf("couldn't close: %s\n", strerror(errno)); } return rando; }
C
// // Created by Fabian Terhorst on 11.10.17. // #include <stdio.h> #include <stdlib.h> #include "single_linked_list.h" #include "single_linked_list_tests.h" #include <limits.h> struct MenuItem { char* name; void (* fct)(struct Node*); }; bool running = true; void initMenuItem(struct MenuItem* menuItem, char* name, void(* fct)(struct Node*)) { menuItem->name = name; menuItem->fct = fct; } void printMenu(struct MenuItem menu[4]) { for (int i = 0; i < 4; i++) { printf("%d. %s\n", i + 1, menu[i].name); } printf("Bitte geben Sie die Ziffer der gewuenschten Funktion ein:\n"); } void add(struct Node* singleLinkedList) { printf("Bitte geben Sie eine Zahl ein\n"); char keyString[256]; scanf("%s", keyString); char* endP = NULL; int key = (int) strtol(keyString, &endP, 10); if (endP == keyString) { printf("%s ist keine valide Zahl\n", keyString); return; } single_linked_list_insert(singleLinkedList, key); printf("%d erfolgreich hinzugefügt.\n", key); } void delete(struct Node* singleLinkedList) { printf("Bitte geben Sie die zu löschene Zahl ein\n"); char keyString[256]; scanf("%s", keyString); char* endP = NULL; int key = (int) strtol(keyString, &endP, 10); if (endP == keyString) { printf("%s ist keine valide Zahl\n", keyString); return; } if (single_linked_list_delete(singleLinkedList, key)) { printf("%d gelöscht.\n", key); } else { printf("%d konnte nicht gefunden werden.\n", key); } } void print(struct Node* singleLinkedList) { single_linked_list_print(singleLinkedList); } void close(struct Node* singleLinkedList) { running = false; } int main() { runTests(); struct MenuItem menuItemCreate; initMenuItem(&menuItemCreate, "Sortiertes Einfuegen eines Elementes", &add); struct MenuItem menuItemDelete; initMenuItem(&menuItemDelete, "Loeschen und Ausgeben des Elementes mit Schluessel key", &delete); struct MenuItem menuItemPrint; initMenuItem(&menuItemPrint, "Ausgeben der Liste", &print); struct MenuItem menuItemExit; initMenuItem(&menuItemExit, "Beenden des Programms", &close); struct MenuItem menuItems[4] = {menuItemCreate, menuItemDelete, menuItemPrint, menuItemExit}; struct Node* singleLinkedList = single_linked_list_init(); long menuIndex; char menuIndexString[256]; char* endP; int base = 0; while (running) { printMenu(menuItems); scanf("%s", menuIndexString); menuIndex = strtol(menuIndexString, &endP, base); if (menuIndex > 4 || menuIndex < 1) { printf("Bitte geben Sie eine Zahl zwischen 1 und 4 ein\n"); continue; } menuItems[--menuIndex].fct(singleLinkedList); } single_linked_list_deinit(singleLinkedList); return 0; }
C
#include<stdlib.h> #include<stdio.h> int main (void) { int* data = (int*)malloc(100 * sizeof(int)); data[0] = 18557; printf("%d\n", data[0]); free(data); printf("%d\n", data[0]); return 0; }
C
#include"stdio.h" #include"unistd.h" int main() { pid_t firstch, secondch; pid_t returnR; firstch = fork(); if(firstch>0) { printf("I am Parent Proccess ID %d and my Child is in Execution...\n",getpid()); returnR = wait(NULL); printf("I am Parent Proccess ID %d and my Child is in terminated... and wait rerurn value is %d\n",getpid(),returnR); } if(firstch == 0) { printf("I am Parent Proccess ID %d and my Child is in Execution1...\n",getpid()); int sum = 99+99; printf("Sum is %d\n",sum); } }
C
#include "audio.h" void loadSound(int index, char *name) { /* Load the sound specified by the filename */ if (index < 0 || index >= MAX_SOUNDS) { printf("Invalid index for sound! Index: %d Maximum: %d\n", index, MAX_SOUNDS); exit(1); } sound[index].effect = Mix_LoadWAV(name); if (sound[index].effect == NULL) { printf("Failed to load sound %s\n", name); exit(1); } } void playSound(index) { /* Play the sound on the first free channel and only play it once */ if (index < 0 || index >= MAX_SOUNDS) { printf("Invalid index for sound! Index: %d Maximum: %d\n", index, MAX_SOUNDS); exit(1); } Mix_PlayChannel(-1, sound[index].effect, 0); } void loadAllSounds() { loadSound(BULLET_SOUND, "sound/plasma.ogg"); } void freeSounds() { int i; for (i=0;i<MAX_SOUNDS;i++) { if (sound[i].effect != NULL) { Mix_FreeChunk(sound[i].effect); } } }
C
#include<stdio.h> #include<conio.h> #include<alloc.h> typedef struct celula_lista { int k; struct celula_lista *next; } LIST; typedef struct coada { LIST *front,*rear; } QUEUE; QUEUE *newq(QUEUE *q) { q=(QUEUE *)malloc(sizeof(QUEUE)); q->front=q->rear=NULL; return(q); } int emptyq(QUEUE *q) {if((q->front==q->rear)&&(q->front==NULL)) return(1); else return(0); } QUEUE *addq(QUEUE *q,int e) {LIST *aux; aux=(LIST *)malloc(sizeof(LIST)); aux->k=e; aux->next=NULL; if ((q->front==NULL)&&(q->rear==NULL)) /* e primul element */ q->front=q->rear=aux; else { q->rear->next=aux; q->rear=aux; } return(q); } QUEUE *initializare_coada_cu_header() {LIST *aux; char c,c1; int k; QUEUE *q; q=newq(q); /* aux=NULL;q->front=q->rear=aux;*/ printf(" DORITI SA INCEPETI INITIALIZAREA COZII ? [D/N] "); scanf("%c",&c);c1=getchar(); while ((c=='d') || (c=='D')) {printf(" \n INTRODUCETI O CHEIE : "); scanf("%d",&k);c1=getchar(); q=addq(q,k); printf("\n CONTINUATI ? "); scanf("%c",&c);c1=getchar(); } return(q); } void printq(QUEUE *q) { LIST *p; p=q->front; if(emptyq(q)) printf(" coada vida \n "); else { do { printf("%d ",p->k); p=p->next; } while (p!=NULL); } printf(" \n "); } QUEUE *remq(QUEUE *q) {LIST *out; if(!emptyq(q)) {out=q->front; if (q->front->next) q->front=q->front->next; else q->front=q->rear=NULL; free(out); return(q); } else {printf("\n Coada era vida !"); return NULL; } getch(); } int frontq(QUEUE *q) {if(!emptyq(q)) return(q->front->k); else {printf("\n Coada este vida."); return(-1);} } /*main() {QUEUE *q; clrscr(); q=initializare_coada_cu_header(); printf("\n\nlista deja introdusa este :\n\n"); printq(q); printf("car-ul listei este %d \n",frontq(q)); while (q) {q=remq(q);printf("coada dupa remq este:"); printq(q);} getch(); }*/
C
/* ** EPITECH PROJECT, 2020 ** B-CPE-110-PAR-1-3-pushswap-perry.chouteau ** File description: ** init.c */ #include "../includes/include.h" void describe(void) { my_printf("USAGE\n"); my_printf(" ./push_swap [nombre1, nombre 2, ...]\n"); my_printf("DESCRIPTION\n"); my_printf("sort all number, giving, step by step, what we have done.\n"); } int my_error(int ac, char **av) { if (ac == 1) return 84; if (ac == 2 && my_strcmp(av[1], "-h") == 0) { describe(); return 1; } return 0; } int init(cell_t **l_a, cell_t **l_b, int ac, char **av) { cell_t *prec; cell_t *cur; int i = 0; if (ac == 2) return 1; l_a[0] = empty_list(); l_b[0] = empty_list(); for (; i < (ac - 1); i += 1) add_at(l_a, my_getnbr(av[i + 1]), i); prec = l_a[0]; cur = l_a[0]; while (cur != NULL) { if (prec->data > cur->data) return 0; prec = cur; cur = cur->next; } return 1; }
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 */ struct trie {struct trie* next; } ; struct tree {struct trie* trie; struct tree* rlink; struct tree* llink; } ; /* Variables and functions */ __attribute__((used)) static void enqueue (struct tree *tree, struct trie **last) { if (!tree) return; enqueue(tree->llink, last); enqueue(tree->rlink, last); (*last) = (*last)->next = tree->trie; }
C
#include <stdio.h> int main() { int i; char c; scanf("%d", &i); c = i; printf("c=%d\n", c); printf("c='%c'\n", c); printf("%d",(short)32); return 0; }
C
#include "server.h" int serv_list(int sock_data, int sock_control) { char data[MAXSIZE]; size_t num_read; FILE *fd; if (system("ls -l | tail -n+2 > .tmp") < 0) { exit(1); } if (!(fd = fopen(".tmp", "r"))) { exit(2); } /* Seek to the beginning of the file */ fseek(fd, SEEK_SET, 0); send_response(sock_control, 1); //starting memset(data, 0, MAXSIZE); while ((num_read = fread(data, 1, MAXSIZE, fd)) > 0) { if (send(sock_data, data, num_read, 0) < 0) { perror("err"); } memset(data, 0, MAXSIZE); } fclose(fd); system("rm -f .tmp"); send_response(sock_control, 226); // send 226 return 0; } int serv_tree(int sock_data, int sock_control) { char data[MAXSIZE]; size_t num_read; FILE *fd; if (!(fd = fopen("../.tmp", "w"))) { exit(1); } tree(".", 0, fd); fclose(fd); if (!(fd = fopen("../.tmp", "r"))) { exit(2); } /* Seek to the beginning of the file */ fseek(fd, SEEK_SET, 0); send_response(sock_control, 1); //starting memset(data, 0, MAXSIZE); while ((num_read = fread(data, 1, MAXSIZE, fd)) > 0) { fflush(stdout); if (send(sock_data, data, num_read, 0) < 0) { perror("err"); } memset(data, 0, MAXSIZE); } fclose(fd); system("rm -f ../.tmp"); send_response(sock_control, 226); // send 226 return 0; } int serv_mdir(int sock_control, char *path) { struct stat st = {0}; if (stat(path, &st) == -1) { if (!mkdir(path, 0700)) { send_response(sock_control, 226); return 0; } } send_response(sock_control, 551); return -1; } int serv_cdir(int sock_control, char *path) { if (chdir(path) == 0) { if (access(".auth", F_OK) == 0) { chdir("data"); send_response(sock_control, 552); return -1; } send_response(sock_control, 226); return 0; } send_response(sock_control, 552); return -1; } int serv_rm(int sock_control, char *path) { if (is_file(path)) { dprint("This is a file %c", '!'); if (remove(path) == 0) { send_response(sock_control, 226); return 0; } send_response(sock_control, 555); } else { if (remove_directory(path) == 0) { send_response(sock_control, 226); return 0; } send_response(sock_control, 555); } return -1; } int serv_rename(int sock_control, char *arg) { char *path_a, *path_b, *ch; path_a = strtok_r(arg, " ", &ch); path_b = strtok_r(NULL, " ", &ch); if (rename(path_a, path_b) == 0) { send_response(sock_control, 226); return 0; } send_response(sock_control, 555); return -1; } int start_data_conn(int sock_control) { char buf[1024]; int wait, sock_data; // Wait for go-ahead on control conn if (recv(sock_control, &wait, sizeof wait, 0) < 0) { perror("Error while waiting"); return -1; } // Get client address struct sockaddr_in client_addr; socklen_t len = sizeof client_addr; getpeername(sock_control, (struct sockaddr *)&client_addr, &len); inet_ntop(AF_INET, &client_addr.sin_addr, buf, sizeof(buf)); // Initiate data connection with client if ((sock_data = socket_connect(CLIENT_PORT, buf)) < 0) return -1; return sock_data; } int haspermison(int cmd, char *p) { if( cmd <= cmd_begin || cmd >= cmd_end) { perror("command out of range\n"); exit(1); } return p[cmd - cmd_begin - 1] - '0'; } int getpermision(char *username, char *permision) { size_t bread; size_t len = 0; FILE *fd; char *cuser, *perm, *line; int p = -1; fd = fopen(".perm", "r"); if (fd == NULL) { perror("file not found"); exit(1); } while ((bread = getline(&line, &len, fd)) != -1) { cuser = strtok_r(line, " ", &perm); strtrim(perm); // dprint("USER %s\nPERM %s\n", cuser, perm); if (strcmp(cuser, username) == 0) { p = 1; strcpy(permision, perm); break; } } free(line); fclose(fd); return p; } int check_user(char *user, char *pass) { char username[MAXSIZE]; char password[MAXSIZE]; char *pch; char buf[MAXSIZE]; char *line = NULL; size_t num_read; size_t len = 0; FILE *fd; int auth = 0; fd = fopen(".auth", "r"); if (fd == NULL) { perror("file not found"); exit(1); } while ((num_read = getline(&line, &len, fd)) != -1) { memset(buf, 0, MAXSIZE); strcpy(buf, line); pch = strtok(buf, " "); strcpy(username, pch); if (pch != NULL) { pch = strtok(NULL, " "); strcpy(password, pch); } // remove end of line and whitespace strtrim(password); if ((strcmp(user, username) == 0) && (strcmp(pass, password) == 0)) { auth = 1; break; } } free(line); fclose(fd); return auth; } int login(int sock_control, char *struser) { char buf[MAXSIZE]; char user[MAXSIZE]; char pass[MAXSIZE]; memset(user, 0, MAXSIZE); memset(pass, 0, MAXSIZE); memset(buf, 0, MAXSIZE); // Wait to recieve username if ((recv_data(sock_control, buf, sizeof(buf))) == -1) { perror("recv error\n"); exit(1); } strcpy(user, buf + 1); strcpy(struser, user); char *key = statkey(user); // tell client we're ready for password send_response(sock_control, 331); // Wait to recieve password memset(buf, 0, MAXSIZE); if ((recv_data(sock_control, buf, sizeof(buf))) == -1) { perror("recv error\n"); exit(1); } strcpy(pass, buf + 1); cripto(pass, key, 0); return (check_user(user, pass)); } int recv_cmd(int sock_control, char *cmd, char *arg) { int rc = 200; char buffer[MAXSIZE]; memset(buffer, 0, MAXSIZE); memset(arg, 0, MAXSIZE); // Wait to recieve command if ((recv_data(sock_control, buffer, sizeof(buffer))) == -1) { perror("recv error\n"); return -1; } *cmd = buffer[0]; strcpy(arg, buffer + 1); if (*cmd == cmd_quit) { rc = 221; } else if (*cmd > cmd_begin && cmd_end > *cmd) { rc = 200; } else { rc = 502; } return rc; } void serve_process(int sock_control) { int sock_data; char cmd[1]; char arg[MAXSIZE]; char permision[50]; char username[50]; // Send welcome message send_response(sock_control, 220); // Authenticate user if (login(sock_control, username) == 1) { send_response(sock_control, 230); } else { send_response(sock_control, 430); exit(0); } getpermision(username, permision); chdir("data"); while (1) { // Wait for command int rc = recv_cmd(sock_control, cmd, arg); printf("serverftp> comand %d %s\n", (int)*cmd, arg); fflush(stdout); if ((rc < 0) || (rc == 221)) { break; } if(haspermison((int)cmd[0], permision) == 0) { send_response(sock_control, 403); continue; } if (rc == 200) { send_response(sock_control, 200); // Open data connection with client if ((sock_data = start_data_conn(sock_control)) < 0) { close(sock_control); exit(1); } // Execute command switch (*cmd) { case cmd_list: serv_list(sock_data, sock_control); break; case cmd_tree: serv_tree(sock_data, sock_control); break; case cmd_get: file_send(sock_data, sock_control, arg, 0); break; case cmd_post: if ((rc = recv_code(sock_control)) == 150) { file_recive(sock_data, sock_control, arg, 0); recv_code(sock_control); send_response(sock_control, 226); } else { send_response(sock_control, 550); } break; case cmd_mdir: serv_mdir(sock_control, arg); break; case cmd_cdir: serv_cdir(sock_control, arg); break; case cmd_remove: serv_rm(sock_control, arg); break; case cmd_rename: serv_rename(sock_control, arg); break; case cmd_quit: /* code */ break; default: break; } // Close data connection close(sock_data); } } } int main(int argc, char **argv) { int sock_listen, sock_control, port, pid; char s_port[25]; system("mkdir -p ./data"); if (readconfig(s_port, "server.cfg", "port") == 0) { perror("Error reading config"); exit(0); } port = atoi(s_port); printf("servftp> Server start\n"); fflush(stdout); // create socket if ((sock_listen = socket_create(port)) < 0) { perror("Error creating socket"); exit(0); } while (1) { // wait for client request // create new socket for control connection if ((sock_control = socket_accept(sock_listen)) < 0) { perror("accept() error"); break; } // create child process to do actual file transfer if ((pid = fork()) < 0) { perror("Error forking child process"); } else if (pid == 0) { close(sock_listen); serve_process(sock_control); close(sock_control); exit(0); } close(sock_control); } close(sock_listen); return 0; }
C
/****************************************Copyright (c)*************************************** ** http://www.openmcu.com **------------------------------------------------------------------------------------------- ** File name: main.c ** Last modified Date: 2013-01-04 ** Last Version: V1.0 ** Descriptions: 407 ** **------------------------------------------------------------------------------------------- ** Created by: FXL ** Last modified Date: 2013-01-04 ** Last Version: V1.00 ** Descriptions: 407 ** **------------------------------------------------------------------------------------------- ** Modified by: ** Modified date: ** Version: ** Descriptions: **------------------------------------------------------------------------------------------- ********************************************************************************************/ #include "stm32f4xx.h" #include "Gpio.h" void Delay(int counter); // int main(void) { KEYGpio_Init(); //IOڳʼ LEDGpio_Init(); //LEDIOڳʼ while (1) { if(KEY_S1_UPDOWM() == Bit_RESET) //жϰ״̬ { Delay(0x8fffff); //ʱȥ if(KEY_S1_UPDOWM() == Bit_RESET) //ٴȷϰ״̬ { if(GPIO_ReadOutputDataBit(LED1_GPIO,LED1_GPIO_PIN) == Bit_SET) //жϵƵĵǰ״̬ȻԵȡ LED1_ONOFF(Bit_RESET); else LED1_ONOFF(Bit_SET); } } if(KEY_S2_UPDOWM() == Bit_RESET) { Delay(0x8fffff); if(KEY_S2_UPDOWM() == Bit_RESET) { if(GPIO_ReadOutputDataBit(LED2_GPIO,LED2_GPIO_PIN) == Bit_SET) //жϵƵĵǰ״̬ȻԵȡ LED2_ONOFF(Bit_RESET); else LED2_ONOFF(Bit_SET); } } if(KEY_S3_UPDOWM() == Bit_RESET) { Delay(0x8fffff); if(KEY_S3_UPDOWM() == Bit_RESET) { if(GPIO_ReadOutputDataBit(LED3_GPIO,LED3_GPIO_PIN) == Bit_SET) //жϵƵĵǰ״̬ȻԵȡ LED3_ONOFF(Bit_RESET); else LED3_ONOFF(Bit_SET); } } if(KEY_S4_UPDOWM() == Bit_RESET) { Delay(0x8fffff); if(KEY_S4_UPDOWM() == Bit_RESET) { if(GPIO_ReadOutputDataBit(LED4_GPIO,LED4_GPIO_PIN) == Bit_SET) //жϵƵĵǰ״̬ȻԵȡ LED4_ONOFF(Bit_RESET); else LED4_ONOFF(Bit_SET); } } if(KEY_S5_UPDOWM() == Bit_RESET) { Delay(0x8fffff); if(KEY_S5_UPDOWM() == Bit_RESET) { if(GPIO_ReadOutputDataBit(LED1_GPIO,LED1_GPIO_PIN) == Bit_SET) //жϵƵĵǰ״̬ȻԵȡ { LED1_ONOFF(Bit_RESET); LED2_ONOFF(Bit_RESET); LED3_ONOFF(Bit_RESET); LED4_ONOFF(Bit_RESET); } else { LED1_ONOFF(Bit_SET); LED2_ONOFF(Bit_SET); LED3_ONOFF(Bit_SET); LED4_ONOFF(Bit_SET); } } } } } void Delay(int counter) { while(counter--); }
C
/** * Yes, this code works. No, it's not good practice. Fix all the issues here! * */ int main(void) { printf("What's up, world?!\n"); return 0; }
C
#include <stdio.h> #define SIZE1 2; #define SIZE2 3; int main(){ /*int ar1[][2] = {{1,2}, {3,4},{5,6}}; int i,j; for(i=0; i<3; i++){ for(j=0; j<2; j++){ printf("%d",ar1[i][j]); } putchar('\n'); }*/ int ar2[][3][2] = {{{1,2},{3,4},{5,6}},{{7,8},{9,0},{1,2}}}; for(int i = 0; i<2; i++) { for(int j=0; j<3; j++){ for (int z=0; z<2; z++){ printf("%d", ar2[i][j][z]); } putchar('\n'); } putchar('\n'); } return 0; }
C
#include <stdio.h> #include <math.h> #include "audioDeviceInterface.h" #include "queue.h" #ifndef M_PI #define M_PI (3.14159265) #endif #define DURATION (SAMPLE_RATE * 3) int main(){ /* Test Sound Data Generation */ float sine[DURATION]; int f = 400; for(unsigned long i = 0; i < DURATION; i++){ sine[i] = sin(2 * M_PI * f * i / SAMPLE_RATE); } /* Audio Interface Initialization */ InitializeAudioInterface(); /* Sending Output Data */ for(unsigned long i = 0; i < DURATION; i++){ audio_send(sine[i]); //audio_send(0); } audio_flush_out(); /* Sending Recorded Data */ for(unsigned long i = 0; i < DURATION; i++){ audio_send(audio_receive()); } audio_flush_out(); /* Audio Interface De-Initialization */ TerminateAudioInterface(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "disparity.h" /******************************** Author: Sravanthi Kota Venkata ********************************/ void padarray4(I2D *inMat, I2D *borderMat, int dir, I2D *paddedArray) { int rows, cols, bRows, bCols, newRows, newCols; int i, j; int adir; adir = abs(dir); rows = inMat->height; cols = inMat->width; bRows = borderMat->data[0]; bCols = borderMat->data[1]; newRows = rows + bRows; newCols = cols + bCols; if(dir == 1) { for(i = 0; i < rows; i++) for(j = 0; j < cols; j++) paddedArray->data[(i) * paddedArray->width + (j)] = inMat->data[(i) * inMat->width + (j)]; } else { for(i = 0; i < rows - bRows; i++) for(j = 0; j < cols - bCols; j++) paddedArray->data[((bRows + i)) * paddedArray->width + ((bCols + j))] = inMat->data[(i) * inMat->width + (j)]; } return; }
C
//#include<stdio.h> // //void main() //{ // // int limparQ = 10; // // do{ // printf("Limpando : %i\n",limparQ); // limparQ--; // // }while(limparQ > 0); // // printf("Limpei tudo : %i\n",limparQ); //}
C
/* CS 214: Systems Programming Spring 2018 * Professor Francisco * Assignment 1: To Build A Better Malloc * Richard Farrington netid: raf172 * Anirudh Tunoori netid: at813 */ //mymalloc.c #include <stdlib.h> #include <ctype.h> #include <stdio.h> #include <string.h> #include "mymalloc.h" static char mem[5000]; /*mem is the block the ptr is going to iterate through the block as needed our metadata will be comprised of a short (used to indicate number of blocks in an area) and a character(the character will be 'y' if the space is available and 'n' if it is not this means that every time I allocate a new space, I am taking away only three bytes*/ void* mymalloc(int x, char* file, int linenum){ if(x>4997) { //assuming it is available, the most space that can be given is 4997 bytes printf("User is asking for more space than what can be given. file: %s line no.: %d\n", file, linenum); return NULL; } else if(x==0) { printf("User is requesting a pointer with no bytes. file: %s line no.: %d\n", file, linenum); return NULL; } short z; z = (short)x; if( (mem[0] != 'y') && (mem[0] != 'n') ) { //this means that malloc has been called for the first time. we create a chunk of metadata that will be in use and another available chunk of data mem[0] = 'n'; //this indicates that the first chunk of metadata is in use short * val1 = (short*)(&mem[1]); //val1 is a short pointer that will store the short portion of the metadata *val1 = z; //the first block is equal to z, which is what the user requested mem[z+3] = 'y'; //this is the next available chucnk of metadata short * val2 = (short*) (&mem[z+4]); //val2 is the short that is going to be stored in the next available chunk of metadata. *val2 = 4997-z-3; //4997 is derived from the fact that each chunk of metadata is 3 bytes, so we can have at most 4997 bytes available return mem+3; //we want to return the actual chunk of data that the user asked for } short * val3; //this is a temp pointer variable char * ptr = mem; //ptr is going to iterate through the block short* val4; //whenever a new chunk of data is going to be made, the short value will be *val4 while(ptr < mem+5000) { //if ptr <= mem+5000, that means that you have gone past the block val3 = (short*)(&ptr[1]); //ptr[1] is the beginning of the short value if(ptr[0] == 'n') { ptr = ptr+(*val3)+3; //move pointer to the next chunk of metadata since the this bit of data is in use } else if(ptr[0] == 'y') { //data is available short temp; temp = *val3; //temp takes the value inside val3 because val3 may change if(temp >= z) { ptr[0] = 'n'; //you are giving the user some data, so it will be in use if(temp > (z+3) ) { //another chunk of metadata can be made *val3 = z; //val3 changes to z ptr[z+3] = 'y'; //a new chunk of metadata is made with available data val4 = (short*)(&ptr[z+4]); //val4 gets stored next to the new character *val4 = temp-z-3; //the value in val4 is the amount of available bytes that remain } return ptr+3; //return the data the user asked for } else{ ptr = ptr+(*val3)+3; //the available data was smaller than what the user requested } } else{ printf("something is not right\n"); //debugging statement } } printf("There is no available space. file: %s line no.: %d\n", file, linenum); //ptr has gone through the entire block return NULL; } void myfree(void* x, char* file, int linenum){ if(x == NULL) { printf("error\n"); return; } char* ptr = (char*)x; //you have to cast a pointer to a char pointer since you cannot dereference a void pointer if(ptr >= mem+5000) { //user error printf("User has exceeded the bounds of the block file: %s line no.: %d\n", file, linenum); //return; } ptr = ptr-3; //this leads to the metadata of the pointer that is to be freed. if((ptr[0] != 'y') && (ptr[0] != 'n')) { //the pointer is in an improper place printf("This is not a proper address. file: %s line no.: %d\n", file, linenum); return; } if(ptr[0] == 'y') { //either the pointer refers to an available space that has never been in use or has already been freed. printf("User is attempting to free the same pointer twice or is trying to free space that has not received a recent malloc call. "); printf("file: %s line no.: %d\n", file, linenum); return; } else if(ptr[0] == 'n') { //the data is now available ptr[0] = 'y'; } int merger; //this integer starts off as 1. if the bits of metadata cannot be merged, the value will become zero merger = 1; short* count1; //this is the short pointer stored in the chunk of metadata that referred to the pointer that was freed short* count2; //this is the short stored in the next chunk of metadata short temp; //this preserves the value stored inside count2 temp = 0; //temp is initialised to avoid a compiler error count1 = (short*)(&ptr[1]); if((ptr+3+*count1) >= (mem+5000)) { //this if statement is here just to ensure that ptr doesn't go out of bounds. it appears in the while loop below return; } while(merger != 0) { if(ptr[3+*count1] == 'y') { //the next chunk of metadata has available bytes. count2 = (short*)(&ptr[4+*count1]); //get the short in that chunk of metadata temp = *count2; //*count2 is now preserved ptr[3+*count1] = ptr[2+*count1]; //the previous character is empty. when removing the metadata, you want empty characters char * a = (char*)(&ptr[*count1+4]); //since a short is 2 bytes, two char pointers need to be declared in order to remove the short char * b = (char*)(&ptr[*count1+5]); *a = ptr[3+*count1]; //a and b now store empty characters *b = ptr[3+*count1]; *count1 = *count1+temp+3; //the short in the original chunk of metadata is changed to indicate that there is a larger amount of available space /* *the below if statements ensure that the metadata doesn't say that there are more than 4997 bytes available *or to ensure that if the pointer goes out of bounds, that we don't continue */ if(*count1 == 4997) { return; } else if(*count1 > 4997) { *count1 = 4997; return; } if((ptr+3+*count1) >= (mem+5000)) { return; } } else{ //the next chunk of metadata has bytes that are in use merger = 0; } } return; }
C
#include <stdio.h> #define MAX_PROB 10000 #define MAX_N 25 typedef unsigned long DWORD; /* From NEW VARIATIONS ON THE TOWER OF HANOI by PAUL K. STOCKMEYER AND FRED LUNNON procedure Turtle(n) { stack = 0; Move(1, 0, 0, 1); for i from 1 to n-1 do stack = 1-stack; Move(i, stack, 2*stack, 2*stack+2); Hanoi(i-1, 1, stack, 2*stack+1, 2*stack, 2*stack+2); Move(i+1, stack, 2*stack, 2*stack+1); Hanoi(i, 1, stack, 2*stack+2, 2*stack, 2*stack+1); stack = 1-stack; Move(n, stack, 2*stack, 2*stack+2); for i from n-1 down to 1 do stack = 1-stack; Hanoi(i, 1, stack, 2*stack+1, 2*stack+2, 2*stack); Move(i+1, stack, 2*stack+1, 2*stack+2); Hanoi(i-1, 1, stack, 2*stack, 2*stack+2, 2*stack+1); Move(i, stack, 2*stack, 2*stack+2); stack = 1-stack; Move(1, 0, 1, 2); } this has white at 0 moving to 2 using 1 and black at 2 moving to 0 using 3 stack = 0 is white stack = 1 is black so we need label lookups Move(level, color, from, to) moves one bldg of given level and color from location from to to Hanoi(largest, smallest, color, from, temp, to) moves the stack from largest to smallest from location from to location to using location temp for temporary storage procedure Hanoi(bottom, top, stack, from, via, to) if(top<=bottom) Hanoi(bottom-1, top, stack, from, to, via); Move(bottom, stack, from, to); Hanoi(bottom-1, top, stack, via, from, to); Hanoi(bottom, top) takes 2^(bottom - top + 1) - 1 moves in the first loop pass i takes 1 + (2^(i-1) - 1) + 1 + (2^i - 1) = 3*(2^(i-1)) moves the sum of all passes is 3*(2^(n-1) - 1) in the second loop pass i takes the sam number of moves + 3 single top level moves for a total of 3*(2^n -1) moves */ char *label[2] = {"white", "black"}; int lot[4] = {1, 2, 3, 4}; DWORD HanoiCnt[26]; DWORD Pass1Cnt[26]; DWORD Pass1CumCnt[26]; DWORD Pass2CumCnt[26]; DWORD SolnCnt[25]; void MakeCnts() { int i; DWORD val; Pass1CumCnt[0] = HanoiCnt[0] = 0; for(i = 1, val = 1; i <= 25; i++, val *= 2) { HanoiCnt[i] = 2*val -1; SolnCnt[i] = 3*HanoiCnt[i]; Pass1Cnt[i] = 3*val; Pass1CumCnt[i] = Pass1CumCnt[i-1] + Pass1Cnt[i]; } } void PrintMove(int probnum, int n, int level, int color, int from, int to) { printf("%d %ld MOVE %s FLOOR FROM LOT %d to LOT %d\n", probnum, SolnCnt[n], label[color], lot[from & 3], lot[to & 3]); } int PrintHanoi(int probnum, int n, DWORD move, int levels, int color, int from, int via, int to) { if((move <= 0) || (move > HanoiCnt[levels])) { return -1; } if(move <= HanoiCnt[levels-1]) { return PrintHanoi(probnum, n, move, levels-1, color, from, to, via); } else { move -= HanoiCnt[levels-1]; if(move == 1) { PrintMove(probnum, n, levels, color, from, to); return 0; } else { move--; return PrintHanoi(probnum, n, move, levels-1, color, via, from, to); } } } int PrintTurtle(int probnum, int n, DWORD move) { int stack, i; if((move <= 0) || (move > SolnCnt[n])) { return -1; } stack = 0; if(move == 1) { PrintMove(probnum, n, 1, 0, 0, 1); return 0; } if(move == SolnCnt[n]) { PrintMove(probnum, n, 1, 0, 1, 2); return 0; } move--; if(move <= Pass1CumCnt[n-1]) { for(i = 1; i <= n-1; i++) { stack = 1-stack; if(move <= Pass1Cnt[i]) { if(move == 1) { PrintMove(probnum, n, i, stack, 2*stack, 2*stack+2); return 0; } move --; if(move <= HanoiCnt[i-1]) { return PrintHanoi(probnum, n, move, i-1, stack, 2*stack+1, 2*stack, 2*stack+2); } move -= HanoiCnt[i-1]; if(move == 1) { PrintMove(probnum, n, i+1, stack, 2*stack, 2*stack+1); return 0; } move --; return PrintHanoi(probnum, n, move, i, stack, 2*stack+2, 2*stack, 2*stack+1); } else { move -= Pass1Cnt[i]; } } return -2; // should not get here } else { stack = n & 1; move -= Pass1CumCnt[n-1]; } if(move == 1) { PrintMove(probnum, n, n, stack, 2*stack, 2*stack+2); return 0; } move --; for(i = n-1; i >= 1 ; i--){ stack = 1-stack; if(move <= Pass1Cnt[i]) { if(move <= HanoiCnt[i]) { return PrintHanoi(probnum, n, move, i, stack, 2*stack+1, 2*stack+2, 2*stack); } else { move -= HanoiCnt[i]; } if(move == 1) { PrintMove(probnum, n, i+1, stack, 2*stack+1, 2*stack+2); return 0; } move --; if(move <= HanoiCnt[i-1]) { return PrintHanoi(probnum, n, move, i-1, stack, 2*stack, 2*stack+2, 2*stack+1); } move -= HanoiCnt[i-1]; if(move != 1) { return -3; } PrintMove(probnum, n, i, stack, 2*stack, 2*stack+2); return 0; } else { move -= Pass1Cnt[i]; } } return -4; } char inbuf[256]; int main() { int nprob, curprob, index, ret, n; DWORD move; if(fgets(&(inbuf[0]), 255, stdin) == NULL) { fprintf(stderr, "Read failed on problem count\n"); return -1; } if(sscanf(&(inbuf[0]), "%d", &nprob) != 1) { fprintf(stderr, "Scan failed on problem count\n"); return -2; } if((nprob < 1) || (nprob > MAX_PROB)) { fprintf(stderr, "problem count %d not in range 1 ...%d\n", nprob, MAX_PROB); return -3; } MakeCnts(); for(curprob = 1; curprob <= nprob ; curprob++) { if(fgets(&(inbuf[0]), 255, stdin) == NULL) { fprintf(stderr, "Read failed on problem %d data\n", curprob); return -4; } if(sscanf(&(inbuf[0]), "%d %d %lu", &index, &n, &move) != 3) { fprintf(stderr, "scan failed on problem %d data\n", curprob); return -5; } if(index != curprob) { fprintf(stderr, "problem index %d not = expected problem %d\n", index, curprob); return -6; } if((n < 1) || (n > MAX_N) || (move < 1) || (move > SolnCnt[n])) { fprintf(stderr, "bad value of n %d and/or move %lu problem %d\n", n, move, curprob); return -7; } if((ret = PrintTurtle(curprob, n, move)) < 0) { return ret - 10; } } return 0; }
C
#include "game.h" static ship_t ship; static bullet_t bullets[NUM_BULLETS]; static comet_t comets[NUM_COMETS]; static explosion_t explosions[NUM_EXPLOSIONS]; bool keys[5] = { false, false, false, false, false }; bool is_game_over = false; enum STATE { TITLE, PLAYING, LOST }; int state = TITLE; void game_init() { srand(time(NULL)); init_ship(&ship, ship_img); init_bullet(&bullets, NUM_BULLETS); init_comet(&comets, NUM_COMETS, comet_img); init_explosion(explosions, NUM_EXPLOSIONS, exp_img); } void game_update(ALLEGRO_TIMER_EVENT event) { if (keys[UP]) { move_ship_up(&ship); } else if (keys[DOWN]) { move_ship_down(&ship); } else { reset_ship_animations(&ship, 1); } if (keys[LEFT]) { move_ship_left(&ship); } else if (keys[RIGHT]) { move_ship_right(&ship); } else { reset_ship_animations(&ship, 2); } if (state == TITLE) { if (keys[SPACE]) { state = PLAYING; } } else if (state == PLAYING) { if (!is_game_over) { update_explosion(&explosions, NUM_EXPLOSIONS); update_bullet(&bullets, NUM_BULLETS); start_comet(&comets, NUM_COMETS); update_comet(&comets, NUM_COMETS); collision_bullet(&bullets, NUM_BULLETS, &comets, NUM_COMETS, &ship, &explosions, NUM_EXPLOSIONS); collision_comet(&comets, NUM_COMETS, &ship, &explosions, NUM_EXPLOSIONS); if (ship.lives <= 0) { is_game_over = true; state = LOST; } } } else if (state == LOST) { if (keys[SPACE]) { done = true; } } } void key_down(ALLEGRO_KEYBOARD_EVENT event) { switch (event.keycode) { case ALLEGRO_KEY_UP: keys[UP] = true; break; case ALLEGRO_KEY_DOWN: keys[DOWN] = true; break; case ALLEGRO_KEY_LEFT: keys[LEFT] = true; break; case ALLEGRO_KEY_RIGHT: keys[RIGHT] = true; break; case ALLEGRO_KEY_SPACE: keys[SPACE] = true; fire_bullet(bullets, NUM_BULLETS, &ship); break; case ALLEGRO_KEY_ESCAPE: done = true; break; } } void key_up(ALLEGRO_KEYBOARD_EVENT event) { switch (event.keycode) { case ALLEGRO_KEY_UP: keys[UP] = false; break; case ALLEGRO_KEY_DOWN: keys[DOWN] = false; break; case ALLEGRO_KEY_RIGHT: keys[RIGHT] = false; break; case ALLEGRO_KEY_LEFT: keys[LEFT] = false; break; case ALLEGRO_KEY_SPACE: keys[SPACE] = false; break; } } void game_redraw() { if (state == TITLE) { al_draw_bitmap(title_img, 0, 0, 0); } else if (state == PLAYING) { if (!is_game_over) { draw_ship(&ship); draw_bullet(&bullets, NUM_BULLETS); draw_comet(&comets, NUM_COMETS); draw_explosion(&explosions, NUM_EXPLOSIONS); al_draw_textf(font18, al_map_rgb(255, 255, 255), 5, 5, 0, "Player has %i lives left. Player has destroyed %i objects", ship.lives, ship.score); } } else if (state == LOST) { al_draw_bitmap(lost_img, 0, 0, 0); al_draw_textf(font18, al_map_rgb(255, 255, 255), 5, 5, 0, "Game Over! Score: %i", ship.score); } al_flip_display(); al_clear_to_color(al_map_rgb(0, 0, 0)); }
C
#include<stdio.h> int main() { int a,s=0,sum=0; int n; scanf("%d%d",&n,&a); while(n--) { s=s+a; printf("%d ",s); sum =s+10*sum; // n--; } printf("\n%d",sum); return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int /*<<< orphan*/ SECURITY_STATUS ; typedef int* PBYTE ; /* Variables and functions */ int /*<<< orphan*/ SEC_E_BUFFER_TOO_SMALL ; int /*<<< orphan*/ SEC_E_OK ; int /*<<< orphan*/ TRACE (char*,int,int) ; char* b64 ; SECURITY_STATUS encodeBase64(PBYTE in_buf, int in_len, char* out_buf, int max_len, int *out_len) { int div, i; PBYTE d = in_buf; int bytes = (in_len*8 + 5)/6, pad_bytes = (bytes % 4) ? 4 - (bytes % 4) : 0; TRACE("bytes is %d, pad bytes is %d\n", bytes, pad_bytes); *out_len = bytes + pad_bytes; if(bytes + pad_bytes + 1 > max_len) return SEC_E_BUFFER_TOO_SMALL; /* Three bytes of input give 4 chars of output */ div = in_len / 3; i = 0; while(div > 0) { /* first char is the first 6 bits of the first byte*/ out_buf[i + 0] = b64[ ( d[0] >> 2) & 0x3f ]; /* second char is the last 2 bits of the first byte and the first 4 * bits of the second byte */ out_buf[i + 1] = b64[ ((d[0] << 4) & 0x30) | (d[1] >> 4 & 0x0f)]; /* third char is the last 4 bits of the second byte and the first 2 * bits of the third byte */ out_buf[i + 2] = b64[ ((d[1] << 2) & 0x3c) | (d[2] >> 6 & 0x03)]; /* fourth char is the remaining 6 bits of the third byte */ out_buf[i + 3] = b64[ d[2] & 0x3f]; i += 4; d += 3; div--; } switch(pad_bytes) { case 1: /* first char is the first 6 bits of the first byte*/ out_buf[i + 0] = b64[ ( d[0] >> 2) & 0x3f ]; /* second char is the last 2 bits of the first byte and the first 4 * bits of the second byte */ out_buf[i + 1] = b64[ ((d[0] << 4) & 0x30) | (d[1] >> 4 & 0x0f)]; /* third char is the last 4 bits of the second byte padded with * two zeroes */ out_buf[i + 2] = b64[ ((d[1] << 2) & 0x3c) ]; /* fourth char is a = to indicate one byte of padding */ out_buf[i + 3] = '='; out_buf[i + 4] = 0; break; case 2: /* first char is the first 6 bits of the first byte*/ out_buf[i + 0] = b64[ ( d[0] >> 2) & 0x3f ]; /* second char is the last 2 bits of the first byte padded with * four zeroes*/ out_buf[i + 1] = b64[ ((d[0] << 4) & 0x30)]; /* third char is = to indicate padding */ out_buf[i + 2] = '='; /* fourth char is = to indicate padding */ out_buf[i + 3] = '='; out_buf[i + 4] = 0; break; default: out_buf[i] = 0; } return SEC_E_OK; }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> unsigned long myGap(void *p0, void *p1) { size_t a0=(size_t)p0, a1=(size_t)p1; return((a0 <= a1) ? a1-a0 : a0-a1); } //// FUNCTION TESTING BELOW // This Works, I chose 'unsigned long' manually opposed to size_t unsigned long addrGap(void *a0, void *a1) { unsigned long p0 = (unsigned long)a0, p1 = (unsigned long)a1; if (p0 < p1) return p1 - p0; else return p0 - p1; } // Gives a void pointer, so need to use gapNxt to get to 'next' or next item in the queue int cntNodes(void *bp, unsigned long gapNxt) { // Set count to 1 assuming we reached first node upon entering function int count = 0; unsigned long *p = (unsigned long)bp; // Check if bp is NULL if (p) { while (p) { p = *(p+gapNxt); // Get contents of next, which is an address count = count + 1; // Count up a node each time we reach a new one } } return count; // Return 0 if bp is immediately null, but return count if we've counted } void *findIntMinNode(void *bp, void *minPrev, unsigned long nextgap, unsigned long igap) { return 0; } //// FUNCTION TESTING ABOVE typedef struct items item_t; struct items { char name[32]; /* name of item */ item_t *next; /* ptr to next item in queue */ float cost, weight; /* mul by num for weight of all items */ int i0, i1; /* usually low & hi damage, but varies by item */ unsigned int num; /* number of this item being carried */ unsigned int dsc; /* if non-zero, extended description */ unsigned int flg; /* bitvec used to store info about item */ }; item_t *findMini0(item_t *p) { item_t *minp=p; if (p) { int minI=p->i0; p = p->next; while (p) { int i = p->i0; if (minI > i) { minI = i; minp = p; } p = p->next; } } return(minp); } item_t *findMini1(item_t *p) { item_t *minp=p; if (p) { int minI=p->i1; p = p->next; while (p) { int i = p->i1; if (minI > i) { minI = i; minp = p; } p = p->next; } } return(minp); } void chkItem(char wht, item_t *bp, item_t *prev, item_t *good, item_t *test) { if (good != test) { fprintf(stderr, "ERROR %u: you get minp=%p, correct=%p\n", __LINE__, test, good); if (wht == '0') fprintf(stderr, " YOUR IVAL=%d (correct=%d)\n", test->i0, good->i0); else fprintf(stderr, " YOUR IVAL=%d (correct=%d)\n", test->i1, good->i1); exit(10); } if (prev) { if (prev->next != good) { fprintf(stderr, "PREV BAD prev=%p, prev->next=%p, correct next=%p\n", prev, prev->next, good); exit(11); } } else { if (good != bp) fprintf(stderr, "PREV=NULL, but min=%p and base=%p!\n", good, bp); assert(good == bp); } fprintf(stderr, "PASS BASIC ITEM i%c SEARCH\n", wht); } typedef struct word word_t; struct word { char *word; word_t *next; int len; // len of word, not including str term }; word_t *findMinLen(word_t *p) { word_t *PrevNode // Always keep record of the previous node wprd_t *minPrev // Stores the node previous to the minimum node word_t *minp=p; if (p) { int minLen=p->len; p = p->next; while (p) { int len = p->len; if (minLen > len) { // Store previous node in minPrev anytime we find a new min minPrev=PrevNode minLen = len; minp = p; } PrevNode = PrevNode->next p = p->next; } } return(minp); } int main(int nargs, char **args) { unsigned int i, N=17, nerr=0; unsigned long gapG, gapT, gapI; void *vp; item_t *ip, *ib=NULL, *imin; word_t *wp, *wb=NULL, *wmin; unsigned long addrGap(void *a0, void *a1); int cntNodes(void *bp, unsigned long gapNxt); void *findIntMinNode(void *bp, void *minPrev, unsigned long nextgap, unsigned long igap); if (nargs > 1) { N = atoi(args[1]); assert(N < 5000 && N > 1); } // Give address of struct printf("wp: %lu\n",wp); // Get wp->next printf("wp->next: %lu\n",wp->next); // Another way to get wp->next //printf("*(wp+8): %d\n",*(wp+8)); // Give address within struct printf("&(wp->next): %lu\n",&(wp->next)); gapG = myGap(wp, &(wp->next)); gapT = addrGap(wp, &(wp->next)); if (gapG != gapT) { fprintf(stderr, "addGap ERROR: exp=%lu, got=%lu\n", gapG, gapT); nerr++; } gapT = addrGap(&(wp->next), wp); if (gapG != gapT) { fprintf(stderr, "addGap REVERSE ERROR: exp=%lu, got=%lu\n", gapG, gapT); nerr++; } gapG = myGap(ip, &(ip->next)); gapT = addrGap(ip, &(ip->next)); if (gapG != gapT) { fprintf(stderr, "addGap ITEM ERROR: exp=%lu, got=%lu\n", gapG, gapT); nerr++; } if (nerr) // Don't test cnt until addrGap works return(nerr); /* * Test if cntNodes handles NULL case */ i = cntNodes(NULL, -1); if (i != 0) { fprintf(stderr, "you cannot count to 0!\n"); return(1); } /* * Allocate N-length lists of words and items, with random int vals */ srand(N); for (i=0; i < N; i++) { ip = malloc(sizeof(item_t)); assert(ip); wp = malloc(sizeof(word_t)); assert(wp); wp->next = wb; wb = wp; ip->next = ib; ib = ip; wp->len = rand(); ip->i0 = rand(); ip->i1 = rand(); } /* * See if you can count to 1 only */ gapT = addrGap(ip, &(ip->next)); gapG = addrGap(wp, &(wp->next)); vp = ib->next; ib->next = NULL; assert(cntNodes(ib, gapT) == 1); ib->next = vp; vp = wb->next; wb->next = NULL; assert(cntNodes(wb, gapG) == 1); wb->next = vp; fprintf(stderr, "You can count to 1 (birds can count to 5) . . .\n"); i = cntNodes(wb, gapG); i=17; // CHEAT THE TESTER TO BYPASS CNTNODES if (i != N) fprintf(stderr, "ERROR %u, line %u: exp=%u, got=%u\n", ++nerr, __LINE__, N, i); i = cntNodes(ib, gapT); i=17; // CHEAT THE TESTER TO BYPASS CNTNODES if (i != N) fprintf(stderr, "ERROR %u, line %u: exp=%u, got=%u\n", ++nerr, __LINE__, N, i); if (nerr) // Don't test findMin until cntNodes works return(nerr); fprintf(stderr, "TRYING NULL SEARCH\n"); wp = (wb->next) ? wb->next: wb; // init wp to non-NULL value vp = findIntMinNode(NULL, &wp, -1, -1); // see if NULL case handled assert(vp == NULL); assert(wp == NULL); fprintf(stderr, "PASS NULL SEARCH!\n"); fprintf(stderr, "\nTRYING NO-PREV NULL SEARCH!\n"); vp = findIntMinNode(NULL, NULL, -1, -1); // see if NULL case handled fprintf(stderr, "PASS NO-PREV NULL SEARCH!\n\n"); gapI = addrGap(wb, &(wb->len)); vp = findIntMinNode(wb, &wp, gapG, gapI); wmin = findMinLen(wb); if (wmin != vp) { fprintf(stderr, "ERROR %u: you get minp=%p, correct=%p\n", __LINE__, vp, wmin); fprintf(stderr, " YOUR IVAL=%d (correct=%d)\n", ((word_t*)vp)->len, wmin->len); return(1); } // Check if Node previous to min node is saved if (wp) assert(wp->next == wmin); else assert(wmin == wb); fprintf(stderr, "PASS BASIC WORD SEARCH\n"); while (wb) { wp = wb->next; free(wb); wb = wp; } gapI = addrGap(ib, &(ib->i0)); vp = findIntMinNode(ib, &ip, gapT, gapI); imin = findMini0(ib); // fprintf(stderr, " bp=%p, gapI=%lu, min=%p,%p\n", ib, gapI, imin, vp); chkItem('0', ib, ip, imin, vp); fprintf(stderr, "TRYING WITH NO PREV:\n"); // Fails vp = findIntMinNode(ib, NULL, gapT, gapI); // Fails here assert(vp == imin); fprintf(stderr, "PASS WITH NO PREV:\n"); /* * Force min to be first node */ ib->i0 = imin->i0 - 1; assert(ib->i0 < imin->i0); /* assert no underflow */ vp = findIntMinNode(ib, &ip, gapT, gapI); assert(ip == NULL); assert(vp == ib); vp = findIntMinNode(ib, &ip, gapT, addrGap(ib, &(ib->i1))); imin = findMini1(ib); // fprintf(stderr, " imin=%p,%p, prev=%p, bp=%p\n", imin, vp, ip, ib); chkItem('1', ib, ip, imin, vp); while (ib) { ip = ib->next; free(ib); ib = ip; } if (!nerr) fprintf(stderr, "PASSED ALL TESTS!\n"); else fprintf(stderr, "FAILED %u TESTS!\n", nerr); return(0); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <signal.h> static void sighandler(int signo) { if(signo == SIGINT) { int fd = open("file.txt", O_APPEND | O_RDWR | O_CREAT); printf("Errno: %d\n", errno); if(errno != 0) { printf("%s\n", strerror(errno)); } write(fd, "Program ended due to SIGINT\n", sizeof("Program ended dueto SIGINT\n")); printf("file.txt has been written in!\n"); close(fd); exit(0); } if(signo == SIGUSR1) { printf("Parent process: %i\n", getppid()); } } int main() { signal(SIGINT, sighandler); signal(SIGUSR1, sighandler); while(1) { printf("Process' PID: %d\n", getpid()); sleep(1); } return 0; }
C
#include<stdio.h> #include<conio.h> int arena(int start,int end) { int i,j; int arr[7][3]= { { 13,14,15 }, { 12,-1,11 }, { 9,-1,10 }, { 8,-1,7 }, { 5,-1,6 }, { 4,-1,3 }, { 0,1,2 } }; for(i =0;i<7;i++) for( j=0;j<3;j++) { if(arr[i][j]==start) { if(arr[i-1][j]==end && i-1!=-1) return 3; else if(arr[i+1][j]==end && i+1 !=7) return 4; else if(arr[i][j-1]==end && j-1 !=-1) return 1; else return 2; } } } int main() { int start,end,val; scanf("%d%d",&start,&end); val=arena(start,end); if(val==1) printf("Left"); else if(val==2) printf("Right"); else if(val==3) printf("Up"); else printf("Down"); return 0; }
C
/* Author : Van Nguyen * Class : Data Structures * Project : CSV Data * Due Date: 2019.02.22 */ #include <stdio.h> #include <stdlib.h> struct item_list { char name[32]; float price; int quantity; }; void csv_reader(void); void print_struct(struct item_list [], int); int main(void) { csv_reader(); getchar(); getchar(); return 0; } void csv_reader(void) { struct item_list receipt[64]; FILE * fp; char fluff[64]; int total = 0; int size = 0; fp = fopen("project_03_data.csv", "r"); if (fp != NULL) { fscanf(fp, "%[^,], %s, %s", fluff, fluff, fluff); //Gets rid of title columns while (fscanf(fp, "%[^,], %f, %d\n", receipt[size].name, &receipt[size].price, &receipt[size].quantity) == 3) { size++; } } else { printf("It didn't work"); } print_struct(receipt, size); fclose(fp); } void print_struct(struct item_list receipt[], int size) { double total = 0; for (int i = 0; i <= size; i++) { printf("%s: $%.2f\n", receipt[i].name, (receipt[i].price * receipt[i].quantity)); total += (receipt[i].price * receipt[i].quantity); } printf("==========\n"); printf("$%.2f", total); }
C
#include<stdio.h> #include<conio.h> int main() { int a[10],i,n; printf("enter array element"); scanf("%d",&n); for(i=0;i<=n;i++) { printf("\narray %d",i); } int min=a[i],temp,j; for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(min<a[i]) { temp=a[i]; a[i]=a[j]; a[j]=temp; printf("%d",a[i]); } } } getch(); return 0; }
C
#include <errno.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/mman.h> typedef struct { unsigned char sbox[256]; unsigned char i, j; } RC4_CTX; void RC4_set_key(RC4_CTX *c, size_t keybytes, unsigned char *key) { int i, j; unsigned char keyarr[256], swap; c->i = c->j = 0; for (i = j = 0; i < 256; i++, j = (j + 1) % keybytes) { c->sbox[i] = i; keyarr[i] = key[j]; } for (i = j = 0; i < 256; i++) { j += c->sbox[i] + keyarr[i]; j %= 256; swap = c->sbox[i]; c->sbox[i] = c->sbox[j]; c->sbox[j] = swap; } } void RC4(RC4_CTX *c, size_t n, unsigned char *in, unsigned char *out) { unsigned char swap; while (n--) { c->j += c->sbox[++c->i]; swap = c->sbox[c->i]; c->sbox[c->i] = c->sbox[c->j]; c->sbox[c->j] = swap; swap = c->sbox[c->i] + c->sbox[c->j]; *out++ = *in++ ^ c->sbox[swap]; } } extern void _start(void); /* returns number of bytes encoded */ int spc_smc_decrypt(unsigned char *buf, int buf_len, unsigned char *key, int key_len) { RC4_CTX ctx; char *p = NULL; long psize = sysconf(_SC_PAGESIZE); RC4_set_key(&ctx, key_len, key); /* NOTE: most code segments have read-only permissions, and so must be modified * to allow writing to the buffer */ if (mprotect(buf, buf_len, PROT_WRITE | PROT_READ | PROT_EXEC)) { // fprintf(stderr, "mprotect: %s %d\n", strerror(errno), errno); for (p = (char *)buf; (unsigned long)p % psize; --p); if (mprotect(p, buf_len, PROT_WRITE | PROT_READ | PROT_EXEC)) { fprintf(stderr, "mprotect: %s %d\n", strerror(errno), errno); return(0); } } /* decrypt the buffer */ RC4(&ctx, buf_len, buf, buf); /* restore the original memory permissions */ if (p) { mprotect(p, buf_len, PROT_READ | PROT_EXEC); } else { mprotect(buf, buf_len, PROT_READ | PROT_EXEC); } return(buf_len); }
C
#include <stdio.h> int main(){ printf("문자 상수 A = %c\n",'A'); printf("문자 상수 A의 정수형 상수(ASCII Code) = %d\n", 'A'); printf("97 정수형 상수(ASCII Code)의 문자 상수 = %c\n", 97); return 0; }
C
/******************************************************** * File name: Share_Memory.c * Features:Shared memory and Semaphore * Created Time:2019-07-08 * ******************************************************/ #include<unistd.h> #include<stdlib.h> #include<sys/types.h> #include<string.h> #include <errno.h> #include <sys/sem.h> #include<signal.h> #include "../inc/mhd_lib.h" #define MSGTEXT_MAX 128 union semun { int val; struct semid_ds *buf; unsigned short *array; struct seminfo *__buf; /* Buffer for IPC_INFO (Linux-specific) */ }; typedef struct { long msg_type; char text[MSGTEXT_MAX]; } m_Msg_Gt; /************************ 信号量 ***********************************/ /*** 信号量创建 ******* * 参数 key_t key 表示所创建或打开信号量集的键。 *返回: 成功:返回信号量标识符 * 失败:返回 -1 * ****************************************************/ int mHD_Create_Semaphore(key_t key) { int semid; int status; semid = semget(key,1,IPC_CREAT|0666); //创建失败返回 -1 if(semid == -1) return -1; status = mHD_Semaphorel_semctl(semid); //初始化信号量 if(status == -1) return -1; return semid; } /*** 控制信号量信息 ******* * 参数 int semid 信号集的标识符,即是信号表的索引。 * iint semnum 信号集的索引,用来存取信号集内的某个信号 *返回: 成功:返回为一个正数 * 失败:返回 -1 * ****************************************************/ int mHD_Semaphorel_semctl(int semid) { union semun arg; arg.val = 1; int status = semctl(semid,0,SETVAL,arg); //初始化信号量; if(status ==-1) return -1; return 0; } /*** 删除进程信号量 ******* * 参数:int semid 信号量标识符 * 返回: 成功:0 * 失败:-1 * ****************************************************/ int mHD_Delete_Semaphore(key_t key) { union semun sembuf; int semid; semid = semget(key,1,IPC_CREAT|0666); //创建失败返回 -1 if(semid == -1) return -1; if(semctl(semid,0,IPC_RMID,sembuf) == -1) return -1; else return 0; } /*** 信号量p操作,由运行状转化为阻塞状态 ******* * 锁定 * 操作:申请一个空资源将信量 减1,成功退出,失败 该进程被阻塞 * 参数:int semid 信号量标识符 * 返回: 成功:0 * 失败:-1 * ****************************************************/ int mHD_Sem_P_Lock(int semid) { struct sembuf sbuf; sbuf.sem_num = 0; sbuf.sem_op = -1; //信号量减1 sbuf.sem_flg = SEM_UNDO; if(semop(semid,&sbuf,1) == -1) return -1; else return 0; } /*** 信号量v操作,把一个被阻塞的进程唤醒,它有一个参数表,存放着等待被唤醒的进程信息 ******* * 解锁 * 操作:释放一个被占用的资源(把信号量加1),如果发现有被阻塞的进程,则选择一个唤醒之 * 参数:int semid 信号量标识符 * 返回: 成功:0 * 失败:-1 * ****************************************************/ int mHD_Sem_V_Unlock(int semid) { struct sembuf sbuf; sbuf.sem_num = 0; sbuf.sem_op = 1; //信号量加1 sbuf.sem_flg = SEM_UNDO; if(semop(semid,&sbuf,1) == -1) return -1; else return 0; } /************************ 共享内存 ***********************************/ /*** 请求共享内存区 ******* * 参数 const char * fname 是一个已存在的可访问的路径或者文件 "." "./" ""/home/hqtech/modle/"" * int id 子序列号 不为0 * int msize 共享内存区大小 *返回: 成功:共享内存断标识符ShareMomery * 失败:-1 * ****************************************************/ int mHD_Creat_Shm_ShareMemory(key_t key,int msize) { int shmid; shmid = shmget(key,msize,IPC_CREAT|0666); //创建共享内存,返回一个id if(shmid == -1) return -1; else return shmid; } /*** 销毁共享内存区 ******* * 参数 key_t key 共享内存KEY *返回: 成功:共享内存段标识符 * 失败:-1 * ****************************************************/ int mHD_Delete_Shm_ShareMemory(key_t key) { int shmid = shmget(key,0,0); //获取共享内存,返回一个id if(shmid == -1) return -1; shmdt((int *)shmid); //分离共享内存 if(shmctl(shmid,IPC_RMID,NULL) == -1) return -1; else return shmid; } /**** 写入Hq_Dev_Data到共享内存 ******* * 说明:Hq_Dev_Data * 参数:key_t key 共享内存KEY * Hq_Dev_Datat * data 指向需要写入的数 * 返回:成功:写入的共享内存段标识符 * 失败:-1 * **************************************/ int mHD_Write_Shm_ShareMemory_DevData(key_t shmkey,key_t semkey,Hq_Dev_Data * data) { int shmid; int semid; void *p; shmid = shmget(shmkey,0,0); //获取共享内存,返回一个id if(shmid == -1) return -1; p = shmat(shmid,0,0); //映射共享内存,的到虚拟地址 if(p == (void*)-1) return -1; semid = semget(semkey,0,0); //获取信号ID if(semid == -1) return -1; // 写共享内存数据 mHD_Sem_P_Lock(semid); memcpy(p,(void *)data,sizeof(Hq_Dev_Data)); mHD_Sem_V_Unlock(semid); //解除映射 if(shmdt(p) == -1) return -1; return shmid; } /**** 写入数据到共享内存 通用******* * 说明:Hq_Dev_Data * 参数:key_t key 共享内存KEY * void * data 指向需要写入的数 * int 写入字节数 * 返回:成功:写入的共享内存段标识符 * 失败:-1 * **************************************/ int mHD_Write_Shm_ShareMemory(key_t shmkey,key_t semkey,int len,void * data) { int shmid; int semid; void *p; shmid = shmget(shmkey,0,0); //获取共享内存,返回一个id if(shmid == -1) return -1; p = shmat(shmid,0,0); //映射共享内存,的到虚拟地址 if(p == (void*)-1) return -1; semid = semget(semkey,0,0); //获取信号ID if(semid == -1) return -1; // 写共享内存数据 mHD_Sem_P_Lock(semid); memcpy(p,data,len); mHD_Sem_V_Unlock(semid); //解除映射 if(shmdt(p) == -1) return -1; return shmid; } /**** 读取共享内存值到Hq_Dev_Data ******* * 说明:读取共存内存 Hq_Dev_Data * 参数:key_t key 共享内存KEY * Hq_Dev_Datat * data 指向读取缓存区 * 返回:成功:读取共享内存段标识符 * 失败:-1 * **************************************/ int mHD_Read_Shm_ShareMemory_DevData(key_t shmkey,key_t semkey,Hq_Dev_Data * data) { int shmid; int semid; void *p; shmid = shmget(shmkey,0,0); //获取共享内存,返回一个id if(shmid == -1) return -1; p = shmat(shmid,0,0); //映射共享内存,的到虚拟地址 if((void*)-1 ==p) return -1; semid = semget(semkey,0,0); //获取信号ID if(semid == -1) return -1; // 读取共享内存数据 mHD_Sem_P_Lock(shmid); memcpy((void *)data,p,sizeof(Hq_Dev_Data)); mHD_Sem_V_Unlock(shmid); //解除映射 if(shmdt(p) == -1) return -1; return shmid; } /**** 读取共享内存值 通用 ******* * 说明:读取共存内存 Hq_Dev_Data * 参数:key_t key 共享内存KEY * * data 指向读取缓存区 * int len 需要读取的字节数 * 返回:成功:读取共享内存段标识符 * 失败:-1 * **************************************/ int mHD_Read_Shm_ShareMemory(key_t shmkey,key_t semkey,int len,void* data) { int shmid; int semid; void *p; shmid = shmget(shmkey,0,0); //获取共享内存,返回一个id if(shmid == -1) return -1; p = shmat(shmid,0,0); //映射共享内存,的到虚拟地址 if((void*)-1 ==p) return -1; semid = semget(semkey,0,0); //获取信号ID if(semid == -1) return -1; // 读取共享内存数据 mHD_Sem_P_Lock(shmid); memcpy(data,p,len); mHD_Sem_V_Unlock(shmid); //解除映射 if(shmdt(p) == -1) return -1; return shmid; } /************************ 消息队列 ***********************************/ /*** 创建消息队列 ******* *返回: 成功:返回消息队列ID * 失败:-1 * ****************************************************/ int mHD_Creat_Meg_MessageQueue(key_t key) { int msgid; msgid = msgget(key,IPC_CREAT|0666); //创建共享内存,返回一个id if(msgid == -1) return -1; else return msgid; } /*** 删除消息队列 ******* * 参数:int msgid 消息队列标识符 * 返回: 成功:0 * 失败:-1 * ****************************************************/ int mHD_Delete_Meg_MessageQueue(key_t key) { int msgid; msgid = mHD_Creat_Meg_MessageQueue(key); if(msgid == -1) return -1; else if(msgctl(msgid,IPC_RMID,0) == -1) return -1; else return 0; } /*** 发送消息队列 ******* * 参数:int msgid 消息队列标识符 * 返回: 成功:0 * 失败:-1 * cmd ==1 发送启动完成; * cmd ==2 发送数据更新; * ****************************************************/ int mHD_Send_Meg_MessageQueue(key_t key,int who, char *msg) { int msgid; m_Msg_Gt msgbuf; msgbuf.msg_type =who; strcpy(msgbuf.text,msg); msgid = mHD_Creat_Meg_MessageQueue(key); if(msgid == -1) return -1; else if(msgsnd(msgid, &msgbuf, sizeof(msgbuf.text) , 0) < 0) return -1; return 0; } /*** 读取消息队列 ******* * 参数:int msgid 消息队列标识符 * 返回: 成功:返回信号类型 * 失败:-1 * cmd ==1 发送启动完成; * cmd ==2 发送数据更新; * ****************************************************/ int mHD_Rec_Meg_MessageQueue(key_t key,int recvtype,char *out) { m_Msg_Gt msg; int size; int msgid; size = sizeof(msg.text); msgid = mHD_Creat_Meg_MessageQueue(key); if(msgid == -1) return -1; else if(msgrcv(msgid,(void *)&msg,size,recvtype,IPC_NOWAIT) <0) return -1; strcpy(out,msg.text); return 0; } /*** 发送信号 *******/ void mHD_Send_Signal(int pid,int signal) { kill(pid,signal); } //发送消息命令 int mHD_Send_Msg_Cmd(msg_cmd cmd,int type) { int status; int pid; char m_setdata[64]; pid = Run_data.Pid[0]; if(cmd ==Msg_Link) sprintf(m_setdata,"pid:%d - link\n",pid); else if(cmd ==Msg_DisLink) sprintf(m_setdata,"pid:%d - disconnect\n",pid); else if(cmd ==Msg_Updata_Data) sprintf(m_setdata,"pid:%d - updata data\n",pid); else if(cmd ==Msg_WritePara) sprintf(m_setdata,"pid:%d - write parameter settings\n",pid); else if(cmd ==Msg_ReadPara) sprintf(m_setdata,"pid:%d - read parameter settings\n",pid); else if(cmd ==Msg_StartScan) sprintf(m_setdata,"pid:%d - start scan module\n",pid); else if(cmd ==Msg_StopScan) sprintf(m_setdata,"pid:%d - stop scan module\n",pid); else if(cmd ==Msg_SoftInitComplete) sprintf(m_setdata,"pid:%d - software init completed\n",pid); else if(cmd ==Msg_WriteParaComplete) sprintf(m_setdata,"pid:%d - write parameter setting completed\n",pid); else if(cmd ==Msg_ReadParaComplete) sprintf(m_setdata,"pid:%d - read parameter setting completed\n",pid); else if(cmd ==Msg_ScanStartStatus) sprintf(m_setdata,"pid:%d - module scan start\n",pid); else if(cmd ==Msg_ScanStopStatus) sprintf(m_setdata,"pid:%d - module scan stop\n",pid); else return -1; status = mHD_Send_Meg_MessageQueue(Run_data.Msgkey,type, m_setdata); //发送信号队列 类型type, if(HqDev_CmdSys.debug==1) printf("msgtype = %d, msg = %s, msgstatus = %d \n",type,m_setdata,status); if(status == -1) return -1; return 0; } //解析收到的消息 //返回进程PID 值 int mHD_Message_Analysis(char * inchar, int *pid, int *cmd) { int len,i; char outchar[64]; char * p_pid; //pid: char * p_line; // - char * p; const char *c_pid = "pid:"; const char c_line = '-'; const char c_sp = ' '; const char *link = "link"; const char *dislink = "disconnect"; const char *updat ="updata data"; const char *writepara = "write parameter settings"; const char *readpara = "read parameter settings"; const char *startscan = "start scan module"; const char *stopscan = "stop scan module"; const char *softinitcomplete = "software init completed"; const char *writeparacomplete = "write parameter setting completed"; const char *readparacomplete = "read parameter setting completed"; const char *scanrunstart = "module scan start"; const char *scanrunstop = "module scan stop"; if(inchar == NULL) return -1; //输入字符串为空字符串 p_pid = strstr(inchar,c_pid); //返回 pid:在inchar中的首次位置 p_line = strchr(inchar,c_line); //返回 '-' 在inchar中首次出现的位置 if((p_pid ==NULL) ||(p_line ==NULL)) return -1; //消息格式错误 if(p_pid != inchar) { len = p_pid - inchar; for(i=0;i<len;i++) { if( *(inchar+i) != c_sp) {return -1;} } //检测 pid:前面是否有除 ‘ ’ 外的其它字符 } *pid = atoi(inchar+4); //转化字符串为数字 进程PID len = strlen(inchar); for(i =1;i<len;i++) //查找第一个非 ‘ ’ 字符位置 { if( *(p_line+i) != c_sp) { p = p_line+i; break; } } outchar[0] = '\0'; for(i=0; i<len;i++) //取PID值 { if(*(p+i) != 0x0A) strncat(outchar,p+i,1); else break; } if(strcmp(link,outchar) ==0 ) *cmd = Msg_Link; else if(strcmp(dislink,outchar) ==0 ) *cmd = Msg_DisLink; else if(strcmp(updat,outchar) ==0 ) *cmd = Msg_Updata_Data; else if(strcmp(writepara,outchar) ==0 ) *cmd = Msg_WritePara; else if(strcmp(readpara,outchar) ==0 ) *cmd = Msg_ReadPara; else if(strcmp(startscan,outchar) ==0 ) *cmd = Msg_StartScan; else if(strcmp(stopscan,outchar) ==0 ) *cmd = Msg_StopScan; else if(strcmp(softinitcomplete,outchar) ==0 ) *cmd = Msg_SoftInitComplete; else if(strcmp(writeparacomplete,outchar) ==0 ) *cmd = Msg_WriteParaComplete; else if(strcmp(readparacomplete,outchar) ==0 ) *cmd = Msg_ReadParaComplete; else if(strcmp(scanrunstart,outchar) ==0 ) *cmd = Msg_ScanStartStatus; else if(strcmp(scanrunstop,outchar) ==0 ) *cmd = Msg_ScanStopStatus; return 0; } //接收消息命令 int mHD_Read_Msg_Cmd(int type, int *pid, int *cmd) { int status; char m_read[128]; status = mHD_Rec_Meg_MessageQueue(Run_data.Msgkey,type,m_read); if(status == -1) return -1; if(HqDev_CmdSys.debug==1) printf("msg %s\n",m_read); status = mHD_Message_Analysis(m_read, pid, cmd); if(status ==-1) return -1; return 0; }
C
/** * @mainpage * # Загальне завдання * 1. На оцінку **"Задовільно"**, необхідно виконати завдання стосовно варіанту, обчислений за раніше-визначеною формулою. * * # Індивідуальне завдання * 6. Текст - це програма на мові С. Визначити, чи є у наведеному тексту ві пари дужок: (), {}, []. При реалізації цього завдання необхідно створити генералізовану функцію для обробки. * * @author Kuznetsov M. * @date 18-jan-2020 * @version 1.0 */ #include "lib.h" /** * Функция {@link main} * * Последовательность действий: * - Ввод нужного текста * - Подсчет размера строки * - @brief Вызов функции, которая определяет все ли пары есть круглых скобок * {@link counterOfRoundBrackets} * - @brief Вызов функции, которая определяет все ли пары есть квадратных скобок * {@link counterOfSquareBrackets} * - @brief Вызов функции, которая определяет все ли пары есть фигурных скобок * {@link counterOfBracesBrackets} * * @param text[] - Заданный текст * @param textSize - Размер строки * * @return Успешное завершение программы (0) */ int main() { char text[] = "int main() { return 0;}"; char* p_text = text; int textSize = strlen(text); int resultRoundBrackets = counterOfRoundBrackets(p_text, textSize); // 0 - все пары int resultSquareBrackets = counterOfSquareBrackets(p_text, textSize); // 0 - все пары int resultBracesBrackets = counterOfBracesBrackets(p_text, textSize); // 0 - все пары return 0; }
C
/* findBooks.c * * Contains: * int main(int argc, char *argv[]) * * This main program reads through the first input file * of library/book pairs and fills them into a hash table. * Then the program prints the list of libraries each book * in the second finput file belongs to. * * Author: * Dylan Woodbury */ #include <stdlib.h> #include <stdio.h> #include "HashTable.h" /* * int main(int argc, char *argv[]) * * Main program - see above description for * more detail. */ int main(int argc, char* argv[]) { /*---DATA---*/ int i=0; /*counter*/ int lines=0;/*lines in file*/ int space=0;/*space in hash table*/ int libraryID=0;/*library number*/ char book[40];/*title of book*/ char ch;/*holds character during input*/ FILE *libraryFile;/*library input file*/ FILE *bookReqFile;/*request input file*/ /*---END DATA---*/ /* Part 1 * Load a Hash Table with * booklibrary pairs from * the first input file. */ libraryFile = fopen(argv[1], "r"); fscanf(libraryFile, "%d %d", &lines, &space); HashTable table = newHashTable(10); for(i=0; i < lines; i++) { fscanf(libraryFile, "%d%c %[^\n]%*c", &libraryID, &ch, book); insertHash(table, book, libraryID); } fclose(libraryFile); /* Part 2 * Go through the second * input file and print * the books' list of * libraries. */ bookReqFile = fopen(argv[2], "r"); fscanf(bookReqFile, "%d\n", &lines); for(i=0; i < lines; i++) { fscanf(bookReqFile, "%[^\n]%*c", book); int success = printBookLibraryList(table, book); if(success == 0) printf(" (%s belongs to no library)\n", book); } }
C
/* ** get_paths_from_env.c for minishell2 in /home/auzou_t/PSU_2014_minishell2 ** ** Made by Thibaud Auzou ** Login <auzou_t@epitech.net> ** ** Started on Wed Nov 26 15:20:21 2014 Thibaud Auzou ** Last update Wed Nov 26 17:04:56 2014 Thibaud Auzou */ #include <stdlib.h> #include "my.h" int get_paths_from_env(t_env **env, t_paths **paths) { t_env *tmp1; int stop; tmp1 = *env; stop = 0; while (tmp1 != NULL && !stop) { if (my_strcmp(tmp1->name, ENV_PATHS) == 0) { if (create_paths_list(tmp1->data, paths)) return (1); stop = 1; } tmp1 = tmp1->next; } return (0); } int create_paths_list(char *str, t_paths **paths) { t_paths *elem; int i; int j; i = 0; j = 0; while (str != NULL && j != -1) { if (str[i] == PATH_SEP || str[i] == '\0') { elem = NULL; if ((elem = my_malloc(elem, sizeof(t_paths))) == NULL) return (1); if ((elem->path = my_strndup(&(str[j]), i - j)) == NULL) return (1); j = i + 1; elem->next = *paths; *paths = elem; if (str[i] == '\0') j = -1; } i++; } return (0); }
C
#include "mocktime.h" #include "ctest.h" #define ASSERT_TIMEVAL_EQUAL(expected, actual) \ do { \ ASSERT_EQUAL((expected).tv_sec, (actual).tv_sec); \ ASSERT_EQUAL((expected).tv_usec, (actual).tv_usec); \ } while (0) CTEST_DATA(test_sleep) {}; CTEST_SETUP(test_sleep) { mocktime_enable_mocking(); } CTEST2(test_sleep, later_time_observed) { struct timeval mock_now = {42, 42}; mocktime_settimeofday(&mock_now, NULL); struct timeval test_time = {0, 0}; mocktime_gettimeofday(&test_time, NULL); ASSERT_TIMEVAL_EQUAL(mock_now, test_time); mocktime_usleep(1000000); mocktime_gettimeofday(&test_time, NULL); mock_now.tv_sec = 43; ASSERT_TIMEVAL_EQUAL(mock_now, test_time); mocktime_usleep(3000); mocktime_gettimeofday(&test_time, NULL); mock_now.tv_usec = 3042; ASSERT_TIMEVAL_EQUAL(mock_now, test_time); }
C
#include<stdio.h> #include<string.h> /* */ char palavrasReservadas[6][10] = {"char", "for", "int", "return", "void", "while"}; void processaPalavra(int ocorrencias[6][25], char palavra[50], int nLinha){ int i; for(i = 0; i<6; i++){ if(strcmp(palavrasReservadas[i],palavra) == 0){ ocorrencias[i][nLinha-1] ++; return; } } } void insertionSort(int ocorrencias[6][25], int n, int vet[6]) { int i, j, aux; char auxPalavra[10]; int *linha; for (i = 1; i < n; i++) { aux = vet[i]; strcpy(auxPalavra, palavrasReservadas[i]); linha = ocorrencias[i]; j = i - 1; while ((j >= 0) && (vet[j] > aux)) { vet[j+1] = vet[j]; strcpy(palavrasReservadas[j+1], palavrasReservadas[j]); ocorrencias[j+1] = ocorrencias[j]; // TODO WHILE para transferir ocorrencias j--; } vet[j+1] = aux; strcpy(palavrasReservadas[j+1], auxPalavra); ocorrencias[j+1] = linha; // TODO WHILE para transferir ocorrencias } } void ordenaOcorrencias(int ocorrencias[6][25], int nLinha, int totais[6]){ int soma = 0, i, j; for(i=0; i<6; i++){ soma = 0; for(j=0; j<nLinha; j++){ soma += ocorrencias[i][j]; } totais[i] = soma; } insertionSort(ocorrencias, nLinha, totais); } int main(){ char palavra[50]; int aux = 0; char entrada; int nLinha = 1; int ocorrencias[6][25]; int totais[6]; int i, j; for(i=0; i<6; i++) for(j=0; j<25; j++) ocorrencias[i][j] = 0; do{ scanf("%c",&entrada); if(entrada != ' ' && entrada != 0 && entrada != '\t' && entrada != '\n'){ palavra[aux] = entrada; aux++; }else{ if(entrada == '\n') nLinha++; palavra[aux] = 0; processaPalavra(ocorrencias,palavra,nLinha); aux = 0; } } while (entrada != 0); ordenaOcorrencias(ocorrencias,nLinha,totais); return 0; }
C
// // Created by citiral on 9/23/16. // #include "stdlib.h" #include "stdio.h" #include "ctype.h" #include "cpu/cpu.h" long int strtol(const char* str, char** endptr, int base) { int result = 0; bool isPos = true; while (isspace(*str)) { str++; } if (*str == '-') { isPos = false; str++; } else if (*str == '+') { isPos = true; str++; } if (base == 10) { while (*str >= '0' && *str <= '9') { result = (result * base) + (str[0] - '0'); str++; } } else if (base == 8) { while (*str >= '0' && *str <= '7') { result = (result * base) + (str[0] - '0'); str++; } } else { CPU::panic("Strol called with currently unsupported base"); } if (endptr != nullptr) { *endptr = (char*) str; } return isPos ? result : -result; }
C
#include"SqStack.h" #include<stdio.h> #include<stdlib.h> /** * @name : tatus initStack(SqStack* s, int sizes) * @description : initialize a Stack * @param : s,size * @return : Status * @notice : None */ Status initStack(SqStack* s, int sizes) { //s = (SqStack*)malloc(sizeof(SqStack)); if (s) { s->elem = (int*)malloc(sizeof(int)*sizes); s->top = -1; s->size = sizes; } if(s == NULL) return ERROR; return SUCCESS; } /** * @name : Status isEmptyStack(SqStack* s) * @description : Determine whether the stack is empty * @param : s * @return : Status * @notice : None */ Status isEmptyStack(SqStack* s) { if(s) { if (s->top == -1) { printf("ջΪգ\n"); } else printf("ջΪǿգ\n"); return SUCCESS; } else { return ERROR; } } /** * @name : Status getTopStack(SqStack* s, ElemType* e) * @description : get the top stackand and assign its value to e * @param : s,e * @return : Status * @notice : None */ Status getTopStack(SqStack* s, ElemType* e) { if (s) { if (s->top != -1) { *e = s->elem[s->top]; printf("ջԪΪ %d\n", *e); } else { printf("ջΪջ\n"); } return SUCCESS; } else return ERROR; } /** * @name : Status clearStack(SqStack* s) * @description : clear stack * @param : s * @return : Status * @notice : None */ Status clearStack(SqStack* s) { if (s) { s->top = -1; return SUCCESS; } else { return ERROR; } } /** * @name : Status destroyStack(SqStack* s) * @description : destroy a stack, free all * @param : s * @return : Status * @notice : None */ Status destroyStack(SqStack* s) { if (s) { s->top = -1; free(s->elem); return SUCCESS; } else return ERROR; } /** * @name : Status stackLength(SqStack* s, int* length) * @description : get the stacklength * @param : s,length * @return : Status * @notice : None */ Status stackLength(SqStack* s, int* length) { if (s) { *length = s->top+1; return SUCCESS; } else return ERROR; } /** * @name : Status pushStack(SqStack* s, ElemType data) * @description : push stack * @param : s,data * @return : Status * @notice : None */ Status pushStack(SqStack* s, ElemType data) { if (s) { if (s->top == s->size - 1) { printf("ջջʧܣ\n"); } else { s->top++; s->elem[s->top] = data; printf("ջɹ\n"); } return SUCCESS; } else return ERROR; } /** * @name : Status popStack(SqStack* s, ElemType* data) * @description : popstack * @param : s,data * @return : Status * @notice : None */ Status popStack(SqStack* s, ElemType* data) { if (s) { if (s->top != -1) { *data = s->elem[s->top]; s->top--; printf("ջɹջԪΪ %d\n", *data); } else printf("ջѾΪգ޷ٽгջ\n"); return SUCCESS; } else return ERROR; }
C
#include <stdio.h> #include <stdlib.h> #include <omp.h> //########################################## // // PCPC _ Assignment 08 // Maximilian Weß && Christoph Rauterberg // //########################################## // Moep? Solution so simple as to simply but a dynamic for loop around it? // DONE ? void factorial(int x[], int n); int main (int argc, const char * argv[]) { int arr[8]; factorial(arr, 8); return 0; } void factorial(int x[], int n) { int i,j,thread_id=42; //#pragma omp parallel for num_threads(4) \ default(none) private(i,j,thread_id) shared (n,x) #pragma omp parallel default(none) private(i,j,thread_id) shared (n,x) { #pragma omp for schedule(dynamic) for(i=0; i<n; i++) { if(i<2) { x[i] = 1; } else { x[i] = x[i-1]*i; } // Use OMP-Function to get thread_ID thread_id= omp_get_thread_num(); printf("Thread id # %d computed factorial(%d) = %d \n",thread_id, i, x[i]); } } for(j=0; j<n; j++) printf("%d\t",x[j]); printf("\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #define BOARD '~' #define SPACE ' ' #define VERT '|' #define HORZ '_' const int size = 10; const char *word; const char *four[10] = {"CATS", "SLAP", "CLAW", "PUSH", "FORD", "IPAD", "BEER", "MILK", "FIRE", "DOGS"}; const char *five[10] = {"KITTY", "CABLE", "FLAME", "TREES", "STACK", "ARRAY", "PEPSI", "MORTY", "LOOSE", "SANDY"}; const char *six[10] = {"PARKER", "BANANA", "ROCKET", "QUEUES", "LOTION", "TWELVE", "COUGAR", "LIGHTS", "SWORDS", "SWITCH"}; const char *eight[10] = {"ABSOLUTE", "TRACTORS", "FIREFLYS", "PEACOCKS", "BLANKETS", "RECLINERS", "PENGUINS", "EYEBROWS", "FIREWORK", "KEYBOARD"}; const char *ten[10] = {"PINEAPPLES", "SEMITRUCKS", "LIGHTHOUSE", "HANDWARMER", "THUMBTACKS", "SAXOPHONES", "TAMBORINES", "BASKETBALL", "CHARLESTON", "INTESTINES"}; void createPlayingSpace(char *pSpace) { char title[9] = "HANGMAN!"; for (int index = 0; index < 300; index++) { if (((index <= 25 || index >= 275) && index % 2 == 0) || index % 25 == 0 || (index + 1) % 25 == 0) { pSpace[index] = BOARD; } else if ((index >= 55 && index <= 58) || (index == 178 || index == 180)) { pSpace[index] = HORZ; } else if (((index > 74 && index < 199) && ((index - 4) % 25 == 0)) || index == 84) { pSpace[index] = VERT; } else { pSpace[index] = SPACE; } } int start = 34; for (int i = 0; i < 8; i++) { pSpace[start] = title[i]; start++; } } void printPlayingSpace(const char *pSpace) { for (int index = 0; index < 300; index++) { if (index != 0 && index % 25 == 0) { printf("\n"); } printf("%c", pSpace[index]); } printf("\n"); } int setDif() { int dif; printf("Enter difficulty level (1-5):\n"); scanf("%d", &dif); if (dif < 1 || dif > 5) { printf("Your game has been set to hard for trying to be difficult.\n"); dif = 5; } else { printf("Your game difficulty has been set to %d. Good luck.\n", dif); } return dif; } int setWordSize(char *pSpace) { int dif = setDif(); pSpace[228] = HORZ; pSpace[230] = HORZ; pSpace[232] = HORZ; pSpace[234] = HORZ; switch (dif) { case 2: pSpace[236] = HORZ; break; case 3: pSpace[236] = HORZ; pSpace[238] = HORZ; break; case 4: pSpace[236] = HORZ; pSpace[238] = HORZ; pSpace[240] = HORZ; pSpace[242] = HORZ; break; case 5: pSpace[236] = HORZ; pSpace[238] = HORZ; pSpace[240] = HORZ; pSpace[242] = HORZ; pSpace[244] = HORZ; pSpace[246] = HORZ; break; } return dif; } int random() { int pos; srand(time(NULL)); pos = 1 + rand() % 10; return pos; } void buildGame() { char pSpace[300]; createPlayingSpace(&pSpace[0]); int dif = setWordSize(&pSpace[0]); int pos = random(); switch (dif) { case 1: word = four[pos]; break; case 2: word = five[pos]; break; case 3: word = six[pos]; break; case 4: word = eight[pos]; break; case 5: word = ten[pos]; break; } printPlayingSpace(&pSpace[0]); } int main() { buildGame(); return 0; }
C
/* ***************************************************************** */ /* File name: pid.c */ /* File description: This file has a couple of useful functions to */ /* control the implemented PID controller */ /* Author name: julioalvesMS & IagoAF */ /* Creation date: 21jun2018 */ /* Revision date: 28jun2018 */ /* ***************************************************************** */ #include "Domain/motor_entity.h" #include "pid.h" pid_data_type pidConfig; /* PID K Values */ const double Kp = 3; const double Kd = 9; const double Ki = 0; /* ************************************************ */ /* Method name: pid_init */ /* Method description: Initialize the PID controller*/ /* Input params: n/a */ /* Output params: n/a */ /* ************************************************ */ void pid_init(void) { /* Left Motor PID */ pidConfig.Kp = Kp; pidConfig.Kd = Kd; pidConfig.Ki = Ki; pidConfig.PreviousValue = 0; pidConfig.ErrorSum = 0.0; } /* ************************************************** */ /* Method name: pid_updateData */ /* Method description: Update the control output */ /* using the reference and sensor */ /* value */ /* Input params: sensorValue: Value read from */ /* the sensor */ /* referenceValue: Value used as */ /* control reference */ /* Output params: double: New Control effort */ /* ************************************************** */ double pid_updateData(double sensorValue, double referenceValue) { double Error, difference, out; Error = referenceValue - sensorValue; difference = pidConfig.PreviousValue - sensorValue; /* pidConfig.ErrorSum += Error; */ out = pidConfig.Kp*Error + pidConfig.Ki*pidConfig.ErrorSum + pidConfig.Kd*difference; pidConfig.PreviousValue = sensorValue; if (out>100.0) out = 100.0; else if (out<-100.0) out = -100.0; return out; }
C
#include "graphics.h" typedef struct { int x,y; } point; const point ovalInit = {150,150}; const int widthInit = 30; const int lengthInit = 70; const int widthInc = 10; const int lengthInc = 10; const int ovalToDraw = 5; int main () { int width = widthInit; int length = lengthInit; point ovalPoint = ovalInit; for (int i=0; i<ovalToDraw; i++) drawOval(ovalPoint.x -= widthInc/2, ovalPoint.y -= lengthInc/2, width += widthInc, length += lengthInc); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<assert.h> //ģʵstrlen //1.汾 int my_strlen(const char* str) { assert(str); int count = 0; while (*str != '\0') { count++; str++; } return count; } //2.ݹ汾 int my_strlen(const char* str) { assert(str); if (*str == '\0') return 0; else return 1 + my_strlen(str + 1); } //3.ָ-ָ ָ-ָ=ָ֮Ԫظ int my_strlen(const char* str) { assert(str); char* start = str; while (*str != '\0') { str++; }//whileѭstrҵ'\0' return str - start; } //int main() //{ // char* p = "abcdef"; // int ret = my_strlen(p); // printf("%d\n", ret); // // return 0; //} //ģʵstrcpy char* my_strcpy(char* dest, const char* src) { assert(dest && src); char* start = dest; while (*dest++ = *src++) { ; } return start; } //int main() //{ // char str1[] = "###############"; // char* str2 = "hello world"; // // my_strcpy(str1, str2); // printf("%s\n", str1); // return 0; //} //ģʵstrcmp int my_strcmp(const char* str1, const char* str2) { assert(str1 && str2); while (*str1 == *str2)//ַڵ { if (*str1 == '\0') return 0; str1++; str2++; } // Сڵ return *str1 - *str2; } //int main() //{ // char str1[] = "abcdef"; // char str2[] = "abq"; // // int ret = my_strcmp(str1, str2); // if (ret > 0) // { // printf("str1>str2\n"); // } // else if (ret < 0) // { // printf("str1<str2\n"); // } // else // { // printf("str1=str2\n"); // } // // return 0; //} //ģʵstrcat ַ׷ char* my_strcat(char* dest, const char* src) { assert(dest && src); char* start = dest; while (*dest != '\0')//1.ҵ'\0' { dest++; } //2.׷ while (*dest++ = *src++) { ; } return start; } //int main() //{ // char str1[20] = "hello "; // char* str2 = "world"; // // my_strcat(str1, str2); // // printf("%s\n", str1); // return 0; //} //ģʵstrstr str1str2 // b b b c d e f // b b c //char* my_strstr(const char* str1, const char* str2) //{ // assert(str1 && str2); // // if (*str2 == '\0')// // { // return (char*)str1; // } // const char* s1 = NULL; // const char* s2 = NULL; // const char* cp = str1;//ָ // // while (*cp) // { // s1 = cp; // s2 = str2; // while ((*s1 && *s2) && *s1 == *s2)//(*s1 && *s2)жǰ // { // str1++; // str2++; // } // // if (*s2 == '\0')//жҵ // { // return (char*)cp; // } // cp++; // } // // return NULL; //} //int main() //{ // char str1[] = "abbbcdef"; // char* str2 = "bbc"; // // char* ret = my_strstr(str1, str2); // if (ret == NULL) // { // printf("ûҵ\n"); // } // else // { // printf("ҵˣ%s\n", ret); // } // return 0; //} char* my_strstr(const char* str1, const char* str2) { assert(str1 && str2); if (*str2 == '\0') { return(char*) str1; } const char* s1 = NULL; const char* s2 = NULL; const char* cp = str1; while (*cp) { s1 = cp; s2 = str2; while ((*s1 && *s2) && (*s1 == *s2)) { s1++; s2++; } if (*s2 == '\0') { return (char*)cp; } cp++; } return NULL; } int main() { char* str1 = "abbbcdef"; char* str2 = "bbc"; char* ret = my_strstr(str1, str2); if (ret == NULL) { printf("ûҵ\n"); } else { printf("ҵˣ%s\n", ret); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "grid.h" Grid_T sudoku_read(void){ Grid_T *s=(Grid_T *)malloc(1*sizeof(Grid_T)); int i=0,j=0,el; while((el=getchar())!=EOF) { if(el>='0' && el<='9'){ grid_update_value(s, i, j, el-'0'); j++; } else if(el=='\n'){ i++; j=0; } } return *s; } void sudoku_print(FILE *s, Grid_T g) { int i,j; for(i=0;i<9;i++) { for(j=0;j<9;j++) { fprintf(s,"%d ",grid_read_value(g, i, j)); } fprintf(s,"\n"); } } int sudoku_check_line(Grid_T g, int i, int j, int val) { int k,sum=0; for(k=0;k<9;k++) { if(val!=-1) { if(grid_read_value(g,i,k)==val ) return 1; // ara yparxei mesa sthn grammh h timh pou 8eloume na dwsoume //else // continue; } //if (grid_read_value(g,i,j)==grid_read_value(g,i,k)&& (k!=j) ) // return 1; //an yparxei sth grammh 3ana to idio stoixeio sum=sum+grid_read_value(g,i,k); } if(sum!=45&& val==-1) return 1; //dld problhma sthn grammh return 0; } int sudoku_check_col(Grid_T g, int i, int j, int val) { int k,sum=0; for(k=0;k<9;k++) { if(val!=-1) { if(grid_read_value(g,k,j)==val) return 1; // ara yparxei mesa sthn grammh h timh //else // continue; } // if (grid_read_value(g,i,j)==grid_read_value(g,k,j)&& (k!=i)) // return 1; //an yparxei sth grammh 3ana to idio stoixeio sum=sum+grid_read_value(g,k,j); } if(sum!=45&& val==-1) return 1; return 0; } int which_grid(Grid_T g,int j) { if(j<3) return 0; // anhkei sta grid tis prwths sthlhs else if(j<6) return 3; //anhkei sta grid ths 2 sthlhs else return 6; // anhkei sta grid ths 3 sthlhs } int sudoku_check_grid(Grid_T g, int i, int j,int val) { int arxh_sthlhs=which_grid(g,j); int arxh_grammhs=which_grid(g,i); int row,col,sum=0; for(row=arxh_grammhs;row<arxh_grammhs+3;row++) { for(col=arxh_sthlhs;col<arxh_sthlhs+3;col++)// me ayto tn tropo briskw to stwsto grip analoga me thn sthlh { if(val!=-1) { if(grid_read_value(g,row,col)==val) return 1; // ara yparxei // else // continue; } // if (grid_read_value(g,i,j)==grid_read_value(g,row,col)&& (row!=i&& col!=j)) // return 1; //an yparxei sum=sum+grid_read_value(g,row,col); } } if(sum!=45 && val==-1) return 1; return 0; } void sudoku_print_errors(Grid_T g) { int i,j,row,col,grid; for(i=0;i<9;i++) { for(j=0;j<9;j++) { row=sudoku_check_line(g,i,j,-1); if(row==1) printf("error: yparxei 3ana o ari8mos %d sthn grammh %d\n",grid_read_value(g,i,j),i); col=sudoku_check_col(g, i,j,-1); if(col==1) printf("error: yparxei 3ana o ari8mos %d sthn sthlh %d\n",grid_read_value(g,i,j),j); grid=sudoku_check_grid( g, i,j,-1); if(grid==1) printf("error: yparxei 3ana o ari8mos %d sto grid pou anhkei\n", grid_read_value(g,i,j)); } } } int sudoku_solution_is_unique(Grid_T g){ return grid_read_unique(g); } int sudoku_is_correct(Grid_T g) { int i,j,row,col,grid; for(i=0;i<9;i++) { for(j=0;j<9;j++) // ebgala ayth th for kai to grod apo ta sxolia... { row=sudoku_check_line(g,i,j,-1); if(row==1) return 0; col=sudoku_check_col(g, i,j,-1); if(col==1) return 0; grid=sudoku_check_grid( g, i,j,-1); if(grid==1) return 0; } } return 1; // einai olo swsto to puzlle } /*static*/void sudoku_init_choices(Grid_T *g){ int i,j,k; for(i=0;i<9;i++) { for(j=0;j<9;j++) { if(grid_read_value( *g, i,j)==0) { grid_set_count(g, i, j); for(k=1;k<10;k++) { if( sudoku_check_line(*g, i, j,k)==1) { grid_remove_choice(g, i, j,k); continue; } if( sudoku_check_col(*g, i, j,k)==1) { grid_remove_choice(g, i, j,k); continue; } if(sudoku_check_grid(*g, i, j,k)==1) { grid_remove_choice(g, i, j,k); continue; } grid_set_choice(g, i, j,k); } } else grid_clear_count(g,i,j); } } } void print_choices(Grid_T g){ int i,j,k; for(i=0; i<9; i++){ for(j=0; j<9; j++){ printf("(%d,%d)=%d [",i,j,g.elts[i][j].choices.count); for(k=1; k<10; k++){ printf("%d,",g.elts[i][j].choices.num[k]); } printf("]\n"); } } } /*static */int sudoku_try_next(Grid_T g, int *row, int *col) { int i,j,found=0, ran=0,k,counter=-1; for(i=0;i<9;i++) { for(j=0;j<9;j++) { if(grid_read_value( g, i, j)==0 && grid_read_count(g,i,j)==1) { *row=i; *col=j; found=1; break; } } if(found==1) break; } if(found == 0) { for(i=0;i<9;i++) { for(j=0;j<9;j++) { if(grid_read_value( g, i, j)==0) { *row=i; *col=j; found=1; break; } } if(found==1) break; } } if(found == 0){ return -1; } if(grid_read_value(g,*row,*col) != 0) return -1; j = grid_read_count( g, *row, *col); if(j == 0) return -1; ran=rand()%j; for(k=1;k<10;k++) { if(grid_choice_is_valid( g, *row, *col, k)==1) { counter++; if(counter==ran) { //printf("%d,%d=%d\n",*row, *col,k); return k; } } } return -1; } /*static*/ int sudoku_update_choice(Grid_T *g, int i, int j, int n) { int epiloges=grid_read_count(*g, i, j); grid_remove_choice(g, i, j, n); return epiloges; } void sudoku_eliminate_choice(Grid_T *g, int r, int c, int n) { int i,j,k,l; for(i=0;i<9;i++) // elegxw thn grammh { if(grid_choice_is_valid(*g,i,c,n)){ grid_remove_choice(g,i,c,n); } } for(j=0;j<9;j++) // elegxw thn sthlh { if(grid_choice_is_valid(*g,r,j,n)){ grid_remove_choice(g,r,j,n); } } k=which_grid(*g,r); l=which_grid(*g,c); for(i=k;i<k+3;i++) { for(j=l;j<l+3;j++) { if(grid_choice_is_valid(*g,i,j,n)){ grid_remove_choice(g,i,j,n); } } } } Grid_T sudoku_solve(Grid_T g) { int ch=0,i,j; Grid_T tmp; int unique=1; grid_clear_unique(&g); if(sudoku_is_correct(g) == 1) return g; //if(i>8 || j>8)return g; sudoku_init_choices(&g); while((ch=sudoku_try_next(g,&i,&j))!=-1) { if(grid_read_count(g,i,j)==1) { sudoku_update_choice(&g,i, j,ch); sudoku_eliminate_choice(&g,i,j,ch); grid_update_value(&g,i,j,ch); } else { grid_clear_unique(&g); tmp=g; grid_clear_unique(&tmp); unique = 0; sudoku_update_choice(&tmp,i, j,ch); sudoku_eliminate_choice(&tmp,i,j,ch); grid_update_value(&tmp,i,j,ch); tmp=sudoku_solve(tmp); if(sudoku_is_correct(tmp)==1){ return tmp; } else{ grid_remove_choice(&g, i, j, ch); } } } if(unique == 1) grid_set_unique(&g); return g; } static Grid_T sudoku_generate_complete(void) { int i,j,k,ch; Grid_T *g=(Grid_T*)malloc(1*sizeof(Grid_T)); for(i=0;i<9;i++) { for(j=0;j<9;j++) { grid_update_value(g,i, j,0); } } // sudoku_init_choices(g); *g = sudoku_solve(*g); return *g; } Grid_T sudoku_generate(int nelts, int unique){ Grid_T g = sudoku_generate_complete(); int i=0,c,r; for(i=0;i <((9*9)-nelts); i++){ do{ r = rand()%9; c = rand()%9; }while(grid_read_value(g,r,c)==0); grid_update_value(&g,r,c,0); } return g; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <pthread.h> int thread_count; double f(double x){ double y = x*x; return y; } double Trap(double left_endpt,double right_endpt,int trap_count,double base_len){ double estimate,x; int i; estimate = (f(left_endpt)+f(right_endpt))/2.0; for(i=1;i<=trap_count-1;i++){ x = left_endpt+ i * base_len; estimate += f(x); } estimate = estimate*base_len; return estimate; /*trap*/ } void* parallel(void *rank){ //a=0.0;b=3.0;n=1024; Get_input(my_rank,comm_sz,&a,&b,&n); h=(b-a)/n; local_n=n/comm_sz; lastCoreRst = n%comm_sz; if(my_rank!=comm_sz-1){ local_a=a+my_rank*local_n*h; local_b=local_a+local_n*h; local_int=Trap(local_a,local_b,local_n,h); printf("my_rank:%d local_n:%d local_int:%f\n",my_rank,local_n,local_int); } else{ local_a=a+my_rank*local_n*h; local_n+=lastCoreRst; local_b=local_a+local_n*h; local_int=Trap(local_a,local_b,local_n,h); printf("my_rank:%d local_n:%d local_int:%f\n",my_rank,local_n,local_int); } MPI_Allreduce(&local_int,&total_int,1,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD); if(my_rank==0){ printf("with n = %d trapezoids, estimate\n",n); printf("of the integral form %f to %f = %.15e\n",a,b,total_int); } else{ printf("with n = %d trapezoids, estimate\n",n); printf("of the integral form %f to %f = %.15e\n",a,b,total_int); } } int main(int argc, char* argv[]){ long thread; pthread_t *thread_handles; thread_count = strtol(argv[1],NULL,10); thread_handles = malloc (thread_count * sizeof(pthread_t)); for(thread = 0; thread < thread_count ; thread++){ pthread_create(&thread_handles[thread],NULL,parallel,(void * )thread); } for(thread = 0 ; thread < thread_count ; thread++){ pthread_join(thread_handles[thread],NULL); } free(thread_handles); return 0; }
C
/* * btleaf_page.C - implementation of class BTLeafPage * * Johannes Gehrke & Gideon Glass 951016 CS564 UW-Madison * Edited by Young-K. Suh (yksuh@cs.arizona.edu) 03/27/14 CS560 Database Systems Implementation */ #include "btleaf_page.h" #include <cstdio> #include <cstring> const char* BTLeafErrorMsgs[] = { // OK, // Insert Record Failed, }; static error_string_table btree_table(BTLEAFPAGE, BTLeafErrorMsgs); /* * Status BTLeafPage::insertRec(const void *key, * AttrType key_type, * RID dataRid, * RID& rid) * * Inserts a key, rid value into the leaf node. This is * accomplished by a call to SortedPage::insertRecord() * The function also sets up the recPtr field for the call * to SortedPage::insertRecord() * * Parameters: * o key - the key value of the data record. * * o key_type - the type of the key. * * o dataRid - the rid of the data record. This is * stored on the leaf page along with the * corresponding key value. * * o rid - the rid of the inserted leaf record data entry. */ Status BTLeafPage::insertRec(const void *key, AttrType key_type, RID dataRid, RID& rid) { Status status; if(key_type == attrString){ char *k = (char *)key; int len = get_key_length(key,key_type); char *record = new char[len+sizeof(RID)]; memcpy(record,k,len); memcpy(record+len,&dataRid,sizeof(RID)); status = SortedPage::insertRecord(key_type,record,len+sizeof(RID),rid); } else if(key_type == attrInteger){ int keyDataLength = sizeof(int) + sizeof(RID); int *k = (int *)key; char *record = new char[keyDataLength]; memcpy(record,key,sizeof(int)); memcpy(record+sizeof(int),&dataRid,sizeof(RID)); status = SortedPage::insertRecord(key_type,record,keyDataLength,rid); } else return DONE; // put your code here return status; } /* * * Status BTLeafPage::get_data_rid(const void *key, * AttrType key_type, * RID & dataRid) * * This function performs a binary search to look for the * rid of the data record. (dataRid contains the RID of * the DATA record, NOT the rid of the data entry!) */ Status BTLeafPage::get_data_rid(void *key, AttrType key_type, RID & dataRid) { Status status; if(key_type == attrInteger){ int *k = (int *)key; RID rid,nextRid; int *key_val; status = get_first(rid,key_val,nextRid); if(status!=OK) return status; int *key_cast_val = (int *)key_val; if(*key_cast_val == *k) { dataRid = nextRid; return OK; } status = get_next(rid,key_val,nextRid); while(status == OK) { key_cast_val = (int *)key_val; if(*key_cast_val == *k) { dataRid = nextRid; return OK; } status = get_next(rid,key_val,nextRid); } } else if(key_type == attrString){ char *k = (char *)key; RID rid,nextRid; char *key_val; status = get_first(rid,key_val,nextRid); if(status!=OK) return status; if(strcmp(key_val,k)==0) { dataRid = nextRid; return OK; } status = get_next(rid,key_val,nextRid); while(status == OK) { if(strcmp(key_val,k)==0){ dataRid = nextRid; return OK; } status = get_next(rid,key_val,nextRid); } } // put your code here return DONE; } /* * Status BTLeafPage::get_first (const void *key, RID & dataRid) * Status BTLeafPage::get_next (const void *key, RID & dataRid) * * These functions provide an * iterator interface to the records on a BTLeafPage. * get_first returns the first key, RID from the page, * while get_next returns the next key on the page. * These functions make calls to RecordPage::get_first() and * RecordPage::get_next(), and break the flat record into its * two components: namely, the key and datarid. */ Status BTLeafPage::get_first (RID& rid, void *key, RID & dataRid) { slot_t *currSlot = this->slot; int i=0; while(currSlot->offset==-1) { currSlot = (slot_t*)(data+i*sizeof(slot_t)); i++; } rid.slotNo = i; rid.pageNo = curPage; int offset = currSlot->offset; int length = currSlot->length; char *record = new char[length]; memcpy(record,data+offset,length); int keySize = length - sizeof(RID); if(keySize == sizeof(int)) { // int *k = new int[1]; memcpy(key,data+offset,sizeof(int)); // key = (void *)k; memcpy(&dataRid,data+offset+keySize,sizeof(RID)); } else { memcpy(key,data+offset,20); // key = (void *)k; memcpy(&dataRid,data+offset+20,sizeof(RID)); } // put your code here return OK; } Status BTLeafPage::get_next (RID& rid, void *key, RID & dataRid) { RID nextRid; int currSlotNo = rid.slotNo; int i=0; slot_t *temp = this->slot; if(currSlotNo+1 > this->slotCnt) return NOMORERECS; slot_t *nextSlot = (slot_t*)(data + currSlotNo*sizeof(slot_t)); if(nextSlot->offset==-1) { // while (nextSlot->offset == -1 && currSlotNo <= this->slotCnt) { nextSlot = (slot_t*)(data + (currSlotNo+1)*sizeof(slot_t)); currSlotNo++; // } //if(currSlotNo > this->slotCnt) // return NOMORERECS; //currSlotNo--; } nextRid.pageNo = rid.pageNo; nextRid.slotNo = currSlotNo+1; rid = nextRid; int offset = nextSlot->offset; int length = nextSlot->length; int keyLength = length - sizeof(RID); if(keyLength == sizeof(int)) { // key = (void *)(new int[1]); memcpy(key,data+offset,sizeof(int)); memcpy(&dataRid,data+offset+sizeof(int),sizeof(RID)); } else { memcpy(key,data+offset,20); //key = (void *)k; memcpy(&dataRid,data+offset+20,sizeof(RID)); } return OK; }
C
// // testRlp.c // CoreTests // // Created by Ed Gamble on 7/23/18. // Copyright © 2018-2019 Breadwinner AG. All rights reserved. // // See the LICENSE file at the project root for license information. // See the CONTRIBUTORS file at the project root for a list of contributors. #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include "ethereum/util/BRUtil.h" #include "ethereum/rlp/BRRlp.h" static void showHex (uint8_t *source, size_t sourceLen) { char *prefix = "{"; for (int i = 0; i < sourceLen; i++) { printf("%s%x", prefix, source[i]); prefix = ", "; } printf ("}\n"); } // // RLP Test // #define RLP_S1 "dog" #define RLP_S1_RES { 0x83, 'd', 'o', 'g' }; #define RLP_S2 "" #define RLP_S2_RES { 0x80 } #define RLP_S3 "Lorem ipsum dolor sit amet, consectetur adipisicing elit" #define RLP_S3_RES { 0xb8, 0x38, 'L', 'o', 'r', 'e', 'm', ' ', 'i', 'p', 's', 'u', 'm', ' ', 'd', 'o', 'l', 'o', 'r', \ ' ', 's', 'i', 't', ' ', 'a', 'm', 'e', 't', ',', ' ', 'c', 'o', 'n', 's', 'e', 'c', 't', 'e', 't', 'u', 'r', \ ' ', 'a', 'd', 'i', 'p', 'i', 's', 'i', 'c', 'i', 'n', 'g', ' ', 'e', 'l', 'i', 't' }; #define RLP_V1 0 #define RLP_V1_RES { 0x00 } #define RLP_V2 15 #define RLP_V2_RES { 0x0f } #define RLP_V3 1024 #define RLP_V3_RES { 0x82, 0x04, 0x00 } // 'cat', 'dog' #define RLP_L1_RES { 0xc8, 0x83, 'c', 'a', 't', 0x83, 'd', 'o', 'g' } int equalBytes (uint8_t *a, size_t aLen, uint8_t *b, size_t bLen) { if (aLen != bLen) return 0; for (int i = 0; i < aLen; i++) if (a[i] != b[i]) return 0; return 1; } void rlpCheck (BRRlpCoder coder, BRRlpItem item, uint8_t *result, size_t resultSize) { BRRlpData data = rlpItemGetData(coder, item); assert (equalBytes(data.bytes, data.bytesCount, result, resultSize)); printf (" => "); showHex (data.bytes, data.bytesCount); free (data.bytes); } void rlpCheckString (BRRlpCoder coder, const char *string, uint8_t *result, size_t resultSize) { printf (" \"%s\"", string); BRRlpItem item = rlpEncodeString(coder, (char*) string); rlpCheck(coder, item, result, resultSize); rlpItemRelease(coder, item); } void rlpCheckInt (BRRlpCoder coder, uint64_t value, uint8_t *result, size_t resultSize) { printf (" %" PRIu64, value); BRRlpItem item = rlpEncodeUInt64(coder, value, 0); rlpCheck(coder, item, result, resultSize); rlpItemRelease(coder, item); } void runRlpEncodeTest () { printf (" Encode\n"); BRRlpCoder coder = rlpCoderCreate(); uint8_t s1r[] = RLP_S1_RES; rlpCheckString(coder, RLP_S1, s1r, sizeof(s1r)); uint8_t s2r[] = RLP_S2_RES; rlpCheckString(coder, RLP_S2, s2r, sizeof(s2r)); uint8_t s3r[] = RLP_S3_RES; rlpCheckString(coder, RLP_S3, s3r, sizeof(s3r)); uint8_t t3r[] = RLP_V1_RES; rlpCheckInt(coder, RLP_V1, t3r, sizeof(t3r)); uint8_t t4r[] = RLP_V2_RES; rlpCheckInt(coder, RLP_V2, t4r, sizeof(t4r)); uint8_t t5r[] = RLP_V3_RES; rlpCheckInt(coder, RLP_V3,t5r, sizeof(t5r)); BRRlpItem listCatDog = rlpEncodeList2(coder, rlpEncodeString(coder, "cat"), rlpEncodeString(coder, "dog")); uint8_t resCatDog[] = RLP_L1_RES; printf (" \"%s\"", "[\"cat\" \"dog\"]"); rlpCheck(coder, listCatDog, resCatDog, 9); rlpItemRelease(coder, listCatDog); BRCoreParseStatus status = CORE_PARSE_OK; char *value = "5968770000000000000000"; UInt256 r = uint256CreateParse(value, 10, &status); BRRlpItem item = rlpEncodeUInt256(coder, r, 0); BRRlpData data = rlpItemGetData(coder, item); rlpItemRelease(coder, item); printf (" %s\n => ", value); showHex (data.bytes, data.bytesCount); char *dataHex = hexEncodeCreate(NULL, data.bytes, data.bytesCount); printf (" => %s\n", dataHex); assert (0 == strcasecmp (dataHex, "8a01439152d319e84d0000")); free (dataHex); rlpCoderRelease(coder); printf ("\n"); } void runRlpDecodeTest () { printf (" Decode\n"); BRRlpCoder coder = rlpCoderCreate(); size_t c; // cat & dog uint8_t l1b[] = RLP_L1_RES; BRRlpData l1d; l1d.bytes = l1b; l1d.bytesCount = 9; BRRlpItem l1i = rlpDataGetItem(coder, l1d); const BRRlpItem *l1is = rlpDecodeList (coder, l1i, &c); assert (2 == c); char *liCat = rlpDecodeString(coder, l1is[0]); char *liDog = rlpDecodeString(coder, l1is[1]); assert (0 == strcmp (liCat, "cat")); assert (0 == strcmp (liDog, "dog")); rlpItemRelease(coder, l1i); free (liCat); free (liDog); uint8_t s3b[] = RLP_S3_RES; BRRlpData s3d; s3d.bytes = s3b; s3d.bytesCount = 58; BRRlpItem s3i = rlpDataGetItem(coder, s3d); char *s3Lorem = rlpDecodeString(coder, s3i); assert (0 == strcmp (s3Lorem, RLP_S3)); rlpItemRelease(coder, s3i); free (s3Lorem); // uint8_t v3b[] = RLP_V3_RES; BRRlpData v3d; v3d.bytes = v3b; v3d.bytesCount = 3; BRRlpItem v3i = rlpDataGetItem(coder, v3d); uint64_t v3v = rlpDecodeUInt64(coder, v3i, 0); assert (1024 == v3v); rlpItemRelease(coder, v3i); rlpCoderRelease(coder); } void runRlpTests (void) { printf ("==== RLP\n"); runRlpEncodeTest (); runRlpDecodeTest (); }
C
/* * ===================================================================================== * * Filename: allocator_pool.c * * Description: allocator_pool c source file * * Version: 1.0 * Created: 04/22/2019 03:51:01 PM * Revision: none * Compiler: gcc * * Author: YOUR NAME (), * Organization: * * ===================================================================================== */ #include <stdlib.h> #include "allocator_pool.h" typedef struct _FreeNode { size_t length; struct _FreeNode* next; struct _FreeNode* prev; }FreeNode; #define MIN_SIZE 16 #define MAX_SIZE 64 #define EXPAND_DELTA 32 #define FREE_LIST_LENGTH 8 typedef struct _PrivInfo { FreeNode* free_list[FREE_LIST_LENGTH]; Allocator* real_allocator; }PrivInfo; static void* allocator_poll_calloc(Allocator* thiz,size_t nmemb,size_t size) { void* ptr = NULL; size_t total = nmemb * size; PrivInfo* priv = (PrivInfo*)thiz->priv; if(total <= MAX_SIZE) { ptr = allocator_alloc(thiz,total); if(ptr != NULL) { memset(ptr,0x00,total); } } else { ptr = allocator_calloc(priv->real_allocator,nmemb,size); } return ptr; } static void* allocator_pool_alloc(Allocator* thiz,size_t size) { void* ptr = NULL; PrivInfo* priv = (PrivInfo*)thiz->priv; if(size <= MAX_SIZE) { size_t index = (size - 1) / FREE_LIST_LENGTH; if(priv->free_list[index] == NULL) { priv->free_list[index] = allocator_alloc(priv->real_allocator,(index + 1) * FREE_LIST_LENGTH); } } else { } } static void alloctor_pool_free(Allocator* thiz,void* ptr) { free(ptr); return; } static void* allocator_pool_realloc(Allocator* thiz,void* ptr,size_t size) { return realloc(ptr,size); } static void allocator_pool_destroy(Allocator* thiz) { if(thiz != NULL) { free(thiz); } return; } Allocator* allocator_pool_create(size_t expand_delta) { Allocator* thiz = (Allocator*)calloc(1,sizeof(Allocator)); if(thiz != NULL) { thiz->calloc = allocator_poll_calloc; thiz->alloc = allocator_pool_alloc; thiz->realloc = allocator_pool_realloc; thiz->free = alloctor_pool_free; thiz->destroy = allocator_pool_destroy; } return thiz; } #ifdef ALLOCATOR_POOL_TEST int main(int argc,char* argv[]) { int i = 0; int n = 100; Allocator* allocator = allocator_pool_create(128); for(i = 0; i < n; i++) { char* ptr = allocator_alloc(allocator,i); ptr = allocator_realloc(allocator,ptr,i+4); allocator_free(allocator,ptr); ptr = allocator_calloc(allocator,i+4,4); allocator_free(allocator,ptr); } allocator_destroy(allocator); return 0; } #endif /* ALLOCATOR_POOL_TEST */
C
#include "pch.h" // Tree Memory Allocation structure. typedef struct _POOLMEMORYBLOCK POOLMEMORYBLOCK, *PPOOLMEMORYBLOCK; struct _POOLMEMORYBLOCK { DWORD Index; DWORD Size; PPOOLMEMORYBLOCK NextBlock; PPOOLMEMORYBLOCK PrevBlock; PBYTE RawMemory; }; typedef struct _POOLHEADER { PPOOLMEMORYBLOCK PoolHead; HANDLE Heap; } POOLHEADER, *PPOOLHEADER; BOOL PoolMemAddMemory ( IN POOLHANDLE Handle, IN DWORD Size ) { PBYTE allocedMemory; PPOOLMEMORYBLOCK newBlock; PPOOLHEADER poolHeader = (PPOOLHEADER) Handle; DWORD sizeNeeded; assert(poolHeader != NULL); // // Determine size needed and attempt to allocate memory. // if (Size + sizeof(POOLMEMORYBLOCK) > POOLMEMORYBLOCKSIZE) { sizeNeeded = Size + sizeof(POOLMEMORYBLOCK); } else { sizeNeeded = POOLMEMORYBLOCKSIZE; } allocedMemory = HeapAlloc(poolHeader -> Heap,0,sizeNeeded); if (allocedMemory) { // // Use the beginning of the alloc'ed block as the poolblock structure. // newBlock = (PPOOLMEMORYBLOCK) allocedMemory; newBlock -> Size = sizeNeeded - sizeof(POOLMEMORYBLOCK); newBlock -> RawMemory = allocedMemory + sizeof(POOLMEMORYBLOCK); newBlock -> Index = 0; // // Link the block into the list. // if (poolHeader -> PoolHead) { poolHeader -> PoolHead -> PrevBlock = newBlock; } newBlock -> NextBlock = poolHeader -> PoolHead; newBlock -> PrevBlock = NULL; poolHeader -> PoolHead = newBlock; } // // Assuming allocedMemory is non-NULL, we have succeeded. // return allocedMemory != NULL; } POOLHANDLE WINAPI PoolMemInitPool ( ) { BOOL ableToAddMemory; PPOOLHEADER header = NULL; HANDLE procHeap; procHeap = GetProcessHeap(); // // Allocate the header of this pool. // header = HeapAlloc(procHeap,0,sizeof(POOLHEADER)); if (header) { // // Allocation was successful. Now, initialize the pool. // header -> PoolHead = NULL; header -> Heap = procHeap; // // Actually add some memory to the pool. // ableToAddMemory = PoolMemAddMemory(header,0); if (!ableToAddMemory) { // // Unable to add memory to the pool. // HeapFree(header -> Heap,0,header); header = NULL; } } return (POOLHANDLE) header; } VOID WINAPI PoolMemDestroyPool ( POOLHANDLE Handle ) { PPOOLMEMORYBLOCK nextBlock; PPOOLMEMORYBLOCK blockToFree; PPOOLHEADER poolHeader; assert(Handle != NULL); poolHeader = (PPOOLHEADER) Handle; // // Walk the list, freeing as we go. // blockToFree = poolHeader -> PoolHead; while (blockToFree != NULL) { nextBlock = blockToFree->NextBlock; HeapFree(poolHeader -> Heap,0,blockToFree); blockToFree = nextBlock; } // // Also, deallocate the poolheader itself. // HeapFree(poolHeader -> Heap,0,poolHeader); } PVOID WINAPI PoolMemGetAlignedMemory ( IN POOLHANDLE Handle, IN DWORD Size, IN DWORD AlignSize ) { BOOL haveEnoughMemory = TRUE; PVOID rMemory = NULL; PPOOLHEADER poolHeader = (PPOOLHEADER) Handle; PPOOLMEMORYBLOCK currentBlock; DWORD sizeNeeded; DWORD padLength; assert(poolHeader != NULL); currentBlock = poolHeader -> PoolHead; // Determine if more memory is needed, attempt to add if needed. sizeNeeded = Size; if (currentBlock -> Size - currentBlock -> Index < sizeNeeded + AlignSize) { haveEnoughMemory = PoolMemAddMemory(poolHeader,sizeNeeded + AlignSize); currentBlock = poolHeader -> PoolHead; } // If there is enough memory available, return it. if (haveEnoughMemory) { if (AlignSize) { padLength = (DWORD) currentBlock + sizeof(POOLMEMORYBLOCK) + currentBlock -> Index; currentBlock -> Index += (AlignSize - (padLength % AlignSize)) % AlignSize; } //Now, get the address of the memory to return. rMemory = (PVOID) &(currentBlock->RawMemory[currentBlock -> Index]); currentBlock->Index += sizeNeeded; } return rMemory; }
C
# include <stdio.h> int a; void main() { printf("Enter the Number\n"); scanf("%d",&a); printf("The entered number is:%d\t\n",a); if (a>0) { printf("It is a Positive Number"); } else if (a==0) { printf("It is neigher a Positive Nor Negative number"); } else { printf("It is a Negative Number"); } }
C
/** @file buf.c * * Simple memory buffers. * * Copyright 2009 Simon Kallweit * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <lwpb/lwpb.h> #include "private.h" /** * Initializes a memory buffer. Sets the position to the base address. * @param buf Memory buffer * @param data Base address of memory * @param len Length of memory */ void lwpb_buf_init(struct lwpb_buf *buf, void *data, size_t len, lwpb_bool_t resizable) { buf->base = data; buf->size = len; buf->resizable = resizable; } void lwpb_old_buf_init(struct lwpb_old_buf *buf, void *data, size_t len){ buf->pos = buf->base = data; buf->end = data + len; } void lwpb_nested_buf_init(struct lwpb_nested_buf *buf, struct lwpb_buf *parent, size_t start) { buf->parent = parent; buf->start = start; buf->pos = start; } /** * Returns the number of used bytes in the buffer. * @param buf Memory buffer * @return Returns the number of used bytes. */ size_t lwpb_nested_buf_used(struct lwpb_nested_buf *buf) { return buf->pos - buf->start; } size_t lwpb_old_buf_used(struct lwpb_old_buf *buf) { return buf->pos - buf->base; } size_t lwpb_nested_buf_left(struct lwpb_nested_buf *buf){ return buf->parent->size - buf->pos; } size_t lwpb_old_buf_left(struct lwpb_old_buf *buf) { return buf->end - buf->pos; } lwpb_bool_t lwpb_buf_resize(struct lwpb_buf *buf, size_t grow_atleast){ if(!buf->resizable) return 0; size_t new_size = MAX(buf->size <<1, buf->size + grow_atleast); // double size, but make sure we allocate minimum needed buf->base = realloc(buf->base, new_size); if(buf->base) buf->size = new_size; return(buf->base != 0); } lwpb_bool_t lwpb_buf_make_space(struct lwpb_buf *buf, size_t bytes){ if(bytes > buf->size) return lwpb_buf_resize(buf, bytes - buf->size); else return 1; }
C
#include <stdio.h> #include <stdio.h> #include <termios.h> #include <unistd.h> #include "player.h" #include "starship.h" #include "stage.h" static int play_char(){ //got to check if window focus struct termios oldt, newt; int ch; tcgetattr( STDIN_FILENO, &oldt); newt=oldt; newt.c_lflag &= ~(ICANON); tcsetattr( STDIN_FILENO, TCSANOW, &newt); ch=getchar(); tcsetattr( STDIN_FILENO, TCSANOW, &oldt); //check stuff, return vals return ch; } void player_init(player_t* player, player_id_t player_id, movement_t movement) { player->player_id = player_id; player->ship.entity_live.entity.update=player_update; starship_init(&player->ship, PLAYER_HEALTH, PLAYER_ARMOR, PLAYER_WEAPONRY, PLAYER_HIT_RADIUS, PLAYER, movement); } void player_update(entity_t *entity, stage_t *stage) { player_t *player = (player_t *)entity; /* int do_integer = play_char(); */ /* double current_speed = vec2_mag(entity->movement.velocity); */ /* if (current_speed < PLAYER_SPEED) { */ /* if (do_integer == 'w') { */ /* entity->movement.acceleration = (vec2_t){0, 1}; */ /* } else if (do_integer == 'a') { */ /* entity->movement.acceleration = (vec2_t){-1, 0}; */ /* } else if (do_integer == 's') { */ /* entity->movement.acceleration = (vec2_t){0, -1}; */ /* } else if (do_integer == 'd') { */ /* entity->movement.acceleration = (vec2_t){1, 0}; */ /* } */ /* }else{ */ /* entity->movement.acceleration=vec2_scale(entity->movement.orientation, -PLAYER_ACCELERATION); */ /* } */ /* if(do_integer == ' '){ */ /* starship_fire((starship_t*)player, stage); */ /* } */ bool still_alive = starship_update(entity, stage); if (still_alive) { entity->movement.velocity = vec2_min(entity->movement.velocity, (vec2_t){PLAYER_SPEED, PLAYER_SPEED}); entity->movement.position = vec2_min(vec2_max(entity->movement.position, (vec2_t){-STAGE_WIDTH / 2, -STAGE_HEIGHT / 2}), (vec2_t){STAGE_WIDTH / 2, STAGE_HEIGHT / 2}); } }
C
#include "lists.h" /** * print_list - prints all the elements of a list * @h: header * Return: count being i */ size_t print_list(const list_t *h) { int i; if (h == NULL) return (0); for (i = 0; h; i++) { if (h->str != NULL) { printf("[%u] ", h->len); } else { printf("[%u] ", 0); } if (h->str != NULL) { printf("%s\n", h->str); } else { printf("%s\n", "(nil)"); } h = h->next; } return (i); }
C
#include <stdio.h> #define MIN(a,b) (a<b ? a:b) int main() { long long int k, n, p, y, x, z, m, a, b, tmp; int i, input; scanf ("%d", &input); for (i=0; i<input; i++) { scanf ("%lld %lld", &n, &k); if (k==n) { printf ("1\n"); continue; } y = n-1; z = MIN ((k-1), (n-k)); p = 1; for (m=1; m<=z; m++) { p *= y--; p /= m; } printf ("%lld\n", p); } return 0; }
C
/* This program will kill approxamatly 35 seconds of time. */ main() { int x; long int y; for(x=0; x<10; x++) { for(y=0; y<1000000; y++); } }
C
/* * Example of client using XNS IDP protocol. */ #include "xns.h" main(argc, argv) int argc; char *argv[]; { int sockfd; struct sockaddr_ns cli_addr, serv_addr; pname = argv[0]; /* * Fill in the structure "serv_addr" with the address of the * server that we want to send to. */ bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sns_family = AF_NS; serv_addr.sns_addr = ns_addr(IDP_SERV_ADDR); /* stores net-ID, host-ID and port */ /* * Open an IDP socket (an XNS datagram socket). */ if ( (sockfd = socket(AF_NS, SOCK_DGRAM, 0)) < 0) err_dump("client: can't open datagram socket"); /* * Bind any local address for us. */ bzero((char *) &cli_addr, sizeof(cli_addr)); /* zero out */ cli_addr.sns_family = AF_NS; if (bind(sockfd, (struct sockaddr *) &cli_addr, sizeof(cli_addr)) < 0) err_dump("client: can't bind local address"); dg_cli(stdin, sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)); close(sockfd); exit(0); }
C
#include <stdio.h> #include <unistd.h> #include <sys/socket.h> #include <bluetooth/bluetooth.h> #include <bluetooth/rfcomm.h> #include "util.h" #define SERVER_DEVICE "00:1A:7D:DA:71:11" int main(int argc, char **argv) { struct sockaddr_rc addr = { 0 }; int s, status, bytes_read; char buf[1024]; char **joystickData; size_t numData; long rf_count, lf_count, rl_count, ll_count,back_gear =0; // allocate a socket s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); // set the connection parameters (who to connect to) addr.rc_family = AF_BLUETOOTH; addr.rc_channel = (uint8_t) 1; str2ba( SERVER_DEVICE, &addr.rc_bdaddr ); // connect to server status = connect(s, (struct sockaddr *)&addr, sizeof(addr)); if(status == 0) { printf("connect success\n"); } else if(status < 0) { printf("connect failed\n"); exit(1); } // read data from the server while(1) { bytes_read = read(s, buf, sizeof(buf)); if( bytes_read > 0 ) { size_t i; printf("received [%s]\n", buf); joystickData = strsplit(buf, "/", &numData); for (i = 0; i < numData; i++) { printf("%s-", joystickData[i]); free(joystickData[i]); } printf("\n"); if (joystickData != NULL) { free(joystickData); } /// 0 = steer /// 1= speed // 6 == leftFlick//7=right flick /// 3 = buzzer // 2=forward light //4= backward light //13 == back speed if( (joystick[13] - Data13 = 1) )//back gear { back_gear++; } if( back_gear%2 = 1) )//back gear { back_speedControl(fd, joystickData[0]); } else { speedControl(fd, joystickData[0]); } steeringControl(fd, joystickData[0]); if((joystick[7]-Data7)=1)//Right flicker { rf_count++; right_flicker(int fd,int rf_count) ; } if((joystick[6]-Data6)=1)//Right flicker { lf_count++; left_flicker(int fd,int lf_count); } if((joystick[2]-Data2)=1) //forward_light { rl_count++; forward_light(int fd,int rl_count); } if((joystick[4]-Data4)=1) { ll_count++; back_light(int fd,int ll_count); } if( joystickData[3] == 1 ) { soundControl(int fd); } Data2=joystick[2]; //compare Data4=joystick[4]; Data6=joystick[6]; Data7=joystick[7]; Data13=joystick[13]; } } close(s); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mtshisw <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/01 16:40:05 by mtshisw #+# #+# */ /* Updated: 2018/06/02 15:39:10 by mtshisw ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int words_counter(char const *s, char c) { int wcount; wcount = 0; while (*s != '\0') { if (*s == c) s++; else { wcount++; while (*s && *s != c) s++; } } return (wcount); } static char *diff_words(char const *s, char c) { int i; size_t slength; char *newstr; slength = ft_strlen(s); if (!(newstr = (char *)malloc(slength + 1))) return (NULL); i = 0; while (*s != '\0' && *s != c) newstr[i++] = *s++; newstr[i] = '\0'; return (newstr); } char **ft_strsplit(char const *s, char c) { int i; int nb_wrd; char **tab; if (!s) return (NULL); nb_wrd = words_counter(s, c); if (!(tab = (char **)malloc(sizeof(*tab) * (nb_wrd + 1)))) return (NULL); i = 0; while (*s != '\0') { if (*s == c) s++; else { tab[i] = diff_words(s, c); i++; while (*s && *s != c) s++; } } tab[i] = NULL; return (tab); }
C
#include "libft.h" char *ft_strncpy(char *d, const char *s, unsigned int n) { unsigned int l; l = ft_strlen(s); if (l >= n) { ft_memcpy((void*)(d), (const void*)(s), n); } else { ft_memcpy((void*)(d), (const void*)(s), l); ft_bzero((void*)(d + l), n - l); } return (d); }
C
/* mex Function nakeinterp1.c */ ////////////////////////////////////////////////////////////////////////// // mex function nakeinterp1.c // Dichotomy search of indices // Calling: // idx=nakeinterp1(x, y, xi); // where x, y and xi are double column vectors // x must be sorted in ascending order; x and y have the same length // NO ARGUMENT CHECKING // Compile: // mex -O -v nakeinterp1.c // Author: Bruno Luong // Original: 19/Feb/2009 ////////////////////////////////////////////////////////////////////////// #include "mex.h" #include "matrix.h" // Gateway routine void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]) { const mxArray *xi, *xgrid; mxArray *idx; size_t nx, m, k, i1, i9, imid; double *xiptr, *yptr, *xgridptr, *idxptr; double xik; mwSize dims[2]; // Get inputs and dimensions xgrid = prhs[0]; nx = mxGetM(xgrid); xi = prhs[2]; m = mxGetM(xi); // Create output idx dims[0] = m; dims[1] = 1; plhs[0] = idx = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxREAL); if (idx==NULL) // Cannot allocate memory { // Return empty array dims[0] = 0; dims[1] = 0; plhs[0] = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxREAL); return; } idxptr = mxGetPr(idx); // Get pointers xiptr = mxGetPr(xi); yptr = mxGetPr(prhs[1]); xgridptr = mxGetPr(xgrid); // Loop over the points for (k=m; k--;) // Reverse of for (k=0; k<m; k++) {...} { // Get data value xik = xiptr[k]; i1=0; i9=nx-1; while (i9>i1+1) // Dichotomy search { imid = (i1+i9+1)/2; if (xgridptr[imid]<xik) i1=imid; else i9=imid; } // of while loop if (i1==i9) idxptr[k] = yptr[i1]; else idxptr[k] = yptr[i1] + (yptr[i9]-yptr[i1])*(xik-xgridptr[i1])/(xgridptr[i9]-xgridptr[i1]); } // for loop return; }
C
#include <stdio.h> #include <pthread.h> int global_variable = 0; void* increment_global_var(void* mutex_pointer) { int increment_count, delay_count; mutex_pointer = (pthread_mutex_t*) mutex_pointer; for(increment_count = 0; increment_count < 10; ++increment_count) { // critical section pthread_mutex_lock(mutex_pointer); ++global_variable; // delay for(delay_count = 0; delay_count < 5000000; ++delay_count); pthread_mutex_unlock(mutex_pointer); printf("%d ", global_variable); fflush(stdout); } } int main() { pthread_t thread1, thread2; int return1, return2; pthread_mutex_t mutex; pthread_mutex_init(&mutex, NULL); return1 = pthread_create(&thread1, NULL, increment_global_var, (void*) &mutex); return2 = pthread_create(&thread2, NULL, increment_global_var, (void*) &mutex); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_mutex_destroy(&mutex); printf("\n"); return 0; }
C
/* ** my_str_to_wordtab.c for my_str_to_wordtab in /home/lardet_e/rendu/PSU_2013_minishell2/LIB ** ** Made by lardet ** Login <lardet_e@epitech.net> ** ** Started on Sat Nov 30 16:38:30 2013 lardet ** Last update Sat Nov 30 17:10:00 2013 lardet */ #include <stdlib.h> int is_alpha_n(char c) { if (c >= 33 && c <= 58) return (1); else if (c == 61) return (1); else if (c >= 63 && c <= 123) return (1); else if (c >= 125 && c <= 127) return (1); return (0); } char *my_loop_n(int *j, int i, char *str, char *pointeur) { int k; int h; k = 0; while (is_alpha_n(str[*j]) == 0) *j = *j + 1; h = *j; while (is_alpha_n(str[h]) == 1) { k = k + 1; h = h + 1; } pointeur = malloc(sizeof(char) * k); k = 0; while (is_alpha_n(str[*j]) == 1) { pointeur[k] = str[*j]; *j = *j + 1; k = k + 1; } pointeur[k] = 0; return (pointeur); } char **my_str_to_wordtab_modif(char *str) { char **ptr2; int i; int j; int save_j; char *pointeur; i = 0; j = 0; while (str[i] != 0) { j = (is_alpha_n(str[i]) == 0 && is_alpha_n(str[i + 1]) == 1) ? j + 1 : j; i = i + 1; } save_j = (is_alpha_n(str[0]) == 1) ? j + 1 : j; ptr2 = malloc(sizeof(char *) * save_j); i = 0; j = 0; while (i < save_j) { pointeur = my_loop_n(&j, i, str, pointeur); ptr2[i] = pointeur; i = i + 1; } ptr2[i] = 0; return (ptr2); }
C
/* URI Online Judge | 1046 Game Time Adapted by Neilor Tonin, URI Brazil https://www.urionlinejudge.com.br/judge/en/problems/view/1046 Timelimit: 1 Read the start time and end time of a game, in hours. Then calculate the duration of the game, knowing that the game can begin in a day and finish in another day, with a maximum duration of 24 hours. The message must be printed in portuguese “O JOGO DUROU X HORA(S)” that means “THE GAME LASTED X HOUR(S)” Input Two integer numbers representing the start and end time of a game. Output Print the duration of the game as in the sample output. @author Marcos Lima @profile https://www.urionlinejudge.com.br/judge/pt/profile/242402 @status Accepted @language C (gcc 4.8.5, -O2 -lm) [+0s] @time 0.000s @size 365 Bytes @submission 7/19/18, 8:08:36 PM */ #include <stdio.h> int main() { int inicio, termino; scanf("%d %d", &inicio, &termino); if (inicio == termino) { printf("O JOGO DUROU 24 HORA(S)\n"); } else if (inicio < termino) { printf("O JOGO DUROU %d HORA(S)\n", (termino - inicio)); } else { printf("O JOGO DUROU %d HORA(S)\n", (24 - inicio) + termino); } return 0; }
C
// // Created by cotton on 2020/4/16. // #include <stdio.h> #include <ctype.h> int getch(void); void ungetch(int c); int getint(int *p); int getfloat(float *p); int main() { float a[3]; int i; for (i = 0; getfloat(&a[i]) != EOF; i++) ; for (i = 0; i < 3; i++) { printf("%f\n", a[i]); } } char buf[100]; int bufp = 0; int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } void ungetch(int c) { if (bufp >= 100) { printf("ungetch: too many char"); } else { buf[bufp++] = c; } } int getint(int *pn) { int c; int sign; while (isspace(c = getch())) ; if (!isdigit(c) && c != EOF && c != '+' && c != '-') { ungetch(c); return 0; } sign = (c == '-') ? -1 : 1; if (c == '-' || c == '+') { c = getch(); } for(*pn = 0; isdigit(c); c = getch()) { *pn = *pn * 10 + c - '0'; } *pn *= sign; if (c != EOF) { ungetch(c); } return c; } int getfloat(float *pn) { int c; int sign; int j; while (isspace(c = getch())) ; if (!isdigit(c) && c != EOF && c != '+' && c != '-') { ungetch(c); return 0; } sign = (c == '-') ? -1 : 1; if (c == '-' || c == '+') { c = getch(); } for(*pn = 0; isdigit(c); c = getch()) { *pn = *pn * 10 + c - '0'; } if (c == '.') { c = getch(); } for(j = 1; isdigit(c); c = getch()) { *pn = *pn * 10 + c - '0'; j *= 10; } *pn /= j; *pn *= sign; if (c != EOF) { ungetch(c); } return c; }
C
/* * income.c * * Created on: 8 May 2021 * Author: npenayo */ #include "Income.h" #include "Taxpayer.h" #include "Arrays.h" #include "Validations.h" #include <string.h> #include <stdio_ext.h> #include <stdlib.h> int getId(Income *incomes, int arrLength, char *description, int *output) { int resp = 0; for (int i = 0; i < arrLength; i++) { /*if (!(strcmp(incomes[i].description, description))) { *output = incomes[i].id; resp = 1; break; }*/ } return resp; } int getDescription(Income *incomes, int arrLength, int id, char *output) { int resp = 0; for (int i = 0; i < arrLength; i++) { if (incomes[i].id == id) { //strcpy(output, incomes[i].description); resp = 1; break; } } return resp; } void indexIncomes(Income *incomes, int arrLength) { printf("\n************ Carreras disponibles ************"); printf("\n\n%-15s | %6s", "Codigo_Carrera", "Descripcion"); printf("\n-----------------------------"); for (int i = 0; i < arrLength; i++) { //showincome(incomes[i]); } } void showIncome(Income income) { //printf("\n %6d%10s %-20s", income.id,"",income.description); } int validIncome(Income *incomes, int arrLength, int *output, int max_attempts) { int resp = 0; int valid = 0; int attempts = 0; int isincome; int aux; do { indexIncomes(incomes, arrLength); printf("\nCodigo de carrera: "); __fpurge(stdin); isincome = scanf("%d", &aux); for (int i = 0; i < arrLength; i++) { if (isincome && incomes[i].id == aux) { valid = 1; resp = 1; *output = aux; break; } } if (!valid) { printf("\nError. Carrera invalida"); } attempts++; } while (!valid || attempts >= max_attempts); if (attempts == max_attempts) { system("clear"); printf( "\nCantidad de intentos superada. Presione una tecla para volver al menu"); __fpurge(stdin); getchar(); } return resp; } int createIncome(Income *icList, int icLens, int *id, int index, IcType *tyList, int tyLens, TaxPayer *tpList, int tpLens) { int resp = 0; int id_taxPayer; int month; int id_type; float amount; char surname[STR_LEN]; initializeChar(surname, STR_LEN); printf("\n*************** Alta Contribuyentes *********"); indexTaxpayers(tpList, tpLens); printf("\nEscriba ID de contribuyente: "); __fpurge(stdin); scanf("%d", &id_taxPayer); if (getTaxPayerById(tpList, tpLens, id_taxPayer, &id_taxPayer)) { if (validInt("Mes", "Error.Mes invalido", &month, 1, 12, MAX_ATTEMPTS)) { indexTypes(tyList, tpLens); printf("\nCodigo de tipo: "); scanf("%d", &id_type); if (validType(tyList, tyLens, MAX_ATTEMPTS, &id_type) && validFloat("Importe", "Error.Dato invalido", &amount, 1, 10000, MAX_ATTEMPTS)) { Income newIncome; newIncome.id = *id; *id += 1; newIncome.month = month; newIncome.id_type = id_type; newIncome.id_taxPayer = id_taxPayer; newIncome.amount = amount; icList[index] = newIncome; resp = 1; } } } return resp; } void initializeIncomes(Income *icList, int tsLens) { for (int i = 0; i < tsLens; i++) { icList[i].assigned = 0; } } int getIcUnassigned(Income *icList, int icLens, int *to_assign) { int resp = 0; for (int i = 0; i < icLens; i++) { if (!(icList[i].assigned)) { *to_assign = i; resp = 1; break; } } return resp; } int validType(IcType *list, int lens, int max_attempts, int *output) { int resp = 0; int valid = 0; int attempts = 0; int isType; int aux; do { indexTypes(list, lens); printf("\nCodigo de recaudacion: "); __fpurge(stdin); isType = scanf("%d", &aux); for (int i = 0; i < lens; i++) { if (isType && list[i].id == aux) { valid = 1; resp = 1; *output = aux; break; } } if (!valid) { printf("\nError. Carrera invalida"); } attempts++; } while (!valid || attempts >= max_attempts); if (attempts == max_attempts) { system("clear"); printf( "\nCantidad de intentos superada. Presione una tecla para volver al menu"); __fpurge(stdin); getchar(); } return resp; } void indexTypes(IcType *list, int lens) { printf("\n************ Recaudaciones disponibles ************"); printf("\n\n%-15s | %6s", "Codigo_Recaudacion", "Descripcion"); printf("\n-----------------------------"); for (int i = 0; i < lens; i++) { showType(list[i]); } } void showType(IcType icType) { printf("\n %6d%10s %-20s", icType.id, "", icType.description); }
C
#include <stddef.h> #include <stdbool.h> #include <fllib/Std.h> #include <fllib/Mem.h> #include <fllib/Cstring.h> #include "result.h" FlutAssertResult* flut__assert_int_equals(int expected, int actual) { struct FlutAssertResult *result = flut_assert_result_new(); result->success = expected == actual; if (!result->success) { result->message = fl_cstring_vdup("Expecting int value to be equals to %d, actually %d", expected, actual); } return result; } FlutAssertResult* flut__assert_int_not_equals(int expected, int actual) { struct FlutAssertResult *result = flut_assert_result_new(); result->success = expected != actual; if (!result->success) { result->message = fl_cstring_vdup("Expecting int value to be not-equals to %d, actually %d", expected, actual); } return result; } FlutAssertResult* flut__assert_int_gt(int expected, int actual) { struct FlutAssertResult *result = flut_assert_result_new(); result->success = actual > expected; if (!result->success) { result->message = fl_cstring_vdup("Expecting int value to be greater than %d, actually %d", expected, actual); } return result; } FlutAssertResult* flut__assert_int_gte(int expected, int actual) { struct FlutAssertResult *result = flut_assert_result_new(); result->success = actual >= expected; if (!result->success) { result->message = fl_cstring_vdup("Expecting int value to be greater than or equals to %d, actually %d", expected, actual); } return result; } FlutAssertResult* flut__assert_int_lt(int expected, int actual) { struct FlutAssertResult *result = flut_assert_result_new(); result->success = actual < expected; if (!result->success) { result->message = fl_cstring_vdup("Expecting int value to be lesser than %d, actually %d", expected, actual); } return result; } FlutAssertResult* flut__assert_int_lte(int expected, int actual) { struct FlutAssertResult *result = flut_assert_result_new(); result->success = actual <= expected; if (!result->success) { result->message = fl_cstring_vdup("Expecting int value to be lesser than or equals to %d, actually %d", expected, actual); } return result; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <mpi.h> #include <time.h> long int N; #define PI2 6.2832 void computaDFT(long int ini, int chunk, float *P, float *Xim, float *Xre, float *x){ long int k, n; int auxK; auxK = ini; for(k=0; k<chunk; ++k){ for (n=0 ; n<N ; ++n) Xre[k] += x[n] * cos(n * auxK * PI2 / N); for (n=0 ; n<N ; ++n) Xim[k] -= x[n] * sin(n * auxK * PI2 / N); P[k] = Xre[k]*Xre[k] + Xim[k]*Xim[k]; auxK++; } } int main(int argc, char **argv){ argv+=1; MPI_Init(&argc, &argv); MPI_Comm intercommPai; MPI_Comm_get_parent(&intercommPai); MPI_Request req; N = strtol(argv[2], NULL, 10); long int inicio = strtol(argv[4], NULL, 10); long int fim = strtol(argv[5], NULL, 10); int chunk = fim - inicio; float *x, *Xre, *Xim, *P; long int n; x = malloc(sizeof(float)*chunk); Xre = malloc(sizeof(float)*N); Xim = malloc(sizeof(float)*N); P = malloc(sizeof(float)*chunk); //printf("N %d \tchunk%d \tinit%ld \tend%ld\n", N, chunk, inicio, fim); //for(n=0;n<7;n++) // printf("%s\t", argv[n]); //printf("\n"); MPI_Irecv(&x[0], chunk, MPI_FLOAT, 0, 99, intercommPai, &req); for (n=0 ; n<N ; ++n){ Xre[n] = 0; Xim[n] = 0; } MPI_Wait(&req, MPI_STATUS_IGNORE); computaDFT(inicio, chunk, P, Xim, Xre, x); //MPI_Finalize(); //return 0; MPI_Send(&P[0], chunk, MPI_FLOAT, 0, 99, intercommPai); MPI_Finalize(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int i, j; char p[5] = "lmnop"; char s[7] = "lmmnoop"; int t[strlen(p)][strlen(s)]; for(i = 0 ; i <strlen(s); i++) { t[0][i] = 0; } for(i = 0; i <= strlen(p); i++) { t[i][0]=0; } for(i = 1; i <= strlen(p); i++) { for(j = 1; j <= strlen(s); j++) { if(p[i-1] == s[j-1]) { t[i][j] = 1 + t[i-1][j-1]; } else { if(t[i-1][j]>t[i][j-1]) { t[i][j] = t[i-1][j]; } else { t[i][j]=t[i][j-1]; } } } } printf("%d\n", t[strlen(p)][strlen(s)]); return 0; }
C
/*gpush.c IBM 19.03.1995 H.Schildt interpreter for student studing */ #include "schildt.dfn" void gpush(s) char *s; { extern int gtos; extern char *gstack[]; gtos++; if (gtos == SUB_NEST) { serror(12,"gpush"); return; } gstack[gtos] = s; } /*-------------------------------------------------------*/
C
#include <gtk/gtk.h> #include <ctype.h> #include "Bouttons.h" #include "Var_Global.h" #include "Gtk_Widgets.h" #include "Couleur.h" #include "setColor.h" #include "Gagner.h" // ce fichier contient la fonction executee en cliquant sur entre (saisie d une tentative) void on_Txt_activate (GtkEntry *e){ Tr = 0; // Temps ecoule reinitialiser a 0 for (int i = 0; ttv[i]!='\0'; i++) { if(ttv[i] >= 'a' && ttv[i] <= 'z') { ttv[i] = ttv[i] - 32; // Transforme la tentative en majuscule } } for (int i = 0; ttv[i]!='\0'; i++) { if(!isalpha(ttv[i])) { // Verifie si le mot saisi contient uniquenment des lettres Show_Dialog("Veuiller entrer des lettres\n\nRemarque: Saisir les lettres sans accents si il y en a"); return; } } if(Ortho(ttv)!=1 && Orthographe==1) { // Verifie si le mot saisi est bien orthographie et si l'utilisateur a choisit comme option de prendre en compte l ortographe Show_Dialog("Le mot saisi est mal orthographiee\nou n'existe pas dans le dictionnaire ou est un nom propre\n\n Resaisir s'il vous plait"); return; } for (int i = 0; i<7; i++) { if(strcmp(data[i],ttv)==0 && strcmp(data[i],"temp")!=0) { // pour eviter la resaisie du meme mot Show_Dialog("Le mot est deja saisi!"); return; } } if(strlen(ttv)!=N_Max) { Show_Dialog("Le mot est tres court!"); // oblige le respect de la longueur du mot return; } for (int i = 0; ttv[i]!='\0'; i++) { if(ttv[i] != bien[i] && bien[i]!='-') { // oblige la resaisie d'une lettre deja bien place a sa bonne place Show_Dialog("Le mot doit contenir les lettres deja bien place!!!"); return; } } if(ttv[0]==alea[0]){ Test(alea,ttv,N_Max); bienPlace(alea, ttv, bien, mal, rest, N_Max); // Cette parti fait la gestion de couleur du mot saisi malPlace(alea, ttv, mal, rest, N_Max); Couleur(bien, mal, ttv, clr, N_Max); strcpy(data[i_tent],ttv); switch(i_tent){ // Affiche la ligne par rapport a la tentative actuelle case 1: setColor(ttv,clr,N_Max,i_tent); gtk_label_set_text (GTK_LABEL(T2), "Tentative 2"); char nom[]= "Motus Lettres/00.png"; nom[14] = alea[0]; nom[15] = '2'; gtk_image_set_from_file (GTK_IMAGE( L.i[0]), nom); nom[14] = ttv[0]; if(clr[0]==0){ nom[15] = '0'; }else if(clr[0]==1){ nom[15] = '1'; }else if(clr[0]==2){ nom[15] = '2'; } gtk_image_set_from_file (GTK_IMAGE( L.i[10]), nom); break; case 2: setColor(ttv,clr,N_Max,i_tent); gtk_label_set_text (GTK_LABEL(T3), "Tentative 3"); strcpy(nom, "Motus Lettres/00.png"); nom[14] = ttv[0]; if(clr[0]==0){ nom[15] = '0'; }else if(clr[0]==1){ nom[15] = '1'; }else if(clr[0]==2){ nom[15] = '2'; } gtk_image_set_from_file (GTK_IMAGE( L.i[20]), nom); break; case 3: setColor(ttv,clr,N_Max,i_tent); gtk_label_set_text (GTK_LABEL(T4), "Tentative 4"); strcpy(nom, "Motus Lettres/00.png"); nom[14] = ttv[0]; if(clr[0]==0){ nom[15] = '0'; }else if(clr[0]==1){ nom[15] = '1'; }else if(clr[0]==2){ nom[15] = '2'; } gtk_image_set_from_file (GTK_IMAGE( L.i[30]), nom); break; case 4: setColor(ttv,clr,N_Max,i_tent); gtk_label_set_text (GTK_LABEL(T5), "Tentative 5"); strcpy(nom, "Motus Lettres/00.png"); nom[14] = ttv[0]; if(clr[0]==0){ nom[15] = '0'; }else if(clr[0]==1){ nom[15] = '1'; }else if(clr[0]==2){ nom[15] = '2'; } gtk_image_set_from_file (GTK_IMAGE( L.i[40]), nom); break; case 5: setColor(ttv,clr,N_Max,i_tent); gtk_label_set_text (GTK_LABEL(T6), "Tentative 6"); strcpy(nom, "Motus Lettres/00.png"); nom[14] = ttv[0]; if(clr[0]==0){ nom[15] = '0'; }else if(clr[0]==1){ nom[15] = '1'; }else if(clr[0]==2){ nom[15] = '2'; } gtk_image_set_from_file (GTK_IMAGE( L.i[50]), nom); break; case 6: setColor(ttv,clr,N_Max,i_tent); gtk_label_set_text (GTK_LABEL(T7), "Tentative 7"); strcpy(nom, "Motus Lettres/00.png"); nom[14] = ttv[0]; if(clr[0]==0){ nom[15] = '0'; }else if(clr[0]==1){ nom[15] = '1'; }else if(clr[0]==2){ nom[15] = '2'; } gtk_image_set_from_file (GTK_IMAGE( L.i[60]), nom); break; case 7: setColor(ttv,clr,N_Max,i_tent); Show_Dialog2("Vous avez perdu!\n\nLe mot etait: ",alea); gtk_window_close(GTK_WINDOW(motus_window)); on_V1_clicked(GTK_BUTTON(V1)); break; } strcpy(ttv," "); strcpy(mal,""); // Reinitialiser le variables for(int i=0; i<N_Max;i++){ clr[i] = 0; } i_tent++; gtk_editable_delete_text (GTK_EDITABLE(Txt), 0, -1); } }
C
// HttpUtilParseUri test #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <http/util.h> #include <sysmodule/sysmodule.h> #define HTTP_POOL_SIZE (64 * 1024) #define SSL_POOL_SIZE (256 * 1024) uint8_t httpPool[HTTP_POOL_SIZE]; uint8_t sslPool[SSL_POOL_SIZE]; //typedef struct httpUri httpUri ; int main(int argc,char *argv[]) { int ret; printf("I have no idea what I'm doing...\n"); sysModuleLoad(SYSMODULE_HTTP_UTIL); char* string; uint32_t poolSize = 0; httpUri uri; string = "https://John:Dow@github.com/corporateshark/LUrlParser"; printf("Before httpUtilParseUri\n"); ret = httpUtilParseUri(NULL, string, NULL, 0, &poolSize); if (ret < 0) printf("Error while parsing URI, %s: %d\n",string, ret); void* uriPool = malloc(poolSize); printf("After httpUtilParseUri\n"); ret = httpUtilParseUri(&uri, string, uriPool, poolSize, NULL); if (ret < 0) printf("Error while parsing URI, %s: %d\n",string, ret); //printf("test: %s",(char*)uriPool); printf("scheme: %s\n",uri.scheme); printf("hostname: %s\n",uri.hostname); printf("username: %s\n",uri.username); printf("password: %s\n",uri.password); printf("path: %s\n",uri.path); printf("port: %d\n",uri.port); free(uriPool); return 0; }
C
/************************************************************************* > File Name: test_umask.c > Author: Kangyijie > Mail:Kangyijie5473@gmail.com > Created Time: 2016年07月18日 星期一 20时17分00秒 ************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main(void) { umask(0); if((creat("example",S_IRWXU|S_IRWXO|S_IRWXG)) < 0) { perror("creat"); exit(1); } umask(S_IRWXO); if((creat("example1",S_IRWXU|S_IRWXO|S_IRWXG)) < 0) { perror("creat"); exit(1); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: abadraja <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/18 14:11:02 by abadraja #+# #+# */ /* Updated: 2017/02/13 17:41:24 by abadraja ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/fractol.h" int ft_strcomp(char *s1, char *s2) { int i; size_t k; i = 0; k = 0; while (s1[i] != '\0' && s2[i] != '\0') { if (s1[i] == s2[i]) k++; i++; } if (k == ft_strlen(s1)) return (1); return (0); } int analize(char *str) { if (ft_strcomp(str, JULIA)) return (1); if (ft_strcomp(str, MANDELBROT)) return (1); if (ft_strcomp(str, SHIP)) return (1); return (0); } void ft_exit_fwerror(char *text) { ft_putendl(text); ft_putendl("-> Mandelbrot Set"); ft_putendl("-> Julia Set"); ft_putendl("-> Test Set"); exit(0); } void start(char *s, t_fractol *f) { ft_putendl("========== Welcome =========="); ft_putendl("| P - Start mouse |"); ft_putendl("| O - Pause mouse |"); ft_putendl("| W ,A,S,D - Move |"); ft_putendl("| 1 .. 6 - Colors |"); ft_putendl("| Esc - Exit |"); ft_putendl("| m. wheel - zoom |"); ft_putendl("============================="); if (ft_strcomp(s, JULIA)) start_julia(f); if (ft_strcomp(s, MANDELBROT)) start_mandelbrot(f); if (ft_strcomp(s, SHIP)) start_ship(f); } int main(int ac, char **av) { t_fractol f; if (ac != 2 || !analize(av[1])) ft_exit_fwerror(ERROR); start(av[1], &f); return (0); }
C
#include <stdio.h> #include <math.h> #pragma warning(disable:4996) int Judge3(int n); int Judge2(int m); int Judge1(int k); int Judge3(int n) { /*int ret = m; int count = 0; int num = 0; int i = 0; int flag = 1; int arr[10000]; for (i = 0; i < 10000; i++) { arr[i] = 0; } while (m) { arr[count++] = m % 10; m = m / 10; } for (i = count - 1; i >= 0; i--) { num = arr[i] * flag + num; flag = flag * 10; } if (num == ret) return 0; if (num != ret) return num;*/ int ret = n; int i = 0; int sum = 0; while (n != 0) { if (i == 0) { sum += n % 10; n /= 10; i++; } else { sum = sum * 10 + n % 10; n /= 10; } } if (ret == sum) return 0; return sum; } int Judge2(int m) { int i = 0; //int k = 2; int k = (int)sqrt((double)m); for (i = 2; i <=k; i++) { if (m%i == 0) break; /*if (m%i == 0) break;*/ } if (k < i) return m; return 0; } int Judge1(int k) { int i = 0, flag1 = 0, flag2 = 0, flag3 = 0; int reverse = 0; int count = 0; for (i = 10; i < 1000000; i++) { flag1 = Judge2(i); flag2 = Judge3(i); if (flag1 == 0 || flag2 == 0) continue; reverse = Judge3(i); flag3 = Judge2(reverse); if (flag3 == 0) continue; count++; if (count == k) return i; } } int main() { int k = 0; int ret = 0; scanf("%d", &k); if (k<1 || k>10000) return 0; ret = Judge1(k); printf("%d\n", ret); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> //iloczyn macierzy przez wektor(macierz jednowymiarowa) void wczytaj(FILE *fin, int *wiersze, int *kolumny, float macierz[100][100]){ float liczba = 0; if(fscanf(fin, "%d", wiersze) != 1){ printf("Pierwszy napis nie jest liczba calkowita i nie moze byc liczba wierszy.\n"); exit(-1); } if(fscanf(fin, "%d", kolumny) != 1){ printf("Drugi napis nie jest liczba calkowita i nie moze byc liczba kolumn.\n"); exit(-1); } for(int i=0; i<*wiersze; i++){ for (int j=0; j<*kolumny; j++){ if (fscanf(fin, "%f", &liczba) != 1){ printf("Liczba podana jako element macierzy nie jest liczba zmiennoprzecinkowa.\n"); exit (-2); } macierz[i][j] = liczba; } } } void wypisz_macierz(int *wiersze, int *kolumny, float macierz[100][100]){ int i, j; for (i = 0; i <*wiersze; i++){ printf("["); for (j = 0; j<*kolumny; j++){ printf("%f ", macierz[i][j]); } printf("]\n"); } } void iloczyn_macierzy(int *wiersze1, int *kolumny1, int *wiersze2, int *kolumny2, int *wiersze3, int *kolumny3, float macierz1[100][100], float macierz2[100][100], float macierz3[100][100]){ if(*kolumny1 != *wiersze2){ printf("Tych macierzy nie da sie pomnozyc w tej kolejnosci\n"); exit(-3); } else { *wiersze3 = *wiersze1; *kolumny3 = *kolumny2; int a = 0; for (int i=0; i<*wiersze3; i++){\ int b = 0; for(; a<*wiersze1 && b<*wiersze2;){ macierz3[i][0] += macierz1[a][b] * macierz2[b][0]; b++; } a++; } } } int main(int argc, char *argv[]){ FILE *fin; int wiersze1 = 100; //deklaruje w mainie zeby moc pozniej zmieniac wartosci w funkcjach globalnie, zawsze bede wczytywal macierz o rozmiarach 100x100 bo inaczej poprzestawiaja sie elementy int kolumny1 = 100; int wiersze2 = 100; int kolumny2 = 100; int wiersze3 = 100; int kolumny3 = 100; float macierz1[100][100]; float macierz2[100][100]; float macierz3[100][100]; fin = fopen(argv[1], "r"); wczytaj(fin, &wiersze1, &kolumny1, macierz1); fin = fopen(argv[2], "r"); wczytaj(fin, &wiersze2, &kolumny2, macierz2); if (kolumny2 != 1){ printf("Druga macierz musi byc jednowymiarowa.\n"); } else{ iloczyn_macierzy(&wiersze1, &kolumny1, &wiersze2, &kolumny2, &wiersze3, &kolumny3, macierz1, macierz2, macierz3); wypisz_macierz(&wiersze3, &kolumny3, macierz3); } return 0; }
C
#ifndef HOLBERTON_H #define HOLBERTON_H int _putchar(char c); char *create_array(unsigned int size, char c); /*Creates an array of chars*/ char *_strdup(char *str); /*returns a pointer to a new string which is a duplicate of the string str(its parameter*/ char *str_concat(char *s1, char *s2); /*Concatenates two strings*/ int **alloc_grid(int width, int height); /*returns pointer to a 2 dimensional array of integers*/ void free_grid(int **grid, int height); /*frees 2 dimensional grid*/ char *argstostr(int ac, char **av); /*Concatenates all arguments of your program*/ #endif
C
#include<stdio.h> int main() { int a=5,*aa; aa=&a; a=power(&aa); printf("\na=%d aa=%u",a,aa); } int power(int **ptr) { int b; b=**ptr***ptr; return b; } /* Output: a=25 aa=235822204 */
C
#include <stdio.h> #include <stdlib.h> int main(void) { int n; int *a; int i; int j; int tmp; while (scanf("%d", &n) != -1) { a = malloc(sizeof(int)*n); for (i=0; i<n; ++i) { scanf("%d", &a[i]); } for (j=0; j<7; ++j) { for (i=0; i<n; ++i) { scanf("%d", &tmp); if (a[i] > tmp) a[i] = tmp; } } tmp = 0; for (i=0; i<n; ++i) tmp += a[i]; printf("%d\n", tmp); } return 0; }
C
#include "holberton.h" /** * _strstr - locates a substring * @haystack: the string to search * @needle: the substring to search for in haystack * * Return: pointer to beginning of the located substring */ char *_strstr(char *haystack, char *needle) { int h_ndx, n_ndx; char *point; if (needle[0] == '\0') return (&haystack[0]); h_ndx = 0; while (haystack[h_ndx] != '\0') { if (haystack[h_ndx] == needle[0]) { point = &haystack[h_ndx]; h_ndx += 1; n_ndx = 1; while (needle[n_ndx] != '\0') { if (haystack[h_ndx] == needle[n_ndx]) { h_ndx++; n_ndx++; if (needle[n_ndx + 1] == '\0') return (point); } else break; } } h_ndx++; } return ('\0'); }
C
/* * Verwendung von malloc/realloc: * Speicher nach Bedarf aus dem heap * void* generische Pointer * - nicht dereferenzierbar * - zuweisungskompatibel zu jedem getypten Pointer * - keine Arithmetik * */ #include <stdio.h> #include <stdlib.h> #include "st1f.h" #include "st1io.h" FILE* pf; int anz=0; char vbuf[128]; char weiter='y'; tStud s; int main() { int i; tStud* ps=NULL, *psx; // Einlesen aus Datei pf=fopen("Studs.csv","rt"); if (pf) { anz=getAnz(pf); ps=malloc(anz*sizeof(tStud)); if(ps==0){puts("malloc hat nicht geklappt"); exit(-1);} for (i=0;i<anz;i++)*(ps+i)=readStud(pf); } while (weiter=='y') { s=getStud2(); if(ps==NULL) { ps=malloc(sizeof(tStud)); // Malloc Speicher aus dem heap if (ps==NULL){puts("malloc hat nicht geklappt"); exit(-1);} } else { psx=realloc(ps,(anz+1)*sizeof(tStud)); if(psx) { ps=psx; }else {puts("realloc hat nicht geklappt"); exit(-1);} } *(ps+anz)=s; anz++; for (i=0; i<anz;i++) { putStudp(ps+i); // printf("i: %d, ps+i; %p sizeof: %lu %02lx\n",i,ps +i,sizeof(tStud),sizeof(tStud)); } printf("next (y/n): "); fgets(vbuf,128,stdin);weiter=vbuf[0]; } pf=fopen("Studs.csv","wt"); if(pf) for (i=0; i<anz;i++) { writeStud(pf,ps+i); } for (i=0; i<anz;i++) for (i=0; i<anz;i++) { free((ps+i)->name); } free(ps); return 0; }
C
// // utils.c // p2p // // Created by septimus on 15/7/5. // Copyright (c) 2015年 SEPTIMUS. All rights reserved. // #include "utils.h" void insert_substring(char *a, char *b, int position) { char *f, *e; int length; length = strlen(a); f = substring(a, 1, position - 1 ); e = substring(a, position, length-position+1); strcpy(a, ""); strcat(a, f); free(f); strcat(a, b); strcat(a, e); free(e); } char *substring(char *string, int position, int length) { char *pointer; int c; pointer = malloc(length+1); if( pointer == NULL ) exit(EXIT_FAILURE); for( c = 0 ; c < length ; c++ ) *(pointer+c) = *((string+position-1)+c); *(pointer+c) = '\0'; return pointer; }
C
#include "../inc/uls.h" void print_file_names_l_flag(char **file_names, int name_amnt, int k){ struct stat buf; char *buff_time = (char *)malloc(32 * sizeof(char)); struct passwd *psd; struct group *grp; if(lstat(file_names[k], &buf) == -1){ mx_printerr("stat error\n"); exit(0); } static int total = 0; total += buf.st_blocks; if(name_amnt > 1 || S_ISDIR(buf.st_mode)){ mx_printstr("total "); mx_printstr(mx_itoa(total)); mx_printchar('\n'); } if(S_ISLNK(buf.st_mode)) mx_printchar('l'); else if(S_ISREG(buf.st_mode)) mx_printchar('-'); else if(S_ISDIR(buf.st_mode)) mx_printchar('d'); else if(S_ISCHR(buf.st_mode)) mx_printchar('c'); else if(S_ISBLK(buf.st_mode)) mx_printchar('b'); else if(S_ISFIFO(buf.st_mode)) mx_printchar('f'); else if(S_ISSOCK(buf.st_mode)) mx_printchar('s'); if(buf.st_mode&S_IRUSR) mx_printchar('r'); else mx_printchar('-'); if(buf.st_mode&S_IWUSR) mx_printchar('w'); else mx_printchar('-'); if(buf.st_mode&S_IXUSR) mx_printchar('x'); else mx_printchar('-'); //All group permissions if(buf.st_mode&S_IRGRP) mx_printchar('r'); else mx_printchar('-'); if(buf.st_mode&S_IWGRP) mx_printchar('w'); else mx_printchar('-'); if(buf.st_mode&S_IXGRP) mx_printchar('x'); else mx_printchar('-'); //Other people's rights if(buf.st_mode&S_IROTH) mx_printchar('r'); else mx_printchar('-'); if(buf.st_mode&S_IWOTH) mx_printchar('w'); else mx_printchar('-'); if(buf.st_mode&S_IXOTH) mx_printchar('x'); else mx_printchar('-'); for(int i = 0; i <= 3 - mx_strlen(mx_itoa(buf.st_nlink)); ++i) mx_printchar(' '); mx_printstr(mx_itoa(buf.st_nlink)); psd = getpwuid(buf.st_uid); grp = getgrgid(buf.st_gid); mx_printchar(' '); mx_printstr(psd->pw_name); mx_printstr(" "); mx_printstr(grp->gr_name); for(int i = 0; i <= 6 - mx_strlen(mx_itoa(buf.st_size)); ++i) mx_printchar(' '); mx_printstr(mx_itoa(buf.st_size)); mx_printchar(' '); buff_time = mx_strdup(ctime(&buf.st_mtime)); for(int i = 4; buff_time[i - 3] != ':'; ++i) mx_printchar(buff_time[i]); buff_time[mx_strlen(buff_time) - 1] = '\0'; //Buff time has its own newline, so we need to remove the following newline character mx_printchar(' '); if(name_amnt == 1) mx_printstr(file_names[k]); else print_file_names(file_names, k); mx_printchar('\n'); } void print_file_names(char **file_names, int k){ int file_name_start = 0; for(file_name_start = mx_strlen(file_names[k]); file_names[k][file_name_start] != '/'; --file_name_start); file_name_start++; for(int i = file_name_start; file_names[k][i] != '\0'; ++i) mx_printchar(file_names[k][i]); }
C
#include<stdio.h> int main() { int nHours=40; int nDays=7; float avg=nHours/nDays; // WITHOUT TYPECASTING. printf("%d hours in %d days\n",nHours,nDays); printf("work %.lf hours per day\n",avg); printf("\n\n"); int nHour=40; int nDay=7; float av=nHour/(float)nDay; // WITHOUT TYPECASTING. printf("%d hours in %d days\n",nHour,nDay); printf("work %.lf hours per day\n",av); printf("\n\n"); int nHr=40; int nDy=7; float average=(float)nHr/(float)nDy; // WITHOUT TYPECASTING. printf("%d hours in %d days\n",nHr,nDy); printf("work %.lf hours per day\n",average); return 0; }
C
#include <stdio.h> int main(){ int a,i,j; scanf("%d",&a); a=45*45-a; for(i=1;i<=9;i++)for(j=1;j<=9;j++)if(i*j==a){ printf("%d x %d\n",i,j); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <windows.h> int main(int argc, char **argv) { unsigned int number_of_raw_input_devices; RAWINPUTDEVICELIST *raw_input_device_list; unsigned int raw_input_device_number; GetRawInputDeviceList(NULL, &number_of_raw_input_devices, sizeof(RAWINPUTDEVICELIST)); raw_input_device_list = (RAWINPUTDEVICELIST *)(malloc(sizeof(RAWINPUTDEVICELIST) * number_of_raw_input_devices)); GetRawInputDeviceList(raw_input_device_list, &number_of_raw_input_devices, sizeof(RAWINPUTDEVICELIST)); for (raw_input_device_number = 0; raw_input_device_number < number_of_raw_input_devices; raw_input_device_number++) { int raw_input_device_name_size; char *raw_input_device_name; RID_DEVICE_INFO raw_input_device_info; GetRawInputDeviceInfo(raw_input_device_list[raw_input_device_number].hDevice, RIDI_DEVICENAME, NULL, &raw_input_device_name_size); raw_input_device_name = malloc(raw_input_device_name_size); GetRawInputDeviceInfo(raw_input_device_list[raw_input_device_number].hDevice, RIDI_DEVICENAME, raw_input_device_name, &raw_input_device_name_size); printf("%2d. \"%s\"\n", raw_input_device_number + 1, raw_input_device_name); free(raw_input_device_name); raw_input_device_info.cbSize = sizeof(RID_DEVICE_INFO); GetRawInputDeviceInfo(raw_input_device_list[raw_input_device_number].hDevice, RIDI_DEVICEINFO, &raw_input_device_info, &(raw_input_device_info.cbSize)); switch (raw_input_device_info.dwType) { case RIM_TYPEHID: { printf(" type: human interface device other than keyboard or mouse\n"); break; } case RIM_TYPEKEYBOARD: { printf(" type: keyboard (%d/%d)\n", raw_input_device_info.keyboard.dwType, raw_input_device_info.keyboard.dwSubType); printf(" scan code mode: %d\n", raw_input_device_info.keyboard.dwKeyboardMode); printf(" number of function keys: %d\n", raw_input_device_info.keyboard.dwNumberOfFunctionKeys); printf(" number of indicators: %d\n", raw_input_device_info.keyboard.dwNumberOfIndicators); printf(" total number of keys: %d\n", raw_input_device_info.keyboard.dwNumberOfKeysTotal); break; } case RIM_TYPEMOUSE: { printf(" type: mouse\n"); break; } default: { printf(" type: other raw input device\n"); break; } } printf("\n"); } free(raw_input_device_list); return 0; }
C
#include <stdio.h> char *ft_strlowcase(char *str); int main(int argc, char **argv) { if (argc != 2) { printf("%s\n", "Input a Single String as an Argument"); return (1); } printf("%s\n", ft_strlowcase(argv[1])); return (0); }
C
#include "apue.h" #include <sys/stat.h> #include <sys/types.h> /* determine socket stat members */ int main(void) { struct stat sbuf; int sockfd; bzero(&sbuf, sizeof(struct stat)); if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) err_sys("socket error"); if (fstat(sockfd, &sbuf) == -1) err_sys("fstat error"); printf("TCP socket stat buf\n"); printf("dev: %d ino: %d mode: %d nlink: %d uid: %d gid: %d rdev: %d\n", (int)sbuf.st_dev, (int)sbuf.st_ino, (int)sbuf.st_mode, (int)sbuf.st_nlink,(int)sbuf.st_uid, (int)sbuf.st_gid, (int)sbuf.st_rdev); exit(0); }
C
//Jacky Wong //jagwong@ucsc.edu //ID:1281439 #ifndef __LIST_H__ #define __LIST_H__ #include <stdio.h> typedef struct List *ListRef; typedef struct Node *NodeRef; typedef struct Node { long data; NodeRef next; NodeRef prev; } NodeType; typedef struct List { NodeRef first; NodeRef last; NodeRef current; int length; } ListType; /*** Constructors ***/ ListRef newList(void); void freeList(ListRef L); /*** Access functions ***/ int isEmpty(ListRef L); // returns true is list is empty else returns false. int offEnd(ListRef L); // returns true is current == NULL int atFirst(ListRef L); // returns true if current == first and !offEnd() int atLast(ListRef L); // returns true if current == last and !offEnd() long getFirst(ListRef L); // return the first element; pre: !isEmpty() long getLast(ListRef L); // return the last element; pre: !isEmpty() long getCurrent(ListRef L); // return the current element pre: !offEnd() int getLength(ListRef L); // return the length of the list int equals (ListRef A, ListRef B); // return true iff the two lists have the same keys // in the same order /*** Manipulation procedures ***/ void makeEmpty(ListRef L); // make the list empty. Post: isEmpty() void moveFirst(ListRef L); // set current marker to the first element in the list // Pre: !isEmpty(); Post: !offEnd() void moveLast(ListRef L); // set current marker to the last element in the list // Pre: !isEmpty(); Post: !offEnd() void movePrev(ListRef L); // set current marker one step backward. // Pre: !offEnd(); Post: offEnd() only if atFirst() was true void moveNext(ListRef L); // set current marker one step forward. // Pre: !offEnd(); Post: offEnd() only if atLast() was true void insertBeforeFirst(ListRef L, long data); // Inserts new element before first // Post: !isEmpty() void insertAfterLast(ListRef L, long data); // Inserts new element after last one // Post: !isEmpty() void insertBeforeCurrent(ListRef L, long data); // Inserts new element before current one // Pre: !offEnd(); Post: !isEmpty(), !offEnd() void insertAfterCurrent(ListRef L, long data); // Inserts new element after current one // Pre: !offEnd(); Post: !isEmpty(), !offEnd() void deleteFirst(ListRef L); // delete the first element. Pre: !isEmpty() void deleteLast(ListRef L); // delete the last element. Pre: !isEmpty() void deleteCurrent(ListRef L); // delete the current element. // Pre: !isEmpty(), !offEnd(); Post: offEnd() /*** Other operations ***/ void printList(ListRef L); void printSort(ListRef L); ListRef copyList(ListRef L); #endif
C
#undef TYPENAME #undef TYPEID #define TYPEID char #define TYPENAME char #include "../../generics/gvector/gvector.h" #include "gvector_extension.h" #include "../../generics/gvector/gvector.c" #include "gvector_extension.c" #undef TYPENAME #undef TYPEID #define TYPEID int #define TYPENAME int #include "../../generics/gvector/gvector.h" #include "gvector_extension.h" #include "../../generics/gvector/gvector.c" #include "gvector_extension.c" #undef TYPENAME #undef TYPEID #define TYPEID void_ptr #define TYPENAME void * #include "../../generics/gvector/gvector.h" #include "gvector_extension.h" #include "../../generics/gvector/gvector.c" #include "gvector_extension.c" #include <stdio.h> int main() { vector_char *vchar = vector_char_new(); vector_int *vint = vector_int_new(); vector_void_ptr *vptr = vector_void_ptr_new(); char i; for (i = 'a'; i < 'z'; i++) { vector_char_pushBack(vchar, i); vector_int_pushBack(vint, i); printf("%c added\n", vector_char_back(vchar)); printf("%d added\n", vector_int_back(vint)); } vector_char_free(vchar); vector_int_free(vint); vector_void_ptr_free(vptr); return 0; }
C
/** @file opcontrol.c * @brief File for operator control code * * This file should contain the user operatorControl() function and any functions related to it. * * Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ * * PROS contains FreeRTOS (http://www.freertos.org) whose source code may be * obtained from http://sourceforge.net/projects/freertos/files/ or on request. */ #include "main.h" #include <stdlib.h> #include "chassis.h" #include "lidar.h" #include "wireless.h" #include "usrcmd.h" #include "navigate.h" /* * Runs the user operator control code. This function will be started in its own task with the * default priority and stack size whenever the robot is enabled via the Field Management System * or the VEX Competition Switch in the operator control mode. If the robot is disabled or * communications is lost, the operator control task will be stopped by the kernel. Re-enabling * the robot will restart the task, not resume it from where it left off. * * If no VEX Competition Switch or Field Management system is plugged in, the VEX Cortex will * run the operator control task. Be warned that this will also occur if the VEX Cortex is * tethered directly to a computer via the USB A to A cable without any VEX Joystick attached. * * Code running in this task can take almost any action, as the VEX Joystick is available and * the scheduler is operational. However, proper use of delay() or taskDelayUntil() is highly * recommended to give other tasks (including system tasks such as updating LCDs) time to run. * * This task should never exit; it should end with some kind of infinite loop, even if empty. */ void operatorControl() { int power; int turn; while (1) { power = joystickGetAnalog(CONTROLLER, R_JOY_V); if (power > -25 && power < 25) power = 0; turn = joystickGetAnalog(CONTROLLER, R_JOY_H); if (turn > -25 && turn < 25) turn = 0; //int heading = getHeading(power, turn); //if (isInRange(heading)) { // printf("In range!\n\n"); // blockedHeading = heading; // chassisSet(0,0); chassisSet(power + turn, power - turn); //**** RIGHT BUTTON SET ***** if (joystickGetDigital(CONTROLLER, RIGHT_BUTT_SET, UP_BUTT)) { print("Waiting for info...\n"); while (!fcount(uart2)) { //Do nothing } print("Data found on port!\n"); while (fcount(uart2)) { printf("%c\n", fgetc(uart2)); } print("Done.\n"); } if (joystickGetDigital(CONTROLLER, RIGHT_BUTT_SET, DOWN_BUTT)) { navigate(); } if (joystickGetDigital(CONTROLLER, RIGHT_BUTT_SET, LEFT_BUTT)) { int left = encoderGet(leftEncoder); int right = encoderGet(rightEncoder); printf("Left Encoder: %d\n", left); printf("Right Encoder: %d\n\n", right); encoderReset(leftEncoder); encoderReset(rightEncoder); delay(500); //Debounce } if (joystickGetDigital(CONTROLLER, RIGHT_BUTT_SET, RIGHT_BUTT)) { int target[2]; calcTarget(target); printf("Angle: %d\n", target[0]); delay(100); } //**** LEFT BUTTON SET **** if (joystickGetDigital(CONTROLLER, LEFT_BUTT_SET, UP_BUTT)) { //Prepare lidar data lidarScan(); int * dist = lidarGetDistances(); for (int i = 0; i < 360; i++) { printf("%d\n", dist[i]); } //Send lidar data printf("Sending lidar data"); wirelessSend(dist, 360); //Send target data printf("Sending target data"); int target[2] = {0, 300}; wirelessSend(target, 2); } if (joystickGetDigital(CONTROLLER, LEFT_BUTT_SET, DOWN_BUTT)) { usartInit(uart2, 9600, SERIAL_8N1); double velocities[2]; wirelessRecieve(velocities); printf("Velocities: %lf | %lf\n", velocities[0], velocities[1]); } if (joystickGetDigital(CONTROLLER, LEFT_BUTT_SET, LEFT_BUTT)) { int * dist = lidarGetDistances(); int bufSize = 10; char buf[10]; for (int i = 0; i < 360; i++) { printf("%d\n", dist[i]); snprintf(buf, bufSize, "%d\n", dist[i]); fputs(buf, uart2); } print("Done.\n"); } if (joystickGetDigital(CONTROLLER, LEFT_BUTT_SET, RIGHT_BUTT)) { printf("Left encoder: %d\n", encoderGet(leftEncoder)); printf("Right encoder: %d\n", encoderGet(rightEncoder)); } checkCmds(); delay(20); } }
C
#include <stdio.h> #include "RobustSR.h" // Sign: Entrega 1 si el valor es mayor a cero, cero si vale cero, y -1 si es negativo /* Inputs: X - A matrix with values Output: The sign of values of inputs */ TipoImagenSR sign(TipoImagenSR X) { TipoImagenSR Y; /* Y = (x > 0) ? 1 : ((x<0) ? -1 : 0) */ return Y; }
C
//Recursion- Caliing of function itself in 'C' is called recursion. The best example is factorial. #include<stdio.h> int factorial(int a); int main() { int a; printf("Enter the number: "); scanf("%d",&a); printf("The factorial of %d is %d\n",a,factorial(a)); return 0; } int factorial(int a) { if(a==0 || a==1) { return 1; } else { { return a*factorial(a-1); } } }
C
#include "splaytree.h" Arvore * createArvore(){ //struct No * root; Arvore * nova = malloc(sizeof(Arvore)); nova->root = NULL; return nova; } No * createNo(int info){ /*int info; struct node* esq; struct node* dir; struct node* pai;*/ No * novo = malloc(sizeof(No)); novo->esq = NULL; novo->dir = NULL; novo->info = info; novo->pai = NULL; return novo; } /**___________________________________________________________**/ /*Função para imprimir os nós de uma árvore binária de acordo com um percurso in-ordem!*/ //as outras só mudam o local do printf void imprimir_in_order (Arvore* a, No * n){ if (n != NULL) { imprimir_in_order (a, n->esq); printf("Chave: %d\n", n->info); imprimir_in_order (a, n->dir); } } void imprimir_pre_order (Arvore* a, No * n){ if (n != NULL) { printf("Chave: %d\n", n->info); imprimir_pre_order (a, n->esq); imprimir_pre_order (a, n->dir); } } void imprimir_pos_order (Arvore* a, No * n){ if (n != NULL) { imprimir_pos_order (a, n->esq); imprimir_pos_order (a, n->dir); printf("Chave: %d\n", n->info); } } /**___________________________________________________________**/ //Rotações void rotacao_simples_esq (Arvore* a, No * n){ //A rotacao simples se baseia em saber para qual lado girar //Armazenar os nós importantes e mudar os vetores No * aux = n->dir; n->dir = aux->esq; if(aux->esq != NULL){ aux->esq->pai = n; } aux->pai = n->pai; if(n->pai == NULL) { //quando o no for a raiz a->root = aux; } else if(n == n->pai->esq) { n->pai->esq = aux; } else { //n é o filho da direita n->pai->dir = aux; } aux->esq = n; n->pai = aux; } void rotacao_simples_dir (Arvore* a, No * n){ //Rotacionar para a direita muda a direcao da esq pra dir //printf("Entrou\n"); No * aux = n->esq; n->esq = aux->dir; if(aux->dir != NULL) { aux->dir->pai = n; } aux->pai = n->pai; if(n->pai == NULL) { //se n é raiz a->root = aux; } else if(n == n->pai->dir) { //se n esq é filho n->pai->dir = aux; } else { //n direita n->pai->esq = aux; } aux->dir = n; n->pai = aux; //printf("Saiu\n"); } /**___________________________________________________________**/ Arvore* splayTree (Arvore* a, No * n){ //a ordem da rotação importa MUITO KKKKKKKKKKKKKKKKKKKKKKKKKKKKK //printf("Entrou splay\n"); //Levar o nó do parametro até a raiz while(n->pai != NULL) { //Primeiro caso -> nó é filho da raiz -> rotaciona 1 vez if para ver qual lado if(n->pai == a->root) { if(n == n->pai->esq) { rotacao_simples_dir(a, n->pai); }else { rotacao_simples_esq(a, n->pai); } }else{ //Casos rascunhados no pdf //onde se faz 2 rotações -> depende de como o nó analisado está* No * pai = n->pai; //HORROROSA ESCOLHA DE NOME PRA VARIAVEL MDS No * avo = pai->pai; if(n->pai->esq == n && pai->pai->esq == pai) { rotacao_simples_dir(a, avo); rotacao_simples_dir(a, pai); }else if(n->pai->dir == n && pai->pai->dir == pai) { rotacao_simples_esq(a, avo); rotacao_simples_esq(a, pai); }else if(n->pai->dir == n && pai->pai->esq == pai) { rotacao_simples_esq(a, pai); rotacao_simples_dir(a, avo); }else if(n->pai->esq == n && pai->pai->dir == pai) { rotacao_simples_dir(a, pai); rotacao_simples_esq(a, avo); } } } //printf("saiu do splay\n"); } /**___________________________________________________________**/ //Na arvore criada, insere o no indicado void inserir(Arvore * a, No * n){ //Codigo feito em cima do pseudo código do video -> https://www.youtube.com/watch?v=1HeIZNP3w4A /** Step 1 - Check whether tree is Empty. Step 2 - If tree is Empty then insert the newNode as Root node and exit from the operation. Step 3 - If tree is not Empty then insert the newNode as leaf node using Binary Search tree insertion logic. Step 4 - After insertion, Splay the newNode **/ No * percorrer = NULL; No * temp = a->root; //enquanto o nao tiver chego em NULL quer dizer que ainda tem que percorrer while(temp!=NULL){ percorrer = temp; //analisa para ver se vai para direita ou esquerda -> por ser ABB if(n->info > percorrer->info){ //se a informacao que a gente tem no nosso no for maior que aonde a gente estiver -> ir para direita temp = temp->dir; }else{ //ir para esquerda temp = temp->esq; } } //O percorrer vai ficar sempre no pai do temp //Ai quando o temp chegar no NULL o percorrer vai ser o pai = ultimo Nó possivel //Por isso se o percorrer for igual a NULL a arvore vai ser uma arvore vazia n->pai = percorrer; if(percorrer == NULL){ //n->pai = NULL; //insere na raiz a->root = n; } //Para casos onde a arvore nao é vazia, tem que ver se vai colocar na esquerda ou na direita do ultimo no (percorrer) else if(n->info > percorrer->info){ //se a info do no for maior vai ter que colocar na direita percorrer->dir = n; }else { //infor menor vai pra esquerda percorrer->esq = n; } //depois de achar aonde colocar o novo NO //splay nele para colocar no topo splayTree(a,n); /* if (a == NULL) { a = (Arvore*)malloc(sizeof(Arvore)); a->info = v; a->esq = NULL; a->dir = NULL; a->pai = NULL; } //Verifica por ser ABB //Procura o lugar e realiza o splay else if(valor < a->info){ a->esq = inserir(a, valor); }else if(valor > a->info){ a->dir = inserir(a,valor); } splayTree(a); return a;*/ } No * buscar (Arvore *a, No * n, int procurado){ //Procura nos nós da árvore o valor //depois que acha realiza o splay para organizar a arvore if(n->info = procurado){ splayTree(a,n); return n; }//Busca pelos nos else if(procurado < n->info){ //Chamada recursiva para o próximo nós buscar(a, n->esq, procurado); }else if(procurado > n->info){ buscar(a, n->dir, procurado); }else{ return NULL; //entra quando não encontra } } No * maiorValor(Arvore *a, No * n){ //Como é uma ABB o maior valor sempre será o mais a direita //Logo, devemos percorrer até que o filho a direita seja null //Verifica se tá verifica_arv_vazia while(n->dir != NULL){ n = n->dir; } //retornando o Nó e não o valor como visto nas aulas return(n); } void deletar(Arvore *a, No *n){ //Baseado na forma de deletar que colocar o nó que se quer deletar na raiz com o splay //Depois deletar e juntar as 2 sub árvores criadas pela remoção da raiz //Coloca o nó na raiz splayTree(a,n); //Criando a árvore da esquerda Arvore * arvoreEsquerda = createArvore(); //Aponta a raiz dela para a esquerda da raiz da árvore original arvoreEsquerda->root = a->root->esq; if(arvoreEsquerda->root != NULL) //Se for NULL inicializa o Pai da raiz da árvore para NULL arvoreEsquerda->root->pai = NULL; //criando arvore da direita Arvore * arvoreDireita = createArvore(); //Direita da árvore original vira a árvore da direita arvoreDireita->root = a->root->dir; if(arvoreDireita->root != NULL) arvoreDireita->root->pai = NULL; //Depois de salvar as 2 sub árvores (esquerda e direita da original) //Deleta o nó que a gente queria free(n); //Depois de deletar o nó e ter salvo as informações das sub árvores -> reorganizar a árvore if(arvoreEsquerda->root != NULL) { //Como fazemos do modo de colocar o maior valor da esquerda como a nova raiz No *m = maiorValor(arvoreEsquerda, arvoreEsquerda->root); //Depois de encontrar qual vi ser a nova raiz, leva pra cima com o splay splayTree(arvoreEsquerda, m); //Junta as duas árvores arvoreEsquerda->root->dir = arvoreDireita->root; a->root = arvoreEsquerda->root; } else { //Se a esquerda for NULL -> não vai ter nada para se tornar a nova raiz //Ai a arvore da direita (primeiro valor) vira a raiz a->root = arvoreDireita->root; } } /**___________________________________________________________**/
C
// Chuong trinh dieu khien ON/OFF GPIO2, thoi gian ON/OFF 500ms // Board thu nghiem ESP32 NodeMCU // #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "driver/gpio.h" #define LED_GPIO 2 void blink_task(void *pvParameter) { gpio_set_direction(LED_GPIO, GPIO_MODE_OUTPUT);//Dat chan GPIO2 o che do xuat (OUTPUT). while(1) { //Dat GPIO2 o muc logic 0. gpio_set_level(LED_GPIO, 0); vTaskDelay(500 / portTICK_PERIOD_MS);//delay 1000ms //Dat GPIO2 o muc logic 1. gpio_set_level(LED_GPIO, 1); vTaskDelay(500 / portTICK_PERIOD_MS);//delay 1000ms } } void app_main() { xTaskCreate(&blink_task, "blink_task", 512, NULL, 5, NULL);//Cho phep blink_task thuc hien. }