language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include <cs50.h> typedef unsigned char byte; byte getRed(int color); byte getGreen(int color); byte getBlue(int color); int main(int argc, string argv[]) { if (argc != 2) { printf("usage: ./rgb number\n"); return 1; } int color = atoi(argv[1]); byte red = getRed(color); byte green = getGreen(color); byte blue = getBlue(color); // print each component printf("red:\t%#x\n", red); printf("green:\t%#x\n", green); printf("blue:\t%#x\n", blue); return 0; } byte getRed(int color) { return (byte)(color >> 16); } byte getGreen(int color) { return (byte)(color >> 8); } byte getBlue(int color) { return (byte)color; }
C
#include <stdio.h> #include <stdlib.h> #define CANTIDAD_NUMEROS_ALEATORIOS 10 #define TOPE_SUPERIOR 180 #define TOPE_INFERIOR 4 int main(int argc, char *argv[]) { int numero_aleatorio, semilla, vector_numeros[CANTIDAD_NUMEROS_ALEATORIOS]; int vector_numeros_copia[CANTIDAD_NUMEROS_ALEATORIOS], suma_aux; // Inicializa la semilla de generador de numeros aleatorios printf("Ingrese una semilla para inicializar valor aleatorios: "); scanf("%d", &semilla); srand(semilla); // Genera numeros aleatorios for(int i = 0; i<CANTIDAD_NUMEROS_ALEATORIOS; i++){ numero_aleatorio = rand() % (TOPE_SUPERIOR+1); // genera el numero aleatorio vector_numeros[i] = numero_aleatorio; // lo almacena en el vector } printf("Vector resultante: "); // Muestra el vector resultante for(int i = 0; i<CANTIDAD_NUMEROS_ALEATORIOS; i++){ printf(" [%d] ", vector_numeros[i]); } // Recorremos todas las posiciones del vector copia for(int i = 0; i<CANTIDAD_NUMEROS_ALEATORIOS; i++){ suma_aux = 0; // re inicializamos en cero la suma auxiliar por cada iteracion for(int j = i; j<CANTIDAD_NUMEROS_ALEATORIOS; j++){ // recorremos el vector de numeros, desde la posicion i hasta el final suma_aux += vector_numeros[j]; // y vamos sumando cada valor } vector_numeros_copia[i] = suma_aux;//finalmente almacenamos en la posicion i del vector copia, dicha suma } printf("\nSegundo vector resultante: "); // Muestra el vector resultante for(int i = 0; i<CANTIDAD_NUMEROS_ALEATORIOS; i++){ printf(" [%d] ", vector_numeros_copia[i]); } return 0; }
C
/* Una señal discreta es un conjunto de valores tomados de forma equidistante a partir de una señal continua a intervaos fijos de tamaños Ts Ts= Es el periodo de muestreo */ #include <stdio.h> #include "archivos.h" #include "procesamiento.h" #include <math.h> #include <stdlib.h> int main(int argc, char const *argv[]) { if(argc>0){ register int n=strtol(argv[1],NULL,10); float fn=strtol(argv[2],NULL,10); float x[n+1]; //el numero de muestras que necesito genera_seno(x,n,fn); guarda_datos(x,n); return 0; } }
C
#include "PID.h" void PID_Initialize(PID_Controller * _PID) { // Init all values to zero _PID->sampleError = 0.0f; _PID->deltaInput = 0.0f; _PID->lastError = 0.0f; _PID->PTerm = 0.0f; _PID->ITerm = 0.0f; _PID->DTerm = 0.0f; _PID->controllerOutput = 0.0f; _PID->updates = 0; } double PID_Update(PID_Controller * _PID, double systemFeedback) { double new_i = 0.0f; int windGaurd = 1; // Compute error between set-point and system measurement _PID->sampleError = _PID->setPoint - systemFeedback; // Compute diff from last error if(_PID->kD > 0.0f) _PID->deltaInput = _PID->lastError - _PID->sampleError; // Remember last error value _PID->lastError = _PID->sampleError; // Calculate terms _PID->PTerm = _PID->kP * _PID->sampleError; new_i = _PID->ITerm + (_PID->kI * _PID->deltaTime * _PID->sampleError); if(_PID->kD > 0.0f) _PID->DTerm = _PID->kD * (_PID->deltaInput / _PID->deltaTime); // Sum terms into controller output _PID->controllerOutput = _PID->PTerm + new_i + _PID->DTerm; // Prevent integrator wind-up if(_PID->controllerOutput > _PID->windupMax) { _PID->controllerOutput = _PID->windupMax; if(_PID->sampleError > 0.0f) { windGaurd = 0; } } else if(_PID->controllerOutput < _PID->windupMin) { _PID->controllerOutput = _PID->windupMin; if(_PID->sampleError < 0.0f) { windGaurd = 0; } } if(windGaurd == 1) _PID->ITerm = new_i; _PID->updates++; return _PID->controllerOutput; } void PID_SetSetpoint(PID_Controller * _PID, double newSetpoint) { _PID->setPoint = newSetpoint; } double PID_GetOutput(PID_Controller * _PID) { return _PID->controllerOutput; } void PID_SetOutput(PID_Controller * _PID, double newOutput) { _PID->controllerOutput = newOutput; } double PID_GetSetpoint(PID_Controller * _PID) { return _PID->setPoint; } double PID_GetLastInput(PID_Controller * _PID) { return _PID->lastError; } void PID_SetKp(PID_Controller * _PID, double proportional_gain) { _PID->kP = proportional_gain; } void PID_SetKi(PID_Controller * _PID, double integral_gain) { _PID->kI = integral_gain; } void PID_SetKd(PID_Controller * _PID, double derivative_gain) { _PID->kD = derivative_gain; } void PID_Reset(PID_Controller * _PID) { _PID->sampleError = 0.0f; _PID->deltaInput = 0.0f; _PID->lastError = 0.0f; _PID->controllerOutput = 0.0f; _PID->updates = 0; _PID->PTerm = 0.0f; _PID->ITerm = 0.0f; _PID->DTerm = 0.0f; }
C
#include <stdio.h> #include <stdlib.h> #define MAX_STRING 50 int main() { int numero; printf("Ingrese el numero de caracteres:"); scanf("%d", &numero); numero -= 1; char palabra[numero]; printf("Ingrese la palabra:"); scanf("%s", &palabra); int i; int j = 0; for(i=0; i<=numero;i++){ if(palabra[i] == palabra[numero-i]){ j++; } } if(j == numero+1){ printf("La cadena de caracteres es palindromo"); } else{ printf("La cadena de caracteres no es palindromo"); } }
C
#include <stdio.h> add(int n); int main() { int n, sum; printf("\n\n\t*Welcome! to Akash Addition Calculator*\n\n"); printf("______________________________________________________\n\n"); printf("Enter the number you want the sum of: \n"); scanf("%d", &n); sum = add(n); printf("The sum of the number %d = %d", n, sum); return 0; } int add(int n) { if (n == 0) { return 0; } else { return ((n%10) + (add(n/10))); // in this if the if statement is false it will move to else statement and in this else statement n module 10 give the last digit of number and the add(n/10) divide the number by 10 and remainder until the condition of if becomes true. } }
C
#ifndef _CLOCK_TIMER_H #define _CLOCK_TIMER_H #include <sys/time.h> #define BILLION 1000000000L /* The argument now should be a double (not a pointer to a double) */ #define GET_TIME(now) { \ struct timespec time; \ clock_gettime(CLOCK_MONOTONIC, &time); \ now = time.tv_sec + time.tv_nsec/1000000000.0; \ } #endif //now = time.tv_sec + time.tv_nsec/1000000000.0; //seconds //now = (BILLION * time.tv_sec) + time.tv_nsec; //nanoseconds
C
//#include "list.h" //#include <stdio.h> //#include <stdlib.h> //#include "coordinate.h" /* * Output: * Returns a newly allocated List * Summary: * Allocates space for an empty new List and returns it */ List* ConstructList() { List* result = (List*) malloc(sizeof(List)); if (result != (List*) NULL) { result->head = (ListNode*) NULL; result->size = 0; } return result; } /* * Input: * FILE* fp, a file pointer pointing to a read-only open file * Output: * Returns a newly alllocated list * Summary: * Reads coordinates from a file and puts them in a new List */ List* ReadList(FILE* fp) { int row, col; List* result; if (fp == (FILE*) NULL) { printf("ReadList Error: NULL parameter passed.\n"); exit(EXIT_FAILURE); } result = ConstructList(); while (fscanf(fp, "%d %d", &row, &col) == 2) { PushFrontList(result, ConstructCoordinate(row, col)); } return result; } /* * Input: * List* list, the List to delete * Summary: * Calls free on every node to deallocate memory * used by the nodes of the List, then deallocates * the list itself */ void DeleteList(List* list) { ListNode* current_node = list->head; while (current_node != (ListNode*) NULL) { ListNode* next_node = current_node->next; free(current_node); current_node = next_node; } free(list); return; } /* * Input: * List* list, a List to add data to * Coordinate data, data to add to the list * Output: * Returns the size of list after adding data * Summary: * Adds a data to the front of list */ int PushFrontList(List* list, Coordinate data) { ListNode* new_node = ConstructListNode(data, list->head); if (new_node != (ListNode*) NULL) { list->head = new_node; list->size++; } return list->size; } /* * Input: * List* list, a List to print * Summary: * Prints elements from list, starting with the head */ void PrintList(List* list) { Coordinate C; ListNode* current_node = list->head; while (current_node != (ListNode*) NULL) { C = current_node->data; printf("Coordinate: (%d,%d)\n", C.x, C.y); current_node = current_node->next; } return; } /* * Input: * Coordinate data, data for the ListNode * ListNode* node, the next node after the ListNode * Output: * Returns a ListNode* to a newly allocated ListNode * Summary: * Allocates space for a ListNode and initializes its * data and node members */ ListNode* ConstructListNode(Coordinate data, ListNode* node) { ListNode* list_node = (ListNode*) malloc(sizeof(ListNode)); if (list_node != (ListNode*) NULL) { list_node->data = data; list_node->next = node; } return list_node; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include<assert.h> #define MAX_CHARACTERS 1005 #define MAX_PARAGRAPHS 5 int COUNT = 1; char** split_string(char* s, char d); void print_char_array(char**); char* strip(char*); char* kth_word_in_mth_sentence_of_nth_paragraph(char**** document, int k, int m, int n) { return document[n-1][m-1][k-1]; } char** kth_sentence_in_mth_paragraph(char**** document, int k, int m) { return document[m-1][k-1]; } char*** kth_paragraph(char**** document, int k) { return document[k-1]; } char**** get_document(char* text) { char**** document = NULL; int paragraphs = 1, sentences = 0, words = 0; COUNT = 1; char** p = split_string(text, '\n'); //printf("%i Paragraphs: \n", COUNT-1); //print_char_array(p); paragraphs = COUNT - 1; document = malloc(sizeof(char***)*paragraphs); for (int c=0; c<paragraphs; c++) { COUNT = 1; char** s = split_string(p[c], '.'); //printf("%i Sentences in Paragraph %i: \n", COUNT-1, c+1); //print_char_array(s); sentences = COUNT - 1; document[c] = malloc(sizeof(char**)*sentences); for (int d=0; d<sentences; d++) { COUNT = 1; char** w = split_string(s[d], ' '); //printf("%i words in Sentence %i of Paragraph %i: \n",COUNT-1, d+1, c+1); //print_char_array(w); words = COUNT - 1; document[c][d] = malloc(sizeof(char*)*words); for (int e=0; e<words; e++) { document[c][d][e] = malloc(sizeof(char)*(strlen(w[e])+1)); for (int f=0, z=strlen(w[e]); f<=z; f++) document[c][d][e][f] = w[e][f]; //printf("%s\n", document[c][d][e]); free(w[e]); } } } return document; } char** split_string(char* s, char d) { if (!s || !d) return NULL; char* word = NULL; char** string = NULL; int k=0, l=strlen(s), counter = 0; for (int x=0; x<=l; x++) { if ((s[x] == d || s[x] == '\0') && word != NULL) { string = realloc(string, sizeof(char*)*(COUNT)); if (string == NULL) return NULL; string[COUNT-1] = strip(word); word = NULL; k=0; COUNT++; } else { word = realloc(word, sizeof(char)*(k+2)); if (word == NULL) return NULL; word[k] = s[x]; word[k+1] = '\0'; k++; } } free(s); return string; } void print_char_array(char** sp) { for (int c=0; c<COUNT-1; c++) printf("Item %i: %s\n", c+1, sp[c]); } char* strip(char* word) { if (word == NULL) return NULL; char* new_word = NULL; int start, end, c=2, l = strlen(word); for (start=0; start<l; start++) { if (word[start] != ' ') break; } for (end=l-1; end>=0; end--) { if (word[end] != ' ') break; } for (int d = start; d <= end; d++ ) { new_word = realloc(new_word, sizeof(char)*c); new_word[c-2] = word[d]; new_word[c-1] = '\0'; c++; } free(word); return new_word; } char* get_input_text() { int paragraph_count; scanf("%d", &paragraph_count); char p[MAX_PARAGRAPHS][MAX_CHARACTERS], doc[MAX_CHARACTERS]; memset(doc, 0, sizeof(doc)); getchar(); for (int i = 0; i < paragraph_count; i++) { scanf("%[^\n]%*c", p[i]); strcat(doc, p[i]); if (i != paragraph_count - 1) strcat(doc, "\n"); } char* returnDoc = (char*)malloc((strlen (doc)+1) * (sizeof(char))); strcpy(returnDoc, doc); return returnDoc; } void print_word(char* word) { printf("%s", word); } void print_sentence(char** sentence) { int word_count; scanf("%d", &word_count); for(int i = 0; i < word_count; i++){ printf("%s", sentence[i]); if( i != word_count - 1) printf(" "); } } void print_paragraph(char*** paragraph) { int sentence_count; scanf("%d", &sentence_count); for (int i = 0; i < sentence_count; i++) { print_sentence(*(paragraph + i)); printf("."); } } int main() { char* text = get_input_text(); char**** document = get_document(text); int q; scanf("%d", &q); while (q--) { int type; scanf("%d", &type); if (type == 3){ int k, m, n; scanf("%d %d %d", &k, &m, &n); char* word = kth_word_in_mth_sentence_of_nth_paragraph(document, k, m, n); print_word(word); } else if (type == 2){ int k, m; scanf("%d %d", &k, &m); char** sentence = kth_sentence_in_mth_paragraph(document, k, m); print_sentence(sentence); } else{ int k; scanf("%d", &k); char*** paragraph = kth_paragraph(document, k); print_paragraph(paragraph); } printf("\n"); } }
C
// // menuTest.c // AnalyserDude // // Created by Peter Shaw on 3/9/13. // // #include <stdio.h> #include "../cu/cu.h" #include "../../src/ui/menu.h" static void dummy(void){} TEST(test1) { assertTrue(1); printf("MenuTest test\n"); assertEquals(1, 1); } TEST(test_init_menu) { ui_menu_init(); assertTrue( sizeof(menu->firstentry) == 8); assertTrue( menu->firstentry == menu->lastentry ); } TEST(test_add_elements) { ui_menu_init(); char *text_one; asprintf(&text_one, "A Test Entry"); ui_menu_add(text_one, &dummy); char *text_two; asprintf(&text_two, "A second Test"); ui_menu_add(text_two, &dummy); printf("Data first: %s\n", menu->firstentry->data); printf("Data last: %s\n", menu->lastentry->data); assertFalse( menu->firstentry == menu->lastentry ); assertTrue( menu->firstentry->next == menu->lastentry); } TEST(test_move_around){ ui_menu_init(); char *text_one; asprintf(&text_one, "one"); ui_menu_add(text_one, &dummy); char *text_two; asprintf(&text_two, "two"); ui_menu_add(text_two, &dummy); char *text_three; asprintf(&text_three, "three"); ui_menu_add(text_three, &dummy); menuentry_t *current = menu->firstentry; assertEquals(text_one, current->data); current = current->next; assertEquals(text_two, current->data); current = current->next; assertEquals(text_three, current->data); // move to top on end of menu current = current->next; assertEquals(text_one, current->data); } TEST(test_add_submenu) { ui_menu_init(); char *text_one; asprintf(&text_one, "A Leaf Entry"); ui_menu_add(text_one, &dummy); char *text_two; char *text_two_one; char *text_two_two; asprintf(&text_two, "A Node Entry"); asprintf(&text_two_one, "A Sub Leaf Entry"); asprintf(&text_two_two, "Another Sub Leaf Entry"); menuentry_t *e = ui_menu_add(text_two, &dummy); ui_menu_add_sub(e, text_two_one, &dummy ); ui_menu_add_sub(e, text_two_two, &dummy ); menuentry_t *current = menu->firstentry; assertEquals(text_one, current->data); assertTrue(current->submenu == NULL); current = current->next; assertEquals(text_two, current->data); current = current->submenu; assertEquals(text_two_one, current->data); current = current->next; assertEquals(text_two_two, current->data); } TEST(test_move_around_submenu) { ui_menu_init(); char *text_two; char *text_two_one; char *text_two_two; asprintf(&text_two, "A Node Entry"); asprintf(&text_two_one, "A Sub Leaf Entry"); asprintf(&text_two_two, "Another Sub Leaf Entry"); menuentry_t *e = ui_menu_add(text_two, &dummy); ui_menu_add_sub(e, text_two_one, &dummy ); ui_menu_add_sub(e, text_two_two, &dummy ); menuentry_t *current = menu->firstentry; current = current->submenu; assertEquals(text_two_one, current->data); current = current->next; assertEquals(text_two_two, current->data); // move around current = current->next; assertEquals(text_two_one, current->data); } TEST(test_next_and_enter_submenu) { ui_menu_init(); char *text_one; asprintf(&text_one, "A Leaf Entry"); ui_menu_add(text_one, &dummy); char *text_two; char *text_two_one; char *text_two_two; asprintf(&text_two, "A Node Entry"); asprintf(&text_two_one, "A Sub Leaf Entry"); asprintf(&text_two_two, "Another Sub Leaf Entry"); menuentry_t *e = ui_menu_add(text_two, &dummy); ui_menu_add_sub(e, text_two_one, &dummy ); ui_menu_add_sub(e, text_two_two, &dummy ); assertEquals(text_one, active->data); assertTrue(active->submenu == NULL); ui_menu_next(); assertEquals(text_two, active->data); assertEquals(text_two, ui_menu_show()); printf("text_two> ", ui_menu_show()); ui_menu_enter_submenu(); assertEquals(text_two_one, active->data); assertEquals(text_two_one, ui_menu_show()); printf("text_two_one> ", ui_menu_show()); ui_menu_next(); assertEquals(text_two_two, active->data); assertEquals(text_two_two, ui_menu_show()); printf("text_two_two> ", ui_menu_show()); } TEST(test_next_and_leave_submenu) { ui_menu_init(); char *text_one; asprintf(&text_one, "A Leaf Entry"); ui_menu_add(text_one, &dummy); char *text_two; char *text_two_one; char *text_two_two; asprintf(&text_two, "A Node Entry"); asprintf(&text_two_one, "A Sub Leaf Entry"); asprintf(&text_two_two, "Another Sub Leaf Entry"); menuentry_t *e = ui_menu_add(text_two, &dummy); ui_menu_add_sub(e, text_two_one, &dummy ); ui_menu_add_sub(e, text_two_two, &dummy ); assertEquals(text_one, active->data); assertTrue(active->submenu == NULL); ui_menu_next(); assertEquals(text_two, active->data); // ENTER ui_menu_enter_submenu(); assertEquals(text_two_one, active->data); ui_menu_next(); assertEquals(text_two_two, active->data); // LEAVE ui_menu_leave_submenu(); assertEquals(text_two, active->data); } TEST(test_has_submenu) { ui_menu_init(); char *text_one; asprintf(&text_one, "A Leaf Entry"); ui_menu_add(text_one, &dummy); char *text_two; char *text_two_one; asprintf(&text_two, "A Node Entry"); asprintf(&text_two_one, "A Sub Leaf Entry"); menuentry_t *e = ui_menu_add(text_two, &dummy); ui_menu_add_sub(e, text_two_one, &dummy ); assertEquals(text_one, active->data); assertTrue(active->submenu == NULL); assertFalse(ui_menu_has_submenu()); ui_menu_next(); assertEquals(text_two, active->data); assertTrue(ui_menu_has_submenu()); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "common.h" #include "utils.h" #include "sym.h" #include "types.h" #include "instance.h" #include "absyn.h" #include "table.h" InstanceVar *newInstanceVar(Sym* name, InstanceVar *next, Sym *className, Sym *fileName, int offset) { InstanceVar *tmp = allocate(sizeof(InstanceVar)); tmp->isEmpty = FALSE; tmp->className = className; tmp->fileName = fileName; tmp->name = name; tmp->next = next; tmp->offset = offset; return tmp; } InstanceVar *newEmptyInstanceVar(void) { InstanceVar *tmp; tmp = newInstanceVar(NULL,NULL,NULL,NULL,0); tmp->isEmpty = TRUE; return tmp; } InstanceVar *copyInstanceVar(InstanceVar *src) { InstanceVar *tmp; if ( src->isEmpty ) tmp = newEmptyInstanceVar(); else { tmp = newInstanceVar( src->name, copyInstanceVar(src->next), src->className, src->fileName, src->offset); } return tmp; } int findInstanceVar(InstanceVar* src, Sym *name) { while ( ! src->isEmpty ) { if ( strcmp(symToString(src->name), symToString(name)) == 0 ) { return src->offset; } src = src->next; } return -1; } void replaceInstanceVar(InstanceVar* src, Sym *name, Sym *className, Sym *fileName, int offset) { while( ! src->isEmpty ) { if ( src->offset == offset ) { src->name = name; src->className = className; src->fileName = fileName; return; } src = src->next; } } void appendInstanceVar(InstanceVar* src, Sym *name, Sym *className, Sym *fileName) { if ( src->isEmpty ) { src->isEmpty = FALSE; src->name = name; src->className = className; src->fileName = fileName; src->offset = 0; src->next = newEmptyInstanceVar(); } else { while ( ! src->next->isEmpty ) { src = src->next; } src->next = newInstanceVar(name, src->next, className, fileName, src->offset + 1); } } static void printIndent(int indent) { for (;indent > 0;indent--) { printf(" "); } } void showInstanceVar(InstanceVar* src, int indent) { printIndent(indent); if ( src->isEmpty ) { printf("===== END =====\n"); return; } printf("%d:\t%s(%s)(%s)\n", src->offset, src->name->string, src->className->string, src->fileName->string); showInstanceVar(src->next, indent); } static void traverseBintree(Bintree *bintree, Class *class, Sym *fileName, InstanceVar *attList) { Entry *entry; Sym *name; int offset; if (bintree == NULL) { return; } traverseBintree(bintree->left, class, fileName, attList); entry = bintree->entry; name = bintree->sym; if ( entry->kind == ENTRY_KIND_VARIABLE ) { if ( ! entry->u.variableEntry.isStatic ) { offset = findInstanceVar(attList, name); if (offset >= 0) { replaceInstanceVar(attList, name, class->name, fileName, offset); } else { appendInstanceVar(attList, name, class->name, fileName); } } } traverseBintree(bintree->right, class, fileName, attList); } static void traverseTable(Class *class, Sym *className, Sym *fileName, InstanceVar* instancevar) { traverseBintree(class->mbrTable->bintree, class, fileName, instancevar); } void makeInstanceVariableOffsets(Class *class, char *fileName) { InstanceVar *tmp; /* nothing to do if instance variable offsets already calculated */ if ( class->attibuteList != NULL ) { return; } /* calculate offsets of superclass if it is not done by now */ if ( class->superClass->attibuteList == NULL ) { makeInstanceVariableOffsets(class->superClass, fileName); } tmp = copyInstanceVar(class->superClass->attibuteList); traverseTable(class, class->name, newSym(fileName), tmp); class->attibuteList = tmp; } int countFields(InstanceVar *attList) { int count = 0; while(!attList->isEmpty) { count++; attList = attList->next; } return count; }
C
#include "log.h" #include <stdio.h> #include <stdarg.h> void log_it(const char * prefix, const char * fmt, ...) { fprintf(stderr, "%s: ", prefix); va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); fprintf(stderr, "\n"); }
C
#include "Filter.h" //==================================================================== // 初始化上升沿滤波。 //==================================================================== void InitPosEdge ( tPosEdge * A_pPosEdge, U1 A_bIn ) { A_pPosEdge->last = A_bIn; } //==================================================================== // 更新上升沿滤波。 //==================================================================== U1 PosEdge ( tPosEdge * A_pPosEdge, U1 A_bIn ) { U1 isPosEdge = (!A_pPosEdge->last && A_bIn); A_pPosEdge->last = A_bIn; return isPosEdge; } //==================================================================== // 初始化下降沿滤波。 //==================================================================== void InitNegEdge ( tNegEdge * A_pNegEdge, U1 A_bIn ) { A_pNegEdge->last = A_bIn; } //==================================================================== // 更新下降沿滤波。 //==================================================================== U1 NegEdge ( tNegEdge * A_pNegEdge, U1 A_bIn ) { U1 isNegEdge = (A_pNegEdge->last && !A_bIn); A_pNegEdge->last = A_bIn; return isNegEdge; } //==================================================================== // 初始化平均值滤波。 //==================================================================== void InitMovAve ( tMovAve *A_pMovAve, REAL A_fSampleTime, REAL A_fTimeConstant, REAL A_fIn ) { A_pMovAve->timeConstant = A_fSampleTime / A_fTimeConstant; A_pMovAve->movAve = A_fIn; } //==================================================================== // 更新平均值滤波。 //==================================================================== REAL MovAve ( tMovAve *A_pMovAve, REAL A_fIn ) { A_pMovAve->movAve = A_fIn * A_pMovAve->timeConstant + A_pMovAve->movAve * (1.0 - A_pMovAve->timeConstant); return A_pMovAve->movAve; } //==================================================================== // 初始化真持续时间滤波。 //==================================================================== void InitTrueDuration ( tTrueDuration *A_pTrueDuration, REAL A_fSampleTime, U1 A_bIn) { A_pTrueDuration->sampleTime = A_fSampleTime; A_pTrueDuration->trueSamples = 0; } //==================================================================== // 更新真持续时间滤波。 //==================================================================== REAL TrueDuration ( tTrueDuration *A_pTrueDuration, U1 A_bIn) { if ( !A_bIn ) { A_pTrueDuration->trueSamples = 0; return 0; } else { if (A_pTrueDuration->trueSamples < U16_MAX) { A_pTrueDuration->trueSamples++; } return A_pTrueDuration->sampleTime * A_pTrueDuration->trueSamples; } } //==================================================================== // 初始化双脉冲计数。 //==================================================================== void InitCountDualPulse ( tCountDualPulse * A_pCountDualPulse, REAL Step, REAL Init, U1 A, U1 B) { A_pCountDualPulse->step = Step; A_pCountDualPulse->value = Init; if ( A && B ) { A_pCountDualPulse->state = AllTrue; } else if ( A && ( !B ) ) { A_pCountDualPulse->state = ATBF; } else if ( ( !A ) && B ) { A_pCountDualPulse->state = AFBT; } else if ( ( !A ) && ( !B ) ) { A_pCountDualPulse->state = AllFalse; } A_pCountDualPulse->oldstate = A_pCountDualPulse->state; A_pCountDualPulse->span = 0; } //==================================================================== // 初始化双脉冲计数。 //==================================================================== REAL CountDualPulse(tCountDualPulse * A_pCountDualPulse, U1 A, U1 B) { A_pCountDualPulse->span += 1; if ( A_pCountDualPulse->span >= 1000 ) A_pCountDualPulse->span = 1000; if ( A_pCountDualPulse->oldstate == A_pCountDualPulse->state ) { A_pCountDualPulse->oldstate = A_pCountDualPulse->state; A_pCountDualPulse->step = 10.0/1000;; A_pCountDualPulse->span = 0; } switch ( A_pCountDualPulse->state ) { case AllFalse: if ( A && ( !B ) ) { A_pCountDualPulse->state = CwInc; } else if ( ( !A ) && B ) { A_pCountDualPulse->state = CcwInc; } break; case ATBF: if ( A && B ) { A_pCountDualPulse->state = CwInc; } else if ( ( ! A ) && ( ! B ) ) { A_pCountDualPulse->state = CcwInc; } break; case AllTrue: if ( ( ! A ) && B ) { A_pCountDualPulse->state = CwInc; } else if ( A && ( ! B ) ) { A_pCountDualPulse->state = CcwInc; } break; case AFBT: if ( ( ! A ) && ( ! B ) ) { A_pCountDualPulse->state = CwInc; } else if ( A && B ) { A_pCountDualPulse->state = CcwInc; } break; case CwInc: A_pCountDualPulse->value += A_pCountDualPulse->step; if ( A && B ) { A_pCountDualPulse->state = AllTrue; } else if ( ( ! A ) && ( ! B ) ) { A_pCountDualPulse->state = AllFalse; } else if ( A && ( ! B ) ) { A_pCountDualPulse->state = ATBF; } else if ( ( ! A ) && B ) { A_pCountDualPulse->state = AFBT; } break; case CcwInc: A_pCountDualPulse->value -= A_pCountDualPulse->step; if ( A && B ) { A_pCountDualPulse->state = AllTrue; } else if ( ( ! A ) && ( ! B ) ) { A_pCountDualPulse->state = AllFalse; } else if ( A && ( ! B ) ) { A_pCountDualPulse->state = ATBF; } else if ( ( ! A ) && B ) { A_pCountDualPulse->state = AFBT; } break; } return A_pCountDualPulse->value; } REAL Wrap2PI ( REAL angle ) { while ( angle > pi ) angle = angle - 2*pi; while ( angle < -pi ) angle = angle + 2*pi; return angle; } REAL Wrap22PI ( REAL angle ) { while ( angle > 2*pi ) angle = angle - 2*pi; while ( angle < 0 ) angle = angle + 2*pi; return angle; }
C
/* Auther : Heinz Samuelsson Date : 2013-04-14 File : thread_test1.c Reference : https://computing.llnl.gov/tutorials/pthreads/#Overview Description : Test of threads and function calls. */ #include <stdio.h> // standard I/O routines #include <stdlib.h> // exit functions #include <pthread.h> // pthread functions and data structures #define LOOP1 15000 int counter = 0; int f1() { counter++; printf("----> f1() called no: %d\n",counter); return 1; } void *Thread1(void *threadid) { long tid; int a = 0; tid = (long)threadid; printf("Thread id no %ld started.\n",tid); while (a<5) { for (int i=0; i<LOOP1; i++) { //printf("Outer loop.\n"); for (int j=0; j<LOOP1; j++) { //printf("Inner loop.\n"); } } // do something here a++; printf("--> Thread id no: %ld\n",tid); f1(); } printf("*** Thread id no: %ld has finished ***.\n",tid); return 0; } /* *** MAIN *** */ int main(void) { pthread_t tid1; int rc; long t; t = 1; // create thread rc = pthread_create(&tid1,NULL,Thread1,(void*)t); if (rc) { printf("Error: return code from pthread_create() is %d\n",rc); exit(-1); } printf("*** Thread is now running ***\n"); pthread_exit(NULL); return 0; } /* Result from run: */
C
#include<stdio.h> #include<string.h> /*A program that defines a structure employee containing the details such as empno, empname, department name and salary. The structure has to store 20 employees in an organization. Use the appropriate method to define the above details and define a function that will display the contents?*/ struct employee { int empage, salary; char empname[15]; }e[20]; int main() { int i=0; printf("\nEnter details of employees\n"); while(i<20) { printf("Enter name: "); scanf("%s",e[i].empname); printf("\nEnter age: "); scanf("%d",&e[i].empage); printf("\nEnter salary: "); scanf("%d",&e[i].salary); ++i; } i=0; printf("\n\nDetails of Employees : "); printf("\nName Age Salary\n"); while(i<20) { puts(e[i].empname); printf(" %d",e[i].empage); printf(" %d",e[i].salary); ++i; } return 0; }
C
// // System accessor functions for the Printer Application Framework // // Copyright © 2020-2023 by Michael R Sweet. // // Licensed under Apache License v2.0. See the file "LICENSE" for more // information. // // // Include necessary headers... // #include "system-private.h" #ifdef HAVE_LIBJPEG # include <jpeglib.h> # ifndef JPEG_LIB_VERSION_MAJOR // Added in JPEGLIB 9 # define JPEG_LIB_VERSION_MAJOR 8 # define JPEG_LIB_VERSION_MINOR 0 # endif // !JPEG_LIB_VERSION_MAJOR #endif // HAVE_LIBJPEG #ifdef HAVE_LIBPNG # include <png.h> #endif // HAVE_LIBPNG #ifndef _WIN32 # include <sys/resource.h> #endif // !_WIN32 // // Local functions... // static bool add_listeners(pappl_system_t *system, const char *name, int port, int family); static int compare_filters(_pappl_mime_filter_t *a, _pappl_mime_filter_t *b); static int compare_timers(_pappl_timer_t *a, _pappl_timer_t *b); static _pappl_mime_filter_t *copy_filter(_pappl_mime_filter_t *f); // // 'papplSystemAddListeners()' - Add network or domain socket listeners. // // This function adds socket listeners. The "name" parameter specifies the // listener address. Names starting with a slash (/) specify a UNIX domain // socket path, otherwise the name is treated as a fully-qualified domain name // or numeric IPv4 or IPv6 address. If name is `NULL`, the "any" addresses are // used ("0.0.0.0" and "[::]"). // // Listeners cannot be added after @link papplSystemRun@ is called. // bool // O - `true` on success, `false` on failure papplSystemAddListeners( pappl_system_t *system, // I - System const char *name) // I - Hostname, domain socket filename, or `NULL` { bool ret; // Return value if (!system) { return (false); } else if (system->is_running) { papplLog(system, PAPPL_LOGLEVEL_FATAL, "Tried to add listeners while system is running."); return (false); } #if !_WIN32 if (name && *name == '/') { // Add a domain socket listener... ret = add_listeners(system, name, 0, AF_LOCAL); if (ret && !system->domain_path) system->domain_path = strdup(name); } else #endif // !_WIN32 if (name && isdigit(*name & 255)) { // Add IPv4 listener... if (system->port) { ret = add_listeners(system, name, system->port, AF_INET); } else { int port; // Current port #if _WIN32 port = 7999; #else port = 7999 + (getuid() % 1000); #endif // _WIN32 do { port ++; ret = add_listeners(system, name, port, AF_INET); } while (!ret && port < 10000); if (ret) system->port = port; } } else if (name && *name == '[') { // Add IPv6 listener... if (system->port) { ret = add_listeners(system, name, system->port, AF_INET6); } else { int port; // Current port #if _WIN32 port = 7999; #else port = 7999 + (getuid() % 1000); #endif // _WIN32 do { port ++; ret = add_listeners(system, name, port, AF_INET6); } while (!ret && port < 10000); if (ret) system->port = port; } } else { // Add named listeners on both IPv4 and IPv6... if (system->port) { ret = add_listeners(system, name, system->port, AF_INET) || add_listeners(system, name, system->port, AF_INET6); } else { int port; // Current port #if _WIN32 port = 7999; #else port = 7999 + (getuid() % 1000); #endif // _WIN32 do { port ++; ret = add_listeners(system, name, port, AF_INET); } while (!ret && port < 10000); if (ret) { system->port = port; add_listeners(system, name, port, AF_INET6); } } } return (ret); } // // 'papplSystemAddMIMEFilter()' - Add a file filter to the system. // // This function adds a file filter to the system to be used for processing // different kinds of document data in print jobs. The "srctype" and "dsttype" // arguments specify the source and destination MIME media types as constant // strings. A destination MIME media type of "image/pwg-raster" specifies a // filter that uses the driver's raster interface. Other destination types // imply direct submission to the output device using the `papplDeviceXxx` // functions. // // > Note: This function may not be called while the system is running. // void papplSystemAddMIMEFilter( pappl_system_t *system, // I - System const char *srctype, // I - Source MIME media type (constant) string const char *dsttype, // I - Destination MIME media type (constant) string pappl_mime_filter_cb_t cb, // I - Filter callback function void *data) // I - Filter callback data { _pappl_mime_filter_t key; // Search key if (!system || system->is_running || !srctype || !dsttype || !cb) return; if (!system->filters) system->filters = cupsArrayNew((cups_array_cb_t)compare_filters, NULL, NULL, 0, (cups_acopy_cb_t)copy_filter, (cups_afree_cb_t)free); key.src = srctype; key.dst = dsttype; key.cb = cb; key.cbdata = data; if (!cupsArrayFind(system->filters, &key)) { papplLog(system, PAPPL_LOGLEVEL_DEBUG, "Adding '%s' to '%s' filter.", srctype, dsttype); cupsArrayAdd(system->filters, &key); } } // // 'papplSystemAddTimerCallback()' - Add a timer callback to a system. // // This function schedules a function that will be called on the main run loop // thread at the specified time and optionally every "interval" seconds // thereafter. The timimg accuracy is typically within a few milliseconds but // is not guaranteed. Since the callback is run on the main run loop thread, // functions should create a new thread for any long-running operations. // // The callback function receives the "system" and "cb_data" pointers and // returns `true` to repeat the timer or `false` to remove it: // // ``` // bool my_timer_cb(pappl_system_t *system, void *cb_data) // { // ... do periodic task ... // return (true); // repeat the timer // } // ``` // bool // O - `true` on success, `false` on error papplSystemAddTimerCallback( pappl_system_t *system, // I - System time_t start, // I - Start time in seconds or `0` for the current time int interval, // I - Repeat interval in seconds or `0` for no repeat pappl_timer_cb_t cb, // I - Callback function void *cb_data) // I - Callback data { _pappl_timer_t *newt; // New timer // Range check input... if (!system || !cb || interval < 0) return (false); // Allocate the new timer... if ((newt = calloc(1, sizeof(_pappl_timer_t))) == NULL) return (false); _papplRWLockWrite(system); if (!system->timers) system->timers = cupsArrayNew((cups_array_cb_t)compare_timers, NULL, NULL, 0, NULL, NULL); newt->cb = cb; newt->cb_data = cb_data; newt->next = start ? start : time(NULL) + interval; newt->interval = interval; cupsArrayAdd(system->timers, newt); _papplRWUnlock(system); return (true); } // // '_papplSystemExportVersions()' - Export the firmware versions to IPP attributes... // void _papplSystemExportVersions( pappl_system_t *system, // I - System ipp_t *ipp, // I - IPP message ipp_tag_t group_tag, // I - Group (`IPP_TAG_PRINTER` or `IPP_TAG_SYSTEM`) cups_array_t *ra) // I - Requested attributes or `NULL` for all { cups_len_t i; // Looping var ipp_attribute_t *attr; // Attribute char name[128]; // Attribute name const char *name_prefix = (group_tag == IPP_TAG_PRINTER) ? "printer" : "system"; const char *values[20]; // String values char cups_sversion[32]; // String version of libcups #ifdef HAVE_LIBJPEG char jpeg_sversion[32]; // String version of libjpeg #endif // HAVE_LIBJPEG unsigned short version[4]; // Version of software components // "xxx-firmware-name" snprintf(name, sizeof(name), "%s-firmware-name", name_prefix); if (!ra || cupsArrayFind(ra, name)) { for (i = 0; i < system->num_versions; i ++) values[i] = system->versions[i].name; values[i ++] = "PAPPL"; values[i ++] = "libcups"; #ifdef HAVE_LIBJPEG values[i ++] = "libjpeg"; #endif // HAVE_LIBJPEG #ifdef HAVE_LIBPNG values[i ++] = "libpng"; #endif // HAVE_LIBPNG ippAddStrings(ipp, group_tag, IPP_TAG_NAME, name, i, NULL, values); } // "xxx-firmware-patches" snprintf(name, sizeof(name), "%s-firmware-patches", name_prefix); if (!ra || cupsArrayFind(ra, name)) { for (i = 0; i < system->num_versions; i ++) values[i] = system->versions[i].patches; values[i ++] = ""; // No patches for PAPPL values[i ++] = ""; // No patches for CUPS #ifdef HAVE_LIBJPEG values[i ++] = ""; // No patches for libjpeg #endif // HAVE_LIBJPEG #ifdef HAVE_LIBPNG values[i ++] = ""; // No patches for libpng #endif // HAVE_LIBPNG ippAddStrings(ipp, group_tag, IPP_TAG_TEXT, name, i, NULL, values); } // "xxx-firmware-string-version" snprintf(name, sizeof(name), "%s-firmware-string-version", name_prefix); if (!ra || cupsArrayFind(ra, name)) { for (i = 0; i < system->num_versions; i ++) values[i] = system->versions[i].sversion; values[i ++] = PAPPL_VERSION; snprintf(cups_sversion, sizeof(cups_sversion), "%d.%d.%d", CUPS_VERSION_MAJOR, CUPS_VERSION_MINOR, CUPS_VERSION_PATCH); values[i ++] = cups_sversion; #ifdef HAVE_LIBJPEG snprintf(jpeg_sversion, sizeof(jpeg_sversion), "%d.%d", JPEG_LIB_VERSION_MAJOR, JPEG_LIB_VERSION_MINOR); values[i ++] = jpeg_sversion; #endif // HAVE_LIBJPEG #ifdef HAVE_LIBPNG values[i ++] = png_libpng_ver; #endif // HAVE_LIBPNG ippAddStrings(ipp, group_tag, IPP_TAG_TEXT, name, i, NULL, values); } // "xxx-firmware-version" snprintf(name, sizeof(name), "%s-firmware-version", name_prefix); if (!ra || cupsArrayFind(ra, name)) { for (i = 0, attr = NULL; i < system->num_versions; i ++) { if (attr) ippSetOctetString(ipp, &attr, ippGetCount(attr), system->versions[i].version, (int)sizeof(system->versions[i].version)); else attr = ippAddOctetString(ipp, group_tag, name, system->versions[i].version, (int)sizeof(system->versions[i].version)); } memset(version, 0, sizeof(version)); sscanf(PAPPL_VERSION, "%hu.%hu.%hu", version + 0, version + 1, version + 2); if (attr) ippSetOctetString(ipp, &attr, ippGetCount(attr), version, (int)sizeof(version)); else attr = ippAddOctetString(ipp, group_tag, name, version, (int)sizeof(version)); version[0] = CUPS_VERSION_MAJOR; version[1] = CUPS_VERSION_MINOR; version[2] = CUPS_VERSION_PATCH; ippSetOctetString(ipp, &attr, ippGetCount(attr), version, (int)sizeof(version)); #ifdef HAVE_LIBJPEG version[0] = JPEG_LIB_VERSION_MAJOR; version[1] = JPEG_LIB_VERSION_MINOR; version[2] = 0; ippSetOctetString(ipp, &attr, ippGetCount(attr), version, (int)sizeof(version)); #endif // HAVE_LIBJPEG #ifdef HAVE_LIBPNG memset(version, 0, sizeof(version)); sscanf(png_libpng_ver, "%hu.%hu.%hu", version + 0, version + 1, version + 2); ippSetOctetString(ipp, &attr, ippGetCount(attr), version, (int)sizeof(version)); #endif // HAVE_LIBPNG } } // // '_papplSystemFindMIMEFilter()' - Find a filter for the given source and destination formats. // _pappl_mime_filter_t * // O - Filter data _papplSystemFindMIMEFilter( pappl_system_t *system, // I - System const char *srctype, // I - Source MIME media type string const char *dsttype) // I - Destination MIME media type string { _pappl_mime_filter_t key, // Search key *match; // Matching filter if (!system || !srctype || !dsttype) return (NULL); _papplRWLockRead(system); key.src = srctype; key.dst = dsttype; match = (_pappl_mime_filter_t *)cupsArrayFind(system->filters, &key); _papplRWUnlock(system); return (match); } // // 'papplSystemGetAdminGroup()' - Get the current administrative group, if any. // // This function copies the current administrative group, if any, to the // specified buffer. // char * // O - Admin group or `NULL` if none papplSystemGetAdminGroup( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { _papplRWLockRead(system); if (system->admin_group) { papplCopyString(buffer, system->admin_group, bufsize); ret = buffer; } else *buffer = '\0'; _papplRWUnlock(system); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetAuthService()' - Get the PAM authorization service, if any. // // This function returns the PAM authorization service being used by the system // for authentication, if any. // const char * // O - PAM authorization service or `NULL` if none papplSystemGetAuthService( pappl_system_t *system) // I - System { return (system ? system->auth_service : NULL); } // // 'papplSystemGetContact()' - Get the "system-contact" value. // // This function copies the current system contact information to the specified // buffer. // pappl_contact_t * // O - Contact papplSystemGetContact( pappl_system_t *system, // I - System pappl_contact_t *contact) // O - Contact { if (!system || !contact) { if (contact) memset(contact, 0, sizeof(pappl_contact_t)); return (contact); } _papplRWLockRead(system); *contact = system->contact; _papplRWUnlock(system); return (contact); } // // 'papplSystemGetDefaultPrinterID()' - Get the current "default-printer-id" value. // // This function returns the positive integer identifier for the current // default printer or `0` if there is no default printer. // int // O - "default-printer-id" value papplSystemGetDefaultPrinterID( pappl_system_t *system) // I - System { return (system ? system->default_printer_id : 0); } // // 'papplSystemGetDefaultPrintGroup()' - Get the default print group, if any. // // This function copies the current default print group, if any, to the // specified buffer. // char * // O - Default print group or `NULL` if none papplSystemGetDefaultPrintGroup( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { _papplRWLockRead(system); if (system->default_print_group) { papplCopyString(buffer, system->default_print_group, bufsize); ret = buffer; } else *buffer = '\0'; _papplRWUnlock(system); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetDNSSDName()' - Get the current DNS-SD service name. // // This function copies the current DNS-SD service name of the system, if any, // to the specified buffer. // char * // O - Current DNS-SD service name or `NULL` for none papplSystemGetDNSSDName( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { _papplRWLockRead(system); if (system->dns_sd_name) { papplCopyString(buffer, system->dns_sd_name, bufsize); ret = buffer; } else *buffer = '\0'; _papplRWUnlock(system); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetFooterHTML()' - Get the footer HTML for the web interface, if any. // // This function returns the HTML for the web page footer, if any. The footer // HTML can be set using the @link papplSystemSetFooterHTML@ function. // const char * // O - Footer HTML or `NULL` if none papplSystemGetFooterHTML( pappl_system_t *system) // I - System { return (system ? system->footer_html : NULL); } // // 'papplSystemGetGeoLocation()' - Get the system geo-location string, if any. // // This function copies the current system geographic location as a "geo:" URI // to the specified buffer. // char * // O - "geo:" URI or `NULL` for none papplSystemGetGeoLocation( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { _papplRWLockRead(system); if (system->geo_location) { papplCopyString(buffer, system->geo_location, bufsize); ret = buffer; } else *buffer = '\0'; _papplRWUnlock(system); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetHostname()' - Get the system hostname. // // This function is deprecated. Use the @link papplSystemGetHostName@ function // instead. // // @deprecated@ @exclude all@ // char * // O - Hostname papplSystemGetHostname( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { return (papplSystemGetHostName(system, buffer, bufsize)); } // // 'papplSystemGetHostName()' - Get the system hostname. // // This function copies the current system hostname to the specified buffer. // char * // O - Hostname papplSystemGetHostName( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { _papplRWLockRead(system); if (system->hostname) { papplCopyString(buffer, system->hostname, bufsize); ret = buffer; } else *buffer = '\0'; _papplRWUnlock(system); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetHostPort()' - Get the port number for network connections to // the system. // // This function returns the port number that is used for network connections // to the system. // int // O - Port number papplSystemGetHostPort( pappl_system_t *system) // I - System { return (system ? system->port : 0); } // // 'papplSystemGetLocation()' - Get the system location string, if any. // // This function copies the current human-readable location, if any, to the // specified buffer. // char * // O - Location string or `NULL` for none papplSystemGetLocation( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { _papplRWLockRead(system); if (system->location) { papplCopyString(buffer, system->location, bufsize); ret = buffer; } else *buffer = '\0'; _papplRWUnlock(system); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetLogLevel()' - Get the system log level. // // This function returns the current system log level as an enumeration. // pappl_loglevel_t // O - Log level papplSystemGetLogLevel( pappl_system_t *system) // I - System { return (system ? system->loglevel : PAPPL_LOGLEVEL_UNSPEC); } // // 'papplSystemGetMaxClients()' - Get the maximum number of clients. // // This function gets the maximum number of simultaneous clients that are // allowed by the system. // int // O - Maximum number of clients papplSystemGetMaxClients( pappl_system_t *system) // I - System { return (system ? system->max_clients : 0); } // // 'papplSystemGetMaxImageSize()' - Get the maximum supported size for images. // // This function retrieves the image size limits in bytes (uncompressed), // columns, and lines. // size_t // O - Maximum image size (uncompressed) papplSystemGetMaxImageSize( pappl_system_t *system, // I - System int *max_width, // O - Maximum width in columns int *max_height) // O - Maximum height in lines { size_t max_size; // Maximum image file size // Range check input... if (!system) { if (max_width) *max_width = 0; if (max_height) *max_height = 0; return (0); } // Grab a snapshot of the limits... _papplRWLockRead(system); max_size = system->max_image_size; if (max_width) *max_width = system->max_image_width; if (max_height) *max_height = system->max_image_height; _papplRWUnlock(system); return (max_size); } // // 'papplSystemGetMaxLogSize()' - Get the maximum log file size. // // This function gets the maximum log file size, which is only used when logging // directly to a file. When the limit is reached, the current log file is // renamed to "filename.O" and a new log file is created. Set the maximum size // to `0` to disable log file rotation. // // The default maximum log file size is 1MiB or `1048576` bytes. // size_t // O - Maximum log file size or `0` for none papplSystemGetMaxLogSize( pappl_system_t *system) // I - System { return (system ? system->logmaxsize : 0); } // // 'papplSystemGetMaxSubscriptions()' - Get the maximum number of event subscriptions. // // This function gets the maximum number of event subscriptions that are // allowed. A maximum of `0` means there is no limit. // // The default maximum number of event subscriptions is 100. // size_t // O - Maximum number of subscriptions or `0` papplSystemGetMaxSubscriptions( pappl_system_t *system) // I - System { return (system ? system->max_subscriptions : 0); } // // 'papplSystemGetName()' - Get the system name. // // This function copies the current system name to the specified buffer. // char * // O - Name string papplSystemGetName( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { _papplRWLockRead(system); if (system->name) { papplCopyString(buffer, system->name, bufsize); ret = buffer; } else *buffer = '\0'; _papplRWUnlock(system); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetNextPrinterID()' - Get the next "printer-id" value. // // This function returns the positive integer identifier that will be used for // the next printer that is created. // int // O - Next "printer-id" value papplSystemGetNextPrinterID( pappl_system_t *system) // I - System { return (system ? system->next_printer_id : 0); } // // 'papplSystemGetOptions()' - Get the system options. // // This function returns the system options as a bitfield. // pappl_soptions_t // O - System options papplSystemGetOptions( pappl_system_t *system) // I - System { return (system ? system->options : PAPPL_SOPTIONS_NONE); } // // 'papplSystemGetOrganization()' - Get the system organization string, if any. // // This function copies the current organization name, if any, to the // specified buffer. // char * // O - Organization string or `NULL` for none papplSystemGetOrganization( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { _papplRWLockRead(system); if (system->organization) { papplCopyString(buffer, system->organization, bufsize); ret = buffer; } else *buffer = '\0'; _papplRWUnlock(system); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetOrganizationalUnit()' - Get the system organizational unit string, if any. // // This function copies the current organizational unit name, if any, to the // specified buffer. // char * // O - Organizational unit string or `NULL` for none papplSystemGetOrganizationalUnit( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { _papplRWLockRead(system); if (system->org_unit) { papplCopyString(buffer, system->org_unit, bufsize); ret = buffer; } else *buffer = '\0'; _papplRWUnlock(system); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetPassword()' - Get the current web site access password. // // This function copies the current web site password hash, if any, to the // specified buffer. // // Note: The access password is only used when the PAM authentication service // is not set. // char * // O - Password hash papplSystemGetPassword( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { if (system && buffer && bufsize > 0) { _papplRWLockRead(system); papplCopyString(buffer, system->password_hash, bufsize); _papplRWUnlock(system); } else if (buffer) *buffer = '\0'; return (buffer); } // // 'papplSystemGetPort()' - Get the port number for network connections to the // system. // // This function is deprecated. Use the @link papplSystemGetHostName@ function // instead. // // @deprecated@ @exclude all@ // int // O - Port number papplSystemGetPort( pappl_system_t *system) // I - System { return (system ? system->port : 0); } // // 'papplSystemGetServerHeader()' - Get the Server: header for HTTP responses. // // This function returns the value of the HTTP "Server:" header that is used // by the system. // const char * // O - Server: header string or `NULL` for none papplSystemGetServerHeader( pappl_system_t *system) // I - System { return (system ? system->server_header : NULL); } // // 'papplSystemGetSessionKey()' - Get the current session key. // // This function copies the current session key to the specified buffer. The // session key is used for web interface forms to provide CSRF protection and is // refreshed periodically. // char * // O - Session key papplSystemGetSessionKey( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { time_t curtime = time(NULL); // Current time if (system && buffer && bufsize > 0) { if ((curtime - system->session_time) > 86400) { // Lock for updating the session key with random data... pthread_rwlock_wrlock(&system->session_rwlock); snprintf(system->session_key, sizeof(system->session_key), "%08x%08x%08x%08x%08x%08x%08x%08x", papplGetRand(), papplGetRand(), papplGetRand(), papplGetRand(), papplGetRand(), papplGetRand(), papplGetRand(), papplGetRand()); system->session_time = curtime; } else { // Lock for reading... pthread_rwlock_rdlock(&system->session_rwlock); } papplCopyString(buffer, system->session_key, bufsize); pthread_rwlock_unlock(&system->session_rwlock); } else if (buffer) *buffer = '\0'; return (buffer); } // // 'papplSystemGetTLSOnly()' - Get the TLS-only state of the system. // // This function returns whether the system will only accept encrypted // connections. // bool // O - `true` if the system is only accepting TLS encrypted connections, `false` otherwise papplSystemGetTLSOnly( pappl_system_t *system) // I - System { return (system ? system->tls_only : false); } // // 'papplSystemGetUUID()' - Get the "system-uuid" value. // // This function returns the system's UUID value. // const char * // O - "system-uuid" value papplSystemGetUUID( pappl_system_t *system) // I - System { return (system ? system->uuid : NULL); } // // 'papplSystemGetVersions()' - Get the firmware names and versions. // // This function copies the system firmware information to the specified buffer. // The return value is always the number of firmware versions that have been // set using the @link papplSystemSetVersions@ function, regardless of the // value of the "max_versions" argument. // int // O - Number of firmware versions papplSystemGetVersions( pappl_system_t *system, // I - System int max_versions, // I - Maximum number of versions to return pappl_version_t *versions) // O - Versions array or `NULL` for don't care { if (versions && max_versions > 0) memset(versions, 0, (size_t)max_versions * sizeof(pappl_version_t)); if (system && versions && system->num_versions > 0) { _papplRWLockRead(system); if (max_versions > (int)system->num_versions) memcpy(versions, system->versions, (size_t)system->num_versions * sizeof(pappl_version_t)); else memcpy(versions, system->versions, (size_t)max_versions * sizeof(pappl_version_t)); _papplRWUnlock(system); } return (system ? (int)system->num_versions : 0); } // // 'papplSystemHashPassword()' - Generate a password hash using salt and password strings. // // This function generates a password hash using the "salt" and "password" // strings. The "salt" string should be `NULL` to generate a new password hash // or the value of an existing password hash to verify that a given plaintext // "password" string matches the password hash. // // > Note: Hashed access passwords are only used when the PAM authentication // > service is not set. // char * // O - Hashed password papplSystemHashPassword( pappl_system_t *system, // I - System const char *salt, // I - Existing password hash or `NULL` to generate a new hash const char *password, // I - Plain-text password string char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { if (system && password && buffer && bufsize > 0) { char nonce[100], // Nonce string *ptr, // Pointer into string temp[256]; // Temporary hash unsigned char hash[32]; // SHA2-256 hash if (salt && strchr(salt, '~')) { // Copy existing nonce from the salt string... papplCopyString(nonce, salt, sizeof(nonce)); if ((ptr = strchr(nonce, ':')) != NULL) *ptr = '\0'; } else { // Generate a new random nonce... snprintf(nonce, sizeof(nonce), "%08x%08x", papplGetRand(), papplGetRand()); } snprintf(temp, sizeof(temp), "%s:%s", nonce, password); cupsHashData("sha2-256", temp, strlen(temp), hash, sizeof(hash)); cupsHashString(hash, sizeof(hash), temp, sizeof(temp)); snprintf(buffer, bufsize, "%s~%s", nonce, temp); } else if (buffer) *buffer = '\0'; return (buffer); } // // 'papplSystemIsRunning()' - Return whether the system is running. // // This function returns whether the system is running. // bool // O - `true` if the system is running, `false` otherwise papplSystemIsRunning( pappl_system_t *system) // I - System { bool is_running; // Return value // Range check input if (!system) return (false); _papplRWLockRead(system); is_running = system->is_running; _papplRWUnlock(system); return (is_running); } // // 'papplSystemIsShutdown()' - Return whether the system has been shutdown. // // This function returns whether the system is shutdown or scheduled to // shutdown. // bool // O - `true` if the system is shutdown, `false` otherwise papplSystemIsShutdown( pappl_system_t *system) // I - System { return (system ? (!system->is_running || system->shutdown_time != 0) : false); } // // 'papplSystemIteratePrinters()' - Iterate all of the printers. // // This function iterates each of the printers managed by the system. The // "cb" function is called once per printer with the "system" and "data" values. // void papplSystemIteratePrinters( pappl_system_t *system, // I - System pappl_printer_cb_t cb, // I - Callback function void *data) // I - Callback data { cups_len_t i, // Looping var count; // Number of printers if (!system || !cb) return; // Loop through the printers. // // Note: Cannot use cupsArrayGetFirst/Last since other threads might be // enumerating the printers array. _papplRWLockRead(system); for (i = 0, count = cupsArrayGetCount(system->printers); i < count; i ++) (cb)((pappl_printer_t *)cupsArrayGetElement(system->printers, i), data); _papplRWUnlock(system); } // // 'papplSystemMatchDriver()' - Match a driver to an IEEE-1284 device ID. // const char * papplSystemMatchDriver( pappl_system_t *system, // I - System const char *device_id) // I - IEEE-1284 device ID string { cups_len_t i; // Looping var pappl_pr_driver_t *driver; // Current driver const char *drvstart, // Start of key/value pair *drvend, // End of key/value pair *didptr, // Pointer into device ID *didend; // End of device ID size_t drvlen, // Length of key/value pair didlen; // Length of device ID if (!system) return (NULL); didlen = strlen(device_id); for (i = system->num_drivers, driver = system->drivers; i > 0; i --, driver ++) { if (!driver->device_id) continue; // Parse each of the driver's device ID pairs and compare against the // supplied device ID... drvstart = driver->device_id; while (*drvstart) { // Skip leading semicolons and whitespace (not valid, but sometimes // present...) while (*drvstart == ';' || isspace(*drvstart & 255)) drvstart ++; if (!*drvstart) break; // Find the end of the current key:value pair... drvend = drvstart + 1; while (*drvend && *drvend != ';') drvend ++; if (*drvend == ';') drvend ++; drvlen = (size_t)(drvend - drvstart); // See if this string exists in the target device ID... didptr = device_id; didend = didptr + didlen - drvlen; while (didptr && didptr < didend) { if (!strncmp(didptr, drvstart, drvlen)) break; if ((didptr = strchr(didptr, ';')) != NULL) didptr ++; } if (!didptr || didptr >= didend) break; drvstart = drvend; } if (!*drvstart) break; } if (i > 0) return (driver->name); else return (NULL); } // // '_papplSystemNeedClean()' - Mark the system needing cleaning. // void _papplSystemNeedClean( pappl_system_t *system) // I - System { _papplRWLockWrite(system); if (!system->clean_time) system->clean_time = time(NULL) + 60; _papplRWUnlock(system); } // // 'papplSystemRemoveTimerCallback()' - Remove a timer callback. // // This function removes all matching timer callbacks from the specified system. // Both the callback function and data must match to remove a timer. // void papplSystemRemoveTimerCallback( pappl_system_t *system, // I - System pappl_timer_cb_t cb, // I - Callback function void *cb_data) // I - Callback data { _pappl_timer_t *t; // Current timer // Range check input... if (!system || !cb) return; // Loop through the timers and remove any matches... _papplRWLockWrite(system); for (t = (_pappl_timer_t *)cupsArrayGetFirst(system->timers); t; t = (_pappl_timer_t *)cupsArrayGetNext(system->timers)) { if (t->cb == cb && t->cb_data == cb_data) { cupsArrayRemove(system->timers, t); free(t); } } _papplRWUnlock(system); } // // 'papplSystemSetAdminGroup()' - Set the administrative group. // // This function sets the group name used for administrative requests such as // adding or deleting a printer. // // > Note: The administrative group is only used when the PAM authorization // > service is also set when the system is created. // void papplSystemSetAdminGroup( pappl_system_t *system, // I - System const char *value) // I - Admin group { if (system) { _papplRWLockWrite(system); free(system->admin_group); system->admin_group = value ? strdup(value) : NULL; #if !_WIN32 // TODO: Implement Windows admin group support if (system->admin_group && strcmp(system->admin_group, "none")) { char buffer[8192]; // Buffer for strings struct group grpbuf, // Group buffer *grp = NULL; // Admin group if (getgrnam_r(system->admin_group, &grpbuf, buffer, sizeof(buffer), &grp) || !grp) papplLog(system, PAPPL_LOGLEVEL_ERROR, "Unable to find admin group '%s'.", system->admin_group); else system->admin_gid = grp->gr_gid; } else #endif // !_WIN32 system->admin_gid = (gid_t)-1; _papplSystemConfigChanged(system); _papplRWUnlock(system); } } // // 'papplSystemSetAuthCallback()' - Set an authentication callback for the specified scheme. // // This function sets the authentication callback that is used for Client // requests. The authentication callback is used for every Client request // containing the WWW-Authenticate header (`HTTP_FIELD_WWW_AUTHENTICATE`). // The callback returns one of the following status codes: // // - `HTTP_STATUS_CONTINUE` if the authentication succeeded, // - `HTTP_STATUS_UNAUTHORIZED` if the authentication failed, or // - `HTTP_STATUS_FORBIDDEN` if the authentication succeeded but the user is // not part of the specified group. // void papplSystemSetAuthCallback( pappl_system_t *system, // I - System const char *auth_scheme, // I - Authentication scheme pappl_auth_cb_t auth_cb, // I - Callback function void *auth_cbdata) // I - Callback data { if (system) { _papplRWLockWrite(system); free(system->auth_scheme); system->auth_scheme = auth_scheme ? strdup(auth_scheme) : NULL; system->auth_cb = auth_cb; system->auth_cbdata = auth_cbdata; _papplRWUnlock(system); } } // // 'papplSystemSetContact()' - Set the "system-contact" value. // // This function sets the system contact value. // void papplSystemSetContact( pappl_system_t *system, // I - System pappl_contact_t *contact) // I - Contact { if (!system || !contact) return; _papplRWLockWrite(system); system->contact = *contact; _papplSystemConfigChanged(system); _papplRWUnlock(system); } // // 'papplSystemSetDefaultPrinterID()' - Set the "default-printer-id" value. // // This function sets the default printer using its unique positive integer // identifier. // void papplSystemSetDefaultPrinterID( pappl_system_t *system, // I - System int default_printer_id) // I - "default-printer-id" value { if (system) { _papplRWLockWrite(system); system->default_printer_id = default_printer_id; _papplSystemConfigChanged(system); _papplRWUnlock(system); } } // // 'papplSystemSetDefaultPrintGroup()' - Set the default print group. // // This function sets the default group name used for print requests. // // > Note: The default print group is only used when the PAM authorization // > service is also set when the system is created. // void papplSystemSetDefaultPrintGroup( pappl_system_t *system, // I - System const char *value) // I - Default print group or `NULL` for none { if (system) { _papplRWLockWrite(system); free(system->default_print_group); system->default_print_group = value ? strdup(value) : NULL; _papplSystemConfigChanged(system); _papplRWUnlock(system); } } // // 'papplSystemSetDNSSDName()' - Set the DNS-SD service name. // // This function sets the DNS-SD service name of the system. If `NULL`, the // DNS-SD registration is removed. // void papplSystemSetDNSSDName( pappl_system_t *system, // I - System const char *value) // I - DNS-SD service name or `NULL` for none { if (system) { _papplRWLockWrite(system); free(system->dns_sd_name); system->dns_sd_name = value ? strdup(value) : NULL; system->dns_sd_collision = false; system->dns_sd_serial = 0; _papplSystemConfigChanged(system); if (!value) _papplSystemUnregisterDNSSDNoLock(system); else _papplSystemRegisterDNSSDNoLock(system); _papplRWUnlock(system); } } // // 'papplSystemSetEventCallback()' - Set a callback for monitoring system events. // // This function sets a callback function to receive event notifications from // the system. // void papplSystemSetEventCallback( pappl_system_t *system, // I - System pappl_event_cb_t event_cb, // I - Event callback function void *event_data) // I - Event callback data { if (system && event_cb) { _papplRWLockWrite(system); system->event_cb = event_cb; system->event_data = event_data; _papplRWUnlock(system); } } // // 'papplSystemSetFooterHTML()' - Set the footer HTML for the web interface. // // This function sets the footer HTML for the web interface. // // > Note: The footer HTML can only be set prior to calling // > @link papplSystemRun@. // void papplSystemSetFooterHTML( pappl_system_t *system, // I - System const char *html) // I - Footer HTML or `NULL` for none { if (system && html && !system->is_running) { _papplRWLockWrite(system); free(system->footer_html); system->footer_html = strdup(html); _papplRWUnlock(system); } } // // 'papplSystemSetGeoLocation()' - Set the geographic location string. // // This function sets the geographic location of the system as a "geo:" URI. // If `NULL`, the location is cleared. // void papplSystemSetGeoLocation( pappl_system_t *system, // I - System const char *value) // I - "geo:" URI or `NULL` for none { float lat, lon; // Latitude and longitude from geo: URI // Validate geo-location - must be NULL or a "geo:" URI... if (value && *value && sscanf(value, "geo:%f,%f", &lat, &lon) != 2) return; if (system) { _papplRWLockWrite(system); free(system->geo_location); system->geo_location = value && *value ? strdup(value) : NULL; _papplSystemConfigChanged(system); _papplSystemRegisterDNSSDNoLock(system); _papplRWUnlock(system); } } // // 'papplSystemSetHostname()' - Set the system hostname. // // This function is deprecated. Use the @link papplSystemSetHostName@ function // instead. // // @deprecated@ @exclude all@ // void papplSystemSetHostname( pappl_system_t *system, // I - System const char *value) // I - Hostname or `NULL` for default { papplSystemSetHostName(system, value); } // // '_papplSystemSetHostNameNoLock()' - Set the system hostname without locking. // // This function sets the system hostname. If `NULL`, the default hostname // is used. // void _papplSystemSetHostNameNoLock( pappl_system_t *system, // I - System const char *value) // I - Hostname or `NULL` for default { char temp[1024], // Temporary hostname string *ptr; // Pointer in temporary hostname if (value) { #if !defined(__APPLE__) && !_WIN32 cups_file_t *fp; // Hostname file if ((fp = cupsFileOpen("/etc/hostname", "w")) != NULL) { cupsFilePrintf(fp, "%s\n", value); cupsFileClose(fp); } #endif // !__APPLE__ && !_WIN32 #ifdef HAVE_AVAHI _pappl_dns_sd_t master = _papplDNSSDInit(system); // DNS-SD master reference if (master) avahi_client_set_host_name(master, value); #endif // HAVE_AVAHI #if !_WIN32 sethostname(value, (int)strlen(value)); #endif // !_WIN32 } else { _papplDNSSDCopyHostName(temp, sizeof(temp)); if ((ptr = strstr(temp, ".lan")) != NULL && !ptr[4]) { // Replace hostname.lan with hostname.local papplCopyString(ptr, ".local", sizeof(temp) - (size_t)(ptr - temp)); } else if (!strrchr(temp, '.')) { // No domain information, so append .local to hostname... ptr = temp + strlen(temp); papplCopyString(ptr, ".local", sizeof(temp) - (size_t)(ptr - temp)); } value = temp; } if (system->hostname && strcasecmp(system->hostname, value) && system->is_running) { // Force an update of all DNS-SD registrations... system->dns_sd_host_changes = -1; } // Save the new hostname value free(system->hostname); system->hostname = strdup(value); // Set the system TLS credentials... cupsSetServerCredentials(NULL, system->hostname, 1); } // // 'papplSystemSetHostName()' - Set the system hostname. // // This function sets the system hostname. If `NULL`, the default hostname // is used. // void papplSystemSetHostName( pappl_system_t *system, // I - System const char *value) // I - Hostname or `NULL` for default { if (system) { _papplRWLockWrite(system); _papplSystemSetHostNameNoLock(system, value); _papplRWUnlock(system); } } // // 'papplSystemSetLocation()' - Set the system location string, if any. // // This function sets the human-readable location of the system. If `NULL`, // the location is cleared. // void papplSystemSetLocation( pappl_system_t *system, // I - System const char *value) // I - Location or `NULL` for none { if (system) { _papplRWLockWrite(system); free(system->location); system->location = value ? strdup(value) : NULL; _papplSystemConfigChanged(system); _papplSystemRegisterDNSSDNoLock(system); _papplRWUnlock(system); } } // // 'papplSystemSetLogLevel()' - Set the system log level // // This function sets the log level as an enumeration. // void papplSystemSetLogLevel( pappl_system_t *system, // I - System pappl_loglevel_t loglevel) // I - Log Level { if (system) { _papplRWLockWrite(system); system->loglevel = loglevel; _papplSystemConfigChanged(system); _papplRWUnlock(system); } } // // 'papplSystemSetMaxClients()' - Set the maximum number of clients. // // This function sets the maximum number of simultaneous clients that are // allowed by the system from 0 (auto) to 32768 (half of the available TCP // port numbers). // // The default maximum number of clients is based on available system resources. // void papplSystemSetMaxClients( pappl_system_t *system, // I - System int max_clients) // I - Maximum number of clients or `0` for auto { if (!system) return; if (max_clients <= 0) { // Determine the maximum number of clients to support... #ifdef _WIN32 max_clients = 100; // Use a default of 100... #else struct rlimit file_limits, // Current file descriptor limits mem_limits; // Current memory limits max_clients = 100; // Use a default of 100... if (!getrlimit(RLIMIT_NOFILE, &file_limits) && !getrlimit(RLIMIT_DATA, &mem_limits)) { // Calculate a maximum number of clients... int max_files, max_mem; // Maximum files and memory if (file_limits.rlim_cur != file_limits.rlim_max && file_limits.rlim_cur < 65536) { // Try increasing the limit to the maximum allowed... if (file_limits.rlim_max > 65536) file_limits.rlim_cur = 65536; else file_limits.rlim_cur = file_limits.rlim_max; if (setrlimit(RLIMIT_NOFILE, &file_limits)) getrlimit(RLIMIT_NOFILE, &file_limits); } // Max clients based on file descriptors is 1/2 the limit... if (file_limits.rlim_cur == RLIM_INFINITY) max_files = 32768; else max_files = (int)(file_limits.rlim_cur / 2); // Max clients based on memory is 1/64k the limit... if (mem_limits.rlim_cur == RLIM_INFINITY) max_mem = 32768; else max_mem = (int)(mem_limits.rlim_cur / 65536); // Use min(max_files,max_mem)... if (max_files > max_mem) max_clients = max_mem; else max_clients = max_files; } #endif // _WIN32 } // Restrict max_clients to <= 32768... if (max_clients > 32768) max_clients = 32768; // Set the new value... _papplRWLockWrite(system); system->max_clients = max_clients; _papplSystemConfigChanged(system); _papplRWUnlock(system); } // // 'papplSystemSetMaxImageSize()' - Set the maximum allowed JPEG/PNG image sizes. // // This function sets the maximum size allowed for JPEG and PNG images. The // default limits are 16384x16384 and 1/10th the maximum memory the current // process can use or 1GiB, whichever is less. // void papplSystemSetMaxImageSize( pappl_system_t *system, // I - System size_t max_size, // I - Maximum image size (uncompressed) or `0` for default int max_width, // I - Maximum image width in columns or `0` for default int max_height) // I - Maximum image height in lines or `0` for default { // Range check input... if (!system || max_width < 0 || max_height < 0) return; if (max_size == 0) { // By default, limit images to 1/10th available memory... #if _WIN32 MEMORYSTATUSEX statex; // Memory status if (GlobalMemoryStatusEx(&statex)) max_size = (size_t)statex.ullTotalPhys / 10; else max_size = 16 * 1024 * 1024; #else struct rlimit limit; // Memmory limits if (getrlimit(RLIMIT_DATA, &limit)) max_size = 16 * 1024 * 1024; else max_size = limit.rlim_cur / 10; #endif // _WIN32 } // Don't allow overlarge limits... if (max_size > (1024 * 1024 * 1024)) // Max 1GB total size max_size = 1024 * 1024 * 1024; if (max_width > 65535) // Max 65535 wide max_width = 65535; if (max_height > 65535) // Max 65535 high max_height = 65535; // Update values _papplRWLockWrite(system); system->max_image_size = max_size; system->max_image_width = max_width == 0 ? 16384 : max_width; system->max_image_height = max_height == 0 ? 16384 : max_height; _papplSystemConfigChanged(system); _papplRWUnlock(system); } // // 'papplSystemSetMaxLogSize()' - Set the maximum log file size in bytes. // // This function sets the maximum log file size in bytes, which is only used // when logging directly to a file. When the limit is reached, the current log // file is renamed to "filename.O" and a new log file is created. Set the // maximum size to `0` to disable log file rotation. // // The default maximum log file size is 1MiB or `1048576` bytes. // void papplSystemSetMaxLogSize( pappl_system_t *system, // I - System size_t maxsize) // I - Maximum log size in bytes or `0` for none { if (system) { _papplRWLockWrite(system); system->logmaxsize = maxsize; _papplSystemConfigChanged(system); _papplRWUnlock(system); } } // // 'papplSystemSetMaxSubscriptions()' - Set the maximum number of event subscriptions. // // This function Sets the maximum number of event subscriptions that are // allowed. A maximum of `0` means there is no limit. // // The default maximum number of event subscriptions is `100`. // void papplSystemSetMaxSubscriptions( pappl_system_t *system, // I - System size_t max_subscriptions) // I - Maximum number of subscriptions or `0` for no limit { if (system) { _papplRWLockWrite(system); system->max_subscriptions = max_subscriptions; _papplSystemConfigChanged(system); _papplRWUnlock(system); } } // // 'papplSystemSetMIMECallback()' - Set the MIME typing callback for the system. // // This function sets a custom MIME typing callback for the system. The MIME // typing callback extends the built-in MIME typing support for other media // types that are supported by the application, typically vendor print formats. // // The callback function receives a buffer containing the initial bytes of the // document data, the length of the buffer, and the callback data. It can then // return `NULL` if the content is not recognized or a constant string // containing the MIME media type, for example "application/vnd.hp-pcl" for // HP PCL print data. // void papplSystemSetMIMECallback( pappl_system_t *system, // I - System pappl_mime_cb_t cb, // I - Callback function void *data) // I - Callback data { if (system) { _papplRWLockWrite(system); system->mime_cb = cb; system->mime_cbdata = data; _papplRWUnlock(system); } } // // 'papplSystemSetNetworkCallbacks()' - Set the network configuration callbacks. // // This function sets the network configuration callbacks for a system. The // "get" callback reads the configuration of all network interfaces and stores // them in an array of @link pappl_network_t@ structures that is passed to the // callback. The "set" callback writes the configuration of all network // interfaces and returns a boolean value indicating whether the configuration // has been written successfully. // void papplSystemSetNetworkCallbacks( pappl_system_t *system, // I - System pappl_network_get_cb_t get_cb, // I - "Get networks" callback pappl_network_set_cb_t set_cb, // I - "Set networks" callback void *cb_data) // I - Callback data { // Range check input... if (system && (get_cb != NULL) == (set_cb != NULL)) { _papplRWLockWrite(system); system->network_get_cb = get_cb; system->network_set_cb = set_cb; system->network_cbdata = cb_data; _papplRWUnlock(system); } } // // 'papplSystemSetNextPrinterID()' - Set the next "printer-id" value. // // This function sets the unique positive integer identifier that will be used // for the next printer that is created. It is typically only called as part // of restoring the state of a system. // // > Note: The next printer ID can only be set prior to calling // > @link papplSystemRun@. // void papplSystemSetNextPrinterID( pappl_system_t *system, // I - System int next_printer_id) // I - Next "printer-id" value { if (system && !system->is_running) { _papplRWLockWrite(system); system->next_printer_id = next_printer_id; _papplSystemConfigChanged(system); _papplRWUnlock(system); } } // // 'papplSystemSetOperationCallback()' - Set the IPP operation callback. // // This function sets a custom IPP operation handler for the system that is // called for any IPP operations that are not handled by the built-in IPP // services. // // > Note: The operation callback can only be set prior to calling // > @link papplSystemRun@. // void papplSystemSetOperationCallback( pappl_system_t *system, // I - System pappl_ipp_op_cb_t cb, // I - Callback function void *data) // I - Callback data { if (system && !system->is_running) { _papplRWLockWrite(system); system->op_cb = cb; system->op_cbdata = data; _papplRWUnlock(system); } } // // 'papplSystemSetOrganization()' - Set the system organization string, if any. // // This function sets the organization name for the system. If `NULL`, the // name is cleared. // void papplSystemSetOrganization( pappl_system_t *system, // I - System const char *value) // I - Organization or `NULL` for none { if (system) { _papplRWLockWrite(system); free(system->organization); system->organization = value ? strdup(value) : NULL; _papplSystemConfigChanged(system); _papplRWUnlock(system); } } // // 'papplSystemSetOrganizationalUnit()' - Set the system organizational unit // string, if any. // // This function sets the organizational unit name for the system. If `NULL`, // the name is cleared. // void papplSystemSetOrganizationalUnit( pappl_system_t *system, // I - System const char *value) // I - Organizational unit or `NULL` for none { if (system) { _papplRWLockWrite(system); free(system->org_unit); system->org_unit = value ? strdup(value) : NULL; _papplSystemConfigChanged(system); _papplRWUnlock(system); } } // // 'papplSystemSetPassword()' - Set the access password hash string. // // This function sets the hash for the web access password. The hash string is // generated using the @link papplSystemHashPassword@ function. // // > Note: The access password is only used when the PAM authentication service // > is not set. // void papplSystemSetPassword( pappl_system_t *system, // I - System const char *hash) // I - Hash string { if (system && hash) { _papplRWLockWrite(system); papplCopyString(system->password_hash, hash, sizeof(system->password_hash)); _papplSystemConfigChanged(system); _papplRWUnlock(system); } } // // 'papplSystemSetPrinterDrivers()' - Set the list of drivers and the driver // callbacks. // // This function sets the lists of printer drivers, the optional auto-add // callback function, the optional creation callback, and the required driver // initialization callback function. // // The auto-add callback ("autoadd_cb") finds a compatible driver name for the // specified printer. It is used when the client or user specifies the "auto" // driver name, and for the "autoadd" sub-command for the `papplMainloop` API. // // The creation callback ("create_cb") is called at the end of printer creation // to make any common changes or additions to a new printer. It is typically // used to add extra web pages, add per-printer static resources, and/or // initialize the contact and location information. // // The driver initialization callback ("driver_cb") is called to initialize the // `pappl_pr_driver_data_t` structure, which provides all of the printer // capabilities and callbacks for printing. // void papplSystemSetPrinterDrivers( pappl_system_t *system, // I - System int num_drivers, // I - Number of drivers pappl_pr_driver_t *drivers, // I - Drivers pappl_pr_autoadd_cb_t autoadd_cb, // I - Auto-add callback function or `NULL` if none pappl_pr_create_cb_t create_cb, // I - Printer creation callback function or `NULL` if none pappl_pr_driver_cb_t driver_cb, // I - Driver initialization callback function void *data) // I - Callback data { if (system) { _papplRWLockWrite(system); system->num_drivers = (cups_len_t)num_drivers; system->drivers = drivers; system->autoadd_cb = autoadd_cb; system->create_cb = create_cb; system->driver_cb = driver_cb; system->driver_cbdata = data; _papplRWUnlock(system); } } // // 'papplSystemSetSaveCallback()' - Set the save callback. // // This function sets a callback that is used to periodically save the current // system state. Typically the callback function ("cb") is // @link papplSystemSaveState@ and the callback data ("data") is the name of // the state file: // // ``` // |papplSystemSetSaveCallback(system, (pappl_save_cb_t)papplSystemSaveState, // | (void *)filename); // ``` // // > Note: The save callback can only be set prior to calling // > @link papplSystemRun@. // void papplSystemSetSaveCallback( pappl_system_t *system, // I - System pappl_save_cb_t cb, // I - Callback function void *data) // I - Callback data { if (system && !system->is_running) { _papplRWLockWrite(system); system->save_cb = cb; system->save_cbdata = data; _papplRWUnlock(system); } } // // 'papplSystemSetUUID()' - Set the system UUID. // // This function sets the system UUID value, overriding the default (generated) // value. It is typically used when restoring the state of a previous // incarnation of the system. // // > Note: The UUID can only be set prior to calling @link papplSystemRun@. // void papplSystemSetUUID( pappl_system_t *system, // I - System const char *value) // I - UUID { if (system && !system->is_running) { _papplRWLockWrite(system); free(system->uuid); if (value) { system->uuid = strdup(value); } else { char uuid[64]; // UUID value _papplSystemMakeUUID(system, NULL, 0, uuid, sizeof(uuid)); system->uuid = strdup(uuid); } _papplSystemRegisterDNSSDNoLock(system); _papplRWUnlock(system); } } // // 'papplSystemSetVersions()' - Set the firmware names and versions. // // This function sets the names and versions of each firmware/software component // of the printer application. // void papplSystemSetVersions( pappl_system_t *system, // I - System int num_versions, // I - Number of versions pappl_version_t *versions) // I - Firmware versions { if (system && num_versions && versions) { _papplRWLockWrite(system); if (num_versions > (int)(sizeof(system->versions) / sizeof(system->versions[0]))) system->num_versions = sizeof(system->versions) / sizeof(system->versions[0]); else system->num_versions = (cups_len_t)num_versions; memcpy(system->versions, versions, (size_t)system->num_versions * sizeof(pappl_version_t)); _papplRWUnlock(system); } } // // 'papplSystemSetWiFiCallbacks()' - Set Wi-Fi callbacks. // // This function sets the 802.11 Wi-Fi interface callbacks for the system. The // "join_cb" is used to join a Wi-Fi network, the "list_cb" is used to list // available networks, and the "status_cb" is used to query the current Wi-Fi // network connection status and Secure Set Identifier (SSID). The "join_cb" // and "status_cb" functions are used to support getting and setting the IPP // "printer-wifi-state", "printer-wifi-ssid", and "printer-wifi-password" // attributes, while the "list_cb" function enables changing the Wi-Fi network // from the network web interface, if enabled. // // Note: The Wi-Fi callbacks can only be set prior to calling // @link papplSystemRun@. // void papplSystemSetWiFiCallbacks( pappl_system_t *system, // I - System pappl_wifi_join_cb_t join_cb, // I - Join callback pappl_wifi_list_cb_t list_cb, // I - List callback pappl_wifi_status_cb_t status_cb, // I - Status callback void *data) // I - Callback data pointer { if (system && !system->is_running && join_cb && status_cb) { _papplRWLockWrite(system); system->wifi_join_cb = join_cb; system->wifi_list_cb = list_cb; system->wifi_status_cb = status_cb; system->wifi_cbdata = data; _papplRWUnlock(system); } } // // 'add_listeners()' - Create and add listener sockets to a system. // static bool // O - `true` on success or `false` on failure add_listeners( pappl_system_t *system, // I - System const char *name, // I - Host name or `NULL` for any address int port, // I - Port number int family) // I - Address family { bool ret = false; // Return value int sock; // Listener socket http_addrlist_t *addrlist, // Listen addresses *addr; // Current address char service[255]; // Service port if (name && (!strcmp(name, "*") || !*name)) name = NULL; snprintf(service, sizeof(service), "%d", port); if ((addrlist = httpAddrGetList(name, family, service)) == NULL) { if (name && *name == '/') papplLog(system, PAPPL_LOGLEVEL_INFO, "Unable to lookup address(es) for '%s': %s", name, cupsGetErrorString()); else papplLog(system, PAPPL_LOGLEVEL_INFO, "Unable to lookup address(es) for '%s:%d': %s", name ? name : "*", port, cupsGetErrorString()); } else { for (addr = addrlist; addr && system->num_listeners < _PAPPL_MAX_LISTENERS; addr = addr->next) { if ((sock = httpAddrListen(&(addrlist->addr), port)) < 0) { char temp[256]; // String address if (system->port) { if (name && *name == '/') papplLog(system, PAPPL_LOGLEVEL_ERROR, "Unable to create listener socket for '%s': %s", name, cupsGetErrorString()); else papplLog(system, PAPPL_LOGLEVEL_ERROR, "Unable to create listener socket for '%s:%d': %s", httpAddrGetString(&addr->addr, temp, (cups_len_t)sizeof(temp)), system->port, cupsGetErrorString()); } } else { ret = true; system->listeners[system->num_listeners].fd = sock; system->listeners[system->num_listeners ++].events = POLLIN; if (name && *name == '/') papplLog(system, PAPPL_LOGLEVEL_INFO, "Listening for connections on '%s'.", name); else papplLog(system, PAPPL_LOGLEVEL_INFO, "Listening for connections on '%s:%d'.", name ? name : "*", port); } } httpAddrFreeList(addrlist); } return (ret); } // // 'compare_filters()' - Compare two filters. // static int // O - Result of comparison compare_filters(_pappl_mime_filter_t *a,// I - First filter _pappl_mime_filter_t *b)// I - Second filter { int result = strcmp(a->src, b->src); if (!result) result = strcmp(a->dst, b->dst); return (result); } // // 'compare_timers()' - Compare two timers. // static int // O - Result of comparison compare_timers(_pappl_timer_t *a, // I - First timer _pappl_timer_t *b) // I - Second timer { if (a->next < b->next) return (-1); else if (a->next > b->next) return (1); else if (a < b) return (-1); else if (a > b) return (1); else return (0); } // // 'copy_filter()' - Copy a filter definition. // static _pappl_mime_filter_t * // O - New filter copy_filter(_pappl_mime_filter_t *f) // I - Filter definition { _pappl_mime_filter_t *newf = calloc(1, sizeof(_pappl_mime_filter_t)); // New filter if (newf) memcpy(newf, f, sizeof(_pappl_mime_filter_t)); return (newf); }
C
// // main.c // CPULab // // Created by Maor Zeevi on 6/16/19. // Copyright © 2019 Meir Zeevi. All rights reserved. // #include "oslabs.h" #include <stdio.h> #include <string.h> struct PCB handle_process_arrival_pp(struct PCB ready_queue[QUEUEMAX], int *queue_cnt, struct PCB current_process, struct PCB new_process, int timestamp) { if ((current_process.process_id == 0) && (current_process.total_bursttime == 0) && (current_process.execution_endtime == 0) && (current_process.remaining_bursttime == 0) && (current_process.execution_starttime == 0) && (current_process.arrival_timestamp == 0) && (current_process.process_priority == 0)) {// NULLPCB , New process priorty new_process.execution_starttime = timestamp; new_process.execution_endtime = timestamp + new_process.total_bursttime; new_process.remaining_bursttime = new_process.total_bursttime; return new_process; } else if ( new_process.process_priority >= current_process.process_priority) { //New process goes to queue new_process.execution_starttime = 0; new_process.execution_endtime = 0; new_process.remaining_bursttime = new_process.total_bursttime; ready_queue[*queue_cnt] = new_process; *queue_cnt = *queue_cnt + 1; return current_process; } else { //current process goes to queue new_process.execution_starttime = timestamp; new_process.execution_endtime = timestamp + new_process.total_bursttime; new_process.remaining_bursttime = new_process.total_bursttime; current_process.remaining_bursttime = current_process.execution_endtime - timestamp; current_process.execution_endtime = 0; ready_queue[*queue_cnt] = current_process; *queue_cnt = *queue_cnt + 1; return new_process; } } struct PCB handle_process_completion_pp(struct PCB ready_queue[QUEUEMAX], int *queue_cnt, int timestamp) { if (*queue_cnt > 0) { struct PCB next_process; int priorty = ready_queue[0].process_priority; int temp_queue = 0; for (int i = 1 ; i <= *queue_cnt - 1; i++){ if (priorty > ready_queue[i].process_priority){ priorty = ready_queue[i].process_priority; temp_queue = i; } } next_process = ready_queue[temp_queue]; if (*queue_cnt == 1) { ready_queue[0].process_id = 0; ready_queue[0].arrival_timestamp = 0; ready_queue[0].total_bursttime = 0; ready_queue[0].execution_starttime = 0; ready_queue[0].execution_endtime = 0; ready_queue[0].remaining_bursttime = 0; ready_queue[0].process_priority = 0; } else ready_queue[temp_queue] = ready_queue[*queue_cnt - 1]; *queue_cnt = *queue_cnt - 1; next_process.execution_starttime = timestamp; next_process.execution_endtime = timestamp + next_process.total_bursttime; return next_process; } else { struct PCB null_PCB; null_PCB.process_id = 0; null_PCB.arrival_timestamp = 0; null_PCB.total_bursttime = 0; null_PCB.execution_starttime = 0; null_PCB.execution_endtime = 0; null_PCB.remaining_bursttime = 0; null_PCB.process_priority = 0; return null_PCB; } } //******************************************************************************************************* struct PCB handle_process_arrival_srtp(struct PCB ready_queue[QUEUEMAX], int *queue_cnt, struct PCB current_process, struct PCB new_process, int time_stamp){ if ((current_process.process_id == 0) && (current_process.total_bursttime == 0) && (current_process.execution_endtime == 0) && (current_process.remaining_bursttime == 0) && (current_process.execution_starttime == 0) && (current_process.arrival_timestamp == 0) && (current_process.process_priority == 0)) {// NULLPCB , New process priority new_process.execution_starttime = time_stamp; new_process.execution_endtime = time_stamp + new_process.total_bursttime; new_process.remaining_bursttime = new_process.total_bursttime; return new_process; } else if ( new_process.total_bursttime > current_process.remaining_bursttime) { //new process goes to the queue new_process.execution_starttime = 0; new_process.execution_endtime = 0; new_process.remaining_bursttime = new_process.total_bursttime; ready_queue[*queue_cnt] = new_process; *queue_cnt = *queue_cnt + 1; return current_process; } else { //current process goes to the queue new_process.execution_starttime = time_stamp; new_process.execution_endtime = time_stamp + new_process.total_bursttime; new_process.remaining_bursttime = new_process.total_bursttime; current_process.remaining_bursttime = current_process.execution_endtime - time_stamp; current_process.execution_endtime = 0; current_process.execution_starttime = 0; ready_queue[*queue_cnt] = current_process; *queue_cnt = *queue_cnt + 1; return new_process; } } struct PCB handle_process_completion_srtp(struct PCB ready_queue[QUEUEMAX], int *queue_cnt, int timestamp) { if (*queue_cnt > 0) { struct PCB next_process; int r_bursttime = ready_queue[0].remaining_bursttime; int temp_queue = 0; for (int i = 1 ; i <= *queue_cnt - 1; i++){ if (r_bursttime > ready_queue[i].remaining_bursttime){ //looking for the smallest bursttime r_bursttime = ready_queue[i].remaining_bursttime; temp_queue = i; } } next_process = ready_queue[temp_queue]; if (*queue_cnt == 1) { ready_queue[0].process_id = 0; ready_queue[0].arrival_timestamp = 0; ready_queue[0].total_bursttime = 0; ready_queue[0].execution_starttime = 0; ready_queue[0].execution_endtime = 0; ready_queue[0].remaining_bursttime = 0; ready_queue[0].process_priority = 0; } else ready_queue[temp_queue] = ready_queue[*queue_cnt - 1]; *queue_cnt = *queue_cnt - 1; next_process.execution_starttime = timestamp; next_process.execution_endtime = timestamp + next_process.remaining_bursttime; return next_process; } else { struct PCB null_PCB; null_PCB.process_id = 0; null_PCB.arrival_timestamp = 0; null_PCB.total_bursttime = 0; null_PCB.execution_starttime = 0; null_PCB.execution_endtime = 0; null_PCB.remaining_bursttime = 0; null_PCB.process_priority = 0; return null_PCB; } } //***************************************************************************************************** struct PCB handle_process_arrival_rr(struct PCB ready_queue[QUEUEMAX], int *queue_cnt, struct PCB current_process, struct PCB new_process, int timestamp, int time_quantum) { if ((current_process.process_id == 0) && (current_process.total_bursttime == 0) && (current_process.execution_endtime == 0) && (current_process.remaining_bursttime == 0) && (current_process.execution_starttime == 0) && (current_process.arrival_timestamp == 0) && (current_process.process_priority == 0)) {// NULLPCB , New process priorty new_process.execution_starttime = timestamp; if (time_quantum <= new_process.total_bursttime){ new_process.execution_endtime = timestamp + time_quantum; } else { new_process.execution_endtime = timestamp + new_process.total_bursttime; } new_process.remaining_bursttime = new_process.total_bursttime; return new_process; } else { new_process.execution_starttime = 0; new_process.execution_endtime = 0; new_process.remaining_bursttime = new_process.total_bursttime; ready_queue[*queue_cnt] = new_process; *queue_cnt = *queue_cnt + 1; return current_process; } } struct PCB handle_process_completion_rr(struct PCB ready_queue[QUEUEMAX], int *queue_cnt, int timestamp, int time_quantum) { if (*queue_cnt > 0) { struct PCB next_process; int arr_timestamp = ready_queue[0].arrival_timestamp; int temp_queue = 0; for (int i = 1 ; i <= *queue_cnt - 1; i++){ if (arr_timestamp > ready_queue[i].arrival_timestamp){ arr_timestamp = ready_queue[i].arrival_timestamp; temp_queue = i; } } next_process = ready_queue[temp_queue]; if (*queue_cnt == 1) { ready_queue[0].process_id = 0; ready_queue[0].arrival_timestamp = 0; ready_queue[0].total_bursttime = 0; ready_queue[0].execution_starttime = 0; ready_queue[0].execution_endtime = 0; ready_queue[0].remaining_bursttime = 0; ready_queue[0].process_priority = 0; } else ready_queue[temp_queue] = ready_queue[*queue_cnt - 1]; *queue_cnt = *queue_cnt - 1; next_process.execution_starttime = timestamp; if (time_quantum <= next_process.remaining_bursttime){ next_process.execution_endtime = timestamp + time_quantum; } else { next_process.execution_endtime = timestamp + next_process.remaining_bursttime; } return next_process; } else { struct PCB null_PCB; null_PCB.process_id = 0; null_PCB.arrival_timestamp = 0; null_PCB.total_bursttime = 0; null_PCB.execution_starttime = 0; null_PCB.execution_endtime = 0; null_PCB.remaining_bursttime = 0; null_PCB.process_priority = 0; return null_PCB; } } //*************************************************************************************************** /* int main (){ struct PCB process_1; struct PCB process_2; struct PCB process_3; struct PCB process_4; struct PCB NULL_PCB; process_1.process_id = 1; process_1.arrival_timestamp = 1; process_1.total_bursttime = 5; process_1.execution_starttime = 3; process_1.execution_endtime = 8; process_1.remaining_bursttime = 3; process_1.process_priority = 3; process_2.process_id = 2; process_2.arrival_timestamp = 3; process_2.total_bursttime = 6; process_2.execution_starttime = 6; process_2.execution_endtime = 12; process_2.remaining_bursttime = 0; process_2.process_priority = 2; process_3.process_id = 3; process_3.arrival_timestamp = 5; process_3.total_bursttime = 3; process_3.execution_starttime = 5; process_3.execution_endtime = 8; process_3.remaining_bursttime = 3; process_3.process_priority = 5; process_4.process_id = 4; process_4.arrival_timestamp = 5; process_4.total_bursttime = 3; process_4.execution_starttime = 2; process_4.execution_endtime = 4; process_4.remaining_bursttime = 3; process_4.process_priority = 6; NULL_PCB.process_id = 0; NULL_PCB.arrival_timestamp = 0; NULL_PCB.total_bursttime = 0; NULL_PCB.execution_starttime = 0; NULL_PCB.execution_endtime = 0; NULL_PCB.remaining_bursttime = 0; NULL_PCB.process_priority = 0; struct PCB ready_queue[QUEUEMAX]; int cnt = 0; int *queue_cnt; queue_cnt = &cnt; int timestamp = 0; struct PCB current_process, next_process; printf("queue_cnt value is: %d \n", *queue_cnt); printf("%d", process_1.process_id); next_process = handle_process_completion_pp(ready_queue ,queue_cnt, timestamp); current_process = handle_process_arrival_pp(ready_queue, queue_cnt, process_1, process_2, timestamp); current_process = handle_process_arrival_pp(ready_queue, queue_cnt, current_process, process_3, timestamp); timestamp = 3; next_process = handle_process_completion_pp(ready_queue ,queue_cnt, timestamp); current_process = handle_process_arrival_pp(ready_queue, queue_cnt, current_process, process_4, timestamp); return 0; } */
C
#include <Windows.h> #include <stdlib.h> #include <stdio.h> int main() { //Variables stockage Disque BOOLEAN bSuccess; HANDLE hs = GetStdHandle(STD_OUTPUT_HANDLE); char espace[30]; DWORD written = 0; DWORD lpSectorsPerCluster; DWORD lpBytesPerSector; DWORD lpFreeClusters; DWORD lpTotalClusters; //obtenir de l'espace disque pour le lecteur actuel bSuccess = GetDiskFreeSpace( /*Le rpertoire racine du disque pour lequel les informations doivent tre renvoyes. Si ce paramtre est NULL , la fonction utilise la racine du disque actuel.*/ NULL, /*Un pointeur vers une variable qui reoit le nombre de secteurs par cluster.*/ &lpSectorsPerCluster, /*Un pointeur vers une variable qui reoit le nombre d'octets par secteur.*/ &lpBytesPerSector, /*Pointeur vers une variable qui reoit le nombre total de clusters libres sur le disque qui sont disponibles pour l'utilisateur associ au thread appelant.*/ &lpFreeClusters, /*Pointeur vers une variable qui reoit le nombre total de clusters sur le disque disponibles*/ &lpTotalClusters ); //condition pour verifier les information du lecteur et apres Affichage if (!bSuccess) { //printf("Impossible d'obtenir les informations sur le lecteur. \n"); exit(EXIT_FAILURE); } else { unsigned int uiKBPerCluster = lpBytesPerSector * lpSectorsPerCluster / 1024; //Affiche espace libre sprintf(espace, "%lf", (double)uiKBPerCluster * lpFreeClusters / 1024); char msg1[100] = "\nTP2 : NOTION DE PROCESSUS\n***************************\n\nVous disposez de : "; char msg2[50] = " Mo de stockage libre"; WriteConsoleA(hs, msg1, strlen(msg1), &written, NULL); WriteConsoleA(hs, espace, strlen(espace), &written, NULL); WriteConsoleA(hs, msg2, strlen(msg2), &written, NULL); // Afiiche l'espace total disck sprintf(espace, "%lf", (double)uiKBPerCluster * lpTotalClusters / 1024); char msg3[50] = "\nStockage total en Mo est de : "; char l[100] = "\n___________________________________________________________________\n\n"; WriteConsoleA(hs, l, strlen(l), &written, NULL); WriteConsoleA(hs, msg3, strlen(msg3), &written, NULL); WriteConsoleA(hs, espace, strlen(espace), &written, NULL); } //Temps Boucle //Variables DWORD timeLoop; char msgConsole[50]; timeLoop = GetTickCount(); int i, c = 0; for (i = 0; i < 1000000000; i++) c++; timeLoop = GetTickCount() - timeLoop; char msgBoucle[150] = "\n___________________________________________________________________\n\nBOUCLE FOR DE 0 A 1000000000\n\nCette boucle s'execute en : "; sprintf(msgConsole, "%d ms\n\n", timeLoop); if (hs != NULL && hs != INVALID_HANDLE_VALUE) { WriteConsoleA(hs, msgBoucle, strlen(msgBoucle), &written, NULL); WriteConsoleA(hs, msgConsole, strlen(msgConsole), &written, NULL); } //ID du processus courant DWORD processID = GetCurrentProcessId(); char msgProcessID[150]; sprintf(msgProcessID, "___________________________________________________________________\n\nL'ID du processus courant est: %d\n\n", processID); WriteConsoleA(hs, msgProcessID, strlen(msgProcessID), &written, NULL); //NOm utilisateur CHAR tchBuffer[256]; // _ tcslen utilis la place de strlen DWORD dwBufferSize = strlen(tchBuffer); char msgUsername[200]; if (GetUserNameA(tchBuffer, &dwBufferSize)) { sprintf(msgUsername, "___________________________________________________________________\n\nLe nom d'utilisateur est: %s\n\n", tchBuffer); WriteConsoleA(hs, msgUsername, strlen(msgUsername), &written, NULL); } else { WriteConsoleA(hs, "Impossible d'acqurir le nom d'utilisateur. \n", 50, &written, NULL); exit(EXIT_FAILURE); } char msgGroupe1[MAX_PATH] = "\nTRAVAIL REALISE PAR: \n\n1.\tBOFI NKAKA BOBY\n2.\tDIENDA KIMBUKU JAPHET\n3.\tKIRANDA BAKARI PAULIN\n4.\tKITOGA MIZUMBI MERVEILLE\n5.\tMAMBWE BAYEKWABO GRACE\n6.\tMPOVA LUZIZILA JAPHET\n7.\tMUANJI NGOYI DIVINE"; char msgGroupe2[MAX_PATH] = "\n8.\tMUSONGELA GRACE DJARRIA\n9.\tNDAYE TSHIBUABUA MERVA\n10.\tNGALAMULUME KANU PRINCE\n11.\tNKOY ANGAL HARDY\n12.\tOMBE OLOKE BATISTA\n\n******************************* MERCI *******************************"; WriteConsoleA(hs, msgGroupe1, strlen(msgGroupe1), &written, NULL); WriteConsoleA(hs, msgGroupe2, strlen(msgGroupe2), &written, NULL); //c //Sleep(5000); system("pause"); return 0; }
C
#include <assert.h> #include "builtin.h" static const struct builtin_meta BUILTIN_META_TABLE[] = { [BUILTIN_READ] = { .name = "READ" }, [BUILTIN_EVAL] = { .name = "EVAL" }, [BUILTIN_DOT] = { .name = "." } }; const struct builtin_meta * get_builtin_meta(enum builtin builtin) { assert(BUILTIN_READ <= builtin); assert(builtin <= BUILTIN_DOT); return &BUILTIN_META_TABLE[builtin]; }
C
//Write a removeDuplicates() function which takes a list and deletes //any duplicate nodes from the list. The list is not sorted. // //For example if the linked list is 12->11->12->21->41->43->21, //then removeDuplicates() should convert the list to 12->11->21->41->43. // //Challenge //O(n) time //12 11 12 21 41 43 21 #include "stdlib.h" #include "stdio.h" struct node{ int a; struct node *next; }; int main(){ struct node *head = NULL, *cur; int a; if(scanf("%d",&a)!=EOF){ head = (struct node *)malloc(sizeof(struct node)); head->a = a; cur = head; while(scanf("%d",&a)!=EOF){ cur->next = (struct node *)malloc(sizeof(struct node)); cur = cur->next; cur->a = a; } cur->next = NULL; } cur = head; while(cur!=NULL) { struct node *curr = (struct node *)malloc(sizeof(struct node)); struct node *prev = (struct node *)malloc(sizeof(struct node)); curr = head; prev->next = curr; while(curr!=NULL) if(curr->a==cur->a&&curr!=cur) { prev->next = prev->next->next; curr = curr->next; } else { prev = prev->next; curr = curr->next; } cur = cur->next; } cur = head; while(cur!=0) { printf("%d ", cur->a); cur = cur->next; } return 0; }
C
// //This app captures the background as a difference matte, after this //it subtracts this matte from the frames and quantizes, displaying a //silhouette of the moving spectator. // #include <stdio.h> #include <stdlib.h> #include <string.h> #include "ledmirror.h" #include "utils.h" #include "animation.h" #include "math.h" #include "menu.h" #define CAPTURE_LENGTH 1 #define BUFFER_SIZE 6144 int differClock = 0; static int recordedCounter = 0; static int playbackCounter = 0; static int countDownClock = 0; //durations in frames static int appDuration = 200; static int countdownDuration = 77; static int differenceThreshold = 10; int diffBufferInitialized = 0; uint8_t *displayBuffer; static void *recordedBuffers[CAPTURE_LENGTH]; static unsigned clearframe[2048] = {0}; int differ_quantize(int level) { int output_pixel; if(level < 50){ output_pixel = 0; }else if(level < 150){ output_pixel = 1; }else if(level < 200){ output_pixel = 2; }else{ output_pixel = 3; } return output_pixel; } void createBuffers(){ if(diffBufferInitialized){ return; } uint8_t *diffBuffer = malloc(BUFFER_SIZE); displayBuffer = malloc(BUFFER_SIZE); recordedBuffers[0] = diffBuffer; diffBufferInitialized = 1; } void differ_createOutputVideo(uint8_t* inputbuffer, uint8_t* refbuffer, uint8_t* outputBuffer){ int i; for(i =0; i< BUFFER_SIZE;i++){ int diff = abs(inputbuffer[i] - refbuffer[i]); if (diff > differenceThreshold){ diff = 240; } outputBuffer[i] = diff; } } void differ_videoFrameDidRender(MMAL_BUFFER_HEADER_T *buffer, int framecounter){ //countdown sequence takes 77 frames, after that record diff frame if(recordedCounter < CAPTURE_LENGTH && differClock > countdownDuration){ memcpy(recordedBuffers[0],buffer->data,BUFFER_SIZE); recordedCounter ++; displayImage(frame7); } //clearing overlay and setting displaymode on playback if(differClock == (countdownDuration + CAPTURE_LENGTH)){ displayImage(clearframe); setDisplayMode(displayModePlayback); } if(differClock >= (countdownDuration + CAPTURE_LENGTH)){ differ_createOutputVideo(buffer->data, recordedBuffers[0], displayBuffer); playbackFrame(displayBuffer); playbackCounter ++; } } void differ_videoFrameWillRender(int framecounter){ differClock ++; if(differClock%7 == 0 && countDownClock < 11){ countDownClock ++; } //return to main menu after appDuration if(differClock == (countdownDuration + CAPTURE_LENGTH + appDuration)){ setDisplayMode(displayModeVideoAndOverlay); playbackCounter = 0; differClock = 0; countDownClock = 0; recordedCounter = 0; returnToMenu(); return; } void *frames[12]; frames[0] = frame1; frames[1] = clearframe; frames[2] = frame2; frames[3] = clearframe; frames[4] = frame3; frames[5] = clearframe; frames[6] = frame4; frames[7] = clearframe; frames[8] = frame5; frames[9] = clearframe; frames[10] = frame6; frames[11] = clearframe; displayImage(frames[countDownClock]); if(recordedCounter < CAPTURE_LENGTH && differClock > 77){ if(differClock%6 == 0){ displayImage(frame7); }else{ displayImage(frame8); } } } void differ_init() { differClock = 0; recordedCounter = 0; playbackCounter = 0; countDownClock = 0; createBuffers(); }
C
// exp function demo program #include "stdio.h" #include "math.h" main() { printf("%g \n" , exp(1)); // e ^ 1 = 2.71828 printf("%g \n" , exp(2)); // e ^ 2 printf("%g \n" , exp(-2)); // e ^ -2 printf("%g \n" , exp(0)); // e ^ 0 = 1 } // where e value is 2.71828
C
#include "woody_woodpacker.h" #include <elf.h> #include <assert.h> struct e_ident *parse_ident(STREAM *file) { struct e_ident *e_ident; char magic[4] = {ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3}; if (!(e_ident = sread(file, 0, EI_NIDENT))) return NULL; FT_DEBUG("EI_NIDENT system value is: %u.\n", EI_NIDENT); assert(EI_NIDENT == sizeof(struct e_ident)); if (ft_memcmp(e_ident->magic, magic, 4) != 0) { ft_dprintf(STDERR_FILENO, "Bad ELF magic\n"); return NULL; } switch (e_ident->class) { case ELFCLASS32: FT_DEBUG("ELF class 32.\n"); break; case ELFCLASS64: FT_DEBUG("ELF class 64.\n"); break; default: ft_dprintf(STDERR_FILENO, "Bad ELF class.\n"); return NULL; } switch (e_ident->endian) { case ELFDATA2LSB: FT_DEBUG("Two's complement, little-endian.\n"); break; case ELFDATA2MSB: FT_DEBUG("Two's complement, big-endian.\n"); break; default: ft_dprintf(STDERR_FILENO, "Unknown data format.\n"); return NULL; } switch (e_ident->version) { case EV_CURRENT: FT_DEBUG("ELF version is Current version.\n"); break; case EV_NONE: ft_dprintf(STDERR_FILENO, "Invalid version.\n"); return NULL; default: // TODO I don't know how to manage that case FT_DEBUG("ELF version is %hhu\n", e_ident->version); break; } char *str; switch (e_ident->os_abi) { case ELFOSABI_SYSV: str = "UNIX System V ABI."; break; case ELFOSABI_HPUX: str = "HP-UX ABI."; break; case ELFOSABI_NETBSD: str = "NetBSD ABI."; break; case ELFOSABI_LINUX: str = "Linux ABI."; break; case ELFOSABI_SOLARIS: str = "Solaris ABI."; break; case ELFOSABI_IRIX: str = "IRIX ABI."; break; case ELFOSABI_FREEBSD: str = "FreeBSD ABI."; break; case ELFOSABI_TRU64: str = "TRU64 UNIX ABI."; break; case ELFOSABI_ARM: str = "ARM architecture ABI."; break; case ELFOSABI_STANDALONE: str = "Stand-alone (embedded) ABI."; break; default: ft_dprintf(STDERR_FILENO, "Unknown OS ABI.\n"); return NULL; } FT_DEBUG("%s\n", str); (void)str; FT_DEBUG("Private ABI version is %hhu.\n", e_ident->version_abi); return e_ident; }
C
#include <stdio.h> #define MAX 10000 #define NONE -1 struct Node { int parent; int left; int right; }; struct Node Tree[MAX]; void pre_parse(int u) { if (u == NONE) { return; } printf(" %d", u); pre_parse(Tree[u].left); pre_parse(Tree[u].right); } void in_parse(int u) { if (u == NONE) { return; } in_parse(Tree[u].left); printf(" %d", u); in_parse(Tree[u].right); } void post_parse(int u) { if (u == NONE) { return; } post_parse(Tree[u].left); post_parse(Tree[u].right); printf(" %d", u); } int main(int argc, char const *argv[]) { int n = 0; int root; scanf("%d", &n); for (int i = 0; i < n; i++) { Tree[i].parent = NONE; } for (int i = 0; i < n; i++) { int node = 0; int left, right; scanf("%d %d %d", &node, &left, &right); Tree[node].left = left; Tree[node].right = right; Tree[left].parent = node; Tree[right].parent = node; } for (int i = 0; i < n; i++) { if (Tree[i].parent == NONE) { root = i; break; } } printf("Preorder\n"); pre_parse(root); printf("\n"); printf("Inorder\n"); in_parse(root); printf("\n"); printf("Postorder\n"); post_parse(root); printf("\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* list_formats_pcs.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: Kwillum <daniilxod@gmail.com> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/05/19 20:28:50 by Kwillum #+# #+# */ /* Updated: 2020/05/21 14:21:27 by Kwillum ### ########.fr */ /* */ /* ************************************************************************** */ #include "../libftprintf.h" int p_ch(int *mask, va_list ap) { char c; int res; c = (char)va_arg(ap, int); res = 1; if (mask[1] > 0) { ft_putchar_fd(c, FD); res += print_infill(' ', mask[4] - 1); return (res); } if (mask[0] > 0) res += print_infill('0', mask[4] - 1); else res += print_infill(' ', mask[4] - 1); ft_putchar_fd(c, FD); return (res); } int p_s(int *mask, va_list ap) { char *s; int res; int flag; flag = 0; s = va_arg(ap, char *); if (!s) { s = ft_strdup("(null)"); flag = 1; } res = print_formated_s(mask, s); if (flag == 1) free(s); return (res); } int p_p(int *mask, va_list ap) { char *s; unsigned long res; int len; res = va_arg(ap, unsigned long); s = ft_itoa_ubase(res, 16); if (*s == '0' && mask[5] == 0) *s = '\0'; mask[6] = ft_strlen(s) + 2; len = print_formated_p(mask, s); free(s); return (len); } int p_per(int *mask, va_list ap) { const char c = '%'; int res; va_list a; va_copy(a, ap); va_end(a); res = 1; if (mask[1] > 0) { ft_putchar_fd(c, FD); res += print_infill(' ', mask[4] - 1); return (res); } if (mask[0] > 0) res += print_infill('0', mask[4] - 1); else res += print_infill(' ', mask[4] - 1); ft_putchar_fd(c, FD); return (res); } void infill_oper(int (**oper)(int *, va_list)) { oper[0] = p_ch; oper[1] = p_s; oper[2] = p_p; oper[3] = p_d; oper[4] = p_d; oper[5] = p_u; oper[6] = p_x; oper[7] = p_ux; oper[8] = p_per; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "new_lexan.c" #define MAX 200 char str[30]; Token lookahead; Token tkns[MAX]; int tkn_count = 0; int start = 0; Token genToken(){ return tkns[start++]; } void T(); void E(); void E(){ lookahead = genToken(); if(strcmp(lookahead.type, "Numeric") == 0){ lookahead = genToken(); T(); } else{ printf("Failure\n"); exit(1); } } void T(){ if(strcmp(lookahead.lexname, "*") == 0){ lookahead = genToken(); if(strcmp(lookahead.type, "Numeric") == 0){ lookahead = genToken(); T(); } else{ printf("Failure\n"); return; } } else if(strcmp(lookahead.lexname, "$") == 0){ printf("Success\n"); return; } } int main(){ char c; FILE *fp = fopen("h.c", "r"); //Ignores preprop c = fgetc(fp); while(c != EOF){ char buff[30]; int i = 0; while (c == ' ' || c == '\t') c = fgetc(fp); while (delimiter(c) == 0 && c != EOF) { buff[i++] = c; c = fgetc(fp); } buff[i] = '\0'; Token t = getNextToken(buff, 0, 0); tkns[tkn_count++] = t; if (delimiter(c) && c != ' ' && c != '\n') { char tempb[2]; tempb[0] = c; tempb[1] = '\0'; Token temp = getNextToken(tempb, 0, 0); tkns[tkn_count++] = temp; } c = fgetc(fp); } for(int i = 0; i<tkn_count; i++) printf("%s\t", tkns[i].lexname); printf("\n"); E(); }
C
#include <stdio.h> int main() { int array[][3]= {{1, 2, 3}, {4, 5, 6}}; int (*p)[3] = array; for(int i = 0; i < 2; i++) { for(int j = 0; j < 3; j++) { printf("%p ",&p[i][j]); } printf("\n"); } printf("p = %p\n", p); printf("array = %p\n", array); printf("*p = %p\n", *p); printf("*array = %p\n",*array); printf("array[0] = %p\n",array[0]); printf("array[0][0] = %p\n",&array[0][0]); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <inttypes.h> #include <cuda_runtime.h> #include <sys/time.h> #include "aio.h" #define a(i, j) ((i)*s+(j)) #define b(i, j) ((i)*s+(j)) #define c(i, j) ((i)*s+(j)) void mmul(uint64_t s) { int i, j; int *A_h, *A_d; int *B_h, *B_d; int *C_h, *C_d; void **args; printf("%"PRIu64" ", s); cudaInit(); cudaRegFunc("mmul.fatbin", "matrixMul"); // malloc matrix memory in host A_h = (int*)malloc( s*s*sizeof(int)); B_h = (int*)malloc( s*s*sizeof(int)); C_h = (int*)malloc( s*s*sizeof(int)); // malloc matrix memory in device time_begin(); cudaMalloc((void**)&A_d, s*s*sizeof(int)); cudaMalloc((void**)&B_d, s*s*sizeof(int)); cudaMalloc((void**)&C_d, s*s*sizeof(int)); printf("%u ", time_end()); // init matrix for(i=0; i<s*s; i++) A_h[i] = rand()%10; for(i=0; i<s*s; i++) B_h[i] = rand()%10; //for(int i=0; i<x*z; i++) C_h[i] = 0; // copy matrix from host to device time_begin(); cudaMemcpy(A_d, A_h, s*s*sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(B_d, B_h, s*s*sizeof(int), cudaMemcpyHostToDevice); //cudaMemcpy(C_d, C_h, x*z*sizeof(int), cudaMemcpyHostToDevice); printf("%u ", time_end()); args = (void**)malloc(4*sizeof(void*)); args[0] = &A_d; args[1] = &B_d; args[2] = &C_d; args[3] = &s; cudaExecFunc(((s%32)?s/32+1:s/32), ((s%32)?s/32+1:s/32), 1, 32, 32, 1, 0, args); time_begin(); cudaMemcpy(C_h, C_d, s*s*sizeof(int), cudaMemcpyDeviceToHost); printf("%u ", time_end()); //******************************************************************** /* printf("\n"); for(i=0; i<s; i++){ for(j=0; j<s; j++) printf("%3d ", A_h[a(i,j)]); printf(" "); for(j=0; j<s; j++) printf("%3d ", B_h[a(i,j)]); printf(" "); for(j=0; j<s; j++) printf("%3d ", C_h[a(i,j)]); printf("\n"); } */ time_begin(); cudaFree(A_d); cudaFree(B_d); cudaFree(C_d); printf("%u ", time_end()); free(A_h); free(B_h); free(C_h); cudaFini(); printf("\n"); }
C
#include <stdio.h> float f=1.11; double d=3.14; char s[] = "2.22,1.234567"; int main() { sscanf(s, "%f,%lf", &f, &d); printf("f=%f, d=%lf\n", f, d); return 0; } #ifndef __NO_SYSTEM_INIT void SystemInit() {} #endif
C
#include <stdio.h> #include <stdbool.h> /* In this demo, we'll recap our operators learning by building a simple program that modifies employee salary with a bonus/pay increase following a particularly good year of sales. If an employee earns less than £30,000, then they are entitled to a 1.15% pay increase! */ float arithmeticOperation(float val1, float val2, char operator); int main(void) { // Zero size array. Determined at runtime. We'll do this to calculate // the exact size of our array at runtime. float salaries[] = { 10000.00f, 20000.00f, 30000.00f, 40000.00f, 50000.00f, 60000.00f, 70000.00f, 80000.00f, 90000.00f, 100000.00f }; // To find the total number of employees at runtime, divide the total // size of the array by the typed size of one element. int numberOfEmployees = sizeof(salaries) / sizeof(salaries[0]); int bonus = 1000; float salaryIncrease = 1.15f; for (int i = 0; i < numberOfEmployees; i++) { float salary = salaries[i]; printf("EMPLOYEE %d\n", i); printf("SALARY %.2f\n", salary); float salaryWithBonus= arithmeticOperation(salary, bonus, '+'); printf("Employee Salary W/ Bonus: %.2f\n", salaryWithBonus); if (salary < 30000.00f) printf("Employee %d Is Entitled To A Salary Increase!\n", i); // Ternary conditional to apply salary if salary less than 30000, otherwise // return the salary with just the bonus. float finalSalary = (salaryWithBonus < 30000) ? arithmeticOperation(salaryWithBonus, salaryIncrease, '*') : salaryWithBonus; ; printf("Final Employee Salary: %.2f\n", finalSalary); printf("***************************************\n"); } return 0; } float arithmeticOperation(float val1, float val2, char operator) { float result = 0; switch(operator) { case '+': result = val1 + val2; break; case '-': result = val1 - val2; break; case '*': result = val1 * val2; break; case '/': result = val1 / val2; break; case '%': result = (int) val1 % (int) val2; break; default: printf("Invalid Operator\n"); result = -1; break; } return result; }
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> #include <math.h> #include <conio.h> #include <time.h> #include <string.h> #include <ctype.h> #include <time.h> #define LINHA 5 #define COLUNA 3 #define TAM 10 #include "FUNCAO.h" FILE *MENU (FILE *log) { FILE *arquivo; arquivo = fopen("01-08-2021.log","a"); fprintf(arquivo,"\n\t----------------------MENU-------------------------------\n"); fprintf(arquivo,"\t|\t1 - ANO NASCIMENTO E TAMANHO DO NOME \t|\n"); fprintf(arquivo,"\t|\t2 - OPERAES MATEMTICAS \t|\n"); fprintf(arquivo,"\t|\t3 - CONVERSOR DE FAHRENHEIT PARA CELSIUS \t|\n"); fprintf(arquivo,"\t|\t4 - CALCULO DO FATORIAL \t|\n"); fprintf(arquivo,"\t|\t5 - BOAS VINDAS DE ACORODO COM O HORRIO \t|\n"); fprintf(arquivo,"\t|\t6 - ARRAY MEDIA NUMEROS \t|\n"); fprintf(arquivo,"\t|\t7 - TABUADA EM MATRIZ(MULTIPLICAO) \t|\n"); fprintf(arquivo,"\t|\t8 - MATRIZ DOUBLE 5 X 3 \t|\n"); fprintf(arquivo,"\t|\t0 - SAIR \t|\n"); fprintf(arquivo,"\t---------------------------------------------------------\n"); return arquivo; } FILE *CABECALHO () { FILE *arquivo; arquivo = fopen("01-08-2021.log","w"); printf("\n\t========================================================================\n"); printf("\tNOME: Kaio Vincius Marques de Lucena Sousa\n"); printf("\tE-MAIL: kaiolucena13@gmail.com\n"); printf("\tDESCRIO: Exerccio O cliente mudou de ideia e a entrega vai ser maior! \n"); printf("\tDATA: 28/07/2021"); printf("\n\t========================================================================\n"); fprintf(arquivo,"\n\t========================================================================\n"); fprintf(arquivo,"\tNOME: Kaio Vincius Marques de Lucena Sousa\n"); fprintf(arquivo,"\tE-MAIL: kaiolucena13@gmail.com\n"); fprintf(arquivo,"\tDESCRIO: Exerccio O cliente mudou de ideia e a entrega vai ser maior! \n"); fprintf(arquivo,"\tDATA: 28/07/2021"); fprintf(arquivo,"\n\t========================================================================\n"); return arquivo; } FILE *BOAS_VINDAS (int hora, FILE *log)//VERIFICA O HORRIO E RETORNA A SAUDAO DE ACORDO COM O MESMO { FILE *arquivo; arquivo = fopen("01-08-2021.log","a"); fprintf(arquivo,"\n--------------------------------------------------------------------------------\n"); fprintf(arquivo,"\t|\t5 - EXERCCIO 1\t|\n"); if( hora== 0 || hora < 12 ) { printf("\tBOM DIA!"); fprintf(arquivo,"\tBOM DIA!"); } else if( hora == 12 || hora < 18 ) { printf("\tBOA TARDE!"); fprintf(arquivo,"\tBOA TARDE!"); } else if( hora == 18 || hora <= 23 ) { printf("\tBOA NOITE!"); fprintf(arquivo,"\tBOA NOITE!"); } else { printf("\tHORRIO INVLIDO!"); fprintf(arquivo,"\tHORRIO INVLIDO!"); } return arquivo; } void wait ( int seconds ) { clock_t endwait; endwait = clock () + seconds * CLK_TCK; while (clock() < endwait) {} } FILE *SAIR (FILE *log)//CONTADOR PARA SAIR DO PROGRAMA { int n=10; FILE *arquivo; arquivo = fopen("01-08-2021.log","a"); printf ("\n\t\tENCERRANDO\n\n"); fprintf(arquivo,"\n--------------------------------------------------------------------------------\n"); fprintf(arquivo,"\t|\t0 - SAIR\t|\n"); fprintf (arquivo,"\n\t\tENCERRANDO\n\n"); while(n!=0) { printf("\t\t%d\n",n); fprintf(arquivo,"\t\t%d\n",n); wait (1); n--; } printf ("\n\n============================FIM===================================\n"); fprintf (arquivo,"\n\n============================FIM===================================\n"); return arquivo; } FILE *FATORIAL (int n, FILE *log)//CALCULA O FATORIAL DE UM NMERO { int fat; FILE *arquivo; arquivo = fopen("01-08-2021.log","a"); fprintf(arquivo,"\n--------------------------------------------------------------------------------\n"); fprintf(arquivo,"\t|\t4 - FATORIAL \t|\n"); for(fat = 1; n > 1; n = n - 1) { fat = fat * n; } printf("\n\tFATORIAL CALCULADO: %d\n\n", fat); fprintf(arquivo,"\n\tFATORIAL CALCULADO: %d\n\n", fat); return arquivo; } FILE *CONVERSOR (float far, FILE *log)//FUNO QUE CONVERTE DE FAHRENHEIT PARA CELSIUS { float cel; FILE *arquivo; arquivo = fopen("01-08-2021.log","a"); cel = (far - 32)* 5/9; fprintf(arquivo,"\n--------------------------------------------------------------------------------\n"); fprintf(arquivo,"\t|\t3 - CONVERSOR \t|\n"); fprintf(arquivo,"\n\t O VALOR CONVERTIDO EM CELSIUS : %.2f",cel); printf("\n\t O VALOR CONVERTIDO EM CELSIUS : %.2f",cel); return arquivo; } FILE *MATEMATICA (int num1,int num2,FILE *log) { FILE *arquivo; int produto; int quadrado1; int quadrado2; int soma_quadrados; int diferencanum1num2; float raiz; float seno; int modulo1; quadrado1 = pow(num1,2); quadrado2 = pow(num2,2); soma_quadrados = (quadrado1 + quadrado2); raiz = sqrt(soma_quadrados); diferencanum1num2 = (num1 - num2); seno = sin(diferencanum1num2); modulo1 = abs(num1); printf("\n\t A SOMA DOS DOIS NUMEROS: %d",num1+num2); printf("\n\t O PRODUTO DO PRIMEIRO PELO QUADARDO DO SEGUNDO: %d",produto = num1 * (num2*num2)); printf("\n\t O QUADRADO DO PRIMEIRO: %d",quadrado1); printf("\n\t A RAIZ DA SOMA DOS QUADRADOS: %.2f",raiz); printf("\n\t O SENO DA DIFERENA DO PRIMEIRO NMERO PELO SEGUNDO: %.2f",seno); printf("\n\t O MDULO DO PRIMEIRO NUMERO: %d",modulo1); arquivo = fopen("01-08-2021.log","a"); fprintf(arquivo,"\n--------------------------------------------------------------------------------\n"); fprintf(arquivo,"\t|\t2 - MATEMATICA\t|\n"); fprintf(arquivo,"\n\t A SOMA DOS DOIS NUMEROS: %d",num1+num2); fprintf(arquivo,"\n\t O PRODUTO DO PRIMEIRO PELO QUADARDO DO SEGUNDO: %d",produto = num1 * (num2*num2)); fprintf(arquivo,"\n\t O QUADRADO DO PRIMEIRO: %d",quadrado1); fprintf(arquivo,"\n\t A RAIZ DA SOMA DOS QUADRADOS: %.2f",raiz); fprintf(arquivo,"\n\t O SENO DA DIFERENA DO PRIMEIRO NMERO PELO SEGUNDO: %.2f",seno); fprintf(arquivo,"\n\t O MDULO DO PRIMEIRO NUMERO: %d",modulo1); return arquivo; } FILE *TABUADA (FILE *log)//FUNO QUE IMPRIME A TABUADA DE MULTIPLICAO MENOS A DE 5 { int i=0; int j=0; int k=0; int l=0; int tab[TAM][TAM]; FILE *kaio; FILE *arquivo; kaio = fopen("tabuada_kaio.txt","w"); arquivo = fopen("01-08-2021.log","a"); fprintf(arquivo,"\n--------------------------------------------------------------------------------\n"); fprintf(arquivo,"\t|\t7 - TABUADA EM MATRIZ(SOMA)\t|\n"); for(i=0; i<10; i++) { if(i==5) { i++; } printf("\tTABUADA DE MULTIPLICAO: %d\n",i); fprintf(arquivo,"\tTABUADA DE MULTIPLICAO: %d\n",i); for(j=0; j<10; j++) { tab[i][j]= i*j; printf("\t%d X %d = %d \n",i,j,tab[i][j]); fprintf(arquivo,"\t%d X %d = %d \n",i,j,tab[i][j]); } } for(k=0; k<10; k++) { fprintf(kaio,"\t------------TABUADA DE MULTIPLICAO: %d------------------\n",k); for(l=0; l<10; l++) { fprintf(kaio,"\t\t\t %d X %d = %d \n",k,l,k*l); fflush(stdin); } } return arquivo; } FILE *MATRIZ (FILE *log) //FUNO QUE CRIA UMA MATRIZ DE 5X3 E CALCULA A DIFERENA DAS MEDIAS DOS VALORES DAS COLUNAS PARES PELAS IMPARES { int i=0; int j=0; FILE *arquivo; arquivo = fopen("01-08-2021.log","a"); double mat[LINHA][COLUNA]; double somacolpar=0.0; double somacolimpar=0.0; for(i=0; i<LINHA; i++) //FUNO QUE PBTEM OS VALORES DA MATRIZ { for(j=0; j<COLUNA; j++) { printf("\n\tDIGITE A LINHA %d DA COLUNA %d: ",i,j); scanf("%lf",&mat[i][j]); if(j%2==0) { somacolpar = somacolpar + mat[i][j]; //SOMA OS VALORES SE A COLUNA FOR PAR } else if(j%2!=0) { somacolimpar = somacolimpar + mat[i][j]; //SOMA OS VALORES SE A COLUNA FOR IMPAR } } } printf("\n\t SOMA COLUNA PAR: %.2lf",somacolpar); //IMPRIME O SOMATORIO DOS VALORES DAS COLUNAS PARES printf("\n\t SOMA COLUNA IMPAR: %.2lf",somacolimpar); //IMPRIME O SOMATORIO DOS VALORES DAS COLUNAS IMPARES printf("\n\t MEDIA COLUNA PAR: %.2lf",somacolpar/LINHA); //CALCULA A MEDIA DA SOMA COLUNA PAR E IMPRIME printf("\n\t MEDIA COLUNA IMPAR: %.2lf",somacolimpar/LINHA);//CALCULA A MEDIA DA SOMA DA COLUNA IMPAR E IMPRIME printf("\n\t DIFERENA DAS MEDIAS DAS COLUNAS PARES PELAS IMPARES: %.2lf\n\n",((somacolpar/LINHA)-(somacolimpar/LINHA))); fprintf(arquivo,"\n--------------------------------------------------------------------------------\n"); fprintf(arquivo,"\t|\t8 - MATRIZ DOUBLE 5 X 3\t|\n"); fprintf(arquivo,"\n\t SOMA COLUNA PAR: %.2lf",somacolpar); //IMPRIME O SOMATORIO DOS VALORES DAS COLUNAS PARES fprintf(arquivo,"\n\t SOMA COLUNA IMPAR: %.2lf",somacolimpar); //IMPRIME O SOMATORIO DOS VALORES DAS COLUNAS IMPARES fprintf(arquivo,"\n\t MEDIA COLUNA PAR: %.2lf",somacolpar/LINHA); //CALCULA A MEDIA DA SOMA COLUNA PAR E IMPRIME fprintf(arquivo,"\n\t MEDIA COLUNA IMPAR: %.2lf",somacolimpar/LINHA);//CALCULA A MEDIA DA SOMA DA COLUNA IMPAR E IMPRIME fprintf(arquivo,"\n\t DIFERENA DAS MEDIAS DAS COLUNAS PARES PELAS IMPARES: %.2lf\n\n",((somacolpar/LINHA)-(somacolimpar/LINHA))); return arquivo; } FILE *FRASE (FILE *log) //FUNO QUE RECEBE UMA STRING E CALCULA A MEDIA DOS NUMEROS DIGITADOS { FILE *arquivo; char numeros[10] = ""; int i = 0; float numeros_soma = 0; float media = 0; float contador_media = 0; arquivo = fopen("01-08-2021.log","a"); fprintf(arquivo,"\n--------------------------------------------------------------------------------\n"); fprintf(arquivo,"\t|\t6 - ARRAY MEDIA NUMEROS\t|\n"); printf ("\tDIGITE 10 CARACTERES:\n\n"); for (int i = 0; i < 10;) { printf("\tDIGITE UM NUMERO: "); fflush(stdin); scanf("%c", &numeros[i]); fprintf(arquivo,"\tDIGITE UM NUMERO: %c\n",numeros[i]); if(isdigit(numeros[i])) { numeros_soma += (numeros[i] - '0'); i++; contador_media++; } else { printf("\tCARACTERE INVALIDO!\n"); fprintf(arquivo,"\tCARACTERE INVALIDO!\n"); } } media = numeros_soma/contador_media; printf("\n\tMDIA: %.2f \n", media); fprintf(arquivo,"\tMDIA: %.2f \n", media); fflush(stdin); return arquivo; } FILE *NOME (char nome[TAM],char sobrenome[TAM],int idade, FILE *log)//FUNO QUE RECEBE O NOME SOBRENOME IDADE E RETORNA IDADE E QUANTIDADE DE CARACTERES DO NOME { FILE *arquivo; char nome_completo[20]; strcat(nome_completo,nome); strcat(nome_completo, " "); strcat(nome_completo,sobrenome); printf("\n\t%s ",nome_completo); printf("\n\tSEU ANO DE NASCIMENTO: %d",2021 - idade); printf("\n\tO TAMANHO DO SEU NOME : %d \n\n",strlen(nome)+strlen(sobrenome)); arquivo = fopen("01-08-2021.log","a"); fprintf(arquivo,"\n--------------------------------------------------------------------------------\n"); fprintf(arquivo,"\t|\t1 - ANO NASCIMENTO E TAMANHO DO NOME\t|\n"); fprintf(arquivo,"\n\t%s ",nome_completo); fprintf(arquivo,"\n\tSEU ANO DE NASCIMENTO: %d",2021 - idade); fprintf(arquivo,"\n\tO TAMANHO DO SEU NOME : %d \n\n",strlen(nome)+strlen(sobrenome)); return arquivo; }
C
/************************************************** Program to input Employee details using structures BY SAMARTH C SHETTY USN 1BM19CS141 **************************************************/ #include <stdio.h> #include <conio.h> #include <string.h> int main() { struct Employee { char name[100]; int eno; float salary; char gender[2]; char martial_status[12]; }emp; printf("Employee name : \n"); scanf("%s",&emp.name); printf("Gender : \n "); scanf("%s",&emp.gender); printf("enter the salary : \n"); scanf("%f",&emp.salary); printf("Martial status : \n"); scanf("%s",&emp.martial_status); printf("Employee number : \n "); scanf("%d",&emp.eno); printf("Feed the your data "); printf("\n Name:%s\t",emp.name); printf("\t\n Salary:%f",emp.salary); printf("\t\n Gender:%s",emp.gender); printf("\t\n Employee no:%d",emp.eno); printf("\t\n Martial status:%s",emp.martial_status); return 0; }
C
#include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <arpa/inet.h> #include<pthread.h> typedef struct { double rectX; double rectY; double headCenterX; double headCenterY; double headRadius; double legX; double legY; } package; int main(int argc, char *argv[]) { int sockfd = 0, n = 0; //char recvBuff[1024]; struct sockaddr_in serv_addr; package package1; if(argc != 2) { printf("\n Usage: %s <ip of server> \n",argv[0]); return 1; } if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Error : Could not create socket \n"); return 1; } memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(5007); if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0) { printf("\n inet_pton error occured\n"); return 1; } if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\n Error : Connect Failed \n"); return 1; } while (1) { if(n = read(sockfd, (void*)&package1, sizeof(package1))>0) { (package)package1; printf("%lf\n",package1.rectX); printf("%lf\n",package1.rectY); printf("%lf\n",package1.headCenterX); printf("%lf\n",package1.headCenterY); printf("%lf\n",package1.headRadius); printf("%lf\n",package1.legX); printf("%lf\n",package1.legY); } } }
C
#include "queue.h" #include <stdio.h> #include <stdlib.h> void queue_create(Queue *q) { q->front = 0; q->position = MAX_SIZE - 1; q->size = 0; } int queue_push(Queue *q, int val) { if (queue_full(q)) return QUEUE_IS_FULL; q->position = (q->position + 1) % MAX_SIZE; q->data[q->position] = val; q->size++; return SUCCESS; } int queue_get(Queue *q) { if (queue_empty(q)) return NULL_POINTER_EXCEPTION; int val = q->data[q->front]; return val; } int queue_pop(Queue *q) { if (queue_empty(q)) return NULL_POINTER_EXCEPTION; q->front = (q->front + 1) % MAX_SIZE; q->size--; } int queue_full(Queue *q) { return q->size == MAX_SIZE; } int queue_empty(Queue *q) { return q->size == 0; } int queue_size(Queue *q) { return q->size; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/fcntl.h> #include <wiringPi.h> #include <lcd.h> #include <time.h> #define COLUMNS 16 #define LCD_RS 3 #define LCD_E 14 #define LCD_D4 4 #define LCD_D5 12 #define LCD_D6 13 #define LCD_D7 6 #define LCD_RS 3 int lcd; int main(int argc, char *argv[]) { wiringPiSetup(); if(lcd = lcdInit(2,16,4,LCD_RS, LCD_E, LCD_D4, LCD_D5, LCD_D6, LCD_D7, 0,0, 0, 0)) { printf("lcdInit nije uspeo! \n"); return -1; } int fd = -1, ret; char *tmp1, tmp2[10], ch = 't'; char devname_head[50] = "/sys/bus/w1/devices/28-000007237df2"; char devname_end[10] = "/w1_slave"; char dev_name[100]; long value; double temp; int integer, decimal; char buffer[100]; int i,j; while(1) { strcpy(dev_name, devname_head); strcat(dev_name,devname_end); if((fd = open(dev_name, O_RDONLY)) <0) { perror("Greska pri ocitavanju!"); exit(1); } ret = read(fd, buffer, sizeof(buffer)); if(ret < 0) { perror("Greska pri citanju"); exit(1); } tmp1 = strchr(buffer, ch); sscanf(tmp1, "t=%s", tmp2); value = atoi(tmp2); temp = (double)value/1000; //printf("%lf\n", temp); //printf("%lf\n", prag); lcdPosition(lcd, 0, 0); lcdPrintf(lcd, "%.2lf", temp); delay(2000); lcdClear(lcd); } return 0; }
C
#include <stdio.h> #include <string.h> //arsip beruntun tanpa pencarian typedef struct { char nim[10]; char nama[100]; char nilai[2]; }nilaiMatkul; int main(int argc, char const *argv[]) { nilaiMatkul rekaman; FILE *arsipMatkul; arsipMatkul = fopen("ArsipMatkul.dat", "r"); printf("Isi arsip beruntun adalah: \n"); fscanf(arsipMatkul, "%s %s %s\n", &rekaman.nim, &rekaman.nama, &rekaman.nilai); if(strcmp(rekaman.nim, "XXXXXX") == 0){ printf("arsip konsong\n"); }else { do{ printf("NIM : %s\n", rekaman.nim); printf("Nama : %s\n", rekaman.nama); printf("Nilai : %s\n", rekaman.nilai); fscanf(arsipMatkul,"%s %s %s\n", &rekaman.nim, &rekaman.nama, &rekaman.nilai); }while(strcmp(rekaman.nim, "XXXXXX") != 0); } fclose(arsipMatkul); return 0; }
C
#include "scanner.h" int get_token(){ char caracter; int posicion = 0; do{ caracter = getchar(); }while(isspace(caracter)); switch (caracter){ case EOF: return FDT; break; case ',': buffer[0] = caracter; buffer[1] = '\0'; return SEP; break; default: while (caracter != EOF && caracter != ',' && !isspace(caracter)) { buffer[posicion] = caracter; posicion++; caracter = getchar(); } buffer[posicion] = '\0'; ungetc(caracter, stdin); return CAD; } }
C
/* This file is a portion of the original code supplied by Altera. It has been adapted by N. Manjikian for use in ELEC 371 laboratory work. Various unnecessary or extraneous elements have been excluded. For example, declarations in C for external functions called from asm() instructions are not required because any reference to external names in asm() instructions is embedded directly in the output written to the assembly-language .s file without any other checks by the C compiler. There is one particularly important change: on _reset_, the jump must be to the >> _start << location in order to properly initialize the stack pointer and to perform other crucial initialization tasks that ensure proper C semantics for variable initialization are enforced. The Altera version of the code jumped to main(), which will _not_ perform these crucial initialization tasks correctly. Finally, a reference to control register 'ctl4' in the asm() sequence has been replaced with the more meaningful alias 'ipending' for clarity. Other than the changes described above, the file contents have also been reformatted to fit in 80 columns of text, and comments have been edited. */ /* The assembly language code below handles processor reset */ void the_reset (void) __attribute__ ((section (".reset"))); /***************************************************************************** * Reset code. By giving the code a section attribute with the name ".reset" * * we allow the linker program to locate this code at the proper reset vector* * address. This code jumps to _startup_ code for C program, _not_ main(). * *****************************************************************************/ void the_reset (void) { asm (".set noat"); /* the .set commands are included to prevent */ asm (".set nobreak"); /* warning messages from the assembler */ asm ("movia r2, _start"); /* jump to the C language _startup_ code */ asm ("jmp r2"); /* (_not_ main, as in the original Altera file) */ } /* The assembly language code below handles exception processing. This * code should not be modified; instead, the C language code in the normal * function interrupt_handler() [which is called from the code below] * can be modified as needed for a given application. */ void the_exception (void) __attribute__ ((section (".exceptions"))); /***************************************************************************** * Exceptions code. By giving the code a section attribute with the name * * ".exceptions" we allow the linker program to locate this code at the * * proper exceptions vector address. This code calls the interrupt handler * * and later returns from the exception to the main program. * *****************************************************************************/ void the_exception (void) { asm (".set noat"); /* the .set commands are included to prevent */ asm (".set nobreak"); /* warning messages from the assembler */ asm ("subi sp, sp, 128"); asm ("stw et, 96(sp)"); asm ("rdctl et, ipending"); /* changed 'ctl4' to 'ipending' for clarity */ asm ("beq et, r0, SKIP_EA_DEC"); /* Not a hardware interrupt, */ asm ("subi ea, ea, 4"); /* so decrement ea by one instruction */ asm ("SKIP_EA_DEC:"); asm ("stw r1, 4(sp)"); /* Save all registers */ asm ("stw r2, 8(sp)"); asm ("stw r3, 12(sp)"); asm ("stw r4, 16(sp)"); asm ("stw r5, 20(sp)"); asm ("stw r6, 24(sp)"); asm ("stw r7, 28(sp)"); asm ("stw r8, 32(sp)"); asm ("stw r9, 36(sp)"); asm ("stw r10, 40(sp)"); asm ("stw r11, 44(sp)"); asm ("stw r12, 48(sp)"); asm ("stw r13, 52(sp)"); asm ("stw r14, 56(sp)"); asm ("stw r15, 60(sp)"); asm ("stw r16, 64(sp)"); asm ("stw r17, 68(sp)"); asm ("stw r18, 72(sp)"); asm ("stw r19, 76(sp)"); asm ("stw r20, 80(sp)"); asm ("stw r21, 84(sp)"); asm ("stw r22, 88(sp)"); asm ("stw r23, 92(sp)"); asm ("stw r25, 100(sp)"); /* r25 = bt (r24 = et, saved above) */ asm ("stw r26, 104(sp)"); /* r26 = gp */ /* skip saving r27 because it is sp, and there is no point in saving sp */ asm ("stw r28, 112(sp)"); /* r28 = fp */ asm ("stw r29, 116(sp)"); /* r29 = ea */ asm ("stw r30, 120(sp)"); /* r30 = ba */ asm ("stw r31, 124(sp)"); /* r31 = ra */ asm ("addi fp, sp, 128"); /* frame pointer adjustment */ asm ("call interrupt_handler"); /* call normal function */ asm ("ldw r1, 4(sp)"); /* Restore all registers */ asm ("ldw r2, 8(sp)"); asm ("ldw r3, 12(sp)"); asm ("ldw r4, 16(sp)"); asm ("ldw r5, 20(sp)"); asm ("ldw r6, 24(sp)"); asm ("ldw r7, 28(sp)"); asm ("ldw r8, 32(sp)"); asm ("ldw r9, 36(sp)"); asm ("ldw r10, 40(sp)"); asm ("ldw r11, 44(sp)"); asm ("ldw r12, 48(sp)"); asm ("ldw r13, 52(sp)"); asm ("ldw r14, 56(sp)"); asm ("ldw r15, 60(sp)"); asm ("ldw r16, 64(sp)"); asm ("ldw r17, 68(sp)"); asm ("ldw r18, 72(sp)"); asm ("ldw r19, 76(sp)"); asm ("ldw r20, 80(sp)"); asm ("ldw r21, 84(sp)"); asm ("ldw r22, 88(sp)"); asm ("ldw r23, 92(sp)"); asm ("ldw r24, 96(sp)"); asm ("ldw r25, 100(sp)"); asm ("ldw r26, 104(sp)"); /* skip r27 because it is sp, and we did not save this on the stack */ asm ("ldw r28, 112(sp)"); asm ("ldw r29, 116(sp)"); asm ("ldw r30, 120(sp)"); asm ("ldw r31, 124(sp)"); asm ("addi sp, sp, 128"); asm ("eret"); /* return from exception */ /* Note that the C compiler will still generate the 'standard' end-of-normal-function code with a normal return-from-subroutine instruction. But with the above eret instruction embedded in the final output from the compiler, that end-of-function code will never be executed. */ }
C
/* ** EPITECH PROJECT, 2021 ** B-CPE-200-BER-2-1-matchstick-mickael.riess ** File description: ** play_a _round_after_checks */ #include <stdio.h> #include <stdlib.h> #include "include/matchstick.h" #include "include/my.h" void apply_player_move(matchstick_board *game) { my_putstr("Player removed "); my_put_nbr(game->player_match_amount); my_putstr(" match(es) from line "); my_put_nbr(game->player_line_choice); my_putchar('\n'); game->board_as_int[game->player_line_choice - 1] = game->board_as_int[game->player_line_choice - 1] - game->player_match_amount; game->who_can_win = AI; } void check_win(matchstick_board *game) { for (int i = 0; i < game->lines; i++) { if (game->board_as_int[i] > 0) return; } if (game->who_can_win == AI) my_putstr("\nYOU LOSE NOOB\n"); if (game->who_can_win == PLAYER) my_putstr("\nCONGRATZ BIG BOI YOU WON\n"); game->gameover = 1; }
C
#pragma warning(disable:4996) #include <stdio.h> #include <stdlib.h> //Multi thread //#include <pthread.h> //For doing a thread. //#include <unistd.h> //For using usleep. //Socket #include <stdio.h> #include <sys/types.h> //#include <sys/socket.h> //#include <netinet/in.h> //#include <netdb.h> #include <stdlib.h> //for doing an exit //#include <strings.h> //for using a bzero //#include <unistd.h> //for read & write #include <string.h> //to use strlen #include <sys/stat.h> //to determine size of file //To compile RUN gcc node.c -o node -lpthread. //Default error message from C. void error(const char *msg) { perror(msg); exit(1); } //Configuration file reader function. char * readFile() { FILE *fr; char *message; fr = fopen("elapsed.txt", "r"); /*create variable of stat*/ struct stat stp = { 0 }; /*These functions return information about a file. No permissions are required on the file itself*/ stat("elapsed.txt", &stp); /*determine the size of data which is in file*/ int filesize = stp.st_size; /*allocates the address to the message pointer and allocates memory*/ message = (char *)malloc(sizeof(char) * filesize); if (fread(message, 1, filesize - 1, fr) == -1) { printf("\nerror in reading\n"); /**close the read file*/ fclose(fr); /*free input string*/ free(message); } printf("\n\tEntered Message for Encode is = %s", message); return message; } /* //Thread Init void *threadFunc(void *arg) { char *str; int i = 0; str = (char*)arg; while (i < 10) { usleep(1); printf("threadFunc says: %s\n", str); ++i; } return NULL; } */ /* //Start a thread. void threadInit() { pthread_t threadId; int i = 0; //Thread definition. pthread_create(&threadId, NULL, threadFunc, "processing..."); //Thread connection. pthread_join(threadId, NULL // void ** return value could go here); while (i < 10) { usleep(1); printf("Initializing thread\n"); ++i; } } */ /* //Origin to Destiny. void origin() { int sockfd, n; int portno = 1990; struct sockaddr_in serv_addr; struct hostent *server; char buffer[256]; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); server = gethostbyname("127.0.0.1"); if (server == NULL) { fprintf(stderr, "ERROR, no such host\n"); exit(0); } bzero((char *)&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) error("ERROR connecting"); printf("Please enter the message: "); bzero(buffer, 256); fgets(buffer, 255, stdin); n = write(sockfd, buffer, strlen(buffer)); if (n < 0) error("ERROR writing to socket"); bzero(buffer, 256); n = read(sockfd, buffer, 255); if (n < 0) error("ERROR reading from socket"); printf("%s\n", buffer); } */ /* //Destiny to Origin. void destiny() { int sockfd, newsockfd, clilen; int portno = 1990; char buffer[256]; struct sockaddr_in serv_addr, cli_addr; int n; sockfd = socket(AF_INET, SOCK_STREAM, 0); bzero((char *)&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding"); listen(sockfd, 5); clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept"); bzero(buffer, 256); n = read(newsockfd, buffer, 255); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %s\n", buffer); n = write(newsockfd, "I got your message", 18); if (n < 0) error("ERROR writing to socket"); } */ int main(void) { readFile(); getchar(); }
C
#include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> int main() { int sd, newsd; char buffer[1024]; struct sockaddr_in servAddr; struct sockaddr_storage serverStorage; socklen_t addr_size; sd = socket(PF_INET, SOCK_STREAM, 0); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(7891); serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero); bind(sd, (struct sockaddr *) &serverAddr, sizeof(serverAddr)); if(listen(sd, 5) == 0) printf("Listening\n"); else printf("Error\n"); addr_size = sizeof serverStorage; newsd = accept(sd, (struct sockaddr *) &serverStorage, &addr_size); strcpy(buffer, "Hello"); send(newsd, buffer, 13, 0); return 0; }
C
// Name: Rodrigo Ignacio Rojas Garcia // Course Number: ECE 2230 // Section: 001 // Semester: Spring 2017 // Assignment Number: 3 // © Rodrigo Rojas. All Rights Reserved. // Bug: Once the program reaches a request_counter of 27989, the program starts leaking for unkown reason // Library Declaration Section #include <stdio.h> #include <stdlib.h> #include <string.h> #include "disk_queue.h" #include "event_queue.h" #include "list.h" #include "disk.h" #include "randsim.h" #include "structures.h" // Define Declaration section #define SIZE 1000 #define REQUEST_NUM 1000000 #define MAXCHARACTERS 1994 int main(int argc, char *argv[]) { // Variable Declaration Section double global_time = 0.0; int request_counter = 1; double seek_time_result; double next_request_time = 0; double queue_time = 0; double queue_time_min = 0; double queue_time_max = 0; double queue_time_average = 0; double io_time = 0; double io_time_min = 0; double io_time_max = 0; double io_time_average = 0; double total_time = 0; double total_time_min = 0; double total_time_max = 0; double total_time_average = 0; int first_time = 0; int current_track = 0; event_queue_t event_queue; disk_queue_t disk_queue; request_t request; event_t event; event_t event1; event_t event2; event_t event3; event_t event4; request_t new_request; request_t removed_request; request_t head_request; // Allocates dynamic memory for the event_queue which will also allocate memory for the array of pointers // depending of the value of variable size event_queue = event_queue_init(SIZE); // Allocates dynamic memory for a disk_queue linked list disk_queue = disk_queque_init(); // Allocates dynamic memory for a request request = (request_t)calloc(1, sizeof(struct request_s)); request->track = request_track(); // Allocates dynamic memory for an event_t event = (event_t)calloc(1, sizeof(struct event_s)); // Sets the starting values of an event when nothing has ran and uses event as a "SHELL" for requests that will be passed event->event_time = 0; event->event_type = 1; event->request = request; // Will inser the first event into the array of event pointers event_queue_insert(event_queue, event); // While the event_queue is not EMPTY this loop will continue running while (event_queue_empty(event_queue) == 0) { // Remove and event from the event queue event = event_queue_remove(event_queue); // Sets global time to the current event time global_time = event->event_time; switch (event->event_type) { // REQUEST_SUBMIT will start if the event_type of an event is equal to 1 case 1: // Sets the arrival_time of the request event->request->arrival_time = global_time; if (disk_queue_empty(disk_queue) == -1) { // Schedules a DISK_READY event1 = (event_t)calloc(1, sizeof(struct event_s)); event1->event_time = global_time; event1->event_type = 2; event_queue_insert(event_queue, event1); } // Inserts the request on the disk queue disk_queue_insert(disk_queue, event->request); if (request_counter <= REQUEST_NUM) { // Computes when the next request should arrive next_request_time = randsim_exp(); event2 = (event_t)calloc(1, sizeof(struct event_s)); // Creates new request and allocates dynamic memory for it new_request = (request_t)calloc(1, sizeof(struct request_s)); // Uses function reques_track() function to determine the track the request is on new_request->track = request_track(); event2->event_type = 1; event2->event_time = global_time + next_request_time; event2->request = new_request; event_queue_insert(event_queue, event2); // Increments the request counter request_counter++; } break; // DISK_READY will start if the event_type of an event is equal to 2 case 2: event3 = (event_t)calloc(1, sizeof(struct event_s)); // Creates reuest_t variable head_request which will be used to store the returned request of function // disk_queue_peek(). head_request = disk_queue_peek(disk_queue); // Updates the start_time of the request head_request->start_time = global_time; // Determines how long it will take to process IO using function seek_time() seek_time_result = seek_time(current_track, head_request->track); // Update the current track current_track = head_request->track; event3->event_time = global_time + seek_time_result; // Schedules a new REQUEST_DONE event event3->event_type = 3; event_queue_insert(event_queue, event3); break; // REQUEST DONE case 3: // removed_request that will be returned the request removed from the disk_queue_remove() // function removed_request = disk_queue_remove(disk_queue); if (disk_queue_empty(disk_queue) == 0) { // Schedules another DISK_READY event4 = (event_t)calloc(1, sizeof(struct event_s)); event4->event_time = global_time; event4->event_type = 2; event_queue_insert(event_queue, event4); } // Updates the value of finish_time for the request returned removed_request->finish_time = global_time; // Computes Queue_time, io_time, and total_time queue_time = removed_request->start_time - removed_request->arrival_time; queue_time_average = queue_time_average + removed_request->start_time - removed_request->arrival_time; io_time = removed_request->finish_time - removed_request->start_time; io_time_average = io_time_average + removed_request->finish_time - removed_request->start_time; total_time = removed_request->finish_time - removed_request->arrival_time; total_time_average = total_time_average + removed_request->finish_time - removed_request->arrival_time; // Sets queue_time_min/max, io_time_min/max, and total_time_minx/max to the first value returend on the removed // request if (first_time == 0) { queue_time_min = queue_time; queue_time_max = queue_time; io_time_min = io_time; io_time_max = io_time; total_time_min = total_time; total_time_max = total_time; first_time++; } // Updates minimum, maximum, and average of queue_time, io_time, and total_time else { if (queue_time < queue_time_min) { queue_time_min = queue_time; } if (queue_time > queue_time_max) { queue_time_max = queue_time; } if (io_time < io_time_min) { io_time_min = io_time; } if (io_time > io_time_max) { io_time_max = io_time; } if (total_time < total_time_min) { total_time_min = total_time; } if (total_time > total_time_max) { total_time_max = total_time; } } // Frees the removed_request returned free(removed_request); break; } // Frees an event once is no longer needed free(event); } // Prints the final results of time in milliseconds - printf("\nQueue minimum time: %f\n", queue_time_min); printf("Queue maximum time: %f\n", queue_time_max); printf("Queue average time: %f\n\n", queue_time_average / request_counter); printf("IO minimum time: %f\n", io_time_min); printf("IO maximum time: %f\n", io_time_max); printf("IO average time: %f\n\n", io_time_average / request_counter); printf("Total minimum time: %f\n", total_time_min); printf("Total maximum time: %f\n", total_time_max); printf("Total average time: %f\n\n", total_time_average / request_counter); // Frees all allocated dynamic memory for both disk_queue and event_queue event_queue_finalize(event_queue); disk_queue_finalize(disk_queue); return 0; }
C
#include <assert.h> #include <stdio.h> #include "vulkan.h" #include "swapchain.h" static uint32_t get_min_image_count(VkPhysicalDevice physical_device, VkSurfaceKHR surface) { VkSurfaceCapabilitiesKHR capabilities; vk_get_physical_device_surface_capabilities_khr(physical_device, surface, &capabilities); return capabilities.min_image_count; } static Attachment create_depth_attachment(GPU* gpu, uint32_t width, uint32_t height) { Attachment attachment = {}; VkImageCreateInfo image_info = { .s_type = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .image_type = VK_IMAGE_TYPE_2D, .format = VK_FORMAT_D16_UNORM, .extent = (VkExtent3D){ width, height, 1 }, .mip_levels = 1, .array_layers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL, .usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, .initial_layout = VK_IMAGE_LAYOUT_UNDEFINED, }; vk_create_image(gpu->device, &image_info, NULL, &attachment.image); gpu_set_debug_name(gpu, IMAGE, attachment.image, "Depth image"); VkMemoryRequirements depth_requirements; vk_get_image_memory_requirements(gpu->device, attachment.image, &depth_requirements); attachment.memory_block = gpu_allocate_memory(gpu, &gpu->device_local_heap, &depth_requirements); vk_bind_image_memory(gpu->device, attachment.image, attachment.memory_block.memory, attachment.memory_block.offset); VkComponentMapping components = { .r = VK_COMPONENT_SWIZZLE_R, .g = VK_COMPONENT_SWIZZLE_G, .b = VK_COMPONENT_SWIZZLE_B, .a = VK_COMPONENT_SWIZZLE_A, }; VkImageSubresourceRange subresource_range = { .aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT, .base_mip_level = 0, .level_count = 1, .base_array_layer = 0, .layer_count = 1, }; VkImageViewCreateInfo view_info = { .s_type = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = attachment.image, .view_type = VK_IMAGE_VIEW_TYPE_2D, .format = VK_FORMAT_D16_UNORM, .components = components, .subresource_range = subresource_range, }; vk_create_image_view(gpu->device, &view_info, NULL, &attachment.view); gpu_set_debug_name(gpu, IMAGE_VIEW, attachment.view, "Depth image view"); return attachment; } Swapchain create_swapchain(GPU* gpu, Window* window) { uint32_t min_image_count = get_min_image_count(gpu->physical_device, window->surface); assert(min_image_count <= SWAPCHAIN_MAX_IMAGE_COUNT); VkSwapchainCreateInfoKHR info = { .s_type = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, .surface = window->surface, .min_image_count = min_image_count, .image_format = VK_FORMAT_B8G8R8A8_UNORM, .image_color_space = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, .image_extent = { window->width, window->height }, .image_array_layers = 1, .image_usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, .image_sharing_mode = VK_SHARING_MODE_EXCLUSIVE, .pre_transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, .composite_alpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, .present_mode = VK_PRESENT_MODE_FIFO_KHR, .clipped = VK_TRUE, }; Swapchain swapchain = {}; vk_create_swapchain_khr(gpu->device, &info, NULL, &swapchain.handle); set_debug_name(gpu, SWAPCHAIN_KHR, swapchain.handle, "Swapchain"); vk_get_swapchain_images_khr(gpu->device, swapchain.handle, &swapchain.image_count, NULL); assert(swapchain.image_count < SWAPCHAIN_MAX_IMAGE_COUNT); vk_get_swapchain_images_khr(gpu->device, swapchain.handle, &swapchain.image_count, &swapchain.images[0]); for (uint32_t i = 0; i < swapchain.image_count; i++) { char name[32]; sprintf(name, "Swapchain image %u", i); set_debug_name(gpu, IMAGE, swapchain.images[i], name); } for (uint32_t i = 0; i < swapchain.image_count; i++) { VkComponentMapping components = { .r = VK_COMPONENT_SWIZZLE_R, .g = VK_COMPONENT_SWIZZLE_G, .b = VK_COMPONENT_SWIZZLE_B, .a = VK_COMPONENT_SWIZZLE_A, }; VkImageSubresourceRange subresource_range = { .aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT, .base_mip_level = 0, .level_count = 1, .base_array_layer = 0, .layer_count = 1, }; VkImageViewCreateInfo view_info = { .s_type = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .format = VK_FORMAT_B8G8R8A8_UNORM, .components = components, .subresource_range = subresource_range, .view_type = VK_IMAGE_VIEW_TYPE_2D, .image = swapchain.images[i], }; vk_create_image_view(gpu->device, &view_info, NULL, &swapchain.views[i]); char name[32]; sprintf(name, "Swapchain view %u", i); set_debug_name(gpu, IMAGE_VIEW, swapchain.views[i], name); } swapchain.depth_attachment = create_depth_attachment(gpu, window->width, window->height); return swapchain; } void destroy_swapchain(GPU* gpu, Swapchain* swapchain) { for (uint32_t i = 0; i < swapchain->image_count; i++) { vk_destroy_image_view(gpu->device, swapchain->views[i], NULL); } vk_destroy_image(gpu->device, swapchain->depth_attachment.image, NULL); vk_destroy_image_view(gpu->device, swapchain->depth_attachment.view, NULL); vk_destroy_swapchain_khr(gpu->device, swapchain->handle, NULL); }
C
#include <p24FJ64GB002.h> #include <stdio.h> #include <stdlib.h> #include "DogM.h" // Defining player perspective directions #define NORTH 1 #define EAST 2 #define SOUTH 4 #define WEST 8 void turnLeft(); void turnRight(); void forward(); void drawArea(unsigned int x, unsigned int y, unsigned int length, unsigned int height); void drawLine(unsigned int xA, unsigned int yA, unsigned int xB, unsigned int yB, unsigned int style); void delayMs(unsigned int time); unsigned char direction = 1; unsigned int userX = 1; unsigned int userY = 1; /* * This is a map of the maze * 0 = walkable * 1 = wall * 2 = starting point * 3 = ending point */ int maze [10][10] = { { 1, 3, 1, 1, 1, 1, 1, 1, 1, 1}, { 1, 0, 1, 0, 1, 0, 0, 0, 1, 1}, { 1, 0, 0, 0, 0, 0, 1, 0, 0, 1}, { 1, 1, 0, 0, 1, 1, 1, 1, 0, 1}, { 1, 0, 1, 0, 0, 0, 0, 0, 1, 1}, { 1, 0, 0, 1, 1, 0, 1, 0, 1, 1}, { 1, 1, 0, 0, 0, 1, 0, 0, 0, 1}, { 1, 1, 1, 0, 1, 1, 0, 1, 1, 1}, { 1, 2, 0, 0, 0, 0, 0, 0, 0, 1}, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, }; void forward() { if (direction == NORTH) { if (maze[userY + 1][userX] == 0) { userY++; } else { //wall } } else if (direction == SOUTH) { if (maze[userY - 1][userX] == 0) { userY--; } else { //wall } } else if (direction == EAST) { if (maze[userY][userX + 1] == 0) { userX++; } else { //wall } } else if (direction == WEST) { if (maze[userY][userX - 1] == 0) { userX--; } else { //wall } } else { // error ofzo? } } // The following methods perform bit rotations on the players direction void turnRight() { if (direction >= 1 && direction <= 4) { direction = direction << 1; } else { // reset direction to allow wrap-around direction = 1; } } void turnLeft() { if (direction >= 2 && direction <= 8) { direction = direction >> 1; } else { // reset direction to allow wrap-around direction = 8; } } /* lastButtonChanged is modified on a interrup basis The function doing ths is called _CNInterrupt(void) and is defined in file interrupts. This funtion is called on a pin level change detection. */ int lastButtonChanged = 0; // This is a stupid delay function, it is NOT very precise void delayMs(unsigned int time) { unsigned int i, j; for (i = 0; i <= time; i++) { asm("nop"); for (j = 0; j <= 1140; j++) //1ms { asm("nop"); asm("nop"); } } } /** * drawLine * this function's style parameter takes 1 for dotted lines and 0 for regular lines * @param xA * @param yA * @param xB * @param yB * @param style */ void drawLine(unsigned int xA, unsigned int yA, unsigned int xB, unsigned int yB, unsigned int style) { int dX = xB - xA; int dY = yB - yA; int alpha = dX / dY; unsigned int i; for (i = 0; i < dY; i++) { int yP = yA + i; int xP = xA + (i * alpha); int xP2 = xA + ((i + 1) * alpha); if (style == 1) { setPixel(xP, yP); } else { while (xP < xP2) { setPixel(xP, yP); xP++; } } } } /** * drawArea * @param x * @param y * @param length * @param hight */ void drawArea(unsigned int x, unsigned int y, unsigned int length, unsigned int height) { int i; int j; for (i = 0; i < height; ++i) { for (j = 0; j < length; ++j) { setPixel((x + j), (y + i)); } } } /** * startMenu */ void startMenu() { drawArea(0, 0, 128, 22); drawArea(0, 22, 34, 1); drawArea(0, 23, 33, 1); drawArea(0, 24, 32, 2); setPixel(33, 25); drawArea(0, 26, 34, 3); drawArea(0, 29, 33, 1); drawArea(0, 30, 34, 1); drawArea(0, 31, 33, 8); drawArea(0, 39, 34, 1); drawArea(0, 40, 35, 1); drawArea(0, 41, 37, 1); drawArea(0, 42, 39, 7); drawArea(0, 49, 38, 1); drawArea(0, 50, 37, 1); drawArea(0, 51, 35, 1); drawArea(0, 52, 34, 1); drawArea(0, 53, 33, 1); drawArea(0, 54, 32, 1); drawArea(0, 55, 31, 2); drawArea(0, 57, 30, 7); drawArea(36, 22, 55, 1); drawArea(37, 23, 53, 1); drawArea(38, 24, 51, 1); drawArea(39, 25, 49, 1); drawArea(40, 26, 47, 1); drawArea(41, 27, 45, 1); drawArea(42, 28, 43, 1); drawArea(43, 29, 41, 2); drawArea(44, 31, 39, 1); drawArea(45, 32, 39, 1); drawArea(46, 33, 37, 1); drawArea(47, 34, 11, 1); drawArea(47, 35, 7, 1); drawArea(48, 36, 5, 1); drawArea(49, 37, 4, 2); drawArea(50, 39, 2, 1); drawArea(49, 40, 3, 1); drawArea(45, 41, 7, 1); drawArea(42, 42, 9, 1); drawArea(39, 43, 11, 1); drawArea(39, 44, 8, 1); drawArea(39, 45, 5, 1); drawArea(39, 46, 3, 1); setPixel(39, 47); drawArea(69, 34, 14, 1); drawArea(74, 35, 9, 1); drawArea(74, 36, 10, 1); drawArea(74, 37, 4, 2); drawArea(74, 39, 3, 1); drawArea(79, 37, 4, 1); drawArea(79, 38, 5, 1); drawArea(79, 39, 6, 1); drawArea(75, 40, 11, 1); drawArea(75, 41, 12, 1); drawArea(76, 42, 10, 1); setPixel(88, 42); drawArea(77, 43, 13, 1); drawArea(80, 44, 9, 1); drawArea(83, 45, 7, 1); drawArea(85, 46, 6, 1); drawArea(87, 47, 5, 1); drawArea(88, 48, 6, 1); drawArea(89, 49, 6, 1); drawArea(90, 50, 5, 1); drawArea(92, 51, 3, 1); drawArea(93, 52, 2, 1); drawArea(93, 22, 35, 1); drawArea(94, 23, 34, 1); drawArea(95, 24, 33, 3); drawArea(96, 27, 32, 8); drawArea(97, 35, 31, 6); drawArea(96, 41, 32, 6); drawArea(95, 47, 33, 7); drawArea(96, 54, 32, 10); drawArea(60, 42, 9, 1); drawArea(57, 43, 14, 1); drawArea(56, 44, 16, 1); drawArea(55, 45, 19, 2); drawArea(56, 47, 18, 2); drawArea(56, 49, 17, 1); drawArea(45, 50, 4, 1); drawArea(57, 50, 15, 1); drawArea(80, 50, 4, 1); drawArea(42, 51, 4, 1); drawArea(48, 51, 4, 1); drawArea(58, 51, 13, 1); drawArea(77, 51, 10, 1); drawArea(41, 52, 4, 1); drawArea(47, 52, 6, 1); drawArea(58, 52, 13, 1); drawArea(76, 52, 13, 1); drawArea(39, 53, 6, 1); drawArea(46, 53, 8, 1); drawArea(59, 53, 12, 1); drawArea(75, 53, 15, 1); setPixel(39, 54); drawArea(42, 54, 2, 1); drawArea(46, 54, 9, 1); drawArea(59, 54, 11, 1); drawArea(74, 54, 2, 1); drawArea(77, 54, 10, 1); setPixel(89, 54); drawArea(42, 55, 2, 1); drawArea(45, 55, 11, 1); drawArea(59, 55, 11, 1); drawArea(73, 55, 2, 1); drawArea(77, 55, 7, 1); drawArea(85, 55, 2, 1); drawArea(42, 56, 2, 1); drawArea(46, 56, 7, 1); drawArea(54, 56, 2, 1); drawArea(59, 56, 11, 1); drawArea(73, 56, 2, 1); drawArea(77, 56, 7, 1); drawArea(85, 56, 2, 1); drawArea(43, 57, 1, 1); drawArea(46, 57, 6, 1); drawArea(53, 57, 4, 1); drawArea(59, 57, 11, 1); drawArea(73, 57, 3, 1); drawArea(77, 57, 7, 1); drawArea(85, 57, 2, 1); drawArea(43, 58, 2, 1); drawArea(46, 58, 6, 1); setPixel(53, 58); drawArea(55, 58, 2, 1); drawArea(59, 58, 12, 1); drawArea(72, 58, 4, 1); drawArea(78, 58, 5, 1); drawArea(84, 58, 2, 1); setPixel(44, 59); drawArea(47, 59, 4, 1); drawArea(54, 59, 3, 1); drawArea(59, 59, 12, 1); drawArea(72, 59, 3, 1); drawArea(78, 59, 4, 1); setPixel(84, 59); drawArea(45, 60, 2, 1); drawArea(51, 60, 7, 1); drawArea(59, 60, 19, 1); setPixel(80, 60); setPixel(83, 60); drawArea(46, 61, 37, 1); drawArea(55, 62, 19, 2); } /** * main * @return */ int main(void) { // Init ap set all ports to digital and enables the int on pin change // needed for the buttons/ InitApp(); // Set up the hardware of the display mdog_Init(0x81, 0x19); clearDisplay(); // Initscreen clears a internal bitmap used // in drawScreen to send out to the display initScreen(); // Set both led's of LATBbits.LATB14 = LATBbits.LATB15 = 0; while (1) { // Splash screen if (lastButtonChanged == 0) { // startMenu(); } if (lastButtonChanged == 1) { drawLine(0, 0, 129, 64, 1); drawLine(127, 0, -2, 64, 1); } if (lastButtonChanged == 2) { } if (lastButtonChanged == 3) { } if (lastButtonChanged == 4) { } delayMs(250); drawScreen(dogmScreen, 8, 128); }; }
C
/** * Copyright (c) 2016 BitCoding */ #ifndef CCTALK_HOST_H #define CCTALK_HOST_H 1 // #define CCTALK_WRITEDEBUG 1 // #define CCTALK_READDEBUG 1 #include <cctalk/core/global.h> #include <cctalk/core/tty.h> /*Host*/ struct cctalk_host { /* Serial Interface. */ struct cctalk_tty* tty; /* Host identifier. */ uint8_t id; /* Selected CRC mode to send and to expect. */ enum cctalk_crc_mode crc_mode; }; struct cctalk_host* new_cctalk_host(const char *,int,enum cctalk_crc_mode,uint8_t); /* * write(2) wrapper that attempts to write the whole buffer. * Returns either the original count or -1 to signal failure. * The timeout parameter specifies how long can the function * block until it is allowed to write next byte. */ int write_cctalk_host(struct cctalk_host*, struct cctalk_message*); /* * read(2) wrapper that attempts to fill the whole buffer. * Returns either the original count or -1 to signal failure. * The timeout parameter specifies how long can the function * block until it is allowed to write next byte. */ struct cctalk_message* read_cctalk_host(struct cctalk_host*); int read_status_cctalk_host(struct cctalk_host*); void destroy_cctalk_host(struct cctalk_host*); #endif
C
#include <stdio.h> #include <stdlib.h> // nesting if basically makes program more interactive // taking example of if statement , we we have done previous time , please check it out if you haven't seen it. int main() { int age; int gender; //if you are using or any other softwere for c , just left one space whenever you are using converging character in scanf, // otherwise your code may not be recognize. printf("what's your age ?\n"); scanf(" %d",&age); printf("what's your gender ? (m/f)\n"); scanf(" %c",&gender); if(age>=18){ // logic 1 printf("you are allowed in Club"); if(gender == 'm'){ printf(" dude"); } if(gender == 'f'){ printf(" lady"); } } if(age<18){ //logic 2 printf("you are not allowed"); } // if you type below value 18 , whole logic 1 will skip and logic 2 will print out. return 0; }
C
#include<stdio.h> void main() { int a[100],n,s,i; printf("Specify Number of Elements To Be Stored:"); scanf("%d",&n); printf("Enter the elements to be stored:"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter the position from which it is to be deletd:"); scanf("%d",&s); for(i=s;i<n;i++) a[i]=a[i+1]; n--; printf("Array After deletion is:"); for(i=0;i<n;i++) printf(" %d",a[i]); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> int main() { char *s1 = malloc(sizeof(char) * 61); scanf("%s", s1); char *ptr = strtok(s1, "."); while (ptr != NULL) { printf("%s\n", ptr); ptr = strtok(NULL, "."); } return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<memory.h> #include<string.h> int token; //current token char *src, *old_src; //pointer to source code string int poolsize; //default size of text/stack/data int line; //line number int *text, //text segment *old_text, //for dump text segment *stack; //stack char *data; //data segment int *pc, *bp, *sp, ax, cycle; //virtual machine registers //instructions enum {LEA, IMM, JMP, CALL, JZ, JNZ, ENT, ADJ, LEV, LI, LC, SI, SC, PUSH, OR, XOR, AND, EQ, NE, LT, GT, LE, GE, SHL, SHR, ADD, SUB, MUL, DIV, MOD, OPEN, READ, CLOS, PRTF, MALC, MSET, MCMP, EXIT}; //tokens and classes (operators last and in precedence order) enum { Num = 128, Fun, Sys, Glo, Loc, Id, Char, Else, Enum, If, Int, Return, Sizeof, While, Assign, Cond, Lor, Lan, Or, Xor, And, Eq, Ne, Lt, Gt, Le, Ge, Shl, Shr, Add, Sub, Mul, Div, Mod, Inc, Dec, Brak }; int token_val; //value of current token (mainly for number) int *current_id, //current parsed ID *symbols; //symbol table int *idmain; //the "main" function //fields of identifier enum {Token, Hash, Name, Type, Class, Value, BType, BClass, BValue, IdSize}; enum {CHAR, INT, PTR}; int basetype; //the type of a declaration, make it global for convenience int expr_type; //the type of an expression int index_of_bp; //index of bp pointer on stack void next() { char *last_pos; int hash; while(token = *src) { ++src; //parse token here if (token == '\n') { ++line; } else if (token == '#') { //skip macro, because we will not support it while(*src != 0 && *src != '\n') { src++; } } else if ((token >= 'a' && token <= 'z') || (token >= 'A' && token <= 'Z') || (token == '_')) { //parse identifier last_pos = src - 1; hash = token; while ((*src >= 'a' && *src <= 'z') || (*src >= 'A' && *src <= 'Z') || (*src >= '0' && *src <= '9') || (*src == '_')) { hash = hash * 147 + *src; src++; } //look for existing identifier, linear search current_id = symbols; while(current_id[Token]) { if(current_id[Hash] == hash && !memcmp((char *)current_id[Name], last_pos, src - last_pos)) { //found one, return token = current_id[Token]; return; } current_id = current_id + IdSize; } //store new ID current_id[Name] = (int)last_pos; current_id[Hash] = hash; token = current_id[Token] = Id; return; } else if(token >= '0' && token <= '9') { //parse number, three kinds:dec(123) hex(0x123) oct(017) token_val = token - '0'; if(token > 0) { //dec, starts with [1-9] while(*src >= '0' && *src <= '9') { token_val = token_val * 10 + *src++ - '0'; } } else { //starts with number 0 if(*src == 'x' || *src == 'X') { //hex token = *++src; while((token >= '0' && token <= '9') || (token >= 'a' && token <= 'f') || (token >= 'A' && token == 'F')) { token_val = token_val * 16 + (token & 15) + (token >= 'A' ? 9 : 0); token = *++src; } } else { //oct while(*src >= '0' && *src <= '7') { token_val = token_val * 8 + *src++ - '0'; } } } token = Num; return; } else if(token == '"' || token == '\'') { //parse string literal, currently, the only supported escape //character is '\n', store the string literal into data last_pos = data; while(*src != 0 && *src != token) { token_val = *src++; if(token_val == '\\') { //escape character token_val = *src++; if(token_val == 'n') { token_val = '\n'; } } if(token == '"') { *data++ = token_val; } } src++; //if it's a single character, return Num token if(token == '"') { token_val = (int)last_pos; } else { token = Num; } return; } else if(token == '/') { if(*src == '/') { //skip comments while(*src != 0 && *src != '\n') { ++src; } } else { //divide operator token = Div; return; } } else if(token == '=') { //parse '==' and '=' if(*src == '=') { src++; token = Eq; } else { token = Assign; } return; } else if(token = '+') { //parse '+' and '++' if(*src == '+') { src++; token = Inc; } else { token = Add; } return; } else if(token == '-') { //parse '-' and '--' if(*src == '-') { src++; token = Dec; } else { token = Sub; } return; } else if(token = '!') { //parse '!=' if(*src == '=') { src++; token = Ne; } return; } else if(token == '<') { //parse '<=', '<<' and '<' if(*src == '=') { src++; token = Le; } else if(*src == '<') { src++; token = Shl; } else { token = Lt; } return; } else if(token == '>') { //parse '>=', '>>' and '>' if(*src == '=') { src++; token = Ge; } else if(*src == '>') { src++; token = Shr; } else { token = Gt; } return; } else if(token == '|') { //parse '|' and '||' if(*src == '|') { src++; token = Lor; } else { token = Or; } return; } else if(token == '&') { //parse '&' and '&&' if(*src == '&') { src++; token = Lan; } else { token = And; } return; } else if(token == '^') { token = Xor; return; } else if(token == '%') { token = Mod; return; } else if(token == '*') { token = Mul; return; } else if(token == '[') { token = Brak; return; } else if(token == '?') { token = Cond; return; } else if(token == '~' || token == ';' || token == '{' || token == '}' || token == '(' || token == ')' || token == ']' || token == ',' || token == ':') { //directly return the character as token return; } } return; } void match(int tk) { if(token == tk) { next(); } else { printf("%d: expected token: %d\n", line, tk); exit(-1); } } void expression(int level) { } void function_parameter() { int type; int params; params = 0; while(token != ')') { //int name, ... type = INT; if(token == Int) { match(Int); } else if(token == Char) { type = CHAR; match(Char); } //pointer type while(token == Mul) { match(Mul); type = type + PTR; } //parameter name if(token != Id) { printf("%d: bad parameter declaration\n", line); exit(-1); } if(current_id[Class] == Loc) { printf("%d: duplicate parameter declaration\n", line); exit(-1); } match(Id); //store the local variable current_id[BClass] = current_id[Class]; current_id[Class] = Loc; current_id[BType] = current_id[Type]; current_id[Type] = type; current_id[BValue] = current_id[Value]; current_id[Value] = params++; if(token == ',') { match(','); } } index_of_bp = params + 1; } void function_body() { //type func_name(...) {...} // -->| |<-- // ...{ // 1. local declarations // 2. statements // } int pos_local; //position of local variables on the stack int type; pos_local = index_of_bp; while(token == Int || token == Char) { //local variable declarations, just like global ones. basetype = (token == Int) ? INT : CHAR; match(token); while(token != ';') { type = basetype; while(token == Mul) { match(Mul); type = type + PTR; } } if(token != Id) { //invalid declarations printf("%d: bad local declaration\n", line); exit(-1); } if(current_id[Class] == Loc) { //identifier exists printf("%d: duplicate local declaration", line); exit(-1); } match(Id); //store the local variable current_id[BClass] = current_id[Class]; current_id[Class] = Loc; current_id[BClass] = current_id[Type]; current_id[Type] = type; current_id[BValue] = current_id[Value]; current_id[Value] = ++pos_local; // index of current parameter if(token == ',') { match(','); } } match(';'); //save the stack size for local variables *++text = ENT; *++text = pos_local - index_of_bp; //statements while(token != '}') { statement(); } //emit code for leaving the sub function *++text = LEV; } void function_declaratio() { //type func_name (...){...} // |this part match('('); function_parameter(); match(')'); match('{'); function_body(); //match('}'); //unwind local variable declarations for all local variables. current_id = symbols; while(current_id[Token]) { if(current_id[Class] == Loc) { current_id[Class] = current_id[BClass]; current_id[Type] = current_id[BType]; current_id[Value] = current_id[BValue]; } current_id = current_id + IdSize; } } void enum_declaration() { //parse enum [id] {a = 1, b = 3, ...} int i; i = 0; while(token != '}') { if(token != Id) { printf("%d:bad enum identifier %d\n", line, token); exit(-1); } next(); if(token == Assign) { //like {a=10} next(); if(token != Num) { printf("%d:bad enum initializer\n", line); exit(-1); } i = token_val; next(); } current_id[Class] = Num; current_id[Type] = INT; current_id[Value] = i++; if(token == ',') { next(); } } } void global_declaration() { //global_declaratio ::= enum_decl | variable_decl | function_decl // //enum_decl ::= 'enum' [id] '{' id ['=' 'num'] {',' id ['=' 'num'} '}' // //variable_decl ::= type {'*'} id {',' {'*'} id} ';' // //function_decl ::= type {'*'} id '(' parameter_decl ')' '{' body_decl '}' int type; //tmp,actual type for variable int i; //tmp basetype = INT; //parse enum, this should be treated alone. if(token == Enum) { //enum [id] {a = 10, b = 20, ...} match(Enum); if(token != '{') { match(Id); //skip the [id] part } if(token == '{') { //parse the assign part match('{'); enum_declaration(); match('}'); } match(';'); return; } //parse type information if(token == Int) { match(Int); } else if(token == Char) { match(Char); basetype = CHAR; } //parse the comma seperated variable declaration while(token != ';' && token != '}') { type = basetype; //parse pointer type, note that there may exist `int ****x;` while(token = Mul) { match(Mul); type = type + PTR; } if(token != Id) { //invalid declaration printf("%d:bad global declaration\n", line); exit(-1); } if(current_id[Class]) { //indentifier exists printf("%d:duplicate global declaration\n", line); exit(-1); } match(Id); current_id[Type] = type; if(token == '(') { current_id[Class] = Fun; current_id[Value] = (int)(text + 1); // the memory address of function function_declaration(); } else { //variable declaration current_id[Class] = Glo; //global variable current_id[Value] = (int)data; //assign memory address data = data + sizeof(int); } if(token == ',') { match(','); } } next(); } void program() { next(); while(token > 0) { global_declaration(); } } int eval() { int op, *tmp; while(1) { op = *pc++; //get next operation code //can't understand move instruction if(op == IMM) {ax = *pc++;} //load immediate value to ax else if(op == LC) {ax = *(char *)ax;} //load character to ax, address in ax else if(op == LI) {ax = *(int *)ax;} //load integer to ax, address in ax else if(op == SC) {ax = *(char *)*sp++ = ax;} //save character to address, value in ax, address pn stack else if(op == SI) {*(int *)*sp++ = ax;} //save integer to address, value in ax, address on stack else if(op == PUSH) {*--sp = ax;} //push the value of ax onto the stack else if(op == JMP) {pc = (int *)*pc;} //jump to the address else if(op == JZ) {pc = ax ? pc + 1 : (int *)*pc;} //jump if ax is zero else if(op == JNZ) {pc = ax ? (int *)*pc : pc + 1;} //jump if ax is zero else if(op == CALL) {*--sp = (int)(pc + 1); pc = (int *)*pc;} //call subroutine //else if(op == RET) {pc = (int *)*sp++;} //return from subroutine else if(op == ENT) {*--sp =(int)bp; bp = sp; sp = sp - *pc++;} //make new stack frame else if(op == ADJ) {sp = sp + *pc++;} //add esp,<size> else if(op == LEV) {sp = bp; bp = (int *)*sp++; pc = (int *)*sp++;} //restore call frame and pc else if(op == LEA) {ax = (int)(bp + *pc++);} //load address for argumentsi //operator else if(op == OR) ax = *sp++ | ax; else if(op == XOR) ax = *sp++ ^ ax; else if(op == AND) ax = *sp++ & ax; else if(op == EQ) ax = *sp++ == ax; else if(op == NE) ax = *sp++ != ax; else if(op == LT) ax = *sp++ < ax; else if(op == LE) ax = *sp++ <= ax; else if(op == GT) ax = *sp++ > ax; else if(op == GE) ax = *sp++ >= ax; else if(op == SHL) ax = *sp++ << ax; else if(op == SHR) ax = *sp++ >> ax; else if(op == ADD) ax = *sp++ + ax; else if(op == SUB) ax = *sp++ - ax; else if(op == MUL) ax = *sp++ * ax; else if(op == DIV) ax = *sp++ / ax; else if(op == MOD) ax = *sp++ % ax; //build-in function else if(op == EXIT) {printf("exit(%d)", *sp); return *sp;} else if(op == OPEN) {ax = open((char *)sp[1], sp[0]);} else if(op == CLOS) {ax = close(*sp);} else if(op == READ) {ax = read(sp[2], (char *)sp[1], *sp);} else if(op == PRTF) {tmp = sp + pc[1]; ax = printf((char *)tmp[-1], tmp[-2], tmp[-3], tmp[-4], tmp[-5], tmp[-6]);} else if(op == MALC) {ax = (int)malloc(*sp);} else if(op == MSET) {ax = (int)memset((char *)sp[2], sp[1], *sp);} else if(op == MCMP) {ax = memcmp((char *)sp[2], (char *)sp[1], *sp);} else { printf("unknown instruction:%d\n", op); return -1; } } return 0; } int main(int argc, char **argv) { int i, fd; argc--; argv++; //move to test file poolsize = 256 * 1024; //arbitrary size line = 1; if((fd = open(*argv, 0)) < 0) { printf("count not open(%s)\n", *argv); return -1; } if(!(src = old_src = malloc(poolsize))) { printf("count not malloc(%d) for source area\n", poolsize); return -1; } //read the source file if((i = read(fd, src, poolsize - 1)) <= 0) { printf("read() returned %d\n", i); return -1; } src[i] = 0; //add EOF character close(fd); //allocate memory for virtual machine if(!(text = old_text = malloc(poolsize))) { printf("count not malloc(%d) for text area\n", poolsize); return -1; } if(!(data = malloc(poolsize))) { printf("count not malloc(%d) for data area\n", poolsize); return -1; } if(!(stack = malloc(poolsize))) { printf("count not malloc(%d) for stack area\n", poolsize); return -1; } memset(text, 0, poolsize); memset(data, 0, poolsize); memset(stack, 0, poolsize); bp = sp = (int *)((int)stack + poolsize); ax = 0; src = "char else enum if int return sizeof while open read close printf malloc memset memcmp exit void main"; //add keywords to symbol table i = Char; while(i <= While) { next(); current_id[Token] = i++; } //add library to symbol table i = OPEN; while(i <= EXIT) { next(); current_id[Class] = Sys; current_id[Type] = INT; current_id[Value] = i++; } next(); current_id[Token] = Char; //handle void type next(); idmain = current_id; //keep track of main program(); return eval(); }
C
#include <stdio.h> #include <stdlib.h> //Software Engineer Name: Kariman Karam //All inputs are unsigned character /* - Define your global variables if needed here: actual_result expected_result - Please concider the memoery optimization. */ /* - Define your functional prototypes used here: sum unittest - Please concider optimum Misra C when writing your functions. */ //Prototype of the sum function int sum(unsigned char, unsigned char); //Prototype of the unittest function void unittest(int, int); int main() { //Please declare your initializations here. int num1, num2; int expected, actual; //Please define your infinite loop here. while(1) { //Please insert your screen visualization here. //Please write an expression that takes 2 numbers from the user here (concider screen readability). printf("\n\nPlease enter the first number to be added:"); scanf("%d",&num1); printf("Please enter the second number to be added:"); scanf("%d",&num2); printf("Please enter the Expected result:"); scanf("%d",&expected); //Please write an expression that calls the two function, the activation logic function and the unit test function in sequence. actual = sum(num1, num2); unittest(actual, expected); } return 0; } //Please write the functional description of the sum function here: int sum(unsigned char num1, unsigned char num2) { int result = (unsigned char)num1 + (unsigned char)num2; return result; } //Pleas write the functional description of the unittest function here: void unittest(int actual, int expected) { if(actual == expected) { printf("Test Case Passed\n"); } else { printf("Test Case Failed\n"); } }
C
#include "holberton.h" /** * print_times_table - print times tables. * *@n:is a number * Return: On succes print times table. * On error, dont return times table. */ void print_times_table(int n) { int i, j, mult, m; if(n < 15 && n > 0) { for (i = 0; i <= n; i++) { for (j = 0; j <= n; j++) { mult = i * j; if(mult < 100) { _putchar(mult / 10 + '0'); _putchar(mult % 10 + '0'); _putchar(' '); } else { m = mult / 10; _putchar(m / 10 + '0'); _putchar(m % 10 + '0'); _putchar(mult % 10 + '0'); _putchar(' '); } } _putchar('\n'); } } }
C
#include <stdio.h> #include <stdlib.h> void print_hex(char* buffer, int length){ int i; for(i=0; i<length; ++i){ printf("%hhX ", buffer[i]); } printf("\n"); } typedef struct virus { unsigned short length; char name[16]; char signature[]; } virus; void print_virus(virus* v){ printf("Virus name: %s\n", v->name); printf("Virus size: %d\n", (v->length-16-2)); printf("signature: \n"); print_hex(v->signature, v->length-16-2); } typedef struct link link; struct link { virus *v; link *next; }; void print_detected(virus* v, int i){ printf("Starting byte: %d\n", i); printf("Virus name: %s\n", v->name); printf("Virus size: %d\n", v->length-16-2); } int memcmp(char* buffer1, char* buffer2, unsigned int size){ int i; for(i=0; i<size; ++i){ if(buffer1[i]-buffer2[i]){ return buffer1[i]-buffer2[i]; } } return 0; } void clean_file(FILE* to_clean,unsigned int start,unsigned int size){ fseek(to_clean, start, SEEK_SET); int i; for(i=0; i<size; ++i){ fputc(0x90, to_clean); } } void detect_virus(char *buffer, link *virus_list, unsigned int size, FILE* sus){ int i; while(virus_list!=NULL){ for(i=0; i<size-virus_list->v->length; ++i){ if(memcmp(buffer+i, virus_list->v->signature, virus_list->v->length-18)==0){ print_detected(virus_list->v, i); clean_file(sus, i, virus_list->v->length-18); } } virus_list=virus_list->next; } } void list_print(link *virus_list){ while(virus_list!=NULL){ print_virus(virus_list->v); virus_list = virus_list->next; } } link* list_append(link* virus_list, virus* data){ if(virus_list!=NULL){ link* head = (link*)malloc(1*sizeof(link)); head->v = data; head->next = virus_list; return head; } else{ virus_list = (link*)malloc(1*sizeof(link)); virus_list->v = data; virus_list->next = NULL; return virus_list; } } void list_free(link *virus_list){ while(virus_list!=NULL){ link* temp = virus_list; virus_list = virus_list->next; free(temp->v); free(temp); } } int main(int argc, char **argv) { FILE* sig = fopen("lab3_signatures_opt_2", "r"); FILE* sus = fopen(argv[1], "r+"); char* buf = (char*)calloc(10000, sizeof(char)); int size = fread(buf, 1, 10000, sus); int big_endian_f = fgetc(sig); /* 0 for Little Endian, 1 for Big Endian*/ link* virus_list=NULL; unsigned short len; while(fread(&len, 1, 2, sig) > 0){ virus* v; if(big_endian_f){ len = ((len & 0xff) << 8) + ((len & 0xff00) >> 8); } v = (virus*)malloc(len); v->length = len; fread(((void*)v)+2, 1, v->length - 2, sig); virus_list = list_append(virus_list, v); } detect_virus(buf, virus_list, size, sus); list_free(virus_list); free(buf); fclose(sus); fclose(sig); return 0; }
C
#include <stdio.h> #include <stdlib.h> #define MAXLEN 14 #define MAX_STACK_SIZE 100000 #define MAX 455 #define MALLOC(p,s)\ if(!((p)=malloc(s))){\ fprintf(stderr,"Insufficient memory");\ exit(EXIT_FAILURE);\ } char* make1darr(int n){ char *x; MALLOC(x,n*sizeof(*x)); return x; } char*** make3darr(int rows, int cols,int hei){ char ***x; MALLOC(x,rows*sizeof(**x)); int i,j; for(i=0;i<rows;i++){ MALLOC(x[i],cols*sizeof(**x)); for(j=0;j<hei;j++){ MALLOC(x[i][j],hei*sizeof(***x)); } } return x; } int*** make3darrint(int rows, int cols,int hei){ int ***x; MALLOC(x,rows*sizeof(**x)); int i,j; for(i=0;i<rows;i++){ MALLOC(x[i],cols*sizeof(**x)); for(j=0;j<hei;j++){ MALLOC(x[i][j],hei*sizeof(***x)); } } return x; } typedef struct{ short int row; short int col; short int hei; short int dir;//記錄他跑的方向 } element; element stack[MAX_STACK_SIZE]; int top = -1; void stackFull(){ fprintf(stderr, "堆疊已滿,不能再加入元素"); exit(EXIT_FAILURE); } void push(element item){ if(top >=MAX_STACK_SIZE-1){ stackFull(); } stack [++top] = item; } element pop(){ if(top==-1){ fprintf(stderr, "堆疊已空"); } return stack[top--]; } element stack2[MAX_STACK_SIZE]; int top2 = -1; void push2(element item){ if(top2 >=MAX_STACK_SIZE-1){ }// stack2 [++top2] = item; } element pop2(){ /*if(top2==-1){ return }*/ return stack2[top2--]; } element queue[MAX_STACK_SIZE]; int rear = -1; int front = -1; void queueFull(){ fprintf(stderr, "佇列已滿,不能再加入元素"); exit(EXIT_FAILURE); } void addq(element item){ if(rear==MAX_STACK_SIZE-1){ queueFull(); } queue[++rear] = item; } element deleteq(){ if(front==rear){ fprintf(stderr, "佇列已空"); } return queue[++front]; } //六個方向---------- typedef struct{ short int vert; short int horiz; short int hei; }offsets; offsets move[6]; //------------------ int pathnum=0; int min=100000; int step=0; void path(char*** maze,char*** mark,char*** road,int sr,int sc,int sh,int n,int pnum){ step=0; min=100000; pathnum=0; top=-1; int i,j,k; /*//------------------test------------------ printf("maze!! \n"); for(i=0;i<n/2+1;i++){ for(j=i+1;j<n+2-i-1;j++){ for(k=i+1;k<n+2-i-1;k++){ printf("%c ",maze[i][j][k] ); } printf("\n"); } printf("\n"); } //-----------------------------------------*/ element position; int row,col,hei,dir; int nr,nc,nh; int countp=0; int found=1; int inproad=0; position.row = sr;//j position.col = sc;//k position.hei = sh;//i push(position); while(top>-1){ //printf("----------------------------------------------------\n",maze[0][3][1] ); position=pop(); row = position.row; col = position.col; hei = position.hei; dir = position.dir; if(!found){ //printf("dead road\n" ); while(top2>-1){ element lastposition = pop2();//上一個位置 int lr=lastposition.row;int lc=lastposition.col;int lh=lastposition.hei;int ld=lastposition.dir; //printf("last %d %d %d is %c\n",lh,lr,lc,maze[lh][lr][lc] ); //檢查是否已經倒到新的路開頭的上一步 if(lr+move[dir].vert==row && lc+move[dir].horiz==col && lh+move[dir].hei==hei ){ push2(lastposition);//是新的路開頭的上一步就不用消 加回stack2 break; } road[lh][lr][lc]=maze[lh][lr][lc];//倒車消除路 mark[lh][lr][lc]=maze[lh][lr][lc]; if(maze[lh][lr][lc]=='T'){ step=step-3; } else step--; if(maze[lh][lr][lc]=='P'){ countp--; } /*//------------------test------------------ road[lh][lr][lc]='&'; printf("reroad!! \n"); for(i=0;i<n/2+1;i++){ for(j=i+1;j<n+2-i-1;j++){ for(k=i+1;k<n+2-i-1;k++){ printf("%c ",road[i][j][k] ); } printf("\n"); } printf("\n"); } road[lh][lr][lc]=maze[lh][lr][lc]; printf("countp %d\n\n",countp ); printf("remark!! \n"); for(i=0;i<n/2+1;i++){ for(j=i+1;j<n+2-i-1;j++){ for(k=i+1;k<n+2-i-1;k++){ printf("%c ",mark[i][j][k] ); } printf("\n"); } printf("\n"); } printf("countp %d\n\n",countp ); printf("step %d\n\n",step ); //-----------------------------------------*/ } } mark[hei][row][col]='X'; road[hei][row][col]='*'; if(maze[hei][row][col]=='T'){ step=step+3; } else step++; if(maze[hei][row][col]=='P'){ inproad=1; countp++; } if(countp==pnum){ inproad=0; } push2(position); printf("now %d %d %d\n",hei,row,col ); //------------------test------------------ road[hei][row][col]='@'; printf("road!! \n"); for(i=0;i<n/2+1;i++){ for(j=i+1;j<n+2-i-1;j++){ for(k=i+1;k<n+2-i-1;k++){ printf("%c ",road[i][j][k] ); } printf("\n"); } printf("\n"); } printf("countp %d\n\n",countp ); printf("mark!! \n"); for(i=0;i<n/2+1;i++){ for(j=i+1;j<n+2-i-1;j++){ for(k=i+1;k<n+2-i-1;k++){ printf("%c ",mark[i][j][k] ); } printf("\n"); } printf("\n"); } printf("countp %d\n\n",countp ); printf("step %d\n\n",step ); road[hei][row][col]='*'; //-----------------------------------------*/ if(maze[hei][row][col]=='F' && countp==pnum){ pathnum++; if(min>step){ min=step; } printf("finally------------------------------------------------\n" ); //------------------test------------------ printf("road!! \n"); for(i=0;i<n/2+1;i++){ for(j=i+1;j<n+2-i-1;j++){ for(k=i+1;k<n+2-i-1;k++){ printf("%c ",road[i][j][k] ); } printf("\n"); } printf("\n"); } printf("countp %d pnum %d\n",countp,pnum ); printf("step %d\n\n",step ); printf("pathnum %d\n",pathnum ); //-------------------------------------------------- // } //run---------------------------------------------- found=0; for(i=0;i<4;i++){ nr = row+move[i].vert; nc = col+move[i].horiz; nh = hei+move[i].hei; if(inproad){ if(mark[nh][nr][nc]!='X' && maze[nh][nr][nc]=='P'){ found=1; //printf("push %d %d %d\n",nh,nr,nc ); element nextposition; nextposition.row=nr;nextposition.col=nc;nextposition.hei=nh;nextposition.dir=i; push(nextposition); } } else{ if(mark[nh][nr][nc]!='X'){ found=1; //printf("push %d %d %d\n",nh,nr,nc ); element nextposition; nextposition.row=nr;nextposition.col=nc;nextposition.hei=nh;nextposition.dir=i; push(nextposition); } } } if(maze[hei][row][col]=='U' || maze[hei][row][col]=='P'){ if(inproad){ if(mark[nh][nr][nc]!='X' && maze[hei+1][row][col]=='P'){ found=1; element nextposition; nextposition.row=row;nextposition.col=col;nextposition.hei=hei+1;nextposition.dir=4; push(nextposition); } } else{ if(mark[hei+1][row][col]!='X'){ //printf("push %d %d %d\n",hei+1,row,col ); found=1; element nextposition; nextposition.row=row;nextposition.col=col;nextposition.hei=hei+1;nextposition.dir=4; push(nextposition); } } } if((maze[hei][row][col]=='D' || maze[hei][row][col]=='P')&& hei>0){ if(inproad){ if(mark[nh][nr][nc]!='X' && maze[hei-1][row][col]=='P'){ found=1; element nextposition; nextposition.row=row;nextposition.col=col;nextposition.hei=hei-1;nextposition.dir=5; push(nextposition); } } else{ if(mark[hei-1][row][col]!='X'){ //printf("push %d %d %d\n",hei+1,row,col ); found=1; element nextposition; nextposition.row=row;nextposition.col=col;nextposition.hei=hei-1;nextposition.dir=5; push(nextposition); } } } } } /* int bfs(char*** maze,int*** d,int sr,int sc,int sh,int n,int pnum){ printf("rear : %d\n",rear ); rear=-1;front=-1; int countp; int arrive=0;//檢查有沒有到終點 之後要return element position; position.row = sr;//j position.col = sc;//k position.hei = sh;//i //紀錄起始位置 addq(position);//將起點放進queue int i,j,k; for(i=0;i<n/2+1;i++){ for(j=0;j<n+2;j++){ for(k=0;k<n+2;k++){ d[i][j][k]=MAX; } } } d[sh][sr][sc]=0; //初始化所有格子道起點的距離為MAX,起點道起點距離為0 int nr,nc,nh;//移動後位置 int row,col,hei;//現在位置 while(rear!=front){ //printf("rear: %d front: %d\n",rear,front ); //------------------test------------------ printf("d!! \n"); for(i=0;i<n/2+1;i++){ for(j=i+1;j<n+2-i-1;j++){ for(k=i+1;k<n+2-i-1;k++){ printf("%5d ",d[i][j][k] ); } printf("\n"); } printf("\n"); } //----------------------------------------- position = deleteq(); row = position.row; col = position.col; hei = position.hei; //把現在位置(已知距離)拿出來 //----------------test-------------------- if(maze[hei][row][col]=='F' && countp!=pnum){//如果現在在終點 printf("p is not enough\n"); } //--------------------------------------- if(maze[hei][row][col]=='F' && countp==pnum){//如果現在在終點 //檢查有沒有到終點 之後要return if(min>d[hei][row][col]){ min = d[hei][row][col];///記錄下min } min = d[hei][row][col]; //記錄下min arrive=1; } //跑方向------------------------------------------------------- if(maze[hei][row][col]=='U' || maze[hei][row][col]=='D'){ int upanddown=-1; if(maze[hei][row][col]=='U'){ //printf("meet U\n"); upanddown=1; } //決定是上是下 nr = row; nc = col; nh = hei+upanddown; //下一個位置是哪 if(nh>=0){ if (maze[nh][nr][nc]!='X' && (d[nh][nr][nc]>d[hei][row][col]+1 || maze[nh][nr][nc]=='P')){//可以走且沒走過/找到更短的路 d[nh][nr][nc]=d[hei][row][col]+1;//下個位置的距離是現在位置距離+1 if(maze[nh][nr][nc]=='T'){//遇到陷阱是+3 d[nh][nr][nc]=d[nh][nr][nc]+2; } element nextposition; nextposition.row=nr;nextposition.col=nc;nextposition.hei=nh; addq(nextposition);//把下個位置加進去queue } } } else if(maze[hei][row][col]=='P'){ countp++; for(i=-1;i<=1;i=i+2){ nr = row; nc = col; nh = hei+i; //下一個位置是哪 if(nh>=0){ if (maze[nh][nr][nc]!='X' && (d[nh][nr][nc]>d[hei][row][col]+1 || maze[nh][nr][nc]=='P')){//可以走且沒走過/找到更短的路 d[nh][nr][nc]=d[hei][row][col]+1;//下個位置的距離是現在位置距離+1 if(maze[nh][nr][nc]=='T'){//遇到陷阱是+3 d[nh][nr][nc]=d[nh][nr][nc]+2; } element nextposition; nextposition.row=nr;nextposition.col=nc;nextposition.hei=nh; addq(nextposition);//把下個位置加進去queue } } } } //ODU都可以跑四方 for(i=0;i<4;i++){ nr = row+move[i].vert; nc = col+move[i].horiz; nh = hei+move[i].hei; if (maze[nh][nr][nc]!='X' && (d[nh][nr][nc]>d[hei][row][col]+1 || maze[nh][nr][nc]=='P')){ d[nh][nr][nc]=d[hei][row][col]+1; if(maze[nh][nr][nc]=='T'){ d[nh][nr][nc]=d[nh][nr][nc]+2; } element nextposition; nextposition.row=nr;nextposition.col=nc;nextposition.hei=nh; addq(nextposition); } } //------------------------------------------------------------------------ } return arrive; } */ int main(){ move[0].vert=-1; move[0].horiz=0; move[0].hei=0; move[1].vert=0; move[1].horiz=1; move[1].hei=0; move[2].vert=1; move[2].horiz=0; move[2].hei=0; move[3].vert=0; move[3].horiz=-1; move[3].hei=0; move[4].vert=0; move[4].horiz=0; move[4].hei=1; move[5].vert=0; move[5].horiz=0; move[5].hei=-1; //定義跑的方向 int n=0;//底層邊長 char y;//抓第一航輸入的換行字元 int i,j,k; FILE *pfile; char name[50]; int control; for(control=2;control<=2;control++){//for sprintf(name,"test%d.txt",control); pfile = fopen(name,"r"); if(NULL==pfile){ printf("Open failure"); return 1; } else{//---------------------------------------------------------------------- printf("reading %s\n",name); //輸入的第一行先存在一一維陣列 char* bottom = make1darr(MAXLEN); int n=0; char y; bottom[n]=fgetc(pfile); while(bottom[n]!='\n'){ fgetc(pfile); bottom[++n]=fgetc(pfile); //printf("y: %c\n",y); } char ***maze=make3darr(n/2+1,n+2,n+2);//地圖 char ***road=make3darr(n/2+1,n+2,n+2);//要印出的路徑 char ***mark=make3darr(n/2+1,n+2,n+2);//跑過的打X int ***d=make3darrint(n/2+1,n+2,n+2);//距離 int len=0;//因為要對其所有二微陣列疊成三維振烈 所以上面的陣列會有一邊邊的寬度len int sr,sc,sh;//起始位置 int pnum=0; for(i=0;i<n/2+1;i++){//高度是n/2+1 for(j=0;j<n+2;j++){//弄一個大邊邊所以+2 for(k=0;k<n+2;k++){ if(j==0 || k==0 || j==n+1 || k==n+1){ maze[i][j][k]='X';//圍起每層地圖的大邊邊 } else if(i==0 && j==1){//一樓第一列把bottom[]複製進去 maze[i][j][k]=bottom[k-1];//地圖有大邊邊所以是從1開始喔 } else if(j > len && j <= n-len && k > len && k <= n-len){ fscanf(pfile,"%c ",&maze[i][j][k]);//len+1~n-len*len+1~n-len都是要輸入的地圖 } else{ maze[i][j][k]='X';//寬度為len的邊邊 } if(maze[i][j][k]=='S'){//起始位置 sh=i; sr=j; sc=k; } if(maze[i][j][k]=='P'){ pnum++; } road[i][j][k]=maze[i][j][k]; mark[i][j][k]=maze[i][j][k];//road mark 複製一下 } } len++;//邊邊寬度+1 }//for /* printf("PNUM %d\n",pnum ); //------------------test------------------ printf("maze!! \n"); for(i=0;i<n/2+1;i++){ for(j=i+1;j<n+2-i-1;j++){ for(k=i+1;k<n+2-i-1;k++){ printf("%c ",maze[i][j][k] ); } printf("\n"); } printf("\n"); } //-----------------------------------------*/ FILE *wfile; wfile = fopen( "4108056029output.txt","a" ); if( NULL == wfile ){ printf( "wfile open failure" ); return 1; } else{ fprintf(wfile, "test%d Starts now.\n",control ); /*if(bfs(maze,d,sr,sc,sh,n,pnum)){//如果有路到終點 //------------------test------------------ printf("d!! \n"); for(i=0;i<n/2+1;i++){ for(j=i+1;j<n+2-i-1;j++){ for(k=i+1;k<n+2-i-1;k++){ printf("%5d ",d[i][j][k] ); } printf("\n"); } printf("\n"); } printf("min %d\n",min ); //----------------------------------------- */ if(1){ //printf("min %d\n",min ); mark[sh][sr][sc]='X'; pathnum=0; path(maze,mark,road,sr,sc,sh,n,pnum); printf("Shortest path: %d, The number of different paths: %d\n\n",min-1,pathnum); fprintf(wfile,"Shortest path: %d, The number of different paths: %d\n\n",min-1,pathnum); } else fprintf(wfile,"The maze does not have a path\n" ); } free(bottom); free(maze); free(mark); free(road); free(d); }//else---------------------------------------------------------------------- fclose(pfile); } }
C
#include "resource_table_empty.h" #include "pru.h" #include <stdint.h> #define P9_31 0 volatile register uint32_t __R30; volatile register uint32_t __R31; uint8_t *shared_memory = (uint8_t*)(0x10000); // TODO: multiple channels/pins // E.g. ws281x(0xFF00FF, P9_31) void write_ws281x(uint32_t pixel, int pin) { int i; for (i=0; i<24; i++) { int bit = (pixel >> (23-i)) & 0x1; // Set high __R30 |= (1 << pin); if (bit) { __delay_cycles(700/5); // T1H=700ns } else { __delay_cycles(350/5); // T0H=350ns } __R30 &= ~(1 << pin); if (bit) { __delay_cycles(600/5); // T1L=600ns } else { __delay_cycles(800/5); // T0L=800ns } } } void ws281x_reset(int pin) { __R30 &= ~(1 << pin); __delay_cycles(10000); // 50us } void main(void) { struct pru_ctrl *ctrl = (struct pru_ctrl *)shared_memory; ctrl->state = PRU_STATE_IDLE; ctrl->num_pixels = 0; __R30 = 0; while (1) { while (ctrl->state == PRU_STATE_IDLE); int i; for (i=0; i<ctrl->num_pixels; i++) { write_ws281x(ctrl->pixels[i], P9_31); } // Let user write while we block on the reset ctrl->state = PRU_STATE_IDLE; ws281x_reset(P9_31); } //__halt(); }
C
/* ** EPITECH PROJECT, 2019 ** MUL_my_defender_2018 ** File description: ** combat */ #include "my_defender.h" static void manage_collision(game_t *game, entity_t *ally, entity_t *enemy) { if (ally->type == 'b' && enemy->type != 'b') ally->life--; else if (ally->type != 'b' && enemy->type != 'b') { ally->life--; enemy->life--; game->score += 100; } else { enemy->life--; game->score += 100; } } static void check_intersection(game_t *game, head_t *ally_army, head_t *enemy_army, sfFloatRect *rect) { while (enemy_army->act) { rect[1] = sfSprite_getGlobalBounds(enemy_army->act->sprite); if (sfFloatRect_intersects(&rect[0], &rect[1], NULL)) manage_collision(game, ally_army->act, enemy_army->act); enemy_army->act = enemy_army->act->next; } } void check_collision(game_t *game, head_t *ally_army, head_t *enemy_army) { sfFloatRect *rect = malloc(sizeof(sfFloatRect) * 2); if (!rect) return; ally_army->act = ally_army->first; enemy_army->act = enemy_army->first; while (ally_army->act) { rect[0] = sfSprite_getGlobalBounds(ally_army->act->sprite); check_intersection(game, ally_army, enemy_army, rect); enemy_army->act = enemy_army->first; ally_army->act = ally_army->act->next; } free(rect); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #define Tam 5 void inicializa(int matriz[Tam][Tam]){ srand(time(NULL)); int num_rnd; for (int j=0;j<Tam;j++){ for (int i=0;i<Tam;i++){ num_rnd=3+(rand()%13); matriz[i][j]=num_rnd; } } } int main(){ int matriz[Tam][Tam]; inicializa(matriz); for (int j=0;j<Tam;j++){ for(int i=0;i<Tam;i++){ printf("%i ",matriz[i][j]); } printf("\n"); } return 0; }
C
/* *代码作用:确定主机字节序程序 */ #include <stdio.h> #include <arpa/inet.h> int main(int argc, char *argv[]) { int a = 0x01020304; short int b = 0x0102; union { short s; char c[sizeof(short)]; }un; un.s = 0x0102; if( (un.c[0] == 1)&& (un.c[1] == 2)) { printf("big-endian\n"); } else if((un.c[0] == 2) && (un.c[1] == 1)) { printf("little-endian\n"); } printf("htonl(%08x) = %08x\n",a,htonl(a)); printf("htonl(%04x) = %04x\n",b,htons(b) ); return 0; }
C
#include <SDL2/SDL.h> #include <SDL2/SDL2_gfxPrimitives.h> #include <stdio.h> #include <stdbool.h> #include "Headers\Init.h" #include "Headers\Header.h" void init() { int SCREEN_WIDTH = 960; int SCREEN_HEIGHT = 540; //!ISDL inicializalasa if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 ) { printf( "Nem sikerult az SDL-t inicializalni! SDL_Error: %s\n", SDL_GetError() ); } else { //!Ablak letrehozasa window = SDL_CreateWindow( "MyDigitalFarm", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if( window == NULL ) { printf( "Nem sikerult az ablakot letrehozni! SDL_Error: %s\n", SDL_GetError() ); } else { //!Felulet letrehozasa surface = SDL_GetWindowSurface( window ); if( surface == NULL) { printf( "Nem sikerult a feluletet letrehozni! SDL_Error: %s\n", SDL_GetError() ); } else { renderer = SDL_CreateRenderer(window, -1, 0); if( renderer == NULL) { printf( "Nem sikerult a renderer-t letrehozni! SDL_Error: %s\n", SDL_GetError() ); } } SDL_StartTextInput(); } } }
C
#include <stdio.h> int main(void) { int n,k,i,l; scanf("%d %d",&n,&k); if(n>k) {l=n; } else { l=k; } for(i=l;i>=2;i--) { if(n%i==0 && k%i==0) { printf("%d\n ",i); }} return 0; }
C
#include <stdio.h> void print_binary(int number) { if (number) { print_binary(number >> 1); putc((number & 1) ? '1' : '0', stdout); } } unsigned short swap_bytes(unsigned short i) { return ((0x0ff & i) << 8) | ((0xff00 & i) >> 8); } int main(void) { unsigned short x = 0x1234; // 0001 0010 0011 0100 x = swap_bytes(x); // 0011 0100 0001 0010 print_binary(x); printf("\n"); printf("%hx\n", x); // print hex }
C
#ifndef _REENTRANT #define _REENTRANT #endif #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> #include <time.h> #define TRUE 1 #define FALSE 1 #define MAX_WORMS 128 #define MAX_BABY 7 sem_t empty, refill, wormlock; int worms; void* Parent(void* arg); void* Baby(void* arg); int main(int argc, char* argv[]) { if (argc < 3) { fprintf(stderr, "Usage: ./birds <worms> <babies>\n"); exit(-1); } int numWorm = (atoi(argv[1]) < MAX_WORMS) ? atoi(argv[1]) : MAX_WORMS; int numBaby = (atoi(argv[2]) < MAX_BABY) ? atoi(argv[2]) : MAX_BABY; pthread_t p; pthread_t b[numBaby]; worms = numWorm; srand(time(NULL)); sem_init(&empty, FALSE, 0); sem_init(&refill, FALSE, 0); sem_init(&wormlock, FALSE, 1); printf("Hungry birds starting with %d worms, and %d baby bird(s)\n", numWorm, numBaby); pthread_create(&p, NULL, Parent, &numWorm); for (long i = 0; i < numBaby; i++) pthread_create(&b[i], NULL, Baby, (void*)i); pthread_exit(NULL); } void* Parent(void* arg) { int* numWorm = arg; while (TRUE) { // wait for dish to be empty sem_wait(&empty); printf("\nparent bird is fetching worms... \n"); #ifndef NOSLEEP sleep((rand()%4 + 2)); #endif worms = *numWorm; printf("worms refilled!\n\n"); sem_post(&refill); } } void* Baby(void* arg) { long id = (long)arg; while (TRUE) { // take lock sem_wait(&wormlock); printf("baby bird %ld wants to eat... ", id); // any worms left? if (worms > 0) { worms--; printf("It ate a worm! %d worms left\n", worms); sem_post(&wormlock); // go to sleep. #ifndef NOSLEEP sleep((rand()%4 + 2)); #endif } else { sem_post(&empty); printf("No worms! bird %ld is chirping!\n", id); sem_wait(&refill); worms--; printf("baby bird %ld ate a worm! %d worms left\n", id, worms); sem_post(&wormlock); #ifndef NOSLEEP sleep((rand()%4 + 2)); #endif } } }
C
#include "iodefine.h" // portA LED #define LED_IO PORTA.PDR.BYTE #define LED PORTA.PODR.BYTE void turnOnLed(char status); void turnOnAllLed(); void turnOffAllLed(void); void initLed() { LED_IO = 0xff; } void turnOnAllLed(void) { turnOnLed(0xff); } void turnOffAllLed(void) { turnOnLed(0x00); } void turnOnLed(char status) { LED = status; }
C
#include<stdio.h> float main() { float a,b,c; printf("key in the first number"); scanf("%f", &a); printf("key in the second number"); scanf("%f", &b); c=a+b; printf("The input value of a = %f\n",a); printf("The input value of b = %f\n",b); printf("The output value of c after addition of a & b = %f\n",c); }
C
#include <stdio.h> #include <mpi.h> #define SENDER 0 #define RECEIVER 1 int main (int argc, char **argv) { // rank = id-ul procesului // proc = numarul de procese int rank, proc, a; // initializam procesele MPI_Init(&argc, &argv); // fiecare proces are un rank MPI_Comm_rank(MPI_COMM_WORLD, &rank); // rank // stabilim numarul de procese MPI_Comm_size(MPI_COMM_WORLD, &proc); // send si receive // un proces ii trimite informatia altui proces if (rank == SENDER) { a = 69; MPI_Send(&a, 1, MPI_INT, 1, 0, MPI_COMM_WORLD); printf("Value %d was sent by the process no. %d\n", a, rank); } if (rank == RECEIVER) { MPI_Recv(&a, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); printf ("Process no. %d got value %d\n\n", rank, a); } MPI_Finalize(); return 0; }
C
/* * This file is part of the ESIZON distribution. * Copyright (c) 2020 Ruben Cordero Ramos. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "utils.h" void clearBuffer() { while ((getchar()) != '\n'); } char *toLowerCase(char *str) { unsigned int length = strlen(str); char *tmpString = allocate(sizeof(char)*(length+1), "tmp String to low case"); tmpString[length] = '\x00'; for(int i = 0; i < length; i++) { if(str[i] >= 65 && str[i] <= 90) tmpString[i] = str[i]+32; else tmpString[i] = str[i]; } return tmpString; } void cleanUpUser(User *user) { switch (user->userType) { case client: printf("Client!\n"); for(int i = 0; i < ClientFieldNumber; i++) { deallocate(user->clientUser.fields[i], "exit user client cleanup"); } break; case carrier: printf("Carrier!\n"); for(int i = 0; i < CarrierFieldNumber; i++) { deallocate(user->carrierUser.fields[i], "exit user carrier cleanup"); } break; case admin: case provider: printf("Admin/Provider!\n"); for(int i = 0; i < AdminProviderFieldNumber; i++) { deallocate(user->adminProviderUser.fields[i], "exit user adminprovider cleanup"); } break; default: break; } deallocate(user, "User"); } void copyClient(Client *dest, Client src) { dest->id = src.id; dest->wallet = src.wallet; for(int i = 0; i < ClientFieldNumber; i++) { dest->fields[i] = allocate(sizeof(char)*(strlen(src.fields[i])+1), "field in client login"); strcpy(dest->fields[i], src.fields[i]); } } void copyAdminProvider(AdminProvider *dest, AdminProvider src) { dest->id = src.id; for(int i = 0; i < AdminProviderFieldNumber; i++) { dest->fields[i] = allocate(sizeof(char) * (strlen(src.fields[i]) + 1), "field in admin provider login"); strcpy(dest->fields[i], src.fields[i]); } } void copyCarrier(Carrier *dest, Carrier src) { dest->id = src.id; for(int i = 0; i < CarrierFieldNumber; i++) { dest->fields[i] = allocate(sizeof(char) * (strlen(src.fields[i]) + 1), "field in carrier login"); strcpy(dest->fields[i], src.fields[i]); } } bool isValidLine(char *tmp) { bool validLine = false; unsigned int lineLength = strlen(tmp); for(int i = 0; i < lineLength; i++) { //if(!iscntrl(tmp[i])) if(tmp[i] != '\n' && tmp[i] != '\r') validLine = true; } return validLine && lineLength > 0; } char *getNextID(int lastID, unsigned int length) { //char *finalString = malloc(sizeof(char)*6); char *tmp = allocate(sizeof(char) * length, "Next ID final string"); for(int i = 0; i < length; i++) tmp[i] = '0'; printf("Last id: %d\n", lastID); unsigned int pos = strlen(tmp) - 1; int tmpID = lastID+1; while(tmpID > 0) { tmp[pos] = tmpID % 10 + '0'; tmpID /= 10; pos--; } printf("Final id: %s\n", tmp); return tmp; } bool askCorrect() { char answer; printf("Is that correct? y/n\n"); clearBuffer(); scanf("%c", &answer); if(answer == 'y' || answer == 'Y') { return true; } return false; } char *askForField(char *msg, bool confirm) { char buffer[1024]; char *dest = nullptr; if(confirm) { bool correct = false; do { printf("%s: ", msg); clearBuffer(); scanf("%[^\n]", buffer); //dest = malloc(sizeof(char)*(strlen(buffer)+1)); dest = allocate(sizeof(char)*(strlen(buffer)+1), "Field dest ask for field"); if(askCorrect()) { strcpy(dest, buffer); correct = true; } else { //free(dest); deallocate(dest, "Field dest ask for field"); } } while(!correct); } else { printf("%s: ", msg); scanf("%s", buffer); //dest = malloc(sizeof(char)*(strlen(buffer)+1)); dest = allocate(sizeof(char)*(strlen(buffer)+1), "Field dest"); strcpy(dest, buffer); } return dest; } void askForExit(int *flag) { char answer; printf("Do you want to exit? y/n\n"); clearBuffer(); scanf("%c", &answer); if(answer == 'y' || answer == 'Y') { *flag = exitFlag; } } char *concatenate(char *a, char *b) { unsigned int aSize = strlen(a); unsigned int bSize = strlen(b); unsigned int finalSize = aSize+bSize; //a = realloc(a, sizeof(char)*(finalSize+1)); a = reallocate(a, sizeof(char)*(finalSize+1), "Concatenate a"); int bCounter = 0; for(unsigned int i = aSize; i < finalSize; i++) { a[i] = b[bCounter]; bCounter++; } a[finalSize] = '\0'; //printf("Final string: %s\n", a); return a; } char *concatenateChar(char *a, char b) { unsigned int aSize = strlen(a); unsigned int finalSize = aSize+1; //a = realloc(a, sizeof(char)*(finalSize+1)); a = reallocate(a, sizeof(char)*(finalSize+1), "Concatenate char 'a'"); a[finalSize-1] = b; a[finalSize] = '\0'; return a; } char *toFileStringClient(Client client) { //char *tmp = malloc(sizeof(char)*1); char *tmp = allocate(sizeof(char), "Tmp to file string client"); tmp[0] = '\x00'; int field = 0; int totalFields = ClientFieldNumber + ClientFieldNumber-1; for(int i = 0; i < totalFields; i++) { printf("i: %d\n", i); if(i % 2 == 0) { tmp = concatenate(tmp, client.fields[field]); field++; } else { tmp = concatenateChar(tmp, '/'); } printf("-> %s\n", tmp); } tmp = concatenateChar(tmp, '\n'); return tmp; } unsigned int getFieldLength(char *input) { unsigned int pos = 0; int found = 0; for(int i = 0; i < strlen(input) && !found; i++) { if(input[i] == '/' || input[i] == '\n' || input[i] == EOF || input [i] == '\x00') { pos = i; found = 1; } } pos = found == 0 ? strlen(input) : pos; return pos; } void sanitize(char *string) { #ifdef DEBUG printf("Sanitazing...\n"); #endif bool hasToSanitize = false; unsigned int stringLength = strlen(string); int pos = 0; for(int i = 0; i < stringLength; i++) { if(string[i] == '\n' || string[i] == '\r') { hasToSanitize = true; pos = i; } } if(hasToSanitize) { string = reallocate(string, sizeof(char)*pos, "sanitize string..."); string[pos] = '\x00'; sanitize(string); } } void truncateString(char *input, unsigned int startPos) { int finalLength = strlen(input) - startPos; if (finalLength > 0) { #ifdef DEBUG printf("final length: %d\n", finalLength); #endif //char *tmp = malloc(sizeof(char) * finalLength + sizeof(char)); char *tmp = allocate(sizeof(char) * finalLength + sizeof(char), "tmp truncate string"); unsigned int pos = startPos; for (int i = 0; i < finalLength; i++) { tmp[i] = input[pos]; pos++; } tmp[finalLength] = '\x00'; //input = realloc(input, sizeof(char) * finalLength + sizeof(char)); input = reallocate(input, sizeof(char) * finalLength + sizeof(char), "Input truncate"); for (int i = 0; i < finalLength + 1; i++) { input[i] = tmp[i]; } deallocate(tmp, "tmp truncate string"); } } char *copyUntil(const char *sString, unsigned int pos) { //char *tmpString = malloc(sizeof(char) * pos + sizeof(char)); char *tmpString = allocate(sizeof(char) * pos + sizeof(char), "Copy until tmp string"); for (int i = 0; i < pos; i++) { tmpString[i] = sString[i]; } tmpString[pos] = '\x00'; return tmpString; }
C
#include <stdio.h> struct stu_info { char name[41]; long int id; char dept[16]; short int class; float gpa; }; void setInfo(struct stu_info s[], int size) { int i; for(i=0;i<size;i++){ printf("%d-th student\nEnter name:",i+1); scanf("%s",s[i].name); printf("\nEnter id:"); scanf("%ld",&s[i].id); printf("\nEnter dept:"); scanf("%s",s[i].dept); printf("\nEnter class:"); scanf("%d",&s[i].class); printf("\nEnter gpa:"); scanf("%f",&s[i].gpa); printf("\n"); } } int main(){ int size = 10; struct stu_info student[size]; int i; float avg=0; setInfo(student, size); for (i=0; i<size; i++) avg += student[i].gpa; printf("avg %f\n",avg/size); return 0; }
C
//---------------------------------------------------------- // I2C用関数 by Takuya Matsubara //---------------------------------------------------------- #include <avr/io.h> char i2c_wait(void); void i2c_start(); void i2c_stop(); void i2c_writebyte(unsigned char dat); unsigned char i2c_readbyte(char noack); #ifndef F_CPU #define F_CPU 8000000 //CPUクロック周波数 8MHz #endif //---------------------------------------------------------- // I2C初期化 void i2c_init(long bitrate) { TWSR = 0; //プリスケーラ値 CLK/1 TWBR = ((F_CPU / bitrate) - 16) / (2*1); // SCLの周波数 TWCR = (1 << TWEN); } //---------------------------------------------------------- // 通信終了までウエイト // 戻り値:0=正常 / -1=エラー char i2c_wait(void) { while((TWCR & (1 << TWINT))==0){ } switch(TWSR) { case 0x20: //TW_MT_SLA_NACK case 0x58: //TW_MR_DATA_NACK case 0x38: //TW_MT_ARB_LOST return(-1); // エラー発生 break; default: break; } return(0); // 正常終了 } //---------------------------------------------------------- // 通信開始 void i2c_start() { TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN); i2c_wait(); } //---------------------------------------------------------- // 通信終了 void i2c_stop() { TWCR = (1<<TWINT) | (1<<TWSTO) | (1<<TWEN); } //---------------------------------------------------------- // 1バイト送信 void i2c_writebyte(unsigned char dat) { TWDR = dat; TWCR = (1<<TWINT) | (1<<TWEN); i2c_wait(); } //---------------------------------------------------------- // 1バイト受信 unsigned char i2c_readbyte(char noack) { if (noack) { TWCR = (1<<TWINT)|(1<<TWEN); //NO ACK } else { TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA); //ACK } i2c_wait(); return (TWDR); } //---------------------------------------------------------- // EEPROM書き込み // 引数(スレーブアドレス,アドレス,データ,バイト数) void i2c_2_write( unsigned char addr, unsigned char* data, unsigned char bytecnt) { i2c_start(); i2c_writebyte(0xD0); // SLA + W i2c_writebyte(addr); // address(high 8bits) while(bytecnt > 0){ i2c_writebyte(*data++); bytecnt--; } i2c_stop(); } //---------------------------------------------------------- // EEPROM読み込み // 引数(スレーブアドレス,アドレス,データ,バイト数) void i2c_2_read( unsigned char addr, unsigned char* data, unsigned char bytecnt) { i2c_start(); i2c_writebyte(0xD0); // SLA + W i2c_writebyte(addr); // address(high 8bits) i2c_start(); i2c_writebyte(0xD1); // SLA + R while(bytecnt > 0){ *data++ = i2c_readbyte(bytecnt == 1); bytecnt--; } i2c_stop(); }
C
#include <stdio.h> #define PI 3.14159 int main(void) { double radius; printf("Enter radius: "); scanf("%lf", &radius); printf("volume is: %lf \n\n", 4.0*PI*radius*radius*radius/3.0); return 0; }
C
/* * ===================================================================================== * * Filename: even_odd.c * * Description: determine if value is even or odd * * Version: 1.0 * Created: 01/24/2019 09:36:37 AM * Revision: none * Compiler: gcc even_odd.c -o even_odd.out -lm * * Author: Tyler Whitmore (), tylerwhitmore@mail.weber.edu * Organization: WSU * * ===================================================================================== */ #include <stdio.h> #include <math.h> #include <stdbool.h> // Constants // Function Prototypes // Main Function int main() { int num1,num2; bool passed = true; printf("Enter some even number: "); scanf("%d",&num1); printf("Enter some odd number: "); scanf("%d",&num2); if (num1%2 != 0){ printf("%d was not even\n",num1); passed = false; } if (num2%2 == 0){ printf("%d was not odd\n",num2); passed = false; } if(passed == true){ printf("%d was even and %d was odd\n",num1,num2); } return 0; } // Function Definitions
C
#include<stdio.h> #define gc getchar_unlocked int find() { char c=gc(); while(c<'0'||c>'9') c=gc(); int count=0; while(c>='0'&&c<='9') { if(c=='4') count++; c=gc(); } return count; } int main() { int t,d; char ch; scanf("%d",&t); while(t--) { printf("%d\n",find()); } return 0; }
C
#include "init.h" #include <SDL.h> void Game_init(int width, int height, SDL_Window **pwindow, SDL_Renderer **prenderer, HandList *hand, TTF_Font **font, t_board board[15][15], t_Stones *Stones, previous_step *rst, int *RandTable, HandPosition *posOfHands, int *prev){ //Initializing of SDL libraries if(SDL_Init(SDL_INIT_EVERYTHING) < 0){ SDL_Log("Couldn't initialize SDL: %s", SDL_GetError()); exit(1); } //Create Window SDL_Window *window = SDL_CreateWindow("Scrabble v1.0", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, 0); if(window == NULL){ SDL_Log("Couldn't create window: %s", SDL_GetError()); exit(1); } //Create Renderer SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE); if(renderer == NULL){ SDL_Log("Couldn't create renderer: %s", SDL_GetError()); exit(1); } SDL_RenderClear(renderer); //initializing most important arrays / matrices generateStones(Stones); defineBoard(board, rst); //initializing font and hand initFont(font); initialHand(hand, RandTable, posOfHands, prev); *pwindow = window; *prenderer = renderer; }
C
#include <stdio.h> #include <pthread.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include "crc8.h" #include "cJSON.h" int port = 8083; char HOST[] = "127.0.0.1"; void *do_work(void *p) { int sock_fd; sock_fd = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in srv; srv.sin_family = AF_INET; srv.sin_port = htons(port); srv.sin_addr.s_addr = inet_addr(HOST); connect(sock_fd, (struct sockaddr*)&srv, sizeof(srv)); char szBuf[50]; snprintf(szBuf, 50, "%s %d", p, pthread_self()); printf(szBuf); //use json cJSON *root_json = cJSON_CreateObject(); cJSON_AddItemToObject(root_json, "needResponse", cJSON_CreateTrue()); cJSON_AddItemToObject(root_json, "message", cJSON_CreateString(szBuf)); cJSON_AddItemToObject(root_json, "len", cJSON_CreateNumber(strlen(szBuf))); char *json_str = cJSON_Print(root_json); size_t size = strlen(json_str); uint8_t *pbuf = (uint8_t*)malloc(sizeof(uint8_t)*(size+1)); crc_data(json_str, size, pbuf); time_t t1, t2; time(&t1); send(sock_fd, pbuf, size+1, 0); //recv(sock_fd, pbuf, size+1, 0); time(&t2); printf("all spend %dsec\n", t2-t1); free(pbuf); } int main() { int i; int num = 2; printf("create therads pool..."); pthread_t *threads; threads = (pthread_t*)malloc(sizeof(pthread_t)*num); //char *p = (char*)malloc(sizeof(char)*50); //bzero(p, 50); //snprintf(p, 50, "hello world"); //do_work(p); printf("add jobs to thread pool..."); for(i=0; i<num; ++i) { char param[50] = {0}; snprintf(param, 50, "%d thread:", i+1); pthread_create(&threads[i], NULL, do_work, param); } for(i=0; i<num; ++i) pthread_join(threads[i], NULL); printf("test结束..."); free(threads); }
C
#include <stdio.h> int main(void){ int p1, p2; printf("Media das provas >>>>>>>>\n"); printf("Digite a nota da Prova 1: "); scanf("%d", &p1); printf("Digite a nota da Prova 2: "); scanf("%d", &p2); printf("A nota media e %d\n", (p1+p2)/2); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_itoa_base.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: awoimbee <awoimbee@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/20 20:57:23 by exam #+# #+# */ /* Updated: 2019/04/28 04:55:39 by awoimbee ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> static char *f_strrev(char *str) { char *start; char *end; char buff; start = str; end = str; while (*(end + 1)) ++end; while (start < end) { buff = *start; *start = *end; *end = buff; start++; end--; } return (str); } char *ft_itoa_base(int value, int base) { char *str_base; char *result; int i; int sign; sign = (value < 0) ? -1 : 1; str_base = "0123456789ABCDEF"; if (!(result = malloc(((value / base) * sign + 2)))) return (NULL); i = 0; if (value == 0) result[i++] = '0'; while (value != 0) { result[i++] = str_base[(value % base) * sign]; value /= base; } if (sign == -1) result[i++] = '-'; result[i++] = '\0'; return (f_strrev(result)); }
C
#include<stdio.h> #include<conio.h> void main() { int x,y,z,a,b; clrscr(); printf("enter the value of x,y,z"); scanf("%d%d%d",&x,&y,&z); a=((x+y).z)) b=(x.y)+(y.z) printf("\n value of a=%d",a); printf("\n value ofb=%d",b); getch(); }
C
/** * Filename: debug.h * Author: Alexandru Mosoi (brtzsnr@gmail.com) * Last modified: 07 March 2008 * * Documentation: * * This module offers students some simple C macros meant to facilitate * treating errors and debugging. Messages will be printed to stderr and * will contain, alongside user's message, file, function and line where * the macro was called. * * LOG(level, format, params) * - Print message of level 'level' if 'level' is equal or less than 'LOG_LEVEL' * - There are 4 default levels: FATAL, WARN, INFO, DEBUG * - 'LOG_LEVEL' is a macro. If not defined when including 'log.h' it will take * default value 'WARN' * - 'format' and 'params' have the same meaning as functions similar to 'printf()'. * Internally, params sorted by 'level' are sent to 'fprintf()'. * - After printing messages from 'FATAL' level, program exits. * * LOG_ERROR(format, params) * - Similar to 'LOG(FATAL, fomat, params)', but also prints last error. * * DLOG(level, format, params) * - Prints a debug message of level 'DEBUG + level' * * ASSERT(cond) * - If 'cond' fails, print an error message (with cond and last * system error), then exits the program. * * CHECK_op(left, right) * - Checks that binary operation 'op' is successful * - 'op' can be: * - EQ for 'EQual' * - NE for 'Not Equal' * * To modify the value of LOG_LEVEL add the following option when compiling: * -D LOG_LEVEL=value (when using GCC/Linux) * /D LOG_LEVEL=value (when using MSVS/Windows) * * Examples: * * // LOG_LEVEL = FATAL * LOG(INFO, "result = %d", 3); // prints nothing * LOG(DEBUG, "result = %d", 3); // prints nothing * DLOG(666, "result = %d", 3); // prints nothing * ASSERT(3 == 4); // error, exits program * * // LOG_LEVEL = DEBUG * LOG(INFO, "result = %d", 3); // prints 'result = 3' * LOG(DEBUG, "result = %d", 3); // prints 'result = 3' * DLOG(666, "result = %d", 3); // prints nothing * ASSERT(3 == 4); // error, exits program * * // LOG_LEVEL = (DEBUG+1024) * LOG(INFO, "result = %d", 3); // prints 'result = 3' * LOG(DEBUG, "result = %d", 3); // prints 'result = 3' * DLOG(666, "result = %d", 3); // prints 'result = 3' * ASSERT(3 == 4); // error, exits program * * CHECK_NE(fd = open("file", O_RDONLY), -1); * CHECK_EQ(function(), 0) * * // Following lines exit program * // if 'f()' returns 0. * * if (f() == 0) * LOG(FATAL, "f() == 0"); * CHECK_NE(f(), 0); * ASSERT(f() != 0); * * Examples of messages: * * LOG(WARN, "Warning message"); * // W main.c (main) 9: Warning message * * ASSERT(0 == 1); * // F main.c (main) 11: ASSERT failed: 0 == 1 (last error = Success) * * CHECK_NE(open("does_not_exist", O_RDONLY), -1); * // F main.c (main) 15: CHECK failed: open("does_not_exist", 00) != -1 (last error = No such file or directory) * * DLOG(99, "All work and no play makes %s a dull %s!", "Jack", "boy"); * // 99 main.c (main) 15: All work and no play makes Jack a dull boy! * * open("does_not_exist", O_RDONLY); * LOG_ERROR("%s", "Error message"); * // main.c (main) 18: Error message * // F main.c (main) 18: Last error: No such file or directory. */ #ifndef LOG_H__ #define LOG_H__ #if !defined(__GNUC__) && !defined(_WIN32) #error Unknown operating system. Please check this file. #endif #include <stdio.h> #include <stdlib.h> #ifndef LOG_LEVEL #define LOG_LEVEL (WARN + 1024) #endif #ifdef __GNUC__ /* Linux */ #include <errno.h> #include <string.h> #define __FUNCTION__ __func__ #define LOG_GET_ERROR_MESSAGE \ char *error_buffer; \ char error_buffer2[512]; \ error_buffer = error_buffer2; \ error_buffer = strerror_r(errno, error_buffer, sizeof(error_buffer)); #else /* Windows */ #include <windows.h> #define LOG_GET_ERROR_MESSAGE \ char error_buffer[512]; \ FormatMessage( \ FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_MAX_WIDTH_MASK, \ NULL, \ GetLastError(), \ 0, \ error_buffer, \ sizeof(error_buffer), \ NULL); #endif enum LogType { NONE, FATAL, WARN, INFO, DEBUG }; #define LOG(type, ...) \ do { \ if (type <= LOG_LEVEL) { \ if (type <= DEBUG) \ fprintf(stderr, " %c", " FWID"[type]); \ else \ fprintf(stderr, "%02d", type - DEBUG); \ \ fprintf(stderr, " %s (%s) %d: ", __FILE__, \ __FUNCTION__, __LINE__); \ fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, "\n"); \ fflush(stderr); \ \ /* Abort() is C89 compliant. */ \ if (type == FATAL) \ abort(); \ } \ } while (0) #define LOG_ERROR(...) \ do { \ LOG_GET_ERROR_MESSAGE \ LOG(NONE, __VA_ARGS__); \ LOG(FATAL, "Last error: %s.", error_buffer); \ } while (0) #define DLOG(level, ...) LOG(DEBUG + (level), __VA_ARGS__) #define ASSERT(condition) \ do { \ if (!(condition)) { \ LOG_GET_ERROR_MESSAGE \ LOG(NONE, "ASSERT failed: %s.", #condition); \ LOG(FATAL, "Last error: %s.", error_buffer); \ } \ } while (0) #define CHECK(left, operation, right) \ do { \ if (!((left)operation(right))) { \ LOG_GET_ERROR_MESSAGE \ LOG(NONE, "CHECK failed: %s %s %s.", #left, \ #operation, #right); \ LOG(FATAL, "Last error: %s.", error_buffer); \ } \ } while (0) #define CHECK_EQ(left, right) CHECK(left, ==, right) #define CHECK_NE(left, right) CHECK(left, !=, right) #endif
C
#include "bashniclient.h" #include "board_representation.h" int got_signal = 0; node_t board[32]; node_t moves[32]; void init_moves(){ for(int i = 0 ; i< 32; i++){ if(moves[i].next != NULL){ node_t* temp = moves[i].next; while(temp != NULL){ node_t* next_node = temp->next; free(temp); temp = next_node; } } moves[i].next = NULL; moves[i].prev = NULL; moves[i].val = 0; moves[i].type =0; } } bool jumped_tower = false; //some bitfields uint32_t white_on_top =0; uint32_t black_on_top =0; uint32_t kings = 0; uint32_t towers = 0; uint32_t blocked_space = 0; /* * 01 02 03 04 *05 06 07 08 * 09 10 11 12 *13 14 15 16 * 17 18 19 20 *21 22 23 24 * 25 26 27 28 *29 30 31 32 * */ uint32_t left_3_mask = 0b00000000111000001110000011100000; uint32_t right_3_mask = 0b00000111000001110000011100000000; uint32_t left_5_mask = 0b00000111000001110000011100000111; uint32_t right_5_mask = 0b11100000111000001110000011100000; //uint32_t right_bound_mask = 0b00010000000100000001000000010000; //uint32_t left_bound_mask = 0b10000000100000001000000010001000; uint32_t right_bound_mask = 0b10001000100010001000100010001000; uint32_t left_bound_mask = 0b00010001000100010001000100010001; uint32_t bottom_bound_mask= 0b11110000000000000000000000000000; uint32_t top_bound_mask = 0b00000000000000000000000000001111; void print_board_from_bitfields(uint32_t bf, char color){ int row_num = 8; printf(" A B C D E F G H\n"); for(int i = 0; i < 32; i++){ if(i%4==0){ printf("\n%d ", row_num); row_num--; } if((IS_SET(bf, i) && (row_num%2 == 0))){ printf("%c - ", color); } else if((IS_SET(bf, i) && (row_num%2 != 0))){ printf(" - %c", color); } else if(row_num %2 !=0){ printf(" - -"); } else if(row_num%2 == 0){ printf("- - "); } } printf("\n"); } uint32_t get_white_movers(){ uint32_t not_occupied = ~(white_on_top | black_on_top); uint32_t white_kings = white_on_top&kings; uint32_t movers = (not_occupied << 4) & white_on_top; movers |= ((not_occupied&left_3_mask)<<3) & white_on_top; movers |= ((not_occupied&left_5_mask)<<5) & white_on_top; if(white_kings){ movers |= (not_occupied >> 4) & white_kings; movers |= ((not_occupied & right_3_mask) >> 3) & white_kings; movers |= ((not_occupied & right_5_mask) >> 5) & white_kings; } return movers; } uint32_t get_black_movers(){ //TODO bugfix uint32_t not_occupied = ~(black_on_top | black_on_top); uint32_t black_kings = black_on_top&kings; uint32_t movers = (not_occupied >> 4) & black_on_top; movers |= ((not_occupied&right_3_mask)>>3) & black_on_top; movers |= ((not_occupied&right_5_mask)>>5) & black_on_top; if(black_kings){ movers |= (not_occupied >> 4) & black_kings; movers |= ((not_occupied & left_3_mask) << 3) & black_kings; movers |= ((not_occupied & left_5_mask) << 5) & black_kings; } return movers; } uint32_t get_white_jumpers(){ uint32_t not_occupied = ~(white_on_top | black_on_top); uint32_t white_kings = white_on_top&kings; uint32_t jumpers = 0; uint32_t temp = (not_occupied << 4) & black_on_top; jumpers |= (((temp & left_3_mask) << 3) | ((temp & left_5_mask) << 5)); temp = (((not_occupied & left_3_mask) << 3) | ((not_occupied & left_5_mask) << 5)) & black_on_top; jumpers |= (temp << 4); jumpers &= white_on_top; temp = (not_occupied >> 4) & black_on_top; if(temp){ jumpers |= (((temp & right_3_mask) >> 3) | ((temp & right_5_mask) >> 5)) & white_on_top; } temp = (((not_occupied & right_3_mask) >> 3) | ((not_occupied & right_5_mask) >> 5)) & black_on_top; //jumpers |= (temp >> 4) & white_on_top; if(temp) jumpers |= (temp >> 4) & white_on_top; if(white_kings){ printf("found white kings\n"); temp = (not_occupied >> 4) & black_on_top; print_board_from_bitfields(temp, 'T'); if(temp& right_3_mask){ printf("temp&right_3_mask\n"); // TODO maybe (temp&(~(not_occupied))) if(temp&white_kings) printf("temp&white_kings\n"); if(temp&right_bound_mask) printf("temp&right_bound_mask\n"); if(temp&top_bound_mask) printf("temp&top_bound_mask\n"); while(((temp&white_kings)/* | (temp&right_bound_mask) | (temp & top_bound_mask)*/ )==0){ printf("while1\n"); if(temp == 0) break; if(temp&right_3_mask) temp = temp >>3; else temp = temp >>4; } temp = temp & white_kings; if(temp) jumpers |= temp; } else if(temp & right_5_mask){ printf("temp&right_5_mask\n"); while(((temp&white_kings)/* | (temp & left_bound_mask) | (temp & top_bound_mask)*/)==0){ if(temp == 0) break; if(temp&right_5_mask) temp = temp >> 5; else temp = temp >>4; } temp = temp & white_kings; if(temp) jumpers |= temp; } temp = ((not_occupied & right_3_mask) >>3) & black_on_top; while(((temp & white_kings)/* | (temp & right_bound_mask) | (temp & top_bound_mask)*/)==0){ if(temp == 0) break; if(temp&right_3_mask) temp = temp >>3; else temp = temp >>4; } temp = temp & white_kings; if(temp) jumpers |= temp; temp = ((not_occupied & right_5_mask) >>5) & black_on_top; while(((temp & white_kings) /*| (temp & left_bound_mask) | (temp & top_bound_mask)*/) ==0){ if(temp == 0) break; if(temp&right_5_mask) temp = temp >> 5; else temp = temp >>4; } temp = temp & white_kings; if(temp) jumpers |= temp; //TODO left shifts }//white_kings return jumpers; } uint32_t get_black_jumpers(){ uint32_t not_occupied = ~(white_on_top | black_on_top); uint32_t black_kings = black_on_top&kings; uint32_t jumpers = 0; uint32_t temp = (not_occupied >> 4) & white_on_top; jumpers |= (((temp & right_3_mask) >> 3) | ((temp & right_5_mask) >> 5)); temp = (((not_occupied & right_3_mask) >> 3) | ((not_occupied & right_5_mask) >> 5)) & white_on_top; jumpers |= (temp >> 4); jumpers &= black_on_top; temp = (not_occupied << 4) & white_on_top; if(temp){ jumpers |= (((temp & left_3_mask) << 3) | ((temp & left_5_mask) << 5)) & black_on_top; } temp = (((not_occupied & left_3_mask) << 3) | ((not_occupied & left_5_mask) << 5)) & white_on_top; if(temp) jumpers |= (temp << 4) & black_on_top; if(black_kings){ //TODO same as white kings } return jumpers; } //king contains one king //color is color of king //already_jumped is to avoid already calculated jumps //blocked space is 0 at start and contains all spaces that would cause a 180 deg jump in a consecuteive jump //use blocked space as already jumped in consecutieve calls tu function uint32_t get_royal_jump(uint32_t king, char color, uint32_t already_jumped){ uint32_t dest = 0; uint32_t temp = 0; uint32_t not_occupied = (~(white_on_top | black_on_top | already_jumped | blocked_space)); printf("(get_royal_jump) called with:\n"); print_board_from_bitfields(king, 'K'); print_board_from_bitfields(blocked_space, 'L'); if(color == 'w'){ /* if king &left 5 mask move diagonally to bottom right */ temp = king & left_5_mask; if(temp){ //left shift 5 manually so temp is on unoccupied space temp = temp << 5; blocked_space |= temp; //if temp is not occupied contionue diagonally until border or occupied space is reached if(temp&not_occupied) { //KING & L5MASK while(((temp & bottom_bound_mask) | (temp & right_bound_mask)) ==0 && (temp & not_occupied)) { if(temp&left_5_mask) temp = temp <<5; else temp = temp <<4; blocked_space |= temp; } //check if black piece can be jumped if(temp & black_on_top && (~((temp&right_bound_mask)|(temp & bottom_bound_mask)))){ if(temp&left_5_mask && (temp << 5)&not_occupied){ if(temp & towers) jumped_tower = true; dest = temp <<5; return dest; } else if((temp << 4)&not_occupied){ if(temp &towers) jumped_tower = true; dest = temp <<4; return dest; } else blocked_space = 0; } } //if temp << 5 is occupied check for regular jump else{ //regular jump temp = temp & black_on_top; if(temp && (temp << 4)& not_occupied){ if(temp & towers) jumped_tower = true; dest =temp << 4; return dest; } } //move king to bottom left temp = king; //no need to and with L5M blocked_space |= temp; temp = temp << 4; blocked_space |= temp; //if temp is not occupied move diagonally to bottom left if(temp & not_occupied){ printf("entering buggy loop\n"); while((((temp & bottom_bound_mask) | (temp & left_bound_mask))==0) && (temp & not_occupied)){ //sleep(1); if(temp&left_3_mask){ print_board_from_bitfields(temp, 'T'); temp = temp << 3; print_board_from_bitfields(temp, 'T'); printf ("temp & left_3_mask\n"); } else{ printf("temp << 4\n"); temp = temp << 4; } blocked_space |= temp; if(temp & not_occupied) printf("not not_occupied\n"); } printf("end of buggy loop\n"); //check if black piece can be jumped if(temp & black_on_top && (~((temp &left_bound_mask) | (temp & bottom_bound_mask)))){ printf("found black pawn\n"); if(temp&left_3_mask && (temp<<3)&not_occupied){ printf("and it is jumpable (<<3)\n"); if(temp&towers) jumped_tower = true; dest = temp << 3; return dest; } else if((temp <<4) & not_occupied){ if(temp & towers) jumped_tower = true; printf("and it is jumpable (<<4)\n"); print_board_from_bitfields(temp<<4, 'D'); dest = temp <<4; return dest; } else blocked_space = 0; } } else{ //normal jump temp = temp &black_on_top; if((temp&left_3_mask) && (temp <<3)&not_occupied){ if(temp & towers) jumped_tower = true; dest = temp << 3; return dest; } } }//END if(king & l5_mask) //if king is on l3 mask move diagonally to bottom left temp = king & left_3_mask; blocked_space |= temp; if(temp){ // << 3 so temp temp is on unoccupied space temp = temp <<3; if(temp & not_occupied){ //move diagonally while(((temp & bottom_bound_mask) | (temp & left_bound_mask)) == 0 && (temp & not_occupied)){ if(temp&left_3_mask) temp = temp <<3; else temp = temp <<4; blocked_space |= temp; } //check if black piece can be jumped if(temp & black_on_top && (~((temp &left_bound_mask) | (temp & bottom_bound_mask)))){ if(temp&left_3_mask && (temp<<3)&not_occupied){ if(temp&towers) jumped_tower = true; dest = temp << 3; return dest; } else if((temp <<4) & not_occupied){ if(temp & towers) jumped_tower = true; dest = temp <<4; return dest; } else blocked_space = 0; } } else{ //regular jump temp = temp & black_on_top; if((temp) && (temp <<4)&not_occupied){ if(temp & towers) jumped_tower = true; dest = temp <<4; return dest; } } //move king to bottom right temp = king << 4; blocked_space |= temp; if(temp & not_occupied){ //move diagonally bottom right while(((temp & bottom_bound_mask) | (temp & right_bound_mask)) == 0 && (temp & not_occupied)){ if(temp & left_5_mask) temp = temp << 5; else temp =temp << 4; blocked_space |= temp; } //check if black piece can be jumped if(temp & black_on_top && (~((temp & right_bound_mask) | (temp & bottom_bound_mask)))){ if((temp&left_5_mask) && (temp <<5)&not_occupied){ if(temp & towers) jumped_tower = true; dest = temp << 5; return dest; } else if ((temp << 4) & not_occupied){ if(temp & towers) jumped_tower = true; dest =temp <<4; return dest; } else blocked_space = 0; } } else{ //regular jump temp = temp & black_on_top; if((temp & left_5_mask) && (temp << 4)&not_occupied){ if(temp & towers) jumped_tower = true; dest = temp << 5; return dest; } } }//end if(king & l_3mask) temp = king; blocked_space |= temp; if(temp) //if king is on neiteher l3 or l3 mask {//king << 4 temp = temp << 4; blocked_space |= temp; if(temp & left_3_mask){ if(temp &not_occupied){ //move diagonally (bottom left) while(((temp &bottom_bound_mask) | (temp & left_bound_mask)) ==0 && (temp&not_occupied)){ if(temp&left_3_mask) temp = temp <<3; else temp = temp <<4; blocked_space |= temp; } //check if black piece can be jumped if(temp & black_on_top && (~((temp & left_bound_mask) | (temp&bottom_bound_mask)))){ if(temp&left_3_mask && (temp <<3) &not_occupied){ if(temp&towers) jumped_tower = true; dest = temp <<3; return dest; } else blocked_space = 0; } } //regular jump else{ temp = temp &black_on_top; if((temp) && (temp<<3)&not_occupied){ if(temp & towers) jumped_tower = true; dest = temp << 3; return dest; } } }//end temp&l3mask else if( temp & left_5_mask){ if(temp &not_occupied){ //move diagonally (bottom left) while(((temp &bottom_bound_mask) | (temp & left_bound_mask)) ==0 && (temp&not_occupied)){ if(temp&left_5_mask) temp = temp <<5; else temp = temp <<4; blocked_space |= temp; } //check if black piece can be jumped if(temp & black_on_top && (~((temp & left_bound_mask) | (temp&bottom_bound_mask)))){ if(temp&left_5_mask && (temp <<5) &not_occupied){ if(temp&towers) jumped_tower = true; dest = temp <<5; return dest; } else blocked_space = 0; } } //regular jump else{ temp = temp &black_on_top; if((temp) && (temp<<5)&not_occupied){ if(temp & towers) jumped_tower = true; dest = temp << 5; return dest; } } }//end temp & l5mask }//End king <<4 /* if king &right 5 mask move diagonally to bottom right */ temp = king & right_5_mask; if(temp){ //right shift 5 manually so temp is on unoccupied space temp = temp >> 5; blocked_space |= temp; //if temp is not occupied contionue diagonally until border or occupied space is reached if(temp&not_occupied) { //KING & L5MASK while(((temp & top_bound_mask) | (temp & left_bound_mask)) ==0 && (temp & not_occupied)) { if(temp&right_5_mask) temp = temp >>5; else temp = temp >>4; blocked_space |= temp; } //check if black piece can be jumped if(temp & black_on_top && (~((temp&left_bound_mask)|(temp & top_bound_mask)))){ if(temp&right_5_mask && (temp >> 5)&not_occupied){ if(temp & towers) jumped_tower = true; dest = temp >>5; return dest; } else if((temp >> 4)&not_occupied){ if(temp &towers) jumped_tower = true; dest = temp >>4; return dest; } else blocked_space = 0; } } //if temp >> 5 is occupied check for regular jump else{ //regular jump temp = temp & black_on_top; if(temp && (temp >> 4)& not_occupied){ if(temp & towers) jumped_tower = true; dest =temp >> 4; return dest; } } //move king to top right temp = king; //no need to and with r5M blocked_space |= temp; temp = temp >> 4; blocked_space |= temp; //if temp is not occupied move diagonally to top right if(temp & not_occupied){ //printf("entering buggy loop\n"); while((((temp & top_bound_mask) | (temp & right_bound_mask))==0) && (temp & not_occupied)){ //sleep(1); if(temp&right_3_mask){ print_board_from_bitfields(temp, 'T'); temp = temp >> 3; print_board_from_bitfields(temp, 'T'); // printf ("temp & right_3_mask\n"); } else{ // printf("temp >> 4\n"); temp = temp >> 4; } blocked_space |= temp; // if(temp & not_occupied) printf("not not_occupied\n"); } //printf("end of buggy loop\n"); //check if black piece can be jumped if(temp & black_on_top && (~((temp &right_bound_mask) | (temp & top_bound_mask)))){ // printf("found black pawn\n"); if(temp&right_3_mask && (temp>>3)&not_occupied){ // printf("and it is jumpable (>>3)\n"); if(temp&towers) jumped_tower = true; dest = temp >> 3; return dest; } else if((temp >>4) & not_occupied){ if(temp & towers) jumped_tower = true; // printf("and it is jumpable (>>4)\n"); dest = temp >>4; return dest; } else blocked_space = 0; } } else{ //normal jump temp = temp &black_on_top; if((temp&right_3_mask) && (temp >>3)&not_occupied){ if(temp & towers) jumped_tower = true; dest = temp >> 3; return dest; } } }//END if(king & r5_mask) //if king is on r3 mask move diagonally to top right temp = king & right_3_mask; blocked_space |= temp; if(temp){ // >> 3 so temp temp is on unoccupied space temp = temp >>3; if(temp & not_occupied){ //move diagonally while(((temp & top_bound_mask) | (temp & right_bound_mask)) == 0 && (temp & not_occupied)){ if(temp&right_3_mask) temp = temp >>3; else temp = temp >>4; blocked_space |= temp; } //check if black piece can be jumped if(temp & black_on_top && (~((temp &right_bound_mask) | (temp & top_bound_mask)))){ if(temp&right_3_mask && (temp>>3)&not_occupied){ if(temp&towers) jumped_tower = true; dest = temp >> 3; return dest; } else if((temp >>4) & not_occupied){ if(temp & towers) jumped_tower = true; dest = temp >>4; return dest; } else blocked_space = 0; } } else{ //regular jump temp = temp & black_on_top; if((temp) && (temp >>4)&not_occupied){ if(temp & towers) jumped_tower = true; dest = temp >>4; return dest; } } //move king to bottom right temp = king >> 4; blocked_space |= temp; if(temp & not_occupied){ //move diagonally bottom right while(((temp & top_bound_mask) | (temp & left_bound_mask)) == 0 && (temp & not_occupied)){ if(temp & right_5_mask) temp = temp >> 5; else temp =temp >> 4; blocked_space |= temp; } //check if black piece can be jumped if(temp & black_on_top && (~((temp & left_bound_mask) | (temp & top_bound_mask)))){ if((temp&right_5_mask) && (temp >>5)&not_occupied){ if(temp & towers) jumped_tower = true; dest = temp >> 5; return dest; } else if ((temp >> 4) & not_occupied){ if(temp & towers) jumped_tower = true; dest =temp >>4; return dest; } else blocked_space = 0; } } else{ //regular jump temp = temp & black_on_top; if((temp & right_5_mask) && (temp >> 5)&not_occupied){ if(temp & towers) jumped_tower = true; dest = temp >> 5; return dest; } } }//end if(king & l_3mask) temp = king; blocked_space |= temp; if(temp) //if king is on neiteher r3 or r3 mask {//king >> 4 temp = temp >> 4; blocked_space |= temp; if(temp & right_3_mask){ if(temp &not_occupied){ //move diagonally (bottom right) while(((temp &top_bound_mask) | (temp & right_bound_mask)) ==0 && (temp&not_occupied)){ if(temp&right_3_mask) temp = temp >>3; else temp = temp >>4; blocked_space |= temp; } //check if black piece can be jumped if(temp & black_on_top && (~((temp & right_bound_mask) | (temp&top_bound_mask)))){ if(temp&right_3_mask && (temp >>3) &not_occupied){ if(temp&towers) jumped_tower = true; dest = temp >>3; return dest; } else blocked_space = 0; } } //regular jump else{ temp = temp &black_on_top; if((temp) && (temp>>3)&not_occupied){ if(temp & towers) jumped_tower = true; dest = temp >> 3; return dest; } } }//end temp&r3mask else if( temp & right_5_mask){ if(temp &not_occupied){ //move diagonally (bottom right) while(((temp &top_bound_mask) | (temp & left_bound_mask)) ==0 && (temp&not_occupied)){ if(temp&right_5_mask) temp = temp >>5; else temp = temp >>4; blocked_space |= temp; } //check if black piece can be jumped if(temp & black_on_top && (~((temp & left_bound_mask) | (temp&top_bound_mask)))){ if(temp&right_5_mask && (temp >>5) &not_occupied){ if(temp&towers) jumped_tower = true; dest = temp >>5; return dest; } else blocked_space = 0; } } //regular jump else{ temp = temp &black_on_top; if((temp) && (temp>>5)&not_occupied){ if(temp & towers) jumped_tower = true; dest = temp >> 5; return dest; } } }//end temp & r5mask }//End king >>4 }//end if(color == 'w') return dest; } //finds possible jump form jumper, color is color of jumper //already jumped is used to exclude jumps that were already calculated uint32_t get_jump(uint32_t jumper, char color, uint32_t already_jumped){ uint32_t dest = 0; uint32_t temp = 0; uint32_t not_occupied = (~(white_on_top | black_on_top | already_jumped)); //uint32_t white_kings = kings & white_on_top; //uint32_t black_kings = kings & black_on_top; // print_board_from_bitfields(not_occupied, 'n'); print_board_from_bitfields(jumper, 'j'); if(color == 'w'){ if(jumper&kings) return get_royal_jump(jumper, 'w', already_jumped); temp = jumper & left_3_mask; if(temp){ printf("case jumper << 3\n"); temp = (temp << 3) & black_on_top; if(temp){ dest = (temp << 4)& not_occupied; if((temp&towers)&&dest) jumped_tower = true; } if(dest) return dest; } temp= jumper & left_5_mask; if(temp){ printf("case jumper << 5\n"); temp = (temp << 5) & black_on_top; if(temp) { dest = (temp << 4)& not_occupied; if((temp&towers)&&dest) jumped_tower = true; } if(dest) return dest; } temp= jumper & right_5_mask; if(temp){ printf("case jumper >> 5\n"); temp = (temp >> 5) & black_on_top; if(temp){ dest = (temp >> 4)& not_occupied; if((temp&towers)&&dest) jumped_tower = true; } if(dest) return dest; } temp = jumper & right_3_mask; if(temp){ printf("case jumper >> 3\n"); temp = (temp >> 3) & black_on_top; if(temp){ dest = (temp >> 4)& not_occupied; if((temp&towers)&&dest) jumped_tower = true; } if(dest) return dest; } temp = (jumper << 4) & black_on_top; if(temp){ printf("case jumper << 4\n"); if(temp&left_3_mask){ dest = (temp <<3) & not_occupied; if((temp&towers)&&dest) jumped_tower = true; if(dest) return dest; } if(temp&left_5_mask){ dest = (temp << 5) &not_occupied; if((temp&towers)&&dest) jumped_tower = true; if(dest) return dest; } } temp = (jumper >> 4) & black_on_top; if(temp){ printf("case jumper >> 4\n"); if(temp&right_3_mask){ dest = (temp >>3) & not_occupied; if((temp&towers)&&dest) jumped_tower = true; if(dest) return dest; } if(temp&right_5_mask){ dest = (temp >> 5) & not_occupied; if((temp&towers)&&dest) jumped_tower = true; if(dest) return dest; } } } //END if color = 'w' else if(color == 'b'){ if(jumper&kings) return get_royal_jump(jumper, 'b', already_jumped); temp = jumper & left_3_mask; if(temp){ printf("case jumper << 3\n"); temp = (temp << 3) & white_on_top; if(temp){ dest = (temp << 4)& not_occupied; if((temp&towers)&&dest) jumped_tower = true; } if(dest) return dest; } temp= jumper & left_5_mask; if(temp){ printf("case jumper << 5\n"); temp = (temp << 5) & white_on_top; if(temp) { dest = (temp << 4)& not_occupied; if((temp&towers)&&dest) jumped_tower = true; } if(dest) return dest; } temp= jumper & right_5_mask; if(temp){ printf("case jumper >> 5\n"); temp = (temp >> 5) & white_on_top; if(temp){ dest = (temp >> 4)& not_occupied; if((temp&towers)&&dest) jumped_tower = true; } if(dest) return dest; } temp = jumper & right_3_mask; if(temp){ printf("case jumper >> 3\n"); temp = (temp >> 3) & white_on_top; if(temp){ dest = (temp >> 4)& not_occupied; if((temp&towers)&&dest) jumped_tower = true; } if(dest) return dest; } temp = (jumper << 4) & white_on_top; if(temp){ printf("case jumper << 4\n"); if(temp&left_3_mask){ dest = (temp <<3) & not_occupied; if((temp&towers)&&dest) jumped_tower = true; if(dest) return dest; } if(temp&left_5_mask){ dest = (temp << 5) &not_occupied; if((temp&towers)&&dest) jumped_tower = true; if(dest) return dest; } } temp = (jumper >> 4) & white_on_top; if(temp){ printf("case jumper >> 4\n"); if(temp&right_3_mask){ dest = (temp >>3) & not_occupied; if((temp&towers)&&dest) jumped_tower = true; if(dest) return dest; } if(temp&right_5_mask){ dest = (temp >> 5) & not_occupied; if((temp&towers)&&dest) jumped_tower = true; if(dest) return dest; } } } //print_board_from_bitfields(dest, 'd'); return dest; } //TODO consider towers void get_all_jumps(uint32_t jumpers, char color){ printf("color is %c\n", color); //uint32_t old_kings = kings; int j = 0; for(int i = 0; i< 32; i++){ if(IS_SET(jumpers, i)){ uint32_t temp = 0; SET_BIT(temp, i); pos_node_from_bf(temp, &moves[j]); printf("callinf get jump\n"); uint32_t dest = get_jump(temp, color, 0); if(temp&kings){ kings |= dest; } if(dest == 0){ printf("(get_all_jumps) could not find jump!!\n"); //exit(EXIT_SUCCESS); } while(dest){ //check if jumper can jump in multiple directions // sleep(1); // print_board_from_bitfields(dest, 'd'); node_t* new_node = create_new_list(0, 0); pos_node_from_bf(dest, new_node); // printf("get_tail_1\n"); printf("appending new node to list %c%c list nr %i\n", moves[j].type, moves[j].val, j); append_to_list(new_node, get_tail(&moves[j])); uint32_t prev_dest = dest; //only works for no. jumps < 2 dest = get_jump(temp, color, prev_dest); // if jumper can only jump in one direction dest will bi 0 j++; if(j == 32){ //exit(EXIT_FAILURE); printf("(get all jumps) something went wrong\n"); break; } } } } //moves now contains all single jumps now looking for multi jump j=0; for(int i = 0; i<32; i++){ // printf("get_tail_2"); uint32_t current_pos = bf_from_pos_node(get_tail(&moves[j])); print_board_from_bitfields(current_pos, 'c'); if (current_pos == 0) break; //print_board_from_bitfields(current_pos, 'c'); //printf("get_tail_3"); uint32_t prev_pos =0; if(get_tail(&moves[j])->prev != NULL){ prev_pos = bf_from_pos_node(get_tail(&moves[j])->prev); //to avoid 180deg turns } //print_board_from_bitfields(prev_pos, 'p'); uint32_t dest = get_jump(current_pos, color, prev_pos); if(current_pos&kings){ kings &= ~current_pos; kings |= dest; printf("current_pos&kings\n"); print_board_from_bitfields(kings, 'K'); } if(dest == 0){ //kings = old_kings; j++; // printf("j is now %d\n", j); } else{ // printf("appending new_node\n"); // print_board_from_bitfields(dest, 'd'); node_t* new_node = create_new_list(0,0); printf("appending new node to list %c%c list nr %i\n", moves[j].type, moves[j].val, j); new_node = pos_node_from_bf(dest, new_node); append_to_list(new_node, get_tail(&moves[j])); } } } //mover shoud be one single mover not all of them //in case a mover can move in two directions set previouslu calculated move to already move to find other move uint32_t get_move(uint32_t mover, char color, uint32_t already_moved){ uint32_t not_occupied = (~(white_on_top | black_on_top | already_moved)); uint32_t temp =0; if(color == 'w'){ temp = (mover >> 4) & not_occupied; if (temp) return temp; temp = mover & right_3_mask; if(temp && (temp >> 3)&not_occupied) return temp >>3; temp = mover & right_5_mask; if(temp && (temp >>5)&not_occupied) return temp >>5; } else if(color == 'b'){ temp = (mover << 4) & not_occupied; if (temp) return temp; temp = mover & left_3_mask; if(temp && (temp << 3)&not_occupied) return temp <<3; temp = mover & left_5_mask; if(temp && (temp <<5)&not_occupied) return temp <<5; } else{ printf("(get_move) invalid color!\n"); return 0; } printf("(get_move) could not find valid move\n"); return 0; } void get_all_moves(uint32_t movers, char color){ int j = 0; for(int i = 0; i<32; i++){ if(moves[i].next == 0 && moves[i].prev == NULL && moves[i].type == 0 && moves[i].val == 0){ j=i; break; } } for(int i = 0; i< 32; i++){ if(IS_SET(movers, i)){ uint32_t temp = 0; SET_BIT(temp, i); pos_node_from_bf(temp, &moves[j]); uint32_t dest = get_move(temp, color, 0); int moved = 0; while(dest){ if (moved >= 2) break; node_t* new_node = create_new_list(0, 0); pos_node_from_bf(dest, new_node); printf("(get_all_moves) appending node to list %c%c list nr %i\n", moves[j].type, moves[j].val, j); append_to_list(new_node, get_tail(&moves[j])); uint32_t prev_dest = dest; dest = get_move(temp, color, prev_dest); moved++; j++; if(j == 32){ exit(EXIT_FAILURE); } } } } } //generates move string from list of nodes //head has to be head of list!! char* move_str_from_list(node_t* head){ //get list len int len= count_list_elements(head); char* move = malloc(sizeof(char)*(3*len+2)); // memset(&move, 0, sizeof(move)); strcpy(move, "\0"); while(head != NULL){ strncat(move, &head->type, 1); // printf("type %s\n", move); strncat(move, &head->val,1 ); // printf("val %s\n", move); strcat(move, ":"); // printf(": %s\n", move); head = head->next; } move[strlen(move)-1] = '\n'; printf("(move_str_from_list) : %s", move); return move; } //uses node_t board[32] to generate white, black, king and tower bitfields void gen_bitfields(){ white_on_top = 0; black_on_top = 0; kings = 0; towers = 0; for(int i =0; i < 32; i++){ node_t* temp = get_tail(&board[i]); //printf("(gen_bitfields) current type is: %c\n", temp->type); if((temp->type == 'W') | (temp->type == 'w')){ SET_BIT(white_on_top, i); } if((temp->type == 'B') | (temp->type == 'b')){ SET_BIT(black_on_top, i); } if((temp->type == 'W') | (temp->type == 'B')){ SET_BIT(kings, i); } if(temp->prev != NULL){ SET_BIT(towers, i); } } } void init_board(){ for (int i = 0; i < 32; i++){ if(board[i].next != NULL){ node_t* temp = board[i].next; while(temp != NULL){ node_t* next_node = temp->next; free(temp); temp = next_node; } } board[i].prev = NULL; board[i].next = NULL; board[i].type = ' '; } } int think(sharestruct* sharedmem){ printf("(think) thinking\n"); lock_mem_segment(&sharedmem, sizeof(sharestruct)); char color = sharedmem->spielernumer==0 ? 'w' : 'b'; printf("(think) printing piecelist:\n"); for(int i =0; i<64; i++){//replace 64 with global var if(sharedmem->piecelist[i][0] == '\0'){ printf("sharedmem->piecelist[%d] == '\\0'\n", i); break; } else{ printf("(think) piece[%d]: %s",i, sharedmem->piecelist[i]); } } unlock_mem_segment(&sharedmem, sizeof(sharestruct)); init_board(); init_moves(); create_board_from_piecelist(sharedmem, board); gen_bitfields(); print_board_from_bitfields(white_on_top, 'w'); print_board_from_bitfields(black_on_top, 'b'); print_board_from_bitfields(towers, 't'); print_board_from_bitfields(kings, 'K'); uint32_t white_movers = get_white_movers(); uint32_t black_movers = get_black_movers(); uint32_t white_jumpers = 0; uint32_t black_jumpers = 0; printf("white_movers:\n"); print_board_from_bitfields(white_movers, 'w'); printf("black_movers:\n"); print_board_from_bitfields(black_movers, 'b'); if(color == 'w'){ printf("white_jumpers:\n"); white_jumpers = get_white_jumpers(); print_board_from_bitfields(white_jumpers, 'w'); } if(color == 'b'){ printf("black jumpers:\n"); black_jumpers = get_black_jumpers(); print_board_from_bitfields(black_jumpers, 'b'); } printf("looking for jumps:\n"); init_moves(); blocked_space = 0; if(white_jumpers && color == 'w'){ printf("looking for white jumps\n"); get_all_jumps(white_jumpers, 'w'); for(int i = 0; i <32 ; i++){ if(moves[i].val == 0) break; printlist(&moves[i]); } } else if(black_jumpers && color == 'b'){ printf("looking for black jumps\n"); get_all_jumps(black_jumpers, 'b'); } if (color == 'w'){ printf("looking for white movers\n"); get_all_moves(white_movers, 'w'); } if(color == 'b'){ printf("looking for black movers\n"); get_all_moves(black_movers, 'b'); } return EXIT_SUCCESS; } void sig_handler() { got_signal=1; } void sigterm_handler(){ printf("got sigterm\n"); exit(EXIT_SUCCESS); } int run_thinker(sharestruct* sharedmem, int* fields){ while(1){ printf("(run_thinker) waiting for signal from child\n"); init_moves(); while(got_signal == 0 ){ lock_mem_segment(&sharedmem->sent_signal, sizeof(bool)); if(sharedmem->sent_signal == true){ sharedmem->sent_signal = false; unlock_mem_segment(&sharedmem->sent_signal, sizeof(bool)); signal(SIGUSR1, sig_handler); signal(SIGTERM, sigterm_handler); } if(kill(sharedmem->connector_pid, 0) !=0) return EXIT_SUCCESS; unlock_mem_segment(&sharedmem->sent_signal, sizeof(bool)); } got_signal =0; //reset siganl; printf("(sig_handler)got signal form child\n"); think(sharedmem); int longes_move = 0; int j = 0; // printf("(run_thinker) count_list_elements test\n"); // int test = count_list_elements(get_head(&moves[1])); // printf("(run_thinker list 1 is %d elems long\n", test); printf("(run_thinker) finding longest move..\n"); for(int i = 0; i < 32; i++){ if(moves[i].val == 0) break; if(count_list_elements(get_head(&moves[i])) > longes_move){ longes_move = count_list_elements(get_head(&moves[i])); j = i; } } // printf("generating chess notation from list..\n"); char* final_move = move_str_from_list(get_head(&moves[j])); printf("(run_thinker) longes_move: %s", final_move); write(fields[1], final_move, strlen(final_move)); free(final_move); } printf("(run_thinker) finished... terminating\n"); return 0; }
C
#include <iostream> #include <stdio.h> #include <stdlib.h> #define BLOCK_SIZE 1024 #define MAX_MASK_WIDTH 5 #define TILE_SIZE 1024 __constant__ int M[MAX_MASK_WIDTH]; using namespace std; __global__ void ConvolutionBasic(int *N,int *M,int *P,int Mask_Width,int Width){ int i = blockIdx.x*blockDim.x + threadIdx.x; int N_start_point = i - (Mask_Width/2); int Pvalue=0; for (int j= 0;j<Mask_Width;j++) { if (N_start_point+j >= 0 && N_start_point + j < Width) { Pvalue+=N[N_start_point+j]*M[j]; } } if(i<Width) P[i]=Pvalue; } __global__ void ConvolutionCaching(int *N,int *P,int Mask_Width,int Width){ int i = blockIdx.x*blockDim.x + threadIdx.x; int N_start_point = i - (Mask_Width/2); int Pvalue=0; for (int j= 0;j<Mask_Width;j++) { if (N_start_point+j >= 0 && N_start_point + j < Width) { Pvalue+=N[N_start_point+j]*M[j]; } } P[i]=Pvalue; } __global__ void ConvolutionTile(int *N, int *P, int Mask_Width,int Width) { int i = blockIdx.x*blockDim.x + threadIdx.x; __shared__ int N_ds[TILE_SIZE + MAX_MASK_WIDTH -1]; int n = Mask_Width/2; int halo_index_left = (blockIdx.x - 1)*blockDim.x + threadIdx.x; if (threadIdx.x >= blockDim.x - n) { N_ds[threadIdx.x - (blockDim.x - n)] =(halo_index_left < 0) ? 0 : N[halo_index_left]; } if(i<Width) N_ds[n + threadIdx.x] = N[i]; else N_ds[n + threadIdx.x] = 0; int halo_index_right = (blockIdx.x + 1)*blockDim.x + threadIdx.x; if (threadIdx.x < n) { N_ds[n + blockDim.x + threadIdx.x] =(halo_index_right >= Width) ? 0 : N[halo_index_right]; } __syncthreads(); int Pvalue = 0; for(int j = 0; j < Mask_Width; j++) { Pvalue += N_ds[threadIdx.x + j]*M[j]; } P[i] = Pvalue; } void convolutionSec(int *N,int *M,int *P,int Mask_Width,int Width){ for(int i=0;i<Width;i++){ int N_start_point = i - (Mask_Width/2); int Pvalue=0; for (int j= 0;j<Mask_Width;j++) { if (N_start_point+j >= 0 && N_start_point + j < Width) { Pvalue+=N[N_start_point+j]*M[j]; } } P[i]=Pvalue; } } void imprimir(int *V,int n){ cout<<"|"; for(int i=0;i<n;i++) cout<<V[i]<<"|"; cout<<endl; } void llenar(int *V,int N,int flag){ if(flag==1) for(int i = 1; i <=N; i++ ) V[i-1] = i; else for(int i = 1; i <=N; i++ ) V[i-1] = 0; } void comparar(int*A,int *B1,int *B2,int *B3,int width){ for(int i=0;i<width;i++) if(((A[i]!=B1[i])||(A[i]!=B2[i]))||(A[i]!=B3[i])){ printf("\nEl resultado es incorrecto"); return; } printf("El resultado es correcto"); } int main(){ int N=100000000; int bytes=(N)*sizeof(int); int bytesM=MAX_MASK_WIDTH *sizeof(int); int *A=(int*)malloc(bytes); int *P=(int*)malloc(bytes); int Mask[MAX_MASK_WIDTH]={3,4,5,4,3}; llenar(A,N,1); llenar(P,N,0); float blocksize=BLOCK_SIZE; dim3 dimGrid(ceil(N/blocksize),1,1); dim3 dimBlock(blocksize,1,1); /*------------------------------Convolucion Secuencial---------------------------------*/ clock_t start = clock(); convolutionSec(A,Mask,P,5,N); clock_t end= clock(); double elapsed_seconds=end-start; printf("Tiempo Secuencial: %lf\n", (elapsed_seconds / CLOCKS_PER_SEC)); //imprimir(P,N); /*-----------------------------------------------------------------------------------------*/ /*------------------------------Convolucion Paralela Basica--------------------------------*/ int *d_A1; int *d_P1; int *d_Mask1; int *P_out1=(int*)malloc(bytes); int *P_in1=(int*)malloc(bytes); llenar(P_in1,N,0); cudaMalloc(&d_A1,bytes); cudaMalloc(&d_P1,bytes); cudaMalloc(&d_Mask1,bytesM); start=clock(); cudaMemcpy(d_A1, A, bytes, cudaMemcpyHostToDevice); cudaMemcpy(d_P1, P_in1, bytes, cudaMemcpyHostToDevice); cudaMemcpy(d_Mask1, Mask, bytesM, cudaMemcpyHostToDevice); ConvolutionBasic<<<dimGrid,dimBlock>>>(d_A1,d_Mask1,d_P1,MAX_MASK_WIDTH,N); cudaDeviceSynchronize(); cudaMemcpy(P_out1,d_P1, bytes, cudaMemcpyDeviceToHost ); end=clock(); double elapsed_seconds1=end-start; printf("Tiempo Paralelo Basic: %lf\n", (elapsed_seconds1 / CLOCKS_PER_SEC)); //imprimirVec(P_out1,N); //cout<<"Aceleracion: "<<elapsed_seconds/elapsed_seconds1<<endl<<endl; free(P_in1); cudaFree(d_A1); cudaFree(d_P1); /*-----------------------------------------------------------------------------------------*/ /*------------------------------Convolucion Paralela Caching-------------------------------*/ int *d_A2; int *d_P2; int *P_out2=(int*)malloc(bytes); int *P_in2=(int*)malloc(bytes); //Constant Memory cudaMemcpyToSymbol(M,Mask,bytesM); llenar(P_in2,N,0); cudaMalloc(&d_A2,bytes); cudaMalloc(&d_P2,bytes); start=clock(); cudaMemcpy(d_A2, A, bytes, cudaMemcpyHostToDevice); cudaMemcpy(d_P2, P_in2, bytes, cudaMemcpyHostToDevice); ConvolutionCaching<<<dimGrid,dimBlock>>>(d_A2,d_P2,MAX_MASK_WIDTH,N); cudaDeviceSynchronize(); cudaMemcpy(P_out2,d_P2, bytes, cudaMemcpyDeviceToHost ); end=clock(); double elapsed_seconds2=end-start; printf("Tiempo Paralelo Caching: %lf\n", (elapsed_seconds2 / CLOCKS_PER_SEC)); //imprimirVec(P_out2,N); //cout<<"Aceleracion: "<<elapsed_seconds/elapsed_seconds2<<endl<<endl; free(P_in2); cudaFree(d_A2); cudaFree(d_P2); /*-----------------------------------------------------------------------------------------*/ /*------------------------Convolucion Paralela Tile----------------------------------------*/ int *d_A3; int *d_P3; int *P_out3=(int*)malloc(bytes); int *P_in3=(int*)malloc(bytes); llenar(P_in3,N,0); cudaMalloc(&d_A3,bytes); cudaMalloc(&d_P3,bytes); start=clock(); cudaMemcpy(d_A3, A, bytes, cudaMemcpyHostToDevice); cudaMemcpy(d_P3, P_in3, bytes, cudaMemcpyHostToDevice); ConvolutionTile<<<dimGrid,dimBlock>>>(d_A3,d_P3,MAX_MASK_WIDTH,N); cudaDeviceSynchronize(); cudaMemcpy(P_out3,d_P3, bytes, cudaMemcpyDeviceToHost ); end=clock(); double elapsed_seconds3=end-start; printf("Tiempo Paralelo Tile: %lf\n", (elapsed_seconds3 / CLOCKS_PER_SEC)); //imprimirVec(P_out3,N); //cout<<"Aceleracion: "<<elapsed_seconds/elapsed_seconds3<<endl; free(P_in3); cudaFree(d_A3); cudaFree(d_P3); /*-----------------------------------------------------------------------------------------*/ comparar(P,P_out1,P_out2,P_out3,N); free(A); free(P); free(P_out1); free(P_out2); free(P_out3); //free(Mask); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "btree.h" #include "ascii_tree.h" /* * 1. leaks -atExit -- ./a.out | grep LEAK * we use the above command to detect memory leak. */ BTree* create_node(int data) { BTree* tmp = (BTree*) calloc(1, sizeof(struct tree_node)); if(!tmp) { printf("allocation failed in create_node function"); exit(-1); } tmp->data = data; tmp->left = NULL; tmp->right = NULL; return tmp; } void free_tree(BTree* root) { if(root) { if(root->left) free_tree(root->left); if(root->right) free_tree(root->right); free(root); } } // we assume the binary tree is a binary search tree because it's easier to implement the insert function // returns a pointer to the inserted node BTree* insert_node(BTree* root, int data) { if(!root) { BTree* tmp = create_node(data); return tmp; } if(data <= root->data) { BTree* n = insert_node(root->left, data); root->left = n; return n; } else if(data > root->data) { BTree* n = insert_node(root->right, data); root->right = n; return n; } else { /* we don't really need this else block, but we can use this as a gate keeper in case anything went wrong */ return NULL; } } // this version inserts a node into a balanced binary tree. // Rule: we check the left sub tree first, if the left is full, we insert the node into the right sub tree /* e.g. we insert 6 into [1, 2, 3, 4, 5] * before: * 1 * / \ * 2 3 * / \ * 4 5 * after: * 1 * / \ * / \ * 2 3 * / \ / * 4 5 6 */ BTree* insert_node_bal(BTree* root, int data) { if(!root) { BTree* tmp = create_node(data); return tmp; } // 1. check left sub tree hight and right sub tree hight // 2. does left child node have two nodes which are not null? // 3. true -> insert right, false -> insert left } int main() { BTree* root = create_node(0); print_ascii_tree(root); insert_node(root, 1); print_ascii_tree(root); free_tree(root); return 0; }
C
#include<stdio.h> void binaryofnum(int ); #define BITS sizeof(int)*8 int main(void){ unsigned int num,msb; printf("enter a number \n"); scanf("%u",&num); binaryofnum(num); msb=1<<(BITS-1); if(num&msb) printf("msb of %d is set",num); else printf("msb of %d is not set",num); return 0; } void binaryofnum(int num){ for(int i=(BITS-1);i>=0;i--){ printf("%d",(num&(1<<i))?1:0); } printf("\n"); }
C
/* * Name: Declan Simkins * Program: q2.c * Lab Section: Tuesday 2:00pm * Lab Instructor's Name: Stephanie Husby * CMPT 360 * Instructor's Name: Cam Macdonell * -------------------- * Desc: Lab 2 Question 2 * Opens a file, forks, then attempts to access the file descriptor * from both the parent and child * Answer: Yes, both process can access the file descriptor returned by * open(); however, they are accessing their own copy of this file descriptor * (which is simply an unsigned int). Both processes write to the file in * sequence. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> int main(int argc, char *argv[]) { int fd = open("q2test.txt", O_WRONLY | O_CREAT, 0200); int rc = fork(); sleep(2); if (rc < 0) { fprintf(stderr, "Failed to fork.\n"); exit(1); } else if (rc == 0) { char childToWrite[] = "CHILD WRITING TO Q2TEST.TXT\n"; write(fd, childToWrite, sizeof(childToWrite) - sizeof(char)); } else { char parentToWrite[] = "PARENT WRITING TO Q2TEST.TXT\n"; write(fd, parentToWrite, sizeof(parentToWrite) - sizeof(char)); } close(fd); return 0; }
C
#include <stdio.h> #include <assert.h> #include <string.h> #define MAXLINES 5000 #define MAXLINESIZE 256 char **max(char **a, int len) { char **m; m = a; while(--len > 0) { a++; if(strcmp(*a, *m) > 0)//*a > *m) m = a; } return m; } void sort(char **a, int len) { char **tp; char *t; assert(a != NULL); if(len <= 0) return; while(--len > 0) { tp = max(a, len + 1); t = *a; *a = *tp; *tp = t; a++; } return; } // used by read lines // from /Users/darbinreyes/dev/experiments/C/KNR_C/Chapter5/s5.5/ce5.6.c size_t my_getline(char *s,const int lim) { char c; char *t; t=s; assert(lim != 0); while(s < (s+lim-1) && (c=getchar()) != EOF && c!='\n') *s++ = c; if(c == '\n') *s++ = c; *s = '\0'; return (size_t)(s-t); } int readlines(char *lines[], int maxlines){ int count = 0, i = 0; while(my_getline(*lines++, MAXLINESIZE) > 0 && maxlines > count++) ; return count; } // output lines void writelines(char *lines[], int len) { assert(lines != NULL); int i = 0; while(len-- > 0) printf("%s", *lines++); } /** Darbin-Reyess-MacBook-Pro:s5.5 darbinreyes$ echo 'a b c '|./a.out c b a **/ int main(void) { int nlines = 0; char buffer[MAXLINES][MAXLINESIZE]; char *bp[MAXLINES]; while(nlines++ < MAXLINES) bp[nlines-1] = &buffer[nlines-1][0]; nlines = readlines(bp, MAXLINES); sort(bp,nlines); writelines(bp, nlines); }
C
#include "xmempool.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef _WIN32 #include <unistd.h> #endif typedef struct xmem_pool_block { char* start; uint32_t block_size; struct xmem_pool_block* next; uint32_t is_block_start; } xmem_pool_block; typedef struct xmem_pool { uint32_t block_size; uint32_t block_count; char* start; char* end; xmem_pool_block* free_blocks; xmem_pool_block* free_blocks_tail; struct xmem_pool* next; uint32_t next_alloc_length; } xmem_pool; #define MIN_ALLOC_BLOCK_NODE_COUNT (1024) #define MAX_ALLOC_BLOCK_NODE_COUNT (1024 << 2) #define MIN_ALLOC_LENGTH (1024) #define MAX_ALLOC_LENGTH (1024 << 2) static uint32_t _xmem_pool_next_alloc_block_node_count = MIN_ALLOC_BLOCK_NODE_COUNT; static xmem_pool_block* _free_block_ptr = 0; static xmem_pool_block* _free_block_ptr_end = 0; static int _xmem_page_size = 0; static uint32_t _block_size = sizeof(xmem_pool_block); uint32_t size_count_with_4(uint32_t size) { if (size % 4 == 0) { return size; } else { return size + (4 - size % 4); } } static inline void _alloc_block_nodes() { uint32_t size_count = _block_size * _xmem_pool_next_alloc_block_node_count; _xmem_pool_next_alloc_block_node_count <<= 1; if (_xmem_pool_next_alloc_block_node_count > MAX_ALLOC_BLOCK_NODE_COUNT) { _xmem_pool_next_alloc_block_node_count = MAX_ALLOC_BLOCK_NODE_COUNT; } #ifdef _WIN32 char* start = (char*)malloc(size_count); #else char* start; posix_memalign((void**)&start, _xmem_page_size, size_count); #endif char* block_ptr = start; char* end = start + size_count; // can't malloc more space(s). if (!block_ptr) return; for (; block_ptr < end; block_ptr += _block_size) { xmem_pool_block* block = (xmem_pool_block*)block_ptr; block->is_block_start = (block_ptr == start); block->start = 0; // if it's not starting block, // set previous block's next block // to this. if (block_ptr != start) { ((xmem_pool_block*)(block_ptr - _block_size))->next = block; } block->block_size = 0; } ((xmem_pool_block*)(end - _block_size))->next = 0; if (_free_block_ptr && _free_block_ptr_end) { // there's block pointer(s) before, // and still some in the `_free_block_ptr`, // concat newer one list to the old one's tail. _free_block_ptr_end->next = (xmem_pool_block*)start; } else { // otherwise, replace the whole `_free_block_ptr`. _free_block_ptr = (xmem_pool_block*)start; } _free_block_ptr_end = (xmem_pool_block*)(end - _block_size); } static inline xmem_pool_block* _get_next_block_node() { xmem_pool_block* should_return; // if no more block node, // generate a new block node list if (!_free_block_ptr) { _alloc_block_nodes(); } // if still no more block node, // return 0 to stand for error if (!_free_block_ptr) return (xmem_pool_block*)0; should_return = _free_block_ptr; _free_block_ptr = _free_block_ptr->next; // if `should_return` is the last one, // we should set the tail to 0. if (should_return == _free_block_ptr_end) { _free_block_ptr_end = 0; } return should_return; } static inline void _recover_block_node(xmem_pool_block* node) { node->block_size = node->next = node->start = 0; if (_free_block_ptr && _free_block_ptr_end) { _free_block_ptr_end->next = node; _free_block_ptr_end = node; } else { _free_block_ptr = _free_block_ptr_end = node; } } static inline int _xmem_count_free_blocks(xmem_pool* pool) { xmem_pool_block* block; int count; if (!pool->free_blocks) return 0; block = pool->free_blocks; count = 1; while (block != pool->free_blocks_tail) { count++; block = block->next; } return count; } xmem_pool_handle _create_pool(uint32_t block_size, uint32_t block_count) { static uint32_t _pool_size = sizeof(xmem_pool); xmem_pool* pool = (xmem_pool*)malloc(_pool_size); uint32_t size_count = block_count * block_size; uint32_t alloc_size = size_count_with_4(size_count); char* space; #ifndef _WIN32 if (_xmem_page_size < alloc_size) { posix_memalign((void**)&space, _xmem_page_size, alloc_size); } else { #endif space = (char*)malloc(size_count); #ifndef _WIN32 } #endif xmem_pool_block* start_block = 0; xmem_pool_block* end_block = 0; // can't malloc more space if (!pool) return (char*)0; if (!space) { free(pool); return (char*)0; } // set the pool space's start and end pool->start = space; pool->end = space + (block_count * block_size); pool->block_size = block_size; pool->block_count = block_count; pool->next = 0; pool->next_alloc_length = block_count << 1; if (pool->next_alloc_length > MAX_ALLOC_LENGTH) { pool->next_alloc_length = MAX_ALLOC_LENGTH; } // create free nodes! for (; space < pool->end; space += block_size) { xmem_pool_block* wrapper = _get_next_block_node(); if (!start_block) { start_block = wrapper; } // if we can't create any more wrapper, // free `pool`, `space`, // and recover all pool blocks genereated before if (!wrapper) { free(pool); free(space); while (start_block) { xmem_pool_block* next = start_block->next; _recover_block_node(start_block); start_block = next; } return 0; } wrapper->block_size = block_size; wrapper->start = space; wrapper->next = 0; // concat wrapper to the tail of block list if (end_block) { end_block->next = wrapper; } end_block = wrapper; } pool->free_blocks = start_block; pool->free_blocks_tail = end_block; return (char*)pool; } void xmem_print_info(xmem_pool_handle _pool) { xmem_pool* pool = (xmem_pool*)_pool; int pool_id = 0; if (!_pool) return; while (pool) { printf("----- POOL OF SIZE [%.4d] -----\n", pool->block_size); printf(" + id: %d\n", pool_id++); printf(" + count: %d\n", pool->block_count); printf(" + spaces: [0x%.8X, 0x%.8X)\n", (unsigned int)pool->start, (unsigned int)pool->end); if (pool_id == 1) { printf(" + free blocks: %d\n", _xmem_count_free_blocks(pool)); } else { printf(" + free blocks: -\n"); } pool = pool->next; } } xmem_pool_handle xmem_create_pool(unsigned int block_size) { #ifndef _WIN32 if (_xmem_page_size == 0) { _xmem_page_size = getpagesize(); } #endif #ifdef XMEM_DBG char* pool = _create_pool(block_size, MIN_ALLOC_LENGTH); printf("A new pool of [%d] is created!", block_size); return pool; #endif return _create_pool(block_size, MIN_ALLOC_LENGTH); } void xmem_destroy_pool(xmem_pool_handle handle) { xmem_pool* pool = (xmem_pool*)handle; xmem_pool* next_pool; if (!handle) return; // from pool head to pool tail while (pool) { // free the space. // and then remove all free blocks object // from head to tail. free(pool->start); // all the blocks are mansged in the // first pool. if (pool == (xmem_pool*)handle) { xmem_pool_block* block = pool->free_blocks; xmem_pool_block* next_block; // from block head to block tail while (block) { next_block = block->next; _recover_block_node(block); block = next_block; } } // move to next pool next_pool = pool->next; free(pool); pool = next_pool; } return; } char* xmem_alloc(xmem_pool_handle handle) { static uint32_t pool_element_size = sizeof(xmem_pool); xmem_pool* pool = (xmem_pool*)handle; xmem_pool temp_pool; xmem_pool_block* block; char* space; // if no more space, we create a new pool if (!pool->free_blocks) { xmem_pool* new_pool = (xmem_pool*)_create_pool(pool->block_size, pool->next_alloc_length); if (!new_pool) { return 0; } memcpy(&temp_pool, pool, pool_element_size); memcpy(pool, new_pool, pool_element_size); memcpy(new_pool, &temp_pool, pool_element_size); pool->next = new_pool; } // get the first free space block = pool->free_blocks; pool->free_blocks = block->next; space = block->start; if (!pool->free_blocks) pool->free_blocks_tail = 0; // initialize space data & recover block node memset(space, 0, block->block_size); _recover_block_node(block); return space; } int xmem_free(xmem_pool_handle handle, char* pointer) { xmem_pool* pool = (xmem_pool*)handle; // get a block. // if no block, return false. xmem_pool_block* block = _get_next_block_node(); if (!block) { return 0; } // create a new block to the free list. block->block_size = pool->block_size; block->start = pointer; block->next = 0; if (!pool->free_blocks && !pool->free_blocks_tail) { pool->free_blocks = pool->free_blocks_tail = block; return 1; } pool->free_blocks_tail->next = block; pool->free_blocks_tail = block; return 1; } void xmem_init() { // dummy code } void xmem_clean_up() { xmem_pool_block* blk = _free_block_ptr; xmem_pool_block* start = 0; xmem_pool_block* end = 0; while (blk != 0) { if (blk->is_block_start) { if (end) { end->next = blk; } else { start = blk; } end = blk; } blk = blk->next; } end->next = 0; blk = start; while (blk != 0) { end = blk->next; // borrow `end`'s variable name, but it's only a temporary // variable. free(blk); blk = end; } _free_block_ptr = _free_block_ptr_end = 0; }
C
#include "push_swap.h" void destroy_stack(t_stack **stk) { t_stack *tmp; while (*stk) { tmp = *stk; *stk = (*stk)->next; free(tmp); tmp = NULL; } } int stack_size(t_stack *stk) { int size; size = 0; while (stk) { size++; stk = stk->next; } return (size); } void ft_exit(void) { write(1, "Error\n",6); exit(0); } void ft_sort(t_stack **a) { int f; int m; int l; f = (*a)->val; m = (*a)->next->val; l = (*a)->next->next->val; if (f < m && m < l) return ; else if (f < l && l < m) { rrotate(a, 0); ft_swap(*a, 0); } else if (l < f && l > m) rotate(a, 0); else if (f > m && m > l) { ft_swap(*a, 0); rrotate(a, 0); } else if (f > m && m < l) ft_swap(*a, 0); else if (f < m && m > l) rrotate(a, 0); return ; } int main(int ac, char **av) { t_stk stk; if (ac == 1) return (0); stk.a = make_stack(ac, av); if (!stk.a) ft_exit(); check_duplicates(stk.a); stk.b = NULL; // disp_stack(stk); if (stack_size(stk.a) == 3) ft_sort(&stk.a); quick_sort(&stk.a, &stk.b, stack_size(stk.a)); // disp_stack(stk); destroy_stack(&stk.a); destroy_stack(&stk.b); return (0); }
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <pthread.h> #define _OPEN_THREADS #include <time.h> #include <errno.h> #include "linux_nfc_api.h" pthread_cond_t condition = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; nfcTagCallback_t g_TagCB; nfc_tag_info_t g_tagInfos; void onTagArrival(nfc_tag_info_t *pTagInfo){ // Stop waiting when tag is detected g_tagInfos = *pTagInfo; pthread_cond_signal(&condition); } void onTagDeparture(void){ // We do not want anything to occur during tag departure } int main(int argc, char ** argv) { int res = 0x00; int i; time_t T; struct timespec t; g_TagCB.onTagArrival = onTagArrival; g_TagCB.onTagDeparture = onTagDeparture; nfcManager_doInitialize(); nfcManager_registerTagCallback(&g_TagCB); nfcManager_enableDiscovery(DEFAULT_NFA_TECH_MASK, 0x01, 0, 0); // Wait for tag for two ms time(&T); t.tv_sec = T + 2; pthread_cond_timedwait(&condition, &mutex, &t); // The only tag our project supports is ISO15693 if (g_tagInfos.technology == TARGET_TYPE_ISO15693) { unsigned char ReadCmd[] = {0x02U, 0x20, /*block*/ 0x04}; unsigned char Resp[255]; res = nfcTag_transceive(g_tagInfos.handle, ReadCmd, sizeof(ReadCmd), Resp, 32, 3000); if(0x00 == res) { printf("RAW Tag transceive failed\n"); } else { // Raw access to tag succeeded for(i = 0x00; i < (unsigned int)res; i++) printf("%02X ", Resp[i]); printf("\n\n"); } } nfcManager_doDeinitialize(); return 0; }
C
/** * Program to execute strcat ,strcpy and strcmp string functions. * * Compilation: gcc -o ques_14 ques_14.c * Execution:./ques_14 * * @Aniket , (1910990836) , 23/07/2021 * Assignment 1 */ #include<stdio.h> #include<string.h> #include<stdlib.h> #define N 100 /** * Function to find length of the string * * Parameters: * *s : base address of string 1 * * returns length of the string */ int strnlen1(char *s) { int i = 0; while( s[i] != '\0' ) { i++; } return i; } /** * Function to execute strcat function * * Parameters: * *str1 : base address of string 1 * *str2 : base address of string 2 * n : number of characters on which operation is to be performed * */ char *strncat_fun (char *str1, char *str2, int n) { int i = 0; while( *str1 ) { str1++; } while(n > 0 && *str2) { *str1 = *str2; str1++; str2++; n--; } *str1 = '\0'; return str1; } /** * Function to execute strcpy function * * Parameters: * *str1 : base address of string 1 * *str2 : base address of string 2 * n : number of characters on which operation is to be performed * */ char *strncpy_fun(char *s , char *t, int n) { while( *s ) { if(n != 0) { *s = *t; n--; } s++,t++; } *s = '\0'; return s; } /** * Function to execute strcmp function * * Parameters: * *str1 : base address of string 1 * *str2 : base address of string 2 * n : number of characters on which operation is to be performed * * returns 0 : When strings are same * returns > 0 : When String 1 is bigger than String 2 * returns < 0 : When String 1 is smaller than String 2 */ int strncmp_fun(char *s , char *t, int n) { if(strnlen1(s) == strnlen1(t)) { while( *s == *t && n ) { s++,t++,n--; } if( n == 0 ) return 0; else return 1; } else return strnlen1(s) -strnlen1(t); } int main () { int n; // For number of characters on which operation is to be performed char str1[N]; printf("For strcat function\n"); printf("Enter String 1 : "); gets(str1); char str2[N]; printf("Enter String 2 : "); gets(str2); printf("Enter number of characters on which operation is to be performed : "); scanf("%d", &n); strncat_fun(str1, str2, n); printf("Resultant String : %s",str1); printf("\n"); printf("\n"); char str3[N]; printf("\nFor strcpy function\n"); printf("Enter String 1 : "); gets(); gets(str3); char str4[N]; printf("Enter String 2 : "); gets(str4); printf("Enter number of characters on which operation is to be performed : "); scanf("%d", &n); strncpy_fun(str3, str4, n); printf("Resultant String : %s",str3); printf("\n"); printf("\n"); char str5[N]; printf("\nFor strcmp function\n Result = 0 : When strings are same\n Result > 0 When String 1 is bigger than String 2\n Result < 0 : When string 1 is smaller then string 2\n"); printf("Enter String 1 : "); gets(); gets(str5); char str6[N]; printf("Enter String 2 : "); gets(str6); printf("Enter number of characters on which operation is to be performed : "); scanf("%d", &n); printf("Result : %d",strncmp_fun(str5, str6, n)); }
C
#include<stdio.h> #include "my-math.h" #define LEVEL 2 int main () { printf("We are going to multiply with integers from a header file.\n"); printf("The product of 4 and 5 is %d.\n", multiply(4 , 5)); printf("------- Macro Code---------\n"); printf("The square of 4 is %d\n", SQUARE(4)); #if LEVEL > 0 printf("LEVEL is greater than 0.\n"); #endif #if defined(RUNTIME) printf("The RUNTIME is defined.\n"); #endif return 0; }
C
#define MAX_BUFFER_SIZE 128 pthread_mutex_t mutex; pthread_cond_t cond; GMainLoop *loop = NULL; gboolean callback(GSocketService* service, GSocketConnection *conn, GObject* *object, gpointer user_data) { GError *error = NULL; int len; char buffer[MAX_BUFFER_SIZE] = {0x00, }; GInputStream *is = g_io_stream_get_input_stream(G_IO_STREAM(conn)); GOutputStream *os = g_io_stream_get_output_stream(G_IO_STREAM(conn)); // ############################################################################## printf("Server - (2/5) Connection Accepted\n"); while (TRUE) { memset(buffer, 0, sizeof(buffer)); len = g_input_stream_read(is, buffer, sizeof(buffer)-1, NULL, &error); if ( ( len = sscanf(buffer, "%s", buffer) ) == EOF ) { break; } printf("Server - (3/5) Client Message: %s\n", buffer); strcat(buffer, " is also good"); printf("Server - (4/5) Feedback Message: %s\n", buffer); g_output_stream_write(os, buffer, strlen(buffer), NULL, &error); } printf("Server - (5/5) Connection Closed\n"); // ############################################################################## // g_main_loop_quit(loop); return FALSE; } gpointer server_thread_func(gpointer data) { GError *error = NULL; GSocketService *service = g_socket_service_new(); g_socket_listener_add_inet_port(G_SOCKET_LISTENER(service), 9876, NULL, &error); g_signal_connect(service, "incoming", G_CALLBACK(callback), NULL); g_socket_service_start(service); /////////////////////////////////// printf("Server - (1/5) Ready\n"); ////////////////////////////////// loop = g_main_loop_new(NULL, FALSE); g_main_loop_run(loop); // after loop close g_socket_service_stop(service); g_socket_listener_close(G_SOCKET_LISTENER(service)); return NULL; } gpointer server_thread_native_func(gpointer data) { struct sockaddr_in server_addr; int server_socket = socket(PF_INET, SOCK_STREAM, 0); server_addr.sin_family = AF_INET; // IPv4 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // 32bit IPv4 server_addr.sin_port = htons(9876); // port num // bind socket with server address bind(server_socket, (struct sockaddr*) &server_addr, sizeof(server_addr) ); // listen with 5 queue listen(server_socket, 5); printf("Server - (1/5) Ready\n"); // ############################################################################## while (TRUE) { // connect with client addr struct sockaddr_in client_addr; int client_addr_size = sizeof(client_addr); int client_socket = accept(server_socket, (struct sockaddr*) &client_addr, &client_addr_size ); printf("Server - (2/5) Connection Accepted\n"); // printf("%s:%d accepted\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); char buffer[MAX_BUFFER_SIZE] = {0x00, }; int len; while ( TRUE ) { memset(buffer, 0, sizeof(buffer)); len = read(client_socket, buffer, sizeof(buffer)-1 ); if ( strcmp(buffer, "quit") == 0 ) break; // quit with "quit printf("Server - (3/5) Client Message: %s\n", buffer); // g_output_stream_write(os, buffer, strlen(buffer), NULL, &error); strcat(buffer, " is also good"); printf("Server - (4/5) Feedback Message: %s\n", buffer); write(client_socket, buffer, sizeof(buffer)); } close(client_socket); printf("Server - (5/5) Connection Closed\n"); } close(server_socket); return NULL; } gpointer client_thread_func(gpointer data) { GError *error = NULL; GSocketClient *client = g_socket_client_new(); GSocketConnection *conn = g_socket_client_connect_to_host(client, (gchar*)"localhost", 9876, NULL, &error); GOutputStream *os = g_io_stream_get_output_stream(G_IO_STREAM(conn)); GInputStream *is = g_io_stream_get_input_stream(G_IO_STREAM(conn)); // ############################################################################## char buffer[MAX_BUFFER_SIZE] = {0x00, }; char message[MAX_BUFFER_SIZE] = {0x00, }; int len; printf("Client - (1/5) Connection Established\n"); while ( fgets(buffer, sizeof(buffer), stdin) != NULL ) { if( (len = sscanf(buffer, "%s", buffer)) == EOF ) continue; // ignore with empty input if ( strcmp(buffer, "quit") == 0 ) break; // quit with "quit" printf("Client - (2/5) Input Message: %s\n", buffer); strcat(buffer, " is good"); printf("Client - (3/5) Send Message: %s\n", buffer); g_output_stream_write(os, buffer, strlen(buffer), NULL, &error); gsize read_count = g_input_stream_read(is, message, sizeof(message)-1, NULL, &error); message[read_count] = '\0'; printf("Client - (4/5) Feedback Message: %s\n", message); } g_output_stream_write(os, buffer, strlen(buffer), NULL, &error); printf("Client - (5/5) Connection Closed\n"); // ############################################################################## g_object_unref(client); return NULL; } int main(int argc, char *argv[]){ GThread* server_thread = g_thread_new(NULL, server_thread_native_func, NULL); GThread* client_thread = g_thread_new(NULL, client_thread_func, NULL); g_thread_join(server_thread); g_thread_join(client_thread); return 0; }
C
//Raymond Waidmann //rcw5k2 //e-hw3.c //DO NOT HARDCODE FILENAMES //DO NOT HARDCODE THE COUNT OF RECORDS IN THE INPUT FILE #include <stdio.h> #include <stdlib.h> int get_record_count(char*); int load_data(char*, int*, float*, int); void print_data(int*, float*, int); int highest_amount(float*, int); int lowest_amount(float*, int); float average_amount(float*, int); int write_data(char*, int*, float*, int, int, int, float); int main (int argc, char * argv[]) // //use command line args to get file names from user // //use argc to check if there enough inputs by user (if no, display error message and terminate program) // //get number of lines in the input file (so you know how many ints and floats you will need to allocate) // //allocate space using malloc to an int * and float * (for account numbers, and amount numbers) (int array and float array) (malloc only how much space you need based on # of lines) // //call load_data and print_data to load and print the account info // //call print_data to display the updated info // //call highest, lowest, and average functions and print results as shpwn in sample output // //call write_data and write the info to the output text file. // //free the malloced space { if (argc != 3) { printf("Incorrect number of Arguments!"); //if the command line arguments are not the correct number (./a.out and argv[1]), end the program return (-1); } int count = get_record_count (argv[1]); //calling function get_records_count to count the number of lines in the input.txt file //printf("%d", count); (this prints 8 meaning count is the correct number of lines in the input file) if (count == -1) //if the input file could not be opened, terminate the program { return (-1); } int * account = malloc (sizeof(int) * count); float * balance = malloc (sizeof(float) * count); //allocating space to accoutn and balance arrays based of of how many lines were counted in the input file load_data (argv[1], account, balance, count); //calling function load_data to scan in the values of the file into arrays account and balance print_data(account, balance, count); //printing the data to the screen using function print data int high = highest_amount(balance, count); //calling the high, low, and average functions and printing the rresults to the screen //printf("high = %d", high); (testing to make sure the highest valued index is correct, it is 2 which is correct) printf("The highest amount of $%.2f is in the account number %d\n", balance[high], account[high]); int low = lowest_amount(balance, count); printf("The lowest amount of $%.2f is in the account number %d\n", balance[low], account[low]); //printing the high, low, and average values and their account nnumber float average = average_amount(balance, count); printf("The average amount of all the accounts is $%.2f\n\n", average); int sentinel = write_data(argv[2], account, balance, count, high, low, average); if (sentinel == 0) //if the output file could not be opened, terminate the program { return (-1); } free(account); //freeing the malloced space from account and balance arrays free(balance); } int get_record_count (char * filename) //takes the name of an input file //opens and read lines from the file //count the lines as it goes //returns the number of lines in the input file // //assume no line in the input file has no more than 255 characters //use fgets() to read in one line at a time so you can count //be careful about the return value of fgets(fgets returns NULL if it fails to read a line) //be careful about checking feof() - didnt need to use per Madi YEET { FILE * fptr; //open the file and create a file pointer if ((fptr = fopen(filename, "r")) == NULL) //checking for successful opening of the input file { printf("\n*****INPUT FILE COULD NOT BE OPENED*****\n\n"); return (-1); //returning -1 as "count } int count = 0; char buffer[255]; //number of chars per line (assume no line has more than 255 characters) while(fgets(buffer, sizeof(buffer), fptr) != NULL) //reading in a line from the file; loop doesnt execute of line is failed to be read (no contents in the line) { count++; //counting the number of lines } fclose(fptr); //closing the file return (count); //returning the number of lines } int load_data (char * filename, int * account, float * balance, int size) //opens the input file (if unable, return 0) - error checkl for file opening is done in function get_record_count //load account info from the text file into the int and float arrays and return 1 at end (first line of text file) // //use a file pointer to open the file (ex. FILE * file = fopen(filename, x) [where x the file access mode]) { FILE * fptr = fopen (filename, "r"); //opening the input file for reading for (int i = 0; i < size; i++) { fscanf(fptr, "%d%f", &account[i], &balance[i]); //scanning in the info from the file to account and balance arrays } fclose(fptr); //closing the file return(1); //indicated successful run of the function } void print_data (int * account, float * balance, int size) //takes in an int array, float array, and int size //displays the data stored in these arrays as in sample output //make sure things line up correctly as shown { printf("\n%d records in the file.\nAccount No. Amount", size); for (int i = 0; i < size; i++) { printf("\n%-12d%7.2f", account[i], balance[i]); //(correctly prints the contents of account[] and balance[] as assigned from input.txt file } puts(""); puts(""); } int highest_amount (float * balance, int size) //takes float * and number of accounts //finds highest amount and returns index cooresponding to highest amount { int q = 0; for (int m = 0; m < size; ++m) //running through the array as many times as necessary to check for the highest { if (balance[m] > balance[q]) { q = m; //assigning the highest index to q } } return q; } int lowest_amount (float * balance, int size) //same as above but lowest { int q = 0; for (int m = 0; m < size; ++m) { if (balance[m] < balance[q]) //only difference is in this line { q = m; } } return q; } float average_amount (float * balance, int size) //same as above (returns average amount) { float average = 0; for (int i = 0; i < size; i++) { average += balance[i]; //average is really the total of all of the accounts } float da_real_average = (average/size); //total/number of accounts return (da_real_average); //returning the average back to main } int write_data (char * filenameout, int * account, float * balance, int count, int highindex, int lowindex, float average) //outfut file name, acount number info, amount info, number of accounts, index of highest amount, index of lowest amount, average amount //use fprintf to write the data into the text file. return a 0 if the file was unable to open and write, return 1 if success { FILE * fptrout; //opening the output file for writing if ((fptrout = fopen(filenameout, "w")) == NULL) //checking for successful opening of the output file { printf("\n*****OUTPUT FILE COULD NOT BE OPENED*****\n\n"); return (0); //returning 0 as sentinel } fprintf(fptrout, "Account No. Amount"); for (int i = 0; i < count; i++) { fprintf(fptrout,"\n%-12d%7.2f", account[i], balance[i]); //printing all the numbers to the output file } fprintf(fptrout,"\n\nThe highest amount of $%.2f is in the account number %d\n", balance[highindex], account[highindex]); fprintf(fptrout,"The lowest amount of $%.2f is in the account number %d\n", balance[lowindex], account[lowindex]); //printing the high low and average to output file fprintf(fptrout,"The average amount of all the accounts is $%.2f", average); fclose(fptrout); //closing the file pointer return (1); }
C
/*============================*/ /* Euler method for ODE (IVP) */ /* x' = f(t,x) /* x(T0)=X0 /*============================*/ #include <stdio.h> #include <math.h> /*--- Calculate from t=T0 to t=T1 ---*/ #define T0 0.0 #define T1 5.0 /*--- Initial data ---*/ #define X0 2.0 /*--- parameter(s) ---*/ #define A 1.0 /*--- division number ---*/ #define N 50 /*--- f(t,x) ---*/ double f(double t, double x) { return A*x; } double f_2(double t,double x) {return x - x*x;} /*--- Exact solution ---*/ double ExactSol(double t) { return exp(A*t); } double ExactSol_2(double t, double c) { return exp(t)/(exp(t) + c); } /*--- Euler scheme ---*/ double euler(double h, double t, double x) { //switch f/f_2 return(x+h*f_2(t,x)); // x: X_n, t: t_n } /*--- main ---*/ /* h: mesh size x=X_n: approx. sol. t: time en=|e_n|: error maxen=max_n |e_n| */ int main(void) { int n; double h=(T1-T0)/N; double x=X0; double t; double maxen=0.0, en; double c = 0.0; c = (exp(T0) - exp(T0)*X0)/X0 ; printf("euler method\n"); for(n=0; n<N; n++) { t=T0+n*h; //switch f/f_2 en=fabs(x-ExactSol_2(t,c)); maxen=fmax(maxen, en); /* display t_n, X_n, x(t_n) and |e_n| */ //switch f/f_2 printf("%6.4f %16.14f %16.14f %16.10e\n", t, x, ExactSol_2(t,c), en); x=euler(h,t,x); // X_{n+1}=euler(h, t_n, X_n) } /* max of |e_n| */ printf("max_n |e_n|=%16.10e\n",maxen); }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int n, n1, n2, n3, i, sum=0; printf("ڿ Է :"); scanf("%d", &n); n1=n/100; n2=n%100/10; n3=n-(n1*100+n2*10); sum=n1+n2+n3; printf("%d\n", sum); return 0; }
C
#include <stdio.h> int main(void) { int A[10]; int v,sum,i,j,m; printf("Ingrese 10 numeros enteros\n"); printf("\n"); for (i = 0; i < 10; ++i){ printf("Ingresa el valor [%i]: ",i ); scanf("%i",&v); A[i]=v; sum += A[i]; } printf("\n"); printf("El arreglo es: "); for (i = 0; i < 10; ++i) { printf("%i,",A[i]); } printf("\n"); printf("La suma de los elementos del arreglo es: %i\n",sum); int *p,*q; for(i=0;i<10;i++) { for(j=0;j<10-1;j++) { if(A[i]>A[j]) { m=A[i]; A[i]=A[j]; A[j]=m; } } } *p = &m; printf("El numero mayor es: %i\n",*p); return 0; }
C
#ifndef __UTILITIES_H__ #define __UTILITIES_H__ /*************************** MACROS ****************************/ #define TEST(condition, func_name) ((1) == (condition))? \ printf("%s:\t\x1b[32m SUCCESS \x1b[0m | Line: %d\n", #func_name, __LINE__) : \ printf("%s:\t\x1b[31m FAILURE \x1b[0m | Line: %d\n", #func_name, __LINE__) #ifndef NDEBUG #include <stdio.h> #include <errno.h> #define ERR_PRINT() perror("errno"); fprintf(stderr, "Error in %s file, in line: %d\n", __FILE__ , __LINE__) #else #define ERR_PRINT() #endif #endif /* __UTILITIES_H__ */
C
#include <stdio.h> #define PI 3.1416 int y=2; int main(){ float radio ,L=0; printf("Digite el valor del radio: "); scanf("%f", &radio); L= y * PI * radio; printf("La longitud de la circunferencia es: %.2f", L); return 0; }
C
#include "binary_trees.h" /** * binary_tree_balance - calculates balance of a tree * @tree: pointer to the root * Return: integer */ int binary_tree_balance(const binary_tree_t *tree) { int height_r = 0, height_l = 0; if (tree == NULL) return (0); height_r = find_height(tree->right); height_l = find_height(tree->left); return (height_l - height_r); } /** * find_height - finds height * @tree: pointer to the root of a tree * Return: height of the tree */ int find_height(const binary_tree_t *tree) { int l_height = 0; int r_height = 0; if (tree == NULL) return (-1); l_height = find_height(tree->left); r_height = find_height(tree->right); return ((l_height > r_height ? l_height : r_height) + 1); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_getopt_tools.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ldedier <ldedier@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/27 15:43:06 by ldedier #+# #+# */ /* Updated: 2019/11/27 15:44:59 by ldedier ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" void init_opt_parser(t_opt_parser *parser, t_option *opts, size_t size, int need_opts) { parser->options = opts; parser->nb_options = size; parser->need_options = need_opts; } void print_number(int fd, int number) { int mod; mod = number % 10; if (mod == 1) ft_dprintf(fd, "%dst", number); else if (mod == 2) ft_dprintf(fd, "%dnd", number); else ft_dprintf(fd, "%dth", number); } int print_necessaries_options(t_opt_parser *parser, int index) { size_t i; size_t j; print_number(2, index + 1); ft_dprintf(2, " argument has to be one of those:\n"); i = 0; j = 0; while (i < parser->nb_options) { if (parser->options[i].fixed_position == index) { if (j++ == 0) ft_dprintf(2, "\n"); dprint_option(2, &parser->options[i], 1); ft_dprintf(2, "\n"); } i++; } ft_dprintf(2, "\n"); return (E_OPT_RET_ERROR_UNKNOWN_OPTION); } int describe_option(char *arg) { return (ft_strlen(arg) >= 2 && arg[0] == '-'); } int ft_need_option(t_opt_parser *parser) { size_t i; i = 0; while (i < parser->nb_options) { if (parser->options[i++].necessity > 0) return (1); } return (0); }
C
#include <stdio.h> #include <stdlib.h> #define DLAN 50 int main() { char plik[DLAN]; char ch; FILE *wp; long licznik,koniec; puts("podaj nazwe pliku: "); gets(plik); if((wp=fopen(plik,"rb"))==NULL) { fprintf(stderr,"nie moge otworzyc pliku %s\n",plik); exit(1); } fseek(wp,0L,SEEK_END); koniec=ftell(wp); for(licznik=1L;licznik<=koniec;licznik++) { fseek(wp,-licznik,SEEK_END); ch=getc(wp); if(ch!='\032'&&ch!='\r') { putchar(ch); } } putchar('\n'); fclose(wp); printf("Hello world!\n"); return 0; }
C
/** * \file main.c * \author wzj * \brief * \version * \note * \date: 2015年10月29日 星期四 20时09分47秒 CST * * 找到最短路径, 使用最短路径算法时,额外保留当前路径上最高权值 * 的边,用于费用减免 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXN (1024) #define INF (99999) int n_vetex; int map[MAXN][MAXN]; int max_e[MAXN][MAXN]; int begin; int end; char str[MAXN][32]; int find_idx(char *p) { int i; for (i = 0; i < n_vetex; i++) { if (!strcmp(str[i], p)) { return i; } } strcpy(str[i], p); n_vetex++; return i; } void init() { int i, j, total; char str1[32], str2[32]; int idx_f, idx_t, w; for (i = 0; i < MAXN; i++) { for (j = 0; j < MAXN; j++) { map[i][j] = INF; max_e[i][j] = 0; } } n_vetex = 0; scanf("%s %s", str1, str2); begin = find_idx(str1); end = find_idx(str2); scanf("%d", &total); for (i = 0; i < total; i++) { scanf("%s %s %d", str1, str2, &w); idx_f = find_idx(str1); idx_t = find_idx(str2); map[idx_f][idx_t] = w; max_e[idx_f][idx_t] = w; } } void floyd() { int i,j,n; int max; for (n = 0; n < n_vetex; n++) { for (i = 0; i < n_vetex; i++) { for (j = 0; j < n_vetex; j++) { if (i == n || j == n) continue; if (max_e[i][n] < max_e[n][j]) { max = max_e[n][j]; } else { max = max_e[i][n]; } if (map[i][n] + map[n][j] - max < map[i][j] - max_e[i][j]) { map[i][j] = map[i][n] + map[n][j]; if (max > max_e[i][j]) { max_e[i][j] = max; } } } } } } int main(int argc, char* argv[]) { init(); floyd(); printf("%d", map[begin][end] - max_e[begin][end]); return 0; }
C
#include "demo.h" struct sym_list Head; /* head of singly-linked list */ /* * Daemon provides an interactive associative memory * via a socket-based interface. Clients either set * values with an assignment statement or access * values with a $ preface. When the value is * accessed, we write it onto the client's socket. * We currently do this as an iterative server for * reasons of queuing and serialization. If the * server is made concurrent, the database will have * to have serialized access and copy control - this * is not necessary yet. * * Program notes: * Parsing is done * with find_dollar() and find_equals(). * Storage management is carried out by the insert() * and lookup() routines. * save() and restore() routines added to * use disk storage to maintain memory across * invocations. * Iterative server code is copied from Stevens, "UNIX Network * Programming: Networking APIs: Sockets and XTI," p. 101 * */ int main( int argc, char *argv[], char *env[] ) { int server_fd, connection_fd, create_service(); void service(), save(), restore(); socklen_t len; struct sockaddr_in cliaddr; char buf[BUFSIZE]; extern int close(); server_fd = create_service(); restore( DATABASE ); service(server_fd,len,cliaddr); save( DATABASE ); close( server_fd ); } void service( int fd,socklen_t len, struct sockaddr_in cliaddr) { char buf[BUFSIZE]; extern void fix_tcl(), insert(),save(); /* interface between socket and stdio */ len = sizeof(cliaddr); while(recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr*)&cliaddr, &len) > 0 ){ char *ptr, *name, *value; fix_tcl( buf ); /* hack to interface with tcl scripting language */ /* ASSIGN */ if( (ptr = find_equals( buf )) != (char *) NULL ) { #ifdef EBUG fprintf( stderr, "ASSIGN: %s\n", buf ); dump( buf ); #endif *ptr = EOS; name = strsave( buf ); value = strsave( ++ptr ); insert( name, value ); save( DATABASE ); sendto(fd, "\n", BUFSIZE, 0, (struct sockaddr*)&cliaddr, len); #ifdef EBUG fprintf( stderr, "REPLY: <>\n" ); #endif } else if ((ptr = find_dollar( buf )) != (char *) NULL) /* RETRIEVE */ { char *reply, *find_newline; #ifdef EBUG dump( ptr ); #endif /* removes trailing newline if found */ if( (find_newline = strrchr( ptr, NEWLINE )) != NULL ) *find_newline = EOS; if( (reply = lookup( ++ptr )) != NULL ) { sendto(fd, reply, BUFSIZE, 0, (struct sockaddr*)&cliaddr, len); #ifdef EBUG fprintf( stderr, "REPLY: <%s>\n", reply ); #endif } else { sendto(fd, "\n", BUFSIZE, 0, (struct sockaddr*)&cliaddr, len); #ifdef EBUG fprintf( stderr, "REPLY: <>\n" ); #endif } } else { #ifdef EBUG fprintf( stderr, "GARBAGE\n" ); #endif } } return; } int create_service() { int listenfd; struct sockaddr_in servaddr; listenfd = socket(AF_INET, SOCK_DGRAM, 0 ); if( listenfd < 0 ) { perror( "creating socket for listenfd" ); exit( ERR_SOCKET ); } bzero( &servaddr, sizeof(servaddr) ); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl( INADDR_ANY ); servaddr.sin_port = htons( CIS553_PORT ); if( bind( listenfd, (SA *) &servaddr, sizeof(servaddr) ) < 0 ) { perror( "bind on listenfd"); exit( ERR_BIND ); } return listenfd; } void fix_tcl( char *buf ) { char *ptr; #define CARRIAGE_RETURN '\r' if( (ptr = strrchr( buf, CARRIAGE_RETURN )) != NULL ) *ptr = EOS; return; } void dump( char *buf ) { fprintf( stderr, "strlen(buf)=%d, buf=<%s>\n", (int) strlen(buf), buf ); int i; for( i=0; buf[i] != EOS; i++ ) fprintf( stderr, "%d:%c:%x\n", i, buf[i], buf[i] ); }
C
/* Tina Tami * * This file contains the data structure described * in the stack.h file. */ #include <stdlib.h> #include <stdio.h> #include "stack.h" #define STACK_SIZE 100 /* These are the variables we will need. */ struct stack { int pushes; int pops; int maxSize; int currentSize; int myStack[STACK_SIZE]; }; /* Setting all the variables to zero. */ struct stack *stack_init() { struct stack* s = malloc(sizeof(struct stack)); s -> pushes = 0; s -> pops = 0; s -> maxSize = 0; s -> currentSize = 0; return s; } /* Printing the stats and cleaning the stack. */ void stack_cleanup(struct stack* s) { int pushesInt = s -> pushes; int popsInt = s -> pops; int maxSizeInt = s -> maxSize; fprintf(stderr, "Statistics: %d %d %d\n", pushesInt, popsInt, maxSizeInt); free(s); } /* Pushes the element on to the stack if there is room left * in the stack. */ int stack_push(struct stack *s, int c) { if (s -> currentSize < STACK_SIZE) { s -> myStack[s -> currentSize] = c; s -> currentSize++; s -> pushes++; if (s -> currentSize > s -> maxSize) { s -> maxSize = s -> currentSize; } return 0; } return 1; } /* Pops the element from the stack if the stack is not empty. */ int stack_pop(struct stack *s) { if (s -> currentSize == 0) { return -1; } s -> pops++; s -> currentSize--; return s -> myStack[s -> currentSize]; } /* Returns the top element if the stack is not empty. */ int stack_peek(struct stack *s) { if (s -> currentSize == 0) { return -1; } return s -> myStack[s -> currentSize - 1]; } /* Checks if the stack is empty by checking its size. */ int stack_empty(struct stack *s) { if (s -> currentSize == 0) { return 1; } return 0; }