language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
//======================================================================== // quick-sort-main.c //======================================================================== #include <stdio.h> #include <stdlib.h> #include "ece2400-stdlib.h" #include "quick-sort.h" int main() { size_t size = 4; int a[] = { 19, 95, 4, 23 }; // Print out array before printf( "Before sorting: " ); ece2400_print_array( a, size ); // Call sort quick_sort( a, size ); // Print out array after printf( "After sorting: " ); ece2400_print_array( a, size ); return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_6__ TYPE_1__ ; /* Type definitions */ typedef int /*<<< orphan*/ Table ; struct TYPE_6__ {int /*<<< orphan*/ end_of_table; } ; typedef int /*<<< orphan*/ Statement ; typedef int /*<<< orphan*/ Row ; typedef int /*<<< orphan*/ ExecuteResult ; typedef TYPE_1__ Cursor ; /* Variables and functions */ int /*<<< orphan*/ EXECUTE_SUCCESS ; int /*<<< orphan*/ cursor_advance (TYPE_1__*) ; int /*<<< orphan*/ cursor_value (TYPE_1__*) ; int /*<<< orphan*/ deserialize_row (int /*<<< orphan*/ ,int /*<<< orphan*/ *) ; int /*<<< orphan*/ free (TYPE_1__*) ; int /*<<< orphan*/ print_row (int /*<<< orphan*/ *) ; TYPE_1__* table_start (int /*<<< orphan*/ *) ; ExecuteResult execute_select(Statement* statement, Table* table) { Cursor* cursor = table_start(table); Row row; while (!(cursor->end_of_table)) { deserialize_row(cursor_value(cursor), &row); print_row(&row); cursor_advance(cursor); } free(cursor); return EXECUTE_SUCCESS; }
C
//add two numbers #include<stdio.h> int main() { int a,b; printf("Enter the two numbers:\n"); scanf("%d%d",&a,&b); printf("sum= %d",a+b); return 0; }
C
#include <stdio.h> #include <math.h> int main() { int num, bin=0, n, x; scanf("%d", &num); while(num>0) { n=0; while(num>pow(2,n)) { n++; } n--; bin += pow(10,n) +0.5; x = pow(2,n) + 0.5; num = (num % x); if(num==1) { bin+=1; break; } } printf("%d", bin); return 0; }
C
#define PAGO "pago" #define ANULACION "anulacion" #define PRERRESERVA "pre_reserva" #define EVENTO "evento" #define GRADA "grada" #define X 2 #define K 5 #define N 7 #define MAX_TIME 10 #define LOW_LOAD 1 #define MED_LOAD 2 #define HIGH_LOAD 3 #define LIMIT_LOAD 4 int contPagos = 0, contAnulaciones = 0, contPrerreservas = 0, contEventos = 0, contGradas = 0; void admin(struct task_struct *tsk) { //Comprobar si los contadores son accesibles desde el otro metodo al estar definidos fuera de admin() switch(get_sys_load(contPagos, contAnulaciones, contPrerreservas, contEventos, contGradas)) { case LOW_LOAD: add_to_queue(tsk); break; case MED_LOAD: add_to_queue(tsk); break; case HIGH_LOAD: if (strcmp(tsk->comm, PAGO) == 0) { add_to_queue(tsk); } else { kill_process(tsk); } break; case LIMIT_LOAD: if (strcmp(tsk->comm, PAGO) == 0) { replace_process(tsk); } else { kill_process(tsk); } break; } } //Cierre admin int get_sys_load (int contPagos, int contAnulaciones, int contPrerreservas, int contEventos, int contGradas) { int num_procesos = contPagos + contAnulaciones + contPrerreservas + contEventos + contGradas; if ( num_procesos <= X) { return LOW_LOAD; } else if (num_procesos <= K) { return MED_LOAD; } else if (num_procesos <= N) { return HIGH_LOAD; } else { return LIMIT_LOAD; } } //Cierre get_sys_load void add_to_queue(struct task_struct *tsk){ char tipo = tsk->comm; struct sched_param prioridad; if (strcmp(tipo, PAGO) == 0) { prioridad.sched_priority = 85; sched_setscheduler(tsk, SCHED_FIFO, &prioridad); } else if (strcmp(tipo, ANULACION) == 0) { prioridad.sched_priority = 80; sched_setscheduler(tsk, SCHED_FIFO, &prioridad); } else if (strcmp(tipo, PRERRESERVA) == 0) { prioridad.sched_priority = 75; sched_setscheduler(tsk, SCHED_FIFO, &prioridad); } else if (strcmp(tipo, EVENTO) == 0) { prioridad.sched_priority = 70; sched_setscheduler(tsk, SCHED_FIFO, &prioridad); } else if (strcmp(tipo, GRADA) == 0) { prioridad.sched_priority = 65; sched_setscheduler(tsk, SCHED_FIFO, &prioridad); } else { // ¿Darle una prioridad más baja si es otro tipo? } // Si le vamos a cambiar la prioridad a todos los procesos (incluso los que no son del proyecto) //se le asigna en el último else y podemos poner aquí el sched_setscheduler //sched_setscheduler(tsk, SCHED_FIFO, &prioridad); } //Cierre add_to_queue void kill_process(struct task_struct *tsk) { // Así es como lo queríamos hacer nosotros, no recuerdo exactamente la solución que nos habían dado //ellos. kill_pid(find_vpid(proceso->pid), SIGKILL, 1); } //Cierre kill_process int replace_process(struct task_struct *tsk) { struct task_struct *task_buc; // Estructura para el bucle int prio_param = 65; // Valor inicial de la prioridad a buscar int prio_pro = 0; // Prioridad del proceso a consultar if (prio_param < 85) { for_each_process(task_buc) { prio_pro = task_buc->sched_priority; if (prio_pro == prio_param) { kill_process(task_buc); add_to_queue(tsk); return 0; } } //Cierre for_each_process prio_param += 5; } return -1; //Si no reemplazamos nada devolvemos un -1 } //Cierre replace_process
C
#include "../../inc/so_long.h" void put_pixel(t_img *data, int x, int y, int color) { char *dst; dst = data->addr + (y * data->line_len + x * (data->bits_per_pixel / 8)); *(unsigned int *)dst = color; }
C
#include <stdio.h> int main(void) { int i, score[5]; score[0]=65; score[1]=55; score[2]=43; score[3]=77; score[4]=100; for(i=0;i<=4;i++) printf("score[%d]=%d\n",i,score[i]); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "lista.h" LISTA *cria() { LISTA *lista = (LISTA*)malloc(sizeof(LISTA)); if(lista == NULL) return NULL; lista->inicio = NULL; lista->fim = NULL; lista->tam = 0; return lista; } int vazia(LISTA *plista) { return (plista == NULL || plista->inicio == NULL); } void imprimeFila(LISTA *lista) { if(lista == NULL || lista->inicio == NULL) return; NO *paux = lista->inicio; while(paux!= NULL) { printf("%d ", paux->valorVertice); paux = paux->prox; } } int inserirInicio(LISTA *lista, int valorVertice) { if(lista == NULL) return 0; NO *pno = (NO*)malloc(sizeof(NO)); if(pno == NULL) return 0; pno->valorVertice = valorVertice; pno->prox = lista->inicio; lista->inicio = pno; (lista->tam)++; if(lista->fim == NULL)//vazia lista->fim = pno; return 1; } void esvazia(LISTA **lista) //libera memoria { if(vazia(*lista)) { free(*lista); (*lista) = NULL; return; } NO *prem = (*lista)->inicio; (*lista)->inicio = (*lista)->inicio->prox; free(prem); prem = NULL; esvazia(lista); }
C
#include "../../includes/minishell.h" void display_array(char **array) { int i; i = 0; while (DEBUG && array && array[i]) { printf("(%s)\n", array[i]); i++; } } int check_occurence(char *str, char c) { int i; i = 0; while (*str) { if (*str == c) i++; str++; } return (i); } size_t get_word_len(char *word, int i) { int j; j = 0; while (word[i]) { if (ft_isspace(word[i]) || word[i] == '$' || word[i] == '\\' || word[i] == '\"') return (j); i++; j++; } return (j); } void join_if_needed(t_ptoken *array, int *i, int *size, t_list *lst) { if (DEBUG) printf("JE SUIS LA\ntrans[%d]\n", g_shell.trans); if ((((t_token *)lst->content)->type == 10 || ((t_token *)lst->content)->type == 4 || ((t_token *)lst->content)->type == 6) && g_shell.trans) { join_no_space(array, i, size); (array + *i)->is_escaped = true; g_shell.trans = 0; } else if (((t_token *)lst->content)->type == 10) ; else if (((t_token *)lst->content)->type == 4 && get_token_at(((t_token *)lst->content)->id - 1)->type == 3) { (array + *i)->need_join = true; (array + *i)->is_escaped = true; } else join_no_space(array, i, size); }
C
/*********************************************************************************/ /* Course: Advanced Programming for Physics (2020-2021) */ /*********************************************************************************/ /* Program to compute the Fibonacci numbers using a linked list. */ /* */ /* Compile the code: */ /* $ gcc -Wall -Wextra linked_serial.c -o linked_serial */ /* */ /* Run the code: */ /* $ time ./linked_serial */ /* */ /* Author: David Goz - david.goz@inaf.it */ /* */ /* History: Originally written by Tim Mattson, September 2011. */ /* Modified for the purpose of the course by David Goz. */ /* */ /* Assigned tasks: */ /* - OpenMP parallelization: */ /* - parallelize the code targeting the while loop that */ /* processes the linked list. */ /* DO NOT use omp task to solve the problem. */ /*********************************************************************************/ #include <stdlib.h> #include <stdio.h> #define N 5 /* number of elements in the linked list */ #define FS 38 /* input payload for the linked list */ typedef struct node { int data; int fibdata; struct node* next; } node; /* recursive function */ int fib(const int n) { if (n < 2) return (n); else { int x = fib(n - 1); int y = fib(n - 2); return (x + y); } } void processwork(node* p) { p->fibdata = fib(p->data); } node * init_list(node *p) { /* head of the linked list */ node *head = NULL; if (!(head = (node *)malloc(sizeof(node)))) { printf("\n\t Cannot allocate head of the linked list ... aborting ... \n\n"); exit(EXIT_FAILURE); } /* set p to head */ p = head; p->data = FS; /* create the linked list */ node *tmp = NULL; for (int i=0 ; i<N ; i++) { if ((tmp = (node *)malloc(sizeof(node))) == NULL) { printf("\n\t Cannot allocate element of the linked list ... aborting ... \n\n"); exit(EXIT_FAILURE); } /* link p to the next element */ p->next = tmp; /* move p to the next element */ p = tmp; /* set the payload */ p->data = (FS + i + 1); } /* loop over the linked list */ /* end the linked list */ p->next = NULL; /* return the head of the linked list */ return head; } int main() { printf("\n\t Create the linked list"); /* create the linked list */ node *head = NULL, *p = NULL; head = init_list(p); printf("\n\t Each node will compute %d Fibonacci numbers beginning with %d\n\n", N, FS); /* process the linked list */ p = head; while (p) { processwork(p); p = p->next; } /* print the result and free memory */ p = head; while (p) { printf("\t %d : %d\n",p->data, p->fibdata); node *tmp = p->next; free(p); p = tmp; } free (p); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <locale.h> #include <wchar.h> #include <wctype.h> enum { L_bit = 8, l_bit = 4, W_bit = 2, w_bit = 1, BUF_SIZE = 100 }; struct Elem { int data; struct Elem *next; }; struct List { struct Elem *pHead; struct Elem *pTail; }; // Make up a list struct List * MakeList(void) { struct List *a = calloc (1, sizeof(struct List)); a->pHead = NULL; return a; } // Character to pointer translator wchar_t *chtostr (wchar_t x) { wchar_t *p = calloc (2, sizeof (wchar_t)); p[0] = x; p[1] = '\0'; return p; } // Add to list void addToList(int data, struct List *a) { struct Elem *temp = calloc(1, sizeof(struct Elem)); struct Elem *cnt; if (a->pHead == NULL) { a->pHead = temp; temp->data = data; temp->next = NULL; a->pTail = temp; } else { if (a->pHead->data < data) { temp->data = data; temp->next = a->pHead; a->pHead = temp; } else if (a->pHead->data > data) { cnt = a->pHead; while (cnt->next && (cnt->next->data > data)) { cnt = cnt->next; } if (!(cnt->next)) { a->pTail->next = temp; temp->data = data; temp->next = NULL; a->pTail = temp; } else if (cnt->next->data < data) { temp->next = cnt->next; cnt->next = temp; temp->data = data; } } } } struct node { struct node *right; struct node *left; wchar_t *data; int quantity; short height; }; // Free up tree void free_tree (struct node * tree) { if (tree != NULL) { free_tree (tree->left); free_tree (tree->right); free (tree); } } // Free up element void free_elem (struct Elem * x) { if (x != NULL) { free_elem (x->next); free (x); } } // Free up list void free_list (struct List a) { free_elem(a.pHead); } // Get tree height char height(struct node *p) { if (p) { return p->height; } else { return 0; } } // Get balance factor int BF (struct node *p) { return height(p->right)-height(p->left); } // Fix height void OverHeight(struct node *p) { char hleft = height(p->left); char hright = height(p->right); p->height = (hleft > hright ? hleft : hright) + 1; } // Rotate right around x struct node* RightRotation(struct node *x) { struct node *y = x->left; x->left = y->right; y->right = x; OverHeight(x); OverHeight(y); return y; } // Rotate left around y struct node *LeftRotation(struct node *y) { struct node *x = y->right; y->right = x->left; x->left = y; OverHeight(y); OverHeight(x); return x; } // Balance the tree struct node *Balance(struct node *x) { OverHeight(x); if (BF(x) == 2) { if (BF(x->right) < 0) { x->right = RightRotation(x->right); } return LeftRotation(x); } if (BF(x) == -2) { if (BF(x->left) > 0) { x->left = LeftRotation(x->left); } return RightRotation(x); } return x; } // Insert a new node to tree struct node *Insert(struct node *x, wchar_t *k) { if (!x) { struct node *y = calloc(1,sizeof(struct node)); y->data = k; y->quantity = 1; y->height = 1; y->left = y->right = NULL; return y; } int f = wcscmp(k,x->data); if (f < 0) { x->left = Insert(x->left, k); } else if (f == 0) { x->quantity ++; } else { x->right = Insert(x->right, k); } return Balance(x); } // Print the tree void print_tree (struct node* root, FILE *f) { if (root) { print_tree(root->left,f); fwprintf(f, L"%ls - %d\n",root->data, root->quantity); print_tree(root->right,f); } } // Create a list by quantities of tree nodes void Init_List (struct node* root, struct List *head) { if (root) { Init_List(root->left,head); addToList(root->quantity,head); Init_List(root->right,head); } } // Print all the nodes of tree with quantity equal to q by lexics void Go_Through (struct node* root, int q, FILE *f) { if (root) { Go_Through(root->left,q,f); if (root->quantity == q) { fwprintf(f,L"%ls - %d\n", root->data, q); } Go_Through(root->right,q,f); } } // Print the tree by quantities void Print_On_Q (struct node* root, struct List *a, FILE *f) { struct Elem *pTemp = a->pHead; while (pTemp != NULL) { Go_Through(root,pTemp->data,f); pTemp = pTemp->next; } } // Check if the command lie arguments are correct int correct (int flags) { return (!((( (flags & L_bit) > 0) && ( (flags & l_bit) > 0)) || (( (flags & W_bit) > 0) && ( (flags & w_bit) > 0)))); } /* In flags bytes corresponding to lay as foolows: LlWw, 1 if exists, 0 if doesn't. For example if we met lWL we'll try to write 14 = 1110 in binary. As it is innapropriate for our programm we'll check it with correct(int) function. */ FILE * flags (int argc, char *argv[], int * flags) { int out = 0; FILE *fout; int i = 1; for (; i < argc; i++) { if (argv[i][0] == '-') { int l = strlen(argv[i]); for (int j = 1; j < l; j++) { if (argv[i][j] == 'o') { fout = fopen(argv[i + 1],"w"); if (!fout) { fprintf(stderr,"Error opening output file.\n"); return NULL; } } else if (argv[i][j] == 'L') { out = out | L_bit; } else if (argv[i][j] == 'l') { out = out | l_bit; } else if (argv[i][j] == 'W') { out = out | W_bit; } else if (argv[i][j] == 'w') { out = out | w_bit; } } } } if (!correct(out)) { fprintf(stderr,"Error with programm flags.\n"); return NULL; } (*flags) = out; return fout; } int out_loc (int argc, char *argv[]) { int out = 0, f = 0, o, i, j; for (i = 1; i < argc; i++) { if (argv[i][0] == '-') { for (j = 1; j < strlen(argv[i]); j++) { if (argv[i][j] == 'o') { f = 1; out ++; o = i + 1; } } if (f) { f = 0; if (i == argc - 1) return 0; if (argv[i + 1][0] == '-') return 0; } } } if (out != 1) return 0; return o; } int in_loc (int argc, char *argv[], int out_loc) { int input = 0, f = 0, in, i; for (i = 1; i < argc; i++) { if ((argv[i][0] != '-') && (i != out_loc)) { input++; in = i; } } if (input != 1) return 0; return in; } int legal (char x) { return ((x == 'l') || (x == 'L') || (x == 'w') || (x == 'W') || (x == 'o')); } int legal_flags (int argc, char *argv[]) { int i, j; for (i = 1; i < argc; i++) { if (argv[i][0] == '-') { for (j = 1; j < strlen(argv[i]); j++) { if (!legal(argv[i][j])) { return 0; } } } } return 1; } int main (int argc, char *argv[]) { int out,in, flag = 0, i; FILE *fin, *fout; wint_t x; wchar_t c; struct List a,b; struct node *STree = NULL, *CTree = NULL; wchar_t *buf; if ((out = out_loc(argc,argv)) == 0) { fprintf(stderr,"Error with flags for output.\n"); exit(1); } if ((in = in_loc(argc,argv,out)) == 0) { fprintf(stderr,"Error with input tags in command line.\n"); exit(1); } fin = fopen(argv[in],"r"); if ((legal_flags(argc,argv)) == 0) { fprintf(stderr,"Error with flags in command line: some of them are not L,l,W,w,o.\n"); exit(1); } setlocale(LC_ALL, ""); if (!fin) { fprintf(stderr,"Error opening input file.\n"); exit(1); } fout = flags(argc,argv,&flag); if (!fout) { exit(1); } if (!flag) { flag = 5; fwprintf(fout,L"Printing by default (by lexics):\n"); } else { fwprintf(fout,L"Result:\n"); } a.pHead = NULL; b.pHead = NULL; buf = calloc (BUF_SIZE, sizeof(wchar_t)); i = 0; while ((x = fgetwc(fin)) != EOF) { if (!isspace(x)) { if (iswupper(x)) { x = towlower(x); } c = (wchar_t) x; if ((flag & (L_bit | l_bit)) > 0) { CTree = Insert(CTree,chtostr(c)); } if ((flag & (W_bit | w_bit)) > 0) { if (iswalpha(x)) { buf[i] = c; i++; } else if (i > 0) { i++; buf[i] = '\0'; buf = realloc(buf, (i + 1) * sizeof(wchar_t)); STree = Insert(STree,buf); buf = calloc (BUF_SIZE, sizeof(wchar_t)); i = 0; } } } else if (((flag & (W_bit | w_bit)) > 0) && i) { i++; buf[i] = '\0'; buf = realloc(buf, (i + 1) * sizeof(wchar_t)); STree = Insert(STree,buf); buf = calloc (BUF_SIZE, sizeof(wchar_t *)); i = 0; } } if (((flag & (W_bit | w_bit)) > 0) && i) { i++; buf[i] = '\0'; buf = realloc(buf, (i + 1) * sizeof(wchar_t)); STree = Insert(STree,buf); } if ((flag & w_bit) == w_bit) { fwprintf(fout,L"\nWords by alphabetic order:\n\n"); print_tree(STree,fout); } if ((flag & l_bit) == l_bit) { fwprintf(fout,L"\nCharacters by alphabetic order:\n\n"); print_tree(CTree,fout); } if ((flag & W_bit) == W_bit) { fwprintf(fout,L"\nWords by quantity:\n\n"); Init_List(STree,&b); Print_On_Q (STree,&b,fout); } if ((flag & L_bit) == L_bit) { fwprintf(fout,L"\nCharacters by quantity:\n\n"); Init_List(CTree,&a); Print_On_Q (CTree,&a,fout); } if ((flag & (W_bit | w_bit)) > 0) free_list(a); if ((flag & (L_bit | l_bit)) > 0) free_list(b); if ((flag & (W_bit | w_bit)) > 0) free_tree(STree); if ((flag & (L_bit | l_bit)) > 0) free_tree(CTree); return 0; }
C
/*һ numsҳڳ˻С k ĸ ʾ 1: : nums = [10,5,2,6], k = 100 : 8 : 8˻С100ֱΪ: [10], [5], [2], [6], [10,5], [5,2], [2,6], [5,2,6] Ҫע [10,5,2] dz˻С100顣 ˵: 0 < nums.length <= 50000 0 < nums[i] < 1000 0 <= k < 10^6 */ #include <stdio.h> #include <stdlib.h> #define N 50000 int Search(int data[],int n,int k); main() { int n,i,k; int data[N]; printf("Please input array's length:"); scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&data[i]); printf("Please input k:"); scanf("%d",&k); printf("ĸ %d\t",Search(data,n,k)); } int Search(int data[],int n,int k) { int count=0,sum=1,i,j; for(j=0;j<n;j++) { for(i=j,sum=1;i<n;i++) { sum*=data[i]; if(sum<k) count++; else break; } } return count; }
C
// 정수 X에 사용할 수 있는 연산은 다음과 같이 세 가지 이다. // 1. X가 3으로 나누어 떨어지면, 3으로 나눈다. // 2. X가 2로 나누어 떨어지면, 2로 나눈다. // 3. 1을 뺀다. // 정수 N이 주어졌을 때, 위와 같은 연산 세 개를 적절히 사용해서 1을 만들려고 한다. 연산을 사용하는 횟수의 최솟값을 출력하시오. #include <stdio.h> #include <stdlib.h> int main(void){ int N; scanf("%d", &N); int* array; array = (int*)malloc(sizeof(int)*(N+1)); array[1] = 0; array[2] = 1; array[3] = 1; for(int i = 4; i <= N; i++){ array[i] = 1 + array[i-1]; if (i % 2 == 0) { int tmp = 1 + array[i/2]; if (tmp < array[i]) array[i] = tmp; } if (i % 3 == 0) { int tmp = 1 + array[i/3]; if (tmp < array[i]) array[i] = tmp; } } printf("%d\n", array[N]); free(array); return 0; }
C
#include <stdio.h> int print(int *array,int size) { int i; for(i=0;i<size;i++) printf("%d ",*(array+i)); printf("\n"); } void merge(int *array,int start,int mid,int end) { int i=start,j=mid+1,counter=0; int temp[end-start+1]; while(i<=mid && j<=end) { if(*(array+i)>*(array+j)) { temp[counter]=*(array+j); j++; } else { temp[counter]=*(array+i); i++; } counter++; } while(i<=mid) { temp[counter]=*(array+i); i++; counter++; } while(j<=end) { temp[counter]=*(array+j); j++; counter++; } for(i=0;i<counter;i++) *(array+i+start)=temp[i]; return; } void merge_sort(int *array,int start,int end) { int mid; if(start<end) { mid=(start+end)/2; merge_sort(array,start,mid); merge_sort(array,mid+1,end); merge(array,start,mid,end); } } void findpair(int *array,int start,int end,int sum) { int *p=array,*q=(array+end); while(p<q) { if(*p+*q>sum) { q--; } else if(*p+*q<sum) { p++; } else { printf("(%d,%d) ",*p,*q); p++; } } printf("\n"); } int main() { int arr[]={1,2,4,7,10,11,12,6,16,-4,0,-5,-10,32,-2,18,19},size=sizeof(arr)/sizeof(int); merge_sort(arr,0,size-1); findpair(arr,0,size-1,10); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<memory.h> #include<string.h> //struct rooms_info //{ // int rooms_count; // ROOM room[100]; //}; //typedef struct rooms_info ROOMS; struct stu_info { //default表示没有 char name[20]; //0表示没有 int st_no; //0表示没有 int st_sex; }; typedef struct stu_info STU; struct room_info { int no; //10代表男性,11代表女性 int sex; //已容纳学生数 int count; STU stu[4]; }; typedef struct room_info ROOM; void WriteToFile( ROOM *proom, int num); void ReadFromFile( ROOM *proom, int num); void ShowAllRoom(int num); void ShowRoom(ROOM *proom); int CreateRoom(); void InputStu(int num); void SearchStu(int num); void SearchRoom(int num); void ChangeRoom(int num); void ExchangeRoom(int num); void Quit(int num); int Check(int no, int num); int main() { int cmd; int i,num; char str[20]; FILE *fp2; printf("欢迎来到宿舍管理系统\n"); printf("命令如下:\n"); printf("0:输入宿舍信息 1:全部宿舍 2:输入学生信息并分配宿舍\n"); printf("3:查询学生信息 4:查询寝室信息 5:调换宿舍\n"); printf("6:互换宿舍 7:毕业退寝 8:退出系统\n"); printf("提示信息:男为10,女为11,默认为0\n"); fp2 = fopen("rooms_num.txt", "rt"); fgets(str, 20, fp2); if(str!=NULL) { num=atoi(str); printf("现在共有%d个宿舍\n",num); } else { printf("现在还没有任何宿舍,请先创建宿舍\n"); } fclose(fp2); while(1) { printf("请输入命令:"); scanf("%d",&cmd); switch(cmd) { case 0: num = CreateRoom(); break; case 1: ShowAllRoom(num); break; case 2: InputStu(num) ; break; case 3: SearchStu(num) ; break; case 4: SearchRoom(num) ; break; case 5: ChangeRoom(num) ; break; case 6: ExchangeRoom(num) ; break; case 7: Quit(num); break; case 8: exit(0); break; } } return 0; } //返回0表示此学号不存在,返回1表示已存在 int Check(int no, int num) { int i,j; int found = 0; ROOM *proom; proom = (ROOM *)malloc(num * sizeof(ROOM)); ReadFromFile(proom, num); for(i=0;i<num;i++) { for(j=0;j<4;j++) { if(proom[i].stu[j].st_no == no) { found = 1; break; } } if(found == 1) break; } memset(proom, 0, num*sizeof(ROOM)); free(proom); if(found==1) return 1; else return 0; } void Quit(int num) { int i,j,no; //用以中断循环的判定符 int found = 0; ROOM *proom; //为指针分配内存 proom = (ROOM *)malloc(num * sizeof(ROOM)); //从文件中获得对象 ReadFromFile(proom, num); printf("请输入要退寝的学生学号:"); scanf("%d",&no); for(i=0;i<num;i++) { for(j=0;j<4;j++) { if(proom[i].stu[j].st_no == no) { strcpy(proom[i].stu[j].name, "default"); proom[i].stu[j].st_no = 0; proom[i].stu[j].st_sex = 0; proom[i].count --; found = 1; printf("退寝后您寝室的情况为:\n"); ShowRoom(&proom[i]); break; } } if(found == 1) break; } //重新写入文件 WriteToFile(proom, num); //释放所指向的内存块 memset(proom, 0, num*sizeof(ROOM)); //释放指针 free(proom); printf("***********************************************************\n"); } void ExchangeRoom(int num) { int i,j; ROOM *proom; //两学生的学号,所查到的寝室对应的存储编号,在寝室中位次 int no1, no2, room1, room2, loc1, loc2; int founded = 0; proom = (ROOM *)malloc(num * sizeof(ROOM)); ReadFromFile(proom, num); printf("请输入交换寝室的两个人的学号:"); scanf("%d%d", &no1,&no2); //查找第一个人所在的寝室和学生位置 for(i=0;i<num;i++) { for(j=0;j<4;j++) { if(proom[i].stu[j].st_no==no1) { room1 = i; loc1 = j; founded = 1; break; } } if(founded == 1) break; } //查找第二个人所在的寝室和学生位置,查找前重置founded=0 founded = 0; for(i=0;i<num;i++) { for(j=0;j<4;j++) { if(proom[i].stu[j].st_no==no2) { room2 = i; loc2 = j; founded = 1; break; } } if(founded == 1) break; } if(proom[room1].sex != proom[room2].sex) { printf("交换宿舍失败,两人性别不同!\n"); printf("***********************************************************\n"); memset(proom, 0, num*sizeof(ROOM)); free(proom); return; } //把两宿舍里关于这两个学生信息互换 char name[20]; int st_no,st_sex; strcpy(name, proom[room1].stu[loc1].name); st_no = proom[room1].stu[loc1].st_no; st_sex = proom[room1].stu[loc1].st_sex; strcpy(proom[room1].stu[loc1].name,proom[room2].stu[loc2].name); proom[room1].stu[loc1].st_no = proom[room2].stu[loc2].st_no; proom[room1].stu[loc1].st_sex = proom[room2].stu[loc2].st_sex; strcpy(proom[room2].stu[loc2].name, name); proom[room2].stu[loc2].st_no = st_no; proom[room2].stu[loc2].st_sex = st_sex; printf("交换宿舍成功!\n"); printf("学号为%d的学生的宿舍信息为:\n",no1); ShowRoom(&proom[room1]); printf("学号为%d的学生的宿舍信息为:\n",no2); ShowRoom(&proom[room2]); WriteToFile(proom, num); memset(proom, 0, num*sizeof(ROOM)); free(proom); printf("***********************************************************\n"); } void SearchStu(int num) { int s_no,i,j,k; int found = 0; ROOM *proom; //为指针分配内存空间 proom = (ROOM *)malloc(num * sizeof(ROOM)); //从文件中获得对象数组的首地址赋予指针 ReadFromFile(proom, num); printf("您的学号是:"); scanf("%d",&s_no); for(i=0; i<num; i++) { for(j=0; j<4; j++) { if(proom[i].stu[j].st_no == s_no) { printf("%10s%10s%15s\n","寝室号","男/女寝","已容纳学生"); printf("%10d%10d%15d\n",proom[i].no,proom[i].sex,proom[i].count); printf("舍友信息:\n"); printf("%10s%15s%10s\n","姓名","学号","性别"); for(k=0; k<4; k++) { if(k!=j) { printf("%10s%15d%10d\n",proom[i].stu[k].name, proom[i].stu[k].st_no, proom[i].stu[k].st_sex); } } found = 1; break; } } //如果已找到就不再查找 if(found == 1) break; } //没找到,则提示信息 if(found ==0 ) printf("未查到您所输入的学号对应的学生信息\n"); printf("***********************************************************\n"); free(proom); } void SearchRoom(int num) { int i,j,r_no; ROOM *proom; proom = (ROOM *)malloc(num * sizeof(ROOM)); ReadFromFile(proom, num); printf("您所要查找的宿舍号是:"); scanf("%d",&r_no); for(i=0; i<num; i++) { if(proom[i].no == r_no) { ShowRoom(&proom[i]); break; } } if(i==num) { printf("未查到您所输入的寝室号对应的信息\n"); } printf("***********************************************************\n"); free(proom); } void ChangeRoom(int num) { int i_no,i,j; //记录此学生所在的寝室号,及他是寝室里的第几个学生 int rec_no, rec_rank; //所要加入的寝室号 int choosed; int existed = 0; ROOM *proom; proom = (ROOM *)malloc(num * sizeof(ROOM)); ReadFromFile(proom, num); printf("您的学号是:"); scanf("%d",&i_no); printf("可换入的寝室如下:\n"); for(i=0; i<num; i++) { existed = 0; for(j=0; j<4; j++) { if(proom[i].stu[j].st_no == i_no) { existed = 1; rec_no = i; rec_rank = j; } } if(existed == 0 && proom[i].count<4) { ShowRoom(&proom[i]); } } printf("\n"); printf("请输入您想要加入的寝室号:"); scanf("%d",&choosed); // for(i=0; i<num; i++) { if(proom[i].no == choosed) { if(proom[i].sex != proom[rec_no].sex) { printf("您所要求换入的寝室与您性别不符,换寝失败!\n"); printf("***********************************************************\n"); memset(proom, 0, num*sizeof(ROOM)); free(proom); return; } //寻找可换的空位 for(j=0; j<4; j++) { if(proom[i].stu[j].st_no == 0) { proom[i].stu[j].st_no = proom[rec_no].stu[rec_rank].st_no; proom[i].stu[j].st_sex = proom[rec_no].stu[rec_rank].st_sex; strcpy(proom[i].stu[j].name, (proom[rec_no].stu[rec_rank].name)); proom[i].count++; //把原来的宿舍里的该学生位置置空 proom[rec_no].stu[rec_rank].st_no = 0; proom[rec_no].stu[rec_rank].st_sex = 0; strcpy(proom[rec_no].stu[rec_rank].name,"default"); proom[rec_no].count--; break; } } if(j==4) printf("您选择的寝室已满\n"); break; } } if(i==num) printf("您输入的寝室号有误\n"); else printf("调换宿舍成功\n"); WriteToFile(proom, num); memset(proom, 0, num*sizeof(ROOM)); free(proom); printf("***********************************************************\n"); } void InputStu(int num) { char iname[20]; int ino,isex; int selected,i,j; int full = 0; int succeed = 0; ROOM *proom; //给指针proom分配内存空间 proom = (ROOM *)malloc(num * sizeof(ROOM)); //从room.bat中获取ROOM对象数组首地址于指针proom ReadFromFile(proom, num); printf("您的名字:"); scanf("%s",iname); printf("学号:"); scanf("%d",&ino); if(Check(ino,num)==1) { printf("\n您所输入的学号已存在于系统中,请检查是否输错!\n"); return; } printf("性别(10代表男性,11代表女性):"); scanf("%d",&isex); printf("\n"); printf("所有寝室如下,请选择可加入的寝室加入\n"); //调用此方法展示所有寝室及其学生信息 ShowAllRoom(num); printf("请输入您所选择的寝室号\n"); scanf("%d",&selected); for(i=0; i<num; i++) { //printf("%d\n",proom[i].no); if(proom[i].no == selected) { if(proom[i].sex != isex) { printf("您所要求加入的寝室与您性别不符,加入寝室失败!\n"); printf("***********************************************************\n"); memset(proom, 0, num*sizeof(ROOM)); free(proom); return; } for(j=0; j<4; j++) { if(proom[i].stu[j].st_no == 0) { succeed = 1; strcpy(proom[i].stu[j].name, iname); proom[i].stu[j].st_no = ino; proom[i].stu[j].st_sex = isex; proom[i].count++; break; } } if(j==4) { printf("您选择的寝室已满员!\n"); break; } if(succeed == 1) { printf("加入宿舍成功!\n"); break; } } } if(i==num) printf("不存在您所选择的寝室号对应的寝室\n"); WriteToFile(proom, num); ShowAllRoom(num); memset(proom, 0, num*sizeof(ROOM)); free(proom); printf("\n***********************************************************\n"); } void ShowRoom(ROOM *proom) { int j; printf("%10s%10s%15s\n","寝室号","男/女寝","已容纳学生"); printf("%10d%10d%15d\n",(*proom).no, (*proom).sex, (*proom).count); printf("%10s%15s%10s\n","姓名","学号","性别"); for(j=0; j<4; j++) { printf("%10s%15d%10d\n", (*proom).stu[j].name, (*proom).stu[j].st_no, (*proom).stu[j].st_sex); } } void ShowAllRoom(int num) { int i,j; ROOM *proom; proom = (ROOM *)malloc(num * sizeof(ROOM)); printf("\n"); ReadFromFile(proom, num); //输出宿舍信息 for(i=0; i<num; i++) { printf("%10s%10s%15s\n","寝室号","男/女寝","已容纳学生"); printf("%10d%10d%15d\n",proom[i].no,proom[i].sex,proom[i].count); printf("%10s%15s%10s\n","姓名","学号","性别"); for(j=0; j<4; j++) { printf("%10s%15d%10d\n",proom[i].stu[j].name, proom[i].stu[j].st_no, proom[i].stu[j].st_sex); } } printf("***********************************************************\n"); free(proom); } int CreateRoom() { FILE *fp2; int i,j,no,sex,num; char out[20]; printf("\n请输入宿舍个数:"); scanf("%d",&num); fp2 = fopen("rooms_num.txt", "w"); itoa(num, out, 10); fputs(out, fp2); fclose(fp2); ROOM *proom; proom = (ROOM *)malloc(num * sizeof(ROOM)); if(proom == NULL) { printf("\n内存空间不够"); return; } else { for(i=0; i<num; i++) { printf("\n第%d个:",i+1); printf("\n请输入宿舍号:"); scanf("%d",&proom[i].no); printf("请输入宿舍性别:(10代表男性,11代表女性)"); scanf("%d",&proom[i].sex); proom[i].count=0; for(j=0; j<4; j++) { strcpy(proom[i].stu[j].name,"default"); proom[i].stu[j].st_no = 0; proom[i].stu[j].st_sex = 0; } } WriteToFile(proom, num); memset(proom, 0, num*sizeof(ROOM)); free(proom); printf("\n***********************************************************\n"); return num; } } //将proom所指向的宿舍信息写到文件room.dat中 void WriteToFile(ROOM *proom, int num) { FILE *fp; fp = fopen("room.dat", "wb"); if(fp==NULL) { printf("无法创建room.dat\n"); free(proom); exit(0); } fwrite(proom, sizeof(ROOM), num, fp); fclose(fp); } //从文件room.dat中读取宿舍信息到proom所指向的内存块中 void ReadFromFile(ROOM *proom, int num) { FILE *fp; fp = fopen("room.dat", "rb"); if(fp==NULL) { printf("无法打开room.dat\n"); free(proom); exit(0); } fread(proom, sizeof(ROOM), num, fp); fclose(fp); }
C
/* ʱ䣺2018/6/19 2204 ߣ¥Ȼ Ŀ ʽ һиһ N 100 N Уÿа - ĸʽһ 4 ѡT ʾȷѡF ʾѡѡÿոָ ʽ һ wifi 롣 8 A-T B-F C-F D-F C-T B-F A-F D-F A-F D-F C-F B-T B-T A-F C-F D-F B-F D-T A-F C-F A-T C-F B-F D-F D-T B-F C-F A-F C-T A-F B-F D-F 13224143 */ #include <stdio.h> int pan_duan(char n){ if (n == 'A') return 1; else if (n == 'B') return 2; else if (n == 'C') return 3; else if (n == 'D') return 4; } int main(void) { int N; scanf("%d",&N); int i,j; char ans[8]; int res[N]; for(i=0 ; i<N ; i++) { scanf(" %c-%c %c-%c %c-%c %c-%c",&ans[0],&ans[1],&ans[2],&ans[3],&ans[4],&ans[5],&ans[6],&ans[7]); //һ%cǰҪпո for(j=1 ; j<8 ; j+=2) { if(ans[j] == 'T') res[i] = pan_duan(ans[j-1]); } } for (j=0 ; j<N; j++) printf("%d",res[j]); printf("\n"); return 0; }
C
#include <stdio.h> int main(void){ int n, t; ①("何段=>"); scanf("%d", &n); t = n ② + 3 * n; printf("必要な本数は=>%d\n", t ); return 0; }
C
#include <stdio.h> int get_val(const char* linep, size_t start_idx, size_t end_idx, int lo, int hi, char up_char, char dn_char) { int val = -1; int div = -1; char c; for (int i = start_idx; i < end_idx; ++i) { c = linep[i]; div = (hi - lo + 1) / 2; if (c == dn_char) { hi = hi - div; } else if (c == up_char) { lo = lo + div; } } if (linep[end_idx] == dn_char) { val = lo; } else if (linep[end_idx] == up_char) { val = hi; } return val; } int get_id(const char* linep) { int row = get_val(linep, 0, 6, 0, 127, 'B', 'F'); int col = get_val(linep, 7, 9, 0, 7, 'R', 'L'); return row * 8 + col; } int main() { FILE* f; f = fopen("data/day5.dat", "r"); char line[16]; int maxid = 0; int seatid; int seats[861] = {0}; while (fscanf(f, "%s", line) == 1) { seatid = get_id(line); seats[seatid] = 1; if (seatid > maxid) { maxid = seatid; } } for (int i = 0; i < 861; ++i) { if (seats[i] != 1) { printf("%d ", i); } } printf("%d\n", maxid); fclose(f); return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct stat {int /*<<< orphan*/ st_mode; } ; /* Variables and functions */ scalar_t__ S_ISREG (int /*<<< orphan*/ ) ; int /*<<< orphan*/ bcopy (char const*,char*,int) ; char** emptyextlist ; int /*<<< orphan*/ free (char*) ; char* malloc (int) ; scalar_t__ stat (char*,struct stat*) ; int /*<<< orphan*/ strcpy (char*,char*) ; int strlen (char const*) ; __attribute__((used)) static char * file_lookup(const char *path, const char *name, int namelen, char **extlist) { struct stat st; char *result, *cp, **cpp; int pathlen, extlen, len; pathlen = strlen(path); extlen = 0; if (extlist == NULL) extlist = emptyextlist; for (cpp = extlist; *cpp; cpp++) { len = strlen(*cpp); if (len > extlen) extlen = len; } result = malloc(pathlen + namelen + extlen + 2); if (result == NULL) return (NULL); bcopy(path, result, pathlen); if (pathlen > 0 && result[pathlen - 1] != '/') result[pathlen++] = '/'; cp = result + pathlen; bcopy(name, cp, namelen); cp += namelen; for (cpp = extlist; *cpp; cpp++) { strcpy(cp, *cpp); if (stat(result, &st) == 0 && S_ISREG(st.st_mode)) return result; } free(result); return NULL; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstmap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tzaaboul <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/07 14:55:44 by tzaaboul #+# #+# */ /* Updated: 2016/11/09 14:16:42 by tzaaboul ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" t_list *ft_lstmap(t_list *lst, t_list *(*f)(t_list *elem)) { t_list *begin_list; t_list *new; if (!lst || !f) return (NULL); if ((begin_list = ft_lstnew(lst->content, lst->content_size)) == NULL) return (NULL); begin_list = f(begin_list); new = begin_list; lst = lst->next; while (lst) { if ((new->next = ft_lstnew(lst->content, lst->content_size)) == NULL) return (NULL); new->next = f(new->next); new = new->next; lst = lst->next; } return (begin_list); }
C
//文件名: topology/topology.c // //描述: 这个文件实现一些用于解析拓扑文件的辅助函数 // //创建日期: 2015年 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/ioctl.h> //#include <net/if.h> #include <linux/if.h> #include "../son/neighbortable.h" #include "topology.h" #include "../common/constants.h" #include "../common/debug.h" static int NodeNum = 0; static int TopoNum = 0; static NodeInfo_t *NodeArray = NULL; static TopoInfo_t *TopoArray = NULL; char Local_IP[32]; // 仅仅用于统计结点个数 struct IpList{ struct in_addr ip; struct IpList *next; }; static struct IpList * IpListHead = NULL; static int IpListNum = 0; int IpList_Init(){ IpListHead = malloc(sizeof(struct IpList)); if (IpListHead == NULL){ Assert(0, "[SON IpList] Malloc Wrong."); } IpListHead->ip.s_addr = 0; IpListHead->next = NULL; IpListNum = 0; return 0; } int IpList_Insert(struct in_addr ip){ struct IpList *cur = malloc(sizeof(struct IpList)); if (cur == NULL){ Assert(0, "[SON IpList] Malloc Wrong."); } cur->ip = ip; cur->next = IpListHead; IpListHead = cur; ++IpListNum; return 0; } int IpList_Find(struct in_addr ip){ struct IpList *cur = IpListHead; while(cur != NULL){ if (cur->ip.s_addr == ip.s_addr && cur->ip.s_addr != 0){ return 1; } cur = cur->next; } if (cur == NULL) return 0; return 0; } int IpList_GetNum(){ return IpListNum; } int IpList_Free(){ struct IpList *cur = IpListHead; struct IpList *ptr = IpListHead; for(cur = ptr; cur != NULL;){ ptr = ptr->next; free(cur); cur = ptr; } return 0; } static void get_local_ip(){ char * ip; int sockfd, interface; struct ifreq buf[INET_ADDRSTRLEN]; struct ifconf ifc; sockfd = socket(AF_INET, SOCK_DGRAM, 0); if(sockfd == -1){ perror("socket error"); exit(1); } ifc.ifc_len = sizeof(buf); ifc.ifc_buf = (void *)buf; if(!ioctl(sockfd, SIOCGIFCONF, (char *)&ifc)){ interface = ifc.ifc_len/sizeof(struct ifreq); while (interface > 0){ --interface; if (!(ioctl(sockfd, SIOCGIFADDR, (char *)&buf[interface]))){ ip = (inet_ntoa(((struct sockaddr_in*)(&buf[interface].ifr_addr))->sin_addr)); printf("local ip:%s\n", ip); } else{ Log("Get local ip error!!!"); exit(1); } } } else{ Log("Get local ip error!!!"); exit(1); } close(sockfd); for(int i = 0; i < ifc.ifc_len/sizeof(struct ifreq); ++i){ ip = (inet_ntoa(((struct sockaddr_in*)(&buf[i].ifr_addr))->sin_addr)); if(strcmp(ip, "127.0.0.1")){ //Local_IP = ip; strcpy(Local_IP, ip); printf("choose ip: %s\n", Local_IP); break; } } return ; } int topology_init(){ FILE *fp = fopen(TopologyDataPath, "r"); if(fp == NULL) Assert(0, "[Topo] Fopen Topo data Error"); char name1[MAXNAMELEN], name2[MAXNAMELEN]; char NodeIP1[20], NodeIP2[20]; unsigned int linkcost; IpList_Init(); //仅仅用于统计结点个数与Topo关系个数 while(fscanf(fp, "%s %s %s %s %u", name1, NodeIP1, name2, NodeIP2, &linkcost) == 5){ ++TopoNum; struct in_addr ip1, ip2; ip1.s_addr = inet_addr(NodeIP1); ip2.s_addr = inet_addr(NodeIP2); if (!IpList_Find(ip1)) IpList_Insert(ip1); if (!IpList_Find(ip2)) IpList_Insert(ip2); } NodeNum = IpList_GetNum(); fseek(fp, 0, 0); NodeArray = (struct NodeInfo *) malloc(sizeof(struct NodeInfo) * NodeNum); TopoArray = (struct TopoInfo *) malloc(sizeof(struct TopoInfo) * TopoNum); int Nodeidx = 0, Topoidx = 0; while(fscanf(fp ,"%s %s %s %s %u", name1, NodeIP1, name2, NodeIP2, &linkcost) == 5){ struct in_addr ip1, ip2; ip1.s_addr = inet_addr(NodeIP1); ip2.s_addr = inet_addr(NodeIP2); // Node 结点插入 int node1_i, node2_i; for(node1_i = 0; node1_i < Nodeidx; ++node1_i){ if(NodeArray[node1_i].addr.s_addr == ip1.s_addr) break; } if(node1_i == Nodeidx){ NodeArray[Nodeidx].addr.s_addr = ip1.s_addr; strcpy(NodeArray[Nodeidx].name, name1); ++Nodeidx; } for(node2_i = 0; node2_i < Nodeidx; ++node2_i){ if(NodeArray[node2_i].addr.s_addr == ip2.s_addr) break; } if(node2_i == Nodeidx){ NodeArray[Nodeidx].addr.s_addr = ip2.s_addr; strcpy(NodeArray[Nodeidx].name, name2); ++Nodeidx; } // Topo结点插入 TopoArray[Topoidx].node1_idx = node1_i; TopoArray[Topoidx].node2_idx = node2_i; TopoArray[Topoidx].linkcost = linkcost; ++Topoidx; } IpList_Free(); fclose(fp); get_local_ip(); printf("MyNode ID: %d\n", topology_getMyNodeID()); return 0; } int topology_stop(){ free(NodeArray); free(TopoArray); return 0; } //这个函数返回指定主机的节点ID. //节点ID是节点IP地址最后8位表示的整数. //例如, 一个节点的IP地址为202.119.32.12, 它的节点ID就是12. //如果不能获取节点ID, 返回-1. int topology_getNodeIDfromname(char* hostname){ for(int i = 0; i < NodeNum; ++i){ if(!strcmp(hostname, NodeArray[i].name)){ return (NodeArray[i].addr.s_addr >> 24) & 0xff; } } return -1; } //这个函数返回指定的IP地址的节点ID. //如果不能获取节点ID, 返回-1. int topology_getNodeIDfromip(struct in_addr* addr){ for(int i = 0; i < NodeNum; ++i){ if(addr->s_addr == NodeArray[i].addr.s_addr){ return (NodeArray[i].addr.s_addr >> 24) & 0xff; } } return -1; } //这个函数返回本机的节点ID //如果不能获取本机的节点ID, 返回-1. int topology_getMyNodeID(){ struct in_addr local; local.s_addr = inet_addr(Local_IP); return (local.s_addr >> 24) & 0xff; } //这个函数解析保存在文件topology.dat中的拓扑信息. //返回邻居数. int topology_getNbrNum(){ struct in_addr local; local.s_addr = inet_addr(Local_IP); int cnt = 0; for(int i = 0; i < TopoNum; ++i){ if( NodeArray[TopoArray[i].node1_idx].addr.s_addr == local.s_addr || NodeArray[TopoArray[i].node2_idx].addr.s_addr == local.s_addr){ ++cnt; } } return cnt; } int topology_getNbrNumWithBiggerID(){ int cnt = 0; struct in_addr local; local.s_addr = inet_addr(Local_IP); for(int i = 0; i < TopoNum; ++i){ if(NodeArray[TopoArray[i].node1_idx].addr.s_addr == local.s_addr && ((local.s_addr >> 24) & 0xff) < ((NodeArray[TopoArray[i].node2_idx].addr.s_addr >> 24 ) & 0xff) ){ ++cnt; } else if (NodeArray[TopoArray[i].node2_idx].addr.s_addr == local.s_addr && ((local.s_addr >> 24) & 0xff) < ((NodeArray[TopoArray[i].node1_idx].addr.s_addr >> 24 ) & 0xff) ){ ++cnt; } } return cnt; } //这个函数解析保存在文件topology.dat中的拓扑信息. //返回重叠网络中的总节点数. int topology_getNodeNum(){ return NodeNum; } //这个函数解析保存在文件topology.dat中的拓扑信息. //返回一个动态分配的数组, 它包含重叠网络中所有节点的ID. int* topology_getNodeArray(){ int *IdArray = (int *) malloc(sizeof(int) * NodeNum); for(int i = 0; i < NodeNum; ++i){ IdArray[i] = (NodeArray[i].addr.s_addr >> 24) & 0xff; } return IdArray; } //这个函数解析保存在文件topology.dat中的拓扑信息. //返回一个动态分配的数组, 它包含所有邻居的节点ID. int* topology_getNbrArray(){ struct in_addr local; local.s_addr = inet_addr(Local_IP); int ididx = 0; int *IdArray = (int *) malloc(sizeof(int) * topology_getNbrNum()); for(int i = 0; i < TopoNum; ++i){ if(NodeArray[TopoArray[i].node1_idx].addr.s_addr == local.s_addr){ IdArray[ididx] = (NodeArray[TopoArray[i].node2_idx].addr.s_addr >> 24) & 0xff; ++ididx; } else if (NodeArray[TopoArray[i].node2_idx].addr.s_addr == local.s_addr){ IdArray[ididx] = (NodeArray[TopoArray[i].node1_idx].addr.s_addr >> 24) & 0xff; ++ididx; } } return IdArray; } //这个函数解析保存在文件topology.dat中的拓扑信息. //返回指定两个节点之间的直接链路代价. //如果指定两个节点之间没有直接链路, 返回INFINITE_COST. unsigned int topology_getCost(int fromNodeID, int toNodeID){ for(int i = 0; i < TopoNum; ++i){ if( ( ((NodeArray[TopoArray[i].node1_idx].addr.s_addr >> 24) & 0xff) == fromNodeID && ((NodeArray[TopoArray[i].node2_idx].addr.s_addr >> 24) & 0xff) == toNodeID) || ( ((NodeArray[TopoArray[i].node1_idx].addr.s_addr >> 24) & 0xff) == toNodeID && ((NodeArray[TopoArray[i].node2_idx].addr.s_addr >> 24) & 0xff) == fromNodeID) ) return TopoArray[i].linkcost; } return INFINITE_COST; } struct neighborentry *topology_getNbrEntry(){ struct in_addr local; local.s_addr = inet_addr(Local_IP); int ididx = 0; nbr_entry_t *NbrArray = (nbr_entry_t *) malloc(sizeof(struct neighborentry) * topology_getNbrNum()); for(int i = 0; i < TopoNum; ++i){ if(NodeArray[TopoArray[i].node1_idx].addr.s_addr == local.s_addr){ NbrArray[ididx].nodeID = (NodeArray[TopoArray[i].node2_idx].addr.s_addr >> 24) & 0xff; NbrArray[ididx].nodeIP = NodeArray[TopoArray[i].node2_idx].addr.s_addr; NbrArray[ididx].conn = -1; NbrArray[ididx].state = SON_CLOSED; ++ididx; } else if (NodeArray[TopoArray[i].node2_idx].addr.s_addr == local.s_addr){ NbrArray[ididx].nodeID = (NodeArray[TopoArray[i].node1_idx].addr.s_addr >> 24) & 0xff; NbrArray[ididx].nodeIP = NodeArray[TopoArray[i].node1_idx].addr.s_addr; NbrArray[ididx].conn = -1; NbrArray[ididx].state = SON_CLOSED; ++ididx; } } return NbrArray; }
C
#include "ush.h" static char** init_bg_color_reg() { char** bg_color_reg = malloc(9 * sizeof(char *)); bg_color_reg[0] = "black"; bg_color_reg[1] = "red"; bg_color_reg[2] = "green"; bg_color_reg[3] = "yellow"; bg_color_reg[4] = "blue"; bg_color_reg[5] = "purple"; bg_color_reg[6] = "cyan"; bg_color_reg[7] = "white"; bg_color_reg[8] = NULL; return bg_color_reg; } static char** init_bg_color_reg_high() { char** bg_color_high = malloc(9 * sizeof(char *)); bg_color_high[0] = "high_black"; bg_color_high[1] = "high_red"; bg_color_high[2] = "high_green"; bg_color_high[3] = "high_yellow"; bg_color_high[4] = "high_blue"; bg_color_high[5] = "high_purple"; bg_color_high[6] = "high_cyan"; bg_color_high[7] = "high_white"; bg_color_high[8] = NULL; return bg_color_high; } static char** init_bg_color_bold() { char** bg_color_bold = malloc(9 * sizeof(char *)); bg_color_bold[0] = "bold_black"; bg_color_bold[1] = "bold_red"; bg_color_bold[2] = "bold_green"; bg_color_bold[3] = "bold_yellow"; bg_color_bold[4] = "bold_blue"; bg_color_bold[5] = "bold_purple"; bg_color_bold[6] = "bold_cyan"; bg_color_bold[7] = "bold_white"; bg_color_bold[8] = NULL; return bg_color_bold; } static char** init_bg_color_high_inten() { char** bg_color_inten = malloc(9 * sizeof(char *)); bg_color_inten[0] = "intensive_black"; bg_color_inten[1] = "intensive_red"; bg_color_inten[2] = "intensive_green"; bg_color_inten[3] = "intensive_yellow"; bg_color_inten[4] = "intensive_blue"; bg_color_inten[5] = "intensive_purple"; bg_color_inten[6] = "intensive_cyan"; bg_color_inten[7] = "intensive_white"; bg_color_inten[8] = NULL; return bg_color_inten; } void mx_init_color_bg(t_shell *shell) { shell->bg_color_reg = init_bg_color_reg(); shell->bg_color_high = init_bg_color_reg_high(); shell->bg_color_bold = init_bg_color_bold(); shell->bg_color_inten = init_bg_color_high_inten(); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> void mergeSort(int *vetor, int posicaoInicio, int posicaoFim) { int i, j, k, metadeTamanho, *vetorTemp; if(posicaoInicio == posicaoFim) return; // ordenacao recursiva das duas metades metadeTamanho = (posicaoInicio + posicaoFim ) / 2; mergeSort(vetor, posicaoInicio, metadeTamanho); mergeSort(vetor, metadeTamanho + 1, posicaoFim); // intercalacao no vetor temporario t i = posicaoInicio; j = metadeTamanho + 1; k = 0; vetorTemp = (int *) malloc(sizeof(int) * (posicaoFim - posicaoInicio + 1)); while(i < metadeTamanho + 1 || j < posicaoFim + 1) { if (i == metadeTamanho + 1 ) { // i passou do final da primeira metade, pegar v[j] vetorTemp[k] = vetor[j]; j++; k++; } else { if (j == posicaoFim + 1) { // j passou do final da segunda metade, pegar v[i] vetorTemp[k] = vetor[i]; i++; k++; } else { if (vetor[i] < vetor[j]) { vetorTemp[k] = vetor[i]; i++; k++; } else { vetorTemp[k] = vetor[j]; j++; k++; } } } } // copia vetor intercalado para o vetor original for(i = posicaoInicio; i <= posicaoFim; i++) { vetor[i] = vetorTemp[i - posicaoInicio]; } free(vetorTemp); } int main(){ int A[6] = {5, 3, 6, 2, 64, 6}; clock_t ini = clock(); mergeSort(A, 1, 6); clock_t fim = clock(); double tempo_exec = (double)(fim - ini) / CLOCKS_PER_SEC; printf("\n%f segundos\n", tempo_exec * 1000000); return 0; }
C
#include "client_type.h" void check_list(struct clients_t **clients) { if (*clients == NULL) { *clients = (struct clients_t*) malloc(sizeof(struct clients_t)); (*clients)->num_clients = 0; (*clients)->client = NULL; } } void add_client(struct clients_t **clients, int fd) { check_list(clients); struct client_t *new_client = (struct client_t*) malloc(sizeof(struct client_t)); memset(new_client->handle, 0, HANDLE_MAX_LENGTH); new_client->fd = fd; new_client->next = NULL; if ((*clients)->client == NULL) { (*clients)->client = new_client; } else { struct client_t *temp = (*clients)->client; while (temp->next != NULL) { temp = temp->next; } temp->next = new_client; } (*clients)->num_clients++; } void add_handle(struct clients_t **clients, int fd, char *handle, uint8_t handle_len) { struct client_t *temp = (*clients)->client; while (temp != NULL) { if (temp->fd == fd) { memcpy(temp->handle, handle, handle_len); break; } temp = temp->next; } } void remove_client(struct clients_t **clients, int fd) { struct client_t *temp = (*clients)->client; if (temp != NULL && fd == temp->fd) { (*clients)->client = temp->next; (*clients)->num_clients--; } else { while (temp != NULL && temp->next != NULL) { if (fd == temp->next->fd) { struct client_t *to_be_erased = temp->next; temp->next = temp->next->next; (*clients)->num_clients--; free(to_be_erased); } temp = temp->next; } } } int get_client(struct clients_t *clients, int index) { if (clients == NULL) { return -1; } else { struct client_t *temp = clients->client; while (index > 0) { temp = temp->next; index = index-1; } return temp->fd; } } void print(struct clients_t *clients) { struct client_t *temp = clients->client; while (temp != NULL) { printf("%d ", temp->fd); temp = temp->next; } printf("\n"); }
C
#include <fun.h> int main() { if(!fork()) { printf("i am child,uid=%d,gid=%d,pgid=%d,sid=%d",getuid(),getgid(),getpgid(),getsid()); }else { exit(0); return 0; } }
C
/** ****************************************************************************** * @file * @author * @version * @date * @brief ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "db.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ LOG_RING_TYPE ringLog; uint32_t logPositionCnt = 0; uint32_t flagNewLog = 1; /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** * @brief * @param * @param * @retval */ void DB_InitLog(void) { uint8_t u8temp; int32_t i; LOG_RING_TYPE logTemp; ringLog.head = 0; ringLog.tail = 0; ringLog.crc = 0; logPositionCnt = 0; if(sizeof(MSG_STATUS_RECORD) % LOG_WRITE_BYTES) while(1); // Khai bao lai kieu bien for(i = 4095 - sizeof(LOG_RING_TYPE); i >= 0; i -= sizeof(LOG_RING_TYPE)) { SST25_Read(LOG_POSITION_ADDR + i,(uint8_t *)&logTemp, sizeof(LOG_RING_TYPE)); if(logTemp.head != 0xffffffff) { u8temp = DbCalcCheckSum((uint8_t *)&logTemp,sizeof(LOG_RING_TYPE) - 1); if(logPositionCnt == 0) logPositionCnt = i; if(logTemp.crc == u8temp) { ringLog = logTemp; break; } } } } void DB_RingLogReset(void) { ringLog.head = 0; ringLog.tail = 0; DB_RingLogSave(); } void DB_RingLogSave(void) { // calc new crc ringLog.crc = DbCalcCheckSum((uint8_t *)&ringLog,sizeof(LOG_RING_TYPE) - 1); // write HEAD SST25_Write(LOG_POSITION_ADDR + logPositionCnt,(uint8_t *)&ringLog.head,sizeof(ringLog.head)); // increase cnt to save RINGLOG TAIL logPositionCnt += sizeof(ringLog.head); // write TAIL SST25_Write(LOG_POSITION_ADDR + logPositionCnt ,(uint8_t *)&ringLog.tail,sizeof(ringLog.tail)); // increase cnt to save CRC logPositionCnt += sizeof(ringLog.tail); // write CRC SST25_Write(LOG_POSITION_ADDR + logPositionCnt ,(uint8_t *)&ringLog.crc,sizeof(ringLog.crc)); // increase cnt for next time logPositionCnt += sizeof(ringLog.crc); // if outof sector size => reset all RING LOG if(logPositionCnt >= 4095) { SST25_Erase(LOG_POSITION_ADDR, block4k); logPositionCnt = 0; } } uint32_t DB_LogFill(void) { if(ringLog.head >= ringLog.tail) { return (ringLog.head - ringLog.tail); } else { return(LOG_DATA_SIZE_MAX / sizeof(MSG_STATUS_RECORD) - ringLog.tail + ringLog.head); } } int8_t DB_LoadLog(MSG_STATUS_RECORD *log) { uint8_t u8temp; if(ringLog.tail == ringLog.head) return 0xff; // no log // read data from flash SST25_Read(LOG_DATABASE_ADDR + ringLog.tail*sizeof(MSG_STATUS_RECORD), (uint8_t *)log, sizeof(MSG_STATUS_RECORD)); // calc checksum u8temp = DbCalcCheckSum((uint8_t *)log,sizeof(MSG_STATUS_RECORD) - 1); // increase ring log tail ringLog.tail++; if(ringLog.tail >= LOG_DATA_SIZE_MAX / sizeof(MSG_STATUS_RECORD)) // overflow, reset tail ringLog.tail = 0; // save ring log DB_RingLogSave(); if(log->crc == u8temp) // valid data { return 0; } else { return 0xff; } } int8_t DB_SaveLog(MSG_STATUS_RECORD *log) { uint32_t u32temp,tailSector = 0, headSector = 0, headSectorOld = 0, i; tailSector = ringLog.tail * sizeof(MSG_STATUS_RECORD) / SECTOR_SIZE; headSectorOld = ringLog.head * sizeof(MSG_STATUS_RECORD) / SECTOR_SIZE; u32temp = ringLog.head; u32temp++; if(u32temp >= (LOG_DATA_SIZE_MAX / sizeof(MSG_STATUS_RECORD))) { u32temp = 0; } headSector = u32temp * sizeof(MSG_STATUS_RECORD) / SECTOR_SIZE; if(headSector != headSectorOld) { SST25_Erase(LOG_DATABASE_ADDR + headSector * SECTOR_SIZE,block4k); } if((headSector == tailSector) && (u32temp <= ringLog.tail)) { tailSector++; ringLog.tail = tailSector * SECTOR_SIZE / sizeof(MSG_STATUS_RECORD); if((tailSector * SECTOR_SIZE) % sizeof(MSG_STATUS_RECORD)) ringLog.tail++; if(ringLog.tail >= LOG_DATA_SIZE_MAX / sizeof(MSG_STATUS_RECORD)) ringLog.tail = 0; } log->crc = DbCalcCheckSum((uint8_t *)log,sizeof(MSG_STATUS_RECORD) - 1); for(i = 0;i < sizeof(MSG_STATUS_RECORD);i += LOG_WRITE_BYTES) { SST25_Write(LOG_DATABASE_ADDR + ringLog.head*sizeof(MSG_STATUS_RECORD) + i,(uint8_t *)log + i,LOG_WRITE_BYTES); } ringLog.head = u32temp; DB_RingLogSave(); return 0; } uint8_t DbCalcCheckSum(uint8_t *buff, uint32_t length) { uint32_t i; uint8_t crc = 0; for(i = 0;i < length; i++) { crc += buff[i]; } return crc; } /******************* (C) COPYRIGHT 2015 UFOTech *****END OF FILE****/
C
# include <pthread.h> # include <iostream> # include <unistd.h> class a_thread { pthread_t main_thread; int a_number; static void * stat_fnc (void * arg) { a_thread * c = static_cast<a_thread *>(arg); cout << "Entering into " << arg << " number " << c->a_number << endl << flush; sleep(10); cout << "Exiting from " << arg << endl << flush; } public: a_thread(int n) : a_number(n) { // empty } go() { pthread_create(&main_thread, NULL, stat_fnc, this); } wait() { void ** result; pthread_join(main_thread, result); } }; int main() { a_thread thr_1(10), thr_2(20); thr_1.go(); sleep(5); thr_2.go(); thr_1.wait(); thr_2.wait(); }
C
/* ============================================================================ Name : VARIABLES.c Author : QUINO B. JEFFRY Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <conio.h> #include <stdint.h> /*integer types-> int8_t int16_t int32_t uint8_t uint16_t uint32_t*/ /*variables globales*/ //el uint8_t reemplaza-> unsigned char uint8_t age = 10; /*tipo identificador valorInicial*/ char ch = 'c'; /*representacion de un caracter*/ char *str = "ANSI C"; /*forma de declarar una cadena*/ int main(void) { /*variables locales*/ float pi = 3.141592; /*en punto flotante se usa el punto para separar el punto decimal*/ printf("********PRIMER PROGRAMA EN C*****\n\n"); printf("mi edad es->%d\n",age); printf("el valor de pi->%.3f\n",pi);/*Como se puede observar estoy haciendo uso de cuantos decimales quiero que se muestren y uso el indentificador 'f' el cual indica que es un numero flotante*/ printf("esto es una letra->%c\n",ch); printf("esto es un texto->%s\n",str); getch(); return 0; }
C
#include <stdio.h> #include <stdbool.h> #define NODE 8 #define TRUE 1 #define FALSE 0 void unionParent(int * arr, int a, int b); int getParent(int * arr, int min); bool findUnion(int * arr, int a, int b); int main(void) { int arr[11]; int i; for(i=1; i<=10; i++) { arr[i] = i; } unionParent(arr, 1, 2); unionParent(arr, 2, 3); unionParent(arr, 3, 4); unionParent(arr, 5, 6); unionParent(arr, 6, 7); unionParent(arr, 7, 8); /* for(i=1; i<=10; i++) { printf("%d ", arr[i]); } printf("\n"); */ printf("1-5 ? %d\n", findUnion(arr, 1, 5)); unionParent(arr, 1, 5); printf("1-5 ? %d\n", findUnion(arr, 1, 5)); return 0; } void unionParent(int * arr, int a, int b) { int i; int min = (arr[a] <= arr[b]) ? arr[a] : arr[b]; int max = (arr[a] <= arr[b]) ? arr[b] : arr[a]; if(!findUnion(arr, a, b)) { for(i=1; i<=NODE; i++) { if(arr[i] == max) { arr[i] = min; } } } for(i=1; i<=10; i++) { printf("%d ", arr[i]); } printf("\n"); } int getParent(int * arr, int min) { int p = min; while(p != arr[p]) { p = arr[p]; } return p; } bool findUnion(int * arr, int a, int b) { if(arr[a] == arr[b]) return TRUE; else return FALSE; }
C
#include<stdio.h> #include<unistd.h> #include<stdlib.h> int main(){ printf("******* %d\n", getpid()); pid_t pid = fork(); if(pid < 0){ printf("fork error\n"); return -1; } else if(pid == 0){ printf("child %d\n", getpid()); //这段代码只有子进程能够运行到, 因为在子进程中fork的返回值=0 sleep(5); exit(0); } else{ //只有父进程才能运行到 printf("parent %d\n", getpid()); } while(1){ printf("hello world\n"); sleep(1); } return 0; }
C
/* shell sort testings */ int *shellSizes = (int*)malloc(NBR_OF_TESTS * sizeof(int)); int **shellArrays = (int**)malloc(NBR_OF_TESTS * sizeof(int*)); for(i = 0; i < NBR_OF_TESTS; i++){ shellSizes[i] = arrayofsizes[i]; shellArrays[i] = (int*)malloc(arrayofsizes[i] * sizeof(int)); for(j = 0; j < arrayofsizes[i]; j++){ shellArrays[i][j] = arrayofarrays[i][j]; } } fp = fopen("shellOut.txt", "w+"); for(i = 0; i < NBR_OF_TESTS; i++){ gettimeofday(&start, 0); shellSort(shellArrays[i], shellSizes[i]); gettimeofday(&stop, 0); fprintf(fp, "%d %d\n", shellSizes[i], (stop.tv_usec - start.tv_usec)); } fclose(fp);
C
#include<stdio.h> int main() { int a=10,b=10; printf("a<<2=%d",a<<2); printf("b>>2=%d",b>>2); // left shift: // shifting the bits on to the left side // and assigning 0's to the right return 0; }
C
/* ============================================================================ Name : strRemove.c Author : Shivam Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #define SIZE 20 int main(void) { int i,k; char name[SIZE]; char key; int len; printf("\nEnter the String:"); scanf("%s",&name); len=strlen(name); printf("\nEnter Key"); getchar(); scanf("%c",&key); for(i=0;i<len;i++) { if(name[i]==key) { for(k=i;k<len;k++) { name[k]=name[k+1]; }len--; i--; } } printf("\nString becomes %s",name); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <dlfcn.h> #include <stdlib.h> int main(void) { // path could be absolute path---relative paths trigger normal // library searching. void *handler = dlopen("libfoo.so", RTLD_LAZY); if (!handler) { fprintf(stderr,"%s\n", dlerror()); exit(EXIT_FAILURE); } // get access to a function in library // int = return value of the function // *fn = pointer to a function named fn // () = comma separated list of arguments to function. Example: (int *, char c) int (*one) () = dlsym(handler,"one"); char *error; if ((error = dlerror()) != NULL) /* checking error through dlerror() */ { fprintf(stderr,"%s\n", error); exit(EXIT_FAILURE); } int (*two) () = dlsym(handler,"two"); if ((error = dlerror()) != NULL) /* checking error through dlerror() */ { fprintf(stderr,"%s\n", error); exit(EXIT_FAILURE); } // call the function // Older way to call a pointer to a function: (*one)(); // The more familiar way: one(); two(); // close the handler dlclose(handler); return EXIT_SUCCESS; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef scalar_t__ uint32 ; typedef scalar_t__ Oid ; /* Variables and functions */ scalar_t__ INVALID_COLOCATION_ID ; scalar_t__ TableColocationId (scalar_t__) ; bool TablesColocated(Oid leftDistributedTableId, Oid rightDistributedTableId) { uint32 leftColocationId = INVALID_COLOCATION_ID; uint32 rightColocationId = INVALID_COLOCATION_ID; if (leftDistributedTableId == rightDistributedTableId) { return true; } leftColocationId = TableColocationId(leftDistributedTableId); rightColocationId = TableColocationId(rightDistributedTableId); if (leftColocationId == INVALID_COLOCATION_ID || rightColocationId == INVALID_COLOCATION_ID) { return false; } return leftColocationId == rightColocationId; }
C
#ifndef INTERMEDIATE_CODE_H #define INTERMEDIATE_CODE_H #include <string.h> /* Estructura de una cuadrupla. */ // op - Operacion que se va a realizar. // arg1 - Argumento 1. // arg2 - Argumento 2. // res - Donde se va a almacenar el resultado. typedef struct _quad{ char* op; char* arg1; char* arg2; char* res; } quad; /* Estructura de la tabla de cuadruplas. */ // items - Lista de cuadruplas almacenadas. // i - Total de cuadruplas guardadas. typedef struct _intermediate_code{ quad* items; int i; } intermediate_code; typedef struct _label{ int* items; int i; } label; /* Tabla que usara el compilador para guardar las cuadruplas. */ intermediate_code CODE; // Funciones: void init_code(); int gen_code(char *op , char *arg1, char *arg2, char *res); label create_list(int l); label merge(label l1, label l2); void backpatch(label l, int inst); void print_code(); #endif
C
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2023, Intel Corporation */ /* * obj_persist_count.c -- counting number of persists */ #define _GNU_SOURCE #include "obj.h" #include "pmalloc.h" #include "unittest.h" struct ops_counter { unsigned n_cl_stores; unsigned n_drain; unsigned n_pmem_persist; unsigned n_pmem_msync; unsigned n_pmem_flush; unsigned n_pmem_drain; unsigned n_flush_from_pmem_memcpy; unsigned n_flush_from_pmem_memset; unsigned n_drain_from_pmem_memcpy; unsigned n_drain_from_pmem_memset; unsigned n_pot_cache_misses; }; static struct ops_counter ops_counter; static struct ops_counter tx_counter; #define FLUSH_ALIGN ((uintptr_t)64) #define MOVNT_THRESHOLD 256 static unsigned cl_flushed(const void *addr, size_t len, uintptr_t alignment) { uintptr_t start = (uintptr_t)addr & ~(alignment - 1); uintptr_t end = ((uintptr_t)addr + len + alignment - 1) & ~(alignment - 1); return (unsigned)(end - start) / FLUSH_ALIGN; } #define PMEM_F_MEM_MOVNT (PMEM_F_MEM_WC | PMEM_F_MEM_NONTEMPORAL) #define PMEM_F_MEM_MOV (PMEM_F_MEM_WB | PMEM_F_MEM_TEMPORAL) static unsigned bulk_cl_changed(const void *addr, size_t len, unsigned flags) { uintptr_t start = (uintptr_t)addr & ~(FLUSH_ALIGN - 1); uintptr_t end = ((uintptr_t)addr + len + FLUSH_ALIGN - 1) & ~(FLUSH_ALIGN - 1); unsigned cl_changed = (unsigned)(end - start) / FLUSH_ALIGN; int wc; /* write combining */ if (flags & PMEM_F_MEM_NOFLUSH) wc = 0; /* NOFLUSH always uses temporal instructions */ else if (flags & PMEM_F_MEM_MOVNT) wc = 1; else if (flags & PMEM_F_MEM_MOV) wc = 0; else if (len < MOVNT_THRESHOLD) wc = 0; else wc = 1; /* count number of potential cache misses */ if (!wc) { /* * When we don't use write combining, it means all * cache lines may be missing. */ ops_counter.n_pot_cache_misses += cl_changed; } else { /* * When we use write combining there won't be any cache misses, * with an exception of unaligned beginning or end. */ if (start != (uintptr_t)addr) ops_counter.n_pot_cache_misses++; if (end != ((uintptr_t)addr + len) && start + FLUSH_ALIGN != end) ops_counter.n_pot_cache_misses++; } return cl_changed; } static void flush_cl(const void *addr, size_t len) { unsigned flushed = cl_flushed(addr, len, FLUSH_ALIGN); ops_counter.n_cl_stores += flushed; ops_counter.n_pot_cache_misses += flushed; } static void flush_msync(const void *addr, size_t len) { unsigned flushed = cl_flushed(addr, len, Pagesize); ops_counter.n_cl_stores += flushed; ops_counter.n_pot_cache_misses += flushed; } FUNC_MOCK(pmem_persist, void, const void *addr, size_t len) FUNC_MOCK_RUN_DEFAULT { ops_counter.n_pmem_persist++; flush_cl(addr, len); ops_counter.n_drain++; _FUNC_REAL(pmem_persist)(addr, len); } FUNC_MOCK_END FUNC_MOCK(pmem_msync, int, const void *addr, size_t len) FUNC_MOCK_RUN_DEFAULT { ops_counter.n_pmem_msync++; flush_msync(addr, len); ops_counter.n_drain++; return _FUNC_REAL(pmem_msync)(addr, len); } FUNC_MOCK_END FUNC_MOCK(pmem_flush, void, const void *addr, size_t len) FUNC_MOCK_RUN_DEFAULT { ops_counter.n_pmem_flush++; flush_cl(addr, len); _FUNC_REAL(pmem_flush)(addr, len); } FUNC_MOCK_END FUNC_MOCK(pmem_drain, void, void) FUNC_MOCK_RUN_DEFAULT { ops_counter.n_pmem_drain++; ops_counter.n_drain++; _FUNC_REAL(pmem_drain)(); } FUNC_MOCK_END static void memcpy_nodrain_count(void *dest, const void *src, size_t len, unsigned flags) { unsigned cl_stores = bulk_cl_changed(dest, len, flags); if (!(flags & PMEM_F_MEM_NOFLUSH)) ops_counter.n_flush_from_pmem_memcpy += cl_stores; ops_counter.n_cl_stores += cl_stores; } static void memcpy_persist_count(void *dest, const void *src, size_t len, unsigned flags) { memcpy_nodrain_count(dest, src, len, flags); ops_counter.n_drain_from_pmem_memcpy++; ops_counter.n_drain++; } FUNC_MOCK(pmem_memcpy_persist, void *, void *dest, const void *src, size_t len) FUNC_MOCK_RUN_DEFAULT { memcpy_persist_count(dest, src, len, 0); return _FUNC_REAL(pmem_memcpy_persist)(dest, src, len); } FUNC_MOCK_END FUNC_MOCK(pmem_memcpy_nodrain, void *, void *dest, const void *src, size_t len) FUNC_MOCK_RUN_DEFAULT { memcpy_nodrain_count(dest, src, len, 0); return _FUNC_REAL(pmem_memcpy_nodrain)(dest, src, len); } FUNC_MOCK_END static unsigned sanitize_flags(unsigned flags) { if (flags & PMEM_F_MEM_NOFLUSH) { /* NOFLUSH implies NODRAIN */ flags |= PMEM_F_MEM_NODRAIN; } return flags; } FUNC_MOCK(pmem_memcpy, void *, void *dest, const void *src, size_t len, unsigned flags) FUNC_MOCK_RUN_DEFAULT { flags = sanitize_flags(flags); if (flags & PMEM_F_MEM_NODRAIN) memcpy_nodrain_count(dest, src, len, flags); else memcpy_persist_count(dest, src, len, flags); return _FUNC_REAL(pmem_memcpy)(dest, src, len, flags); } FUNC_MOCK_END FUNC_MOCK(pmem_memmove_persist, void *, void *dest, const void *src, size_t len) FUNC_MOCK_RUN_DEFAULT { memcpy_persist_count(dest, src, len, 0); return _FUNC_REAL(pmem_memmove_persist)(dest, src, len); } FUNC_MOCK_END FUNC_MOCK(pmem_memmove_nodrain, void *, void *dest, const void *src, size_t len) FUNC_MOCK_RUN_DEFAULT { memcpy_nodrain_count(dest, src, len, 0); return _FUNC_REAL(pmem_memmove_nodrain)(dest, src, len); } FUNC_MOCK_END FUNC_MOCK(pmem_memmove, void *, void *dest, const void *src, size_t len, unsigned flags) FUNC_MOCK_RUN_DEFAULT { flags = sanitize_flags(flags); if (flags & PMEM_F_MEM_NODRAIN) memcpy_nodrain_count(dest, src, len, flags); else memcpy_persist_count(dest, src, len, flags); return _FUNC_REAL(pmem_memmove)(dest, src, len, flags); } FUNC_MOCK_END static void memset_nodrain_count(void *dest, size_t len, unsigned flags) { unsigned cl_set = bulk_cl_changed(dest, len, flags); if (!(flags & PMEM_F_MEM_NOFLUSH)) ops_counter.n_flush_from_pmem_memset += cl_set; ops_counter.n_cl_stores += cl_set; } static void memset_persist_count(void *dest, size_t len, unsigned flags) { memset_nodrain_count(dest, len, flags); ops_counter.n_drain_from_pmem_memset++; ops_counter.n_drain++; } FUNC_MOCK(pmem_memset_persist, void *, void *dest, int c, size_t len) FUNC_MOCK_RUN_DEFAULT { memset_persist_count(dest, len, 0); return _FUNC_REAL(pmem_memset_persist)(dest, c, len); } FUNC_MOCK_END FUNC_MOCK(pmem_memset_nodrain, void *, void *dest, int c, size_t len) FUNC_MOCK_RUN_DEFAULT { memset_nodrain_count(dest, len, 0); return _FUNC_REAL(pmem_memset_nodrain)(dest, c, len); } FUNC_MOCK_END FUNC_MOCK(pmem_memset, void *, void *dest, int c, size_t len, unsigned flags) FUNC_MOCK_RUN_DEFAULT { flags = sanitize_flags(flags); if (flags & PMEM_F_MEM_NODRAIN) memset_nodrain_count(dest, len, flags); else memset_persist_count(dest, len, flags); return _FUNC_REAL(pmem_memset)(dest, c, len, flags); } FUNC_MOCK_END /* * reset_counters -- zero all counters */ static void reset_counters(void) { memset(&ops_counter, 0, sizeof(ops_counter)); } /* * print_reset_counters -- print and then zero all counters */ static void print_reset_counters(const char *task, unsigned tx) { #define CNT(name) (ops_counter.name - tx * tx_counter.name) UT_OUT( "%-14s %-7d %-10d %-12d %-10d %-10d %-10d %-15d %-17d %-15d %-17d %-23d", task, CNT(n_cl_stores), CNT(n_drain), CNT(n_pmem_persist), CNT(n_pmem_msync), CNT(n_pmem_flush), CNT(n_pmem_drain), CNT(n_flush_from_pmem_memcpy), CNT(n_drain_from_pmem_memcpy), CNT(n_flush_from_pmem_memset), CNT(n_drain_from_pmem_memset), CNT(n_pot_cache_misses)); #undef CNT reset_counters(); } #define LARGE_SNAPSHOT ((1 << 10) * 10) struct foo_large { uint8_t snapshot[LARGE_SNAPSHOT]; }; struct foo { int val; uint64_t dest; PMEMoid bar; PMEMoid bar2; }; int main(int argc, char *argv[]) { START(argc, argv, "obj_persist_count"); if (argc != 2) UT_FATAL("usage: %s file-name", argv[0]); const char *path = argv[1]; PMEMobjpool *pop; if ((pop = pmemobj_create(path, "persist_count", PMEMOBJ_MIN_POOL, S_IWUSR | S_IRUSR)) == NULL) UT_FATAL("!pmemobj_create: %s", path); UT_OUT( "%-14s %-7s %-10s %-12s %-10s %-10s %-10s %-15s %-17s %-15s %-17s %-23s", "task", "cl(all)", "drain(all)", "pmem_persist", "pmem_msync", "pmem_flush", "pmem_drain", "pmem_memcpy_cls", "pmem_memcpy_drain", "pmem_memset_cls", "pmem_memset_drain", "potential_cache_misses"); print_reset_counters("pool_create", 0); /* allocate one structure to create a run */ pmemobj_alloc(pop, NULL, sizeof(struct foo), 0, NULL, NULL); reset_counters(); PMEMoid root = pmemobj_root(pop, sizeof(struct foo)); UT_ASSERT(!OID_IS_NULL(root)); print_reset_counters("root_alloc", 0); PMEMoid oid; int ret = pmemobj_alloc(pop, &oid, sizeof(struct foo), 0, NULL, NULL); UT_ASSERTeq(ret, 0); print_reset_counters("atomic_alloc", 0); pmemobj_free(&oid); print_reset_counters("atomic_free", 0); struct foo *f = pmemobj_direct(root); TX_BEGIN(pop) { } TX_END memcpy(&tx_counter, &ops_counter, sizeof(ops_counter)); print_reset_counters("tx_begin_end", 0); TX_BEGIN(pop) { f->bar = pmemobj_tx_alloc(sizeof(struct foo), 0); UT_ASSERT(!OID_IS_NULL(f->bar)); } TX_END print_reset_counters("tx_alloc", 1); TX_BEGIN(pop) { f->bar2 = pmemobj_tx_alloc(sizeof(struct foo), 0); UT_ASSERT(!OID_IS_NULL(f->bar2)); } TX_END print_reset_counters("tx_alloc_next", 1); TX_BEGIN(pop) { pmemobj_tx_free(f->bar); } TX_END print_reset_counters("tx_free", 1); TX_BEGIN(pop) { pmemobj_tx_free(f->bar2); } TX_END print_reset_counters("tx_free_next", 1); TX_BEGIN(pop) { pmemobj_tx_xadd_range_direct(&f->val, sizeof(f->val), POBJ_XADD_NO_FLUSH); } TX_END print_reset_counters("tx_add", 1); TX_BEGIN(pop) { pmemobj_tx_xadd_range_direct(&f->val, sizeof(f->val), POBJ_XADD_NO_FLUSH); } TX_END print_reset_counters("tx_add_next", 1); PMEMoid large_foo; pmemobj_zalloc(pop, &large_foo, sizeof(struct foo_large), 0); UT_ASSERT(!OID_IS_NULL(large_foo)); reset_counters(); struct foo_large *flarge = pmemobj_direct(large_foo); TX_BEGIN(pop) { pmemobj_tx_xadd_range_direct(&flarge->snapshot, sizeof(flarge->snapshot), POBJ_XADD_NO_FLUSH); } TX_END print_reset_counters("tx_add_large", 1); TX_BEGIN(pop) { pmemobj_tx_xadd_range_direct(&flarge->snapshot, sizeof(flarge->snapshot), POBJ_XADD_NO_FLUSH); } TX_END print_reset_counters("tx_add_lnext", 1); pmalloc(pop, &f->dest, sizeof(f->val), 0, 0); print_reset_counters("pmalloc", 0); pfree(pop, &f->dest); print_reset_counters("pfree", 0); uint64_t stack_var; pmalloc(pop, &stack_var, sizeof(f->val), 0, 0); print_reset_counters("pmalloc_stack", 0); pfree(pop, &stack_var); print_reset_counters("pfree_stack", 0); pmemobj_close(pop); DONE(NULL); }
C
#include <stdio.h> #include <omp.h> extern void do_something_else(int); extern void go_for_it(int); int main() { omp_lock_t lck1, lck2; int id; omp_init_lock(&lck1); omp_init_lock(&lck2); #pragma omp parallel shared(lcki, lck2) private(id) { id = omp_get_thread_num() ; omp_set_lock(&lck1); printf("thread %d has the lock \n", id); printf("thread %d ready to release the lock \n", id); omp_unset_lock(&lck1); while (! omp_test_lock(&lck2)) { do_something_else(id); // do something useful while waiting for the lock } go_for_it(id); // Thread has the lock omp_unset_lock(&lck2); } omp_destroy_lock(&lck1); omp_destroy_lock(&lck2); }
C
#include "binary_trees.h" /** * binary_tree_is_full - checks if a binary tree is full(both branchs are busy) * @tree: pointer to the node * Return: 1 if it is full 0 otherwise **/ int binary_tree_is_full(const binary_tree_t *tree) { int tmp1, tmp2; if (!tree) return (0); if (!tree->left && !tree->right) return (1); if ((!tree->left && tree->right) || (!tree->right && tree->left)) return (0); tmp1 = binary_tree_is_full(tree->left); tmp2 = binary_tree_is_full(tree->right); return (tmp1 && tmp2); }
C
/* ** EPITECH PROJECT, 2017 ** my_sfml ** File description: ** Main engine */ /** ** \file my_sfml_engine.h ** \brief Main engine ** ** Main engine and it's functions. */ /** ** \mainpage mysfml engine ** \section engine_sec Engine ** \subsection intro_sec Introduction ** The \ref main_engine is the only engine you should use directly. ** All of the sub engines are run by the main engine. ** \section gameobject_sec Gameobjects ** \subsection intro_sec Introduction ** \ref my_sfml_gameobject are the core of a game. ** They represent all elements in a \ref scene. ** Refer to the \ref main_engine to know how to register one. ** A gameobject consist of a set of one or more \ref my_sfml_component. ** \subsection component_sec Components ** Components are small amount of data that serve for one job. ** Some are already builtin the engine like: ** \ref my_sfml_transform , \ref my_sfml_animation_2d ,\ ** \ref my_sfml_collider_2d , \ref my_sfml_rigidbody_2d , \ref my_sfml_text ,\ ** \ref my_sfml_button [WIP]. ** Other can be created as you need if you respect the norm given by ** \ref my_sfml_component ** \section owner_sec Owner ** This engine was created by Julian Fräbel on top of the CSFML library. ** It was created for the Graphical module of Epitech. */ #ifndef __MY_SFML_ENGINE_H_ #define __MY_SFML_ENGINE_H_ #include "my_sfml_scenes.h" #include <SFML/Graphics.h> /* --------------------------------DEFINE-------------------------------- */ /* ------------------------------END-DEFINE------------------------------ */ /* --------------------------------ENGINE-------------------------------- */ /** ** \struct main_engine ** \brief main engine ** ** Struct representing the main engine, handle the scenes and it's functions. */ struct main_engine { sfRenderWindow *window; /**< Window used by the engine */ sfClock *main_clock; sf_scene_t *current_scene; /**< Current playing scene */ char *next_scene; /**< Next scene name to be loaded */ void *data; /**< The data to give to the next scene */ sf_linked_list_t *scenes; /**< List of existing scenes */ void (*destroy)(struct main_engine *engine);\ /**< destroy the engine. Refer to destroy_engine() */ void (*update)(struct main_engine *engine);\ /**< run all the updaters in current scene. Refer to update_main_engine() */ int (*add_update)(struct main_engine *engine, void *object, \ int (*update)(void *object, int delta_time));\ /**< Register an updater to the current scene. \ Refer to add_update_main_engine() */ int (*remove_update)(struct main_engine *engine, void *object);\ /**< Unregister an updater from the current scene. Refer to remove_update() */ int (*add_gameobject)(struct main_engine *engine, gameobject_t *obj);\ /**< Register a gameobject to the current scene. Refer to add_gameobject() */ int (*remove_gameobject)(struct main_engine *engine, \ gameobject_t *obj); /**< Unregister a gameobject from the current \ scene and destroy it. Best use destroy_gameobject to clean updaters/renderer.\ Refer to remove_gameobject() */ int (*destroy_gameobject)(struct main_engine *engine, \ gameobject_t *obj); /**< Destroy a gameobject by doing some cleaning \ on the updaters/renderer. Refer to destroy_gameobject_main_engine() */ int (*render)(struct main_engine *engine);\ /**< Render the current frame to the window. Refer to render_main_engine() */ int (*add_to_layer)(struct main_engine *engine, int layer, \ void **data);/**< Add data to a render layer. Refer to \ add_to_layer_main_engine() */ int (*remove_from_layers)(struct main_engine *engine, void **object);\ /**< Remove an object added to a layer from all the layers he is in \ refer to remove_from_layers_main_engine()*/ int (*set_layer_type)(struct main_engine *engine, int priority, \ layer_render_type_t new_type); /**< Set the type of the asked layer to \ new_type. Refer to main_engine_set_layer_type() */ int (*load_texture)(struct main_engine *engine, const char *path);\ /**< Load a texture to the current render engine. \ Refer to load_texture_main_engine() */ int (*add_audio)(struct main_engine *engine, \ const char *path, int loop); /**< Add audio to the current audio engine. \ Refer to add_audio_main_engine() */ int (*play)(struct main_engine *engine, const char *id);\ /**< Play an audio track. Refer to play_audio_main_engine() */ int (*stop)(struct main_engine *engine, const char *id);\ /**< Stop an audio track. Refer to stop_audio_main_engine() */ int (*set_volume)(struct main_engine *engine, const char *id, \ double volume); /**< Set volume of a track. Refer to set_audio_main_engine() */ int (*add_scene)(struct main_engine *engine, sf_scene_t *scene);\ /**< Add a scene to the main engine. Refer to add_scene() */ int (*change_scene)(struct main_engine *engine, \ const char *name, void *data); /**< Change the current scene. \ Refer to change_scene() */ int (*add_physic_object)(struct main_engine *engine, \ gameobject_t *object); /**< Add an object to the current physic engine. \ Refer to add_physic_object_main_engine() */ int (*remove_physic_object)(struct main_engine *engine, \ gameobject_t *object); /**< Remove an object from the current physic engine. \ Refer to remove_physic_object_main_engine() */ gameobject_t **(*get_collisions_rect)(\ struct main_engine *engine, sfIntRect rect, int *size_buff, void *ignore);\ /**< Get an array of gameobjects colliding with the given rect. \ Refer to get_collisions_rect_main_engine() */ gameobject_t **(*get_collisions_point)(\ struct main_engine *engine, vector_t point, int *size_buff);\ /**< Get an array of gameobjects colliding with the given point. \ Refer to get_collisions_point_main_engine() */ gameobject_t **(*get_collisions_go)(\ struct main_engine *engine, gameobject_t *obj, int *size_buff);\ /**< Get an array of gameobjects colliding with the given gamobject. \ Refer to get_collisions_go_main_engine() */ gameobject_t *(*get_gameobject)(struct main_engine *engine, \ const char *name); /**< Get a gameobject given it's name. \ Refer to get_gameobject() */ void (*initialize_physic_state)(struct main_engine *engine);\ /**< Initialise a physic state (register updaters). \ Refer to initialize_physic_state() */ sfTexture *(*get_texture)(struct main_engine *engine, const char *id);\ /**< Get a loaded texture given the texture id (path). \ Refer to get_texture_main_engine() */ sfSprite *(*get_sprite)(struct main_engine *engine, const char *id);\ /**< Get an allocated sprite with the correct texture given the texture id. \ Refer to get_sprite() */ sf_scene_t *(*get_scene)(struct main_engine *engine, const char *name);\ /**< Get a scene based on it's name. Refer to get_scene() */ }; typedef struct main_engine sf_engine_t; /** ** \brief Create a new engine ** @param window the window assotiated with this engine ** ** Return the new engine. */ sf_engine_t *create_engine(sfRenderWindow *window); /** ** \brief Destroy the given engine ** @param engine the engine to destroy ** ** Destroy the given engine and handle all the frees. */ void destroy_engine(sf_engine_t *engine); /** ** \brief Add an updater to the current scene ** @param engine the engine to add to ** @param object the object to give to the updater ** @param update the update function of the updater ** ** Add an updater that run update with the given object and the time passed. ** Return 84 in case of an error, 0 otherwise. */ int add_update_main_engine(sf_engine_t * engine, void *object, \ int (*update)(void *object, int time)); /** ** \brief Remove an updater ** @param engine the engine to remove from ** @param object the object to unregister ** ** Remove all the updaters linked to the given object. ** Return 84 in case of an error, 0 otherwise. */ int remove_update(sf_engine_t *engine, void *object); /** ** \brief Run all the updaters of the current scene ** @param engine the engine to update ** @param time the time passed since the last call of update (sfClock_restart) ** ** Run all the updaters of the given engine current loaded scene. */ void update_main_engine(sf_engine_t *engine); /** ** \brief Add gameobject to the current scene ** @param engine the engine to add too ** @param object the object to register ** ** Add the given object to the main engine so that it handle it's destruction. ** Added object allowed also to find them by name. ** Object added will be added to the current scene only but will be destroy\ when the engine will be destroyed careless of the current scene. ** Return 84 in case of an error, 0 otherwise. */ int add_gameobject(sf_engine_t *engine, gameobject_t *object); /** ** \brief Remove an object from the main engine ** @param engine the engine to update ** @param object the gameobject to remove from the engine. ** ** Remove the given object from the engin handeling. ** The given object will be destroyed after beeing removed. ** Return 84 in case of an error, 0 otherwise. */ int remove_gameobject(sf_engine_t *engine, gameobject_t *object); /** ** \brief Destroy an object from the engines ** @param engine the engine to update ** @param object the gameobject to destroy from the engine. ** ** Remove the given object from the engin handeling, will also try \ to destroy all updaters/physics upaters/renderer. ** It will clean base on the components and will remove sprite from \ animation2d/text from sf_text but more specifics componenets like custom \ sprites will not be handeled and need to be removed manually. ** If updaters are created base on variables in a component they need \ to be handeled manually too ** The given object will be destroyed after all cleaning. ** Return 84 in case of an error, 0 otherwise. */ int destroy_gameobject_main_engine(sf_engine_t *engine, gameobject_t *obj); /** ** \brief Render a frame to the engine window ** @param engine the engine to render ** ** Render the current frame of the engine to the engine window. ** Return 84 in case of an error, 0 otherwise. */ int render_main_engine(sf_engine_t *engine); /** ** \brief Add the given data to the render list of the current graphical engine ** @param engine the engine to add to ** @param layer the layer priority, you can use the layer enum for easy priority ** @param data a the adress of the data to add to the render list ** ** Add the given data to the render list, take as data sfSprite or sfText. ** sfText can only be added on the layers that have been marked to render text\ or errors can occure. ** Return 84 in case of an error, 0 otherwise. */ int add_to_layer_main_engine(sf_engine_t *engine, int layer, void **data); /** ** \brief Remove the data to the render list of the current graphical engine ** @param engine the engine to add to ** @param data a the adress of the data to add to the render list ** ** Remove the given data to the render list, take as data sfSprite or sfText. ** Return 84 in case of an error, 0 otherwise. */ int remove_from_layers_main_engine(sf_engine_t *engine, void **data); /** ** \brief Set a layer render type ** @param engine the engine to serach in ** @param priority the searched layer ** @param new_type the new render type of the layer ** ** Function that changed the render type of the requested layer to new_type. ** Return 84 in case of an error, 0 otherwise. */ int main_engine_set_layer_type(sf_engine_t *engine, int priority, \ layer_render_type_t new_type); /** ** \brief Load a texture on the current graphical engine ** @param engine the engine to load to ** ** Render the current frame of the engine to the engine window. ** Return 84 in case of an error, 0 otherwise. */ int load_texture_main_engine(sf_engine_t *engine, const char *path); /** ** \brief Get a loaded texture given it's id ** @param engine the engine to search in ** @param id the texture id (path) ** ** Get a previously loaded texture (with load_texture_main_engine). ** Return NULL in case of an error, the texture asked otherwise. */ sfTexture *get_texture_main_engine(sf_engine_t *engine, const char *id); /** ** \brief Add an audio track to the current audio engine ** @param engine the engine to add to ** @param path the path to the audio engine (will also be it's id) ** @param loop [0,1] should the track loop when finished (for music mainly) ** ** Add the track to the current audio engine. ** Return 84 in case of an error, 0 otherwise. */ int add_audio_main_engine(sf_engine_t *engine, const char *path, int loop); /** ** \brief Play an audio track ** @param engine the engine to search the audio from ** @param id the audio track id (path) ** ** Play the asked track if loaded in the current scene. ** Return 84 in case of an error, 0 otherwise. */ int play_audio_main_engine(sf_engine_t *engine, const char *id); /** ** \brief Stop an audio track ** @param engine the engine to search the audio from ** @param id the audio track id (path) ** ** Stop the asked track from beeing played. ** Return 84 in case of an error, 0 otherwise. */ int stop_audio_main_engine(sf_engine_t *engine, const char *id); /** ** \brief Set the volume for a given audio track ** @param engine the engine to search the audio from ** @param id the audio track id (path) ** @param volume the volume to set the track to ** ** If the current track exist in the curretn scene will set it's volume. ** Return 84 in case of an error, 0 otherwise. */ int set_audio_main_engine(sf_engine_t *engine, const char *id, double volume); /** ** \brief Get a gameobject from the current scene given it's name ** @param engine the engine to seach the object from ** @param name the name of the gameobject ** ** Get the first gameobject in the current scene to match the asked name. ** Return NULL in case of an error, the asked gameobject otherwise. */ gameobject_t *get_gameobject(sf_engine_t *engine, const char *name); /** ** \brief Get a new sprite with the asked texture ** @param engine the engine to search the texture from ** @param id the texture id (path) ** ** Get a newly allocated texture with the requireded texture loaded. ** If the texture wasn't found the sprite will be return with a NULL texture. ** [WIP]Try to load the texture from path if not found. ** Return NULL in case of an error, a sfSprite otherwise. */ sfSprite *get_sprite(sf_engine_t *engine, char const *id); /** ** \brief Add a scene to the main engine ** @param engine the engine to add to ** @param scene the scene to be added ** ** Add a scene to the main engine that can be run. ** Return 84 in case of an error, 0 otherwise. */ int add_scene(sf_engine_t *engine, sf_scene_t *scene); /** ** \brief Get the first scene in the engine to have the given name ** @param engine the engine to search from ** @param name the name of the researched scene ** ** Get the first scene in the engine to have this name. ** Return NULL in case of an error or if scene wasn't found, scene otherwise. */ sf_scene_t *get_scene(sf_engine_t *engine, const char *name); /** ** \brief Change the current scene ** @param engine the engine to search the scene from ** @param name the name of the scene to change to ** @param data the data to transfer to the next scene ** ** Change the current scene of the engine. ** Data can be what you like it will be passed from a scene to an other. ** This function will call the current scene unload() function. ** This function will call the new scene load() function. ** If the new scene does not exist the scene won't change. ** Return 84 in case of an error, 0 otherwise. */ int change_scene(sf_engine_t *engine, const char *name, void *data); /** ** \brief DO NOT USE ** ** do the actual scene changement. */ int update_selected_scene(sf_engine_t *engine); /** ** \brief Add a physic object to the current physic engine ** @param engine the engine to add to ** @param object the gameobject to add to physics update ** ** Add a gameobject to the physic engine so that it's physics component work. ** Will then handle collisions, triggers, gravity... ** The gameobject require a transform, a rigidbody and a collider to be added. ** Return 84 in case of an error, 0 otherwise. */ int add_physic_object_main_engine(sf_engine_t *engine, gameobject_t *object); /** ** \brief Remove a physic object to the current physic engine ** @param engine the engine to remove from ** @param object the gameobject to remove from physics update ** ** Remove a gameobject to the physic engine. ** Will no longer handle collisions, triggers, gravity... ** Return 84 in case of an error, 0 otherwise. */ int remove_physic_object_main_engine(sf_engine_t *engine, gameobject_t *object); /** ** \brief Get all the collisions with a given rect ** @param engine the engine to detect from ** @param rect the rect to search collisions from ** @param size_buff the buffer with the number of collisions detected ** @param ignore a gameobject to ignore in the detection ** ** Get all the gameobject colliding with the given rect. ** Will set *size_buff to the number of collisions found. ** Return NULL in case of an error, an array of gameobjects otherwise. */ gameobject_t **get_collisions_rect_main_engine(sf_engine_t *engine, \ sfIntRect rect, int *size_buff, void *ignore); /** ** \brief Get all the collisions with a given point ** @param engine the engine to detect from ** @param point the point to search collisions from ** @param size_buff the buffer with the number of collisions detected ** ** Get all the gameobject colliding with the given point. ** Will set *size_buff to the number of collisions found. ** Return NULL in case of an error, an array of gameobjects otherwise. */ gameobject_t **get_collisions_point_main_engine(sf_engine_t *engine, \ vector_t point, int *size_buff); /** ** \brief Get all the collisions with a given gameobject ** @param engine the engine to detect from ** @param obj the gameobject to search collisions from ** @param size_buff the buffer with the number of collisions detected ** ** Get all the gameobject colliding with the given gameobject. ** The given gameobject will not be count as colliding with himself. ** Will set *size_buff to the number of collisions found. ** Return NULL in case of an error, an array of gameobjects otherwise. */ gameobject_t **get_collisions_go_main_engine(sf_engine_t *engine, \ gameobject_t *obj, int *size_buff); /** ** \brief Function that initialize physic state ** @param engine the engine to initialize the current scene physics ** ** This function link the physics update from the current scene \ to the main engine updaters. ** You need to run this function only ONCE per scene or the physics of the \ scene will be multiplied each time you run it. ** You still need to rerun this function after a reset_scene() call. */ void initialize_physic_state(sf_engine_t *engine); /* ------------------------------END-ENGINE------------------------------ */ /** ** \brief Render all hitbox from the given engine ** @param engine the engine to render the hitbox from ** ** Render the current scene hitbox to the engine window. ** Function should be called after render_main_engine or the texture will not \ appear on screen as they will be drawn under the scene. ** the hitbox texture should be 1 pixel by 1 pixel and should be found in \ the HITBOX_TEX folder. ** the hitbox texture should have been previously loaded in the current scene. ** SHOULD ONLY BE USED FOR DEBUGING AS IT CAUSES FLICKERING! ** Return 84 in case of an error, 0 otherwise. */ int display_hitbox(sf_engine_t *engine); #endif /* __MY_SFML_ENGINE_H_ */
C
/* ------------------------------------------------------------------------- @file swap_with_pointers.c @date 10/31/16 02:09:39 @author Martin Noblia @email martin.noblia@openmailbox.org @brief @detail Licence: This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License ---------------------------------------------------------------------------*/ #include <stdio.h> #include "utils.h" #include <stdlib.h> void swap_with_pointers(int* ptr_iNum1, int* ptr_iNum2); int main(void) { int n1 = 3; int n2 = 7; printf("number1:%d , number2:%d\n", n1, n2); swap_with_pointers(&n1, &n2); printf("number1:%d , number2:%d\n", n1, n2); return 0; } void swap_with_pointers(int* ptr_iNum1, int* ptr_iNum2){ int temp; temp = *ptr_iNum1; *ptr_iNum1 = *ptr_iNum2; *ptr_iNum2 = temp; }
C
/********************************************** name : key_drv.c function: the led lights when the button press time : 2017/3/12 author : srfdjkk ***********************************************/ #include <linux/module.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/init.h> #include <linux/delay.h> #include <asm/uaccess.h> #include <asm/irq.h> #include <asm/io.h> #include <asm/arch/regs-gpio.h> #include <asm/hardware.h> /**/ #define DEVICE_NAME "key_drv" //豸 volatile unsigned long *gpfcon; volatile unsigned long *gpfdat; volatile unsigned long *gpgcon; volatile unsigned long *gpgdat; /**/ static struct class * key_drv_class; static struct class_device *key_drv_class_dev; // ֯ӲԴṹ /*жϺ*/ static int key_open(struct inode *inode, struct file *file) { *gpfcon &= ~((0x03<<(0*2))|(0x03<<(2*2))); //GPF0,2 Ϊģʽ *gpgcon &= ~(0x03<<(3*2)); //GPG3 Ϊģʽ return 0; } /*3ĵƽ*/ ssize_t key_read(struct file *file, char __user *buf, size_t size, loff_t *ppos) { unsigned char key_vals[3]; int regval; if(size!=sizeof(key_vals)) return -EINVAL; //ȡGPF0 2 ֵ regval = *gpfdat; key_vals[0] = regval &(1<<0)? 1:0; key_vals[1] = regval &(1<<2)? 1:0; //ȡ GPG3 ֵ regval = *gpgdat; key_vals[2] = regval &(1<<3)? 1:0; copy_to_user(buf, key_vals, sizeof(key_vals)); return sizeof(key_vals); } /* ṹַ豸ĺ * Ӧó豸ļʱõopenreadwriteȺ * ջṹеĶӦ */ static struct file_operations key_fops ={ .owner = THIS_MODULE, .open = key_open, .read = key_read, }; /* **עַ豸 */ int major; static int __init buttons_init(void) { major = register_chrdev(0, DEVICE_NAME, &key_fops); if(major <0) { printk(DEVICE_NAME"register faild \n"); return major; } else { printk(DEVICE_NAME"register successful! \n"); } //࣬洴һ豸ڵ key_drv_class = class_create(THIS_MODULE, DEVICE_NAME); key_drv_class_dev = class_device_create(key_drv_class, NULL, MKDEV(major,0), NULL, "key"); //ioӳ䣬ӳΪַ gpfcon = (volatile unsigned long *)ioremap(0x56000050, 16); gpfdat = gpfcon + 1; gpgcon = (volatile unsigned long *)ioremap(0x56000060, 16); gpgdat = gpgcon + 1; return 0; } /* **ַ豸 */ static void __exit buttons_exit(void) { //ж 豸 unregister_chrdev(major, DEVICE_NAME); //ɾ class_destroy(key_drv_class); class_device_unregister(key_drv_class_dev); //ȡӳ ڴ iounmap(gpfcon); iounmap(gpgcon); return 0; } module_init(buttons_init); module_exit(buttons_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("SHIRUNFA"); MODULE_DESCRIPTION("S3c2440 buttons drivers");
C
//WAP to calculate the area of rectangle, square and circle. Declare pi as constant. #include<stdio.h> #include<conio.h> void main() {int l, b, s, r; const float pi=3.14; clrscr(); printf("\n Enter the lenght, breadth, side and radius"); scanf("%d %d %d %d", &l, &b, &s, &r); printf("\n Area of rectangle:%d", l*b); printf("\n Area of sqaure:%d", s*s); printf("\n Area of circle:%d", pi*r*r); getch(); }
C
#include <stdio.h> #include <string.h> #include <sys/types.h> #include <errno.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <termios.h> #include <stdlib.h> /* set_opt(fd,115200,8,'N',1) */ int set_opt(int fd,int nSpeed, int nBits, char nEvent, int nStop) { struct termios newtio,oldtio; if ( tcgetattr( fd,&oldtio) != 0) { perror("SetupSerial 1"); return -1; } bzero( &newtio, sizeof( newtio ) ); newtio.c_cflag |= CLOCAL | CREAD; newtio.c_cflag &= ~CSIZE; newtio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /*Input*/ newtio.c_oflag &= ~OPOST; /*Output*/ switch( nBits ) { case 7: newtio.c_cflag |= CS7; break; case 8: newtio.c_cflag |= CS8; break; } switch( nEvent ) { case 'O': newtio.c_cflag |= PARENB; newtio.c_cflag |= PARODD; newtio.c_iflag |= (INPCK | ISTRIP); break; case 'E': newtio.c_iflag |= (INPCK | ISTRIP); newtio.c_cflag |= PARENB; newtio.c_cflag &= ~PARODD; break; case 'N': newtio.c_cflag &= ~PARENB; break; } switch( nSpeed ) { case 2400: cfsetispeed(&newtio, B2400); cfsetospeed(&newtio, B2400); break; case 4800: cfsetispeed(&newtio, B4800); cfsetospeed(&newtio, B4800); break; case 9600: cfsetispeed(&newtio, B9600); cfsetospeed(&newtio, B9600); break; case 115200: cfsetispeed(&newtio, B115200); cfsetospeed(&newtio, B115200); break; default: cfsetispeed(&newtio, B9600); cfsetospeed(&newtio, B9600); break; } if( nStop == 1 ) newtio.c_cflag &= ~CSTOPB; else if ( nStop == 2 ) newtio.c_cflag |= CSTOPB; newtio.c_cc[VTIME] = 0; /* 设置从获取到1个字节后开始计时的超时时间 */ newtio.c_cc[VMIN] = 0; /* 设置要求等待的最小字节数 */ tcflush(fd,TCIFLUSH); if((tcsetattr(fd,TCSANOW,&newtio))!=0) { perror("com set error"); return -1; } //printf("set done!\n"); return 0; } int open_port(char *com) { int fd; //fd = open(com, O_RDWR|O_NOCTTY|O_NDELAY); fd = open(com, O_RDWR|O_NOCTTY); if (-1 == fd){ return(-1); } if(fcntl(fd, F_SETFL, 0)<0) { printf("fcntl failed!\n"); return -1; } fcntl(fd, F_SETFL, 0); return fd; } int main(int argc, char **argv) { int oldstate; int oldtype; int iRet; int fd = -1; char line[1024]; int len; char *cmd = "uname\n"; if (argc != 2) { printf("Usage: \n"); printf("%s </dev/ttySAC1 or other>\n", argv[0]); return -1; } fd = open_port(argv[1]); if (fd < 0) { printf("open port err!\n"); return -1; } iRet = set_opt(fd, 115200, 8, 'N', 1); if (iRet) { printf("set port err!\n"); return -1; } write(fd, cmd, strlen(cmd)); sleep(1); len = read(fd,line, 1024); if (len && strstr(line, "Linux")) { printf("Serial ok\n"); return 0; } else { printf("Serial err \n "); return -1; } }
C
#include "binary_trees.h" /** * binary_tree_is_full - check if tree is full * @tree: a started node * Return: 0 or 1 */ int binary_tree_is_full(const binary_tree_t *tree) { if (tree && (tree->right && tree->left)) { if (binary_tree_is_full(tree->left) == 0) return (0); if (binary_tree_is_full(tree->right) == 0) return (0); return (1); } else if (tree && (!tree->left && !tree->right)) { return (1); } return (0); } /** * binary_tree_8 - height of a binary tree * @tree: a node * Return: count or 0 */ size_t binary_tree_8(const binary_tree_t *tree) { size_t count_left = 0; size_t count_right = 0; if (tree && (tree->right || tree->left)) { count_left = binary_tree_8(tree->left); count_right = binary_tree_8(tree->right); if (count_left >= count_right) return (count_left + 1); else return (count_right + 1); } else return (0); } /** * binary_tree_balance - diff between two side * @tree: a node * Return: the balance */ int binary_tree_balance(const binary_tree_t *tree) { size_t count = 0; if (tree && tree->left) count = binary_tree_8(tree->left) + 1; if (tree && tree->right) count = count - (binary_tree_8(tree->right) + 1); return (count); } /** * binary_tree_is_perfect - same height left and right and same child * @tree: the binary tree * Return: 0 or 1 */ int binary_tree_is_perfect(const binary_tree_t *tree) { if (tree) { if (tree->left == NULL && tree->right == NULL) return (1); if ((binary_tree_8(tree->left) == binary_tree_8(tree->right)) && binary_tree_is_perfect(tree->left) && binary_tree_is_perfect(tree->right)) return (1); } return (0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* childs.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bjacob <bjacob@student.42lyon.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/02/17 17:21:20 by bjacob #+# #+# */ /* Updated: 2021/02/18 10:59:37 by bjacob ### ########lyon.fr */ /* */ /* ************************************************************************** */ #include "../../includes/philosophers.h" void *check_full(void *ptr) { t_game *game; game = (t_game*)ptr; sem_wait(game->full_sem); sem_wait(game->print_sem); printf("%d Every philosopher has eaten %d times\n", get_time() - game->start_time, game->nb_philo_eat); return (ptr); } int print_full(t_game *game) { pthread_t thread_full; if (pthread_create(&thread_full, NULL, &check_full, (void*)game)) printf("The thread couldn't be created\n"); else if (pthread_detach(((thread_full)))) printf("The thread couldn't be detached\n"); usleep(1000 * 50); return (SUCCESS); } int create_childs(t_game *game) { int i; pid_t program; i = -1; while (++i < game->nb_philo) { if ((program = fork()) == -1) { ft_kill_all_child(game, i); return (ft_error(game, NULL, F_FORK_CREATE, game->nb_philo)); } if (!program) launch_philo((game->philo)[i]); else game->tab_pid[i] = program; } return (SUCCESS); } void *check_childs(void *ptr) { int status; t_game *game; game = (t_game*)ptr; waitpid(-1, &status, 0); if (WIFSIGNALED(status) == 1 && WTERMSIG(status) != SIGUSR1) { print_error(game->print_sem, F_CHILD_KILLED); inc_sem_end(game); } return (ptr); } int manage_childs(t_game *game) { int i; pthread_t thread_childs; if (pthread_create(&thread_childs, NULL, &check_childs, (void*)game)) { print_error(game->print_sem, F_THREAD_CREATE); inc_sem_end(game); } if (pthread_detach(((thread_childs)))) { print_error(game->print_sem, F_THREAD_DETACH); inc_sem_end(game); } i = -1; while (++i < game->nb_philo) sem_wait(game->end_sem); print_full(game); ft_kill_all_child(game, game->nb_philo); return (SUCCESS); }
C
// 13. Calcular o volume de uma lata de óleo utilizando a fórmula: volume = 3.14159 x r² x Altura #include<stdio.h> #include<math.h> #define pi 3.14159 int main() { float volume, alt, r; printf("Informe a altura: "); scanf("%f", &alt); printf("Informe o raio: "); scanf("%f", &r); volume = (pi * pow(r, 2) * alt); printf("Volume igual a: %.2f", volume); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sort_dop.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: liabanzh <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/04/23 11:58:26 by liabanzh #+# #+# */ /* Updated: 2017/04/23 11:58:27 by liabanzh ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" int push_next(t_stack *a, char sign, int len, int middle) { t_stack *tmp; tmp = a; while (len-- && tmp != NULL) { if (sign == 'a' && tmp->data < middle) return (1); if (sign == 'b' && tmp->data > middle) return (1); tmp = tmp->next; } return (0); } int check_b(t_stack *b, int size) { t_stack *e2; t_stack *e3; if (size <= 1) return (0); e2 = (b->next != NULL) ? b->next : NULL; if (e2 != NULL) e3 = e2->next; if (size == 2) { if (b->data < e2->data) return (1); } else if (b->data < e2->data && e2->data > e3->data && e3->data < b->data) return (1); else if (b->data > e2->data && e2->data < e3->data && e3->data > b->data) return (2); else if (b->data > e2->data && e2->data < e3->data && e3->data < b->data) return (3); else if (b->data < e2->data && e2->data < e3->data && e3->data > b->data) return (4); else if (b->data < e2->data && e2->data > e3->data && e3->data > b->data) return (5); return (0); } int check_a(t_stack *a, int size) { t_stack *e2; t_stack *e3; if (size <= 1) return (0); e2 = (a->next != NULL) ? a->next : NULL; if (e2 != NULL) e3 = e2->next; if (size == 2) { if (a->data > e2->data) return (1); } else if (a->data > e2->data && e2->data < e3->data && e3->data > a->data) return (1); else if (a->data < e2->data && e2->data > e3->data && e3->data < a->data) return (2); else if (a->data < e2->data && e2->data > e3->data && e3->data > a->data) return (3); else if (a->data > e2->data && e2->data > e3->data && e3->data < a->data) return (4); else if (a->data > e2->data && e2->data < e3->data && e3->data < a->data) return (5); return (0); } void simple_sort_b(t_stack **b, int len, t_cmd **cmd) { t_stack *c; t_stack *n; if (len == 2) return (cmd_list(cmd, SB)); c = ((*b)->next != NULL) ? (*b)->next : NULL; if (c != NULL) n = c->next; if ((*b)->data < c->data && c->data > n->data && n->data < (*b)->data) cmd_list(cmd, SB); else if ((*b)->data > c->data && c->data < n->data && n->data > (*b)->data) cmd_list(cmd, RRB); else if ((*b)->data > c->data && c->data < n->data && n->data < (*b)->data) { cmd_list(cmd, RRB); cmd_list(cmd, RRB); } else if ((*b)->data < c->data && c->data < n->data && n->data > (*b)->data) { cmd_list(cmd, SB); cmd_list(cmd, RRB); } else if ((*b)->data < c->data && c->data > n->data && n->data > (*b)->data) cmd_list(cmd, RB); } void simple_sort_a(t_stack **a, int len, t_cmd **cmd) { t_stack *c; t_stack *n; c = NULL; if (len == 2) return (cmd_list(cmd, SA)); c = ((*a)->next != NULL) ? (*a)->next : NULL; if (c != NULL) n = c->next; if ((*a)->data > c->data && c->data < n->data && n->data > (*a)->data) cmd_list(cmd, SA); else if ((*a)->data < c->data && c->data > n->data && n->data < (*a)->data) cmd_list(cmd, RRA); else if ((*a)->data < c->data && c->data > n->data && n->data > (*a)->data) { cmd_list(cmd, RRA); cmd_list(cmd, SA); } else if ((*a)->data > c->data && c->data > n->data && n->data < (*a)->data) { cmd_list(cmd, RA); cmd_list(cmd, SA); } else if ((*a)->data > c->data && c->data < n->data && n->data < (*a)->data) cmd_list(cmd, RA); }
C
#include "Magnetometer.h" volatile float magneto_xyz[3]; float HeadingValue; void MAGNETO_Init(void){ if(BSP_MAGNETO_Init() != MAGNETO_OK){ /* Initialization Error */ Error_Handler(); } } static inline float GetAngle(float y, float x){ float angle = atan2f(y, x); return ( (angle < 0.f) ? (angle + 2.f * M_PI) : angle ); } void MAGNETO_UpdateValues(void){ for(uint32_t i=0; i<3; i++){ acc_xyz[i] /= 100.0f; } float pitch = GetAngle( acc_xyz[1], sqrtf( acc_xyz[0]*acc_xyz[0] + acc_xyz[2]*acc_xyz[2] ) ); float roll = GetAngle( -acc_xyz[0], acc_xyz[2] ); if ((roll <= M_PI_4) && (pitch <= M_PI_4)){ float fTiltedX = magneto_xyz[0]*cosf(pitch)+magneto_xyz[2]*sinf(pitch); float fTiltedY = magneto_xyz[0]*sinf(roll)*sinf(pitch)+magneto_xyz[1]*cosf(roll)-magneto_xyz[1]*sinf(roll)*cosf(pitch); HeadingValue = ( GetAngle( fTiltedY, fTiltedX ) * (180.f / M_PI) + 225.0f + 7.5 /*some error*/); HeadingValue = HeadingValue - (HeadingValue > 360.f) ? 360.f : 0.f; static uint16_t curr_led = -1; uint16_t old_led = curr_led; curr_led = ( ( (uint16_t) ( (HeadingValue ) / ( 180.f / LED_NUM ) ) + 1) >> 1 ) % LED_NUM; if( old_led != curr_led ){ BSP_LED_Off( leds[old_led] ); BSP_LED_On ( leds[curr_led] ); } } }
C
#include<conio.h> #include<stdio.h> #include<math.h> int main() { int p,n; float r,si; clrscr(); printf("enter the principle amount"); scanf("%d",&p); printf("enter the rate"); scanf("%f",&r); printf("enter the period"); scanf("%d",&n); si=(p*r*n)/100; printf("simple interest is %f",si); getch(); return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_9__ TYPE_1__ ; /* Type definitions */ struct TYPE_9__ {int x; int y; int z; } ; typedef TYPE_1__ guVector ; typedef int** Mtx ; /* Variables and functions */ int /*<<< orphan*/ guVecCross (TYPE_1__*,TYPE_1__*,TYPE_1__*) ; int /*<<< orphan*/ guVecNormalize (TYPE_1__*) ; void guLookAt(Mtx mt,guVector *camPos,guVector *camUp,guVector *target) { guVector vLook,vRight,vUp; vLook.x = camPos->x - target->x; vLook.y = camPos->y - target->y; vLook.z = camPos->z - target->z; guVecNormalize(&vLook); guVecCross(camUp,&vLook,&vRight); guVecNormalize(&vRight); guVecCross(&vLook,&vRight,&vUp); mt[0][0] = vRight.x; mt[0][1] = vRight.y; mt[0][2] = vRight.z; mt[0][3] = -( camPos->x * vRight.x + camPos->y * vRight.y + camPos->z * vRight.z ); mt[1][0] = vUp.x; mt[1][1] = vUp.y; mt[1][2] = vUp.z; mt[1][3] = -( camPos->x * vUp.x + camPos->y * vUp.y + camPos->z * vUp.z ); mt[2][0] = vLook.x; mt[2][1] = vLook.y; mt[2][2] = vLook.z; mt[2][3] = -( camPos->x * vLook.x + camPos->y * vLook.y + camPos->z * vLook.z ); }
C
#include <stdio.h> #include <string.h> double get_cpu_usage(void) { double total; double usage; int user; int nice; int system; int idle; unsigned char cpu[8]; unsigned char text[256]; FILE *fp; fp = fopen("/proc/stat", "r"); fread(text, 1, sizeof(text), fp); if (strstr(text, "cpu")) { sscanf(text, "%s %d %d %d %d", cpu, &user, &nice, &system, &idle); } printf("%d %d %d %d\n", user, nice, system, idle); fclose(fp); total = (user + nice + system + idle); usage = (user + nice + system )/total ; return usage; }
C
#include <stdio.h> #include <stdlib.h> #include "aux.h" #include "util.h" #include "fourier.h" int main(int argc, char ** argv) { //declaration double (*fourier_function)(double); //the program will find the fourier coefficients of this function //validates inputs and sets the appropriate function equal to fourier_function if(argc != 6) { return EXIT_FAILURE; } if(argv[1][1] != '\0') { return EXIT_FAILURE; } if(argv[1][0] == '1') { fourier_function = unknown_function_1; } else if(argv[1][0] == '2') { fourier_function = unknown_function_2; } else if(argv[1][0] == '3') { fourier_function = unknown_function_3; } else { return EXIT_FAILURE; } Integrand integrand = { .lower_limit = atof(argv[2]), .upper_limit = atof(argv[3]), .n_intervals = atoi(argv[4]), .func_to_be_integrated = fourier_function }; int n_terms = atoi(argv[5]); if(integrand.lower_limit == integrand.upper_limit) { return EXIT_FAILURE; } if(integrand.n_intervals < 1) { integrand.n_intervals = 1; }//the number of intervals has to be at least one if(n_terms < 1) { n_terms = 1; }//the number of terms has to be at least one Fourier fourier = { .intg = integrand, .n_terms = n_terms, .a_i = malloc(sizeof(*fourier.a_i) * n_terms), .b_i = malloc(sizeof(*fourier.b_i) * n_terms) }; // If allocation of fourier.a_i and/or fourier.b_i failed, then free the // one that didn't fail and then exit with EXIT_FAILURE. if (fourier.a_i == NULL || fourier.b_i == NULL) { free(fourier.a_i); // free(...) has no effect if its argument is NULL free(fourier.b_i); return EXIT_FAILURE; } fourier_coefficients(fourier); print_fourier_coefficients(fourier.a_i, fourier.b_i, fourier.n_terms); free(fourier.a_i); free(fourier.b_i); return EXIT_SUCCESS; }
C
#include "hblk_crypto.h" EC_KEY *ec_load(char const *folder) { EC_KEY *key = NULL; char buf[BUFSIZ]; FILE *fp; if (!folder || strlen(folder) + strlen(PUB_FILENAME) > BUFSIZ) return (NULL); sprintf(buf, "%s/%s", folder, PUB_FILENAME); fp = fopen(buf, "r"); if (!fp) return (NULL); if (!PEM_read_EC_PUBKEY(fp, &key, NULL, NULL)) goto out; sprintf(buf, "%s/%s", folder, PRI_FILENAME); fp = fopen(buf, "r"); if (!fp) return (NULL); if (!PEM_read_ECPrivateKey(fp, &key, NULL, NULL)) goto out; out: fclose(fp); return (key); }
C
#include <stdio.h> #include <cs50.h> int main(void) { char *myName = get_string("What is your name?: "); printf("hello, %s\n", myName); }
C
#include<stdlib.h> #include<stdio.h> #include<string.h> #include<ctype.h> #include<math.h> #include "header.h" /* Show Welcome message, Do you want to continue & Rules. */ void TextArt() { char ch; printf("\n _____ __ _ _ _ _ _ _ "); printf("\n |_ _| / _(_) | \\ | | | | | | (_) "); printf("\n | | _ __ | |_ ___ __ | \\| | ___ | |_ __ _| |_ _ ___ _ __ "); printf("\n | || '_ \\| _| \\ \\/ / | . ` |/ _ \\| __/ _` | __| |/ _ \\| '_ \\ "); printf("\n _| || | | | | | |> < | |\\ | (_) | || (_| | |_| | (_) | | | | "); printf("\n \\___/_| |_|_| |_/_/\\_\\ \\_| \\_/\\___/ \\__\\__,_|\\__|_|\\___/|_| |_| "); printf("\n _ "); printf("\n | | "); printf("\n | |_ ___ "); printf("\n | __/ _ \\ "); printf("\n | || (_) | "); printf("\n \\__\\___/ "); printf("\n ______ _ __ _ ______ __ _ "); printf("\n | ___ \\ | | / _(_) ___ | ___ \\ / _(_) "); printf("\n | |_/ /__ ___| |_| |_ ___ __ ( _ ) | |_/ / __ ___| |_ ___ __"); printf("\n | __/ _ \\/ __| __| _| \\ \\/ / / _ \\/\\ | __/ '__/ _ \\ _| \\ \\/ /"); printf("\n | | | (_) \\__ \\ |_| | | |> < | (_> < | | | | | __/ | | |> < "); printf("\n \\_| \\___/|___/\\__|_| |_/_/\\_\\ \\___/\\/ \\_| |_| \\___|_| |_/_/\\_\\\n"); printf("\n Infix notation to Postfix & Prefix "); printf("\n (Negative numbers and multi-digit are supported)\n"); do { printf("\n Do you want to continue, y/n? "); ch=getchar(); } while ((ch != 'y') && (ch != 'n')); // Ask the user if want to start Simulation or not! if(ch == 'y'){ printf("\n\n Rules: 1) Insert the infix expression without space, e.g. 5*(((7*9)-(8*7))*4)/7.\n"); printf(" 2) Give the negative numbers with this format (-number), e.g. 5*(-7).\n"); printf(" 3) This program supports only these operators: ^, *, /, ~, +, -, =.\n"); printf(" 4) Output format use parentheses with singed number and operators, e.g. (+5) (-7) (*).\n"); printf(" All other formats are not supported and appear respectively error messages as the case.\n\n"); } if (ch=='n') exit(0); getchar(); } /* Show menu and return a valid choice. */ int Menu() { char menu; int choice; do { printf("\n\n +============================================+"); printf("\n | Menu |"); printf("\n +============================================+"); printf("\n | Options: |"); printf("\n | 1. Insert infix notation |"); printf("\n | 2. Display postfix |"); printf("\n | 3. Display prefix |"); printf("\n | 4. Exit |"); printf("\n +============================================+\n"); printf("\n Please, select a option from 1 to 4: "); menu=getchar(); printf(" Option %c selected.\n",menu); if(!((menu=='1') || (menu=='2') ||(menu=='3')||(menu=='4'))) { getchar(); printf("\n *** Try to choice between [1 - 4] next time. ***\n\n"); } } while (!((menu=='1') || (menu=='2') ||(menu=='3')||(menu=='4'))); choice = menu -'0' ; getchar(); return choice; } /* Processes user choice and do the appropriate function. */ void infixToPostAndPre(){ TextArt(); struct treeNode* treeRoot= NULL; int choice; do { choice=Menu() ; if (choice==1){ // Initialization of global pointer. headInfix=NULL; headPostfix=NULL; headOperatorStack=NULL; treeStackHead=NULL; // Create list with infix expession. insertInfix (); // Create list with the postfix expession of infix expession. createPostFixList (); // Create Binary Tree from postfix list. treeRoot= createBinaryTree(); } else if (choice==2){ if(treeRoot!= NULL){ // Display postfix with postorder print. printf("\nPostfix: "); postFix(treeRoot); }else{ printf("\nPlease, insert first Infix notation..."); } } else if (choice==3){ if(treeRoot!= NULL){ // Display postfix with preorder print. printf("\nPrefix: "); preFix(treeRoot); }else{ printf("\nPlease, insert first Infix notation..."); } } }while (choice!=4); // Free all lists & stacks. freeList(1); freeList(2); freeOperatorStack(); freeTreeNodeStack(); printf("\n Goodbye !!!\n"); return ; } /* I call the function readInfix and take user's input, then stored in an array the positions of operands and call function tokenazationInput.*/ void insertInfix (){ char* inputExpretion = readInfix(); int operatorsPositions[100]; int symbolCount=0; int i; // Catch all operands positions & increase symbolCount (the real size of operatorsPositions) . for (i=0; i<strlen(inputExpretion); i++) // Catch op positions. { if (inputExpretion[i]=='^'||inputExpretion[i]=='*'||inputExpretion[i]=='/'||inputExpretion[i]=='~'||inputExpretion[i]=='+'||inputExpretion[i]=='-'||inputExpretion[i]=='('||inputExpretion[i]==')'||inputExpretion[i]=='=') { operatorsPositions[symbolCount]=i; symbolCount++; } } // Call tokenazationInput for separate and save ops & numbers in infixList. tokenazationInput(inputExpretion,operatorsPositions,symbolCount); } /* Create List postfix using operator stack (use addOperatorStack) when reading number entered in the list when entered the operator adds to the stack. Before add operator to the stack check the priorities of top of stack and current operator fron infix and do the right push & pop(use popOperatorStack) , when seen close bracket empty the stack until find the opening of bracket and finally empty the stack. */ void createPostFixList (){ expesionList* temp =headInfix; // Crossing infix list check every element. while(temp!=NULL) { if (temp->term[0] == '(') addOperatorStack(temp->term); // From size of element can see if it's number or operator. else if (strlen(temp->term)>1) addList(2,temp->term); else if (temp->term[0] == ')') { // Check if operator stack is empty. if(headOperatorStack==NULL){ addOperatorStack(temp->term); } // Pop and add elemnts to prostfix list until found the open of parenthesis. else{ while (headOperatorStack->op[0] != '(') { addList(2,popOperatorStack()); } // Throw '('. popOperatorStack(); } // Pop and add elemnts to prostfix list with precedenceOfOperator in headOperatorStack and curentOperator. }else { // Check if operator stack is empty. if(headOperatorStack==NULL){ addOperatorStack(temp->term); }else{ while(precedenceOfOperator(headOperatorStack->op) >= precedenceOfOperator(temp->term)) { addList(2,popOperatorStack()); // Check if operator stack is empty. if(headOperatorStack==NULL) break; } addOperatorStack(temp->term); } } // Next element. temp=temp->next; } // Empty stack and add elements to postfix list. while (headOperatorStack != NULL) // Pop from stack till empty addList(2,popOperatorStack()); } /* Returns an integer corresponding to the priority of the operator given as an argument.*/ int precedenceOfOperator(char* oper) { if(oper[0]=='^') return 4; else if((oper[0]=='*')||(oper[0]=='~')||(oper[0]=='/')) return 3; else if((oper[0]=='+')||(oper[0]=='-')) return 2; else if(oper[0]=='(') return 1; else if (oper[0]=='=') return 0; exit(0); }
C
/** * 2020 Feb * Copyright 2020 petra, all rights reserved. */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define ESC 27 void setProgram(){ printf("loading...\n"); srand(time(NULL)); system("cls"); } int randomNumber(){ int result = (rand() % 9) + 1; return result; } void exitProgram(){ char exitKey; int exitCountNumber = 0; printf("\n"); printf("--------------------------------------------------------------------\n"); printf("program exit : click <esc> key.\n"); do{ exitKey = getch(); switch(exitKey){ case ESC: exitCountNumber = 1; break; } }while(exitCountNumber != 1); }
C
/* * include/arch/x86/scheduler.h * * Author: Fernando Rodriguez * Email: frodriguez.developer@outlook.com * * Copyright 2014-2015 Fernando Rodriguez * All rights reserved. * * This code is distributed for educational purposes * only. It may not be distributed without written * permission from the author. * */ #ifndef __ARCH_SCHEDULER_H__ #define __ARCH_SCHEDULER_H__ #include <stdint.h> #include <mmu.h> /* * task state structure */ typedef struct { uint32_t eip; uint32_t esp; uint32_t ebp; uint32_t ebx; uint32_t esi; uint32_t kernel_stack; uint32_t directory_physical; memmap_t *memmap; page_directory_t *directory; } task_state_t; /* * jump to a virtual address */ #define arch_jump(addr) asm volatile("jmp *%0" : : "r" (addr)) /* * Call a procedure by it's virtual address */ #define arch_call(addr) asm volatile("call *%0" : : "r" (addr)) /* * Macros to get/set machine state fields */ #define arch_get_kernel_stack(task) (task.kernel_stack) #define arch_set_kernel_stack(task, value) task.kernel_stack = value #define arch_get_directory(task) (task.directory) #define arch_set_directory(task, value) task.directory = value #define arch_get_directory_physical(task) (task.directory_physical) #define arch_set_directory_physical(task, value) task.directory_physical = value #define arch_get_memmap(task) (task.memmap) #define arch_set_memmap(task, value) task.memmap = value #define arch_get_user_stack() (current_task->registers->useresp) #define arch_set_user_stack(stack) current_task->registers->useresp = (stack) /* * Given an address for a usermode stack this macro returns what * the stack pointer would be after the stack is relocated to this * buffer. Currently it assumes that the stack grown downwards * so it's not very portable. TODO: We need to FIX that. */ #define arch_adj_user_stack_pointer(stack) ((stack) - (ARCH_STACK_START - current_task->registers->useresp)) /* * Copy the user-mode stack. This is a simple copy of the * stack used by clone() to fork new threads. Pointers to * stack values will still point to the old stack. */ #define arch_copy_user_stack(stack) \ do \ { \ uint32_t *old_stack, *new_stack; \ new_stack = (uint32_t*) (stack - (ARCH_STACK_START - current_task->registers->useresp)); \ old_stack = (uint32_t*) current_task->registers->useresp; \ while ((uint32_t) old_stack <= ARCH_STACK_START) \ *new_stack++ = *old_stack++; \ } \ while (0) /* * returns TRUE if the current task has just been * resumed by calling arch_scheduler_load_task_state() */ #define arch_task_resumed(task) (task.eip == 0x12345) /* * get the current value of the eip register */ #define arch_scheduler_get_ip() (read_eip()) /* * save the current task's eip into a task_state_T * structure * * NOTE: This needs to be done in two asm directives. */ #define arch_scheduler_save_task_ip(task) \ asm __volatile__("mov $1f, %%eax; 1:" : : : "eax"); \ asm __volatile__("mov %%eax, %0;" : "=m" (task.eip) : : "eax") /* * save the current task state (ebp and esp) to a * task_state_t structure */ #define arch_scheduler_save_task_state(task) \ asm __volatile__( \ "mov %0, %%eax;" \ "mov %%esp, 0x04(%%eax);" \ "mov %%ebp, 0x08(%%eax);" \ "mov %%ebx, 0x0C(%%eax);" \ "mov %%esi, 0x10(%%eax);" \ : : "r" (&task) : "eax", "memory" ) /* * load a task_state_t structure into the cpu and jump * to it's current eip */ #define arch_scheduler_load_task_state(task) \ asm __volatile__( \ "cli;" \ "mov %0, current_task;" \ "mov 0x04(%0), %%esp;" \ "mov 0x08(%0), %%ebp;" \ "mov 0x14(%0), %%ebx;" \ "mov 0x1C(%0), %%eax;" \ "mov %%eax, current_memmap;" \ "add %1, %%ebx;" \ "mov $tss_entry, %%eax;" \ "mov %%ebx, 0x4(%%eax);" \ "mov 0x20(%0), %%eax;" \ "mov %%eax, current_directory;" \ "mov 0x18(%0), %%eax;" \ "mov %%eax, %%cr3;" \ "mov $0x12345, %%eax;" \ "mov 0x0C(%0), %%ebx;" \ "mov 0x10(%0), %%esi;" \ "mov 0x00(%0), %0;" \ "sti;" \ "jmp *%0" : : \ "r" (task), \ "i" (SCHED_KERNEL_STACK_SIZE - 4) : \ "memory", "ebx", "esi", "eax" ) /* * load a task_state_t structure into the cpu and jump * into the specified signal handler */ #define arch_scheduler_load_task_state_and_signal(task, sig) \ asm __volatile__( \ "cli;" \ "mov %0, current_task;" \ "mov 0x04(%0), %%esp;" \ "mov 0x08(%0), %%ebp;" \ "mov 0x14(%0), %%ebx;" \ "mov 0x1C(%0), %%eax;" \ "mov %%eax, current_memmap;" \ "mov 0x20(%0), %%eax;" \ "mov %%eax, current_directory;" \ "add %2, %%ebx;" \ "mov $tss_entry, %%eax;" \ "mov %%ebx, 0x4(%%eax);" \ "mov 0x18(%0), %%eax;" \ "mov %%eax, %%cr3;" \ "mov %%esp, %%ebx;" \ "cmp %%ebp, %%ebx;" \ "jge 2f;" \ "1:" \ "mov (%%ebx), %%eax;" \ "mov %%eax, -0xc(%%ebx);" \ "add $0x4, %%ebx;" \ "cmp %%ebp, %%ebx;" \ "jl 1b;" \ "2:" \ "mov %1, %%eax;" \ "mov %%eax, -0x4(%%ebx);" \ "mov $3f, %%eax;" \ "mov %%eax, -0x8(%%ebx);" \ "mov %%ebp, -0xc(%%ebx);" \ "sub $0xc, %%esp;" \ "sub $0xc, %%ebp;" \ "mov 0x0c(%0), %%ebx;" \ "mov 0x10(%0), %%esi;" \ "mov 0x00(%0), %0;" \ "mov $0x12345, %%eax;" \ "sti;" \ "jmp *%0;" \ "3:" \ "call signal_handler;" \ "add $0x4, %%esp;" \ "pop %%ebp;" \ "ret;" : : \ "r" (task), \ "r" (sig), \ "i" (SCHED_KERNEL_STACK_SIZE - 4) : \ "memory", "cc", "esi", "ebx", "eax" ) /* * Switch to user mode and call a function. * * Sets usermode stack as follows: * * +-----------+ * | eip | --> kernel eip * +-----------+ * | esp | --> kernel stack * +-----------+ * | argv | --> arguments data * +-----------+ * | *argv | --> arguments string table * +-----------+ * | argc | --> argument count * +-----------+ * | *main | --> program entry point * +-----------+ * * Then switches to usermode and transfers control * to user_entry(). * */ #define arch_enter_user_mode(stack, vaddr, argc, argv, len) \ asm __volatile__( \ "mov %%esp, %%ebx;" \ "mov %0, %%esp;" \ "1:" \ "push $1b;" \ "push %%ebx;" \ "sub %4, %%esp;" \ "mov %%esp, %%ebp;" \ "push %3;" \ "test %4, %4;" \ "jz 3f;" \ "2:" \ "mov (%3), %%eax;" \ "mov %%eax, 0x4(%%ebp);" \ "add $0x4, %%ebp;" \ "add $0x4, %3;" \ "sub $0x4, %4;" \ "jnz 2b;" \ "3:" \ "pop %3;" \ "lea 0x4(%%esp), %%eax;" \ "push %%eax;" \ "push %2;" \ "push %1;" \ "mov %%eax, %1;" \ "sub %3, %%eax;" \ "test %2, %2;" \ "jz 5f;" \ "4:" \ "mov (%1), %3;" \ "add %%eax, %3;" \ "mov %3, (%1);" \ "add $0x4, %1;" \ "dec %2;" \ "jnz 4b;" \ "5:" \ "mov %%esp, %2;" \ "sub $0x4, %2;" \ "mov %%ebx, %%esp;" \ \ "pushf;" /* eflags */ \ "pop %%eax;" /* read eflags */ \ "or $0x200, %%eax;" /* sti on iret */ \ \ "pushl $0x23;" /* ss */ \ "pushl %2;" /* esp */ \ "push %%eax;" /* eflags */ \ "pushl $0x1B;" /* cs */ \ "push $user_entry;" /* eip */ \ "cli;" \ "mov $0x23, %%ax;" \ "mov %%ax, %%ds;" \ "mov %%ax, %%es;" \ "mov %%ax, %%fs;" \ "mov %%ax, %%gs;" \ "iret;" : : \ "i" (stack), \ "r" (vaddr), \ "r" (argc), \ "r" (argv), \ "r" (len) : \ "cc", "memory", "eax", "ebx" ) /* * Perform arch-specific scheduler * initialization. */ void arch_scheduler_init(void); /* * Relocate the stack */ void arch_move_stack(void *new_stack_start, uint32_t size); #if 1 struct __task; void arch_scheduler_move_the_fucking_task_stack(struct __task *new_task); #endif #endif
C
// // prob3.c // // // Created by Pablo Cecilio on 13/10/2017. // #include <stdio.h> void MAIORES (int a[][4]) { int i, j, n=0; for ( i=0; i<=3; i++) { for (j=0; j<=3; j++) { if (a[i][j]>10) { printf ("%d ", a[i][j]); n++; } } } printf ("sao maiores que 10\n"); printf ("Total = %d valores maiores que 10\n", n); } int main() { int mat[4][4],i,j; for ( i=0; i<=3; i++ ) { for ( j=0; j<=3; j++ ) { printf ("Valor[%d][%d] = ", i, j); scanf ("%d", &mat[i][j]); } } for ( i=0; i<=3; i++ ) { for ( j=0; j<=3; j++ ) { printf ("%d\t", mat[i][j]); } printf ("\n"); } MAIORES(mat); }
C
#ifndef HASH_TABLE_H #define HASH_TABLE_H #include <stdlib.h> #include <string.h> #include <stdbool.h> #include "any.h" typedef struct hash_node hash_node; typedef struct hash_table hash_table; typedef struct hash_table_iter hash_table_iter; struct hash_node { size_t hash; //!< Hash value size_t count; //!< Occurences any key; //!< key any value; //!< value hash_node * next; //!< Pointer to next node hash_node * order_prev; hash_node * order_next; }; struct hash_table { size_t slots[2]; //!< Number of slots size_t nodes; //!< Number of nodes size_t (*hash_fun)(const any *); //!< Pointer to a hash function int (*compare)(const any *, const any *); hash_node ** array[2]; //!< [0] Currently used array of node pointers [1] Expanded array of node pointers hash_node * last; }; struct hash_table_iter { hash_node * next; }; static inline void hash_table_iter_init(const hash_table * table, hash_table_iter * iter) { iter->next = table->last; } static inline bool hash_table_iter_has(const hash_table_iter * iter) { return iter->next != NULL; } static inline hash_node * hash_table_iter_next(hash_table_iter * iter) { hash_node * n = iter->next; iter->next = n->order_prev; return n; } extern hash_table * hash_table_new(size_t capacity, size_t (*hash_fun)(const any *), int (*compare)(const any *, const any *)); extern void hash_table_free(hash_table * table, void (*deallocator)(any * key, any * value)); extern hash_node * hash_table_insert(hash_table * table, const any key, const any value); extern void hash_table_delete(hash_table * table, const any key); extern hash_node * hash_table_find(const hash_table * table, const any key); extern any hash_table_get(const hash_table * table, const any key); #endif // HASH_TABLE_H
C
/* # ricorsione # Programmi di Laboratorio di Programmazione in Linguaggio "C" e Linguaggio "Python" ("PY"). Alunno: Bucchianico Enrico Ruggiero. ricorsione Programmi di Laboratorio di Programmazione in Linguaggio "C" e Linguaggio "Python" ("PY"). Alunno: Bucchianico Enrico Ruggiero. - Programma "potenza.c": Linguaggio "C": Programma che calcola la potenza intera positiva di un numero intero. */ #include <stdio.h> int potenza(int b,int e); int calcolo_potenza(int b,int e); int main() { int b,e; puts("CALCOLO DELLA POTENZA\n\n"); puts("Inserire la base:\t"); scanf("%d",&b); puts("\nInserire l'esponente:\t"); scanf("%d",&e); potenza(b,e); puts("\n\n"); return 0; } int potenza(int b,int e) { if(b==0) { return (printf("\n\n%d ^ %d =\t0",b,e)); } else if(e==0) { return (printf("\n\n%d ^ %d =\t1",b,e)); } else if(e==1) { return (printf("\n\n%d ^ %d =\t%d",b,e,calcolo_potenza(b,e))); } else if(e<0) { return (printf("\n\n%d ^ %d = 1/(%d)^%d = 1/%d",b,e,b,-e,calcolo_potenza(b,e))); } else { return (printf("\n\n%d ^ %d =\t%d",b,e,calcolo_potenza(b,e))); } } int calcolo_potenza(int b,int e) { if(e==1) { return (b); } if(e<0) { e=-e; return (b*calcolo_potenza(b,e-1)); } else { return (b*calcolo_potenza(b,e-1)); } }
C
/** * \file timer.c * \brief Ce fichier permet de répertorier toutes les actions qu'un timer peut faire. * \details On utilise ce programme pour calculer depuis combien de temps la partie ou une action est lancé. * \author Vallet Guillaume */ #include "../include/commun.h" #include "../include/timer.h" /** * \brief Démarre le timer * * \details Initialise les valeurs du timer pour lancer. * \param Le timer a lancer * */ void timer_debut(Timer_t * Timer) { //On demarre le timer Timer->start = true; //On enlève la pause du timer Timer->paused = false; //On récupére le temps courant Timer->tick_debut = SDL_GetTicks(); } /** * \brief Arrête définitivement le timer * * \details Mets le timer en arrêt en mettant ses bool en false * \param Le timer a stoppé * */ void timer_stop(Timer_t * Timer) { //On stoppe le timer Timer->start = false; //On stoppe la pause Timer->paused = false; } /** * \brief Donne le temps depuis lequel le timer a démarrer * * \details Si le timer est en pause, ne donne rien. * \param Le timer a observer * \return Le temps depuis lequel le timer a commencé en entier * */ int timer_get_ticks(Timer_t * Timer) { //Si le timer est en marche if( Timer->start == true ) { //Si le timer est en pause if( Timer->paused == false ) { //On retourne le temps courant moins le temps quand il a démarré return SDL_GetTicks() - Timer->tick_debut; } } //Si le timer n'est pas en marche return 0; } /** * \brief Mets le timer en pause * * \details Initialise le tick_pause du timer au tick du lancement de la fonction pour savoir quand le timer a été mis en pause * \param Le timer a pauser * */ void timer_pause(Timer_t * Timer) { //Si le timer est en marche et pas encore en pause if(( Timer->start == true ) && ( Timer->paused == false )) { //On met en pause le timer Timer->paused = true; //On calcul le pausedTicks Timer->tick_pause = SDL_GetTicks() - Timer->tick_debut; } } /** * \brief Dépause le timer * * \details Dépause le timer en enlevant l'état de pause et en remettant le tick_debut a une valeur qui permettent de redonner le même temps avant la pause * \param Le timer a dépauser * */ void timer_unpause(Timer_t * Timer) { //Si le timer est en pause if( Timer->paused == true ) { //on enlève la pause du timer Timer->paused = false; //On remet à zero le startTicks Timer->tick_debut = SDL_GetTicks() - Timer->tick_pause; //Remise à zero du pausedTicks Timer->tick_pause = 0; } } /** * \brief Regarde si le timer a démarrer * * \details Donne l'état du timer. * \param Le timer a observer * \return Un booléen qui dit si le timer est lancer. * */ bool timer_is_started(Timer_t * Timer) { return (Timer->start); } /** * \brief Regarde si le timer est en pause * * \details Donne l'état du timer. * \param Le timer a observer * \return Un booléen qui dit si le timer est en pause. * */ bool timer_is_paused(Timer_t * Timer) { return (Timer->paused); } /** * \brief Initialise le timer * * \details Fait un malloc et initialise tout les paramètres du timer pour qu'il soit opérationelle * \param Aucun * \return Un pointeur sur timer_t pour pouvoir ensuite affecter ce pointeur a une variable de type timer_t * * */ Timer_t * timer_init() { //Création de l'espace du timer Timer_t * Timer; Timer = malloc(sizeof(Timer_t)); //Initialisation de valeur de base Timer->start = false; Timer->paused = false; Timer->tick_debut = 0; Timer->tick_pause = 0; //Initialisation des fonctions a utiliser Timer->debut = timer_debut; Timer->stop = timer_stop; Timer->pause = timer_pause; Timer->unpause = timer_unpause; Timer->get_ticks = timer_get_ticks; Timer->is_started = timer_is_started; Timer->is_paused = timer_is_paused; return Timer; } /* int main(int arv, char *argc[]) { SDL_Init(SDL_INIT_VIDEO); //Initialisation du timer test Timer_t * test; test = timer_init(); //Lance le timer test->debut(test); printf("%i\n",test->get_ticks(test)); printf("A commence : %i\n", test->is_started(test)); printf("En pause : %i \n", test->is_paused(test)); SDL_Delay(1000); //Mets en pause le timer printf("%i\n",test->get_ticks(test)); test->pause(test); printf("A commence : %i\n", test->is_started(test)); printf("En pause : %i \n", test->is_paused(test)); SDL_Delay(1000); //Depause le timer test->unpause(test); printf("%i\n",test->get_ticks(test)); //N'a pas bouger par rapport au dernier affichage printf("A commence : %i\n", test->is_started(test)); printf("En pause : %i \n", test->is_paused(test)); //Arrete completement le timer test->stop(test); printf("%i\n",test->get_ticks(test)); //Censer renvoyer 0 printf("A commence : %i\n", test->is_started(test)); printf("En pause : %i \n", test->is_paused(test)); } */
C
// RUN: %libomptarget-compilexx-run-and-check-generic // Assuming the stack is allocated on the host starting at high addresses, the // host memory layout for the following program looks like this: // // low addr <----------------------------------------------------- high addr // | 16 bytes | 16 bytes | 16 bytes | ? bytes | // | collidePost | s | collidePre | stackPad | // | | x | y | z | | | // `-------------' // ^ `--------' // | ^ // | | // | `-- too much padding (< 16 bytes) for s maps here // | // `------------------array extension error maps here // // libomptarget used to add too much padding to the device allocation of s and // map it back to the host at the location indicated above when all of the // following conditions were true: // - Multiple members (s.y and s.z below) were mapped. In this case, initial // padding might be needed to ensure later mapped members (s.z) are aligned // properly on the device. (If the first member in the struct, s.x, were also // mapped, then the correct initial padding would always be zero.) // - mod16 = &s % 16 was not a power of 2 (e.g., 0x7ffcce2b584e % 16 = 14). // libomptarget then incorrectly assumed mod16 was the existing host memory // alignment of s. (The fix was to only look for alignments that are powers // of 2.) // - &s.y % mod16 was > 1 (e.g., 0x7ffcce2b584f % 14 = 11). libomptarget added // padding of that size for s, but at most 1 byte is ever actually needed. // // Below, we try many sizes of stackPad to try to produce those conditions. // // When collidePost was then mapped to the same host memory as the unnecessary // padding for s, libomptarget reported an array extension error. collidePost // is never fully contained within that padding (which would avoid the extension // error) because collidePost is 16 bytes while the padding is always less than // 16 bytes due to the modulo operations. (Later, libomptarget was changed not // to consider padding to be mapped to the host, so it cannot be involved in // array extension errors.) #include <stdint.h> #include <stdio.h> template <typename StackPad> void test() { StackPad stackPad; struct S { char x; char y[7]; char z[8]; }; struct S collidePre, s, collidePost; uintptr_t mod16 = (uintptr_t)&s % 16; fprintf(stderr, "&s = %p\n", &s); fprintf(stderr, "&s %% 16 = %lu\n", mod16); if (mod16) { fprintf(stderr, "&s.y = %p\n", &s.y); fprintf(stderr, "&s.y %% %lu = %lu\n", mod16, (uintptr_t)&s.y % mod16); } fprintf(stderr, "&collidePre = %p\n", &collidePre); fprintf(stderr, "&collidePost = %p\n", &collidePost); #pragma omp target data map(to:s.y, s.z) #pragma omp target data map(to:collidePre, collidePost) ; } #define TEST(StackPad) \ fprintf(stderr, "-------------------------------------\n"); \ fprintf(stderr, "StackPad=%s\n", #StackPad); \ test<StackPad>() int main() { TEST(char[1]); TEST(char[2]); TEST(char[3]); TEST(char[4]); TEST(char[5]); TEST(char[6]); TEST(char[7]); TEST(char[8]); TEST(char[9]); TEST(char[10]); TEST(char[11]); TEST(char[12]); TEST(char[13]); TEST(char[14]); TEST(char[15]); TEST(char[16]); // CHECK: pass printf("pass\n"); return 0; }
C
#include <errno.h> #include <assert.h> #include "redjson.h" #include "t-assert.h" const char placeholder[] = "placeholder"; int main() { const char *key, *val; const char *i; /* Happy path: we can start iterating over this valid object */ i = json_as_object("{" "\"a\": null," "\"true\": true," "\"sub\": {}," "\"a\": [1]," "\"z\": 0," "}"); assert(i); /* Its first member is "a":null */ assert((val = json_object_next(&i, &key))); assert(json_strcmp(key, "a") == 0); assert(json_is_null(val)); /* Its next member is "true":true */ assert((val = json_object_next(&i, &key))); assert(json_strcmp(key, "true") == 0); assert(json_as_bool(val)); /* Its next member is "sub":{} but we don't care about the key name */ assert((val = json_object_next(&i, NULL))); assert(json_type(val) == JSON_OBJECT); /* Its next member is also keyed "a" but has a different value * to the earlier member. */ assert((val = json_object_next(&i, &key))); assert(json_strcmp(key, "a") == 0); assert(json_type(val) == JSON_ARRAY); /* The last member is "z":0 */ assert((val = json_object_next(&i, &key))); assert(json_strcmp(key, "z") == 0); assert_errno(json_as_int(val) == 0, 0); /* There are no more members */ key = NULL; assert(!json_object_next(&i, &key)); assert(!key); /* The empty object yields a valid iterator */ assert((i = json_as_object("{}"))); /* Stepping to a non-existent member does not modify the key */ key = placeholder; assert(!json_object_next(&i, &key)); assert(key == placeholder); /* An extra comma is allowed in a simple object */ i = json_as_object("{\"a\":1,}"); assert(i); key = NULL; val = json_object_next(&i, &key); assert(json_strcmp(key, "a") == 0); assert(json_as_int(val) == 1); assert(!json_object_next(&i, &key)); assert(!json_object_next(&i, &key)); /* try it twice */ /* A bare comma in an empty object yields key=empty value=empty */ i = json_as_object("{,}"); assert(i); val = json_object_next(&i, &key); assert(key); assert(json_span(key) == 0); assert(val); assert(json_span(val) == 0); /* And a successive iteration fails */ assert(!json_object_next(&i, &key)); /* Bad inputs return NULL+EINVAL */ assert_errno(!json_as_object(NULL), EINVAL); assert_errno(!json_as_object(""), EINVAL); assert_errno(!json_as_object("[]"), EINVAL); assert_errno(!json_as_object("\"{}\""), EINVAL); assert_errno(!json_as_object("}"), EINVAL); assert_errno(!json_as_object(",{}"), EINVAL); /* Stepping a NULL object iterator has no effect */ i = NULL; key = placeholder; assert(!json_object_next(&i, &key)); assert(key == placeholder); /* We allow the extension of 'bare' words as keys and values */ i = json_as_object("{ name:Fred, age:99 }"); assert(i); assert((val = json_object_next(&i, &key))); assert(json_strcmp(key, "name") == 0); assert(json_strcmp(val, "Fred") == 0); assert((val = json_object_next(&i, &key))); assert(json_strcmp(key, "age") == 0); assert(json_as_int(val) == 99); assert(!json_object_next(&i, &key)); return 0; }
C
#include <stdio.h> #include <ctype.h> #include <cs50.h> #include <string.h> int main(void) { printf("Please input your full name: "); string s = get_string(); if (s != NULL) { char f = toupper(s[0]); printf("%c", f); // prints first letter, in uppercase for (int i = 0, n = strlen(s); i < n; i++) { if (s[i] == ' ') { char x = toupper(s[i+1]); printf("%c", x); //prints every letter after a space, in uppercase } } printf("\n"); } }
C
#include <stdio.h> #include <stdlib.h> struct a{ void (*f)(int); char * b; } ; void run_func(void (*f)(int), int a) { (*f)(a); } void print(int a){ printf("%d\n",a); } int main(int argc, char *argv[]) { struct a b; //b = (struct a*) malloc( sizeof(struct a)); b.f = print; b.b = "hello\n"; printf(b.b); run_func(b.f, 10); }
C
/** Author : Naufal Alee <naufalalee@gmail.com> * Date : 03-05-2017 **/ #include <stdio.h> float cel2fah (int cel); int main (int argc, char *argv[]) { int start, step, max, cel; float fah; start = 1; step = 20; max = 300; cel = 0; while (cel <= max){ printf("%d\t%.2f\n", cel, cel2fah(cel)); cel += step; } return 0; } float cel2fah (int cel) { float fah; float temp; fah = 32.0 + (((float)cel * 9.0) / 5.0); return fah; }
C
#include "lists.h" /** * lm7 - map over a linked list. * @l: the list * @q: the sought index * @f: the function to do at every node. * Return: the node count */ ll *lm7(ll *l, int q, void (*f)(ll **, ll *, int, int)) { int i = 0; ll *goal = (void *)0; ll *temp = (void *)0; ll *curr = l; while (curr != NULL) { temp = curr->next; f(&goal, curr, i, q); i++; curr = temp; } return (goal); } /** * getnode - get a node * @target: the goal * @c: the current * @i: the index * @q: the sought index */ void getnode(ll **target, ll *c, int i, int q) { if (q == i) *target = c; } /** * get_nodeint_at_index - function description * @head: parameter description * @index: parameter description * Return: return description */ listint_t *get_nodeint_at_index(listint_t *head, unsigned int index) { return (lm7(head, index, getnode)); }
C
#include <sys/types.h> #include <sys/socket.h> #include <sys/epoll.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "serveur.h" /* @brief * renvoyer un message (*data) au client (client_socket_fd) * * @params * client_socket_fd : Socket du client. * data : String contenant le message du client. * * @return * EXIT_FAILURE en cas d'erreur. */ int renvoie_message( int client_socket_fd, char *data ) { int data_size = write (client_socket_fd, (void *) data, strlen(data)); if (data_size < 0) { perror("erreur ecriture"); return(EXIT_FAILURE); } /* Error write */ } /* renvoie_message */ /* @brief * renvoyer un message du nom (*data) au client (client_socket_fd) * * @params * client_socket_fd : Socket du client. * data : String contenant le message du client (nom). * * @return * EXIT_FAILURE en cas d'erreur. */ int renvoie_nom_client( int client_socket_fd, char *data ) { int data_size = write (client_socket_fd, (void *) data, strlen(data)); if (data_size < 0) { perror("erreur ecriture"); return(EXIT_FAILURE); } /* Error write */ } /* renvoie_nom_client */ /* @brief * renvoyer le resultat du calcul (*data) au client (client_socket_fd) * * @params * client_socket_fd : Socket du client. * data : String contenant le message du client (opérateur et nombres). * * @return * EXIT_FAILURE en cas d'erreur. */ int recois_numero_calcule( int client_socket_fd, char *data ) { int data_size; char calcule[100], str[12], code[10], operation[5], number1[20], number2[20]; /* Get different string in data */ sscanf(data, "%s %s %s %s", code, operation, number1, number2); if (strstr(number1, ".") != NULL || strstr(number2, ".") != NULL) { /* Number float */ float result = 0.0; if(strcmp(operation, "+") == 0.0){ /* Case + */ result = atof(number1) + atof(number2); } else if(strcmp(operation, "-") == 0.0){ /* Case - */ result = atof(number1) - atof(number2); } else if(strcmp(operation, "*") == 0.0){ /* Case * */ result = atof(number1) * atof(number2); } else if(strcmp(operation, "/") == 0.0){ /* Case / */ result = atof(number1) / atof(number2); } else { /* Case error */ result = -1.0; } sprintf(str, "%.2f", result); } else { /* Number int */ int result = 0; if(strcmp(operation, "+") == 0){ /* Case + */ result = atoi(number1) + atoi(number2); } else if(strcmp(operation, "-") == 0){ /* Case - */ result = atoi(number1) - atoi(number2); } else if(strcmp(operation, "*") == 0){ /* Case * */ result = atoi(number1) * atoi(number2); } else if(strcmp(operation, "/") == 0){ /* Case / */ result = atoi(number1) / atoi(number2); } else { /* Case error */ result = -1; } sprintf(str, "%d", result); } strcpy(calcule, "calcule: "); strcat(calcule, str); data_size = write (client_socket_fd, (void *) calcule, strlen(calcule)); if (data_size < 0) { perror("erreur ecriture"); return(EXIT_FAILURE); } /* Error write */ } /* recois_numero_calcule */ /* @brief * envoyer la confirmation d'enregistrement des couleurs (*data) * au client (client_socket_fd) * * @params * client_socket_fd : Socket du client. * data : String contenant le message du client (nombre de couleurs et les couleurs). * * @return * EXIT_FAILURE en cas d'erreur. */ int recois_couleurs( int client_socket_fd, char *data ) { char code[10], save[20], str[10], number_c[10]; int i, n; FILE *fp; /* Get number of colors */ sscanf(data, "%s %s", code, number_c); n = atoi(number_c); /* Open the save file */ fp = fopen("save.txt", "a+"); /* Go to the first color */ while(*data != ','){ data++; } /* While we dont find a "," */ data++; data++; for(i = 0; i < n; i++){ int j = 0; while(*data != ',' && *data != '\0'){ if(j <= 6){ str[j] = *data; } /* We save just 7 char because a color has 7 char */ data++; j++; } /* While we dont find a "," or "\0" */ if(i < n-1){ data++; data++; } /* If the last we dont increment */ /* Put the color into the file */ fputs(str, fp); fputs("\n", fp); } /* For each color */ fclose(fp); strcpy(save, "couleurs: enregistré"); int data_size = write (client_socket_fd, (void *) save, strlen(save)); if (data_size < 0) { perror("erreur ecriture"); return(EXIT_FAILURE); } /* Error write */ } /* recois_couleurs */ /* @brief * accepter la nouvelle connection d'un client et lire les données * envoyées par le client. En suite, le serveur envoie un message * en retour * * @params * socketfd : Socket. * * @return * EXIT_FAILURE en cas d'erreur. */ int recois_envoie_message( int socketfd ) { struct sockaddr_in client_addr; char data[1024]; int client_addr_len = sizeof(client_addr); // nouvelle connection de client int client_socket_fd = accept(socketfd, (struct sockaddr *) &client_addr, &client_addr_len); if (client_socket_fd < 0 ) { perror("accept"); return(EXIT_FAILURE); } /* Error de connexion */ memset(data, 0, sizeof(data)); //lecture de données envoyées par un client int data_size = read (client_socket_fd, (void *) data, sizeof(data)); if (data_size < 0) { perror("erreur lecture"); return(EXIT_FAILURE); } /* Error read */ printf ("Message recu: %s\n", data); char code[10]; sscanf(data, "%s:", code); if (strcmp(code, "message:") == 0) { /* Si le message commence par le mot: 'message:' */ char message[100]; printf("Votre message (max 1000 caracteres): "); fgets(message, 1024, stdin); strcpy(data, "message: "); strcat(data, message); renvoie_message(client_socket_fd, message); } else if(strcmp(code, "nom:") == 0){ /* Si le message commence par le mot: 'nom:' */ renvoie_nom_client(client_socket_fd, data); } else if(strcmp(code, "calcule:") == 0){ /* Si le message commence par le mot: 'calcule:' */ recois_numero_calcule(client_socket_fd, data); } else if(strcmp(code, "couleurs:") == 0){ /* Si le message commence par le mot: 'couleurs:' */ recois_couleurs(client_socket_fd, data); } //fermer le socket close(socketfd); } /* recois_envoie_message */ int main() { int socketfd; int bind_status; int client_addr_len; struct sockaddr_in server_addr, client_addr; /* * Creation d'un socket */ socketfd = socket(AF_INET, SOCK_STREAM, 0); if ( socketfd < 0 ) { perror("Unable to open a socket"); return -1; } /* Cant open the socket */ int option = 1; setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)); //détails du serveur (adresse et port) memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(PORT); server_addr.sin_addr.s_addr = INADDR_ANY; bind_status = bind(socketfd, (struct sockaddr *) &server_addr, sizeof(server_addr)); if (bind_status < 0 ) { perror("bind"); return(EXIT_FAILURE); } /* Error bind */ listen(socketfd, 10); recois_envoie_message(socketfd); return 0; } /* main */
C
#include <pebble.h> Window *window; TextLayer *text_layer; void init() { // Create the Window window = window_create(); // Push to the stack, animated window_stack_push(window, true); // Create the TextLayer, for display at (0, 0), // and with a size of 144 x 40 text_layer = text_layer_create(GRect(0, 0, 144, 40)); // Set the text that the TextLayer will display text_layer_set_text(text_layer, "Hello, Pebble!"); // Add as child layer to be included in rendering layer_add_child( window_get_root_layer(window), text_layer_get_layer(text_layer) ); } void deinit() { // Destroy the Window window_destroy(window); // Destroy the TextLayer text_layer_destroy(text_layer); } int main(void) { // Initialize the app init(); // Wait for app events app_event_loop(); // Deinitialize the app deinit(); // App finished without error return 0; }
C
#ifndef _RB_TREE_H_ #define _RB_TREE_H_ #include <stdlib.h> #include "utils.h" typedef enum { IN, PRE, POST } ORDER; typedef enum { RED, BLACK } COLOR; typedef struct tree_node { void *data; struct tree_node *parent; struct tree_node *left; struct tree_node *right; COLOR color; } tree_node_t; typedef struct rbtree { tree_node_t *root; unsigned data_size; unsigned size; int (*compare)(void*,void*,unsigned); void (*free_func)(void*); } rbtree_t; rbtree_t* create_tree(unsigned data_size, int (*comp)(void*, void*, unsigned)); void tree_set_comp_func(rbtree_t *tree, int (*comp)(void*, void*, unsigned)); void tree_set_free_func(rbtree_t *tree, void (*free_func)(void*)); tree_node_t* tree_insert(rbtree_t *tree, void *data); void* tree_remove(rbtree_t *tree, tree_node_t *node); tree_node_t* tree_search(rbtree_t *tree, void *data); void tree_traverse(rbtree_t *tree, ORDER order, void (*op)(void*)); void* tree_min(rbtree_t *tree); void* tree_max(rbtree_t *tree); tree_node_t* _grandparent(tree_node_t *node); tree_node_t* _sibling(tree_node_t *node); tree_node_t* _uncle(tree_node_t *node); tree_node_t* _pred(tree_node_t *node); tree_node_t* _succ(tree_node_t *node); void destroy_tree(rbtree_t *tree); #endif
C
/* * Our binary search makes two tests inside the loop, when one would * suffice (at the price of more tests outside). Write a version with * only one test inside the loop and measure the difference in run-time. */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> /* Microsecond timestamp function */ int64_t utime_now(void) { struct timeval tv; gettimeofday(&tv, NULL); return (int64_t) tv.tv_sec*1000000 + tv.tv_usec; } /* binsearch: find x in v[0] <= v[1] <= ... <= v[n-1] */ int binsearch1(int x, int v[], int n) { int low, high, mid; low = 0; high = n-1; while (low <= high) { mid = (low + high) / 2; if (x < v[mid]) high = mid - 1; else if (x > v[mid]) low = mid + 1; else return mid; } return -1; } /* binsearch: find x in v[0] <= v[1] <= ... <= v[n-1] */ int binsearch2(int x, int v[], int n) { int low, high, mid; low = 0; high = n-1; while (low < high) { mid = (low + high) / 2; if (x <= v[mid]) high = mid; else low = mid + 1; } return (x == v[low]) ? low : -1; } int main(void) { int v[10] = {1, 3, 6, 9, 12, 18, 20, 22, 24, 25}; int x = 2; int index1, index2; int64_t t1, t2, t3, t4; t1 = utime_now(); index1 = binsearch1(x, v, 10); t2 = utime_now(); t3 = utime_now(); index2 = binsearch2(x, v, 10); t4 = utime_now(); printf("%d %d\n", index1, index2); printf("Used time: %ld\n", t2 - t1); printf("Used time: %ld\n", t4 - t3); return EXIT_SUCCESS; }
C
/*#include<stdio.h> #include<conio.h> void main() { int i=2; clrscr(); while(i<=20) { printf("%d\n",i); i=i+2; } getch(); }*/ #include<stdio.h> #include<conio.h> void main() { int a[2][2],b[2][2],c[2][2]; int i,j; clrscr(); for(i=0;i<2;i++) { for(j=0;j<4;j++) { c[i][j]=0; } } printf("\n enter first matrix"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { scanf("%d",&a[i][j]); } } printf("\n enter second matrix"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { scanf("%d",&b[i][j]); } } printf("\n multipication of matrix is"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { c[i][j]=c[i][j]+a[i][j]*b[i][j]; } } printf("\n"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf("5%d\t",c[i][j]); } printf("\n"); } getch(); } /* #include<stdio.h> #include<conio.h> void main() { int total,boys; clrscr(); printf("\n\t\t welcome to boys school"); printf("\n\n enter the total"); scanf("%d",&total); boys=(total>0)?total:0; printf("\n number of boys is %d",boys); getch(); }*/ /* #include<stdio.h> #include<conio.h> void main() { int n1,n2,choice; clrscr(); printf("\n enter two numbers\n"); scanf("%d %d",&n1,&n2); printf("\n1 additiom"); printf("\n2 subtraction"); printf("\n enter your choice"); scanf("%d",&choice); switch(choice) { case 1: printf("\n tne addition of two num is %d",n1+n2); break; case 2: printf("\n tne subtraction of two num is %d",n1-n2); break; } getch(); } */ /* #include<stdio.h> #include<conio.h> void main() { int num; clrscr(); printf("enter the num"); scanf("%d",&num); if(num%2==0) { printf("\n num is even"); } else { printf("\n the num is odd"); } getch(); }*/ /* #include<stdio.h> #include<conio.h> void main() { int num=1,square; while(num<=10) { square=num*num; printf("\n number=%d and its square=%d",num,square); num=num+1; } getch(); }*/ /*#include<stdio.h> #include<conio.h> # define MAX 100 void main() { int arr[MAX],n,i,temp; clrscr(); printf("enter size of arry: "); scanf("%d",&n); printf("enter %d element\n",n); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } for(i=0;i<n/2;i++) { temp=arr[i]; arr[i]=arr[n-i-1]; arr[n-i-1]=temp; } printf("array after reversing :"); for(i=0;i<n;i++) { printf("%d\t\n",arr[i]); } getch(); }*/ /* #include<stdio.h> #include<conio.h> #include<string.h> void main() { char str[10]="hello",str2[1]; clrscr(); strcpy (str2,str); printf("\n the string2 is %s",str2); getch(); }*/ /*#include<stdio.h> #include<conio.h> #include<string.h> void main() { char str[10],str2[20]; int i; clrscr(); printf("\n enter two strings\n"); scanf("%s %s",&str,&str2); i=strcmp(str,str2); if(i==0) { printf("\n both string are same"); } else { printf("\n string are different"); } getch(); }*/ /* #include<stdio.h> #include<conio.h> void main() { char str[20],str2[20]; clrscr(); printf("\n enter two strings\n"); scanf(" %s %s",&str,&str2); strcat (str,str2); printf(" string joined are %s",str); getch(); }*/ /* #include<stdio.h> #include<conio.h> #include<string.h> void main() { char str[10]; int len; clrscr(); printf("enter a string\n"); gets(str); len = strlen(str); printf("\n the length of string is %d",len); getch(); }*/ /* #include<stdio.h> #include<conio.h> void main() { int a[4]={10,20,30,40}; clrscr(); printf("\n declaration of arry"); printf("\n %d",a[0]); printf("\n %d",a[1]); printf("\n %d",a[2]); printf("\n %d",a[3]); getch(); }*/ /* #include<stdio.h> #include<conio.h> void main() { int a[5],min,i; clrscr(); printf("enter element of the array\n"); for(i=0;i<5;i++) scanf("%d",&a[i]); min=a[0]; for(i=1;i<5;i++) { if(min>a[i]) min=a[i]; } printf("minimun no= %d",min); getch(); }*/ /* #include<stdio.h> #include<conio.h> void main() { int a[5],i,mul; clrscr(); printf("\n enter the element of array\n"); for(i=0;i<5;i++) scanf("%d",&a[i]); for(i=0;i<5;i++) mul=mul*a[i]; printf("multiplication=%d\n",mul); getch(); }*/ /* #include<stdio.h> #include<conio.h> void main() { int a[2][3],b[2][3],c[2][3]; int i,j; clrscr(); printf("\n enter first matrix"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { scanf("%d",&a[i][j]); } } printf("\n enter second matrix"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { scanf("%d",&b[i][j]); } } printf("\n the addition of matrix is :"); for(i=0;i<2;i++) { for(j=0;j<2;j++) c[i][j]=a[i][j]+b[i][j]; } for(i=0;i<2;i++) { printf("\n"); for(j=0;j<2;j++) { printf("%d\t",c[i][j]); } getch(); }*/ /* #include<stdio.h> #include<conio.h> void main() { int i,j; clrscr(); for(i=1;i<=4;i++) { for(j=1;j<=i;j++) { printf("\n%d",j); } printf("\n"); } getch(); }*/ /* #include<stdio.h> #include<conio.h> #include<graphics.h> void main() { int gd=DETECT,gm; initgraph(& gd,&gm,"C:\\TC\\BGI"); arc(200,250,0,150,60); getch(); closegraph(); }*/
C
/* * File: ports.c * * Edit these functions to port the code to your platform */ #include <stdint.h> #include "ports.h" #include "error.h" // RaspberryPi SPI library // Test if need to use mocks if not compiling on RaspberryPi #ifdef __arm__ #include <wiringPiSPI.h> #else #include "mocks/mock_wiringPiSPI.h" #endif /* spiInit: Initialize SPI device. * * Args: pointer to integer file_descriptor * Return: error status. '0' on success. * WiringPi returns '-1' on error. */ uint8_t spiInit(int *file_descriptor){ *file_descriptor = wiringPiSPISetup(SPI_CHANNEL, SPI_SPEED); if (*file_descriptor != -1){ return 0; } else{ errvar = ERROR_SPI_INIT_FAIL; return 1; } } /* spiWrite: Write 'num_bytes' from the 'data' buffer to SPI device. * * Return: error status. '0' on success. * Array is copied, because WiringPi overwrites 'buffer' array. * WiringPi uses 'ioctl' in the manner: * ioctl (spiFds [channel], SPI_IOC_MESSAGE(1), &spi) * It returns positive value on success. */ uint8_t spiWrite(uint8_t *data, uint8_t num_bytes){ static uint8_t buffer[SPI_BUFFER_SIZE]; uint8_t i; for (i=0; i<num_bytes; i++){ buffer[i] = data[i]; } uint8_t err; err = wiringPiSPIDataRW(SPI_CHANNEL, buffer, num_bytes); if (err > 0 ){ return 0; } else{ errvar = ERROR_SPI_WRITE_FAIL; return 1; } } /* spiRW: Write data to SPI device and synchronously read it * * The number of bytes 'num_bytes' is read from 'data' and th read data is * saved back to it. Synchronous operation. * * Return: error status. '0' on success. * * Works as a simple wrapper for wiringPi's function * WiringPi uses 'ioctl' in the manner: * ioctl (spiFds [channel], SPI_IOC_MESSAGE(1), &spi) * It returns positive value on success. */ uint8_t spiRW(uint8_t *data, uint32_t num_bytes){ uint8_t err; err = wiringPiSPIDataRW(SPI_CHANNEL, data, num_bytes); if (err > 0 ){ return 0; } else{ errvar = ERROR_SPI_WRITE_FAIL; return 1; } }
C
#include <stdio.h> int main() { char ch; printf("Enter the alphabet character: "); scanf("%ch", &ch); printf("%d - in ASCII\n", ch); if (ch >= 'A' && ch <= 'Z') printf("%c - is alphabet uppercase", ch); else if (ch >= 'a' && ch <= 'z') printf("%c - is alphabet lowercase", ch); else printf("%c - is not an alphabet character", ch); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main2_3(){ int i = 0; int count = 0; while (i < 10){ //whileѭѭ . //printf("%d\n", i); if (i < 1) continue; if (i == 5) break; i++; //printf("%d\n", i); } //printf("%d\n", count); system("pause"); return 0; }
C
#include "parser.h" #include <stdlib.h> #include <string.h> #include <stdio.h> struct parser* create_parser(){ struct parser *parser = calloc(1, sizeof(struct parser)); parser->history = NULL; parser->commands = create_container(NULL, COMMAND, create_command("NORTH", "Move in the north direction.", "north", 1)); create_container(parser->commands, COMMAND, create_command("SOUTH", "Move in the south direction.", "south", 1)); create_container(parser->commands, COMMAND, create_command("EAST", "Move in the east direction.", "east", 1)); create_container(parser->commands, COMMAND, create_command("SOUTH", "Move in the west direction.", "west", 1)); create_container(parser->commands, COMMAND, create_command("UP", "Move up.", "up", 1)); create_container(parser->commands, COMMAND, create_command("DOWN", "Move down.", "down", 1)); create_container(parser->commands, COMMAND, create_command("INVENTORY", "Display the content of backpack.", "(inventory)|(backpack)", 1)); create_container(parser->commands, COMMAND, create_command("SAVE", "Save the game progress on disk.", "((save)|(save game)|(save progress))", 3)); create_container(parser->commands, COMMAND, create_command("LOAD", "Game progress will be loaded from the disk.", "(LOAD)", 1)); create_container(parser->commands, COMMAND, create_command("END", "Command ends the current game without saving.", "((QUIT)|(EXIT))", 2)); create_container(parser->commands, COMMAND, create_command("RESTART", "Play the game again from the very beginning.", "(RESTART)", 1)); create_container(parser->commands, COMMAND, create_command("EXPLORE AREA", "Display actual information about area where player is located now.", "(EXPLORE)", 1)); create_container(parser->commands, COMMAND, create_command("COMMANDS", "Show all commands the game provided with.", "((HELP)|(COMMANDS))", 2)); create_container(parser->commands, COMMAND, create_command("VERSION", "Display actual info about the version of the game and author contacts.", "(VERSION)", 1)); create_container(parser->commands, COMMAND, create_command("ABOUT", "Display short game description and preface.", "(ABOUT)", 1)); create_container(parser->commands, COMMAND, create_command("INTERACT", "Inetarct (talk) with different characters.", "(interact)|(talk)|(ask)|(speak)", 2)); create_container(parser->commands, COMMAND, create_command("TAKE", "Pick up something and lay it down to backpack", "(TAKE) *(.*)", 2)); create_container(parser->commands, COMMAND, create_command("DROP", "Drop something from the backpack.", "(DROP) *(.*)", 2)); create_container(parser->commands, COMMAND, create_command("USE", "Use something from backpack or area.", "(USE) *(.*)", 2)); create_container(parser->commands, COMMAND, create_command("DESCRY", "Observe the thing.", "((DESCRY) *(.*))|((OBSERVE) *(.*))|((EXAMINE) *(.*))", 2)); return parser; } struct parser* destroy_parser(struct parser* parser){ if(parser==NULL) return NULL; parser->history = destroy_containers(parser->history); parser->commands = destroy_containers(parser->commands); free(parser); return NULL; } struct command* parse_input(struct parser* parser, char* input){ if(parser == NULL || input == NULL) return NULL; struct container *ptr = parser->commands; int flag = 0; regmatch_t groups[5]; while(ptr != NULL){ if(regexec(&ptr->command->preg, input, ptr->command->nmatch+1, groups, 0) != REG_NOMATCH){ flag = 1; break; } ptr = ptr->next; } if(flag == 0){ printf("Sorry, i din't understand. May you say again?\n"); return NULL; } if(ptr->command->nmatch!=2) return ptr->command; struct command* com = ptr->command; com->groups = (char**)calloc(com->nmatch, sizeof(char*)); for(int i = 1, n=0; i < com->nmatch+1; i++, n++){ com->groups[n] = (char*)calloc((size_t)(groups[i].rm_eo-groups[i].rm_so)+1, sizeof(char)); strncpy(com->groups[n], &input[groups[i].rm_so], (size_t)(groups[i].rm_eo-groups[i].rm_so)); com->groups[n][groups[i].rm_eo-groups[i].rm_so]='\0'; } return ptr->command; }
C
#include<stdio.h> int call_by_val(int,int,int); int call_by_val(int x,int y,int z) { printf("\n original values are: %d %d %d.",x,y,z); x+=100; y+=101; z+=102; printf("\n after changing the values:%d %d %d.",x,y,z); } int main() { int ratna,nipu,romi; ratna=1; nipu=2; romi=3; call_by_val(ratna,nipu,romi); printf("\n after function calling: %d %d %d",ratna,nipu,romi); return 0; }
C
pub typedef { int size; const char *keys[200]; void *values[200]; } map_t; /* * Creates a new map instance. */ pub map_t *map_new() { map_t *m = calloc(1, sizeof(map_t)); return m; } /* * Frees the given instance of map. */ pub void map_free(map_t *m) { free(m); } /* * Assigns value to given key */ pub void map_set(map_t *m, const char *key, void *val) { int pos = find(m, key); if (pos < 0) { pos = m->size++; } m->keys[pos] = key; m->values[pos] = val; } /* * Returns true if given key exists. */ pub bool map_has(map_t *m, const char *key) { return find(m, key) >= 0; } /* * Returns the value from the given key. * Returns null if there is no entry with the given key. * If entries can themselves be nulls, use map_has for explicit checks. */ pub void *map_get(map_t *m, const char *key) { int pos = find(m, key); if (pos < 0) { return NULL; } return m->values[pos]; } int find(map_t *m, const char *key) { for (int i = 0; i < m->size; i++) { if (!strcmp(key, m->keys[i])) { return i; } } return -1; } pub typedef { map_t *map; int pos; } map_iter_t; pub map_iter_t *map_iter(map_t *m) { map_iter_t *it = calloc(1, sizeof(map_iter_t)); it->map = m; it->pos = -1; return it; } pub bool map_iter_next(map_iter_t *it) { if (it->pos + 1 >= it->map->size) { return false; } it->pos++; return true; } pub const char *map_iter_key(map_iter_t *it) { return it->map->keys[it->pos]; } pub void *map_iter_val(map_iter_t *it) { return it->map->values[it->pos]; } pub void map_iter_free(map_iter_t *it) { free(it); }
C
#ifndef PARSE_H #define PARSE_H #include "snippet.h" #include "draw.h" #include <stdarg.h> triplet parseFormatting(couplet startSplit, const char* end, snippetFn drawFn) // startSplit: ...((... // endSplit: ((...))... { if(!startSplit.tail.start || isSpaceChar(*(startSplit.tail.start))) return tripletFail; couplet endSplit = splitAt(startSplit.tail, end); if(!endSplit.head.end || isSpaceChar(*(endSplit.head.end))) return tripletFail; triplet result = { {startSplit.head.start, startSplit.head.end, NULL}, {endSplit.head.start, endSplit.head.end, drawFn}, {endSplit.tail.start, endSplit.tail.end, NULL} }; return result; } #define listSize 16 triplet firstMatch(snippet text, ...) { const char *starts[listSize], *ends[listSize]; snippetFn functions[listSize]; int indices[listSize], inOrder[listSize]; // va stuff int listLen = 0; va_list args; va_start(args, text); while(starts[listLen] = va_arg(args, const char*)) { ends[listLen] = va_arg(args, const char*); functions[listLen] = va_arg(args, snippetFn); indices[listLen] = indexOf(text, starts[listLen]); listLen++; } // Sort int lastMin = -1; for(int i = 0; i < listLen; i++) { int currentMin = sniplen(text); inOrder[i] = -1; for(int j = 0; j < listLen; j++) { if(indices[j] >=0 && indices[j] < currentMin && indices[j] > lastMin) { inOrder[i] = j; currentMin = indices[j]; } } lastMin = currentMin; } // Try each match triplet parseResult = tripletFail; for(int i = 0; i < listLen; i++) { int format = inOrder[i]; if(format == -1) break; parseResult = parseFormatting( splitAt(text, starts[format]), ends[format], functions[format] ); if(parseResult.head.start && *(parseResult.head.start)) break; } return parseResult; } void parsePar(snippet line) { assert(line.start && *(line.start) && line.start != line.end, ); triplet parsed = firstMatch(line, "((", "))", drawFade, "[[", "]]", drawAccent, "_", "_", drawItalic, "**", "**", drawBold, "<", ">", drawTag, "`", "`", drawMono, NULL); if(!parsed.head.start) { drawNormal(line); } else { // head is normal drawNormal(parsed.head); // middle is formatted parsed.middle.fn(parsed.middle); // parse the rest parsePar(parsed.tail); } } void parse(snippet text) { assert(text.start && *(text.start), ); couplet lineSplit = splitAt(text, "\n"); snippet line = lineSplit.head; snippet word1 = word(text, 1); if(startsWith(word1, "|")) { line = fromWord(line, 2); highlightStart(); } parsePar(line); drawNewLine(); if(startsWith(word1, "|")) { highlightEnd(sniplen(word1)); } parse(lineSplit.tail); } #endif
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <stdbool.h> int main(int argc, const char * argv[]) { int cases; scanf("%d", &cases); printf("Lumberjacks:\n"); for (int i = 0; i < cases; ++i) { int length[10]; for (int j = 0; j < 10; ++j) { scanf("%d", &length[j]); } int ascCount = 1; for (int j = 0; j < 9 && length[j] < length[j+1]; ++j) { ++ascCount; } int descCount = 1; for (int j = 0; j < 9 && length[j] > length[j+1]; ++j) { ++descCount; } printf("%s\n", (ascCount == 10 || descCount == 10) ? "Ordered" : "Unordered"); } return 0; }
C
#include "file_recognizer.h" #include <stdio.h> void readfile(const char *filename) { FILE *fp = fopen(filename, "r"); unsigned char arr[8]; int correct = 1; int i; if (fp == 0) { printf("Invalid input.\n"); }else { fread(arr, 1, 8, fp); /*for (int i = 0; i < 8; i++) { printf("arr[%d] = %lx\n", i, arr[i]); }*/ fclose(fp); /*test GIF*/ for (i = 0; i < 6; i++) { if (arr[i] == allfiles[0].signature[i] || arr[i] == allfiles[1].signature[i]) { correct = 1; }else { correct = 0; break; } } if (correct == 1) { printf("%s\n", allfiles[0].type); return; } /*test ELF*/ for (i = 0; i < 4; i++) { if (arr[i] == allfiles[2].signature[i]) { correct = 1; }else { correct = 0; break; } } if (correct == 1) { printf("%s\n", allfiles[2].type); return; } /*test PDF*/ for (i = 0; i < 4; i++) { if (arr[i] == allfiles[3].signature[i]) { correct = 1; }else { correct = 0; break; } } if (correct == 1) { printf("%s\n", allfiles[3].type); return; } /*test ZIP*/ for (i = 0; i < 2; i++) { if (arr[i] == allfiles[4].signature[i]) { correct = 1; }else { correct = 0; break; } } if (correct == 1) { printf("%s\n", allfiles[4].type); return; } /*test Java*/ for (i = 0; i < 4; i++) { if (arr[i] == allfiles[5].signature[i]) { correct = 1; }else { correct = 0; break; } } if (correct == 1) { printf("%s\n", allfiles[5].type); return; } /*test PNG*/ for (i = 0; i < 8; i++) { if (arr[i] == allfiles[6].signature[i]) { correct = 1; }else { correct = 0; break; } } if (correct == 1) { printf("%s\n", allfiles[6].type); return; } printf("File type unknown.\n"); } } int main(int argc, char const *argv[]) { if (argc != 2) { printf("Invalid input.\n"); }else { readfile(argv[1]); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "tree.h" void TreeBiCreat(BiTree *root); void TreePreDisplay(BiTree *root); void TreeInDisplay(BiTree *root); void TreeBackDisplay(BiTree *root); void InThread0(BiTree root,BiTree *pre); void InThread(BiTree root,BiTree *head); Status TreeInThreadDisplay(BiTree head); int main(void) { BiTree root; TreeBiCreat(&root); TreePreDisplay(&root); printf("\n"); TreeInDisplay(&root); printf("\n"); TreeBackDisplay(&root); printf("\n"); BiTree head = (BiTree)malloc(sizeof(Node)); InThread(root,&head); TreeInThreadDisplay(head); return 0; } void TreeBiCreat(BiTree *root) { ElemType ch; scanf("%c",&ch); if(ch == '#'){ *root = NULL; }else{ *root = (Node *)malloc(sizeof(Node)); if(*root == NULL) exit(1); (*root)->data = ch; TreeBiCreat(&((*root)->lchild)); TreeBiCreat(&((*root)->rchild)); } } void TreePreDisplay(BiTree *root) { if(*root == NULL) return; printf("%c ",(*root)->data); TreePreDisplay(&((*root)->lchild)); TreePreDisplay(&((*root)->rchild)); } void TreeInDisplay(BiTree *root) { if(*root == NULL) return; TreeInDisplay(&((*root)->lchild)); printf("%c ",(*root)->data); TreeInDisplay(&((*root)->rchild)); } void TreeBackDisplay(BiTree *root) { if(*root == NULL) return; TreeBackDisplay(&((*root)->lchild)); TreeBackDisplay(&((*root)->rchild)); printf("%c ",(*root)->data); } void InThread0(BiTree root,BiTree *pre) { if(root != NULL){ InThread0(root->lchild,pre); if(root->lchild == NULL){ root->ltag = Thread; root->lchild = *pre;//当前节点的前驱 } if((*pre)->rchild == NULL){ (*pre)->rtag = Thread; (*pre)->rchild = root;//上一节点的后区 } *pre = root; InThread0(root->rchild,pre); } } void InThread(BiTree root,BiTree *head) { if(*head == NULL) *head = (BiTree) malloc(sizeof(Node)); if(*head == NULL) exit(1); (*head)->ltag = Link; (*head)->rtag = Thread; (*head)->rchild = *head; if(root == NULL){ (*head)->lchild = *head; //root为NULL 自己指向自己 }else{ (*head)->lchild = root; BiTree pre = *head; //中序遍历的第一个节点的前驱为head InThread0(root,&pre); pre->rtag = Thread;//线索化结束后pre为最后一个节点 pre->rchild = *head; //pre的后驱改为head (*head)->rchild = pre; } } Status TreeInThreadDisplay(BiTree head) { BiTree p = head->lchild; if(head == NULL)return ERR; while(p != head){ //由原有关系找到叶节点然后由下往上按照线索遍历 while(p->ltag == Link) p = p->lchild; printf("%c ",p->data); while(p->rtag==Thread && p->rchild!=head){ p = p->rchild; printf("%c ",p->data); } p = p->rchild; } return OK; }
C
#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <string.h> #define N 128 struct fun_1 { char fio[N]; int gruop; int semestr[2]; }; struct fun_2 { int fiz; int mat; int angl; int oaip; }; struct fun_3 { int georgafi; int chem; int mat2; int fiz2; }; int main (int argc, char *argv[2]) { int ind1=0,ind2=0,ind3=0,zapret=0; struct fun_1 cp_1[N]; struct fun_2 cp_2[N]; struct fun_3 cp_3[N]; FILE *file,*file2; char *fname = "d:/githubdir/index.txt"; char *foutt ="d:/githubdir/out.txt"; char result_sting[N]; char buffer[N][N]; char fake[N]={}; file = fopen(fname,"r"); int i=0,x=1; while (fscanf (file, "%s%d%d%d%d%d%d%d%d%d%d%d", cp_1[i].fio, &(cp_1[i].gruop), &(cp_1[i].semestr[0]), &(cp_2[i].angl), &(cp_2[i].fiz),&(cp_2[i].mat),&(cp_2[i].oaip),&(cp_1[i].semestr[1]),&(cp_3[i].chem),&(cp_3[i].fiz2),&(cp_3[i].georgafi),&(cp_3[i].mat2) ) != EOF) { i++; ind2++; ind3++; } fclose(file); if (argc==1) { printf(" No param is find\n"); printf("Usage foo param \n"); printf("Where param mean \n"); printf("-e - enter stucturs \n"); printf("-p - print structurs in file \n"); printf("-x - find max marke \n"); printf("-n - find min marke \n"); printf("-h - information \n"); } else { for(int i=0;i<argc;i++) { if(argv[i][0]=='-' && argv[i][1]=='h') { printf("================================================================================\n" " Help:\n\n" "Commands: \\e \\p \\x \\n \n\n" "\\e - Structure input\n" " 1) Enter the name of the student. \n" " 1) Enter the group number. \n" " 3) Enter marks. Marks should be integers from 1 to 10.\n" "\\p - Print whole structure.\n" " Print all entries in file.\n\n" "\\x - Searching for the maximum average of exam\n" " Displays the maximum average of exams.\n\n" "\\n - Searching for the minimum average of exam\n" " Displays the minimum average of exams.\n\n" "================================================================================\n"); exit(0); } if(argv[i][0]=='-' && argv[i][1]=='e') { int kol; printf("information on how many students want to enter ?"); scanf_s("%d",&kol); ind2+=kol; for(int i=0;i<kol;i++) { printf("enter Name\n"); fflush(stdin); for(int j=0;j<1;){ if( strcmp(gets_s(cp_1[i+ind3].fio),fake) == 0 ) {printf("Enter name agein");} else j++; } printf("enter nomber of group"); scanf_s("%d",& cp_1[i+ind3].gruop); cp_1[i+ind3].semestr[0]=1; printf("term 1 :english = "); scanf_s("%d",& cp_2[i+ind3].angl); printf("term 1 :physics = "); scanf_s("%d",& cp_2[i+ind3].fiz); printf("term 1 :mathem = "); scanf_s("%d",& cp_2[i+ind3].mat); printf("term 1 :oaip = "); scanf_s("%d",& cp_2[i+ind3].oaip); cp_1[i+ind3].semestr[1]=2; printf("term 2 :chem = "); scanf_s("%d",& cp_3[i+ind3].chem); printf("term 2 :physics = "); scanf_s("%d",& cp_3[i+ind3].fiz2); printf("term 2 :geography = "); scanf_s("%d",& cp_3[i+ind3].georgafi); printf("term 2 :mathem = "); scanf_s("%d",& cp_3[i+ind3].mat2); } ind3+=kol; zapret=1; break; } if(argv[i][0]=='-' && argv[i][1]=='p' ) { file2 = fopen(foutt,"w"); for(i=0;i<ind2;i++) fprintf(file2,"%s %3d%3d%3d%3d%3d%3d%3d%3d%3d%3d%3d \n", cp_1[i].fio, (cp_1[i].gruop), (cp_1[i].semestr[0]), (cp_2[i].angl), (cp_2[i].fiz),(cp_2[i].mat),(cp_2[i].oaip),(cp_1[i].semestr[1]),(cp_3[i].chem),(cp_3[i].fiz2),(cp_3[i].georgafi),(cp_3[i].mat2) ); fclose(file2); printf("Information print in file ' out.txt ' \n"); break; } if(argv[i][0]=='-' && argv[i][1]=='x') { float max1,middle_markes2[2][20],max2; int sem,ind5[2]={0,0}; for(int i=0;i<ind2;i++) { middle_markes2[0][i]=(cp_2[i].angl + cp_2[i].fiz + cp_2[i].mat + cp_2[i].oaip)/4.; middle_markes2[1][i]=(cp_3[i].chem + cp_3[i].fiz2 + cp_3[i].georgafi + cp_3[i].mat2)/4.; } max1=middle_markes2[0][0]; max2=middle_markes2[1][0]; for(int i=0;i<ind2;i++) { if(middle_markes2[0][i]>max1) { max1=middle_markes2[0][i]; ind5[0]=i; } if(middle_markes2[1][i]>max2) { max2=middle_markes2[1][i]; ind5[1]=i; } } printf("the results of what the term ? 1-first, 2- second"); scanf_s("%d",&sem); if(sem==1) { printf("Fio group term english physics mathem oaip term chem physics geography mathem \n"); printf("%s %3d%3d%3d%3d%3d%3d%3d%3d%3d%3d%3d \n", cp_1[ind5[0]].fio, (cp_1[ind5[0]].gruop), (cp_1[ind5[0]].semestr[0]), (cp_2[ind5[0]].angl), (cp_2[ind5[0]].fiz),(cp_2[ind5[0]].mat),(cp_2[ind5[0]].oaip),(cp_1[ind5[0]].semestr[1]),(cp_3[ind5[0]].chem),(cp_3[ind5[0]].fiz2),(cp_3[ind5[0]].georgafi),(cp_3[ind5[0]].mat2) ); printf("\n averge = %f", max1); } else { printf("Fio group term english physics mathem oaip term chem physics geography mathem \n"); printf("%s %3d%3d%3d%3d%3d%3d%3d%3d%3d%3d%3d \n", cp_1[ind5[1]].fio, (cp_1[ind5[1]].gruop), (cp_1[ind5[1]].semestr[0]), (cp_2[ind5[1]].angl), (cp_2[ind5[1]].fiz),(cp_2[ind5[1]].mat),(cp_2[ind5[1]].oaip),(cp_1[ind5[1]].semestr[1]),(cp_3[ind5[1]].chem),(cp_3[ind5[1]].fiz2),(cp_3[ind5[1]].georgafi),(cp_3[ind5[1]].mat2) ); printf("\n averge = %f", max2); } break; } if(argv[i][0]=='-' && argv[i][1]=='n') { float min1,middle_markes[2][20],min2; int sem,ind4[2]; for(int i=0;i<ind2;i++) { middle_markes[0][i]=(cp_2[i].angl + cp_2[i].fiz + cp_2[i].mat + cp_2[i].oaip)/4.; middle_markes[1][i]=(cp_3[i].chem + cp_3[i].fiz2 + cp_3[i].georgafi + cp_3[i].mat2)/4.; } min1=middle_markes[0][0]; min2=middle_markes[1][0]; for(int i=0;i<ind2;i++) { if(middle_markes[0][i]<min1) { min1=middle_markes[0][i]; ind4[0]=i; } if(middle_markes[1][i]<min2) { min2=middle_markes[1][i]; ind4[1]=i; } } printf("the results of what the term ? 1-first, 2- second"); scanf_s("%d",&sem); if(sem==1) { printf("Fio group term english physics mathem oaip term chem physics geography mathem \n"); printf("%s %3d%3d%3d%3d%3d%3d%3d%3d%3d%3d%3d \n", cp_1[ind4[sem-1]].fio, (cp_1[ind4[sem-1]].gruop), (cp_1[ind4[sem-1]].semestr[0]), (cp_2[ind4[sem-1]].angl), (cp_2[ind4[sem-1]].fiz),(cp_2[ind4[sem-1]].mat),(cp_2[ind4[sem-1]].oaip),(cp_1[ind4[sem-1]].semestr[1]),(cp_3[ind4[sem-1]].chem),(cp_3[ind4[sem-1]].fiz2),(cp_3[ind4[sem-1]].georgafi),(cp_3[ind4[sem-1]].mat2) ); printf("\n averge = %f", min1); } else { printf("Fio group term english physics mathem oaip term chem physics geography mathem \n"); printf("%s %3d%3d%3d%3d%3d%3d%3d%3d%3d%3d%3d \n", cp_1[ind4[sem-1]].fio, (cp_1[ind4[sem-1]].gruop), (cp_1[ind4[sem-1]].semestr[0]), (cp_2[ind4[sem-1]].angl), (cp_2[ind4[sem-1]].fiz),(cp_2[ind4[sem-1]].mat),(cp_2[ind4[sem-1]].oaip),(cp_1[ind4[sem-1]].semestr[1]),(cp_3[ind4[sem-1]].chem),(cp_3[ind4[sem-1]].fiz2),(cp_3[ind4[sem-1]].georgafi),(cp_3[ind4[sem-1]].mat2) ); printf("\n averge = %f", min2); } break; } } } if(zapret==1) { file = fopen(fname,"w"); for(i=0;i<ind2;i++) fprintf(file,"%s %3d%3d%3d%3d%3d%3d%3d%3d%3d%3d%3d \n", cp_1[i].fio, (cp_1[i].gruop), (cp_1[i].semestr[0]), (cp_2[i].angl), (cp_2[i].fiz),(cp_2[i].mat),(cp_2[i].oaip),(cp_1[i].semestr[1]),(cp_3[i].chem),(cp_3[i].fiz2),(cp_3[i].georgafi),(cp_3[i].mat2) ); fclose(file); } getch(); return 0; }
C
#include <stdio.h> int recursion(){ int first,second; scanf("%d", &first); if(first == 1) second++; if(first == 0){ scanf("%d", &first); if(first == 0) return 0; if(first == 1) second++; } second += recursion(); return second; } int main(){ printf("result:%d\n", recursion()); return 0; }
C
/* Да се напише програма на C, която изпълнява команда date. */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <err.h> int main() { if ((execl("/bin/date","date", (char*) NULL)) == -1){ errx(1,"Error\n"); } printf("Success\n"); exit(EXIT_SUCCESS); }
C
#include<stdio.h> #include<conio.h> #define size 5 struct STACK { int st[size]; int top; }; void push(struct STACK *); void pop(struct STACK *); void peek(struct STACK *); void main() { int choice; struct STACK s1; s1.top=-1; do { printf("Press 1 for PUSH OPERATION\n"); printf("Press 2 for POP OPERATION\n"); printf("Press 3 for PEEK OPERATION\n"); printf("Press 4 for EXIT\n"); printf("ENTER YOUR CHOICE\n"); scanf("%d",&choice); switch(choice) { case 1: push(&s1); break; case 2: pop(&s1); break; case 3: peek(&s1); break; } } while(choice>=1 && choice<=3); printf("Exiting from program"); getch(); } void push(struct STACK *p) { int item; if(p->top==size-1) { printf("Overflow ,stack is full"); getch(); system("cls"); return; } printf("Enter the item\n"); scanf("%d",&item); p->top++; p->st[p->top]=item; printf("Item inserted successfully\n"); getch(); system("cls"); } void pop(struct STACK *p) { int item; if(p->top==-1) { printf("Underflow ,stack is empty"); getch(); system("cls"); return; } item=p->st[p->top]; p->top--; printf("Item %d deleted successfully\n",item); getch(); system("cls"); } void peek(struct STACK *p) { int item; if(p->top==-1) { printf("Underflow ,stack is empty"); getch(); system("cls"); return; } item=p->st[p->top]; printf("Item %d is peek element\n",item); getch(); system("cls"); }
C
// Writes many medium-size files to disk in various ways. /* clang -O2 -o foo write.c */ #include <dispatch/dispatch.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const int kNumFiles = 100; const int kChunkSize = 4 << 20; const int kIntChunkSize = kChunkSize / sizeof(uint32_t); void direct_fwrite(uint32_t* data) { char buf[80]; for (int fi = 0; fi < kNumFiles; ++fi) { sprintf(buf, "f%02d.out", fi); FILE* f = fopen(buf, "wb"); fwrite(data + fi * kIntChunkSize, 1, kChunkSize, f); fclose(f); } free(data); } void dispatch_apply_fwrite(uint32_t* data) { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_t group = dispatch_group_create(); for (int fi = 0; fi < kNumFiles; ++fi) dispatch_group_enter(group); // There's no dispatch_group_apply(). dispatch_apply(kNumFiles, queue, ^(size_t fi) { char buf[80]; sprintf(buf, "f%02d.out", (int)fi); FILE* f = fopen(buf, "wb"); fwrite(data + fi * kIntChunkSize, 1, kChunkSize, f); fclose(f); dispatch_group_leave(group); }); dispatch_group_wait(group, DISPATCH_TIME_FOREVER); dispatch_release(group); free(data); } void dispatch_async_fwrite(uint32_t* data) { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_t group = dispatch_group_create(); for (int fi = 0; fi < kNumFiles; ++fi) { dispatch_group_async(group, queue, ^{ char buf[80]; sprintf(buf, "f%02d.out", (int)fi); FILE* f = fopen(buf, "wb"); fwrite(data + fi * kIntChunkSize, 1, kChunkSize, f); fclose(f); }); } dispatch_group_wait(group, DISPATCH_TIME_FOREVER); dispatch_release(group); free(data); } void dispatch_io(uint32_t* data) { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_t group = dispatch_group_create(); char buf[80]; for (int fi = 0; fi < kNumFiles; ++fi) { sprintf(buf, "f%02d.out", fi); #if 0 // FIXME: Why does this not work? (`f` is always 0) dispatch_io_t f = dispatch_io_create_with_path( DISPATCH_IO_STREAM, buf, O_WRONLY | O_CREAT, 0644, queue, ^(int error) {}); if (f == 0) perror("wat"); #else int fd = open(buf, O_WRONLY | O_CREAT, 0644); dispatch_io_t f = dispatch_io_create(DISPATCH_IO_STREAM, fd, queue, ^(int error) {}); #endif dispatch_data_t ddata = dispatch_data_create(data + fi * kIntChunkSize, kChunkSize, queue, ^{}); dispatch_group_enter(group); dispatch_io_write(f, 0, ddata, queue, ^(bool done, dispatch_data_t data, int error) { if (done) dispatch_group_leave(group); }); dispatch_release(ddata); dispatch_io_close(f, 0); dispatch_release(f); } dispatch_group_wait(group, DISPATCH_TIME_FOREVER); dispatch_release(group); free(data); } int main(int argc, char* argv[]) { uint32_t* data = (uint32_t*)malloc(kNumFiles * kChunkSize * sizeof(uint32_t)); // Too slow, so don't initialize the written data: //for (int i = 0; i < kNumFiles * kChunkSize; ++i) data[i] = i; enum { kDirectFwrite, kDispatchApplyWrite, kDispatchAsyncWrite, kDispatchIO, } mode = kDirectFwrite; if (argc > 1) { if (strcmp(argv[1], "dispatch_apply_write") == 0) mode = kDispatchApplyWrite; else if (strcmp(argv[1], "dispatch_async_write") == 0) mode = kDispatchAsyncWrite; else if (strcmp(argv[1], "dispatch_io") == 0) mode = kDispatchIO; } switch (mode) { case kDirectFwrite: direct_fwrite(data); break; case kDispatchApplyWrite: dispatch_apply_fwrite(data); break; case kDispatchAsyncWrite: dispatch_async_fwrite(data); break; case kDispatchIO: dispatch_io(data); break; } }
C
#include<stdio.h> int max2(int a, int b) { return (a > b) ? a : b; } int max3(int a, int b, int c) { return (max2(a,b) > c) ? max2(a, b) : c; } int main() { int n; int podo[10000] = { 0, }, total[10000] = { 0, }; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &podo[i]); } total[0] = podo[0]; total[1] = podo[0]+podo[1]; total[2] = max3(podo[0] + podo[1], podo[0] + podo[2], podo[1] + podo[2]); for (int i = 3; i < n; i++) { total[i] = max3(total[i - 3] + podo[i - 1] + podo[i], total[i - 2] + podo[i], total[i - 1]); } printf("%d", total[n - 1]); return 0; }
C
/*! * \file timerFw.c * \brief Source file for Callback based Timer framework * * Timer framework to cater multiple timer requirements. * It is implemented using a single high precision real timer. * * Revision History: * Date User Comments * 21-Sep-18 Saurabh S Create Original * 26-Sep-18 Saurabh S Moved TimerState_e from header to src */ #include "timerFw.h" #include "platformTimer.h" typedef enum TimerState { TIMER_INIT = 1, TIMER_RUNNING, TIMER_PAUSED, TIMER_EXPIRED, } TimerState_e; /** * Structure to represent timer object */ typedef struct Timer { Bool repeat; UInt8_t timerId; TimerCallback_t cb; Void *arg; UInt32_t ticks; UInt32_t ticksRemaining; UInt32_t expiryCount; TimerState_e state; TimerType_e type; } Timer_t; static Timer_t **gTimerCb = NULL; /**< Dynamic array of timer control blocks */ static UInt8_t gMaxTimers = 0; /**< Maximum number of timers allowed */ static UInt32_t gTickMs = 0; /**< Tick ms for one internal timer expiry */ static UInt8_t gTimerCount = 0; /**< Number of active timers */ static Bool gTimerFwInit = False; /**< True when framework is initialised */ /*Internal timer call back function*/ static void pfTmrCb(void) { /*Process Timers*/ for (int i = 0; i < gMaxTimers; i++) { if (gTimerCb[i] != NULL) { //Valid Timer block /*Avoid processing of EXPIRED, PAUSED or INIT Timers, Only process RUNNING timers*/ if (gTimerCb[i]->state == TIMER_RUNNING) { /*This check avoid expired single shot timers*/ if (gTimerCb[i]->ticksRemaining > 0) { //Active Timer gTimerCb[i]->ticksRemaining--; //Reduce tick; /*Check if ticks are zero, means timer expired*/ if (gTimerCb[i]->ticksRemaining == 0) { //Timer Expired gTimerCb[i]->expiryCount++; //Increment Expiry Count /*If it is a Realtime Timer, Invoke callback here from interrupt context*/ if (gTimerCb[i]->type == TIMER_REALTIME) { if (gTimerCb[i]->cb != NULL) { // Invoke Callback and pass argument gTimerCb[i]->cb(i, gTimerCb[i]->arg); } gTimerCb[i]->expiryCount = 0; //As we have processed the expiry } /*If timer is repetetive, then reload ticks, state will be running*/ if (gTimerCb[i]->repeat == True) { gTimerCb[i]->ticksRemaining = gTimerCb[i]->ticks; } else { //Else Singleshot, update state as expired gTimerCb[i]->state = TIMER_EXPIRED; } } } else { // If control reaches here then its a Bug printf("TMRFW: Bug 1\n"); } } } } /*Invoke Realtime timer callbacks from interrupt context*/ //printf("Timer Tick\n"); } static Void processNonRtTimers(TimerType_e type) { for (int i = 0; i < gMaxTimers; i++) { if (gTimerCb[i] != NULL) { //Valid Timer block /*Only process Expired timers which are pending proessing*/ if (gTimerCb[i]->expiryCount > 0 && gTimerCb[i]->type == type) { if (gTimerCb[i]->cb != NULL) { // Invoke Callback and pass argument gTimerCb[i]->cb(i, gTimerCb[i]->arg); } gTimerCb[i]->expiryCount = 0; // To mark timer expiry as processed } } } } static ErrorType_e validateTimer(Int32_t timerId) { /*Validations*/ if (timerId < 0 || timerId > gMaxTimers - 1) { //Id within Bounds return E_TMR_OUT_OF_BOUND; } else if (gTimerFwInit == False) { //Timer Framework initialised return E_TMR_NOT_READY; } else if (gTimerCb[timerId] == NULL) { //Timer block initialised return E_TMR_NOT_EXIST; } return E_SUCCESS; } ErrorType_e timerFwInit(UInt32_t minTimerMs, UInt8_t maxTimers) { if (True == gTimerFwInit) { return E_TMR_READY; } /*Setup Internal Structures and Initialise*/ gMaxTimers = maxTimers; gTickMs = minTimerMs; /*Allocate memory to hold max timer block pointers*/ gTimerCb = calloc(maxTimers, sizeof(Timer_t *)); /*Setup Plaform Timer*/ //Int32_t platformTimerInit(UInt32_t ms, TmrExpiryCb cb) platformTimerStart(minTimerMs, pfTmrCb); gTimerFwInit = True; /*Timer Initialised*/ return E_SUCCESS; } /*Invoke High Priority and Low Priority Timer Callbacks from main context*/ Void timerFwProcess(Void) { /*Process High Priority Timers first*/ processNonRtTimers(TIMER_HIGH_PRIO); /*We may add some time check to defer processing of Low Prio timers if required*/ /*Process Low Priority Timer*/ processNonRtTimers(TIMER_LOW_PRIO); } Int32_t timerCreate(TimerType_e type, UInt32_t intervalMs, Bool repeat, TimerCallback_t cb, Void *arg) { if (gTimerCount >= gMaxTimers) return E_TMR_MAX; else if (intervalMs < gTickMs) return E_TMR_TOO_SMALL; /*Search timer block array for empty space and setup the timer*/ //// Deploy some sort of synchronization here, as gTimerCb is shared with Interrupt for (int i = 0; i < gMaxTimers; i++) { if (NULL == gTimerCb[i]) { gTimerCb[i] = calloc(1, sizeof(Timer_t)); /*Initialise Timer Control Block*/ gTimerCb[i]->repeat = repeat; gTimerCb[i]->timerId = i; gTimerCb[i]->cb = cb; gTimerCb[i]->arg = arg; gTimerCb[i]->ticks = intervalMs / gTickMs; /*Number of internal expiries*/ gTimerCb[i]->ticksRemaining = 0; //Initiate Ticks remaining from timerStart() gTimerCb[i]->expiryCount = 0; gTimerCb[i]->state = TIMER_INIT; gTimerCb[i]->type = type; gTimerCount++; /*Increment timer count*/ return i; /*Return timer id*/ } } return 0; } ErrorType_e timerStart(Int32_t timerId) { ErrorType_e err = validateTimer(timerId); /*Validations*/ if (E_SUCCESS != err) { return err; } else if (gTimerCb[timerId]->state == TIMER_RUNNING) { return E_TMR_RUNNING; } else if (gTimerCb[timerId]->state == TIMER_PAUSED) { return E_TMR_PAUSED; } /*Start Timer*/ gTimerCb[timerId]->ticksRemaining = gTimerCb[timerId]->ticks; //Initiate Ticks remaining from timerStart() gTimerCb[timerId]->state = TIMER_RUNNING; gTimerCb[timerId]->expiryCount = 0; return E_SUCCESS; } ErrorType_e timerDestroy(Int32_t timerId) { ErrorType_e err = validateTimer(timerId); Void *tmpPtr; //To free timer control block /*Validations*/ if (E_SUCCESS != err) { return err; } else if (gTimerCb[timerId]->state == TIMER_RUNNING) { return E_TMR_RUNNING; } else if (gTimerCb[timerId]->state == TIMER_PAUSED) { return E_TMR_PAUSED; } /*Destroy Timer*/ /// Some sort of syncronisation should be deployed here tmpPtr = gTimerCb[timerId]; gTimerCb[timerId] = NULL; free(tmpPtr); gTimerCount--; return E_SUCCESS; } ErrorType_e timerStop(Int32_t timerId) { ErrorType_e err = validateTimer(timerId); Void *tmpPtr; //To free timer control block /*Validations*/ if (E_SUCCESS != err) return err; /*Stop Timer*/ gTimerCb[timerId]->ticksRemaining = 0; gTimerCb[timerId]->expiryCount = 0; //To avoid invocation of callback gTimerCb[timerId]->state = TIMER_INIT; return E_SUCCESS; } ErrorType_e timerPause(Int32_t timerId) { ErrorType_e err = validateTimer(timerId); /*Validations*/ if (E_SUCCESS != err) { return err; } else if (gTimerCb[timerId]->state != TIMER_RUNNING) { return E_TMR_NOT_RUNNING; } /*Pause Timer*/ gTimerCb[timerId]->state = TIMER_PAUSED; return E_SUCCESS; } ErrorType_e timerResume(Int32_t timerId) { ErrorType_e err = validateTimer(timerId); /*Validations*/ if (E_SUCCESS != err) { return err; } else if (gTimerCb[timerId]->state != TIMER_PAUSED) { return E_TMR_NOT_PAUSED; } /*Resume Timer*/ gTimerCb[timerId]->state = TIMER_RUNNING; return E_SUCCESS; } ErrorType_e timerUpdateInterval(Int32_t timerId, UInt32_t newIntervalMs) { ErrorType_e err = validateTimer(timerId); /*Validations*/ if (E_SUCCESS != err) { return err; } else if (newIntervalMs < gTickMs) { return E_TMR_TOO_SMALL; } gTimerCb[timerId]->ticks = newIntervalMs / gTickMs; /*Number of internal expiries*/ return E_SUCCESS; } Int32_t timerInterval(Int32_t timerId) { ErrorType_e err = validateTimer(timerId); /*Validations*/ if (E_SUCCESS != err) { return err; //Return Error code to indicate error } return gTimerCb[timerId]->ticks * gTickMs; } Int32_t timerRemainingMs(Int32_t timerId) { ErrorType_e err = validateTimer(timerId); /*Validations*/ if (E_SUCCESS != err) { return err; //Return Error code to indicate error } else if (gTimerCb[timerId]->state != TIMER_RUNNING) { return E_TMR_NOT_RUNNING; } return gTimerCb[timerId]->ticksRemaining * gTickMs; } Int32_t timerExpiryCount(Int32_t timerId) { ErrorType_e err = validateTimer(timerId); /*Validations*/ if (E_SUCCESS != err) { return err; //Return Error code to indicate error } return gTimerCb[timerId]->expiryCount; } Int32_t timerType(Int32_t timerId) { ErrorType_e err = validateTimer(timerId); /*Validations*/ if (E_SUCCESS != err) { return err; //Return Error code to indicate error } return gTimerCb[timerId]->type; } Int32_t timerRunning(Int32_t timerId) { ErrorType_e err = validateTimer(timerId); /*Validations*/ if (E_SUCCESS != err) { return err; //Return Error code to indicate error } return (gTimerCb[timerId]->state == TIMER_RUNNING); } Int32_t timerSingleshot(Int32_t timerId) { ErrorType_e err = validateTimer(timerId); /*Validations*/ if (E_SUCCESS != err) { return err; //Return Error code to indicate error } return (gTimerCb[timerId]->type == TIMER_SINGLESHOT); }
C
#include "holberton.h" /** * reverse_array - reverse array * @a: array * @n: number */ void reverse_array(int *a, int n) { int tmp; int i; int rev = n - 1; if (n % 2 == 0) { n = n / 2; } else { n = (n - 1) / 2; } for (i = 0; i < n; i++) { tmp = a[i]; a[i] = a[rev]; a[rev] = tmp; rev--; } }
C
/* * main.c * * Created on: Apr 5, 2010 * Author: XTOg */ #include <stdio.h> #include <string.h> #define MAXN 40 void store(char *buf, int *n, int *l) { int i; *l = strlen(buf) - 1; for (i = 0; i <= *l; ++i) { n[i] = buf[*l - i] - '0'; } } int main(void) { char buf[MAXN + 1]; int n1[MAXN], n2[MAXN], mul[MAXN * 2]; int l1, l2, l; int i, j; scanf("%s", buf); store(buf, n1, &l1); scanf("%s", buf); store(buf, n2, &l2); memset(mul, 0, sizeof(mul)); l = l1 + l2 + 1; for (i = 0; i <= l1; ++i) { for (j = 0; j <= l2; ++j) { mul[i + j] += n1[i] * n2[j]; } } for (i = 0; i < l; ++i) { mul[i + 1] += mul[i] / 10; mul[i] %= 10; } while (mul[l] == 0 && l > 0) --l; for (; l >= 0; --l) printf("%d", mul[l]); printf("\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <string.h> int main(int argc, char *argv[]) { int sm; char res[10]; pid_t pid; pid=fork(); if(pid==0) { printf("I am CHILD PROCESS. ID = %d and PARENT's' ID = %d\n",getpid(),getppid()); execl("pro1","pro1",argv[1],argv[2],(char*)NULL); exit(0); } else if(pid>0) { int sum; wait(&sum); sm=WEXITSTATUS(sum); printf("I am PARENT PROCESS. ID = %d and PARENT's ID = %d\n",getpid(),getppid()); sprintf(res ,"%d", sm); execl("pro2","pro2",res,(char*)NULL); exit(0); } else printf("Error in Child Creation\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstmap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tmendes- <tmendes-@student.42sp.org.br> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/03/07 15:23:40 by tmendes- #+# #+# */ /* Updated: 2020/03/07 17:20:23 by tmendes- ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" t_list *ft_lstmap(t_list *lst, void *(*f)(void *), void (*del)(void *)) { t_list *head; t_list *node_old; t_list *node_new; if (lst == NULL || f == NULL) return (NULL); if (!(head = ft_lstnew(f(lst->content)))) return (NULL); node_old = lst; node_new = head; while (node_old->next != NULL) { if (!(node_new->next = ft_lstnew(f(node_old->next->content)))) { ft_lstclear(&head, del); return (NULL); } node_new = node_new->next; node_old = node_old->next; } return (head); }
C
#include <iostream> #include "Buscador.h" #include "Habitacion.h" #include "login.h" #include "Hotel.h" #include <fstream> using namespace std; char menu(){ char opcion; printf(" \n"); printf("1. Ver todos los hoteles\n"); printf("2. Reservar una habitacin en un hotel\n"); printf("3. Cancelar la reserva de una habitacin\n"); printf("4. Aadir hotel al buscardor\n"); printf("5. Eliminar hotel del buscador\n"); printf("0. Salir\n"); do{ printf("Elige una opcion: \n"); cin>>opcion; }while(opcion<'0' || opcion>'5'); return opcion; } void volcarBuscadorAFichero(Buscador *buscador){ ofstream f1; f1.open("Hoteles.txt",ios::out); f1<<buscador->getMaxHoteles()<<endl; f1<<buscador->getNumHoteles()<<endl; for(int i=0;i<buscador->getNumHoteles();i++){ f1<<buscador->getHotel(i)->getNombre()<<endl; f1<<buscador->getHotel(i)->getDireccion()<<endl; f1<<buscador->getHotel(i)->getCiudad()<<endl; f1<<buscador->getHotel(i)->getNumEstrellas()<<endl; f1<<buscador->getHotel(i)->getMaxHabitaciones()<<endl; f1<<buscador->getHotel(i)->getNumHabitaciones()<<endl; for(int j=0;j<buscador->getHotel(i)->getNumHabitaciones();j++){ f1<<buscador->getHotel(i)->getHabitacion(j)->getNumH()<<endl; f1<<buscador->getHotel(i)->getHabitacion(j)->getTipo()<<endl; f1<<buscador->getHotel(i)->getHabitacion(j)->getPrecio()<<endl; f1<<buscador->getHotel(i)->getHabitacion(j)->getOcupada()<<endl; } } f1.close(); } Buscador *volcarFicheroABuscador(){ Buscador *buscador=NULL; ifstream f1; f1.open("Hoteles.txt",ios::in); if(!f1.fail() && !f1.bad()){ int maxH,numH; f1>>maxH; f1>>numH; buscador = new Buscador(maxH); for(int i=0;i<numH;i++){ char nombre[20]; char direccion[100]; char ciudad[40]; int numEstrellas; int maxHabitaciones; int numHabitaciones; f1>>nombre; f1>>direccion; f1>>ciudad; f1>>numEstrellas; f1>>numHabitaciones; f1>>maxHabitaciones; Hotel *h = new Hotel(nombre,direccion,ciudad,numEstrellas,maxHabitaciones); buscador->addHotel(h); for(int j=0;j<numHabitaciones;j++){ int numHabitacion; char tipo[20]; float precio; int ocupada; f1>>numHabitacion; f1>>tipo; f1>>precio; f1>>ocupada; Habitacion *ha = new Habitacion(numHabitacion,tipo,precio,ocupada); buscador->getHotel(i)->addHabitacion(ha); } } } f1.close(); return buscador; } int main() { int numHo,numHa,posHo,posHa; char opcion; char nombre[20],ciudad[20]; Hotel *h; login *l = new login(); Buscador *buscador= NULL; buscador = volcarFicheroABuscador(); if(buscador==NULL){ buscador = new Buscador(100); } l->iniciarSesion(); do{ opcion = menu(); switch(opcion){ case '0': printf("Gracias por usar nuestro buscador. Hasta otra!\n"); break; case '1': buscador->mostrarHoteles(); break; case '2': buscador->mostrarHoteles(); printf("Introduce el hotel que deseas elegir:\n"); cin>>numHo; buscador->getHotel(numHo)->mostrarHabitaciones(); printf(" \n"); printf("Elige una habitacion: \n"); cin>>numHa; buscador->getHotel(numHo)->getHabitacion(numHa)->setOcupada(1); printf("Habitacin reservada correctamente\n"); break; case '3': printf("Introduce el nombre del hotel:\n"); cin>>nombre; printf("Introduce la ciudad: \n"); cin>>ciudad; posHo = buscador->buscarHotel(nombre, ciudad); if(posHo==-1) printf("Datos del hotel desconocidos\n"); else{ printf("Introduce el numero de habitacion cuya reserva quieres cancelar:\n"); cin>>numHa; posHa = buscador->getHotel(posHo)->buscarHabitacion(numHa); if(posHa==-1) printf("Datos de habitacion desconocida\n"); else{ buscador->getHotel(posHo)->getHabitacion(posHa)->setOcupada(0); printf("Reserva cancelada correctamente\n"); } } break; case '4': h = new Hotel(); h->pedirDatos(); buscador->addHotel(h); break; case '5': printf("Introduce el nombre del hotel: \n"); cin>>nombre; printf("Introduce la ciudad: \n"); cin>>ciudad; posHo = buscador->buscarHotel(nombre, ciudad); if(posHo==-1) printf("Datos del hotel desconocidos\n"); else{ buscador->revomeHotel(posHo); printf("Hotel eliminado del buscador\n"); } break; } }while(opcion!='0'); volcarBuscadorAFichero(buscador); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int main(void) { int fd1 = open("foo.txt", O_CREAT | O_RDONLY, 0); if (fd1 < 0) { perror("c1"); exit(1); } printf("opened fd = %d\n", fd1); // Using close system Call if (close(fd1) < 0) { perror("c1"); exit(1); } printf("closed fd = %d\n", fd1); // assume that bar.txt is already created int fd2 = open("bar.txt", O_CREAT | O_RDONLY, 0); printf("opened fd = %d\n", fd2); exit(0); }
C
/* tpstruct2.c: Defered struct and nested struct */ int a, b, c; struct address { char* name; struct location { int yuban; char* addr; } loc; }; struct list; struct list { int number; struct list* next; }; struct tree { int number; struct tree* child1; struct tree* child2; } t1; struct address tanaka; int main() { tanaka.name = "Tanaka"; tanaka.loc.yuban = 184; if (tanaka.loc.addr == 0) tanaka.loc.addr = " "; printf("tanaka = [%s,[%d,%s]]\n", /* SF030609 */ tanaka.name,tanaka.loc.yuban,tanaka.loc.addr); /* SF030609 */ return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "arrayEmployes.h" #include "utn.h" #define MAX 1000 #define SUELDO 1000000.00 int main() { Employee arrayEmpleado[MAX]; int menu; char respuesta ='n'; int flag=1; int contadorId=0; int auxID; char Name[30]; char lastname[30]; float salary; int sector; int fPosicion; int opListar; int orden; char subMenu='n'; initEmployee(arrayEmpleado,MAX); //harcodeoEmpleados(arrayEmpleado); do { system("CLS"); printf("___MENU____\n\n"); printf("1-Alta.\n"); printf("2-Modificar.\n"); printf("3-Baja.\n"); printf("4-Informar.\n"); printf("5-Salir.\n\n"); fflush(stdin); scanf("%d",&menu); switch(menu) { case 1:// agregar un empleado system("CLS"); if(employee_buscarIsEmpty(arrayEmpleado,MAX,&fPosicion)==0) { printf("Bienvenido al alta de Empleados\n\n"); contadorId++; utn_getName("\nIngrese el Nombre del empleado: ", "\nError ",1,51,3,Name); utn_getName("\nIngrese el Apellido del empleado: ", "\nError ",1,51,3,lastname); utn_getFloat("\nIngrese el sueldo del empleado: ", "\nError Fuera de presupuesto",1,SUELDO,3,&salary); utn_getInt("\nIngrese uno de los 5 sectores donde trabajara el empleado: ", "Error no existe ese sector, intente devuelta: ",1,5,3,&sector); if(addEmployee(arrayEmpleado,MAX,contadorId,Name,lastname,salary,sector)==0) { printf("\n\n Se cargo correctamente los siguientes datos"); mostrar_unEmpleado(arrayEmpleado,MAX,findEmployee(arrayEmpleado,MAX,contadorId)); system("pause"); } else { printf("\n algo salio mal"); } flag=0; } else { printf("no hay espacios libres"); } break; case 2://Modificar un Empleado. if(flag==1) { printf("No se ingreso ningun empleado\n"); system("pause"); } else { system("CLS"); printf("Modificar Empleados\n\n"); printEmployee(arrayEmpleado,MAX); printf("Ingrese el Id del usuario a modificar: "); fflush(stdin); scanf("%d",&auxID); ModEmployee(arrayEmpleado,MAX,auxID); } break; case 3://Eliminar un Empleado if(flag==1) { printf("No se ingreso ningun empleado\n"); system("pause"); } else { system("CLS"); printf("Baja Empleado\n\n"); printf("Ingrese Id a dar de baja: "); fflush(stdin); scanf("%d",&auxID); removeEmployee(arrayEmpleado,MAX,auxID); } break; case 4://Listar if(flag==1) { printf("No se ingreso ningun empleado\n"); system("pause"); } else { do { system("CLS"); printf("Listado de Empleados.\n\n"); printf("1- Mostrar Empleados.\n"); printf("2- Listar por orden alfabetico.\n"); printf("3- Calcular el promedio.\n"); printf("4- <-[menu principal]\n"); fflush(stdin); scanf("%d",&opListar); switch(opListar) { case 1: printEmployee(arrayEmpleado,MAX); break; case 2: printf("\n Elija una opcion: \n0-DE MENOR A MAYOR. \n1-DE MAYOR A MENOR.\n"); fflush(stdin); scanf("%d",&orden); sortEmployees(arrayEmpleado,MAX,orden); printEmployee(arrayEmpleado,MAX); break; case 3: promedioEmployees(arrayEmpleado,MAX); system("pause"); break; case 4: printf("\nvolver al menu principal (s/n): "); fflush(stdin); scanf("%c",&subMenu); break; default: printf("opcion invalida"); system("pause"); break; } } while(subMenu!='s'); break; case 5: printf("Presione s para salir (s/n): "); fflush(stdin); scanf("%c",&respuesta); break; default: printf("Opcion invalida...\n\n"); system("pause"); break; } } } while(respuesta !='s'); return 0; }
C
/* * OpenGL core wrapper. * * Author: Hidetake Iwata * Time-stamp: <2003-07-19 19:41:20 umeda> */ #include <stdio.h> #include <stdlib.h> #if defined(__APPLE__) #include <OpenGL/gl.h> #include <GLUT/glut.h> #else #include <GL/gl.h> #include <GL/glut.h> #endif #include "glwrapper.h" /* ライトのセット. */ void enableLight( GLenum lightnum, struct Light *light ) { glLightfv( lightnum, GL_AMBIENT, light->amb ); glLightfv( lightnum, GL_DIFFUSE, light->dif ); glLightfv( lightnum, GL_SPECULAR, light->spe ); glLightfv( lightnum, GL_POSITION, light->pos ); glEnable( lightnum ); } /* 材質のセット. */ void setMaterial( struct Material *mat ) { glMaterialfv( GL_FRONT, GL_AMBIENT, mat->amb ); glMaterialfv( GL_FRONT, GL_DIFFUSE, mat->dif ); glMaterialfv( GL_FRONT, GL_SPECULAR, mat->spe ); glMaterialf( GL_FRONT, GL_SHININESS, mat->shine ); } /* テクスチャの生成. */ void createTexture( struct Texture *tex ) { int j; char buf[128]; FILE *fp; /* 読み込み. */ fp = fopen( tex->filename, "r" ); if ( !fp ) { fprintf(stderr, "テクスチャ %s を読めません\n", tex->filename); exit(0); } tex->image = (GLubyte*)malloc( tex->width * tex->height * 3 * sizeof(GLubyte) ); for(j = 0 ; j < 3; j++) { fgets(buf, sizeof(buf),fp); if(*buf == '#') j--; } fread( tex->image, tex->width * tex->height * 3, 1, fp ); fclose( fp ); /* 初期化. */ glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glBindTexture(GL_TEXTURE_2D, tex->id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex->width, tex->height, 0, GL_RGB, GL_UNSIGNED_BYTE, tex->image); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); }
C
//https://e-tutor.itsa.org.tw/e-Tutor/mod/programming/view.php?a=2920 #include <stdio.h> int main(){ int n,m; scanf("%d%d",&n,&m); printf("%d\n",(n+m)*(n+m)); // 和平方 return 0; }