language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* ** free.c for in /home/teyssa_r/rendu/PSU_2013_42sh/src/bonus ** ** Made by teyssa_r teyssa_r ** Login <[email protected]> ** ** Started on Sun Sep 28 18:50:23 2014 teyssa_r teyssa_r ** Last update Thu Oct 2 22:18:44 2014 chenev_d chenev_d */ #include <stdlib.h> #include <unistd.h> #include "bonus.h" void free_string(t_string *str) { if (str != NULL) { free(str->tmp); free(str); } } void free_hst(t_hst *hst) { t_hst *tmp; t_hst *rmv; if (hst != NULL && hst->next != NULL) { tmp = hst->next; while (tmp != hst) { rmv = tmp; tmp = rmv->next; free(rmv->name); free(rmv); } free(hst); } } char *free_error(t_hst *hst, t_string *str, char *cmd, int *len) { free_hst(hst); if (str != NULL && *len >= 0) *len = str != NULL ? str->len : 0; free_string(str); free(cmd); return (NULL); } char *free_null(t_string *str, char *cmd) { free_string(str); free(cmd); return (NULL); }
C
#include <stdio.h> #include <stdlib.h> /* Ej4 TP3 -El siguiente programa calcula cuantos dias transcurrieron desde una fecha inicial y final elegidas por el usuario. -Las fechas pueden ser cargadas en 2 tipos de formato Formato 1: dd/mm/aa Formato 2: dd/mm/aaaa Grupo 3 Matias Gasparri Francisco Ledesma Dimas Bosch */ int doscifras (int, int); //Prototipo funcion doscifras int cuatrocifras (int, int, int, int); //Prototipo funcion cuatrocifras int diames (int, int, int); //Prototipo funcion diames int validar (int, int, int); //Prototipo funcion Validar int checkdates(int,int,int,int,int,int); //Prototipo funcion checkdates int fecha(); //Prototipo funcion fecha int anos(); //Prototipo funcion anos int main (void) { int formato; //variable para evaluar el formato elegido. do { printf("Elegi el formato que vas a usar:\nFormato1: dd/mm/aa.\nFormato2: dd/mm/aaaa\n\nElijo el formato numero "); formato=getchar()-'0'; //se imprime un mensaje y se espera que el usuario ingrese un caracter seguido de enter. } while (formato !=1 && formato !=2); //El programa esperara que el usuario elija el formato 1 o 2, caso contrario no realizara otra operacion getchar(); //libero el buffer del teclado int num; //inicializo variable para manejar el numero de los años mas adelante printf("Fecha inicial:"); //imprimo en pantalla Fecha inicial int diai=fecha (); //invoco a la funcion fecha para manejar el ingreso de la fecha inicial getchar(); //Aqui libero el buffer del caracter '/' entre las cifras de la fecha int mesi=fecha (); //invoco a la funcion fecha para almacenar el numero de mes inicial getchar(); //Aqui libero el buffer del caracter '/' entre las cifras de la fecha if (formato==1) //el siguiente if else maneja la parte del ingreso del año inicial { //en el caso del formato 1 se esperan 2 caracteres para el año int ai1=getchar(), ai2=getchar(); //guardo digitos del año num=doscifras (ai1, ai2); //invoco la funcion doscifras que me devuelve el numero entero del año completo if(num>=30){num=num+1900;}else{num=num+2000;} //en el caso del formato 1, los años contemplados van de 1930 a 2029 } else //caso contrario, es el formato 2, se esperan 4 caracteres para el año { int ai1=getchar(), ai2=getchar(), ai3=getchar(), ai4=getchar(); //guardo los 4 caracteres num=cuatrocifras (ai1, ai2, ai3, ai4); // y invoco funcion cuatrocifras que me devuelve el entero del año escogido } int anoi=num; //guardo el numero del año inicial printf ("%d/%d/%d\n", diai, mesi, anoi); //imprimo en pantalla la fecha elegida if (validar(diai, mesi, anoi)==0) // y verifico si la fecha existe { printf("ERROR, FECHA NO VALIDA\n"); //si no existe la fecha imprimo en pantalla un mensaje de error return 0; // y el programa termina } getchar(); //libero buffer teclado '\n' printf("Fecha final:"); //imprimo en pantalla Fecha final int diaf=fecha (); //invoco a la funcion fecha para manejar el ingreso de la fecha final getchar(); //Aqui libero el buffer del caracter '/' entre las cifras de la fecha int mesf=fecha (); //invoco a la funcion fecha para almacenar el numero de mes final getchar(); //Aqui libero el buffer del caracter '/' entre las cifras de la fecha if (formato==1) //el siguiente if else maneja la parte del ingreso del año final { //en el caso del formato 1 se esperan 2 caracteres para el año int af1=getchar(), af2=getchar(); //guardo digitos del año num=doscifras (af1, af2); //invoco la funcion doscifras que me devuelve el numero entero del año completo if(num>=30){num=num+1900;}else{num=num+2000;} //en el caso del formato 1, los años contemplados van de 1930 a 2029 } else //caso contrario, es el formato 2, se esperan 4 caracteres para el año { int af1=getchar(), af2=getchar(), af3=getchar(), af4=getchar(); //guardo los 4 caracteres num=cuatrocifras (af1, af2, af3, af4); // y invoco funcion cuatrocifras que me devuelve el entero del año escogido } int anof=num; //guardo el numero del año final printf ("%d/%d/%d\n", diaf, mesf, anof); //imprimo en pantalla la fecha elegida if (validar(diaf, mesf, anof)==0) // y verifico si la fecha existe { printf("ERROR, FECHA NO VALIDA"); //si no existe la fecha imprimo en pantalla un mensaje de error return 0; // y el programa termina } if (checkdates(diai,mesi,anoi,diaf,mesf,anof)==0) //verifico si fecha final es posterior a fecha inicial { printf("ERROR, FECHA FINAL ES ANTERIOR A FECHA INICIAL\n"); //si la fecha final es anterior indico error return 0; //y el programa termina } int mdf=diames (diaf, mesf, anof); //invoco diames con la fecha final y guardo valor en variable int mdi=diames (diai, mesi, anoi); //invoco diames con la fecha inicial y guardo valor en variable int difmd=mdf-mdi; //La resta de estas 2 variables me da la cantidad de dias de diferencia entre los meses int dify=anos(anoi, anof); //invoco anos para guardar la cantidad de diferencia entre los años elegidos int dif=(dify*365.25)+difmd; //calculo final de los dias totales printf("\nDiferencia=%d dias\n", dif); //imprimo en pantalla los dias finales return 0; //fin del programa } /*Funcion fecha Que hace? -Espera el ingreso por teclado de 1 numero de 2 cifras, luego invoca funcion doscifras para convertir el valor en ASCII a entero. Que recibe? - Nada. Que devuelve? -Devuelve un entero con el valor de las 2 cifras ingresadas. */ int fecha () { int f1,f2; //declaro variables a utilizar f1=getchar(), f2=getchar(); //guardo en las variables los caracteres ingresados por teclado int f=doscifras (f1, f2); //convierto a entero decimal return f; //devuelvo el entero decimal } /*Funcion doscifras Que hace? -Convierte 2 cifras en ASCII al entero correspondiente Ej: '2','1' vuelve como el numero 21 decimal. Que recibe? - 2 valores en ASCII correspondientes al simbolo de las cifras ingresadas Que devuelve? -Devuelve un entero decimal. */ int doscifras (int c1, int c2) { int num; if (c2 !='\n') { c1=(c1-'0')*10; c2=c2-'0'; num=c1+c2; } else { c1=c1-'0'; num=c1; } return num; } /*Funcion cuatrocifras Que hace? -Convierte 4 cifras en ASCII al entero correspondiente Ej: '2','1','3','4' vuelve como el numero 2134 decimal. Que recibe? - 4 valores en ASCII correspondientes al simbolo de las cifras ingresadas Que devuelve? -Devuelve un entero decimal. */ int cuatrocifras (int c1, int c2, int c3, int c4) { c1=(c1-'0')*1000; c2=(c2-'0')*100; c3=(c3-'0')*10; c4=c4-'0'; int num=c1+c2+c3+c4; return num; } /*Funcion diames Que hace? -calcula la cantidad de dias transcurridos en ese año Que recibe? - recibe 3 enteros correspondientes a la fecha (dia, mes, año) Que devuelve? -1 entero correspondiente a la cantidad de dias. */ int diames (int dia, int mes, int year) { int bis=((year%4==0) || (year%400==0)); int u, f=0, p; if (mes>2) { f=1; } switch (mes) { case 1: { u=0; p=0; break; } case 2:case 3: { u=1; p=0; break; } case 4: { u=2; p=0; break; } case 5: { u=2; p=1; break; } case 6: { u=3; p=1; break; } case 7: { u=3; p=2; break; } case 8: { u=4; p=2; break; } case 9: { u=5; p=2; break; } case 10: { u=5; p=3; break; } case 11: { u=6; p=3; break; } case 12: { u=6; p=4; break; } } // u=cantidad de meses transcurridos con 31 dias // f --> si paso febrero F=1 caso contrario f=0 // p=cantidad de meses transcurridos con 30 dias. int md=dia+31*u+(28+bis)*f+30*p; //Calculo completo de los dias transcurridos en el año. return md; } /*Funcion anos Que hace? -Calcula la diferencia de años. -Los años pueden ser ingresados como 2 cifras o 4. Que recibe? - recibe 2 enteros correspondientes a los años. Que devuelve? - 1 entero con el valor de la diferencia de años */ int anos(int year1,int year2) { int years; if(year1<100) { if(year1>year2) // ejemplo (12,1,97)y(1,4,12)el 12 seria 2012, entonces tengo que hacer una cuenta distinta porque sino me daria mal la cantidad de anos { year2=year2+100; //le sumo 100 para poder hacer la resta years=year2-year1; // cantidad de anos entre fechas } else years=year1-year2; // aca seria lo contrario(12/2/12)y(12/2/97) como el primer ano es menor que el segundo se refiere a 1912 y no a 2012 } if (year1<year2) { years=year2-year1; } else years=year1-year2; return years; } /*Funcion validar Que hace? -Verifica que las fechas ingresadas existan. -Contempla años bisiesto y los dias que hay por cada mes. Que recibe? - recibe 3 enteros correspondientes al dia, mes y año. Que devuelve? - 1 entero con valor 1 si es valida o 0 sino lo es. */ int validar(int day,int month,int year) { while(year>=0) //reviso que no cargo un año negativo { switch(month) //en funcion del mes elegido verifico la cantidad de dias { case 1:case 3:case 5:case 6:case 8:case 10:case 12: //enero, marzo,mayo,junio,Agosto,octubre y diciembre if(day<=31) //tienen 31 dias, por lo tanto day no puede ser mayor. { return 1; } else { return 0; } case 2: //febrero, Day no puede ser mayor a 28, a menos que el año sea bisiesto, en ese caso maximo es 29 if(year%4==0){ if(day<=29){return 1;}else {return 0;} } if(year%400==0){ if(day<=29){return 1;}else {return 0;} } if(day<=28){return 1;}else {return 0;} case 4:case 7:case 9:case 11: if(day<=30){return 1;}else{return 0;} default: return 0; } } return 0; } /*Funcion checkdates Que hace? -Verifica que una fecha final sea posterior a una fecha inicial. Que recibe? - recibe 3 enteros correspondientes a dia, mes, año inicial. - recibe 3 enteros correspondientes a dia, mes, año final. Que devuelve? - 1 entero con valor 1 si la fecha es posterior o 0 sino lo es. */ int checkdates(int diai,int mesi,int anoi,int diaf,int mesf,int anof) { if(anoi<anof){return 1;} if(anoi==anof) { if(mesi<mesf){return 1;} if(mesi==mesf) { if(diai<diaf){return 1;} if(diai==diaf){return 1;} } } return 0; }
C
/* * main.c * * Created on: Jul 12, 2020 * Author: jonmckay */ #include <stdio.h> #include <stdint.h> int main(void) { uint64_t totalIncome; double tempIncome; uint64_t tax; printf("Enter your total income:"); scanf("%lf", &tempIncome); totalIncome = (uint64_t) tempIncome; if(totalIncome <= 9525){ tax = 0; } else if (totalIncome >= 9526 && totalIncome <= 38700){ tax = totalIncome * 0.12; } else if (totalIncome >= 38701 && totalIncome <= 82500){ tax = totalIncome * 0.22; } else { tax = (totalIncome * 0.32) + 1000; } printf("Tax Payable: %llu\n", tax); }
C
#include "std.h" #include "App.h" void main() { Init(); Run(); /* char arr[MAX]; int i; int idx = 0; printf("Tell me about charactor!"); for(i=0; i<10; i++) { printf("%d\t", arr[i]); } printf("\n"); */ }
C
/** ****************************************************************************** * @file mb_port.c * @author Derrick Wang * @brief modebus移植接口 ****************************************************************************** * @note * 该文件为modbus移植接口的实现,根据不同的MCU平台进行移植 ****************************************************************************** */ #include "mb_include.h" #include "tim.h" #include "usart.h" #include "gpio.h" void mb_port_uartInit(uint32_t baud,uint8_t parity) { /*串口部分初始化*/ huart1.Instance = USART1; huart1.Init.BaudRate = baud; huart1.Init.WordLength = UART_WORDLENGTH_8B; if(parity==MB_PARITY_ODD) { huart1.Init.StopBits = UART_STOPBITS_1; huart1.Init.Parity = UART_PARITY_ODD; } else if(parity==MB_PARITY_EVEN) { huart1.Init.StopBits = UART_STOPBITS_1; huart1.Init.Parity = UART_PARITY_EVEN; } else { huart1.Init.StopBits = UART_STOPBITS_2; huart1.Init.Parity = UART_PARITY_NONE; } huart1.Init.Mode = UART_MODE_TX_RX; huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart1.Init.OverSampling = UART_OVERSAMPLING_16; if (HAL_UART_Init(&huart1) != HAL_OK) { Error_Handler(); } } void mb_port_uartEnable(uint8_t txen,uint8_t rxen) { if(txen) { __HAL_UART_ENABLE_IT(&huart1,UART_IT_TXE); } else { __HAL_UART_DISABLE_IT(&huart1,UART_IT_TXE); } if(rxen) { __HAL_UART_ENABLE_IT(&huart1,UART_IT_RXNE); } else { __HAL_UART_DISABLE_IT(&huart1,UART_IT_RXNE); } } void mb_port_putchar(uint8_t ch) { huart1.Instance->DR = ch; //直接操作寄存器比HAL封装的更高效 } void mb_port_getchar(uint8_t *ch) { *ch= (uint8_t)(huart1.Instance->DR & (uint8_t)0x00FF); } void mb_port_timerInit(uint32_t baud) { /*定时器部分初始化*/ htim3.Instance = TIM3; htim3.Init.Prescaler = 71; htim3.Init.CounterMode = TIM_COUNTERMODE_UP; if(baud>19200) //波特率大于19200固定使用1800作为3.5T { htim3.Init.Period = 1800; } else //其他波特率的需要根据计算 { /* us=1s/(baud/11)*1000000*3.5 * =(11*1000000*3.5)/baud * =38500000/baud */ htim3.Init.Period = (uint32_t)38500000/baud; } htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; if (HAL_TIM_Base_Init(&htim3) != HAL_OK) { Error_Handler(); } } void mb_port_timerEnable() { __HAL_TIM_DISABLE(&htim3); __HAL_TIM_CLEAR_IT(&htim3,TIM_IT_UPDATE); //清除中断位 __HAL_TIM_ENABLE_IT(&htim3,TIM_IT_UPDATE); //使能中断位 __HAL_TIM_SET_COUNTER(&htim3,0); //设置定时器计数为0 __HAL_TIM_ENABLE(&htim3); //使能定时器 } void mb_port_timerDisable() { __HAL_TIM_DISABLE(&htim3); __HAL_TIM_SET_COUNTER(&htim3,0); __HAL_TIM_DISABLE_IT(&htim3,TIM_IT_UPDATE); __HAL_TIM_CLEAR_IT(&htim3,TIM_IT_UPDATE); } //串口中断服务函数 void USART1_IRQHandler() { HAL_NVIC_ClearPendingIRQ(USART1_IRQn); if((__HAL_UART_GET_FLAG(&huart1,UART_FLAG_RXNE)!=RESET)) { __HAL_UART_CLEAR_FLAG(&huart1,UART_FLAG_RXNE); mbh_uartRxIsr(); } if((__HAL_UART_GET_FLAG(&huart1,UART_FLAG_TXE)!=RESET)) { __HAL_UART_CLEAR_FLAG(&huart1,UART_FLAG_TXE); mbh_uartTxIsr(); } } //定时器中断服务函数 void TIM3_IRQHandler() { __HAL_TIM_CLEAR_IT(&htim3,TIM_IT_UPDATE); mbh_timer3T5Isr(); }
C
#ifndef RADIX_PRIOR #define RADIX_PRIOR #include<stdbool.h> enum SortType {F_NAME, L_NAME, AGE}; typedef struct Record { char* fName; char* lName; int age; } Record; Record* newRecord(char fName[], char lName[], int age); void deleteRecord(Record* record); void printRecord(Record* record); void printRecords(Record* records[], int recordCount); bool compareFName(Record* r1, Record* r2); bool compareLName(Record* r1, Record* r2); bool compareAge(Record* r1, Record* r2); void radixPrioritySort(Record* records[], int numRecords, enum SortType priorities[], int numPriorities); int testRadixPrioritySort(); #endif
C
//Gloria Oliva Olivares Ménez //Estructuras de Datos //Cola Dinámica //1CM6 #include <stdio.h> #include <stdlib.h> #include <string.h> struct dato{ char nombre[30]; int edad; float est; char sexo; }; struct nodo{ struct dato *Dato; struct nodo *sig; }; struct Cola{ struct nodo *pri; struct nodo *ult; }; int menu(){ int opc; fflush(stdin); printf("\n1. Meter dato"); printf("\n2. Sacar dato"); printf("\n3. Recorrer cola"); printf("\n4. Salir"); printf("\nOpcion: "); scanf("%d",&opc); return opc; } struct nodo *CrearNodo(struct dato *Dato1){ struct nodo *ptrnuevo; ptrnuevo=(struct nodo*)malloc(sizeof(struct nodo)); ptrnuevo->Dato=(struct dato*)malloc(sizeof(struct dato)); strcpy(ptrnuevo->Dato->nombre,Dato1->nombre); ptrnuevo->Dato->edad=Dato1->edad; ptrnuevo->Dato->est=Dato1->est; ptrnuevo->Dato->sexo=Dato1->sexo; ptrnuevo->sig=NULL; return ptrnuevo; } void iniciarCola(struct Cola *queue){ queue->pri=NULL; queue->ult=NULL; } int estaVacia(struct Cola *queue){ if(queue->pri==NULL && queue->ult==NULL) return 1; else return 0; } void meterDato(struct Cola *queue, struct dato *datoIn){ struct nodo *nuevo=CrearNodo(datoIn); if(estaVacia(queue)){ queue->pri=nuevo; queue->ult=nuevo; }else{ queue->ult->sig=nuevo; queue->ult=nuevo; } } struct dato *sacarDato(struct Cola *queue,struct dato *datoOut){ struct nodo *temp=queue->pri; datoOut=temp->Dato; temp=temp->sig; return datoOut; } void recorrerCola(struct Cola *queue){ struct nodo *temp=queue->pri; do{ printf("\n%s es el nombre.\n",temp->Dato->nombre); printf("%d es la edad\n",temp->Dato->edad); printf("%.2f es la estatura\n",temp->Dato->est); printf("%c es el sexo\n",temp->Dato->sexo); temp=temp->sig; }while(temp!=NULL); } int main(){ int datoIn; struct Cola *cola00=(struct Cola*)malloc(sizeof(struct Cola)); struct dato *midato=(struct dato*)malloc(sizeof(struct dato)); iniciarCola(cola00); while(1){ printf("\nCola dinamica, elija una opcion:"); switch(menu()){ case 1: printf("Nombre:"); fflush(stdin); gets(midato->nombre); printf("Edad:"); scanf("%d",&midato->edad); printf("Estatura:"); scanf("%f",&midato->est); printf("Sexo:"); fflush(stdin); scanf("%c",&midato->sexo); meterDato(cola00,midato); break; case 2: printf("\n2. Sacar dato\n"); if(estaVacia(cola00)) printf("Cola vacia\n"); else midato=sacarDato(cola00,midato); printf("Salio:\n"); printf("Nombre:%s\n",midato->nombre); printf("Edad:%d\n",midato->edad); printf("Estatura:%.2f\n",midato->est); printf("Sexo:%c\n",midato->sexo); break; case 3: printf("\n3. Recorrer cola\nImpresion de datos (del primero al ultimo):\n\t"); if(estaVacia(cola00)) printf("Cola vacia\n"); else recorrerCola(cola00); printf("\n"); break; case 4: exit(0); break; default: printf("\nOpcion no existente, intente de nuevo.\n"); break; } } return 0; }
C
#include<stdio.h> #include<stdlib.h> /* Faa uma funo que receba, por parmetro, a altura (alt) e o sexo de uma pessoa e retorna o seu peso ideal. Para homens, calcular o peso ideal usando a frmula peso ideal = 72.7 x alt - 58 e, para mulheres, peso ideal = 62.1 x alt - 44.7. Utilize esta funo no programa principal para retornar o peso ideal de uma lista de pessoas. O programa deve ser finalizado quando a altura digitada for menor ou igual a 0. */ float imc (float h, char s) { if (s == 'm' || s == 'M'){ return 72.7*h-58; } else if (s == 'f' || s == 'F'){ return 62.1*h-44.7; } } int main () { float altura; char sexo; float funcao; do{ printf ("\nDigite a sua altura: "); scanf ("%f",&altura); printf ("Digite o seu sexo: "); scanf (" %c",&sexo); funcao = imc (altura, sexo); printf ("O peso ideal eh: %.2f\n",funcao); } while (altura>0); return 0; }
C
/****************************************************************/ /* */ /* Memory */ /* */ /* Description: Fonctions de manipulation de la memoire */ /* Auteur: LePhenixNoir */ /* Version: 3.0 */ /* Date: 11.06.2014 */ /* Fichier: memory.c - Code des fonctions */ /* */ /****************************************************************/ #ifndef __FXLIB_H__ #include "fxlib.h" #endif #ifndef _STDIO #include <stdio.h> #endif #ifndef _STDLIB #include <stdlib.h> #endif #ifndef _STRING #include <string.h> #endif #include "memory.h" int memory_errors = 0; void memory_seterrors(int e) { memory_errors = (e!=0); } void memory_error(char *from, char *func, int val) { unsigned int key; char info[20]; if(!memory_errors) return; sprintf(info,"%d",val); PopUpWin(6); locate(4,2); Print((unsigned char *)"Memory ERROR !!"); locate(3,4); Print((unsigned char *)"FROM:"); locate(8,4); Print((unsigned char *)from); locate(3,5); Print((unsigned char *)"FUNC:"); locate(8,5); Print((unsigned char *)func); locate(3,6); Print((unsigned char *)"INFO:"); locate(8,6); Print((unsigned char *)info); locate(3,7); Print((unsigned char *)"META:"); locate(8,7); switch(val) { case 1: Print((unsigned char *)"NotEnoughRAM"); break; case -1: Print((unsigned char *)"Nonexisting"); break; case -5: Print((unsigned char *)"WrongDevice"); break; case -8: Print((unsigned char *)"AccessDenied"); break; case -14: Print((unsigned char *)"ReadOnly"); break; case -31: Print((unsigned char *)"DeviceError"); break; case -35: Print((unsigned char *)"NotEmpty"); break; default: Print((unsigned char *)"Other"); break; } GetKey(&key); } FONTCHARACTER *memory_char2font(char *adresse) { FONTCHARACTER *adr; int i; adr = calloc((strlen(adresse)+1),sizeof(FONTCHARACTER)); for(i=0;i<strlen(adresse);i++) *(adr+i) = *(adresse+i); return adr; } int memory_createfile(char *adresse, int size) { FONTCHARACTER *adr = memory_char2font(adresse); int i = Bfile_CreateFile(adr,size); if(i<0) memory_error("createfile()","CreateFile()",i); free(adr); return i; } int memory_createdir(char *adresse) { FONTCHARACTER *adr = memory_char2font(adresse); int i = Bfile_CreateDirectory(adr); if(i<0) memory_error("createdir()","CreateDir.()",i); free(adr); return 1; } int memory_openfile(char *adresse, int mode) { FONTCHARACTER *adr = memory_char2font(adresse); int i = Bfile_OpenFile(adr,mode); if(i<0) memory_error("openfile()","OpenFile()",i); free(adr); return i; } int memory_deletefile(char *adresse) { FONTCHARACTER *adr = memory_char2font(adresse); int i = Bfile_DeleteFile(adr); if(i<0) memory_error("deletefil.()","DeleteFil.()",i); free(adr); return i; } char **memory_alloc(int l) { char **p = calloc(l,sizeof(char *)); int i; for(i=0;i<l;i++) *(p+i) = calloc(20,1); return p; } void memory_free(char **p, int l) { int i; for(i=0;i<l;i++) free(*(p+i)); free(p); } int memory_find(char *adresse, char **files, int max) { FONTCHARACTER *adr = memory_char2font(adresse); FONTCHARACTER found[30]; FILE_INFO fileInfo; int searchHandle,i=1,j,x; if(x = Bfile_FindFirst(adr,&searchHandle,found,&fileInfo)) return 0; for(j=0;j<14 && *(found+j);j++) *(*files+j) = *(found+j); while(Bfile_FindNext(searchHandle,found,&fileInfo)==0 && i<max) { for(j=0;j<14 && *(found+j);j++) *(*(files+i)+j) = *(found+j); i++; } Bfile_FindClose(searchHandle); free(adr); return i; } int memory_exists(char *adresse) { char *file[1]; int x; *file = malloc(14); **file=0; x = memory_find(adresse,file,1); free(*file); return x!=0; } void *memory_load(char *adresse) { FONTCHARACTER *adr = memory_char2font(adresse); int handle, x, size; void *p; if((handle=Bfile_OpenFile(adr,_OPENMODE_READ))<0) { memory_error("load()","OpenFile()",handle); return NULL; } size = Bfile_GetFileSize(handle)+1; p = calloc(size,1); if(!p) { memory_error("load()","malloc()",1); Bfile_CloseFile(handle); free(adr); return NULL; } if((x=Bfile_ReadFile(handle,p,size,0))<0) { memory_error("load()","ReadFile()",x); Bfile_CloseFile(handle); free(adr); return NULL; } Bfile_CloseFile(handle); free(adr); return p; } int memory_save(char *adresse, void *data, int l) { FONTCHARACTER *adr = memory_char2font(adresse); int x=0, handle; if(memory_exists(adresse)) x = Bfile_DeleteFile(adr); if(x<0) { memory_error("save()","DeleteFile()",x); free(adr); return x; } x = Bfile_CreateFile(adr,l+1); if(x<0) { memory_error("save()","CreateFile()",x); free(adr); return x; } handle = Bfile_OpenFile(adr,0x02); if(handle<0) { memory_error("save()","OpenFile()",handle); free(adr); return handle; } x = memory_writefile(handle,data,l); if(x<0) { memory_error("save()","WriteFile()",x); free(adr); return x; } memory_closefile(handle); free(adr); return 0; } int memory_user_select(char **files, int n, int extension, int exit) { const unsigned char icons[7][32] = { { 0x0,0x3c,0xf,0xc4,0xf0,0x4,0x80,0x4,0x80,0x2,0x80,0x2,0x40,0x2,0x40,0x2,0x40,0x2,0x40,0x2,0x40,0x1,0x40,0x1,0x20,0x1,0x20,0xf,0x23,0xf0,0x3c,0x0 }, { 0x0,0x3c,0xf,0xc4,0xf0,0x4,0x80,0x74,0x87,0x82,0x98,0x2,0x40,0x2,0x40,0x3a,0x43,0xc2,0x5c,0x2,0x40,0x39,0x43,0xc1,0x2c,0x1,0x20,0xf,0x23,0xf0,0x3c,0x0 }, { 0x0,0x3c,0xf,0xc4,0xf0,0x74,0x87,0x94,0xb8,0x12,0xa0,0xa,0x63,0x8a,0x52,0x8a,0x54,0x4a,0x54,0x66,0x54,0x25,0x48,0x1d,0x29,0xe1,0x2e,0xf,0x23,0xf0,0x3c,0x0 }, { 0x0,0x3c,0xf,0xc4,0xf0,0x4,0x87,0xc4,0x88,0x22,0x8c,0x62,0x4b,0xa2,0x44,0x42,0x42,0x82,0x42,0x82,0x42,0x81,0x44,0x41,0x2f,0xe1,0x20,0xf,0x23,0xf0,0x3c,0x0 }, { 0x0,0x3c,0xf,0xc4,0xf0,0x4,0x87,0xe4,0x88,0x12,0x88,0x12,0x48,0x12,0x47,0xe2,0x44,0x22,0x44,0x22,0x44,0x21,0x44,0x21,0x23,0xc1,0x20,0xf,0x23,0xf0,0x3c,0x0 }, { 0x0,0x3c,0xf,0xc4,0xf0,0x4,0x80,0x64,0x87,0xb2,0x98,0x52,0x51,0xb2,0x57,0x52,0x51,0xd2,0x4b,0xa,0x48,0x19,0x49,0xe1,0x2e,0x1,0x20,0xf,0x23,0xf0,0x3c,0x0 }, { 0x0,0x3c,0xf,0xc4,0xf0,0x4,0x80,0xe4,0x9c,0xa2,0x90,0xa2,0x58,0xe2,0x50,0x2,0x40,0x12,0x4a,0x2a,0x4a,0x39,0x4e,0x29,0x22,0x1,0x20,0xf,0x23,0xf0,0x3c,0x0 } }; char *exts[19] = { ".txt", ".c", ".h", ".cpp", ".hpp", ".bmp",".jpg",".png",".gif", ".sav", ".g1m",".g2m",".g1r",".g2r", ".g1e",".g2e",".g1a", ".hex",".bin" }; unsigned char indexs[19] = { 1,1,1,1,1, 2,2,2,2, 3, 4,4,4,4, 5,5,5, 6,6 }; unsigned char *icoind = malloc(n); unsigned int key; int i,j,k,t; int p=0, offset=0; if(!icoind) { memory_error("user_sele.()","malloc()",1); return -2; } for(i=0;i<n;i++) { for(t=-1,j=0;*(*(files+i)+j);j++) if(*(*(files+i)+j) == '.') t = j; icoind[i] = (t==-1?1:0); for(k=0;k<19;k++) if(!strcmp(*(files+i)+t,exts[k])) { icoind[i]=indexs[k]; break; } if(!extension && t+1) *(*(files+i)+t) = 0; } while(1) { Bdisp_AllClr_VRAM(); for(t=0;t<(n>3?3:n);t++) { if(icoind[offset+i]!=255) for(i=0;i<32;i++) { k = icons[icoind[offset+t]][i]; for(j=0;j<8;j++) { if(k&1) Bdisp_SetPoint_VRAM(11-j+8*(i&1),20*t+4+(i>>1),1); k >>= 1; } } PrintXY(24,20*t+9,(const unsigned char *)*(files+offset+t),0); } Bdisp_DrawLineVRAM(2,20*p+3,2,20*p+20); Bdisp_DrawLineVRAM(3,20*p+2,99,20*p+2); Bdisp_DrawLineVRAM(3,20*p+21,99,20*p+21); Bdisp_DrawLineVRAM(100,20*p+3,100,20*p+20); if(offset>0) PrintXY(114,6,(const unsigned char *)"\346\234",0); if(offset+3<n) PrintXY(114,51,(const unsigned char *)"\346\235",0); while(1) { GetKey(&key); if(key==30002 && exit) { free(icoind); return -1; } if(key==30004) break; if(key==30018 && (offset||p)) { if(p==2) p--; else if(offset) offset--; else p--; break; } if(key==30023 && (offset+p+1<n)) { if(p==0) p++; else if(offset+3<n) offset++; else p++; break; } } if(key==30004) break; } free(icoind); return offset+p; } void *memory_user_autoload(char *prefix, char *selector, int l, int extension, int exit) { char **files = memory_alloc(l); char *adr = malloc(strlen(prefix)+strlen(selector)+1); void *data; int x; sprintf(adr,"%s%s",prefix,selector); x = memory_find(adr,files,l); free(adr); x = memory_user_select(files,x,extension,exit); adr = malloc(strlen(prefix)+strlen(files[x])+1); sprintf(adr,"%s%s",prefix,files[x]); data = memory_load(adr); free(adr); memory_free(files,l); return data; }
C
#pragma once #include <stdbool.h> typedef struct Link { void* value; struct Link* next; } Link; typedef struct Stack { Link* first; int dataCount; } Stack; void InitStack(Stack* st); bool IsStackEmpty(Stack* st); void Push(Stack* st, void* val); void* Pop(Stack* st); void* Top(Stack* st);
C
#include <stdio.h> int main(int argc, char const *argv[]) { FILE *fp; char a='A'; fp=fopen("file1.txt","w"); if(!fp) printf("file not created\n" ); else printf("file created\n" ); putc('a',fp); fclose(fp); fp=fopen("file1.txt","r"); a=getc(fp); printf("%c\n",a ); fclose(fp); return 0; }
C
#ifndef __CONTACT_H__ #define __CONTACT_H__ #include<stdio.h> #include<string.h> #include<assert.h> #include<stdlib.h> #include<errno.h> enum Option { EXIT, ADD, DEL, SEARCH, MODIFY, SHOW, EMPTY, SORT, }; #define MAX 1000 #define MAX_NAME 20 #define SEX_MAX 5 #define TELE_MAX 12 #define ADDR_MAX 30 #define AEFAULT_SZ 3 #define INC_SZ 2 typedef struct PeoInfo { char name[MAX_NAME]; char sex[SEX_MAX]; short int age; char tele[TELE_MAX]; char addr[ADDR_MAX]; }PeoInfo; typedef struct Contact { //PeoInfo data[MAX];// PeoInfo* data; int sz;//ͨѶ¼ЧϢ int capacity;//ͨѶ¼ĵǰ }Contact; void InitContact(Contact* pcon); void destroyContact(Contact* pcon); void AddContact(Contact* pcon); void ShowContact(const Contact* pcon); void DelContact(Contact* pcon); int CheckCapacity(Contact* pcon); void SaveContact(Contact* pcon); void LoaContact(Contact* pcon); #endif //__CONTACT_H__
C
#include <stdio.h> #include <wchar.h> #include <wctype.h> #include <locale.h> void remove_white(wchar_t *to, const wchar_t *from){ int i = 0; int j = 0; for(; i < wcslen(from); i++){ if(!iswspace(from[i])) to[j++] = from[i]; } to[j] = '\0'; } void backwards(wchar_t *to, const wchar_t *from){ int i = 0; int j = wcslen(from)-1; for(; i<wcslen(from); i++, j--){ to[i] = from[j]; } to[i] = '\0'; } void lowercase(wchar_t *to, const wchar_t *from){ int i = 0; for(; i < wcslen(from); i++){ // if(!iswlower(from[i])) to[i] = towlower(from[i]); } to[i] = '\0'; } _Bool anagram(wchar_t *array){ wchar_t copynowhite[20]; wchar_t copylow[20]; wchar_t copycompare[20]; remove_white(copynowhite, array); lowercase(copylow, copynowhite); backwards(copycompare, copylow); for(int i = 0; i < wcslen(copylow); i++){ if(copylow[i] != copycompare[i]) return 0; } return 1; } void anagramkontroll(wchar_t *array){ wchar_t copynowhite[20]; wchar_t copylow[20]; wchar_t copycompare[20]; remove_white(copynowhite, array); lowercase(copylow, copynowhite); backwards(copycompare, copylow); // for(int i = 0; i < wcslen(copylow); i++){ // if(copylow[i] != copycompare[i]) // return 0; //} printf("%ls\n", copycompare); printf("%ls\n", copylow); } int main(){ setlocale(LC_ALL, "sv_SE.UTF-8"); //Kontroll av varje funktion. wchar_t str[20] = L" Hej på dig!"; wchar_t strrw[20]; wchar_t strbw[20]; wchar_t strlc[20]; remove_white(strrw, str); printf("%ls", strrw); printf("\n"); backwards(strbw, str); printf("%ls\n", strbw); lowercase(strlc, str); printf("%ls\n", strlc); // Kontroll av anagram. wchar_t check[20] = L"Emil Asplund"; if(anagram(check)) printf("Anagram!!\n"); else printf("Ej anagram!\n"); anagramkontroll(check); }
C
#include "../inc/cool.h" char * lowercase(char * string) { int i = 0; while (string[i] != '\0'){ if (string[i] >= 65 && string[i] <= 90){ string[i] += 32; } i++; } return string; } char * put_backslash(char * string) { int i = 0; int length = 0; int pt; char * res; while(string[i]){ if(string[i] == '\'') length ++; i++; } if(!(strchr(string, '\''))) return string; else { if(!(res = malloc(sizeof(char) * (strlen(string) + length + 1)))) return NULL; pt = strchr(string, '\'') - string; strncpy(res, string, pt); res[pt] = '\0'; strcat(strcat(res,"\\"),strchr(string, '\'')); free(string); return res; } } char * get_date(char * date) { int day, month, year; time_t t = time(NULL); struct tm tm = *localtime(&t); day = tm.tm_mday; month = tm.tm_mon + 1; year = tm.tm_year + 1900; sprintf(date,"%d-%d-%d", day, month, year); return date; } char * get_peremption(char * date, char * tmp) { int final; int day, month, year; char dayc[3], monthc[3], yearc[5]; char month30 []= "04,06,09,11"; char month31 []= "01,03,05,07,08,10,12"; sscanf(tmp, "%d", &final); sscanf(date,"%d-%d-%d", &day, &month, &year); if (final == 0){ strcpy(date, "NULL"); return date; } else { while (final != 0){ day++; if(day > 28 && strcmp(monthc, "02")==0 && (year%4)!=0){ month++; day = 01; } else if(day > 29 && strcmp(monthc, "02")==0 && (year%4) == 0){ month++; day = 01; } if ((day > 30) && (strstr(month30, monthc) != NULL)){ month++; day = 01; } if(day > 31 && (strstr(month31, monthc)!= NULL)){ month++; day = 01; } if( month > 12){ month = 01; year ++; } if (day < 10) sprintf(dayc, "0%d", day); else sprintf(dayc, "%d", day); if (month < 10) sprintf(monthc, "0%d", month); else sprintf(monthc, "%d", month); sprintf(yearc, "%d", year); final--; } sprintf(date, "%s-%s-%s", dayc, monthc, yearc); return date; } } int verify_peremption(char * date, char * peremption) { int dayn, monthn, yearn; int daye, monthe, yeare; if (peremption == NULL) return (0); if( strstr(peremption, "NULL") || peremption[0] == '\0') return 0; sscanf(date,"%d-%d-%d", &dayn, &monthn, &yearn); sscanf(peremption,"%d-%d-%d", &daye, &monthe, &yeare); if(yearn > yeare) return 1; if(monthn > monthe) return 1; if( (dayn > daye) && (monthn == monthe) && (yearn == yeare)) return 1; else return 0; } void delete_stock(char * id, MYSQL * con) { char request[200]; sprintf(request, "DELETE FROM contenant WHERE id_stock = '%s'", id); if(mysql_query(con, request)) { finish_with_error(con); } sprintf(request, "DELETE FROM stock WHERE id = '%s'", id); if(mysql_query(con, request)) { finish_with_error(con); } return ; } void adjust_stock() { char * date; char ** res = NULL; char ** res_split; MYSQL * con = NULL; MYSQL_RES * result = NULL; int i = 0; date = malloc(sizeof(char) * 15); if (!(con = connection_bdd(con))) { finish_with_error(con); return ; } get_date(date); if(mysql_query(con, "SELECT * FROM stock")){ finish_with_error(con); return ; } if (!(result = mysql_store_result(con))) { finish_with_error(con); return ; } if (!(res = format_res(result))) return ; while( res[i] ){ res_split = ft_split(res[i], ';'); if( verify_peremption( date , res_split[5]) == 1){ delete_stock(res_split[0], con); } i++; } free(date); free_res(res, 100); free_res(res_split, 10); mysql_free_result(result); mysql_close(con); return ; }
C
// all functions that manages the page table for the process. #include "pagetable.h" #include <stdlib.h> int ptInit(int pageTableSize) { pageTable = (int *)malloc(pageTableSize * sizeof(int)); for (int i = 0; i < pageTableSize; i++) { pageTable[i] = -1; } printf("init done\n"); return 0; }
C
/* *-------------------------------------- * Program Name: CUBE * Author: De2290 aka kafirhamsaeiyya * License: GNU GPLv3 * Description: A simple cube timer for the TI84 Plus CE *-------------------------------------- */ /* Keep these headers */ #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <tice.h> /* Standard headers (recommended) */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <graphx.h> #include "gfx/logo_gfx.h" #define FONT_HEIGHT 8 /* Put your function prototypes here */ void dispSprite_Centered(gfx_sprite_t *sprite); void print_Time(float elasped); void print_TextCentered(char *text); /* Put all your globals here */ void main(void) { char *cubewelcome = "Cube Timer"; real_t cubeFinish_time; list_t *times_List; gfx_Begin(); gfx_SetPalette(logo_gfx_pal, sizeof_logo_gfx_pal, 0); gfx_SetTextFGColor(255); gfx_FillScreen(0); gfx_SetTextTransparentColor(1); gfx_SetTextBGColor(0); print_TextCentered(cubewelcome); dispSprite_Centered(rubikcube); print_Time(0.0f); timer_Control = TIMER1_DISABLE; timer_1_Counter = 0; while (!os_GetCSC()); timer_Control = TIMER1_ENABLE | TIMER1_32K | TIMER1_UP; do { float elapsed = (float)atomic_load_increasing_32(&timer_1_Counter) / 32768; print_Time(elapsed); cubeFinish_time = os_FloatToReal(elapsed); } while (!os_GetCSC()); times_List = ti_MallocList(5); times_List->items[0] = cubeFinish_time; ti_SetVar(TI_REAL_LIST_TYPE, ti_L1, times_List); free(times_List); while (!os_GetCSC()); gfx_End(); } /* Put other functions here */ void dispSprite_Centered(gfx_sprite_t *sprite) { gfx_Sprite(sprite, (LCD_WIDTH - 60) / 2, (LCD_HEIGHT - 60) / 2); } void print_Time(float elapsed) { real_t elapsed_real; char str[10]; elapsed_real = os_FloatToReal(elapsed <= 0.001f ? 0.0f : elapsed); os_RealToStr(str, &elapsed_real, 8, 1, 2); gfx_PrintStringXY(str, (LCD_WIDTH - gfx_GetStringWidth(str)) / 2, (LCD_HEIGHT - FONT_HEIGHT) / 2+60); } void print_TextCentered(char *text) { gfx_PrintStringXY(text, (LCD_WIDTH - gfx_GetStringWidth(text)) / 2, (LCD_HEIGHT - FONT_HEIGHT) / 2-60); }
C
/* * interrupts.c * * Note: By the default the FIQ interruptions will remain disabled. */ #include <debug.h> #include <stdbool.h> #include <stdio.h> #include <stdint.h> #include "../devices/bcm2835.h" #include "../devices/timer.h" #include "flags.h" #include "interrupt.h" #include "thread.h" /* Number of BCM2853 interrupts. */ #define IRQ_COUNT 64 /* Functions defined in interruptsHandlers.s. */ extern uint32_t get_cpsr_value(); extern void enable_irq_interruptions(); extern void disable_irq_interruptions(); extern void disable_fiq_interruptions(); /* Interrupt handler functions for each interrupt. */ static interrupts_handler_function *irq_handlers[IRQ_COUNT]; /* Names for each interrupt, for debugging purposes. */ static const char *irq_names[IRQ_COUNT]; static interrupts_handler_function *swi_handler; static const char *swi_name; /* External interrupts are those generated by devices outside the CPU, such as the timer. External interrupts run with interrupts turned off, so they never nest, nor are they ever pre-empted. Handlers for external interrupts also many not sleep, although they may invoke interrupts_yield_on_return() to request that a new process be scheduled just before the interrupt returns. */ static bool in_external_interrupt; /* Are we processing an external interrupt (IRQ)? */ /* This variable is similar to in_interrupts_context, the difference is that this flag is active till the end of the processing of the IRQ. */ static bool was_irq_generated; /*Was an IRQ generated and is still being processed? */ static bool yield_on_return; /* Should we yield on interrupt return? */ /* Returns true if the IRQ number is valid, otherwise false. */ static bool interrupts_is_valid_irq_number(unsigned char irq_number); /* Enables the given IRQ in the interrupt controller (BCM2835 SoC - System on Chip). */ static void interrupts_enable_irq(unsigned char irq_number); /* Dispatches the pending IRQ. */ static void interrupts_dispatch_pending_irq(struct interrupts_stack_frame *stack_frame, int32_t irq_number); /* Dummy interrupt handler. */ static void dummy_handler(struct interrupts_stack_frame *stack_frame); /* * Initializes the interrupt system. It assumes that the interrupts FIQ and IRQ are disabled. * * Note: By the default the FIQ interruptions will remain disabled. */ void interrupts_init(void) { printf("\nInitializing interrupts....."); int32_t i; was_irq_generated = false; in_external_interrupt = false; yield_on_return = false; /* Initialize irq_names and irq_handlers. */ for (i = 0; i < IRQ_COUNT; i++) { irq_names[i] = "Unknown"; irq_handlers[i] = dummy_handler; } // FIQ interrupts remain disabled. disable_fiq_interruptions(); // disable_fiq_interruptions() is defined in interruptsHander.s } /* Register the IRQ handler for the given interrupt number. The BCM2835 has 64 IRQ interruptions * that are enumerated from 0 to 63. */ void interrupts_register_irq(unsigned char irq_number, interrupts_handler_function *handler, const char *name) { if (!interrupts_is_valid_irq_number(irq_number)) { return; } irq_handlers[irq_number] = handler; irq_names[irq_number] = name; // Enables the IRQ in the Interrupt Controller. interrupts_enable_irq(irq_number); } /* Register the SWI hander for the Software interrupts. */ void interrupts_register_swi(interrupts_handler_function *handler, const char *name) { swi_handler = handler; swi_name = name; } /* Return the IRQ name that correspond to the interrupt number. */ const char* interrupts_get_irq_name(unsigned char irq_number) { if (!interrupts_is_valid_irq_number(irq_number)) { return '\0'; } return irq_names[irq_number]; } /* Return the SWI name. */ const char* interrupts_get_swi_name() { return swi_name; } /* Returns the interrupt level. */ enum interrupts_level interrupts_get_level(void) { uint32_t cpsr = get_cpsr_value(); // get_cpsr_value() is defined in interruptsHandlers.s. // When the IRQ flag is set, it means that IRQ interrupts are disabled, otherwise are enabled. return cpsr & FLAG_IRQ ? INTERRUPTS_OFF : INTERRUPTS_ON; } /* Sets the interrupts level and returns the previous one. */ enum interrupts_level interrupts_set_level(enum interrupts_level level) { return level == INTERRUPTS_ON ? interrupts_enable() : interrupts_disable(); } /* Enables the interrupts and returns the previous one. */ enum interrupts_level interrupts_enable(void) { enum interrupts_level old_level = interrupts_get_level(); // TODO ADD THE ASSERT (!intr_context ()); /* Enables the IRQ interrupts by setting the IRQ interrupt flag in the * CPSR (Current Process Status Register). */ enable_irq_interruptions(); // enable_irq_interruptions() is defined in interruptsHandler.s. return old_level; } /* Disables the interrupts and returns the previous one. */ enum interrupts_level interrupts_disable(void) { enum interrupts_level old_level = interrupts_get_level(); /* Disables the IRQ interrupts by clearing the IRQ interrupt flag in the CPSR (Current Process Status Register). */ disable_irq_interruptions(); // disable_irq_interruptions() is defined in interruptsHandler.s. return old_level; } /* Prints status of the interrupts. */ void interrupts_print_status(void) { uint32_t cpsr = get_cpsr_value(); // get_cpsr_value() is defined in interruptsHandlers.s. bool enable_irq_status = !(cpsr & FLAG_IRQ); bool enable_fiq_status = !(cpsr & FLAG_FIQ); if (enable_irq_status) { printf("\nIRQ ON"); } else { printf("\nIRQ OFF"); } if (enable_fiq_status) { printf("\nFIQ ON"); } else { printf("\nFIQ OFF"); } } /* Returns true during processing of an external interrupt and false at all other times. */ bool interrupts_context(void) { return in_external_interrupt; } /* Returns true if an IRQ was generated. It is similar to interrupts_context, the difference is that this flag is active till the end of the processing of the IRQ. */ bool interrupts_was_irq_generated(void) { return was_irq_generated; } /* During processing of an external interrupt, directs the interrupt handler to yield to a new process just before returning from the interrupt. May not be called at any other time. */ void interrupts_yield_on_return (void) { yield_on_return = true; } /* IRQ Dispatcher * * Dispatches the IRQ interrupt requests. Every time that an interrupt happens, a bit that refers * to the specify interrupt number is marked in the interrupts register indicating that that * interrupt was triggered. * */ void interrupts_dispatch_irq(struct interrupts_stack_frame *stack_frame) {; unsigned short blue = 0x1f; int32_t foreColour = GetForeColour(); SetForeColour(blue); printf("\nKERNEL TAKING OVER - Dispatching IRQ"); /* External interrupts are special. We only handle one at a time (so interrupts must be off). An external interrupt handler cannot sleep. */ ASSERT(interrupts_get_level() == INTERRUPTS_OFF); ASSERT(!interrupts_context()); ASSERT(!interrupts_was_irq_generated()); was_irq_generated = true; in_external_interrupt = true; /* In external interrupt context. */ yield_on_return = false; int32_t i; // First half of the pending interrupts (0-31) int32_t *interrupt_ptr = (int32_t *) INTERRUPT_REGISTER_PENDING_IRQ_0_31; for (i = 0; i < IRQ_COUNT / 2; i++) { bool enable = *interrupt_ptr & (1 << i); if (enable) { interrupts_dispatch_pending_irq(stack_frame, i); } } // Second half of the pending interrupts (32-63) interrupt_ptr = (int32_t *) INTERRUPT_REGISTER_PENDING_IRQ_32_63; for (i = 0; i < IRQ_COUNT / 2; i++) { bool enable = *interrupt_ptr & (1 << i); if (enable) { interrupts_dispatch_pending_irq(stack_frame, i); } } SetForeColour(foreColour); ASSERT(interrupts_get_level() == INTERRUPTS_OFF); ASSERT(interrupts_context()); in_external_interrupt = false; /* End of the interrupt context. */ if (yield_on_return) thread_yield(); was_irq_generated = false; } /* SWI Dispatcher * * Dispatches the SWI interrupt requests. */ void interrupts_dispatch_swi(struct interrupts_stack_frame *stack_frame, int32_t swi_number) { printf("\nInterrupt SWI handler: #%d", swi_number); } void interrupts_debug(struct interrupts_stack_frame *stack_frame) { printf("\nCPSR: "); debug_print_bits_int(stack_frame->cpsr); printf("\nr13_sp: %d", (int32_t) stack_frame->r13_sp); printf("\nr14_lr: %d", (int32_t) stack_frame->r14_lr); printf("\nr15_pc: %d", (int32_t) stack_frame->r15_pc); printf("\nr0: %d", stack_frame->r0); printf("\nr1: %d", stack_frame->r1); printf("\nr2: %d", stack_frame->r2); printf("\nr3: %d", stack_frame->r3); printf("\nr4: %d", stack_frame->r4); printf("\nr5: %d", stack_frame->r5); printf("\nr6: %d", stack_frame->r6); printf("\nr7: %d", stack_frame->r7); printf("\nr8: %d", stack_frame->r8); printf("\nr9: %d", stack_frame->r9); printf("\nr10: %d", stack_frame->r10); printf("\nr11: %d", stack_frame->r11); printf("\nr12: %d", stack_frame->r12); } /* Dispatches the pending IRQ. */ static void interrupts_dispatch_pending_irq(struct interrupts_stack_frame *stack_frame, int32_t irq_number) { irq_handlers[irq_number](stack_frame); } /* Dummy interrupt handler. */ static void dummy_handler(struct interrupts_stack_frame *stack_frame) { printf("\nDummy Interrupt handler......"); } /* Returns true if the IRQ number is valid, otherwise false. */ static bool interrupts_is_valid_irq_number(unsigned char irq_number) { if (irq_number >= IRQ_COUNT) { return false; } return true; } /* Enables the given IRQ in the interrupt controller (BCM2835 SoC - System on Chip). */ static void interrupts_enable_irq(unsigned char irq_number) { if (!interrupts_is_valid_irq_number(irq_number)) { return; } int32_t half_interrupts = IRQ_COUNT / 2; int32_t *interrupt_ptr; if (irq_number < half_interrupts) { interrupt_ptr = (int32_t *) (INTERRUPT_REGISTER_ENABLE_IRQ_0_31); *interrupt_ptr = *interrupt_ptr | (1 << irq_number); } else { irq_number = irq_number - half_interrupts; interrupt_ptr = (int32_t *) (INTERRUPT_REGISTER_ENABLE_IRQ_32_63); *interrupt_ptr = *interrupt_ptr | (1 << irq_number); } }
C
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <error.h> #include <strings.h> #include <unistd.h> #include <arpa/inet.h> #include <string.h> #include <signal.h> #include <errno.h> #include <fcntl.h> #include <sys/time.h> #include <sys/ioctl.h> #include <netdb.h> #include <stdarg.h> #define MAX_DATA 4096 void main(int argc, char **argv) { struct sockaddr_in remote_server; /* variable names for the socket addr data structure */ int sock, len, sent; char input[MAX_DATA]; char *request = "GET HTTP/1.1\r\n"; int srvlen = sizeof(remote_server); if (argc != 3) { printf("Too few arguments \n"); printf("Usage: %s <IP Addr> <Port Number> \n", argv[0]); exit(1); } /* socket creation */ if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("socket"); exit(1); } remote_server.sin_family = AF_INET; remote_server.sin_port = htons(atoi(argv[2])); remote_server.sin_addr.s_addr = inet_addr(argv[1]); bzero(&remote_server.sin_zero, 0); sent = sendto(sock, request, strlen(request), 0, (struct sockaddr *)&remote_server, sizeof(remote_server)); printf("Sent\n"); len = recvfrom(sock, input, sizeof(input), 0, (struct sockaddr *)&remote_server, &srvlen); printf("Received\n "); input[len] = '\0'; printf("Received from, server : %s\n", input); close(sock); exit(0); }
C
/**************** Elad Zohar ezohar pa2 ****************/ #include<stdlib.h> #include<stdio.h> #include"List.h" #ifndef _BIGINTEGER_H_INCLUDE_ #define _BIGINTEGER_H_INCLUDE_ // Exported type ------------------------------------------------------------- // BigInteger reference type typedef struct BigIntegerObj* BigInteger; // Constructors-Destructors --------------------------------------------------- // Returns a reference to a new BigInteger object in the zero state. BigInteger newBigInteger(void); // Frees heap memory associated with *pN, sets *pN to NULL. void freeBigInteger(BigInteger* pN); // Access functions ----------------------------------------------------------- // Returns -1 if N is negative, 1 if N is positive, and 0 if N is in the zero state. int sign(BigInteger N); // Returns -1 if A<B, 1 if A>B, and 0 if A=B. int compare(BigInteger A, BigInteger B); // Return true (1) if A and B are equal, false (0) otherwise. int equals(BigInteger A, BigInteger B); // Manipulation procedures ---------------------------------------------------- // Re-sets N to the zero state. void makeZero(BigInteger N); // Reverses the sign of N: positive <--> negative. Does nothing if N is in the zero state. void negate(BigInteger N); // BigInteger Arithmetic operations ----------------------------------------------- // Returns a reference to a new BigInteger object representing the decimal integer represented in base 10 // by the string s. Pre: s is a non-empty string containing only base ten digits {0,1,2,3,4,5,6,7,8,9} and // an optional sign {+, -} prefix. BigInteger stringToBigInteger(char* s); // Returns a reference to a new BigInteger object in the same state as N. BigInteger copy(BigInteger N); // Places the sum of A and B in the existing BigInteger S, overwriting its current state: S = A + B void add(BigInteger S, BigInteger A, BigInteger B); // Returns a reference to a new BigInteger object representing A + B. BigInteger sum(BigInteger A, BigInteger B); // Places the difference of A and B in the existing BigInteger D, overwriting its current state: D = A - B void subtract(BigInteger D, BigInteger A, BigInteger B); // Returns a reference to a new BigInteger object representing A - B. BigInteger diff(BigInteger A, BigInteger B); // Places the product of A and B in the existing BigInteger P, overwriting its current state: P = A*B void multiply(BigInteger P, BigInteger A, BigInteger B); // Returns a reference to a new BigInteger object representing A*B BigInteger prod(BigInteger A, BigInteger B); // Other operations ----------------------------------------------------------- // Prints a base 10 string representation of N to filestream out. void printBigInteger(FILE* out, BigInteger N); #endif
C
#include <stdio.h> /** *main- entry point *Return: 0 when success then quit */ int main(void) { unsigned long int pp = 1; unsigned long int p = 2; unsigned long int n = p + pp; int c = 4; printf("%lu, %lu, %lu, ", pp, p, n); do { pp = p; p = n; n = pp + p; printf("%lu, ", n); c++; } while (c < 98); n = n + p; printf("%lu\n", n); return (0); }
C
#include<stdio.h> #include<conio.h> void main(void) { int a[6],i,sum=0; clrscr(); printf(" Enter a 6-digit number:"); scanf("%d %d %d %d %d %d",&a[0],&a[1],&a[2],&a[3],&a[4],&a[5]); printf(" What you entered is:"); for(i=0; i<6; i++) printf("%d",a[i]); printf("\n The inverse is:"); for(i=5; i>=0; i--) printf("%d",a[i]); printf("\n The sum of numbers is:"); for(i=0; i<6; i++) sum+=a[i]; printf("%d",sum); printf("\n Even number(s) (is/are):"); for(i=0; i<6; i++) if(a[i]%2==0) printf("%d ",a[i]); printf("\n Odd number(s) (is/are):"); for(i=0; i<6; i++) if(a[i]%2!=0) printf("%d ",a[i]); gotoxy(1,24); printf(" Press any key to exit..."); getch(); }
C
#include<stdio.h> int main() { int L,B,H,c; printf("enter the volume of cuboid\n"); scanf("%d%d%d",&L,&B,&H); c=L*B*H; printf("%d",c); return 0; }
C
#include "helpers.h" #include <math.h> // Convert image to grayscale void grayscale(int height, int width, RGBTRIPLE image[height][width]) { int w; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { w = ((image[i][j].rgbtGreen + image[i][j].rgbtBlue + image[i][j].rgbtRed) / 3.0) + 0.5; image[i][j].rgbtGreen = w; image[i][j].rgbtRed = w; image[i][j].rgbtBlue = w; } } return; } // Reflect image horizontally void reflect(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE tmp[height][width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { tmp[i][width - j - 1] = image[i][j]; } } for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { image[i][j] = tmp[i][j]; } } return; } // Blur image void blur(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE tmp[height][width]; RGBTRIPLE colors[9]; int cblue = 0; int cgreen = 0; int cred = 0; int z = 0; for (int i = 0; i < 9; i++) { colors[i].rgbtBlue = 0; colors[i].rgbtGreen = 0; colors[i].rgbtRed = 0; } for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { z = 0; cblue = 0; cgreen = 0; cred = 0; for (int k = -1; k <= 1; k++) { if ((i + k >= 0) && (i + k < height)) { for (int l = -1; l <= 1; l++) { if ((j + l >= 0) && (j + l < width)) { colors[z] = image[i + k][j + l]; z++; } } } } for (int m = 0; m < z; m++) { cblue += colors[m].rgbtBlue; cgreen += colors[m].rgbtGreen; cred += colors[m].rgbtRed; } cblue = (cblue / (float) z) + 0.5; cgreen = (cgreen / (float) z) + 0.5; cred = (cred / (float) z) + 0.5; tmp[i][j].rgbtBlue = cblue; tmp[i][j].rgbtGreen = cgreen; tmp[i][j].rgbtRed = cred; } } for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { image[i][j] = tmp[i][j]; } } return; } // Detect edges void edges(int height, int width, RGBTRIPLE image[height][width]) { typedef struct { int x; int y; } color; RGBTRIPLE tmp[height][width]; color blue; color green; color red; int cblue = 0; int cgreen = 0; int cred = 0; const int GX[3][3] = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}}; const int GY[3][3] = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}}; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { blue.x = 0; blue.y = 0; green.x = 0; green.y = 0; red.x = 0; red.y = 0; for (int k = -1; k <= 1; k++) { if ((i + k >= 0) && (i + k < height)) { for (int l = -1; l <= 1; l++) { if ((j + l >= 0) && (j + l < width)) { blue.x += image[i + k][j + l].rgbtBlue * GX[k + 1][l + 1]; green.x += image[i + k][j + l].rgbtGreen * GX[k + 1][l + 1]; red.x += image[i + k][j + l].rgbtRed * GX[k + 1][l + 1]; blue.y += image[i + k][j + l].rgbtBlue * GY[k + 1][l + 1]; green.y += image[i + k][j + l].rgbtGreen * GY[k + 1][l + 1]; red.y += image[i + k][j + l].rgbtRed * GY[k + 1][l + 1]; } } } } cblue = sqrt(blue.x * blue.x + blue.y * blue.y) + 0.5; if (cblue > 255) { cblue = 255; } cgreen = sqrt(green.x * green.x + green.y * green.y) + 0.5; if (cgreen > 255) { cgreen = 255; } cred = sqrt(red.x * red.x + red.y * red.y) + 0.5; if (cred > 255) { cred = 255; } tmp[i][j].rgbtBlue = cblue; tmp[i][j].rgbtGreen = cgreen; tmp[i][j].rgbtRed = cred; } } for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { image[i][j] = tmp[i][j]; } } return; }
C
/* ** my_show_wordtab.c for wordtab in /home/soumph_s ** ** Made by sirininh soumpholphakdy ** Login <[email protected]> ** ** Started on Mon May 4 15:15:06 2015 sirininh soumpholphakdy ** Last update Mon May 4 15:31:38 2015 sirininh soumpholphakdy */ #include <stdlib.h> int **my_show_wordtab(char **tab) { int a; i = 0; if (tab == NULL) return (NULL); while (tab[i] != NULL) { my_putchar(i + '0'); my_putstr(tab[i]); my_putchar(' '); my_putchar('\n'); i++; } return (NULL); int main() { my_show_wordtab(); }
C
#include <stdlib.h> #include <stdio.h> #include "fila.h" p_fila criarfila(){ p_fila f; f = malloc(sizeof(Fila)); if(f == NULL){ exit(1); } f->ini = f->fim = NULL; f->tam = 0; return f; } void enfileira(p_fila f, int x){ p_no novo; novo = malloc(sizeof(No)); if(novo == NULL){ exit(1); } novo->as = 0; novo->mao = x; if(x == 11){ novo->as++; } novo->play = f->tam; f->tam++; novo->prox = NULL; if(f->ini == NULL){ f->ini = novo; }else{ f->fim->prox = novo; } f->fim = novo; } void desenfileira(p_fila f){ p_no primeiro; primeiro = f->ini; f->ini = f->ini->prox; free(primeiro); } void troca(p_fila f){ f->fim->prox = f->ini; f->fim = f->ini; f->ini = f->ini->prox; f->fim->prox = NULL; } int soma(int nova_mao, int x){ return nova_mao + x; } void liberar_fila(p_fila f){ free(f); }
C
#include "include/types.h" #include "include/stdio.h" #include "include/errno.h" #include "include/string.h" #include "include/net/net.h" // negative hex skipped int hex_str_to_val(const char *str, unsigned long *val) { int len = 0; unsigned long tmp = 0; while (*str != '\0') { if (*str >= '0' && *str <= '9') { tmp <<= 4; tmp |= *str - '0'; } else if (*str >= 'a' && *str <= 'f') { tmp <<= 4; tmp |= *str - 'a' + 10; } else if (*str >= 'A' && *str <= 'F') { tmp <<= 4; tmp |= *str - 'A' + 10; } else return -EINVAL; str++; len++; if (len > sizeof(tmp) * 2) return -EINVAL; } *val = tmp; return len; } int hex_str2val_bylen(const char *str, void *val, unsigned char len) { int cnt = 0; unsigned long tmp = 0; while (cnt < len) { if (*str >= '0' && *str <= '9') { tmp <<= 4; tmp |= *str - '0'; } else if (*str >= 'a' && *str <= 'f') { tmp <<= 4; tmp |= *str - 'a' + 10; } else if (*str >= 'A' && *str <= 'F') { tmp <<= 4; tmp |= *str - 'A' + 10; } else return -EINVAL; str++; cnt++; if (cnt > sizeof(tmp) * 2) return -EINVAL; } switch (len) { case 2: *(unsigned char*)val = tmp; break; case 4: *(unsigned short*)val = tmp; break; case 8: *(unsigned int *)val = tmp; break; } return cnt; } #define MAX_DEC_LEN 32 int val_to_dec_str(char *str, long val) { char buff[MAX_DEC_LEN]; int i = MAX_DEC_LEN - 1, j = 0; if (val < 0) { str[j++] = '-'; val = -val; } do { buff[i] = val % 10 + '0'; val /= 10; i--; } while (val); while (++i < MAX_DEC_LEN) { str[j] = buff[i]; j++; } str[j] = '\0'; return j; } #define MAX_HEX_LEN (sizeof(unsigned long) * 2 + 1) int val_to_hex_str(char *str, unsigned long val) { char buff[MAX_HEX_LEN]; int i = MAX_HEX_LEN - 1, j = 0; while (val) { unsigned long num = val & 0xf; if (num < 0xa) buff[i] = (char)num + '0'; else buff[i] = (char)(num - 0xa) + 'a'; val >>= 4; i--; } while (++i < MAX_HEX_LEN) { str[j] = buff[i]; j++; } str[j] = '\0'; return j; } // fixme: merge the following 2 functions into 1 int dec_str_to_long(const char *str, long *val) { long tmp = 0; const char *num = str; if ('-' == *num) num++; while (*num != '\0') { if (ISDIGIT(*num)) tmp = 10 * tmp + *num - '0'; else return -EINVAL; num++; } if ('-' == *str) *val = -tmp; else *val = tmp; return num - str; } int dec_str_to_int(const char *str, int *val) { int tmp = 0; const char *num = str; if ('-' == *num) num++; while (*num != '\0') { if (ISDIGIT(*num)) tmp = 10 * tmp + *num - '0'; else return -EINVAL; num++; } if ('-' == *str) *val = -tmp; else *val = tmp; return num - str; } /* * Convert human string to value. e.g.: * "3G40M512K256" */ #define G_MARK (1 << 7) #define M_MARK (1 << 6) #define K_MARK (1 << 5) int hr_str_to_val(const char *str, unsigned long *val) { __u8 mark = 0; __u32 num = 0, tmp = 0; while (1) { switch (*str) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': tmp = tmp * 10 + *str - '0'; break; case 'g': case 'G': if (mark & (G_MARK | M_MARK | K_MARK)) goto error; num += tmp << 30; tmp = 0; mark |= G_MARK; break; case 'm': case 'M': if (mark & (M_MARK | K_MARK)) goto error; num += tmp << 20; tmp = 0; mark |= M_MARK; break; case 'k': case 'K': if (mark & K_MARK) goto error; num += tmp << 10; tmp = 0; mark |= K_MARK; break; case '\0': num += tmp; *val = num; return 0; default: goto error; } str++; } error: return -EINVAL; } int str_to_val(const char *str, unsigned long *val) { int ret; unsigned long tmp; if ('0' == *str && ('x' == *(str + 1) || 'X' == *(str + 1))) ret = hex_str_to_val(str + 2, &tmp); else ret = dec_str_to_long(str, (long *)&tmp); if (ret >= 0) *val = tmp; return ret; } #define KB_MASK ((1 << 10) - 1) int val_to_hr_str(unsigned long val, char str[]) { char *ch = str; __u32 sect; int i; struct { int shift; char sign; } soff[] = {{30, 'G'}, {20, 'M'}, {10, 'K'}, {0, 'B'}}; for (i = 0; i < ARRAY_ELEM_NUM(soff); i++) { sect = (val >> soff[i].shift) & KB_MASK; if (sect) { ch += val_to_dec_str(ch, sect); *ch++ = soff[i].sign; } } *ch = '\0'; return ch - str; } int str_to_ip(__u8 ip_val[], const char *ip_str) { int dot = 0; unsigned int num = 0; const char *iter = ip_str; #if 1 while (*iter) { if (ISDIGIT(*iter)) { num = 10 * num + *iter - '0'; } else if ('.' == *iter && num <= 255 && dot < 3) { ip_val[dot] = (__u8)num; dot++; num = 0; } else { DPRINT("%s() line %d: invalid IP string \"%s\"\n", __func__, __LINE__, ip_str); return -EINVAL; } iter++; } if (dot < 3 || num > 255) return -EINVAL; ip_val[dot] = num; #else while (1) { switch (*iter) { case '0' ... '9': num = 10 * num + *iter - '0'; break; case '.': if (num > 255 || 3 == dot) return -EINVAL; ip_val[dot] = (__u8)num; dot++; num = 0; break; case '\0': if (3 != dot) return -EINVAL; ip_val[dot] = num; return 0; default: return -EINVAL; } iter++; } #endif return 0; } /* int ip_to_str(char buf[], const __u32 ip) { ksnprintf(buf, "%d.%d.%d.%d", ip & 0xff, (ip >> 8) & 0xff, (ip >> 16) & 0xff, (ip >> 24) & 0xff); return 0; } */ // fixme! int str_to_mac(__u8 mac[], const char *str) { int i, j; __u32 num; char buf[MAC_STR_LEN]; char *p = buf; strncpy(buf, str, MAC_STR_LEN); for (i = j = 0; i <= MAC_STR_LEN && j < MAC_ADR_LEN; i++) { if (':' == buf[i]|| '\0' == buf[i]) { buf[i] = '\0'; if (hex_str_to_val(p, (unsigned long *)&num) <= 0 || num > 255) goto error; mac[j++] = num; p = buf + i + 1; } } if (j != MAC_ADR_LEN) goto error; return 0; error: DPRINT("%s() line %d: invalid MAC address \"%s\"\n", __func__, __LINE__, str); return -EINVAL; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parce_argc.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: npiatiko <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/29 14:41:01 by npiatiko #+# #+# */ /* Updated: 2019/01/29 14:41:01 by npiatiko ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" void ft_collect_flags(char *av, char *optns) { static int i = 0; while (*av) if (ft_strchr("ABCFGHLOPRSTUW@abcdefghiklmnopqrstuwx1", *av)) { if (*av == 'f') optns[i++] = 'a'; optns[i++] = *av; *av++ = 0; } else { ft_printf("illegal option -- %c\nusage: " "ls [-ABCFGHLOPRSTUWabcdefghiklmnopqrstuwx1] [file ...]\n", *av); exit(1); } } void ft_parse_optns(int ac, char **av, char *options) { int j; j = 1; while (ac - 1) { if (*av[j] == '-' && *(av[j] + 1)) { *av[j]++ = 0; ft_collect_flags(av[j], options); } else break ; j++; ac--; } } t_file *ft_sort_args(t_file *list, t_file **errs, char *optns) { char a[100]; *errs = ft_sort_tree(*errs, a); return (ft_sort_tree(list, optns)); } t_file *ft_parse_args(int ac, char **av, t_file **errs, char *optns) { t_file *list; t_file *tmp; struct stat buf; list = 0; *errs = 0; while (ac-- - 1 && !**av) av++; while (ac--) { tmp = ft_new_node(*av[0] == '/' ? "" : ".", *av, optns); if (lstat(*av, &buf)) { tmp->next = *errs; *errs = tmp; } else { tmp->next = list; list = tmp; } av++; } return (ft_sort_args(list, errs, optns)); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> int ahtoi(char ch) { int tmp; tmp = toupper(ch); tmp = (ch - '0'); if(tmp > 9) tmp = (tmp - 7); return tmp; } int main(void) { char ch; int i = 0; int j = 0; char state = 0; int rlen = 0; int radd = 0; int rtyp = 0; char rdat[4]; printf("Please paste your hex code into teminal:\n"); while(!feof(stdin)) { ch = fgetc(stdin); switch(state) { case 0 : if(ch == ':') { i = 2; j = 0; rlen = 0; state = 1; } break; case 1 : rlen = (rlen << 4) + ahtoi(ch); i -= 1; if(i == 0) { i = 4; j = 0; rlen = rlen / 2; radd = 0; state = 2; } break; case 2 : radd = (radd << 4) + ahtoi(ch); i -= 1; j += 1; if(i == 0) { i = 2; j = 0; radd = radd / 2; rtyp = 0; state = 3; } break; case 3 : rtyp = (rtyp << 4) + ahtoi(ch); i -= 1; if(i == 0) { i = 4; j = 0; if(rtyp == 0) { fprintf(stdout, "@%04X\n", radd); state = 4; } else { state = 0; } } break; case 4 : rdat[j] = ch; i -= 1; j += 1; if(i == 0) { i = 4; j = 0; fprintf(stdout, "%c%c%c\n", rdat[3], rdat[0], rdat[1]); rlen -= 1; if(rlen == 0) { state = 0; } else { state = 4; } } break; default : break; } } return 0; }
C
#include <stdio.h> #include <stdlib.h> struct bstNode { int val; struct bstNode *l; struct bstNode *r; }; typedef struct bstNode bstNode; int add_bst(bstNode **root, int val); int printTreeInOrder(bstNode *root); int printLevelOrder(bstNode *root); int add_bst(bstNode **root,int val) { if (root == NULL){ return -1; } if (*root == NULL) { *root=(bstNode*)malloc(sizeof(bstNode)); if (*root==NULL){ return -1; } (*root)->val = val; return 1; } if (val<(*root)->val){ return(add_bst(&(*root)->l,val)); } else if(val>(*root)->val){ return(add_bst(&(*root)->r,val)); }} int printTreeInOrder(bstNode *root){ if (root == NULL){ return -1; } if ((root)->l != NULL){ (printTreeInOrder((root)->l)); } printf("%d\n",(root)->val); if ((root)->r != NULL){ (printTreeInOrder((root)->r)); } return 1; } int printLevelOrder(bstNode *root){ if (root == NULL){ return -1; } printLevelOrder((root)->l); printf("%d\n",(root->val)); printLevelOrder((root)->r); return 0; } int main(void) { bstNode *root=NULL; int value = 0; while(scanf("%d", &value) != EOF){ add_bst(&root,value); } printTreeInOrder(root); return 0; }
C
/* THIS FILE IS ONLY FOR TESTING */ #include "player.h" #include "game.h" #include "card.h" #include "deck.h" void testDeckInit() { //test if deal worked for (int i = 0; i < 52; i++ ) { printf("suit: %d, number: %d\n",deck[i].suit,deck[i].type); } } void testDeal() { //test if deal worked for (int i = 0; i < 6; i++ ) { printf("suit: %d, number: %d\n",players[0].hand.cards[i]->suit,players[0].hand.cards[i]->type); } } void testShuffle() { //test if deal worked for (int i = 0; i < 52; i++ ) { printf("suit: %d, number: %d\n",shuffled[i]->suit,shuffled[i]->type); } } void testCribContents() { //print cards in crib for (char i = 0; i < CRIB_SIZE; i++) { if (players[dealer].crib.cards[i]) { printf("crib slot %d = %p, suit = %d\n", i, players[dealer].crib.cards[i],players[dealer].crib.cards[i]->suit); } } } void printDeck() { for (int i = 0; i < 52; i++) { printf("deck: %d = val: %d of suit: %d\n",i,deck[i].type,deck[i].suit); } /* deck: 0 = val: 1 of suit: 1 deck: 1 = val: 2 of suit: 2 deck: 2 = val: 3 of suit: 3 deck: 3 = val: 4 of suit: 4 deck: 4 = val: 5 of suit: 5 deck: 5 = val: 6 of suit: 6 deck: 6 = val: 7 of suit: 7 deck: 7 = val: 8 of suit: 8 deck: 8 = val: 9 of suit: 9 deck: 9 = val: 10 of suit: 10 deck: 10 = val: 11 of suit: 11 deck: 11 = val: 12 of suit: 12 deck: 12 = val: 13 of suit: 13 deck: 13 = val: 1 of suit: 1 deck: 14 = val: 2 of suit: 2 deck: 15 = val: 3 of suit: 3 deck: 16 = val: 4 of suit: 4 deck: 17 = val: 5 of suit: 5 deck: 18 = val: 6 of suit: 6 deck: 19 = val: 7 of suit: 7 deck: 20 = val: 8 of suit: 8 deck: 21 = val: 9 of suit: 9 deck: 22 = val: 10 of suit: 10 deck: 23 = val: 11 of suit: 11 deck: 24 = val: 12 of suit: 12 deck: 25 = val: 13 of suit: 13 deck: 26 = val: 1 of suit: 1 deck: 27 = val: 2 of suit: 2 deck: 28 = val: 3 of suit: 3 deck: 29 = val: 4 of suit: 4 deck: 30 = val: 5 of suit: 5 deck: 31 = val: 6 of suit: 6 deck: 32 = val: 7 of suit: 7 deck: 33 = val: 8 of suit: 8 deck: 34 = val: 9 of suit: 9 deck: 35 = val: 10 of suit: 10 deck: 36 = val: 11 of suit: 11 deck: 37 = val: 12 of suit: 12 deck: 38 = val: 13 of suit: 13 deck: 39 = val: 1 of suit: 1 deck: 40 = val: 2 of suit: 2 deck: 41 = val: 3 of suit: 3 deck: 42 = val: 4 of suit: 4 deck: 43 = val: 5 of suit: 5 deck: 44 = val: 6 of suit: 6 deck: 45 = val: 7 of suit: 7 deck: 46 = val: 8 of suit: 8 deck: 47 = val: 9 of suit: 9 deck: 48 = val: 10 of suit: 10 deck: 49 = val: 11 of suit: 11 deck: 50 = val: 12 of suit: 12 deck: 51 = val: 13 of suit: 13 */ } void cutOverride() { topCard = &deck[4]; } /* results in unshuffled deck */ void shuffleOverride(){ //Leave this for testing with sequences /* //clear shuffled slots first memset(shuffled,0,sizeof(Card*)*DECK_SIZE); //set each pointer to NULL //for all 52 cards for (char i = 0; i < DECK_SIZE; i++) { shuffled[i] = &(deck[i]); //pointer to a card } //leave this for manual testing */ shuffleDeck(); shuffled[0] = &deck[51]; //discared shuffled[1] = &deck[50]; //discared shuffled[2] = &deck[49]; //discared shuffled[3] = &deck[10]; //discared shuffled[4] = &deck[0]; //second (comp) shuffled[5] = &deck[10]; //first (player) shuffled[6] = &deck[1]; //fourth (comp) //go shuffled[7] = &deck[17]; //third (player) shuffled[8] = &deck[2]; //6th (comp) shuffled[9] = &deck[30]; //5th (player) shuffled[10] = &deck[15]; //8th (comp) shuffled[11] = &deck[43]; //7th (player) }
C
/* Copyright (c) 2011 Dietger van Antwerpen ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _FRESNEL_H #define _FRESNEL_H #include "math/vec3.h" #include "color/spectralcolor.h" /** * Computes reflected and transmitted directions according to * Fresnel's formulas. * * @param reflectedOut the computed unit vector of the reflection direction * @param transmittedOut the computed unit vector of the transmission direction * @param normal the normal unit vector of the surface * @param in the direction unit vector of the incoming ray * @param iorRatio the index of refraction of the surface side where * the normal vector points into, divided by the index of refraction * of the opposite side * @return the reflection coefficient */ /* float Fresnel (Vec3 *reflectedOut, Vec3 *transmittedOut, const Vec3 *normal, const Vec3 *in, float iorRatio ) { *transmittedOut = *in; float cos = -v3dot( normal, in ); v3smad( reflectedOut, normal, 2 * cos, transmittedOut ); float tmp = iorRatio * cos; float t = (1 - iorRatio * iorRatio) + tmp * tmp; if (t <= 0) { return 1; } else { v3smul( transmittedOut, in, iorRatio ); float cost = (float) sqrt (t); v3smad( transmittedOut, normal , (iorRatio * cos - cost) , transmittedOut ); v3norm( transmittedOut , transmittedOut ); // Is this realy necceseary?? tmp = (cost - iorRatio * cos) / (cost + iorRatio * cos); float Rs = tmp * tmp; tmp = (cos - iorRatio * cost) / (cos + iorRatio * cost); float Rp = tmp * tmp; return (Rs + Rp) * 0.5f; } } */ /** * Computes reflection coefficient according to * Fresnel's formulas. * * @param normal the normal unit vector of the surface * @param in the direction unit vector of the incoming ray * @param iorRatio the index of refraction of the surface side where * the normal vector points into, divided by the index of refraction * of the opposite side * @return the reflection coefficient */ /* float EvalFresnel (const Vec3 *normal, const Vec3 *in, float iorRatio ) { float cos = -v3dot( normal, in ); float tmp = iorRatio * cos; float t = (1 - iorRatio * iorRatio) + tmp * tmp; if (t <= 0) { return 1; } else { float cost = (float) sqrt (t); tmp = (cost - iorRatio * cos) / (cost + iorRatio * cos); float Rs = tmp * tmp; tmp = (cos - iorRatio * cost) / (cos + iorRatio * cost); float Rp = tmp * tmp; return (Rs + Rp) * 0.5f; } } */ #ifdef REFRACTION /* When refraction is enabled, we require a unique ior ratio per path*/ typedef float IORRatio; #else /*When refraction is disabled, we can use an ior ratio for each spectral channel, allowing to simulate multiple channels at once*/ typedef Spectrum IORRatio; #endif IORRatio EvalFresnel(const Vec3 *normal, const Vec3 *in, const IORRatio *iorRatio ) { float cos = -v3dot( normal, in ); IORRatio tmp = (*iorRatio) * cos; IORRatio t = ((IORRatio)(1.f) - (*iorRatio) * (*iorRatio)) + tmp * tmp; IORRatio cost = (IORRatio) sqrt (t); tmp = (cost - (*iorRatio) * cos) / (cost + (*iorRatio) * cos); IORRatio Rs = tmp * tmp; tmp = (cos - (*iorRatio) * cost) / (cos + (*iorRatio) * cost); IORRatio Rp = tmp * tmp; IORRatio fresnel = (Rs + Rp) * 0.5f; fresnel = select( fresnel, (IORRatio)(1.f), (t <= 0) ); return fresnel; /* if (t <= 0) { return 1; } else { IORRatio cost = (IORRatio) sqrt (t); tmp = (cost - (*iorRatio) * cos) / (cost + (*iorRatio) * cos); IORRatio Rs = tmp * tmp; tmp = (cos - (*iorRatio) * cost) / (cos + (*iorRatio) * cost); IORRatio Rp = tmp * tmp; return (Rs + Rp) * 0.5f; } */ } #ifdef REFRACTION IORRatio Fresnel (Vec3 *reflectedOut, Vec3 *transmittedOut, const Vec3 *normal, const Vec3 *in, const IORRatio *iorRatio ) { *transmittedOut = *in; float cos = -v3dot( normal, in ); v3smad( reflectedOut, normal, 2 * cos, transmittedOut ); float tmp = (*iorRatio) * cos; float t = (1 - (*iorRatio) * (*iorRatio)) + tmp * tmp; if (t <= 0) { return 1.f; } else { v3smul( transmittedOut, in, (*iorRatio) ); float cost = (float) sqrt (t); v3smad( transmittedOut, normal , ((*iorRatio) * cos - cost) , transmittedOut ); v3norm( transmittedOut , transmittedOut ); // Is this realy necceseary?? tmp = (cost - (*iorRatio) * cos) / (cost + (*iorRatio) * cos); float Rs = tmp * tmp; tmp = (cos - (*iorRatio) * cost) / (cos + (*iorRatio) * cost); float Rp = tmp * tmp; return (Rs + Rp) * 0.5f; } } #else IORRatio Fresnel (Vec3 *reflectedOut, Vec3 *transmittedOut, const Vec3 *normal, const Vec3 *in, const IORRatio *iorRatio ) { *transmittedOut = *in; float cos = -v3dot( normal, in ); v3smad( reflectedOut, normal, 2 * cos, transmittedOut ); return EvalFresnel( normal, in, iorRatio ); } #endif #endif
C
#include <stdio.h> // ü struct GameInfo { char* name; int year; int price; struct GameInfo* friendGame; // ü. ü ü }; typedef struct { char* name; int year; int price; struct GameInfo* friendGame; } GAME_INFO; // Ʒٿ int main_struct(void) { // ü struct GameInfo gameInfo1; gameInfo1.name = ""; gameInfo1.year = 2017; gameInfo1.price = 1000; // ü printf("== ==\n"); printf("Ӹ : %s\n", gameInfo1.name); printf("ÿ : %d\n", gameInfo1.year); printf(" : %d\n", gameInfo1.price); // ü 迭ó ʱȭ struct GameInfo gameInfo2 = {"ʵ",2020,2000,"ʵȸ"}; printf("== Ǵٸ ==\n"); printf("Ӹ : %s\n", gameInfo2.name); printf("ÿ : %d\n", gameInfo2.year); printf(" : %d\n", gameInfo2.price); // ü 迭 struct GameInfo gameArray[2] = { {"",2010,5000,"ȸ"} , {"ʵ",2030,7000,"ȸ"} }; // ü struct GameInfo* gamePtr; gamePtr = &gameInfo1; printf("\n\n== ==\n"); printf("Ӹ : %s\n", (*gamePtr).name); printf("ÿ : %d\n", (*gamePtr).year); printf(" : %d\n", gamePtr->price); // ϶ Ͱ . Ⱦ ȭǥ ̿밡 //ü ӼҰ gameInfo1.friendGame = &gameInfo2; // friendGame̶ ü ü printf("\n\n== ü ==\n"); printf("Ӹ : %s\n", (*gameInfo1.friendGame).name); printf("ÿ : %d\n", (*gameInfo1.friendGame).year); printf(" : %d\n", gameInfo1.friendGame->price); // typedef // ڷ int i = 1; typedef int ; // "" "int" ϰ 밡 j = 3; typedef float Ǽ; Ǽ Ǽ1 = 4.3218f; printf("\ni = %d\nj = %d\nǼ1 = %.3f\n", i, j, Ǽ1); typedef struct GameInfo ; game1; // == struct GameInfo game1; game1.name = "ѱ۰"; game1.year = 1991; GAME_INFO game2; game2.name = "ѱ۰2"; game2.year = 1891; // ̷ ص // ̷ struct GameInfo game2; // ̷δ ( ) return 0; }
C
#include "lists.h" #include <stdio.h> /** *pop_listint- deletes the head node of a listint_t linked list *@head: double pointer *Return: integer */ int pop_listint(listint_t **head) { listint_t *x, *y; int i; if (*head == NULL) { return (0); } x = *head; y = (*head)->next; i = (*head)->n; *head = y; free(x); return (i); }
C
//ler um numero inteiro e imprimir seu quadrado #include<stdio.h> int main () { int numero; scanf("%d",&numero); printf("%d",numero*numero); return 0; }
C
/* * default.c * * Created on: Sep 2, 2014 * Author: chenbfeng2 */ #include <stdio.h> #include <string.h> int main(void) { //initial the array to store the inout text. char ipt[100]=""; //initial the quit instruction array char qt[]="quit"; int i=0; //the loop continue reading and printing strings for(;;){ //get the input from user gets(ipt); //compare the string if it is same as ""quit. if (strcmp(ipt,qt)!=0) { //print the string in reverse order. for (i=(int)strlen(ipt)-1;i>=0;i--) { printf("%c",ipt[i]); } printf("\n"); } else{ //end the loop if user input quit. break; } } return 0; }
C
/****************************************************************************** * @file server.cpp * @brief The server application for a simple chatroom that uses sockets for * communication. * @author Matt Anderson <[email protected]> * Matt Gualdoni <[email protected]> * @version 0.1 ******************************************************************************/ #include "chatroom.h" #include <signal.h> #include <netinet/in.h> #include <stdlib.h> #include <pthread.h> void initClientList( ); bool addClient( int fileDesc ); void removeClient( int fileDesc ); void writeClients( int ns, char msg[] ); void *clientHandle( void* sock_addr ); void signalHandler( int sig ); //Create table of clients int clients[MAX_CLIENTS]; int ns; //Mutex for client table pthread_mutex_t clientLock; //Mutex for writing to clients pthread_mutex_t writeLock; int main(int argc, char** argv) { //thread id pthread_t tid; //Create the socket addresses for client and server struct sockaddr_in server_addr = { AF_INET, htons( SERVER_PORT ) }; struct sockaddr_in client_addr = { AF_INET }; bool success; int client_len = sizeof( client_addr ); char buffer[MAX_BUFFER], *host; int sock, k, pid; initClientList(); //Open the socket if( ( sock = socket( AF_INET, SOCK_STREAM, 0 ) ) == -1 ) { printf("Server: Socket failed\n"); exit( 1 ); } //Bind the socket to the server port if(bind(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) { printf("Server: Bind failed\n"); exit( 1 ); } //Listen for clients if( listen( sock, 1 ) == -1 ) { printf("Server: Listen failed\n"); exit( 1 ); } printf("Listening for clients...\n"); signal(SIGINT, signalHandler); while(1) { if( ( ns = accept( sock, (struct sockaddr*)&client_addr, &client_len ) ) == -1 ) { printf("Server: Accept failed\n"); exit( 1 ); } else { pthread_mutex_lock(&clientLock); success = addClient(ns); pthread_mutex_unlock(&clientLock); if(success) { pthread_create(&tid, NULL, &clientHandle, (void*)ns); } } } //unlink(server_addr.sin_addr); return 0; } void initClientList( ) { for(int i = 0; i < MAX_CLIENTS; i++) { clients[i] = -1; } return; } bool addClient( int fileDesc ) { bool added = false; for(int i = 0; i < MAX_CLIENTS; i++) { //find empty spot in the list if(clients[i] == -1) { //add client clients[i] = fileDesc; added = true; break; } } if(!added) { printf("Chatroom is full, connection refused"); } return added; } void removeClient( int fileDesc ) { for(int i = 0; i < MAX_CLIENTS; i++) { if(clients[i] = fileDesc) { clients[i] = -1; } } return; } void writeClients( int ns, char msg[] ) { for(int i = 0; i < MAX_CLIENTS; i++) { //check client is valid if(clients[i] > -1 && clients[i] != ns) { write(clients[i], msg, MAX_BUFFER); } } } void *clientHandle( void* sock_addr ) { char buffer[MAX_BUFFER]; char username[MAX_BUFFER]; char msg[MAX_BUFFER]; bool init = true; int k, ns = (int*)sock_addr; //Data transfer on connected socket while( (k = read(ns, buffer, sizeof(buffer))) != 0) { if(init) { strcpy(username, buffer); strcat(buffer, " has connected."); pthread_mutex_lock(&writeLock); printf("%s\n", buffer); writeClients(ns, buffer); pthread_mutex_unlock(&writeLock); init = false; } else if(strcmp(buffer, "/exit") == 0 || strcmp(buffer, "/quit") == 0 || strcmp(buffer, "/part") == 0) { pthread_mutex_lock(&clientLock); removeClient(ns); pthread_mutex_unlock(&clientLock); strcat(username, " has left."); pthread_mutex_lock(&writeLock); printf("%s\n", username); writeClients( ns, username); pthread_mutex_unlock(&writeLock); close(ns); break; } else { strcpy(msg, username); strcat(msg, ": "); strcat(msg, buffer); pthread_mutex_lock(&writeLock); writeClients( ns, msg ); printf("%s\n", msg); pthread_mutex_unlock(&writeLock); } } pthread_detach(pthread_self()); } void signalHandler( int sig ) { char msg[] = "Server will shut down in 10 seconds."; //Print shutdown message pthread_mutex_lock(&writeLock); printf("%s\n", msg); writeClients(-1, msg); pthread_mutex_unlock(&writeLock); //wait for 10 seconds sleep(10); strcpy(msg, "Have a nice day!"); //Signal shutdown pthread_mutex_lock(&writeLock); printf("%s\n", msg); writeClients(-1, msg); pthread_mutex_unlock(&writeLock); for(int i = 0; i < MAX_CLIENTS; i++) { if(clients[i] != -1) { close(clients[i]); } } close(ns); exit(0); }
C
#ifndef PERCORR_H #define PERCORR_H #include "arv.h" //////////////////////////////////////// /* * Encontra o ancestral comum mais prximo "subindo" a rvore. */ No ancestralSimples(No a, No b) { while (a->nivel > b->nivel) a = a->pai; while (b->nivel > a->nivel) b = b->pai; while (a != b) { a = a->pai; b = b->pai; } return a; } //////////////////////////////////////// No ancestral(Arvore* arv, No a, No b) { /* Opes: * mascaras[bsf(dif)] // bit scan forward (__builtin_ctz(x)) * (signed) ((dif-1) ^ dif) >> 1 * ((dif-1) | dif) ^ dif */ ID dif, bit, masc, id; // Bits que diferem dif = a->id ^ b->id; // Primeiro diferente (usar para encontrar o array do nvel?) bit = dif & (-dif); masc = bit - 1; // Todos bits antes do primeiro diferente //masc = (((dif-1) ^ dif) >> 1); // Id do ancestral comum mais prximo id = a->id & masc; // a->id ou b->id, tanto faz // Encontra o n int nivel = arv->bitParaNivel(bit); No *imagemNivel = arv->imagemNiveis[nivel]; return imagemNivel[arv->dadosFuncao[nivel].aplicar(id)]; } #endif /* PERCORR_H */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* here_document.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: paulohl <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/29 10:28:00 by paulohl #+# #+# */ /* Updated: 2020/11/30 11:17:53 by paulohl ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "minishell.h" #include <fcntl.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> int here_doc_handler(char *stop) { int here_doc[2]; char buffer[1000]; int tmp; if (pipe(here_doc)) return (0); buffer[0] = 0; tmp = 0; while (tmp != -1) { write(1, "> ", 2); tmp = read(0, buffer, 999); buffer[tmp - 1] = 0; if (ft_strcmp(stop, buffer)) { buffer[tmp - 1] = '\n'; write(here_doc[1], buffer, tmp); } else tmp = -1; } write(here_doc[1], "\0", 1); close(here_doc[1]); return (here_doc[0]); } int main(int argc, char **argv) { int tmp; int doc; char buffer[1000]; if (argc != 2) return (12); doc = here_doc_handler(argv[1]); tmp = read(doc, buffer, 999); buffer[tmp] = 0; printf("Result:\n%s", buffer); }
C
// // 1413_SortedArrayToBST.h // LeetCode // // Created by 郝源顺 on 2020/3/16. // Copyright © 2020 desezed. All rights reserved. // #ifndef _413_SortedArrayToBST_h #define _413_SortedArrayToBST_h #include <stdio.h> #include "Defines.h" //面试题 04.02. 最小高度树 //给定一个有序整数数组,元素各不相同且按升序排列,编写一个算法,创建一棵高度最小的二叉搜索树。 // //示例: //给定有序数组: [-10,-3,0,5,9], // //一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树: // // 0 // / \ // -3 9 // / / // -10 5 struct TreeNode* sortedArrayToBST(int* nums, int numsSize); #endif /* _413_SortedArrayToBST_h */
C
/* ***************************************** */ /* */ /* EP3 - MAC0438 - Programação Concorrente */ /* */ /* Bárbara de Castro Fernandes - 7577351 */ /* Taís Aparecida Pereira Pinheiro - 7580421 */ /* */ /* ***************************************** */ #include "monitor.h" int N, R, refeicoes = 0; /* Variáveis de Condição */ condicao *semFilosofos; sem_t semGarfos,semRefeicoes, semImpressao; /* *************************************************************************************** */ /* ***************************** Inicialização do Monitor ******************************* */ void inicializaMonitor(int n, int r, Filosofo *filosofos) { int i; N = n; R = r; for(i = 0; i < n; i++) { filosofos[i].id = i + 1; /* Id dos filósofos irá de 1 até N */ filosofos[i].refeicoesComidas = 0; filosofos[i].estado = PENSANDO; } inicializaControladores(); } /* Inicialização das variáveis de condição */ void inicializaControladores() { int i; /* Controla a utilização dos garfos */ if(sem_init(&semGarfos, 0, 1)) { printf("Erro ao iniciar variavel semGarfos!\n"); exit(EXIT_FAILURE); } /* Controla quando um filósofo está comendo */ semFilosofos = mallocSafe(N * sizeof(condicao)); for(i = 0; i < N; i++) { if(sem_init(&semFilosofos[i], 0, 1)) { printf("Erro ao iniciar variavel semFilosofos!\n"); exit(EXIT_FAILURE); } } /* Controla a quantidade de refeições já consumidas */ if(sem_init(&semRefeicoes, 0, 1)) { printf("Erro ao iniciar variavel semRefeicoes!\n"); exit(EXIT_FAILURE); } /* Controla a impressão dos valores*/ if(sem_init(&semImpressao, 0, 1)) { printf("Erro ao criar iniciar variavel semImpressao!\n"); exit(EXIT_FAILURE); } } /* *************************************************************************************** */ /* ***************** Implementação das Funções wait(cv) e signal(cv) ******************** */ void wait(condicao *var) { sem_wait(var); } void signal(condicao *var) { sem_post(var); } /* *************************************************************************************** */ /* ********************************* Funções Auxiliares ********************************* */ /* Devolve o índice do filósofo à esquerda do atual */ int esquerda(int i) { return (i - 1) % N; } /* Devolve o índice do filósofo à direita do atual */ int direita(int i) { return (i + 1) % N; } /* *************************************************************************************** */ /* ********************************** Métodos do Monitor ******************************** */ /* Faz com que o i-ésimo filósofo fique faminto e, consequentemente, tente pegar os garfos */ void ficaFaminto(int i, Filosofo *filosofos) { sem_wait(&semGarfos); filosofos[i].estado = FAMINTO; sem_wait(&semImpressao); printf("Filósofo %d ficou com fome\n", filosofos[i].id); sem_post(&semImpressao); tentaPegarGarfos(i,filosofos); sem_post(&semGarfos); /*sem_wait(&semFilosofos[i]);*/ } /* Faz com que o filósofo tente pegar os garfos para comer */ void tentaPegarGarfos(int i, Filosofo *filosofos) { if(filosofos[i].estado == FAMINTO && filosofos[esquerda(i)].estado != COMENDO && filosofos[direita(i)].estado != COMENDO) { filosofos[i].estado = COMENDO; sem_wait(&semImpressao); printf("Filósofo %d está comendo\n", filosofos[i].id); sem_post(&semImpressao); signal(&semFilosofos[i]); } else wait(&semFilosofos[i]); } /* Solta os garfos e os deixa disponíveis para caso os filósofos vizinhos estejam famintos */ void soltaGarfos(int i, Filosofo *filosofos, int *ref) { sem_wait(&semGarfos); filosofos[i].refeicoesComidas++; sem_wait(&semRefeicoes); refeicoes++; *ref = refeicoes; sem_post(&semRefeicoes); filosofos[i].estado = PENSANDO; sem_wait(&semImpressao); printf("Filósofo %d terminou de comer\n", filosofos[i].id); printf("\nrefeicoesComidas: %d\n\n", refeicoes); sem_post(&semImpressao); tentaPegarGarfos(esquerda(i),filosofos); tentaPegarGarfos(direita(i),filosofos); sem_post(&semGarfos); } /* Aloca a memória requerida pela variável e devolve uma mensuagem de erro caso a memória não seja alocada corretamente */ void *mallocSafe(size_t n) { void *pt; pt = malloc(n); if(pt == NULL) { printf("Erro na alocação de memória!\n"); exit(EXIT_FAILURE); } return pt; }
C
#ifndef STACK_H #define STACK_H #include <stdlib.h> #include <stdbool.h> #include <string.h> typedef char byte; typedef struct { byte *data; byte *ptr; byte *end; size_t typeSize; } stack_t; stack_t *stackCreate ( size_t size, size_t typeSize ); void stackDestroy( stack_t *stack ); bool stackPush ( stack_t *stack, void *data );/*cria uma cópia do dado apontado por data e a guarda na pilha*/ void *stackPop ( stack_t *stack ); void *stackTop ( stack_t *stack); bool stackIsEmpty( stack_t *stack ); bool stackIsFull ( stack_t *stack ); #define STACK( type, size ) stackCreate( size , sizeof(type) ) #endif
C
#include <shuttlesock.h> #include <shuttlesock/buffer.h> #include <errno.h> void shuso_buffer_init(shuso_t *S, shuso_buffer_t *buf, shuso_buffer_memory_type_t mtype, void *allocator_data) { *buf = (shuso_buffer_t) { .first = NULL, .last = NULL, .memory_type = mtype, .allocator_data = allocator_data }; switch(mtype) { case SHUSO_BUF_HEAP: assert(allocator_data == NULL); break; case SHUSO_BUF_POOL: case SHUSO_BUF_FIXED: case SHUSO_BUF_SHARED: assert(allocator_data); break; case SHUSO_BUF_EXTERNAL: break; default: //nope, this is not allowed abort(); } } void *shuso_buffer_allocate(shuso_t *S, shuso_buffer_t *buf, size_t sz) { void *data = NULL; switch(buf->memory_type) { case SHUSO_BUF_HEAP: data = malloc(sz); break; case SHUSO_BUF_POOL: data = shuso_palloc(buf->pool, sz); break; case SHUSO_BUF_FIXED: //TODO abort(); break; case SHUSO_BUF_SHARED: data = shuso_shared_slab_alloc(buf->shm, sz); break; case SHUSO_BUF_DEFAULT: case SHUSO_BUF_EXTERNAL: case SHUSO_BUF_MMAPPED: //that makes no sense abort(); } if(!data) { shuso_set_error_errno(S, "Failed to allocate %d bytes for buffer", sz, ENOMEM); } return data; } static void shuso_buffer_cleanup(shuso_t *S, shuso_buffer_t *buf, shuso_buffer_link_t *link) { if(!link->have_cleanup) { return; } shuso_buffer_link_with_cleanup_t *lnc = container_of(link, shuso_buffer_link_with_cleanup_t, link); // link-and-cleanup lnc->cleanup.cleanup(S, buf, link, lnc->cleanup.cleanup_privdata); } void shuso_buffer_free(shuso_t *S, shuso_buffer_t *buf, shuso_buffer_link_t *link) { assert(buf->first != link && buf->last != link); shuso_buffer_cleanup(S, buf, link); shuso_buffer_memory_type_t mtype = link->memory_type; if(mtype == SHUSO_BUF_DEFAULT) { mtype = buf->memory_type; } switch(mtype) { case SHUSO_BUF_HEAP: free(link); break; case SHUSO_BUF_POOL: //can't free break; case SHUSO_BUF_FIXED: //TODO break; case SHUSO_BUF_SHARED: shuso_shared_slab_free(buf->shm, link); break; case SHUSO_BUF_DEFAULT: case SHUSO_BUF_EXTERNAL: case SHUSO_BUF_MMAPPED: //that makes no sense abort(); } } void shuso_buffer_queue(shuso_t *S, shuso_buffer_t *buf, shuso_buffer_link_t *link) { shuso_buffer_link_t *last = buf->last; if(!buf->first) { buf->first = link; } if(last) { last->next = link; } buf->last = link; } shuso_buffer_link_t *shuso_buffer_dequeue(shuso_t *S, shuso_buffer_t *buf) { shuso_buffer_link_t *link = buf->first; if(!link) { return NULL; } buf->first = link->next; if(buf->last == link) { buf->last = NULL; } return link; } shuso_buffer_link_t *shuso_buffer_last(shuso_t *S, shuso_buffer_t *buf) { return buf->last; } shuso_buffer_link_t *shuso_buffer_next(shuso_t *S, shuso_buffer_t *buf) { return buf->first; } char *shuso_buffer_add_charbuf(shuso_t *S, shuso_buffer_t *buf, size_t len) { shuso_buffer_link_t *link; char *charbuf; size_t sz = sizeof(*link) + len; if((link = shuso_buffer_allocate(S, buf, sz)) == NULL) { return NULL; } charbuf = (void *)&link[1]; *link = (shuso_buffer_link_t ) { .buf = charbuf, .len = len, .data_type = SHUSO_BUF_CHARBUF, .memory_type = SHUSO_BUF_DEFAULT, .next = NULL }; shuso_buffer_queue(S, buf, link); return charbuf; } struct iovec *shuso_buffer_add_iovec(shuso_t *S, shuso_buffer_t *buf, int iovcnt) { shuso_buffer_link_t *link; struct iovec *iov; size_t sz = sizeof(*link) + sizeof(*iov)*iovcnt; if((link = shuso_buffer_allocate(S, buf, sz)) == NULL) { return NULL; } iov = (void *)&link[1]; *link = (shuso_buffer_link_t ) { .iov = iov, .iovcnt = iovcnt, .data_type = SHUSO_BUF_IOVEC, .memory_type = SHUSO_BUF_DEFAULT, .next = NULL }; shuso_buffer_queue(S, buf, link); return iov; } char *shuso_buffer_add_msg_fd(shuso_t *S, shuso_buffer_t *buf, int fd,size_t data_sz) { return shuso_buffer_add_msg_fd_with_cleanup(S, buf, fd, data_sz, NULL, NULL); } #ifndef __clang_analyzer__ //clang analyzer doesn't like this. //it would be nice to have added a data[] at the end of the msgblob, but the trailing // space is already taken up by char buf[CMSG_SPACE(...)] char *shuso_buffer_add_msg_fd_with_cleanup(shuso_t *S, shuso_buffer_t *buf, int fd,size_t data_sz, shuso_buffer_link_cleanup_fn *cleanup, void *cleanup_pd) { struct msgblob_s { struct msghdr msg; struct iovec iov; union { char buf[CMSG_SPACE(sizeof(int))]; struct cmsghdr align; } ancillary_buf; } *msgblob; shuso_buffer_link_t *link; struct msghdr *msg; if(cleanup) { struct { shuso_buffer_link_with_cleanup_t lwc; struct msgblob_s msgblob; } *linkblob; if((linkblob = shuso_buffer_allocate(S, buf, sizeof(*linkblob) + data_sz)) == NULL) { return NULL; } linkblob->lwc.cleanup.cleanup = cleanup; linkblob->lwc.cleanup.cleanup_privdata = cleanup_pd; link = &linkblob->lwc.link; msgblob = &linkblob->msgblob; assert((void *)link == (void *)linkblob); } else { struct { shuso_buffer_link_t link; struct msgblob_s msgblob; } *linkblob; if((linkblob = shuso_buffer_allocate(S, buf, sizeof(*linkblob) + data_sz)) == NULL) { return NULL; } link = &linkblob->link; msgblob = &linkblob->msgblob; assert((void *)link == (void *)linkblob); } *msgblob = (struct msgblob_s) { .ancillary_buf = {{0}}, .msg = { .msg_name = NULL, .msg_namelen = 0, .msg_iov = &msgblob->iov, .msg_iovlen = 1, .msg_control = &msgblob->ancillary_buf.buf, .msg_controllen = sizeof(msgblob->ancillary_buf.buf), .msg_flags = 0 } }; msg = &msgblob->msg; struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof(fd)); memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd)); msgblob->iov.iov_base = &msgblob[1]; //clang analyzer doesn't like this. //it would be nice to have added a data[] at the end of the msgblob, but the trailing // space is already taken up by char buf[CMSG_SPACE(...)] msgblob->iov.iov_len = data_sz; *link = (shuso_buffer_link_t ) { .msg = msg, .flags = 0, .data_type = SHUSO_BUF_IOVEC, .memory_type = SHUSO_BUF_DEFAULT, .next = NULL, .have_cleanup = cleanup ? 1 : 0 }; shuso_buffer_queue(S, buf, link); return msgblob->iov.iov_base; } #endif void shuso_buffer_link_init_msg(shuso_t *S, shuso_buffer_link_t *link, struct msghdr *msg, int flags) { *link = (shuso_buffer_link_t ){ .msg = msg, .flags = flags, .data_type = SHUSO_BUF_MSGHDR, .memory_type = SHUSO_BUF_EXTERNAL, .have_cleanup = 0, .next = NULL }; } void shuso_buffer_link_init_charbuf(shuso_t *S, shuso_buffer_link_t *link, const char *charbuf, size_t len) { *link = (shuso_buffer_link_t ){ .buf = (char *)charbuf, .len = len, .data_type = SHUSO_BUF_CHARBUF, .memory_type = SHUSO_BUF_EXTERNAL, .have_cleanup = 0, .next = NULL }; } void shuso_buffer_link_init_shuso_str(shuso_t *S, shuso_buffer_link_t *link, const shuso_str_t *str) { *link = (shuso_buffer_link_t ){ .buf = str->data, .len = str->len, .data_type = SHUSO_BUF_CHARBUF, .memory_type = SHUSO_BUF_EXTERNAL, .have_cleanup = 0, .next = NULL }; } void shuso_buffer_link_init_iovec(shuso_t *S, shuso_buffer_link_t *link, struct iovec *iov, int iovcnt) { *link = (shuso_buffer_link_t ){ .iov = iov, .iovcnt = iovcnt, .data_type = SHUSO_BUF_IOVEC, .memory_type = SHUSO_BUF_EXTERNAL, .have_cleanup = 0, .next = NULL }; }
C
#include <stdio.h> #include <cs50.h> #include <stdlib.h> #include <string.h> int main(void) { FILE *archivo; archivo = fopen ("datos.csv", "r"); for (int nL = 0; nL < 3; nL++) { char linea [40]; fgets (linea, 40, archivo); string nombres = strtok(linea, ","); string apellidos = strtok(NULL, ","); float notas [3]; float suma = 0; for(int i = 0; i < 3; i++) { notas [i] = atof (strtok(NULL, ",")); suma = suma + notas[i]; } suma = suma/3; printf ("Nombres: %s\n", nombres); printf ("Apellidos: %s\n", apellidos); printf ("Nota: %f\n\n", suma); } fclose(archivo); }
C
#include<stdio.h> #include<math.h> #include<stdbool.h> int M, B, tm, tb; bool go(int x, int t, int m, int b){ if (m == M && b == B) return true; if (m != M && t+abs(x-m)+abs(m-M) > tm || b != B && t+abs(x-b)+abs(b-B) > tb) return false; if (m != M) { if (go(M, t + abs(x-m)+abs(m-M), M, b)) return true; if (m != b && go(b, t + abs(x-m)+abs(m-b), b, b)) return true; } if (b != B) { if (go(B, t + abs(x-b)+abs(b-B), m, B)) return true; if (m != b && go(m, t + abs(x-b)+abs(b-m), m, m)) return true; } return false; } int main(){ int m, b; scanf("%d%d%d%d%d%d", &m, &b, &M, &B, &tm, &tb); printf("%s\n", go(0, 0, m, b) ? "possible" : "impossible"); return 0; }
C
#include "stm8s.h" #include "stm8s_gpio.h" uint32_t delay(uint32_t t) //объявление статической функции часла типа long переменной t для реализации работы функции delay { t=500; while(t--); return t; } static void delay1(uint32_t m) //объявление статической функции часла типа long переменной t для реализации работы функции delay1 { while(m--); } /* * GPIO_PIN_3 = 0x10 = 0b00001000 = 008 = 2^3 * GPIO_PIN_4 = 0x10 = 0b00010000 = 016 = 2^4 * GPIO_PIN_5 = 0x20 = 0b00100000 = 032 = 2^5 * GPIO_PIN_6 = 0x40 = 0b01000000 = 064 = 2^6 * GPIO_PIN_6 = 0x80 = 0b10000000 = 128 = 2^7 */ char n=0; //инициализация переменной uint32_t ms=0; uint32_t msb = 0; _Bool bs = 0; _Bool bls = 0; _Bool b; void Pin() // настройка портов { GPIOC->DDR |= 0xf8; //GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7; //направление данных порта out-0; input-1 GPIOC->CR1 |= 0xf8; //GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7; //установка подтягивающего резистора open-drain=0; push-pull=1 GPIOC->ODR |= 0xf8; //GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7; //установка значения бита 0/1 GPIOD->DDR |= 0x00; GPIOD->CR1 |= 0x10; GPIOD->CR2 |= 0x00; } void RunningUp() //функция направление бегущиго огня с л->п { if(n<=1){ GPIOC->ODR ^= 0b01010000; // 1-0b01010000->delay(1000)->2-0b10001000->delay(1000)->3-(1)->delay(1000)->(2)->delay(1000)->4-0b11011000; delay1(10000); GPIOC->ODR |= 0b01010000; delay1(10000); GPIOC->ODR ^= 0b10001000; // 1-0b01010000->delay(1000)->2-0b10001000->delay(1000)->3-(1)->delay(1000)->(2)->delay(1000)->4-0b11011000; delay1(10000); GPIOC->ODR |= 0b10001000; delay1(10000); n++; } else GPIOC->ODR ^= 0b11011000; } void RunningDn() //функция направление бегущиго огня с п->л { GPIOC->ODR ^= 0x80 >> n; delay1(10000); GPIOC->ODR |= 0x80 >> n; n++; if ( n>=5 ) { n=0; } } uint32_t button () { if ((GPIOD->IDR & 0x10) ==0x00 && !bs && (delay(ms)-msb)>50) // фиксируем нажатие кнопки { bs=1; msb=ms; b^=0; } if ((GPIOD->IDR & 0x10) ==0x10 && bs && (delay(ms)-msb)>50) // фиксируем отпускание нажатие кнопки { bs=0; msb=ms; b^=1; } return b; } int main( void ) //основная программа { Pin(); while(1) //бесконечный цикл { button(); if (b==0) // проверяем нажатие кнопки { RunningUp(); } else { RunningDn(); } } }
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #define MAX 200 struct pixel { char arr[MAX]; }*Ptrpixel; int largura; int altura; Ptrpixel invertImagem(struct pixel vetor, int tamanho){ typedef struct pixel vetor_aux; int j = tamanho -1; for(int i = 0; i < j; i++){ vetor_aux[i].arr = vetor[j].arr; j--; } return vetor_aux; } int main(int argc, char *argv[]) { int i = 0; FILE *in = fopen(argv[1], "r"); FILE *out = fopen(argv[2], "w"); if (!in) { printf("erro no arquivo de leitura"); exit(1); } if (!out) { printf("erro no arquivo de escrita"); } while (i < 3) { char cabeca[70]; fgets(cabeca, 67, in); if (cabeca[0] == '#') continue; else if(i == 1 && cabeca[0] != '#'){ fscanf(in, "%d %d", &largura, &altura); } else { fputs(out, cabeca); i++; } } int h = largura * altura; typedef struct pixel vetor[h]; while (!feof(in)|| i < h){ char corpo[300]; fgets(corpo, 290, in); if(corpo[0] == '#') continue; else{ (*vetor[i]).arr = corpo; i++; } } inverteImagem(vetor, h); fclose(in); fclose(out); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int sommeRed(int nombre); int nbAm(char nom[] , int lon); int main() { int i; int nombre; int nbAmour; char nom[50]; int lon; for(i = 0 ; i < 2 ; i++ ) { scanf("%s", nom); lon = strlen(nom); nombre = nbAm(nom , lon); nbAmour = sommeRed(nombre); printf("%d " , nbAmour); } return 0; } int sommeRed(int nombre) { int rest; int somme = 0; while(nombre >= 10) { while(nombre != 0) { rest = nombre%10; somme += rest; nombre = nombre/10; } nombre = somme; somme = 0; } return nombre; } int nbAm(char nom[] , int lon) { int i; int somme = 0; for(i = 0 ; i < lon ; i++) { somme += nom[i] - 65; } return somme; }
C
#include<stdio.h> #include<stdlib.h> void swap(int *a,int *b) {int temp; temp=*a; *a=*b; *b=temp; } void main() {int n,i,j; float sw=0,st=0; printf("Enter the number of process:"); scanf("%d",&n); int *a=(int*)malloc(n*sizeof(int)); int *b=(int*)malloc(n*sizeof(int)); int *w=(int*)malloc(n*sizeof(int)); int *t=(int*)malloc(n*sizeof(int)); for( i=0;i<n;++i) {printf("Enter the AT of %d :",i+1); scanf("%d",&a[i]); //printf("%d",a[i]); printf("Enter the BT of %d :",i+1); scanf("%d",&b[i]); } for(i=0;i<n-1;++i) for(j=i+1;j<n;++j) {if(a[i]>a[j]) {swap(&a[i],&a[j]); swap(&b[i],&b[j]); } } for( i=0;i<n;++i) {w[i]=0; for(j=0;j<i;++j) w[i]+=b[j]; w[i]=w[i]-a[i]+a[0]; t[i]=w[i]+b[i]; } printf("Process \t Burst Time \t Arrival Time \t Waiting Time \t Turnaround Time\n"); for(i=0;i<n;++i) {printf("P%d \t \t %d \t \t %d \t \t %d \t \t %d \n",i+1,b[i],a[i],w[i],t[i]); sw+=w[i]; st+=t[i];} printf("Average waiting time is %f \nAverage turnaround time is %f \n",sw/n,st/n); printf("GANT chart\n"); int *pid=(int*)malloc(n*sizeof(int)); int *finish=(int*)malloc(n*sizeof(int)); for(i=0;i<n;++i) { pid[i]=i; finish[i]=a[i]+b[i]+w[i]; } for(i=0;i<n-1;++i) for(j=i+1;j<n;++j) {if(finish[i]>finish[j]) {swap(&finish[i],&finish[j]); swap(&pid[i],&pid[j]); } } for(i=0;i<n;++i) {printf("P%d \t",pid[i]+1); } printf("\n"); for(i=0;i<n;++i) {printf("%d \t",finish[i]); } printf("\n"); }
C
#include<stdio.h> #include<stdlib.h> #include<time.h> main(){ clock_t timer; timer=clock(); int i; for(i=0;i<10;i++){ printf("%d",i); } timer=clock()-timer; printf("\n\n%f milesegundo(s) de execucao\n\n",((float)timer)/(CLOCKS_PER_SEC/1000)); }
C
// SPDX-License-Identifier: GPL-2.0 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ioctl.h> #define V240P _IOW('a', 'a', int*) #define V360P _IOW('a', 'b', int*) #define V480P _IOW('a', 'c', int*) #define V720P _IOW('a', 'd', int*) static int ff_initialize(int fd, int cmd, int count); int main(void) { int fd, fd1; int count = 1; //By default frame count is 1 int cmd; //Resolution int rd = 0; char head[20]; fd = open("/dev/ffemulator", O_RDWR); if (fd < 0) { printf("device file cannot be opened..\n"); return 0; } printf("Enter required resolution for test frame..\n"); printf("\t240 for 240p\n\t360 for 360p\n\t480 for 480p\n\t720 for 720p\n"); scanf("%d", &cmd); if (ff_initialize(fd, cmd, count)) return 0; printf("Enter 1 to read frame..\n"); scanf("%d", &rd); if (rd == 1) { unsigned char *data; int size; switch (cmd) { case 240: strcpy(head, "P6\n426 240\n255\n"); size = 306720; break; case 360: strcpy(head, "P6\n640 360\n255\n"); size = 691200; break; case 480: strcpy(head, "P6\n854 480\n255\n"); size = 1229760; break; default: strcpy(head, "P6\n1280 720\n255\n"); size = 2764800; break; } remove("sample.ppm"); fd1 = open("sample.ppm", O_WRONLY | O_CREAT, 0777); write(fd1, head, sizeof(head)); close(fd1); data = malloc(size); read(fd, data, size); fd1 = open("sample.ppm", O_WRONLY | O_APPEND); write(fd1, data, size); close(fd1); } close(fd); return 0; } static int ff_initialize(int fd, int cmd, int count) { switch (cmd) { case 240: ioctl(fd, V240P, (int *) &count); break; case 360: ioctl(fd, V360P, (int *) &count); break; case 480: ioctl(fd, V480P, (int *) &count); break; case 720: ioctl(fd, V720P, (int *) &count); break; default: printf("sorry..! The option entered is not valid..\n"); return -1; } }
C
/* @JUDGE_ID: 17051CA 336 C++ */ #include<stdio.h> #include<stl.h> #include<slist> #include<map> #include<set> #include<vector> #include<iostream> #include<string> #include<queue> class graph{ public: vector<slist<int> > adj; vector<slist<int>::iterator> pos; graph(){} graph(int n){ resize(n); } void resize(int n){ adj.resize(n), pos.resize(n); for(int i=0; i<n; i++){ adj[i].clear(); } } int size(){ return adj.size();} int next(int i){ if(pos[i]==adj[i].end()) return -1; return *pos[i]++; } void insert(int i, int j, int e){ adj[i].push_front(j); } void reset(int i){pos[i] = adj[i].begin();} void reset(){for(int i=0; i<size(); i++) reset(i);} void clear(){adj.clear(), pos.clear();} }; void work(); int read(); void bfs(graph &g, vector<int> &pi, vector<int> &d, int s); graph g; int n; int caseN; void work(){ int ii, jj; vector<pair<int, int> > edge; edge.clear(); set<int> ver; for(int i=0; i<n; i++){ cin >> ii >> jj; pair<int, int> p; p.first = ii; p.second = jj; edge.push_back(p); ver.insert(ii); ver.insert(jj); } vector<int> v; v.resize(ver.size()); copy(ver.begin(), ver.end(), v.begin()); g = graph(v.size()); map<int, int> mp; for(int i=0; i<v.size(); i++){ mp[ v[i] ] = i; } for(int i=0; i<edge.size(); i++){ pair<int, int> e = edge[i]; g.insert( mp[e.first], mp[e.second], 1 ); g.insert( mp[e.second], mp[e.first], 1 ); } vector<int> pi, d; int ttl; int nd; while(1){ cin >> nd >> ttl; if( nd == 0 && ttl==0 ) break; int s = mp[nd]; bfs(g, pi, d, s); int cnt = 0; for(int i=0; i<d.size(); i++){ if(d[i]>ttl+1 || d[i]==0) cnt++; } cout << "Case " << caseN << ": " << cnt << " nodes not reachable from node " << nd << " with TTL = " << ttl << "." << endl; caseN++; } } void bfs(graph &g, vector<int> &pi, vector<int> &d, int s){ queue<int> q; int u, v; pi.resize(g.size()); fill(pi.begin(), pi.end(), -1); d.resize(g.size()); fill(d.begin(), d.end(), 0); q.push(s); d[s] = 1; g.reset(); while(!q.empty()){ u = q.front(), q.pop(); while((v=g.next(u))!=-1){ if(!d[v]){ d[v] = d[u]+1; pi[v] = u; q.push(v); } } } } main(){ caseN = 1; while(read()){ work(); } } int read(){ cin >> n; if(n==0) return 0; return 1; }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <math.h> #include "list.h" #include "display.h" #include "array.h" #include "graph.h" #include "picture.h" #define STRMAX 256 extern struct table_fill Tf_tab; extern struct display_tab D_tab; extern int update_ind; extern int Inactive; extern int I,J,K,L,M,N; extern FILE *fpin, *fpout, *fperr;/* input, output, and error for scripts */ /* Remove a Fill name and its values. */ int removeTf_name(str) char str[]; { struct table_fill *ptab,*ptb; for (ptab=ptb=&Tf_tab;ptab != NULL; ptb=ptab,ptab=ptab->next) { if (cmpnbl(str,ptab->name) == 0) { if (ptab == &Tf_tab) { err_warn(0,fperr, "Warning - Fill (%s) default can't be removed.\n",str); return 0; } ptb->next=ptab->next; check_d_fill(str); if (update_ind == 0) { ptb->next=ptab->next; free_points( &ptab->fx ); free_points( &ptab->fy ); if (ptab->fais != NULL) free((char *)ptab->fais); if (ptab->fasi != NULL) free((char *)ptab->fasi); if (ptab->faci != NULL) free((char *)ptab->faci); free((char *)ptab); } else { err_warn(0,fperr, "Warning - Fill (%s) in use can't be removed.\n",str); return 0; } if (!Inactive && fpout != NULL) fprintf(fpout,"REMOVE(Tf_%s)\n",str); return 1; } } err_warn(0,fperr,"Warning - Fill (%s) can't be found to remove.\n",str); return 0; } /* Rename a Fill descriptor. (str2 -> str1) */ int renameTf_name(char *str1,char *str2) { int i,j; char s2[17]; char s1[17]; struct table_fill *p; for (i=0,j=0;str2 != NULL && i < 16 && str2[i] != '\0';i++) if (str2[i] > ' ') s2[j++]=str2[i]; s2[j]='\0'; for (i=0,j=0;str1 != NULL && i < 16 && str1[i] != '\0';i++) if (str1[i] > ' ') s1[j++]=str1[i]; s1[j]='\0'; if (str2 == NULL || str1 == NULL || strprt(s1) == 0 || strprt(s2) == 0) { err_warn(0,fperr, "Warning - a Fill name is empty, not renamed.\n"); return 0; } if (strcmp(s1,Tf_tab.name) == 0) { err_warn(1,fperr,"Error - the default fill can't be renamed.\n"); return 0; } if (strcmp(s1,s2) == 0) { err_warn(0,fperr,"Warning - rename (%s) to (%s).\n",s1,s2); return 1; } for (p=&Tf_tab;p != NULL;p=p->next) { if (strcmp(s2,p->name) == 0) { err_warn(1,fperr, "Error - rename to (%s) would duplicate an existing name.\n",s2); return 0; } } for (p=&Tf_tab;p != NULL;p=p->next) { if (strcmp(s1,p->name) == 0) { check_d_fill(s1); if (update_ind == 0) strcpy(p->name,s2); else { err_warn(0,fperr, "Warning - Fill (%s) in use can't be renamed.\n",s1); return 0; } if (!Inactive && fpout != NULL) fprintf(fpout,"RENAME(Tf_%s,Tf_%s)\n",str1,str2); return 1; } } err_warn(0,fperr,"Warning - Fill (%s) can't be found.\n", str1); return 0; } /* Copy Fill to another (str1 -> str2) if a name exists in str2. */ int copy_Tf_name(char *str1,char *str2) { int i,j; struct table_fill *p,*p1; char s1[17]; char s2[17]; for (i=0,j=0;str2 != NULL && i < 16 && str2[i] != '\0';i++) if (str2[i] > ' ') s2[j++]=str2[i]; s2[j]='\0'; for (i=0,j=0;str1 != NULL && i < 16 && str1[i] != '\0';i++) if (str1[i] > ' ') s1[j++]=str1[i]; s1[j]='\0'; if (str1 == NULL || strprt(s1) == 0) { err_warn(1,fperr, "Error - Fill name is empty, not copied.\n"); return 0; } if (strcmp(s1,s2) == 0) return 1; /* If a target fill name isn't given return 0. */ if (str2 == NULL || strprt(s2) == 0) return 0; /* Search Fill table for Fill to be created. */ for (p=&Tf_tab;p != NULL;p=p->next) if (strcmp(s2,p->name) == 0) { err_warn(1,fperr, "Error - Fill (%s) already exists copy would duplicate it.\n",s2); return 0; } /* Search fill table for fill to be copied. */ for (p1=&Tf_tab;p1 != NULL;p1=p1->next) if (strcmp(s1,p1->name) == 0) break; if (p1 == NULL) { err_warn(0,fperr, "Warning - Fill (%s) can't be found for copy.\n",str1); return 0; } /* Find the last fill table entry. */ for (p=&Tf_tab;p != NULL;p=p->next) if (p->next == NULL) break; if (p->next == NULL && (p->next=(struct table_fill *)malloc(sizeof(struct table_fill)))==NULL) { err_warn(1,fperr, "Error - memory for fill (%s) can't be found.\n",s2); return 0; } p=p->next; strcpy (p->name,s2); strcpy (p->proj,p1->proj); p->next=NULL; copy_int_array(&p->fais, &p1->fais, &p->fais_size, p1->fais_size, 1 ); copy_int_array(&p->fasi, &p1->fasi, &p->fasi_size, p1->fasi_size, 1 ); copy_int_array(&p->faci, &p1->faci, &p->faci_size, p1->faci_size, 241 ); p->faci_size=p1->faci_size; p->x=0; /* Note: not in use at this time */ p->y=0; /* Note: not in use at this time */ p->w=0.1; /* Note: not in use at this time */ p->h=0.1; /* Note: not in use at this time */ p->priority=p1->priority; p->fvp[0]=p1->fvp[0]; p->fvp[1]=p1->fvp[1]; p->fvp[2]=p1->fvp[2]; p->fvp[3]=p1->fvp[3]; p->fwc[0]=p1->fwc[0]; p->fwc[1]=p1->fwc[1]; p->fwc[2]=p1->fwc[2]; p->fwc[3]=p1->fwc[3]; if (copy_points( &p->fx, p1->fx) == 0) return 0; if (copy_points( &p->fy, p1->fy) == 0) return 0; if (!Inactive && fpout != NULL) fprintf(fpout,"COPY(Tf_%s,Tf_%s)\n",str1,str2); return 1; }
C
#include <8052.h> #include "uart.h" void uart_init(){ SCON = 0x50; /* uart in mode 1 (8 bit), REN=1 */ T2CON &= 0xF0; /* EXEN2=0; TR2=0; C/T2#=0; CP/RL2#=0; */ T2CON |= 0x30; /* RCLK = 1; TCLK=1; */ TH2=0xFF; TL2=0xEC; RCAP2H=0xFF; RCAP2L=0xEC; /* 38400 Baud at 24.576MHz */ TR2 = 1; /* Timer 2 run */ TI = 1; RI = 0; } byte uart_getc(){ byte tmp; while(!RI); tmp = SBUF; RI = 0; return(tmp); } void uart_putc(byte c){ while(!TI); TI = 0; SBUF = c; } void uart_putstr(byte * p){ while(*p){ uart_putc(*p); } }
C
/* * Program represents a simple calculator. Its functions - addition, subtraction, * iteger division, real division, modulo, multiplication, N-th power, * factorial, sum of numbers, average of nubers, binomial coefficient and primality * test - are called by arguements in front of parameters. */ #include <stdio.h> int add(int a, int b) { return a+b; } int sub(int a, int b) { return a-b; } float div(float a, float b) { return a/b; } int iDiv(int a, int b) { return a/b; } int mod(int a, int b) { return a%b; } int mul(int a, int b) { return a*b; } long long int nthPower(int a, int b) { if(b==0) return 1; int res=a; for(int i=1;i<b;i++) { res*=a; } return res; } long long int fact(int f) { if(f<0) { return -1; } else if(f==0||f==1) { return 1; } else { return f*fact(f-1); } } int sum(int size) { int sum=0; int b=0; for(int i=0;i<size;i++) { scanf("%d", &b); sum += b; } return sum; } float avg(int size) { if(size !=0) { return (float)sum(size)/size; } else { return 0; } } long long int binom(int a, int b) { if(a<b || a<0 || b<0) { return -1; } else { return fact(a)/(fact(a-b)*fact(b)); } } int prime(int a) { if(a==1||a==0) return 0; for(int i=2;i*i<=a;i++) { if(a%i==0) return 0; } return 1; } int main(void) { char choice='x'; int a,b, exit=0; float fa,fb; do { printf("> "); fflush(stdin); scanf("%1s", &choice); switch(choice) { case '+': scanf("%d %d", &a, &b); printf("# %d\n",add(a,b)); break; case '-': scanf("%d %d", &a, &b); printf("# %d\n",sub(a,b)); break; case '/': scanf("%f %f", &fa, &fb); printf("# %.2f\n",div(fa, fb)); break; case 'd': scanf("%d %d", &a, &b); printf("# %d\n",iDiv(a,b)); break; case 'm': scanf("%d %d", &a, &b); printf("# %d\n",mod(a,b)); break; case '*': scanf("%d %d", &a, &b); printf("# %d\n",mul(a,b)); break; case '^': scanf("%d %d", &a,&b); printf("# %lld\n",nthPower(a, b)); break; case '!': scanf("%d", &a); printf("# %lld\n",fact(a)); break; case 's': scanf("%d", &a); printf("# %d\n",sum(a)); break; case 'a': scanf("%d", &a); printf("# %.2f\n",avg(a)); break; case 'c': scanf("%d %d", &a, &b); printf("# %lld\n",binom(a,b)); break; case 'p': scanf("%d", &a); if(prime(a)) printf("# y\n"); else printf("# n\n"); break; case 'q': exit = 1; break; default:printf("Unknown arguement: %c\n", choice); } } while(!exit); return 0; }
C
#include <stdio.h> #include <semaphore.h> #include <unistd.h> #include <stdlib.h> #include <sys/shm.h> #include <sys/types.h> #include <sys/wait.h> sem_t *KO; int *s1 = 0; sem_t *p1; sem_t *p2; sem_t *p3; sem_t *stol_prazan; void trgovac() { do { *s1 = rand()%(3-1+1) +1; //(s1, s2) = nasumice_odaberi_dva_različita_sastojka sem_wait(KO); if(*s1 == 1) { printf("Trgovac stavlja duhan i šibice\n"); sem_post(p1); } if(*s1 == 2){ printf("Trgovac stavlja duhan i papir\n"); sem_post(p2); } if(*s1 == 3){ printf("Trgovac stavlja papir i šibice\n"); sem_post(p3); } sem_post(KO); sem_wait(stol_prazan); sleep(1); } while(1); } void pusac(int p) { do { if (p == 1) { sem_wait(p1); sem_wait(KO); printf("Pusac %d: Uzima sastojke i ...\n\n",p); sem_post(KO); sem_post(stol_prazan); } if(p == 2){ sem_wait(p2); sem_wait(KO); printf("Pusac %d: Uzima sastojke i ...\n\n",p); sem_post(KO); sem_post(stol_prazan); } if(p == 3){ sem_wait(p3); sem_wait(KO); printf("Pusac %d: Uzima sastojke i ...\n\n",p); sem_post(KO); sem_post(stol_prazan); } else { sem_post(KO); } } while(1); } int main () { int ID,i; pid_t pid; srand(time(NULL)); ID = shmget (IPC_PRIVATE, sizeof(sem_t) + sizeof(int), 0600); KO = shmat(ID, NULL, 0); p1 = (sem_t *) (KO +1); p2 = (sem_t *) (KO +2); p3 = (sem_t *) (KO +3); stol_prazan = (sem_t *) (KO +4); s1 = (int *) (KO + 5); shmctl(ID, IPC_RMID, NULL); //moze odmah ovdje, nakon shmat sem_init(KO, 1, 1); sem_init(p1,1,0); sem_init(p2,1,0); sem_init(p3,1,0); sem_init(stol_prazan,1,0); printf("Pusac 1: ima papir\n"); printf("Pusac 2: ima šibice\n"); printf("Pusac 3: ima duhan\n"); printf("\n"); pid = fork(); if(pid == 0){ trgovac(); exit(1); } else if(pid == -1){ perror("Greska pri stvaranju procesa"); exit(1); } pid = fork(); if(pid == 0){ pusac(1); exit(1); } else if(pid == -1){ perror("Greska pri stvaranju procesa"); exit(1); } pid = fork(); if(pid == 0){ pusac(2); } else if(pid == -1){ perror("Greska pri stvaranju procesa"); exit(1); } pid = fork(); if(pid == 0){ pusac(3); } else if(pid == -1){ perror("Greska pri stvaranju procesa"); exit(1); } sleep(2); for (i = 0; i < 4; i++ ) wait(NULL); sem_destroy(KO); shmdt(KO); sem_destroy(p1); shmdt(p1); sem_destroy(p2); shmdt(p2); sem_destroy(p3); shmdt(p3); sem_destroy(stol_prazan); shmdt(stol_prazan); return 0; }
C
/* * _EXECUTE_TEST_C_ * * HMCSIM MUTEX EXECUTION FUNCTIONS * * * rsp_payload[0] = data * rsp_payload[1] = success bit */ #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <string.h> #include "hmc_sim.h" /* ------------------------------------------------- DATATYPES */ struct mylock{ int64_t tid; uint64_t mlock; }; /* ------------------------------------------------- TAG MACROS */ #define TAG_START 0x0000 /* -- start state */ #define TAG_LOCK_SEND 0x0001 /* -- sent a lock message */ #define TAG_LOCK_RECV 0x0002 /* -- waiting on lock receipt */ #define TAG_TLOCK_SEND 0x0003 /* -- sent a trylock message */ #define TAG_TLOCK_RECV 0x0004 /* -- waiting on a tlock receipt */ #define TAG_ULOCK_SEND 0x0005 /* -- sent an unlock message */ #define TAG_ULOCK_RECV 0x0006 /* -- waiting on an unlock message */ #define TAG_DONE 0xF000 /* -- thread is done */ /* ------------------------------------------------- FIND_MIN_CYCLE */ static uint64_t find_min_cycle( uint64_t *cycles, uint32_t num_threads ){ uint32_t i = 0; uint64_t m = 0; for( i=1; i<num_threads; i++ ){ if( cycles[i] < cycles[m] ){ m = i; } } return cycles[m]; } /* ------------------------------------------------- FIND_MAX_CYCLE */ static uint64_t find_max_cycle( uint64_t *cycles, uint32_t num_threads ){ uint32_t i = 0; uint64_t m = 0; for( i=1; i<num_threads; i++ ){ if( cycles[i] > cycles[m] ){ m = i; } } return cycles[m]; } /* ------------------------------------------------- FIND_AVG_CYCLE */ static double find_avg_cycle( uint64_t *cycles, uint32_t num_threads ){ uint32_t i = 0; uint64_t m = 0x00ull; for( i=0; i<num_threads; i++ ){ m += cycles[i]; } return (double)(((double)(m)/(double)(num_threads))); } /* ------------------------------------------------- INC_TAG */ /* INC_TAG */ static void inc_tag( uint16_t *tag ){ uint16_t ltag = *tag; ltag++; if( ltag == (UINT8_MAX-1)){ ltag = 1; } *tag = ltag; } /* ------------------------------------------------- INC_LINK */ /* INC_LINK */ static void inc_link( struct hmcsim_t *hmc, uint8_t *link ){ uint8_t llink = *link; llink++; if( llink == hmc->num_links ){ llink = 0; } *link = llink; } /* ------------------------------------------------- ZERO_PACKET */ /* * ZERO_PACKET * */ static void zero_packet( uint64_t *packet ) { uint64_t i = 0x00ll; /* * zero the packet * */ for( i=0; i<HMC_MAX_UQ_PACKET; i++ ){ packet[i] = 0x00ll; } return ; } /* ------------------------------------------------- TRIGGER_RESPONSE */ static void trigger_mutex_response( hmc_response_t type, uint16_t tag, uint16_t *wtags, struct mylock *wlocks, uint64_t *status, int *wstatus, struct mylock lock, uint32_t num_threads ){ /* vars */ uint32_t i = 0; uint32_t th = 0; int found = -1; /* ---- */ for( i=0; i<num_threads; i++ ){ if( wstatus[i] != HMC_STALL ){ /* -- thread is not stalled, it is waiting on response */ if( wtags[i] == tag ){ if( (status[i] == TAG_LOCK_RECV) && (type == RD_RS) ){ th = i; found = 1; //printf( "matched tag = thread; %d = %d\n", tag, th ); goto complete_trigger; }else if( (status[i] == TAG_ULOCK_RECV) && (type == WR_RS) ){ th = i; found = 1; //printf( "matched tag = thread; %d = %d\n", tag, th ); goto complete_trigger; } } /* -- the tags match */ }/* -- end if */ } complete_trigger: if( found == 1 ){ if( lock.tid == th ){ wlocks[th].mlock = 1; }else{ wlocks[th].mlock = 2; } }else{ printf( "ERROR: FATAL : COULD TRIGGER EVENT ON TAG = %d; ABORTING\n", tag ); abort(); } } /* ------------------------------------------------- EXECUTE_TEST */ /* * EXECUTE TEST * * FINITE STATE MACHINE FOR MULTITHREADED MUTEX TEST * ALL THREADS ATTEMPT TO ACQUIRE THE LOCK FOR AT LEAST ONE CYCLE * THIS IS DELIBERATEY A NAIVE IMPLEMENTATION * * WHILE( NUM_LOCKS < NUM_THREADS ){ * IF( NOT_LOCKED ){ * ATTEMPT TO LOCK() * IF( SUCCESS ){ * UPDATE GLOBAL * UNLOCK * }ELSE{ * TRYLOCK UNTIL SUCCESS * UNLOCK * } * } * } * */ extern int execute_test( struct hmcsim_t *hmc, uint32_t num_threads, uint32_t shiftamt ) { /* vars */ uint64_t head = 0x00ll; uint64_t tail = 0x00ll; uint64_t payload[8] = {0x00ll, 0x00ll, 0x00ll, 0x00ll, 0x00ll, 0x00ll, 0x00ll, 0x00ll }; int ret = 0; uint8_t cub = 0; uint8_t link = 0; uint16_t tag = 1; uint32_t done = 0; uint32_t i = 0; uint64_t packet[HMC_MAX_UQ_PACKET]; uint64_t addr = 0x5B5B0ull; FILE *ofile = NULL; struct mylock lock; uint64_t d_response_head; uint64_t d_response_tail; hmc_response_t d_type; uint8_t d_length; uint16_t d_tag; uint8_t d_rtn_tag; uint8_t d_src_link; uint8_t d_rrp; uint8_t d_frp; uint8_t d_seq; uint8_t d_dinv; uint8_t d_errstat; uint8_t d_rtc; uint32_t d_crc; struct mylock *wlocks = NULL; /* current thread lock copy */ uint64_t *status = NULL; /* current thread status */ uint64_t *cycles = NULL; /* thread local cycle count */ int *wstatus = NULL; /* current thread wait status */ uint16_t *wtags = NULL; /* current thread wait tags */ /* ---- */ /* allocate memory & init thread state */ cycles = malloc( sizeof( uint64_t ) * num_threads ); status = malloc( sizeof( uint64_t ) * num_threads ); wstatus = malloc( sizeof( int ) * num_threads ); wtags = malloc( sizeof( uint16_t ) * num_threads ); wlocks = malloc( sizeof( struct mylock ) * num_threads ); for( i=0; i<num_threads; i++ ){ status[i] = TAG_START; cycles[i] = 0x00ll; wstatus[i] = -1; wtags[i] = 0; wlocks[i].tid = (int64_t)(-1); wlocks[i].mlock= (uint64_t)(0); } /* init the lock */ lock.tid = (int64_t)(-1); lock.mlock = (uint64_t)(0); /* * setup the tracing mechanisms * */ printf( "...INITIALIZING TRACE FILE\n" ); ofile = fopen( "fe_linear.out", "w" ); if( ofile == NULL ){ printf( "FAILED : COULD NOT OPEN OUPUT FILE mutex.out\n" ); return -1; } hmcsim_trace_handle( hmc, ofile ); hmcsim_trace_level( hmc, (HMC_TRACE_CMD| HMC_TRACE_STALL| HMC_TRACE_LATENCY) ); hmcsim_trace_header( hmc ); printf( "SUCCESS : INITIALIZED TRACE HANDLERS\n" ); /* * zero the packet * */ zero_packet( &(packet[0]) ); printf( "BEGINNING EXECUTION\n" ); /* -- begin cycle loop */ while( done < num_threads ){ /* -- cycle through all the threads */ for( i=0; i<num_threads; i++ ){ /* -- if the thread is not done, try to perform an op */ switch( status[i] ){ /* -- TAG_START */ case TAG_START: /* -- Build a ReadEF */ cycles[i]++; ret = hmcsim_build_memrequest( hmc, 0, addr, tag, CMC71, /* READFE */ link, &(packet[0]), &head, &tail); if( ret == 0 ){ packet[0] = head; packet[1] = tail; ret = hmcsim_send( hmc, &(packet[0]) ); }else{ printf( "ERROR : FATAL : MALFORMED PACKET FROM THREAD %d\n", i ); } switch( ret ){ case 0: /* success */ status[i] = TAG_LOCK_RECV; wlocks[i].mlock = 0; wstatus[i] = 0; wtags[i] = tag; inc_tag( &tag ); inc_link(hmc, &link); /* try to set the lock */ if( lock.mlock == 0 ){ //printf( "...thread %d acquired the lock\n", i ); lock.mlock = 1; lock.tid = i; } //printf( "THREAD %d SENT HMC_LOCK PACKET; TAG=%d\n", i, wtags[i] ); break; case HMC_STALL: /* stalled */ wstatus[i] = HMC_STALL; wtags[i] = 0; /* drop to lock */ status[i] = TAG_LOCK_SEND; break; case -1: default: printf( "FAILED : INITIAL READEF PACKET SEND FAILURE\n" ); goto complete_failure; break; } break; /* -- TAG_LOCK_RECV */ case TAG_LOCK_RECV: cycles[i]++; switch( wlocks[i].mlock ){ case 0: /* still waiting */ break; case 1: /* i have the lock */ status[i] = TAG_ULOCK_SEND; wlocks[i].mlock = 0; wtags[i] = 0; //printf( "THREAD %d RECEIVED A RESPONSE: I HAVE THE LOCK\n", i ); break; case 2: /* the lock is set, but it is not me */ status[i] = TAG_LOCK_SEND; wlocks[i].mlock = 0; wtags[i] = 0; //printf( "THREAD %d RECEIVED A RESPONSE: I DO NOT HAVE THE LOCK\n", i ); break; default: printf( "FAILED : LOCK PACKET RECV FAILURE\n" ); goto complete_failure; break; } break; /* -- TAG_LOCK_SEND */ case TAG_LOCK_SEND: /* -- Build a ReadEF */ cycles[i]++; ret = hmcsim_build_memrequest( hmc, 0, addr, tag, CMC71, /* READFE */ link, &(payload[0]), &head, &tail); if( ret == 0 ){ packet[0] = head; packet[1] = tail; ret = hmcsim_send( hmc, &(packet[0]) ); }else{ printf( "ERROR : FATAL : MALFORMED PACKET FROM THREAD %d\n", i ); } switch( ret ){ case 0: /* success */ status[i] = TAG_LOCK_RECV; wlocks[i].mlock = 0; wstatus[i] = 0; wtags[i] = tag; inc_tag( &tag ); inc_link(hmc, &link); /* try to set the lock */ if( lock.mlock == 0 ){ lock.mlock = 1; lock.tid = i; } //printf( "THREAD %d SENT HMC_TRYLOCK PACKET; TAG=%d\n", i, wtags[i] ); break; case HMC_STALL: /* stalled */ wstatus[i] = HMC_STALL; wtags[i] = 0; break; case -1: default: printf( "FAILED : READFE LOCK PACKET SEND FAILURE\n" ); goto complete_failure; break; } break; /* -- TAG_ULOCK_SEND */ case TAG_ULOCK_SEND: /* -- Send WriteXE */ cycles[i]++; payload[0] = (uint64_t)(i); ret = hmcsim_build_memrequest( hmc, 0, addr, tag, CMC77, /* WriteXE */ link, &(payload[0]), &head, &tail); if( ret == 0 ){ packet[0] = head; packet[1] = (uint64_t)(i); /* TODO, make this th++ */ packet[2] = 0x00ll; packet[3] = tail; ret = hmcsim_send( hmc, &(packet[0]) ); }else{ printf( "ERROR : FATAL : MALFORMED PACKET FROM THREAD %d\n", i ); } switch( ret ){ case 0: /* success */ status[i] = TAG_ULOCK_RECV; wlocks[i].mlock = 0; wstatus[i] = 0; wtags[i] = tag; inc_tag( &tag ); inc_link(hmc, &link); /* try to set the lock */ if( (lock.mlock == 1) /*&& (lock.tid == i)*/ ){ lock.mlock = 0; lock.tid = i; //printf( "THREAD %d SENT HMC_ULOCK PACKET; TAG=%d\n", i, wtags[i] ); } break; case HMC_STALL: /* stalled */ wstatus[i] = HMC_STALL; wtags[i] = 0; break; case -1: default: printf( "FAILED : WRITEXE PACKET SEND FAILURE\n" ); goto complete_failure; break; } break; /* -- TAG_ULOCK_RECV */ case TAG_ULOCK_RECV: cycles[i]++; switch( wlocks[i].mlock ){ case 0: /* still waiting */ break; case 1: case 2: default: /* i have the lock */ status[i] = TAG_DONE; done++; //printf( "THREAD %d RECEIVED A RESPONSE: UNLOCK SUCCESS\n", i ); break; } break; case TAG_DONE: /* thread is done, do nothing */ break; default: /* error */ break; }/*switch( status[i] )*/ }/*-- end for loop */ /* drain all the responses */ for( i=0; i<hmc->num_links; i++ ){ ret = HMC_OK; while( ret != HMC_STALL ){ ret = hmcsim_recv( hmc, cub, i, &(packet[0]) ); if( ret == 0 ){ /* decode the response */ hmcsim_decode_memresponse( hmc, &(packet[0]), &d_response_head, &d_response_tail, &d_type, &d_length, &d_tag, &d_rtn_tag, &d_src_link, &d_rrp, &d_frp, &d_seq, &d_dinv, &d_errstat, &d_rtc, &d_crc ); trigger_mutex_response( d_type, d_tag, wtags, wlocks, status, wstatus, lock, num_threads ); }/* -- good response */ }/* -- get all the responses */ }/* -- end response loop */ /* * clock the sim * */ hmcsim_clock( hmc ); } /* -- end cycle loop */ /* print a summary */ printf( " SUMMARY : NUM_THREADS = %d\n", num_threads ); printf( " MIN_CYCLE = %" PRIu64 "\n", find_min_cycle( cycles, num_threads ) ); printf( " MAX_CYCLE = %" PRIu64 "\n", find_max_cycle( cycles, num_threads ) ); printf( " AVG_CYCLE = %f\n", find_avg_cycle( cycles, num_threads ) ); complete_failure: fclose( ofile ); ofile = NULL; free( cycles ); free( status); free( wstatus); free( wtags); free( wlocks); return 0; } /* EOF */
C
#include <stdio.h> #include <stdlib.h> # define TAM 5 // declarar un array de 5 enteros // cargarlo secuencialmente con numeros ingresados por el usuario // y mostrar solo los numeros pares // void mostrarPares(int vec[], int tam); void mostrarPares(int vec[], int tam); void cargarVector(int vec[], int tam); int main() { int numeros[TAM]; cargarVector(numeros, TAM); mostrarPares(numeros, TAM); return 0; } void cargarVector(int vec[], int tam) { for (int i = 0; i < tam; i++) { printf("Ingrese un numero: "); scanf("%d", &vec[i]); } } //void cargarVector(int* vec, int tam) //{ // for (int i = 0; i < tam; i++) // { // printf("Ingrese un numero: "); // scanf("%d", vec + i); // vec + 4 bytes(size of), aritmetica de punteros // } //} void mostrarPares(int vec[], int tam) { printf("Los numeros pares son: "); for(int i = 0; i < tam; i++) { if(vec[i] % 2 == 0) { printf("%d ", vec[i]); } } printf("\n\n"); } //void mostrarPares(int* vec, int tam) //{ // printf("Los numeros pares son: "); // for(int i = 0; i < tam; i++) // { // if(*(vec + i) % 2 == 0) // { // printf("%d ", *(vec + i)); // } // } // printf("\n\n"); //}
C
#include <stdlib.h> #include <stdio.h> #include "studente.h" int main(void) { struct studente *s1 = construct_studente("Giacomo"); struct studente *s2 = construct_studente("Elisa"); char *s; fa_esame(s1, 18); fa_esame(s1, 15); // non viene registrato fa_esame(s2, 30); fa_esame(s1, 25); fa_esame(s2, 22); fa_esame(s2, 29); fa_esame(s2, 27); printf("%s\n", s = toString(s1)); free(s); printf("%s\n", s = toString(s2)); free(s); destruct_studente(s1); destruct_studente(s2); return 0; }
C
#include <stdio.h> #include <locale.h> int main() { int x,y,r; printf(" : "); scanf("%d",&x); printf(" : "); scanf("%d",&y); printf(" : "); scanf("%d",&r); if ((x>y)&&(x>r)) { printf("%d ", x); } else if ((y>x)&&(y>r)) { printf("%d ", y); } else if ((r>y)&&(r>x)) { printf("%d ", r); } }
C
#include<stdio.h> int main() { int arr[20],i,j,n,temp; printf("Enter the size of the array: \n"); scanf("%d",&n); printf("Enter %d elements in the array: \n",n); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } printf("Elements after reversing: \n"); for(i=0;i<((i+n)/2);i++) { temp=arr[i]; arr[i]=arr[n-i]; arr[n-i]=temp; } for(i=0;i<n;i++) { printf("%d\t",arr[i]); } }
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int i = 2; int result = i*i; printf("result = %d\n", result); result *= i; printf("result = %d\n", result); result *= (i+i); printf("result = %d\n", result); }
C
#include <stdlib.h> #include <errno.h> #include <omp.h> #include "mytest.h" /** * make the opencv image (ordered BGR) grayscale using R*0.30 G*0.59 B*0.11 * * @param ArrayIn An colour opencv image array (ordered BGB) * @param Ydim The height of the images * @param Xdim The width of the images * @param Cdim The number of colour channel (must be 3) * @param pArrayOut A pointer to the output grayscale image array * @param YdimOut The height of the image * @param XdimOut The width of the image */ void grayscale(unsigned char *ArrayIn, int Ydim, int Xdim, int Cdim, unsigned char **pArrayOut, int *YdimOut, int *XdimOut) { int i,j; float temp; unsigned char *ArrayOut = NULL; if (Cdim!=3) { errno = EPERM; goto end; } //allocating memory for the output image if (*pArrayOut == NULL) { *pArrayOut = (unsigned char *)malloc(Ydim*Xdim*sizeof(unsigned char)); } ArrayOut = *pArrayOut; if (ArrayOut == NULL) { errno = ENOMEM; goto end; } #pragma omp parallel for \ default(shared) private(j,temp) for (i = 0; i< Ydim*Xdim; i++) { j = i*3; temp = 0.11*ArrayIn[j] + 0.59*ArrayIn[j+1] + 0.3*ArrayIn[j+2]; ArrayOut[i] = (unsigned char)temp; } end: *pArrayOut = ArrayOut; *YdimOut = Ydim; *XdimOut = Xdim; } /** * Perform numpy.average(stack,axis=0) * * @param ArrayIn An array of pointers to the slices (contiguous Ydim*Xdim memory block, one for each slice) * @param Zdim The number of slices * @param Ydim The height of the images * @param Xdim The width of the images * @param pArrayOut A pointer to the output averaged image * @param YdimOut The height of the image * @param XdimOut The width of the image */ void average(unsigned char **ArrayIn, int Zdim, int Ydim, int Xdim, unsigned char **pArrayOut, int *YdimOut, int *XdimOut) { int z,i; unsigned char *ArrayOut = NULL; float temp; //allocating memory for the output image if (*pArrayOut == NULL) { *pArrayOut = (unsigned char *)calloc(Ydim*Xdim,sizeof(unsigned char)); } ArrayOut = *pArrayOut; if (ArrayOut == NULL) { errno = ENOMEM; goto end; } #pragma omp parallel for \ default(shared) private(z,temp) for (i = 0; i < Ydim*Xdim; i++) { temp = 0; for (z = 0; z < Zdim; z++) { temp += ArrayIn[z][i]; } temp = temp / Zdim; if (temp > 255) temp = 255; ArrayOut[i] = (unsigned char)temp; } end: *pArrayOut = ArrayOut; *YdimOut = Ydim; *XdimOut = Xdim; } /** * For each slice in the list, replace the pixel values with abs(pixel value - background pixel value) * * @param ArrayInpl an array of pointers to the slices (contiguous Ydim*Xdim memory block) * @param Zdim The number of slices * @param Ydim The height of the images * @param Xdim The width of the images * @param ArrayIn2 The background image array (must be the same size as Ydim,Xdim) * @param Ydim2 The height of the background image * @param Xdim2 The width of the background image */ void bsub(unsigned char **ArrayInpl, int Zdim, int Ydim, int Xdim, unsigned char *ArrayIn2, int Ydim2, int Xdim2) { int i,z; if (Ydim!=Ydim2 || Xdim!=Xdim2) { errno = E2BIG; goto end; } #pragma omp parallel for \ default(shared) private(i) for (z = 0; z < Zdim; z++) { for (i = 0; i< Ydim*Xdim; i++) ArrayInpl[z][i] = abs(ArrayInpl[z][i]-ArrayIn2[i]); } end: return; }
C
#include "debug.h" // M_ASSERT void show_memory(const void *start, const size_t size) { M_ASSERT(start != NULL, "Start pointer is NULL"); // buffer contains ASCII characters from this piece of memory unsigned char buffer[DEBUG_MEMORY_ROW_LENGTH + 1]; buffer[DEBUG_MEMORY_ROW_LENGTH] = '\0'; unsigned char *pointer = (unsigned char *)start; for (int i = 0; i < size; i++) { // ADDRESSES if ((i % DEBUG_MEMORY_ROW_LENGTH) == 0) printf(" " HEX_FORMAT ": ", (size_t)(pointer + i)); // VALUES // 0F, ..., 01, 00 printf("%02X ", pointer[i]); buffer[i % DEBUG_MEMORY_ROW_LENGTH] = pointer[i]; if (((i + 1) % DEBUG_MEMORY_ALIGNMENT) == 0) printf(" "); if (((i + 1) % DEBUG_MEMORY_ROW_LENGTH) == 0) { printf(" | "); for (unsigned char *char_ptr = buffer; char_ptr != (buffer + DEBUG_MEMORY_ROW_LENGTH); char_ptr++) { // only printable characters if (*char_ptr < 0x20 || *char_ptr > 0x7F) printf(" "); else printf("%c", *char_ptr); } printf("\n"); } } printf("\n"); // just in case }
C
/** * @file msg_interface.h * * @author Noah Ryan * * This file contains interface definitions for the Message module */ #ifndef __MSG_INTERFACE_H__ #define __MSG_INTERFACE_H__ #include "msg_definitions.h" /** * @brief msg_telemetry_message * * @author Noah Ryan * * This function sets up a telemetry message header given the required information. * * @param[out] header - a pointer to the message header to fill out. * @param[in] packet_id - the packet id of the message. * @param[in] size_bytes - the message size in bytes. * * @return Either MSG_RESULT_OKAY indicating that the message was successfully * filled out, or MSG_RESULT_NULL_POINTER indicating that the message input * was NULL. */ MSG_RESULT_ENUM msg_telemetry_message(MSG_Header *header, MSG_PACKETID_ENUM packet_id, uint16_t size_bytes); /** * @brief msg_command_message * * @author Noah Ryan * * This function sets up a command's message header given the required information. * * @param[out] header - a pointer to the message header to fill out. * @param[in] packet_id - the packet id of the message. * @param[in] size_bytes - the message size in bytes. * * @return Either MSG_RESULT_OKAY indicating that the message was successfully * filled out, or MSG_RESULT_NULL_POINTER indicating that the message input * was NULL. */ MSG_RESULT_ENUM msg_command_message(MSG_Header *header, MSG_PACKETID_ENUM packet_id, uint16_t size_bytes); #endif // ndef __MSG_INTERFACE_H__ */
C
#include<stdio.h> int main(void) { int i; char s[10]; printf("enter the string:\n"); scanf("%s",&s); for(i=1;i<=5;i++) { printf("%s\n",s); } return 0; }
C
#include <punit.h> #include "cstrings.h" static void setup(void) { } static void teardown(void) { } /* * This is exactly the same matcher used in * module/subscriptions.c */ static int field_matcher(const char *list, const char *field) { const char *sep = "."; int match; char *p; match = stringlist_searchn(list, field, strlen(field)); if (!match && (p = strstr(field, sep))) { do { const size_t len = (ptrdiff_t)p++ - (ptrdiff_t)field; match = stringlist_searchn(list, field, len); } while (!match && p && (p = strstr(p, sep))); } return match; } static char * test_invalid_cases(void) { const char *field = "title"; int match; match = field_matcher("", field); pu_assert_equal("should not match", match, 0); match = stringlist_searchn("title", "", 0); pu_assert_equal("should not match", match, 0); match = stringlist_searchn("title", "\0", 1); pu_assert_equal("should not match", match, 0); return NULL; } static char * test_simple_match(void) { const char *list = "title"; const char *field = "title"; int match; match = field_matcher(list, field); pu_assert_equal("should just match", match, 1); return NULL; } static char * test_simple_no_match(void) { const char *list = "title"; const char *field = "titlo"; int match; match = field_matcher(list, field); pu_assert_equal("should not match", match, 0); return NULL; } static char * test_simple_match_in_list(void) { const char *list = "abc\ntitle\ndef"; const char *field = "title"; int match; match = field_matcher(list, field); pu_assert_equal("should match in the middle of the list", match, 1); return NULL; } static char * test_simple_match_in_list_last(void) { const char *list = "abc\ntitle\ndef"; const char *field = "def"; int match; match = field_matcher(list, field); pu_assert_equal("should match in the middle of the list", match, 1); return NULL; } static char * test_sub_match(void) { const char *list = "title"; const char *field = "title.en"; int match; match = field_matcher(list, field); pu_assert_equal("should just match", match, 1); return NULL; } static char * test_sub_list_match(void) { const char *list = "image\ntitle"; const char *field = "title.en"; int match; match = field_matcher(list, field); pu_assert_equal("should just match", match, 1); return NULL; } static char * test_sub_list_no_match(void) { const char *list = "image\ntitle.en"; const char *field = "title.ru"; int match; match = field_matcher(list, field); pu_assert_equal("should not match", match, 0); return NULL; } static char * test_sub_list_no_match_inverse1(void) { const char *list = "image\ntitle.en"; const char *field = "title"; int match; match = field_matcher(list, field); pu_assert_equal("should not match", match, 0); return NULL; } static char * test_sub_list_no_match_inverse2(void) { const char *list = "image\ntitle.en"; const char *field = "title.ru"; int match; match = field_matcher(list, field); pu_assert_equal("should not match", match, 0); return NULL; } static char * test_broken_list1(void) { const char *list = "image\ntitle\n"; const char *field = "title.en"; int match; match = field_matcher(list, field); pu_assert_equal("should match", match, 1); return NULL; } static char * test_broken_list2(void) { const char *list = "pic\n\ntitle.en"; const char *field = "title.en"; int match; match = field_matcher(list, field); pu_assert_equal("should match", match, 1); return NULL; } static char * test_empty_field(void) { const char *list = "abc\ntitle\ndef"; const char *field = ""; int match; match = field_matcher(list, field); pu_assert_equal("no match", match, 0); return NULL; } static char * test_long_string(void) { const char *list = "abc\ntitle\ndef"; const char field[] = "titlee"; int match; match = stringlist_searchn(list, field, sizeof(field) - 3); pu_assert_equal("no match", match, 0); match = stringlist_searchn(list, field, sizeof(field) - 2); pu_assert_equal("match", match, 1); match = stringlist_searchn(list, field, sizeof(field) - 1); pu_assert_equal("no match", match, 0); return NULL; } static char * test_get_array_field_index(void) { const char str1[] = "field"; const char str2[] = "field[]"; const char str3[] = "field[0]"; const char str4[] = "field[90000]"; const char str5[] = "field[-1]"; const char str6[] = "field[[1]"; const char str7[] = "field[1]]"; const char str8[] = "[1]"; const char str9[] = "[field1]"; const char str10[] = "field[a1]"; ssize_t len; ssize_t res; len = get_array_field_index(str1, sizeof(str1) - 1, &res); pu_assert_equal("", len, -1); len = get_array_field_index(str2, sizeof(str2) - 1, &res); pu_assert_equal("", len, -2); len = get_array_field_index(str3, sizeof(str3) - 1, &res); pu_assert_equal("", len, 5); pu_assert_equal("", res, 0); len = get_array_field_index(str4, sizeof(str4) - 1, &res); pu_assert_equal("", len, 5); pu_assert_equal("", res, 90000); len = get_array_field_index(str5, sizeof(str5) - 1, &res); pu_assert_equal("", len, 5); pu_assert_equal("", res, -1); len = get_array_field_index(str6, sizeof(str6) - 1, &res); pu_assert_equal("", len, 6); pu_assert_equal("", res, 1); len = get_array_field_index(str7, sizeof(str7) - 1, &res); pu_assert_equal("", len, -2); len = get_array_field_index(str8, sizeof(str8) - 1, &res); pu_assert_equal("", len, 0); pu_assert_equal("", res, 1); len = get_array_field_index(str9, sizeof(str9) - 1, &res); pu_assert_equal("", len, -2); len = get_array_field_index(str10, sizeof(str10) - 1, &res); pu_assert_equal("", len, -2); return NULL; } void all_tests(void) { pu_def_test(test_invalid_cases, PU_RUN); pu_def_test(test_simple_match, PU_RUN); pu_def_test(test_simple_no_match, PU_RUN); pu_def_test(test_simple_match_in_list, PU_RUN); pu_def_test(test_simple_match_in_list_last, PU_RUN); pu_def_test(test_sub_match, PU_RUN); pu_def_test(test_sub_list_match, PU_RUN); pu_def_test(test_sub_list_no_match, PU_RUN); pu_def_test(test_sub_list_no_match_inverse1, PU_RUN); pu_def_test(test_sub_list_no_match_inverse2, PU_RUN); pu_def_test(test_broken_list1, PU_RUN); pu_def_test(test_broken_list2, PU_SKIP); /* TODO This is currently failing but it's not a big deal */ pu_def_test(test_empty_field, PU_RUN); pu_def_test(test_long_string, PU_RUN); pu_def_test(test_get_array_field_index, PU_RUN); }
C
#include <stdio.h> int main(){ int num, *ptr; printf("Ingresa numero: "); scanf("%d", &num); ptr = &num; if(*ptr%2 == 0) { printf("Es par"); printf("%p\n", ptr); }else{ printf("Es impar\n"); } return 0; }
C
/*################################################################################# #---------------------------------------------------------------------------------# #EXERCICI 5 - Richardson: Marc Pascual i Solé - Universitat de Barcelona # #---------------------------------------------------------------------------------# #Programa que calcula la derivada d'una funció en un punt usant el mètode de Rich-# # ardson, fent servir una matriu. Primer de tot, calcula la primera columna de la # # matriu T fent servir la fòrmula de derivació centrada f' = [ f(a+h)-f(a-h) ]/2h # # amb una h progressivament més petita decrementada un factor donat "q". # # Després, es calculen les demès columnes a partir de la primera amb el mètode de # # Richardson Tij = Ti-1,j-1 + [ Ti-1,j-1 - Ti,j-1]/[ q^2*j - 1 ]. # # Finalment, s'imprimeixen els resultats. # ###################################################################################*/ #include <stdio.h> #include <stdlib.h> #include <math.h> //Nombre màxim de passes de Richardson #define N 4 double foo(double x) { return exp(x); } int main(void) { int i,j; double T[N+1][N+1]; double h,q,a,temp,x; printf("\nEXTRAPOLACIÓ DE RICHARDSON\n\n"); printf("a="); scanf("%lf",&a); printf("h0="); scanf("%lf",&h); printf("q="); scanf("%lf",&q); for(i=0;i<N;i++) { //x és un múltiple de h x=pow(q,i)*h; T[i][0]=(foo(a+x)-foo(a-x))/(2.*x); } for(j=1;j<N;j++) { for(i=0;i<N;i++) { if(i>=j) { temp=pow(q,2*j)-1.; T[i][j]=T[i-1][j-1]+((T[i-1][j-1]-T[i][j-1])/temp); } } } for(i=0;i<N;i++) { for(j=0;j<N;j++) { if(i>=j) { printf("%.10lf ",T[i][j]); } } printf("\n"); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_list_remove_if.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: anmauffr <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/18 12:15:08 by anmauffr #+# #+# */ /* Updated: 2018/07/26 03:18:57 by anmauffr ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_list.h" void ft_suite(t_list *elem, t_list **begin_list, void *data_ref, int (*cmp)()) { t_list *tmp; while (elem->next) { if (elem->next == NULL) { *begin_list = 0; return ; } if (cmp(elem->next->data, data_ref) == 0) { tmp = elem->next->next; free(elem->next); elem->next = tmp; } if (cmp(elem->next->data, data_ref) != 0) elem = elem->next; } } void ft_list_remove_if(t_list **begin_list, void *data_ref, int (*cmp)()) { t_list *elem; t_list *tmp; if (*begin_list == 0) return ; elem = *begin_list; while (cmp(elem->data, data_ref) == 0) { if (elem->next == NULL) { *begin_list = 0; return ; } tmp = elem->next; free(elem); elem = tmp; *begin_list = elem; } ft_suite(elem, begin_list, data_ref, cmp); }
C
/* * employee.h * * Created on: 15 may. 2021 * Author: julio */ #ifndef ARRAYEMPLOYEES_H_ #define ARRAYEMPLOYEES_H_ #define SIZE_NAME 51 typedef struct { int idEmployee; char name[SIZE_NAME]; char lastName[SIZE_NAME]; float salary; int sector; int isEmpty; }Employee; int emp_init(Employee *list, int len); int emp_add(Employee *list, int len, int *id); int emp_remove(Employee *list, int len); int emp_modify(Employee* array,int limite); int emp_findById(Employee *list, int len, int *indexObtained); int emp_print(Employee *list); int emp_printArray(Employee *list, int len); int emp_searchEmptyIndex(Employee* list,int* emptyIndex,int len); int emp_isEmptyIndex(Employee *pEmployee); int emp_searchID(Employee *list, int len, int IdEntered, int *indexObtained); int emp_validateList(Employee *list, int len); int emp_inform(Employee* list, int len); int emp_informSector(Employee* list, int len); int emp_sortByLastName(Employee* list, int len); int emp_sortBySector(Employee* list, int len); int emp_SalaryInfo(Employee* pEmployee, int length); int emp_ForceAdd(Employee *list, int len, char *name, char *lastName, float salary,int sector, int index, int *id); #endif /* ARRAYEMPLOYEES_H_ */
C
// Fighting Fantasy combat analysis // simulation of combat outcomes with simple Luck-based strategy (Luck never depletes, and is used on every successful attack round) // outputs a table of victory probabilities for different Skill differences (kdiff) and hero, opponent Staminas (shero, sopp) // these victory probabilities are, for theoretical interest, further classified by the final successful round -- the sum of these classes gives overall victory probability #include <stdio.h> #include <stdlib.h> // define random number and die roll macros #define RND drand48() #define DIE (1+(int)(RND*6)) int main(void) { int shero, sopp; int kdiff; double outcome[7]; int i; int sh, so; int ah, ao; int lastso; int l = 12 ; int r; int nit = 10000; FILE *fp; fp = fopen("simpleluck.txt", "w"); // loop through Skill differences for(kdiff = -5; kdiff <= 5; kdiff++) { // loop through hero Stamina for(shero = 1; shero <= 24; shero++) { // loop through opponent Stamina for(sopp = 1; sopp <= 24; sopp++) { printf("%i %i %i\n", kdiff, shero, sopp); // we label the following outcomes based on the last change to opponent stamina: // 0: 4->0 ; 1: 3->-1; 2: 2->-2; 3: 1->-3; 4: 1->0 // the sum of these gives overall victory probability for(i = 0; i <= 6; i++) outcome[i] = 0; // loop through simulated iterations for(i = 0; i < nit; i++) { // initial conditions sh = shero; so = sopp; // simulate attack rounds for(;;) { ah = DIE+DIE+kdiff; ao = DIE+DIE; lastso = so; if(ao > ah) sh -= 2; else if(ah > ao) { // employ luck r = DIE+DIE; if(r <= l) so -= 4; else so -= 1; } if(so <= 0 || sh <= 0) break; } // categorise successful outcomes if(sh > so) { if(lastso == 4) outcome[0]++; if(lastso == 3) outcome[1]++; if(lastso == 2 && so == -2) outcome[2]++; if(lastso == 1 && so == -3) outcome[3]++; if(lastso == 1 && so == 0) outcome[4]++; } } fprintf(fp, "%i %i %i ", kdiff, shero, sopp); for(i = 0; i <= 4; i++) { fprintf(fp, "%f ", outcome[i]/nit); } fprintf(fp, "\n"); } } } fclose(fp); return 0; }
C
#include <sys/mman.h> #include <pthread.h> #define N 5000 #define MAX_BB_LIST_SIZE 10 #define MAX_GB_LIST_SIZE 20 #define MAX_SB_LIST_SIZE 100 #define HASHMAP_SIZE 10000 typedef struct BucketStruct { void* ptr; size_t size; struct BucketStruct* next; struct BucketStruct* prev; pthread_t creatorThreadId; } Bucket; //global big buckets list Bucket* gbbList; Bucket* gbbListTail; int gbbListSize = 0; pthread_mutex_t gbbListMutex; typedef struct ThreadInfoStruct { pthread_t threadId; //big buckets list Bucket* bbList; Bucket* bbListTail; int bbListSize; pthread_mutex_t bbListMutex; //small buckets list Bucket* sbList; Bucket* sbListTail; int sbListSize; pthread_mutex_t sbListMutex; struct ThreadInfoStruct* next; } ThreadInfo; ThreadInfo* threadInfo[HASHMAP_SIZE] = {}; pthread_mutex_t threadInfoMutex; void* memcpy(void* destination, const void* source, size_t num); void* memset(void* ptr, int value, size_t num); //#define DEBUG_OUTPUT #ifdef DEBUG_OUTPUT #include <fcntl.h> #define NUMBER_BUFFER_SIZE 24 int debugOutputLineNumber = 0; void writeNumber(size_t number, int bufLen) { char buf[NUMBER_BUFFER_SIZE]; memset(buf, ' ', NUMBER_BUFFER_SIZE); int i = bufLen - 1; while (i >= 0) { buf[i--] = '0' + (number % 10); number /= 10; if (number == 0) break; } write(1, buf, bufLen); } void writeThreadId() { writeNumber(++debugOutputLineNumber, 7); write(1, "| thread[", 9); writeNumber(pthread_self(), NUMBER_BUFFER_SIZE); write(1, "]: ", 3); } #endif ThreadInfo* getThreadInfo(pthread_t tId) { ThreadInfo* tInfo = threadInfo[tId % HASHMAP_SIZE]; while (tInfo != 0 && tInfo->threadId != tId) tInfo = tInfo->next; if (tInfo == 0) { tInfo = (ThreadInfo*)mmap(0, sizeof(ThreadInfo), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); #ifdef DEBUG_OUTPUT if (tInfo == MAP_FAILED) { writeThreadId(); write(1, "mmap failed, crash coming...\n", 29); } #endif tInfo->threadId = tId; tInfo->bbList = 0; tInfo->bbListTail = 0; tInfo->bbListSize = 0; tInfo->sbList = 0; tInfo->sbListTail = 0; tInfo->sbListSize = 0; tInfo->next = 0; pthread_mutex_init(&tInfo->bbListMutex, 0); pthread_mutex_init(&tInfo->sbListMutex, 0); pthread_mutex_lock(&threadInfoMutex); tInfo->next = threadInfo[tId % HASHMAP_SIZE]; threadInfo[tId % HASHMAP_SIZE] = tInfo; pthread_mutex_unlock(&threadInfoMutex); } return tInfo; } #ifdef DEBUG_OUTPUT void writeThreadInfo() { pthread_t tId = pthread_self(); ThreadInfo* tInfo = getThreadInfo(tId); writeNumber(++debugOutputLineNumber, 7); write(1, "| thread[", 9); writeNumber(tId, NUMBER_BUFFER_SIZE); write(1, ", bb: ", 6); writeNumber(tInfo->bbListSize, 4); write(1, ", sb: ", 6); writeNumber(tInfo->sbListSize, 4); write(1, "]: ", 3); } #endif Bucket* searchBucketInList(Bucket* bList, size_t minSize) { Bucket* cur = bList; while (cur != 0 && cur->size < minSize) cur = cur->next; return cur; } void addBucketToList(Bucket* b, Bucket** bList, Bucket** bListTail) { if (*bListTail == 0) *bListTail = b; b->next = *bList; if (b->next != 0) b->next->prev = b; *bList = b; } void deleteBucketFromList(Bucket* b, Bucket** bList, Bucket** bListTail) { if (b == *bList && b == *bListTail) { *bList = 0; *bListTail = 0; return; } if (b == *bList) { *bList = b->next; b->next->prev = 0; b->next = 0; return; } if (b == *bListTail) { *bListTail = b->prev; b->prev->next = 0; b->prev = 0; return; } if (b->next != 0) b->next->prev = b->prev; if (b->prev != 0) b->prev->next = b->next; b->next = 0; b->prev = 0; } Bucket* createNewBucket(size_t size) { #ifdef DEBUG_OUTPUT writeThreadInfo(); write(1, "createB(", 8); writeNumber(size, NUMBER_BUFFER_SIZE); write(1, ")\n", 2); #endif Bucket* b = (Bucket*)mmap(0, sizeof(Bucket) + size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); #ifdef DEBUG_OUTPUT if (b == MAP_FAILED) { writeThreadInfo(); write(1, "mmap failed, crash coming...\n", 29); } #endif b->ptr = ((void*)b) + sizeof(Bucket); b->size = size; b->next = 0; b->prev = 0; b->creatorThreadId = pthread_self(); return b; } void destroyBucket(Bucket* b) { munmap((void*)b, sizeof(Bucket) + b->size); } void destroyBucketList(Bucket* bList) { if (bList == 0) return; if (bList->next != 0) destroyBucketList(bList->next); destroyBucket(bList); } void destroyThreadInfoList(ThreadInfo* tInfo) { if (tInfo == 0) return; destroyThreadInfoList(tInfo->next); pthread_mutex_destroy(&tInfo->bbListMutex); pthread_mutex_destroy(&tInfo->sbListMutex); destroyBucketList(tInfo->bbList); destroyBucketList(tInfo->sbList); munmap((void*)tInfo, sizeof(ThreadInfo)); } void _init() { pthread_mutex_init(&threadInfoMutex, 0); pthread_mutex_init(&gbbListMutex, 0); } void _fini() { pthread_mutex_destroy(&threadInfoMutex); pthread_mutex_destroy(&gbbListMutex); int i; for (i = 0; i < HASHMAP_SIZE; ++i) destroyThreadInfoList(threadInfo[i]); destroyBucketList(gbbList); } void* malloc(size_t size) { ThreadInfo* tInfo = getThreadInfo(pthread_self()); void* res; if (size >= N) { Bucket* bb = searchBucketInList(tInfo->bbList, size); if (bb != 0) { pthread_mutex_lock(&tInfo->bbListMutex); deleteBucketFromList(bb, &tInfo->bbList, &tInfo->bbListTail); --tInfo->bbListSize; pthread_mutex_unlock(&tInfo->bbListMutex); res = bb->ptr; } else { bb = searchBucketInList(gbbList, size); if (bb != 0) { pthread_mutex_lock(&gbbListMutex); deleteBucketFromList(bb, &gbbList, &gbbListTail); --gbbListSize; pthread_mutex_unlock(&gbbListMutex); res = bb->ptr; } else { bb = createNewBucket(size); res = bb->ptr; } } } else { Bucket* sb = searchBucketInList(tInfo->sbList, size); if (sb != 0) { pthread_mutex_lock(&tInfo->sbListMutex); deleteBucketFromList(sb, &tInfo->sbList, &tInfo->sbListTail); --tInfo->sbListSize; pthread_mutex_unlock(&tInfo->sbListMutex); res = sb->ptr; } else { sb = createNewBucket(size); res = sb->ptr; } } #ifdef DEBUG_OUTPUT writeThreadInfo(); write(1, "malloc (", 8); writeNumber(size, NUMBER_BUFFER_SIZE); write(1, ") = ", 4); writeNumber((size_t)res, NUMBER_BUFFER_SIZE); write(1, "\n", 1); #endif return res; } void free(void* ptr) { if (ptr == 0) return; #ifdef DEBUG_OUTPUT writeThreadInfo(); write(1, "free (", 8); writeNumber((size_t)ptr, NUMBER_BUFFER_SIZE); write(1, ")\n", 2); #endif Bucket* curBucket = (Bucket*)(ptr - sizeof(Bucket)); if (curBucket->size >= N) { ThreadInfo* tInfo = getThreadInfo(pthread_self()); pthread_mutex_lock(&tInfo->bbListMutex); addBucketToList(curBucket, &tInfo->bbList, &tInfo->bbListTail); ++tInfo->bbListSize; pthread_mutex_unlock(&tInfo->bbListMutex); if (tInfo->bbListSize > MAX_BB_LIST_SIZE) { //I think, it's better to move out (to gbbList) NOT curBucket, //because there can be smaller buckets holding place in list, so we will alloc and free bigger bucket every time. //Moving out smallest bucket is also a bad idea: this means, that sum size of buckets in list will only increase. //So I'll take the last bucket in list (adding to list adds to front, so that's a kind of a queue). pthread_mutex_lock(&tInfo->bbListMutex); Bucket* toMoveToGlobalBBList = tInfo->bbListTail; deleteBucketFromList(toMoveToGlobalBBList, &tInfo->bbList, &tInfo->bbListTail); --tInfo->bbListSize; pthread_mutex_unlock(&tInfo->bbListMutex); pthread_mutex_lock(&gbbListMutex); addBucketToList(toMoveToGlobalBBList, &gbbList, &gbbListTail); ++gbbListSize; pthread_mutex_unlock(&gbbListMutex); if (gbbListSize > MAX_GB_LIST_SIZE) { pthread_mutex_lock(&gbbListMutex); Bucket* toDestroy = gbbListTail; deleteBucketFromList(toDestroy, &gbbList, &gbbListTail); --gbbListSize; pthread_mutex_unlock(&gbbListMutex); destroyBucket(toDestroy); } } } else { ThreadInfo* tInfo = getThreadInfo(curBucket->creatorThreadId); pthread_mutex_lock(&tInfo->sbListMutex); addBucketToList(curBucket, &tInfo->sbList, &tInfo->sbListTail); ++tInfo->sbListSize; pthread_mutex_unlock(&tInfo->sbListMutex); if (tInfo->sbListSize > MAX_SB_LIST_SIZE) { pthread_mutex_lock(&tInfo->sbListMutex); Bucket* toDestroy = tInfo->sbListTail; deleteBucketFromList(toDestroy, &tInfo->sbList, &tInfo->sbListTail); --tInfo->sbListSize; pthread_mutex_unlock(&tInfo->sbListMutex); destroyBucket(toDestroy); } } } void* realloc(void* ptr, size_t size) { #ifdef DEBUG_OUTPUT writeThreadInfo(); write(1, "realloc(", 8); writeNumber((size_t)ptr, NUMBER_BUFFER_SIZE); write(1, ", ", 2); writeNumber(size, NUMBER_BUFFER_SIZE); write(1, ")\n", 2); #endif if (ptr == 0) return malloc(size); if (size == 0) { free(ptr); return 0; } size_t oldSize = ((Bucket*)(ptr - sizeof(Bucket)))->size; if (oldSize >= size && (size >= N || oldSize < N)) return ptr; void* res = malloc(size); memcpy(res, ptr, oldSize < size ? oldSize : size); free(ptr); return res; } void* calloc(size_t num, size_t size) { void* res = malloc(num * size); return memset(res, 0, num * size); }
C
/** * @file huge_page.h * * Copyright (c) 2016 * All rights reserved. * * * @NETFPGA_LICENSE_HEADER_START@ * * Licensed to NetFPGA C.I.C. (NetFPGA) under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. NetFPGA licenses this * file to you under the NetFPGA Hardware-Software License, Version 1.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.netfpga-cic.org * * Unless required by applicable law or agreed to in writing, Work distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * @NETFPGA_LICENSE_HEADER_END@ * * * @brief A basic library that can manage huge pages in user space. * @author José Fernando Zazo Rollón, [email protected] * @date 2013-07-04 */ #ifndef HP_H #define HP_H #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <sys/mman.h> #include <unistd.h> #include <fcntl.h> //#define HUGEPAGE_SIZE (1024UL*1024UL*1024UL) /**< Size of each page */ //#define NUMBER_HUGEPAGE 8UL /**< Number of pages */ #define FILE_NAME "/dev/hugepages/test" /**< File associated with the page (mmap will be invoked under a fd pointing to this file). */ /** * @brief Structure of a huge page. */ struct hugepage { int identifier; /**< File descriptor to FILE_NAME file. User doesnt need to initialize this field, the library makes it. */ void *data; /**< Pointer to the region of memory of the huge page. */ }; /** * @brief The "malloc" function of a huge page. * * @param hp Struct of type struct hugepage that will be initialized properly. * @param size The size that we wish. * * @return 0 if everything was correct, a negative value in other situation. */ int alloc_hugepage (struct hugepage *hp, uint64_t npages); /** * @brief Free the previously allocated memory on the structure pointed by hp. * * @param hp A struct hugepage which was previously allocated by a alloc_hugepage called. */ void free_hugepage (struct hugepage *hp); /** * @brief Get the current size configuration of huge pages (size: 2MB or 1GB) * * @return The current configuration of the system */ uint64_t hugepage_size(); /** * @brief Get the current number configuration of huge pages (Total number of free hugepages) * * @return The total number of free huge pages */ uint64_t hugepage_number(); #endif
C
#include <webots/distance_sensor.h> #include <webots/gps.h> #include <webots/inertial_unit.h> #include <webots/motor.h> #include <webots/robot.h> #include <stdio.h> #define TIME_STEP 64 int main(int argc, char **argv) { wb_robot_init(); // GPS Sensor WbDeviceTag gps = wb_robot_get_device("GPS"); wb_gps_enable(gps, TIME_STEP); // IMU sensor WbDeviceTag imu = wb_robot_get_device("IMU"); wb_inertial_unit_enable(imu, TIME_STEP); // Distance Sensor WbDeviceTag ds[2]; int i; char ds_names[2][10] = {"ds_left", "ds_right"}; for (i = 0; i < 2; i++) { ds[i] = wb_robot_get_device(ds_names[i]); wb_distance_sensor_enable(ds[i], TIME_STEP); } // Actuators (wheels) WbDeviceTag wheels[4]; char wheels_names[4][8] = {"wheel1", "wheel2", "wheel3", "wheel4"}; for (i = 0; i < 4; i++) { wheels[i] = wb_robot_get_device(wheels_names[i]); wb_motor_set_position(wheels[i], INFINITY); } bool avoid_obstacle_counter = 0; // Control loop while (wb_robot_step(TIME_STEP) != -1) { // Read sensors double ds_values[2]; for (i = 0; i < 2; i++) ds_values[i] = wb_distance_sensor_get_value(ds[i]); const double* gps_values = wb_gps_get_values(gps); const double gps_speed = wb_gps_get_speed(gps); printf("GPS readings: position (%f, %f, %f), speed: %f\n", gps_values[0],gps_values[1],gps_values[2], gps_speed ); const double* imu_values = wb_inertial_unit_get_roll_pitch_yaw(imu); printf("IMU readings: roll %f, pitch: %f, yaw: %f\n", imu_values[0],imu_values[1],imu_values[2]); // Process measurements and select actuator commands double left_speed = 2.0; double right_speed = 2.0; if (avoid_obstacle_counter > 0) { avoid_obstacle_counter--; left_speed = 2.0; right_speed = -2.0; } else { if (ds_values[0] < 950.0 || ds_values[1] < 950.0) avoid_obstacle_counter = 20; } // Write commands to actuators wb_motor_set_velocity(wheels[0], left_speed); wb_motor_set_velocity(wheels[1], right_speed); wb_motor_set_velocity(wheels[2], left_speed); wb_motor_set_velocity(wheels[3], right_speed); } wb_robot_cleanup(); return 0; // EXIT_SUCCESS }
C
#include <stdio.h> #include <stdlib.h> void censor(char *str); int main() { char str[100] = "food fool fike five f"; censor(str); printf(str); return 0; } void censor(char *str) { for(;*str!='\0';) { if (*str == 'f') { if (*(str+1) != '\0' && *(str+2)!='\0' && *(str+1) == 'o' && *(str+2) == 'o') { *str = 'x'; *(str+1) = 'x'; *(str+2) = 'x'; str+=3; continue; } } str+=1; } }
C
#include <stdio.h> /* include information about standard library*/ int main() /* define a function named main that receive no argument value*/ { /* statement of main are enclosed in braces*/ printf("hello, World\n"); /* mains calls library function printf to print the sequence ofcharacter; \n represents the newline character */ printf("fine\n"); }
C
/** * @file gpio_test.c * @brief Quectel SC20 Module about gpio example. * * @note * * @copyright Copyright (c) 2009-2017 @ Quectel Wireless Solutions Co., Ltd. */ #include <stdio.h> #include <stdint.h> #include <string.h> #include <ql_gpio/ql_gpio.h> int main(int argc, char *argv[]) { char buf[64]; uint32_t gpio_number, cfg_val, inout_val; uint32_t dir_index, drv_strength_index, bias_index; char *dir[2] = { "in", "out" }; char *drv_strength[8] = { "2mA", "4mA", "6mA", "8mA", "10mA", "12mA", "14mA", "16mA", }; char *bias[4] = { "no-pull", "weak-pull-down", "weak-keeper", "weak-pull-up" }; if (argc < 2 || argc > 4) { fprintf(stderr, "usage: %s <gpio_number> [gpio_cfg] [gpio_level]\n", argv[0]); return -1; } sscanf(argv[1], "%d", &gpio_number); if (!Gpio_Valid(gpio_number)) { fprintf(stderr, "%s: invalid gpio number: %d\n", argv[0], gpio_number); return -1; } fprintf(stdout, "gpio number: %d\n", gpio_number); if (argc == 2) { // gpio status test QL_Gpio_Get_Config(gpio_number, &cfg_val); QL_Gpio_Get_Level(gpio_number, &inout_val); dir_index = (cfg_val >> 9) & 1; drv_strength_index = (cfg_val >> 6) & 7; bias_index = cfg_val & 3; memset(buf, 0, sizeof(buf)); fprintf(stdout, "%s:%s:%s:%d\n", dir[dir_index], drv_strength[drv_strength_index], bias[bias_index], inout_val); } else if (argc == 3) { sscanf(argv[2], "%x", &cfg_val); fprintf(stdout, "gpio configuration: %#x\n", cfg_val); QL_Gpio_Set_Config(gpio_number, cfg_val); } else if (argc == 4) { // gpio output test sscanf(argv[2], "%x", &cfg_val); sscanf(argv[3], "%x", &inout_val); fprintf(stdout, "gpio configuration: %#x, out level: %d\n", cfg_val, inout_val); QL_Gpio_Set_Config(gpio_number, cfg_val); QL_Gpio_Set_Level(gpio_number, !!inout_val); } return 0; }
C
#include <stdio.h> #ifdef _Cplusplus extern "C" { #endif int code(char *input, char *output); int decode(char *input, char *output); #ifdef _Cplusplus } #endif int main(int argc, char** argv) { if ( argc < 4 || (*argv[1] != '0' && *argv[1] != '1') ) { printf("Usage: ./main <0/1> <input> <output>\n0 - code\n1 - decode\n\n"); return 1; } if (*argv[1] == '0') { code(argv[2], argv[3]); } else if(*argv[1] == '1') { decode(argv[2], argv[3]); } return 0; }
C
#include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include "graphics.h" void *GFX_context = NULL; void LOOP_Start(); void LOOP_Tick(); void LOOP_OnError(const char *s); void *GFX_LoadBitmap(const char *location) { char *path = calloc(1 + strlen(location) + 1, sizeof(char)); strcpy(path + 1, location); path[0] = '.'; SDL_Surface *surf = IMG_Load(path); if (surf == NULL) { LOOP_OnError(SDL_GetError()); return NULL; } SDL_Texture *tex = SDL_CreateTextureFromSurface((SDL_Renderer *) GFX_context, surf); if (tex == NULL) { LOOP_OnError(SDL_GetError()); return NULL; } SDL_FreeSurface(surf); free(path); return (void *) tex; } void GFX_FreeBitmap(void *sprite) { SDL_DestroyTexture((SDL_Texture *) sprite); } void GFX_GetBitmapSize(void *sprite, int *w, int *h) { uint32_t format; int access; SDL_QueryTexture((SDL_Texture *) sprite, &format, &access, w, h); } void GFX_DrawBitmap(void *sprite, int srcx, int srcy, int srcw, int srch, int dstx, int dsty) { SDL_Rect srcrect = {srcx, srcy, srcw, srch}; SDL_Rect dstrect = {dstx, dsty, srcw, srch}; SDL_RenderCopy((SDL_Renderer *) GFX_context, (SDL_Texture *) sprite, &srcrect, &dstrect); } int SDL_main(int argc, char **argv) { SDL_Window *window; window = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, 0); if (window == NULL) { printf("Could not create SDL window\n"); return 1; } GFX_context = SDL_CreateRenderer(window, -1, 0); if (GFX_context == NULL) { printf("Could not create SDL renderer\n"); return 1; } IMG_Init(IMG_INIT_PNG); LOOP_Start(); int running = 1; while (running) { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: running = 0; break; } } LOOP_Tick(); SDL_RenderPresent((SDL_Renderer *) GFX_context); SDL_Delay(16); } SDL_DestroyRenderer((SDL_Renderer *) GFX_context); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); return 0; }
C
#include <stdio.h> int main() { typedef struct { int hora, minutos, segundos; } horario; typedef struct { int dia, mes, ano; } data; typedef struct { horario h; data d; } compromisso; return 0; }
C
#include <stdio.h> #include <string.h> char in[205]; char c; int isvowel(char c){ int r=0; if (c=='a') r=1; if (c=='e') r=1; if (c=='i') r=1; if (c=='o') r=1; if (c=='u') r=1; if (c=='y') r=1; return(r); } int syllables(int s,int l){ int vowel=0; int i; int f=0; for(i=s;i<l;i++){ if( ( isvowel(in[i]) ) && (vowel==0) ) {f++;vowel=1;} if( (!isvowel(in[i]) ) && (vowel==1) ) vowel=0; } return(f); } int findslash(int s){ int i; int r=0; for(i=s;i<strlen(in);i++) if(in[i]=='/'){r=i; i=205;} return(r); } int main(){ int l1,l2,l3; int slashpos; int start,end; while(gets(in)){ if(!strcmp(in,"e/o/i")) exit(0); start=0; end=findslash(start); l1=syllables(start,end); start=end+1; end=findslash(start); l2=syllables(start,end); start=end+1; end=strlen(in); l3=syllables(start,strlen(in)); if(l1!=5) printf("1\n"); else if (l2!=7) printf("2\n"); else if (l3!=5) printf("3\n"); else printf("Y\n"); } }
C
//flow meter using timer1 without prescalar and 5ms delay with issue of INT1 ACTIVATING FIRST RESOLVED IN ft2.c #define F_CPU 8000000UL #include<avr/io.h> #include<util/delay.h> #include<avr/interrupt.h> #include<string.h> #define LED PE6 #define LCD_Command_Dir DDRE #define LCD_Command_Port PORTE #define LCD_Data_Dir DDRC #define LCD_Data_Port PORTC #define RS PE4 #define EN PE2 #define RW PE3 float ticks=0.00; unsigned long overflow=0; unsigned int tcntres=0; double volume=0.00; //for volume calulation double flow=0.00; //for flow calculation flow=vol*60/sec char tcntresult[20]={0}; char overresult[20]={0}; char ticksres[20]={0}; char flowres[20]={0}; ISR(INT0_vect) { PORTE=0b00000000; //led off TCCR1B |= (1<<CS10); //no prescalar and normal mode EIMSK= 0b00000110; //setting interrupt1 on and interrupt0 off EICRA=0X0C; //setting interrupt1 for rising edge // sei(); // while(1) // { // // } } ISR(INT1_vect) { tcntres=65535-TCNT1; PORTE=0b01000000; TCCR1B=0X00; // ticks=(((float)overflow) * 0.009984) + (((float)tcntres) * 0.000128); //for 1024 prescalar with calculation changes ticks=(((float)overflow) * 0.005) + (((float)tcntres) * 0.000000125); //for 1024 prescalar with calculation changes //sprintf(ticksres,"t=%.2f",ticks); //LCD_String_xy(0,0,ticksres); flow=((volume*60)/ticks); sprintf(flowres,"t=%.2f fl=%lf",ticks,flow); LCD_String_xy(0,0,flowres); sprintf(tcntresult,"tcnt=%u ov=%lu ",tcntres,overflow); LCD_String_xy(1,0,tcntresult); ticks=0.00; tcntres=0; overflow=0; flow=0.00; memset(flowres,0,20); memset(tcntresult,0,20); EIMSK = 0b00000100; } ISR(INT2_vect) { LCD_Clear(); PORTE=~PORTE; /* Toggle PORTE */ _delay_ms(100); TCCR1B=0X00; memset(flowres,0,20); memset(tcntresult,0,20); overflow=0; tcntres=0; flow=0.00; ticks=0.00; // LCD_Clear(); LCD_String_xy(0,1,"WELCOME TO"); LCD_String_xy(1,1,"NETEL FLOWMETER"); EIMSK = 0b00000101; } ISR (TIMER1_OVF_vect) //TIMER OVERFLOW ISR { overflow++; TCNT1=25536; } void timer1_init() { TCNT1=25536; //from calculation overflow=0; TIMSK |= (1<<TOIE1); //INTERRUPT FOR TIMER1 OVERFLOW } void LCD_Command(unsigned char cmnd) { LCD_Data_Port= cmnd; LCD_Command_Port &= ~(1<<RS); /* RS=0 command reg. */ _delay_ms(1); LCD_Command_Port &= ~(1<<RW); /* RW=0 Write operation */ _delay_ms(1); LCD_Command_Port |= (1<<EN); /* Enable pulse */ _delay_ms(1); LCD_Command_Port &= ~(1<<EN); _delay_ms(1); } void LCD_Char (unsigned char char_data) /* LCD data write function */ { LCD_Data_Port= char_data; LCD_Command_Port |= (1<<RS); /* RS=1 Data reg. */ _delay_ms(1); LCD_Command_Port &= ~(1<<RW); /* RW=0 write operation */ _delay_ms(1); LCD_Command_Port |= (1<<EN); /* Enable Pulse */ _delay_ms(1); LCD_Command_Port &= ~(1<<EN); _delay_ms(1); } void LCD_Init(void) { LCD_Command_Dir = 0xFF; LCD_Data_Dir = 0xFF; _delay_ms(20); LCD_Command (0x38); //initialize in 8-bit mode _delay_ms(1); LCD_Command (0x0C); //display on cursor off _delay_ms(1); LCD_Command (0x06); //autoincrement cursor _delay_ms(1); LCD_Command (0x01); //clear screen _delay_ms(1); LCD_Command (0x80); //cursor at starting point } void LCD_Clear(void) { LCD_Command (0x01); /* clear display */ _delay_ms(1); LCD_Command (0x80); /* cursor at home position */ _delay_ms(1); } void LCD_String (char *str) /* Send string to LCD function */ { int i; for(i=0;str[i]!=0;i++) /* Send each char of string till the NULL */ { LCD_Char (str[i]); } } void LCD_String_xy (char row, char pos, char *str)/* Send string to LCD with xy position */ { if (row == 0 && pos<16) LCD_Command((pos & 0x0F)|0x80); /* Command of first row and required position<16 */ else if (row == 1 && pos<16) LCD_Command((pos & 0x0F)|0xC0); /* Command of first row and required position<16 */ LCD_String(str); /* Call LCD string function */ } int main ( ) { DDRE=0XFF; //MAKE PORTE OUTPUT PORT DDRD=0X00; //MAKE PORT D AS INPUT PORTE=0b01000000; //LED GLOW FOR INDICATION PORTD=0XFC; //except pd1 and pd0 all pins are high LCD_Init(); //intialize lcd float ID=1.7; //diameter=3.4mm so radius of capillary in mm is d/2 which is 1.7mm int height=47; //height of capillary in mm double pie=3.14285714286; //pie value used for volume calculation LCD_String_xy(0,0,"WELCOME TO"); LCD_String_xy(1,0,"NETEL FLOWMETER"); _delay_ms(1000); volume=(pie*(ID)*(ID)*height)/1000; //volume in mm3 which is converted into ml by dividing it with 1000 // EIMSK |= (1<<INT0); //set int0 interrupt EIMSK = 0b00000101; //set int0 and int2 interrupt // EICRA=0b00100011; //INT0 CONFIGURED FOR rising EDGE AND INT2 FOR FALLING EDGE EICRA=0b00000011; //INT0 CONFIGURED FOR rising EDGE AND INT2 FOR LOW LEVEL sei(); timer1_init(); LCD_Clear(); while(1) { //DO NOTHING // _delay_ms(1000); } }
C
#include "types.h" #include "stat.h" #include "user.h" #define PGSIZE 4096 #define INT_MAX 2147483647 #define USERTOP 0xA0000 void eprinf(void) { printf(1, "mprotect: failed to return -1\n"); printf(1, "TEST FAILED\n"); } int main(int argc, char *argv[]) { if (mprotect((void *)0, -1) == 0) { eprinf(); exit(); } if (mprotect((void *)0, INT_MAX) == 0) { eprinf(); exit(); } if (mprotect((void *)0, (USERTOP / PGSIZE) + 1) == 0) { eprinf(); exit(); } if (mprotect((void *)1, (USERTOP / PGSIZE) + 1) == 0) { eprinf(); exit(); } if (munprotect((void *)0, -1) == 0) { eprinf(); exit(); } if (munprotect((void *)0, INT_MAX) == 0) { eprinf(); exit(); } if (munprotect((void *)0, (USERTOP / PGSIZE) + 1) == 0) { eprinf(); exit(); } if (munprotect((void *)1, (USERTOP / PGSIZE) + 1) == 0) { eprinf(); exit(); } printf(1, "TEST PASSED\n"); exit(); }
C
#include<stdio.h> int* count012(int size, int arr[], int *counts) { for(int i=0; i< size; i++) { if(arr[i] == 0) counts[0]++; else if(arr[i] == 1) counts[1]++; else if(arr[i] == 2) counts[2]++; } return counts; } void sort(int size, int arr[], int *counts) { int i=0; while(counts[0] != 0) { arr[i] = 0; i++; counts[0]--; } while(counts[1] != 0) { arr[i] = 1; i++; counts[1]--; } while(counts[2] != 0) { arr[i] = 2; i++; counts[2]--; } } int main() { int sizeofarr=0, rotateby=0, counts[3]={0};; printf("Program to sort 0s 1s and 2s of unsorted array without using sorting algorithm!\n"); printf("Enter size of array: "); scanf("%d", &sizeofarr); int inputarr[sizeofarr]; for(int i=0; i< sizeofarr; i++) { scanf("%d", &inputarr[i]); } int *count = count012(sizeofarr, inputarr, counts); sort(sizeofarr, inputarr, count); for(int i=0; i< sizeofarr; i++) { printf("%d", inputarr[i]); } return 0; }
C
//PARAM: --enable ana.int.interval_set --enable ana.int.def_exc #include <goblint.h> int main(){ int top; // 2^33 long long x = 8589934592l; // 2^31 - 1 long long y = 2147483647; if(top) { x = x - 1; } long long z = x/y; if(z == 4){ // Should be reachable __goblint_check(1); } __goblint_check(z == 4); }
C
#include <stdlib.h> #include <stdio.h> #include <dlfcn.h> //#include "func_calc.h" int menu(); int main(int argc, char* argv[]){ void* LIB_so; char* ERROR; int (*add)(int, int); int (*sub)(int, int); int (*mul)(int, int); float (*div)(float, float); //LIB_so = dlopen("/mnt/usbstorage/My_tests/DLfcn/libfunc_calc.so", // RTLD_LAZY); // gcc main.c -ldl -o BIN -Wl,-rpath,. LIB_so = dlopen("libfunc_calc.so", RTLD_LAZY); if(ERROR = dlerror()){ printf("dlopen() error: %s\n", ERROR); exit(1); } add = dlsym(LIB_so, "addition"); if(ERROR = dlerror()){ printf("dlsym() function addition error: %s\n", ERROR); exit(1); } sub = dlsym(LIB_so, "subtraction"); if(ERROR = dlerror()){ printf("dlsym() function subtraction error: %s\n", ERROR); exit(1); } mul = dlsym(LIB_so, "multiplication"); if(ERROR = dlerror()){ printf("dlsym() function multiplication error: %s\n", ERROR); exit(1); } div = dlsym(LIB_so, "division"); if(ERROR = dlerror()){ printf("dlsym() function division error: %s\n", ERROR); exit(1); } int count; int a, b; do{ count = menu(); switch(count){ case 1: printf("Число A: "); scanf("%d", &a); printf("Число B: "); scanf("%d", &b); printf("\n%d + %d = %d\n", a, b, add(a, b)); break; case 2: printf("Число A: "); scanf("%d", &a); printf("Число B: "); scanf("%d", &b); printf("\n%d - %d = %d\n", a, b, sub(a, b)); break; case 3: printf("Число A: "); scanf("%d", &a); printf("Число B: "); scanf("%d", &b); printf("\n%d * %d = %d\n", a, b, mul(a, b)); break; case 4: printf("Число A: "); scanf("%d", &a); printf("Число B: "); scanf("%d", &b); printf("\n%d / %d = %.2f\n", a, b, div((float)a, (float)b)); break; case 5: printf("До свидания!\n"); break; } }while(count != 5); dlclose(LIB_so); //return 0; } int menu(){ int count; printf("\nВыберите действие\n1.Сложение\n2.Вычитание\n3.Умножение\n4.Деление\n5.Выход\n"); scanf("%d", &count); return count; }
C
/* Key to Ex 2.4 R.O. Gray */ #include <stdio.h> #include <math.h> int main() { double t,x,y; int i; t = 0.0; for(i=0;i<=10;i++) { x = 5.0 + 0.12*t*t; y = 0.02*pow(t,3.0); printf("t = %3.1f x = %f y = %f\n",t,x,y); t += 0.5; } return(0); }
C
#include "screen_engine.h" #include "sprites.h" static int F_screen; static uint16_t *Screen; #define SCREEN(x, y) Screen[(x) + SCREEN_X*(y)] void screen_init() { F_screen = open("/dev/fb0", O_RDWR); if(F_screen < 0) { fprintf(stderr, "Cannot open screen\n"); exit(-1); } Screen = mmap(NULL, SCREEN_SIZE*sizeof(uint16_t), PROT_READ | PROT_WRITE, MAP_SHARED, F_screen, 0); if(Screen == MAP_FAILED) { fprintf(stderr, "Cannot map screen error %d\n", errno); exit(-2); } memset(Screen, 0, SCREEN_SIZE*sizeof(uint16_t)); screen_update(0, 0, SCREEN_X, SCREEN_Y); } void screen_update(uint16_t x, uint16_t y, uint16_t width, uint16_t height) { struct fb_copyarea rect; rect.dx = x; rect.dy = y; rect.width = width; rect.height = height; ioctl(F_screen, 0x4680, &rect); } void print_image() { printf("Printing an image to the screen\n"); print_sprite(head, 0, 60); print_sprite(tail, 60, 60); print_sprite(snake, 60, 0); } #define IMG_SIZE 12 #define IMG(x,y) image[x+IMG_SIZE*y] //FIXME void print_sprite(const uint16_t *image, uint16_t off_x, uint16_t off_y) { uint16_t i, j; for(i=0; i<IMG_SIZE; i++) { for(j=0; j<IMG_SIZE; j++) { if(IMG(i, j) != 0xffff) SCREEN(i+off_x, j+off_y) = IMG(i, j); } } //screen_update(off_x, off_y, IMG_SIZE, IMG_SIZE); } //x and y are in screen size #define BOARD(x,y) gameboard[(x/BOARD_RATIO)+(y/BOARD_RATIO)*BOARD_SIDE] void print_gameboard(uint16_t *gameboard){ uint16_t i, j; for(i=0; i< SCREEN_X; i++){ for(j=0; j < SCREEN_Y; j++){ if(i>BOARD_SCREEN) { SCREEN(i, j) = PAD_COLOR; } else { //SCREEN(i, j) = color(BOARD(i,j)); color_tile(gameboard, i, j); } } } screen_update(0, 0, SCREEN_X, SCREEN_Y); } void print_test_board() { uint16_t board[BOARD_SIDE*BOARD_SIDE] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0, 0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,1,0,0,0,0, 0,0,0,0,0,3,0,0,0,1,0,0,0,0,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,5,0, 0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0 }; print_gameboard(board); } uint16_t color(uint16_t tileState){ if(tileState == 0){ return 0xffff; }else if (tileState == 1 || tileState == 2){ return 0x0000; } return PAD_COLOR; } void color_tile(uint16_t *gameboard, uint8_t x, uint8_t y){ uint16_t tileState = BOARD(x,y); if(tileState == 0){ SCREEN(x, y) = BG_COLOR; } else if (tileState == BOARD_SNAKE_BODY){ SCREEN(x, y) = SNK_COLOR; } else if(x % BOARD_RATIO == 0 && y % BOARD_RATIO == 0) { //here print sprites if(tileState == 3) { print_sprite(tail, x, y); } if(tileState == 4) { print_sprite(head, x, y); } if(tileState == BOARD_APPLE) { print_sprite(apple, x, y); } } } void screen_cleanup() { munmap(Screen, SCREEN_SIZE*sizeof(uint16_t)); close(F_screen); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddenkin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/02/24 20:49:04 by ddenkin #+# #+# */ /* Updated: 2018/02/24 20:49:06 by ddenkin ### ########.fr */ /* */ /* ************************************************************************** */ #include "filler.h" int token_fits(t_map *map, t_token *token, t_coord c) { t_coord iter; int covers; int h[2]; covers = 0; iter.x = -1; while (++iter.x < token->h) { iter.y = -1; while (++iter.y < token->w) { if (token->piece[iter.x][iter.y] != '*') continue ; if ((c.x + iter.x < 0 || c.y + iter.y < 0 || c.x + iter.x >= map->h\ || c.y + iter.y > map->w) && token->piece[iter.x][iter.y] == '*') return (-1); h[0] = ft_tolower(map->field[c.x + iter.x][c.y + iter.y]); h[1] = ft_tolower(token->piece[iter.x][iter.y]); if (h[0] == map->pchar && c.y + iter.y < map->w && h[1] == '*') covers++; if (h[0] != map->pchar && h[0] != '.' && h[0] != 0 && h[1] == '*') return (-1); } } return (covers); } double min_token_distance(t_map *map, t_coord tc, t_coord enc) { int i; double min; double tmp; i = 0; min = map->w * map->h; tmp = ft_sqrt(ft_pow(tc.x - enc.x, 2) + ft_pow(tc.y - enc.y, 2)); if (tmp < min) min = tmp; return (min); } double find_distance(t_map *map, t_coord c) { t_coord iter; double wat; double wtemp; iter.x = 0; wat = map->h * map->w; while (iter.x < map->h) { iter.y = 0; while (iter.y < map->w + 1) { if (map->field[iter.x][iter.y] != '.' && map->field[iter.x][iter.y] != 0 && ft_tolower(map->field[iter.x][iter.y]) != map->pchar) { wtemp = min_token_distance(map, c, iter); if (wtemp < wat) wat = wtemp; } iter.y++; } iter.x++; } return (wat); } void calculate_coords(t_map *map, t_token *token) { t_coord iter; t_coord res; double d; double distance; iter.x = -map->h; res.x = 100; res.y = 100; d = (map->h + token->h) * (map->w + token->w); while (++iter.x < map->h) { iter.y = -map->w; while (++iter.y < map->w) { if (token_fits(map, token, iter) == 1) if ((distance = find_distance(map, iter)) < d) { res.x = iter.x; res.y = iter.y; d = distance; } } if (iter.x == map->h - 1) print_res(res); } } void print_map(t_map *map) { int fd; fd = open("out.txt", O_CREAT | O_WRONLY | O_APPEND); for (int i = 0; i < map->h; i++) ft_putendl_fd(map->field[i], fd); close(fd); } int main(void) { t_map *map; t_token *token; char *stuff; map = init_map(); token = init_token(); get_next_line(0, &stuff); if (parse_player(stuff, map) == -1) return (-1); while (1) { if (get_next_line(0, &stuff) == 0 || stuff[0] == '=') break ; parse_sizes(stuff, map); get_next_line(0, &stuff); parse_rows(map->h, map->field, 1); get_next_line(0, &stuff); parse_tsizes(stuff, token); parse_rows(token->h, token->piece, 0); print_map(map); calculate_coords(map, token); } return (0); }
C
#include "HTU21D.h" #include <avr/io.h> void UART_Init() { UBRR1H = 0; UBRR1L = 103; UCSR1B |= (1<<TXEN1); UCSR1C |= (1<<UCSZ10) | (1<<UCSZ11); } void UART_PrintString(char* message) { for (int i = 0; i < strlen(message); i++) { while (!(UCSR1A & (1<<UDRE1))); UDR1 = message[i]; } } void UART_PrintFloat(float number) { unsigned char buff[32]; dtostrf(number, 6, 2, buff); UART_PrintString(buff); } int main(void) { float temperature; float humidity; HTU21D_Init(); UART_Init(); UART_PrintString("INIT OK\r\n"); if (HTU21D_ReadTemperature(&temperature) == 0) { // success UART_PrintString("Temperature: "); UART_PrintFloat(temperature); UART_PrintString("\r\n"); } else { // error UART_PrintString("Error while reading temperature\r\n"); } if (HTU21D_ReadHumidity(&humidity) == 0) { // success UART_PrintString("Humidity: "); UART_PrintFloat(humidity); UART_PrintString("\r\n"); } else { // error UART_PrintString("Error while reading humidity\r\n"); } while (1) {} }
C
#include <fcntl.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include "westfield-dmabuf.h" #include "westfield-util.h" void dmabuf_attributes_finish(struct dmabuf_attributes *attribs) { for (int i = 0; i < attribs->n_planes; ++i) { close(attribs->fd[i]); attribs->fd[i] = -1; } attribs->n_planes = 0; } bool dmabuf_attributes_copy(struct dmabuf_attributes *dst, const struct dmabuf_attributes *src) { memcpy(dst, src, sizeof(struct dmabuf_attributes)); int i; for (i = 0; i < src->n_planes; ++i) { dst->fd[i] = fcntl(src->fd[i], F_DUPFD_CLOEXEC, 0); if (dst->fd[i] < 0) { wfl_log_errno(stderr, "fcntl(F_DUPFD_CLOEXEC) failed"); goto error; } } return true; error: for (int j = 0; j < i; j++) { close(dst->fd[j]); dst->fd[j] = -1; } dst->n_planes = 0; return false; }
C
#include <stdio.h> #define N 32 int main(void) { char nazwapliku[N]; /* bufor na nazw pliku */ FILE *fp; int c; printf("Podaj nazwe pliku (uwaga: mniej ni %d znaki):\n", N); scanf("%s", nazwapliku); if( (fp = fopen(nazwapliku,"r")) == NULL) /* czy dao si otworzy? */ { /* komunikat o bdzie wypiszemy na stderr */ fprintf(stderr,"! Nie moge otworzyc pliku %s\n", nazwapliku); return(-1); /* koczymy program, zwracajc nietypow warto */ } /* kopiujemy znak po znaku, a do napotkania koca pliku */ while( (c = getc(fp)) != EOF ) putc(c, stdout); /* rwnowanie: putchar(c) */ fclose(fp); return(0); }
C
/* ****************************************************************************************************************************** * ****************************************************** 分析输出模块 ********************************************************** * ******************************************************************************************************************************/ #include "header.h" /* * 定义全局变量 * 布尔变量straight, flush, four_of_a_kind, three_of_a_kind分别表示本轮游戏抽取的5张牌所能形成的4种基本结果 * 布尔变量初始化均为false,如果通过函数的分析发现本轮游戏出现了某种结果,则将对应布尔量的值设置为true * straight : 顺子(5张牌的等级连续) * flush : 同花(5张牌的花色相同) * four_of_a_kind : 四张(4张牌的等级相同) * three_of_a_kind : 三张(3张牌的等级相同) * 整型变量num_of_pairs初始化为0,可能取值为1或2,代表了本轮游戏抽取的5张牌所能形成的另外两种基本结果 * num_of_pairs = 2: 两对(2对牌的等级相同) * num_of_pairs = 1: 一对(1对牌的等级相同) * * 注意: * 除了上述所列的6种基本情况外,还有两种由基本情况组合出的结果 * straight flush : 同花顺(5张牌的等级连续,花色相同) * full horse : 葫芦(5张牌中有3张牌为同一个等级,另外2张牌为另一种等级) * 如果5张牌可以形成上述8种结果中的多种结果,则程序将自动选择最好的一种情况输出 * 8中结果的好坏排序:同花顺 > 四张 > 葫芦 > 同花 > 顺子 > 三张 > 两对 > 一对 */ bool straight; bool flush; bool four_of_a_kind; bool three_of_a_kind; int num_of_pairs; void analyze_hand(void) { straight = false; flush = false; four_of_a_kind = false; three_of_a_kind = false; num_of_pairs = 0; /* * 首先检查是否出现同花 * 出现同花意味着某种花色连续出现了5次 * 对应到程序中就是数组num_in_suit中有且仅有一个元素的值为5,而其余3个元素值均为0 */ for (int i = 0; i < NUM_OF_SUITS; i++) { if (num_in_suit[i] == CARDS_IN_HAND) { flush = true; } } /* * 接着检查是否出现顺子 * 出现顺子意味着从某一个等级开始,包括它在内和往后的四个等级出现且仅出现一次 * 对应到程序中就是数组num_in_rank中从某一个位置开始,该位置及其后四个位置上的元素值均为1,而其余8个元素值均为0 */ int j = 0; /* 定义变量表示数组num_in_rank的下标 */ int count = 0; /* 定义变量充当计数器:每找到相邻且值为1的元素就自增1 */ while (num_in_rank[j] == 0) /* 首先找到数组num_in_rank中第一个值为1的元素的位置,从该位置进行顺子判断 */ { j++; } for (; j < CARDS_IN_HAND && num_in_rank[j] == 1; j++) /* 从第一个位置起,每找到相邻且值为1的元素就将计数器count自增1 */ { count++; } if (count == CARDS_IN_HAND) /* 循环完成后通过计数器的值是否等于5来判断这一手牌是否构成顺子 */ { straight = true; } /* * 接着检查是否出现三张、四张、两对、一对这四种情况 * 这四种情况都是检查相同等级的出现次数,对应到程序中就是检查数组num_in_rank中元素的值 */ for (int i = 0; i < NUM_OF_RANKS; i++) { if (num_in_rank[i] == 4) { four_of_a_kind = true; } if (num_in_rank[i] == 3) { three_of_a_kind = true; } if (num_in_rank[i] == 2) { num_of_pairs++; } } } void print_result(void) { if (straight && flush) { printf("同花顺!"); } else if (four_of_a_kind) { printf("四张!"); } else if (three_of_a_kind && num_of_pairs == 1) { printf("葫芦!"); } else if (flush) { printf("同花!"); } else if (straight) { printf("顺子!"); } else if (three_of_a_kind) { printf("三张!"); } else if (num_of_pairs == 2) { printf("两对!"); } else if (num_of_pairs == 1) { printf("一对!"); } else { printf("其它!"); } printf("\n\n"); }
C
// program to generate all permutation of the given string #include <stdio.h> #include <string.h> #include <stdlib.h> //declare permutation and swap functions void permutation(char *,int,int); void swap(char *,char *); int main() { char *s; // dynamically creating string length s=(char*)malloc(sizeof(char)*1000); // getting string fgets(s,1000,stdin); // changing size to the length of string+1 to store null at end s=realloc(s,strlen(s)+1); //calling permutation permutation(s,0,strlen(s)-1); return 0; } void permutation(char *str,int s,int e) { //declare variables static int count; int i; //base condition if(s==e) { count++; //Printing the string permutation's printf("%d(%s)\n",count,str); } else { for(i=s;i<=e;i++) { //swapping variables value swap(str+s,str+i); //calling permutation function permutation(str,s+1,e); //now swap the variables value and make it before one swap(str+s,str+i); } } } //swap function void swap(char *a,char *b) { char temp; //putting value in temp temp=*a; // putting value in a pointer *a=*b; //now putting value of temp in b pointer *b=temp; //swapping done } /* Example: Input: abc Output: 1(abc) 2(acb) 3(bac) 4(bca) 5(cba) 6(cab) Time Complexity: O(n*n!) */
C
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<malloc.h> #include<string.h> #include<pthread.h> typedef struct blocky{ int size; char msg[60]; }; pthread_cond_t cond_var; pthread_mutex_t mutexlock; void* send(void*args){ struct blocky b; FILE* fp = fopen("D:\\nik1.bin", "rb+"); while (1){ printf("\nboy: "); fflush(stdin); gets(b.msg); //scanf("%[^\n]*c", b.msg); b.size = strlen(b.msg); fwrite(&b, sizeof(struct blocky), 1, fp); fflush(fp); } fclose(fp); return 0; } void* recieve(void*args){ struct blocky b; //pthread_mutex_lock(&mutexlock); FILE* fs = fopen("D:\\nik.bin", "rb+"); char ch; while (1){ if ((ch = fgetc(fs)) == EOF){ fseek(fs, -1, SEEK_CUR); continue; } else{ fseek(fs, -1, SEEK_CUR); } fread(&b, sizeof(struct blocky), 1, fs); if (b.size < 0) continue; printf("girl: %s\n\n", b.msg); b.size = ((-1) * (b.size)); fseek(fs, -64, SEEK_CUR); fwrite(&b, sizeof(struct blocky), 1, fs); } fclose(fs); //pthread_mutex_unlock(&mutexlock); return 0; } int main(){ //FILE* fs = fopen("D:\\nik.bin", "rb+"); //struct blocky b; pthread_t t0, t4; void*agrs; pthread_mutex_init(&mutexlock, NULL); pthread_cond_init(&cond_var, NULL); pthread_create(&t0, NULL, send, NULL); pthread_create(&t4, NULL, recieve, NULL); //pthread_join(t0, NULL); pthread_join(t0, NULL); pthread_join(t4, NULL); getchar(); return 0; }
C
#include <lib/validar.h> #include <Listas/Generica/Lista.h> #include <Listas/Generica/Nodo.h> #include <stdlib.h> Lista * nuevaListaDoble (int tamanno) { int i = 0; Lista *lista = NULL; valTam (tamanno); lista = crearNodos (tamanno, 2, 0); Nodo *start = NULL; Nodo *next = NULL; for (i = tamanno - 1; i > 0; i--) { start = obtenerNodo (lista, i, 0); next = obtenerNodo (lista, i - 1, 0); enlazarNodo (start, next, 1); } return lista; } Lista * destruirListaDoble (Lista * lista) { return destruirNodos (lista, 0); } void mostrarListaDoble (Lista * lista) { conextion_characther = "⇄"; mostrarNodos (lista, 0); } void insertarListaDoble (Lista * lista, int posicion, int valor) { int tamanno = 0; Nodo *nodo = NULL; Lista *ultima = NULL; valNeg (posicion); tamanno = tamannoNodos (lista, 0); ultima = (Lista *) malloc (sizeof (Lista)); valMem (ultima); ultima->nodo = ultimoNodo (lista, 0); nodo = nuevoNodo (valor, 2); annadirNodo (lista, nodo, posicion, 0); annadirNodo (ultima, nodo, tamanno - posicion, 1); free (ultima); } void eliminarListaDoble (Lista * lista, int posicion) { int tamanno = 0; Lista *ultima = NULL; valNeg (posicion); tamanno = tamannoNodos (lista, 0); ultima = (Lista *) malloc (sizeof (Lista)); valMem (ultima); ultima->nodo = ultimoNodo (lista, 0); eliminarNodo (lista, posicion, 0); eliminarNodo (ultima, tamanno - posicion, 1); } int buscarListaDoble (Lista * lista, int valor) { return buscarNodos (lista, valor, 0); }
C
/* ** EPITECH PROJECT, 2020 ** fridge ** File description: ** init fridge */ #include "../include/fridge.h" int check_pizza(fridge *cool) { int tomato = 5; int dough = 1; int onion = 3; int olive = 8; int peppers = 8; int ham = 4; int cheese = 3; if (cool->food[0]->stock >= tomato && cool->food[1]->stock >= dough \ && cool->food[2]->stock >= onion && cool->food[4]->stock >= olive \ && cool->food[5]->stock >= peppers && cool->food[6]->stock >= ham \ && cool->food[7]->stock >= cheese) return 1; print_not_enough_pizza(cool); return 0; } void cook_pizza(fridge *cool) { int tomato = 5; int dough = 1; int onion = 3; int olive = 8; int peppers = 8; int ham = 4; int cheese = 3; cool->food[0]->stock -= tomato; cool->food[1]->stock -= dough; cool->food[2]->stock -= onion; cool->food[4]->stock -= olive; cool->food[5]->stock -= peppers; cool->food[6]->stock -= ham; cool->food[7]->stock -= cheese; }
C
#include <stdio.h> #include <string.h> /* Union it's a special datatype that's capable to store diferents data type in the same memory segment. You can define a Union with many member, but only one member can contain a value at any given time. Ex: data.integer = 10; data.floating = 3.14; strcpy(data.text, "waka"); You will get waka when you print the string but incorrect values when you put integer or float */ union Data{ int integer; float floating; char text[20]; }; int main (){ union Data data; printf("Uso incorreto da Union : \n"); data.integer = 10; data.floating = 3.14; strcpy(data.text, "waka"); printf("Data '10' != %d\n", data.integer); printf("Data '3.14' != %f\n", data.floating); printf("Data 'waka' == %s\n", data.text); /**************************************************/ printf("\nUso correto da Union : \n"); data.integer = 10; printf("Data '10' == %d\n", data.integer); data.floating = 3.14; printf("Data '3.14' == %f\n", data.floating); strcpy(data.text, "waka"); printf("Data 'waka' == %s\n", data.text); return 0; }
C
#include <stdio.h> int main(int argc, char *argv[]) { int i = 0; for (i = 0; i < argc; i++) { printf("arg %d: %s\n",i,argv[i]); } // let's make our own array of strings char*states[] = {"California","Oregon","Washington","Texas"}; int num_states= 4; for(i= 0;i<num_states;i++) { printf("state %d: %s\n",i,states[i]); } return 0; }
C
#include <assert.h> /* Test of reduction on both parallel and loop directives (workers and vectors in gang-partitioned mode, int type with XOR). */ int main (int argc, char *argv[]) { int i, j, arr[32768], res = 0, hres = 0; for (i = 0; i < 32768; i++) arr[i] = i; #pragma acc parallel num_gangs(32) num_workers(32) vector_length(32) \ reduction(^:res) { #pragma acc loop gang /* { dg-warning "nested loop in reduction needs reduction clause for 'res'" "TODO" } */ for (j = 0; j < 32; j++) { #pragma acc loop worker vector reduction(^:res) for (i = 0; i < 1024; i++) res ^= 3 * arr[j * 1024 + i]; #pragma acc loop worker vector reduction(^:res) for (i = 0; i < 1024; i++) res ^= arr[j * 1024 + (1023 - i)]; } } for (j = 0; j < 32; j++) for (i = 0; i < 1024; i++) { hres ^= 3 * arr[j * 1024 + i]; hres ^= arr[j * 1024 + (1023 - i)]; } assert (res == hres); return 0; }