language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <string.h> #include <time.h> #include <unistd.h> pthread_mutex_t lock= PTHREAD_MUTEX_INITIALIZER; FILE *fp; void *Thread1(); void *Thread2(); struct timespec startTime,stopTime; float secsElapsed1; float secsElapsed2; clock_t t1,t2; int main() { clock_t startTime = clock(); pthread_t tid1, tid2; int ret1, ret2; float a; if (pthread_mutex_init(&lock, NULL) != 0) { printf("\n mutex init has failed\n"); return 1; } if(ret1!=0 && ret2!=0) { printf("Cant create thread\n"); } ret1 = pthread_create(&tid1, NULL, &Thread1, NULL); ret2 = pthread_create(&tid2, NULL, &Thread2, NULL); pthread_join( tid1, NULL); pthread_join( tid2, NULL); printf("tid 1 returns: %d\n",ret1); printf("tid 2 returns: %d\n\n",ret2); a= (float)(t2-t1)/CLOCKS_PER_SEC; printf("switching time between two threads %f",a); clock_t stopTime = clock(); float secsElapsed = (float)(stopTime - startTime)/CLOCKS_PER_SEC; printf("\n\nTime taken by program is %lf\n\n",secsElapsed); exit(0); } void *Thread1(void* arg) { clock_t startTime = clock(); printf("starttime=%ld\n",startTime); pthread_mutex_lock(&lock); fp=fopen("temp.txt","a+"); char character; printf("The alphabets from A TO Z are\n "); for(character='A';character<='Z';character++) { fprintf(fp," %c", character); } fclose(fp); pthread_mutex_unlock(&lock); clock_t stopTime = clock(); t1 = stopTime=clock(); printf("stop time=%ld",t1); float secsElapsed1 = (float)(stopTime - startTime)/CLOCKS_PER_SEC; printf("\nTime taken by first thread is %lf\n\n",secsElapsed1); } void *Thread2(void* arg) { sleep(5); clock_t startTime = clock(); t2=startTime=clock(); printf("starttime=%ld",t2); //pthread_mutex_lock(&lock); fp=fopen("temp.txt","a+"); char ch; printf("\nThe alphabets from a TO z are\n "); for(ch='a';ch<='z';ch++) { fprintf(fp," %c ", ch); } fclose(fp); //pthread_mutex_unlock(&lock); clock_t stopTime = clock(); printf("stop time=%ld",stopTime); float secsElapsed2 = (float)(stopTime - startTime)/CLOCKS_PER_SEC; printf("\nTime taken by 2nd thread is %lf\n\n",secsElapsed2); }
C
include <stdio.h> void swapByPointer(int *A, int *B); int main(){ int a,b,*n,*m; scanf("%d",&a); scanf("%d",&b); n = &a; m=&b; swapByPointer(n,m); return 0; } void swapByPointer(int *A, int *B){ int t; t=*A; *A=*B; *B=t; printf("%d %d",*A,*B); }
C
#include <stdio.h> #include <stdlib.h> #define MAXLINE 2 /* maksymalny rozmiar wiersza */ #include "getline.h" int main() { char line[MAXLINE]; while (my_getline(line,MAXLINE) > 0) { printf("[%s]\n",line); } }
C
/* * i2c.c * * Created: 20-Jan-20 3:55:19 PM * Author: LENOVO */ /*- INCLUDES ----------------------------------------------*/ #include "i2c.h" #include "../../micro_config.h" #include "../../micro_registers.h" #include "../../common/macros.h" #include <math.h> /*- LOCAL MACROS ------------------------------------------*/ #define CLEAR_STATUS (0x07) #define STATUS_READER (0xF8) #define IDLE_MODE (0U) #define START_DONE (1U) #define ADDRESS_WRITE_DONE (2U) #define ADDRESS_READ_DONE (3U) #define SEND_BYTE (4U) #define STOP_BIT (5U) #define WAITING_DATA (6U) #define DATA_RECEIVED (7U) #define TWI_WAIT_RESPONSE (20U) #define TWI_ADDRESS_WRITTING (21U) /*- LOCAL Dataypes ----------------------------------------*/ /*- LOCAL FUNCTIONS PROTOTYPES ----------------------------*/ /*- GLOBAL STATIC VARIABLES -------------------------------*/ static uint8_t gu8_TWI_state_machine = IDLE_MODE;/* Used to indicate where twi stopped at. */ static uint8_t gu8_last_byte_received;/* Saved Last Byte received. */ static uint8_t gu8_address_byte_received; uint8_t au8_status; /*- GLOBAL EXTERN VARIABLES -------------------------------*/ /*- LOCAL FUNCTIONS IMPLEMENTATION ------------------------*/ /*- APIs IMPLEMENTATION -----------------------------------*/ #if MASTER_MODE == ENABLE I2C_STATUS_t I2C_InitMaster(const StrI2cConfig_t* aStr_i2c_config) { /* TWBR => Master. --DONE. */ TWBR = (uint8_t)((F_CPU/(aStr_i2c_config->speed_mode)) - 16U)/(2 * pow(4, aStr_i2c_config->prescaler)); TWSR |= aStr_i2c_config->prescaler; /** * TWCR * TWIE: TWI Interrupt Enable --DONE. * TWEN: TWI Enable Bit --DONE. * TWSTO: TWI STOP Condition Bit => in case of Master.--DONE. * TWSTA: TWI START Condition Bit => in case of Master.--DONE. * TWEA: TWI Enable Acknowledge Bit => Enable ACK.--DONE. * TWINT: TWI Interrupt Flag. * TWSR * Bits [7:3] – TWS: TWI Status. * Bits [1:0] – TWPS: TWI Prescaler Bits. --DONE. * Prescaler should be masked when checking for status of I2C. * TWI (Slave) Address Register – TWAR. --DONE. * Bits 7..1 – TWA: TWI (Slave) Address Register. */ #if INTERRUPT_MODE == ENABLE SET_BIT(TWCR, TWIE);/* Enable Interrupt. */ sei(); #endif //SET_BIT(TWCR, TWEA);/* Enable ACK. */ /* Set Address. */ TWAR = SLAVE_ADDRESS << 1; SET_BIT(TWCR, TWEN);/* Enable TWI Module. */ return TWI_SUCCESS; } /** * @brief Used to start a transimission. * @return I2C_STATUS_t */ void I2C_StartBit() { /** * TWCR: * TWSTO: TWI STOP Condition Bit => in case of Master. * TWSTA: must be cleared by software when the START condition has been transmitted. */ /* TWSTA must be cleared by software when the START condition has been transmitted. */ TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN) | (1 << TWIE); } /** * @brief Used to stop a transimission. * @return I2C_STATUS_t */ void I2C_StopBit() { TWCR= (1<<TWINT)|(1<<TWEN)|(1<<TWSTO) | (1 << TWIE); } #endif #if SLAVE_MODE == ENABLE I2C_STATUS_t I2C_InitSlave() { /** * TWCR * TWIE: TWI Interrupt Enable * TWEN: TWI Enable Bit * TWSTO: TWI STOP Condition Bit => in case of Master. * TWSTA: TWI START Condition Bit => in case of Master. * TWEA: TWI Enable Acknowledge Bit => Enable ACK. * TWINT: TWI Interrupt Flag. * TWSR * Bits [7:3] – TWS: TWI Status. * Bits [1:0] – TWPS: TWI Prescaler Bits. * Prescaler should be masked when checking for status of I2C. * TWI (Slave) Address Register – TWAR. * Bits 7..1 – TWA: TWI (Slave) Address Register. */ #if INTERRUPT_MODE == ENABLE SET_BIT(TWCR, TWIE);/* Enable Interrupt. */ sei(); #endif SET_BIT(TWCR, TWEA);/* Enable ACK. */ /* Set Address. */ TWAR = SLAVE_ADDRESS << 1; SET_BIT(TWCR, TWEN);/* Enable TWI Module. */ return TWI_SUCCESS; } #endif I2C_STATUS_t I2C_SendByte(uint8_t au8_slave_address ,uint8_t au8_byte) { /** * TWI Data Register – TWDR. */ gu8_address_byte_received = au8_slave_address; gu8_last_byte_received = au8_byte; TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN) | (1 << TWIE); return TWI_SUCCESS; } I2C_STATUS_t I2C_ReceiveByte(uint8_t* au8_byte) { /** * TWI Data Register – TWDR. */ switch (gu8_TWI_state_machine) { case DATA_RECEIVED: if ( NULL != au8_byte ) { *au8_byte = gu8_last_byte_received; } else { /* NOP. */ } gu8_TWI_state_machine = IDLE_MODE; break; default: break; } return TWI_SUCCESS; } ISR( TWI_vect ) { /* Read Status. */ au8_status = ((STATUS_READER & (TWSR))); #if MASTER_MODE == ENABLE if( gu8_TWI_state_machine == IDLE_MODE ) { TWDR = gu8_address_byte_received; TWCR = (1<<TWINT) | (1<<TWEN)| (1 << TWIE); gu8_TWI_state_machine = ADDRESS_WRITE_DONE; } else if ( gu8_TWI_state_machine == ADDRESS_WRITE_DONE ) { /* SLA + W. */ TWDR = gu8_last_byte_received; //Clear Flag. TWCR = (1<<TWINT) | (1<<TWEN)| (1 << TWIE); gu8_TWI_state_machine = SEND_BYTE; } else if ( gu8_TWI_state_machine == SEND_BYTE ) { /* Send ADDRESS With Write. */ I2C_StopBit(); gu8_TWI_state_machine = IDLE_MODE; } else { gu8_TWI_state_machine = IDLE_MODE; } #endif #if SLAVE_MODE == ENABLE if( au8_status == TWI_SLA_W ) { gu8_TWI_state_machine = WAITING_DATA; } else if ( au8_status == TWI_DATA_RECEIVED ) { gu8_TWI_state_machine = DATA_RECEIVED; } else { gu8_TWI_state_machine = IDLE_MODE; } #endif }
C
#include<stdio.h> #define TRUE 1 #define FALSE 0 typedef int BOOL; BOOL CheckBit(int iNo) { int iMask=0X00000010; int iMask1=0X00020000; int iResult=0; int iResult1=0; iResult=iMask&iNo; iResult1=iMask1&iNo; if((iResult==iMask)&&(iResult1==iMask1)) { return TRUE; } else { return FALSE; } } int main() { int iValue=0; BOOL bRet=0; printf("Enter the Number\n"); scanf("%d",&iValue); bRet=CheckBit(iValue); if(bRet==TRUE) { printf("The fifth and eighteenth bits are ON\n"); } else { printf("OFF\n"); } return 0; } /* Decimal Binary Hexadecimal 0 0000 0 1 0001 1 2 0010 2 3 0011 3 4 0100 4 5 0101 5 6 0110 6 7 0111 7 8 1000 8 9 1001 9 10 1010 a 11 1011 b 12 1100 c 13 1101 d 14 1110 e 15 1111 f Binary 0000 0000 0000 0000 0000 0000 0000 1000 Hexadecimal 0 0 0 2 0 0 0 8 HexadecimalRepresentation 0X00000008-->MASK 86 binary iNo 86 0101 0110 & 0X00000008-->MASK 0000 1000 0000000000 */
C
#include <stdint.h> #include <string.h> #include <stdio.h> #define min(X, Y) (((X) < (Y)) ? (X) : (Y)) #define SIGIL_START "{{" #define SIGIL_END "}}" struct buffer { char *data; unsigned int size; }; struct buffer lookup(struct buffer stream) { struct buffer result; static char *url = "https://www.groovestomp.com"; static char *label = "My Website"; if (strncmp(stream.data, "url", min(stream.size, strlen("url"))) == 0) { result.data = url; result.size = strlen(url); } else if (strncmp(stream.data, "label", min(stream.size, strlen("label"))) == 0) { result.data = label; result.size = strlen(label); } else { result.data = NULL; result.size = 0; } return result; } struct buffer trim(struct buffer stream) { char *head = stream.data + 2; char *tail = stream.data + stream.size - 2; for(; *head == ' '; ++head); for(; *tail == ' '; --tail); struct buffer result; result.data = head; result.size = tail - head; return result; } uint8_t memory[10000] = { 0 }; char *front_buffer = (char *)memory; char *back_buffer = (char *)(memory + 5000); char *swap; int main(int argc, char *argv[]) { /* To Do: Output usage information. */ if (argc != 2) { return 1; } char *replace_start, *replace_end, *stream; stream = argv[1]; while (1) { struct buffer to_replace, trimmed, replaced; replace_start = strstr(stream, SIGIL_START); replace_end = strstr(stream, SIGIL_END); if (replace_start == NULL || replace_end == NULL) break; replace_end += 1; to_replace.data = replace_start; to_replace.size = replace_end - replace_start; trimmed = trim(to_replace); replaced = lookup(trimmed); strncpy(front_buffer, back_buffer, strlen(back_buffer)); strncpy(front_buffer + strlen(front_buffer), stream, replace_start - stream); strncpy(front_buffer + strlen(front_buffer), replaced.data, replaced.size); swap = back_buffer; back_buffer = front_buffer; front_buffer = swap; stream = replace_end + 1; } strncpy(front_buffer, back_buffer, strlen(back_buffer)); strncpy(front_buffer + strlen(front_buffer), stream, strlen(stream)); printf("%s\n", front_buffer); return(0); }
C
#include "lista_spesa.h" /** * Funzione che provvede a scrivere su file(il nome e' specificato dal parametro in ingresso) il nome dell'alimento che passiamo alla funzione. * * Dopo aver eseguito i vari controlli sulla modalit di apertura del file della spesa(esso pu riferirsi a quello personale o a quello globale), * viene scritto su di esso il nome dell'alimento. Qualora l'inserimento non vada a termine viene notificato un messaggio di errore e si chiede * di riscrivere l'alimento * * @pre Che il nome del file sia significativo e che la stringa che rappresenta il nome dell'alimento non sia vuota * @post Deve essere scritto su file l'alimento passato */ int aggiorna_lista_spesa(char nome_alimento[LUNG_NOME_ALIMENTO],char nome_file[LUNG_NOME_FILE_SPESA]) { FILE *fp; int esito_scrittura; int flag_presenza = 0; char alimento_letto[LUNG_NOME_ALIMENTO + 1]; // tentativo di apertura del file frigo in lettura e scrittura if ((fp = fopen(nome_file, "r+")) == NULL) { // se il file non viene aperto, si decide di crearne uno nuovo if ((fp = fopen(nome_file, "w+")) == NULL) return 0; }else{ //vengono estratti gli alimenti gi presenti nel file e per evitare caricamento di alimenti omonimi. Inoltre viene troncato lo \n //per far si che strcmp lavori senza intoppi. while (fgets(alimento_letto, LUNG_NOME_ALIMENTO, fp) != NULL) { if(alimento_letto[strlen(alimento_letto) - 1] != '\n'){ pulisci_riga_flusso(fp); } sscanf(alimento_letto, "%20[a-zA-Z]", alimento_letto); if (strcmp(alimento_letto, nome_alimento) == 0) { flag_presenza = 1; break; } } } if (flag_presenza == 1) { return 0; } esito_scrittura = fprintf(fp, "%s\n", nome_alimento); if (esito_scrittura < 0) { printf("Errore nella scrittura di %s. Si prega di inserire manualmente l'alimento\n",nome_alimento); do { esito_scrittura = fprintf(fp, "%s\n", input_nome_alimento()); } while (esito_scrittura == 0); } fclose(fp); return 0; } /** Funzione che si occupa di effettuare l'autenticazione dell'utente per poter poi poter mostrare la lista della spesa personale * * @pre Nessuna particolare pre condizione * @post nessuna particolare post condizione */ int visualizzazione_personale(){ utente u; //autenticazione(con controllo su esito) dell'utente if (autenticazione(&u) == -1){ printf("Operazione di utenticazione fallita\n"); return -1; } //generazione del nome del file che ospiter la spesa personale char nome_file[LUNG_NOME_FILE_SPESA] = PREFIX_FILE_SPESA; strcat(nome_file, u.nickname); strcat(nome_file, SUFFIX_FILE_SPESA); visualizza_lista_spesa(nome_file); return 1; } /** * Funzione che provvede a visualizzare gli alimenti che devono essere comprati dal file della lista personale o di quella globale. * * Qualora non sia possibile aprire il file in lettura(ricordiamo che il nome del file della spesa viene generato esternamente alla funzione), * viene restituito -1. Nel caso in cui sia possibile aprire il file da cui desideriamo estrarre gli alimenti da acquistare viene effettuata * la stampa fino al termine del file. * * @pre Il nome del file deve essere significativo(il file deve esistere e deve possedere almeno un alimento) * @post Deve essere stampato almeno un alimento */ int visualizza_lista_spesa(char nome_file[LUNG_NOME_FILE_SPESA]) { FILE *stream = NULL; char nome_alimento[LUNG_NOME_ALIMENTO + 1]; int num_alimenti = 0; printf("Lista della spesa: %s\n", nome_file); if ((stream = fopen(nome_file, "r")) == NULL) { puts("Non possibile aprire il file."); return -1; } else { while (fgets(nome_alimento, LUNG_NOME_ALIMENTO, stream) != NULL) { if(nome_alimento[strlen(nome_alimento) - 1] != '\n'){ pulisci_riga_flusso(stream); } num_alimenti++; sscanf(nome_alimento, "%20[a-zA-Z]", nome_alimento); printf("%s\n", nome_alimento); } if(num_alimenti == 0){ puts("Non sono presenti alimenti nella lista della spesa.\n"); } } fclose(stream); return 1; } /** * Funzione che si occupa di eliminare il nome del file specificato e di restituire in caso di successo il valore -1 * * @pre Il nome del file deve essere significativo(il file deve esistere) * @post In caso il file esista esso deve essere eliminato correttamente */ int elimina_file_spesa(char nome_file[LUNG_NOME_FILE_SPESA]) { FILE *fp; if ((fp = fopen(nome_file, "r")) == NULL) { return -1; } fclose(fp); int ret = remove(nome_file);//rimuove il file dal nome specificato if (ret == 0) { return 1; } else { return -1; } return 0; } /** * Funzione che si occupa di leggere dal database gli alimenti che possono essere inseriti nella lista della spesa. Per far ci viene * effettuata la lettura del database alimenti e viene fatto un controllo sulla soglia tramite la funzione controllo soglia. Se la condizione * e' vera(vedi funione controllo_soglia per avere un'idea sui valori restituiti) allora l'alimento viene passato alla funzione aggiorna_lista_spesa * Al termine viene restituito 1 * * @pre nessuna particolare pre condizione * @post nessuna particolare post condizione */ int generatore_spesa_globale() { int num_alimenti_database; num_alimenti_database = conta_alimenti_database(); if(num_alimenti_database == 0){ return 0; } elimina_file_spesa(LISTA_SPESA_GLOBALE); alimento_database alimenti_database[num_alimenti_database]; if (leggi_database_alimenti(alimenti_database) == 0 ) { return 0; } else { for(int i = 0; i < num_alimenti_database; i++) { //se la soglia e' maggiore di 0 e se la quantit disponibile e' minore di tale soglia allora occorre memorizzare l'alimento if (controllo_soglia(alimenti_database[i].soglia_spesa, alimenti_database[i].nome)) aggiorna_lista_spesa(alimenti_database[i].nome, LISTA_SPESA_GLOBALE); } return 1; } return 0; } /** * Funzione che si occupa di creare il file che conterr gli alimenti che un utente specifico deve comprare. * * Per far ci la prima operazione da compiere e' l'autenticazione dell'utente. Qualora essa vada a buon fine viene sfruttato il nickname * dell'utente per creare un file della spesa personalizzato. La seconda operazione necessaria e' quella di estrarre dal menu settimanale * gli alimenti e le ricette che l'utente consuma giornalmente. Per ogni pasto viene fatto un confronto sulla tipologia dell'alimento. * Se siamo in presenza di una ricetta viene popolato un array di struct(di tipo ingrediente) che avr tutti gli ingredienti che compongono la * ricetta. Se il numero di ingredienti di una data ricetta e' -1 vuol dire che la ricetta non e' presente nel database e viene notificato un messaggio * all'utente. Se viene restituito un valore diverso vuol dire che gli ingredienti sono candidati ad essere memorizzati nella lista della spesa, * ma occorre effettuare un controllo con la soglia e la quantit disponibile. Sela quantit disponibile e' inferiore alla soglia l'ingrediente viene * memorizzato. Stessa ragionamento per gli alimenti singoli presenti nel men settimanale. * * @pre Nessuna pre condizione * @post Venga generato il file della spesa dell'utente */ int generatore_spesa_personale() { utente u; giorno menu; float soglia_spesa; //autenticazione(con controllo su esito) dell'utente if (autenticazione(&u) == -1){ printf("Operazione di utenticazione fallita\n"); return -1; } //generazione del nome del file che ospiter la spesa personale char nome_file[LUNG_NOME_FILE_SPESA] = PREFIX_FILE_SPESA; strcat(nome_file, u.nickname); strcat(nome_file, SUFFIX_FILE_SPESA); elimina_file_spesa(nome_file);//eliminazione del file "vecchio" se presente for (int i_giorno = 1; i_giorno <= 7; i_giorno++) { estrai_giorno(&menu, u.nickname, i_giorno); //viene estratto il menu giornaliero for (int i_pasto = 0; i_pasto < NUM_PASTI; i_pasto++) { for (int i_alimento = 0; i_alimento < NUM_CIBI; i_alimento++) { if (menu.pasti[i_pasto].cibi[i_alimento].flag == FLAG_RICETTA) {//se l'alimento che si sta analizzando e' una ricetta //vengono estratti gli ingredienti int num_ingredienti; ingrediente ingredienti[MAX_INGREDIENTI]; num_ingredienti = estrazione_ingredienti(menu.pasti[i_pasto].cibi[i_alimento].nome_cibo, ingredienti); if (num_ingredienti == -1) {//controllo che ci aiuta a capire se la ricetta non esiste nel database printf( "Non e' stato possibile estrarre gli alimenti che compongono la ricetta: %s\n", menu.pasti[i_pasto].cibi[i_alimento].nome_cibo); printf( "Si cosiglia di caricare la ricetta nel database delle ricette per facilitare la creazione della spesa\n"); } else { //se la ricetta in questione esiste, gli ingredienti estratti verranno analizzati in base alla loro soglia e aggiunti // in caso alla lista for (int i_ingrediente = 0; i_ingrediente < num_ingredienti; i_ingrediente++){ if(controllo_soglia(soglia_alimento(ingredienti[i_ingrediente].nome),ingredienti[i_ingrediente].nome) == 1){ aggiorna_lista_spesa(ingredienti[i_ingrediente].nome, nome_file); } } } } else if(menu.pasti[i_pasto].cibi[i_alimento].flag == FLAG_ALIMENTO){ //altrimenti se ci che si sta analizzando e' un alimento si effettua un controllo diretto sulla soglia e sulla quantit //disponibile soglia_spesa = soglia_alimento(menu.pasti[i_pasto].cibi[i_alimento].nome_cibo); if(soglia_alimento(menu.pasti[i_pasto].cibi[i_alimento].nome_cibo) == -1){ printf("Non e' stato possibile estrarre l'alimento perche' sconosciuto al database: %s\n", menu.pasti[i_pasto].cibi[i_alimento].nome_cibo); }else if(controllo_soglia(soglia_spesa, menu.pasti[i_pasto].cibi[i_alimento].nome_cibo) == 1){ aggiorna_lista_spesa(menu.pasti[i_pasto].cibi[i_alimento].nome_cibo, nome_file); } } } } } return 1; } /** * Funzione che si occupa di confrontare la soglia in ingresso con la quantit di quell'alimento. Qualora la quantit disponibile nel frigo * sia inferiore della soglia prestabilita viene restituito 1 e 0 in caso contrario. Nel caso in cui invece la soglia di un determinato alimento * sia settata a 0 viene restituito, allo stesso modo, 0. Qualora i controlli non vadano a buon fine viene restituito -1 * * @pre nessuna particolare pre condizione * @post Che venga effettuato correttamente il confronto tra quantit e soglia dell'alimento */ int controllo_soglia(float soglia_spesa, char nome_alimento[LUNG_NOME_ALIMENTO]) { int lung_nome_alimento = strlen(nome_alimento); if(lung_nome_alimento < 1 || lung_nome_alimento > LUNG_NOME_ALIMENTO){ return -1; } if(soglia_spesa < 0){ return -1; } if (soglia_spesa > 0) { if (quantita_alimento(nome_alimento) < soglia_spesa) { return 1; } else { return 0; } } else { return 0; } }
C
#ifndef _ERR_H_DEF #define _ERR_H_DEF // For handling the format attribute #ifndef __GNUC__ # define __attribute__(x) // Nothing #endif /** * Gets the error number from a function that failed. * * A value of 0 means no error, otherwise its an error. * * \note There are currently no specific codes, just zero and * non-zero. */ extern int m2_errno(); /** * Gets a string with a nice message about the error. * * The pointer returned is a pointer to the actual string, * so it is not suggested that you edit it or rely on it since * it can change underneath you. * * If m2_errno() is 0, then this function returns NULL */ extern char * m2_strerror(); extern char * m2_strerror_cpy(char * dest); /** * Prints the message from m2_strerror to stderr */ extern void m2_perror(); extern void m2_set_errstr(char * message, ...) __attribute__((format(printf, 1, 2))); extern void m2_set_errno(int n); #define check(A,M,...) if (!(A)) { m2_set_errno(-1); m2_set_errstr((M), ##__VA_ARGS__); assert(!(A)); goto error; } else { m2_set_errno(0); } #define check_mem(A) check(A, "Out of memory") #endif//_ERR_H_DEF
C
#include<stdio.h> int main() { int a,b,sum,d,e,u,digit,j,w=0,l[10]={0}; digit=1; scanf("%d%d",&a,&b); sum=a+b; if(sum<0) { sum=-sum; printf("-"); } d=sum; while(d>0) { d=d/10; digit=digit+1; } digit=digit-1; if(sum==0) digit=digit+1; for(j=0;j<digit;j++) { e=sum%10; l[digit-j]=e; sum=sum/10; } u=digit%3; for(j=1;j<=u;j++) printf("%d",l[j]); if(digit==3) { for(j=1;j<=3;j++) printf("%d",l[j]); //3 digits } while(digit>3&&u<digit) { if(u!=0) printf(","); for(j=1;j<=3;j++) printf("%d",l[u+j]); u=u+3; } return 0; }
C
#include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int readln(int fildes,char *buf,int nbyte); // 1. /* int main(){ char c; while (read(0,&c,1)) write(1,&c,1); return 0; } */ /* // 2 int main(int argc, char *argv[]){ int file; int i; if (argc<2){ printf("Nome do ficheiro em falta\n"); return 0; } file = open(argv[1],O_CREAT|O_WRONLY,0666); for (i=0;i<10*1024;i++) write(file,"a",1); return 0; } */ /* //3. int main(int argc, char *argv[]){ if (argc <2){ printf("Não foi referido o nº de bytes\n"); return 0; } int nbytes = atoi(argv[1]); char *buff = malloc(nbytes); while (read(0,buff,nbytes)) write(1,buff,nbytes); return 0; } */ // 4 ---- // 5. int main(int argc, char *argv[]){ if (argc<3){ printf("Não especificou o filde/nbytes \n Primeiro especifique o filde e depois os nbytes"); return 0; } int filde = atoi(argv[1]); int nbytes = atoi(argv[2]); char *buff = malloc(nbytes); readln(filde,buff,nbytes); write(1,buff,nbytes); return 0; } int readln(int fildes,char *buf,int nbyte){ int i; char c; int n = 1; for (i=0;n>0 && i<nbyte && c!= '\n';i++){ n=read(fildes,&c,1); if (c!='\n'){ buf[i++] = c; } } if (i<nbyte) buf[i]=0; else{ i--; buf[i] = 0; } // erro no read if (n<0) return n; // caso não tenha lido nada if ((n==0) && (i==0)) return (-1); // caso de sucesso return i; }
C
/** * \mainpage * The Sorter is an application to sort data files using various algorithms * * * @file main.c * @brief Main source file for the Sorter program * @date 2009-10-28 File creation * @author Cláudio Esperança <2070030@student.estg.ipleiria.pt>, Diogo Serra <2081008@student.estg.ipleiria.pt> */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <assert.h> #include <ctype.h> #include <dirent.h> #include <time.h> #include <limits.h> #include <sys/time.h> #include <sys/types.h> #include <sys/sem.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/shm.h> #include <arpa/inet.h> #include "3rd/debug.h" #include "3rd/sorter_options.h" #include "3rd/semaforos.h" #include "includes/definitions.h" #include "includes/aux.h" #include "includes/commonlib.h" #include "includes/sorterlib.h" #include "includes/sorters.h" #include "main.h" /** * @brief Flag for the no sigint signal */ char* _sigint_time=NULL; /** * @brief The main program function * @param argc integer with the number of command line options * @param argv *char[] with the command line options * @return integer 0 on a successfully exit, another integer value otherwise * * @author Cláudio Esperança <2070030@student.estg.ipleiria.pt>, Diogo Serra <2081008@student.estg.ipleiria.pt> */ int main(int argc, char *argv[]){ /* Variable declarations */ struct gengetopt_args_info args_info; // structure for the command line parameters processing FILE *log_file = NULL; // log file reference int result = 0; /* Main code */ system("clear"); // Initializes the command line parser and check for the application parameters if (cmdline_parser(argc,argv,&args_info) != 0){ DEBUG("\nInvalid parameters"); result = M_INVALID_PARAMETERS; } // Check the number of files on the directory if(result == 0 && count_dir_items(args_info.input_arg)<=0){ DEBUG("\nNo files found to sort"); result = M_NUMBER_OF_FILES; } // If no error occurred if(result == 0){ // Remove the duplicated algorithms given by the program arguments remove_duplicated_algorithms(&args_info); // Enable daemon mode if the flag was sent daemonize(args_info); // Enable log mode if the parameter was sent log_file=lognize(args_info); // Register the signal handler register_signal_handlers(); // print the header message print_log_header(args_info, argc, argv); // Let's process the directory if((result = processDir(args_info, argc, argv))!=TRUE){ printf("\nThe processing failed with the error %d\n",result); result = M_PROCESSING_FAILED; } // If we are logging to a file, let's restore the default behavior if (args_info.log_given && log_file!=NULL){ close_log_file(log_file); } } // Free the command line parser memory cmdline_parser_free(&args_info); return result; } /** * @brief Print the output log to a file or to the stdout (based on the application parameters) * @param args_info struct gengetopt_args_info with the parameters given to the application * @param argc integer with main argument count * @param argv with the arguments * * @author Cláudio Esperança <2070030@student.estg.ipleiria.pt>, Diogo Serra <2081008@student.estg.ipleiria.pt> */ void print_log_header(struct gengetopt_args_info args_info, int argc, char *argv[]){ int a=0; char* aux=NULL; printf("\n# sorter\n# options: "); // command-line options for(a=1;a<argc;a++){ printf("%s ",argv[a]); } //Print the date aux = get_current_time("@%Y-%m-%d %Hh%M", strlen("@2009-10-09 15h30")); printf("\n# start date: %s\n",aux); free(aux); aux=NULL; // For the host name if((aux=malloc((MAXCHARS+1)*sizeof(char)))==NULL){ ERROR(M_FAILED_MEMORY_ALLOCATION,"\nMemory allocation failed for host name"); } if(gethostname(aux, MAXCHARS)!=0){ ERROR(M_GETHOSTNAME_FAILED,"\nCan't get the host name"); } printf("# machine: %s, user: %s\n",aux,getlogin()); free(aux); aux=NULL; // PID printf("# PID: %d\n",getpid()); // Files to process printf("# Files to process: %d\n",count_dir_items(args_info.input_arg)); // Algorithms to execute printf("# Algorithms to execute: %d\n",args_info.serial_algorithm_given); printf("#-----------------------\n"); } /** * @brief Process the input directory items * @param args_info the gengetopt_args_info object * @param argc integer with main argument count * @param argv with the arguments * @return integer TRUE if the directory exists, FALSE otherwise * * @author Cláudio Esperança <2070030@student.estg.ipleiria.pt>, Diogo Serra <2081008@student.estg.ipleiria.pt> */ int processDir(struct gengetopt_args_info args_info, int argc, char *argv[]){ unsigned int a=0; // auxiliary integer for the algorithms parameters loop int files_counter=0, files_total=0, algorithm_counter=0; // integers to store some counters int result; // auxiliary result integer char *input_filename=NULL, *output_filename; // to store the input and output filenames char *model_name=NULL; // to store the computer model name char md5sum_char[MD5SUMCHARS+1]; // string to store the md5 sum struct dirent *dirItem=NULL; // to reference a directory item struct stat fileDetails; // to reference the file details struct sockaddr_in udp_time_server_addr, udp_results_server_addr; // to store server addresses DIR *dir = NULL; // to reference the directory descriptor FILE_LINES_T *flines = NULL, *sorted_flines=NULL; // to store the file lines ALGORITHM_STAT_T* stat=NULL; // to store the statistical data of the sort operation ALGORITHM_FUNC algorithm_function=NULL; // to store the algorithm function to use on the sort operation CONTROLLER_STAT_T controller_stat; // to store the statistical controller control REMOTE_UDP_REQUEST_T rur_time, rur_results; // to store the UDP request data for the UDP time server // Begin of the function code (void) argc; // silence the unused warning // Verify if we really have a input and output parameters if (args_info.input_given && args_info.output_given && args_info.serial_algorithm_given>0){ // Initializes and, if requested, creates a socket UDP for the time server rur_time.sock_fd = -1; rur_time.server_addr = &udp_time_server_addr; if(args_info.time_server_addr_given && args_info.time_server_port_given){ if((result = initialize_udp_connection(&rur_time, args_info.time_server_addr_arg, args_info.time_server_port_arg))!=0){ return result; } } // Initializes and, if requested, creates a socket UDP for the results server rur_results.sock_fd = -1; rur_results.server_addr = &udp_results_server_addr; if(args_info.stats_server_given && args_info.stats_port_given){ if((result = initialize_udp_connection(&rur_results, args_info.stats_server_arg, args_info.stats_port_arg))!=0){ return result; } if((model_name = get_model_name())==NULL){ MY_DEBUG("\nError while retrieving the computer model name info\n"); return M_RETRIEVE_MODEL_NAME_ERROR; } } // Initializes the controller result = initializes_controller_stat(&controller_stat, argv[0], count_dir_items(args_info.input_arg), args_info.serial_algorithm_given); // Test for errors switch(result){ case M_SEMSET_FAILED_FOR_DATA: shmdt(controller_stat.stats); case M_SHMAT_FAILED_FOR_DATA_STATS: sem_delete(controller_stat.sem_data_id); case M_SEMCREATE_FAILED_FOR_DATA: shmctl(controller_stat.shm_data_id, IPC_RMID, 0); case M_SHMGET_FAILED_FOR_DATA: case M_FTOK_FAILED_FOR_DATA: shmdt(controller_stat.control_data); case M_SHMAT_FAILED_FOR_CONTROL: case M_SEMSET_FAILED_FOR_CONTROL: sem_delete(controller_stat.sem_control_id); case M_SEMCREATE_FAILED_FOR_CONTROL: shmctl(controller_stat.shm_control_id, IPC_RMID, 0); case M_SHMGET_FAILED_FOR_CONTROL_ID: case M_FTOK_FAILED_FOR_CONTROL_KEY: return result; } // Verify if we can open the output directory if(dir_exists(args_info.output_arg)!=TRUE){ ERROR(M_OPEN_DIR_FAILED,"\nError while open the output directory %s", args_info.output_arg); } closedir(dir); // Verify if we can open the input directory if((dir = opendir(args_info.input_arg))==NULL){ ERROR(M_OPEN_DIR_FAILED,"\nError while open the input directory %s", args_info.input_arg); } // Set selected algorithms variable for(a=0; a<args_info.serial_algorithm_given; a++){ if(a!=0){ sprintf(controller_stat.control_data->selected_algorithms, "%s%s", controller_stat.control_data->selected_algorithms, ", "); } sprintf(controller_stat.control_data->selected_algorithms, "%s%s", controller_stat.control_data->selected_algorithms, args_info.serial_algorithm_orig[a]); } // Give the green light for the shared memory access by another process release_controller_stat(&controller_stat); // Allocate memory for statistical data stat = allocate_memory_for_stat(NULL,NULL); // Count the number of files to process files_total = count_dir_items(args_info.input_arg); // Reads all the items on the directory while(_sigint_time == NULL && ((dirItem = readdir(dir))!=NULL)){ output_filename = path_filename(args_info.output_arg, dirItem->d_name); input_filename = path_filename(args_info.input_arg, dirItem->d_name); // Reads the file attributes if(lstat(input_filename, &fileDetails)==0){ //if item is a regular file if((fileDetails.st_mode & S_IFREG)!=0){ MY_DEBUG("\nLoading the file %s (%lld bytes)... \n", input_filename, (long long) fileDetails.st_size); // Read the file to memory if((flines = read_file(input_filename, MAXCHARS))!=NULL){ MY_DEBUG("Loading OK!\n"); files_counter++; algorithm_counter=0; // Loop between the specified algorithms for(a=0; a<args_info.serial_algorithm_given; a++){ // Count current algorithm algorithm_counter++; MY_DEBUG("Sorting the %d lines", flines->num_lines); // Set the algorithm function and resets the statistical data if(args_info.serial_algorithm_arg[a]==serial_algorithm_arg_bubble){ MY_DEBUG(" using the %s algorithm... \n", "bubble sort"); // Sets the sort function for the bubble sort algorithm algorithm_function = bubble_sort; // Resets the statistical data for the current sort process reset_stat(stat, dirItem->d_name, "bubble"); }else if(args_info.serial_algorithm_arg[a]==serial_algorithm_arg_merge){ MY_DEBUG(" using the %s algorithm... \n", "merge sort"); // Sets the sort function for the merge sort algorithm algorithm_function = merge_sort; // Resets the statistical data for the current sort process reset_stat(stat, dirItem->d_name, "merge"); }else if(args_info.serial_algorithm_arg[a]==serial_algorithm_arg_quick){ MY_DEBUG(" using the %s algorithm... \n", "quick sort"); // Sets the sort function for the quick sort algorithm algorithm_function = quick_sort; // Resets the statistical data for the current sort process reset_stat(stat, dirItem->d_name, "quick"); }else if(args_info.serial_algorithm_arg[a]==serial_algorithm_arg_shell){ MY_DEBUG(" using the %s algorithm... \n", "shell sort"); // Sets the sort function for the shell sort algorithm algorithm_function = shell_sort; // Resets the statistical data for the current sort process reset_stat(stat, dirItem->d_name, "shell"); }else{ ERROR(M_UNKNOWN_ALGORITHM, "Unknown algorithm\n"); } // Sort the data if((sorted_flines = sort_lines(clone_of_lines(flines), algorithm_function, stat, rur_time))!=NULL){ // Check if the output file exists if(file_exists(output_filename, "r")!=TRUE){ // if not, write the file MY_DEBUG("Sort OK!\nSaving the result to %s... \n", output_filename); if(save_file(output_filename, sorted_flines)!=TRUE){ ERROR(M_FILE_OUTPUT_FAILED, "\nError creating the output file %s", output_filename); } MY_DEBUG("Save OK!\n"); }else{ // if exists, skip the output file creation MY_DEBUG("File %s exists! Skipping file creation.\n", output_filename); } // Calculates the md5 sum of the output_filename and store it on the md5sum_char string md5sum(md5sum_char,output_filename); // Output the results or log it to the log file printf("[%d/%d]%s:[%d/%d]%s:%.0f\n", files_counter, files_total, stat->filename, algorithm_counter, args_info.serial_algorithm_given, stat->algorithm, stat->time); // Append this new data to the shared memory append_stat(&controller_stat, stat, _sigint_time!=NULL); // Send result to the UDP results server send_udp_result(rur_results, stat, NICKNAME, model_name, md5sum_char); // free the used memory for the lines clone free_memory_of_clone_of_lines(sorted_flines); }else{ ERROR(M_SORT_FAILED, "\nError sorting the file %s", input_filename); } } // free the used memory for the file lines free_memory_of_lines(flines); } } }else{ ERROR(M_FILE_ATTRIBUTES_READ_FAILED, "\nError reading the file attributes from %s", input_filename); } // free the others resources free(input_filename); input_filename=NULL; free(output_filename); output_filename=NULL; } //end while closedir(dir); // Free the statistical used memory free_memory_of_stat(stat); // If we have a _sigint_time, the operation was interrupted by the user if(_sigint_time!=NULL){ printf("\nOperation interrupted by user %s\n",_sigint_time); free(_sigint_time); _sigint_time=NULL; } // Flag for any listener to exit lock_controller_stat(&controller_stat); controller_stat.control_data->to_exit=TRUE; release_controller_stat(&controller_stat); release_new_data(&controller_stat); // If we have a time socket open, close it if(rur_time.sock_fd>-1){ close(rur_time.sock_fd); } // If we have a results socket open, close it if(rur_results.sock_fd>-1){ close(rur_results.sock_fd); } // Free the allocated memory for the model_name if(model_name!=NULL){ free(model_name); } } // Wait for the other showStats wait_for_exit_unlock(&controller_stat); // Remove the controller, shared memory and semaphores result = remove_controller_stat(&controller_stat); // Test for errors switch(result){ case M_SHMDT_FAILED: ERROR(result, "\nError while detaching shared control memory"); case M_SHMCTL_FAILED: ERROR(result, "\nError while removing the shared memory segment"); case M_SEMDELETE_FAILED: ERROR(result, "\nError while deleting the semaphore"); } return TRUE; } /** * @brief Handle the signals sent to the application * @param signal integer with the signal to be handled * * @author Cláudio Esperança <2070030@student.estg.ipleiria.pt>, Diogo Serra <2081008@student.estg.ipleiria.pt> */ void handle_signal(int signal) { int aux; /* Copy the value of the global variable errno */ aux = errno; if(signal==SIGINT){ _sigint_time = get_current_time("@%Y-%m-%d %Hh%M", strlen("@2009-10-08 16h02")); MY_DEBUG("Signal SIGINT received!\n"); } /* Restore the value for the global variable errno */ errno = aux; } /** * @brief Register the signal handler function * * @author Cláudio Esperança <2070030@student.estg.ipleiria.pt>, Diogo Serra <2081008@student.estg.ipleiria.pt> */ void register_signal_handlers(void){ struct sigaction action; // structure for the signal handling // Signal handling function action.sa_handler = handle_signal; // Mask without signals - won't block the signals sigemptyset(&action.sa_mask); action.sa_flags = 0; // Recover the blocked calls action.sa_flags |= SA_RESTART; // Specify the signals that will be handled if(sigaction(SIGINT, &action, NULL) < 0){ ERROR(M_SIGACTION_SIGINT_FAILED, "Action for signal SIGINT failed!\n"); } } /** * @brief Enable the daemon mode if such setting was request through command line parameter * @param args_info struct gengetopt_args_info with the parameters given to the application * * @author Cláudio Esperança <2070030@student.estg.ipleiria.pt>, Diogo Serra <2081008@student.estg.ipleiria.pt> */ void daemonize(struct gengetopt_args_info args_info){ pid_t pid; // pid for the daemon // If the flag daemon was sent if (args_info.daemon_given){ // And we have a output log filename parameter if(args_info.log_given){ // Let's fork the main program switch(pid=fork()){ case -1: ERROR(M_FORK_FAILED, "\nFork for the daemon mode failed!\n"); break; case 0: //Child proceeds break; default: //Parent exit // Free the command line parser memory cmdline_parser_free(&args_info); exit(0); } }else{ // fail safe that should happen; this should be verified by the gengetopt code printf("\nDaemon mode requested but no log file given! Exiting...\n"); exit(M_DAEMON_BUT_NO_LOG_FILE); } } } /** * @brief Enable the log mode if such setting was request through command line parameter * @param args_info struct gengetopt_args_info with the parameters given to the application * @return FILE* descriptor if a file was opened, NULL otherwise * * @author Cláudio Esperança <2070030@student.estg.ipleiria.pt>, Diogo Serra <2081008@student.estg.ipleiria.pt> */ FILE* lognize(struct gengetopt_args_info args_info){ FILE *log_file = NULL; // If we have a log parameter, let's redirect the stdout directly to the file if (args_info.log_given){ if((log_file=open_log_file(args_info.log_arg,"a"))==NULL){ printf("\nUnable to log to the %s file...", args_info.log_arg); } } return log_file; } /** * @brief Removes the duplicated algorithms in the serial_algorithm_arg array from the gengetopt_args_info structure * @param args_info struct gengetopt_args_info with the algorithms to normalize * * @author Cláudio Esperança <2070030@student.estg.ipleiria.pt>, Diogo Serra <2081008@student.estg.ipleiria.pt> */ void remove_duplicated_algorithms(struct gengetopt_args_info *args_info){ enum enum_serial_algorithm serial_algorithm_arg[args_info->serial_algorithm_given]; char* serial_algorithm_orig[args_info->serial_algorithm_given]; unsigned int a, b, total=0; int exits=FALSE; total=0; // Loop trough the given algorithms for(a=0; a<args_info->serial_algorithm_given; a++){ exits=FALSE; // Verify if the algorithm already exists in the unique algorithms array, and if it exists, free it's memory for(b=0; b<total; b++){ if(args_info->serial_algorithm_arg[a]==serial_algorithm_arg[b]){ exits=TRUE; // Free the associated memory free(args_info->serial_algorithm_orig[a]); args_info->serial_algorithm_orig[a]=NULL; } } // If not, add the current algorithm to the unique algorithms array if(exits!=TRUE){ serial_algorithm_arg[total] = args_info->serial_algorithm_arg[a]; serial_algorithm_orig[total] = args_info->serial_algorithm_orig[a]; total++; } } // Copy from the unique algorithms array to the gengetopt_args_info structure for(b=0; b<args_info->serial_algorithm_given; b++){ if(b<total){ args_info->serial_algorithm_arg[b]=serial_algorithm_arg[b]; args_info->serial_algorithm_orig[b]=serial_algorithm_orig[b]; } } args_info->serial_algorithm_given=total; }
C
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> #define MaxSize 1000 int main( int argc, const char *argv[]){ int Stack[MaxSize]; int Top = -1; int M, N, K; int Tmp; int Current;/* 当前栈顶元素 */ bool flag; /* 判断该序列是否合法*/ scanf( "%d %d %d\n", &M, &N, &K ); for( int i = 0 ; i < K ; i++ ){/* 判断 K 次 */ Top = -1; /* 每开始一轮新的判断时,重置堆栈和标记位 */ Current = 1; flag = true; for( int j = 1; j <= N ; j++ ){ scanf( "%d", &Tmp ); /* 读取序列 */ while( Current <= Tmp ) /* 当栈顶元素小于等于读取的 Tm p值时,持续压栈 */ Stack[++Top] = Current++; /* 压栈完成判断是否堆栈溢出 */ /* 弹出当前栈顶元素,判断是否和读取的 Tmp 相等 */ /* 二者有任一条件不满足,视为非法序列 */ if( Top == M || Stack[Top--] != Tmp ) flag = false; } getchar(); if( flag ) printf( "YES\n"); else printf( "NO\n"); } }
C
/* 习题10-4 递归求简单交错幂级数的部分和 (15 分) 本题要求实现一个函数,计算下列简单交错幂级数的部分和: f(x,n)=x-x^2+x^3-x^4+...+(-1)^(n-1)*x^n x 00 函数接口定义: double fn( double x, int n ); 其中题目保证传入的n是正整数,并且输入输出都在双精度范围内。 函数fn应返回上述级数的部分和。建议尝试用递归实现。 裁判测试程序样例: 输入样例: 0.5 12 输出样例: 0.33 */ #include <stdio.h> double fn(double x, int n); int main() { double x; int n; scanf("%lf %d", &x, &n); for (int i = 0; i <= n; i++) { printf("%d %.2f\n", i, fn(x, i)); // printf("%.2f\n", fn(x,i)); } return 0; } /* 你的代码将被嵌在这里 */ double fn(double x, int n) { if (n == 0) { return 1; } if (n == 1) { return 1 - x; } return x * (1 - fn(x, n - 1)); }
C
////ƳвԴļеСдĸȫתΪдĿļctype.h,ıģʽ ////argv[1]Ŀļargv[2]Դļ //#include<stdio.h> //#include<stdlib.h>//exit() //#include<ctype.h>//toupper() //#include<string.h>//strcmp() //#define BUFSIZE 1024 // //void file_copy(FILE * dest,FILE * source); // //int main(int argc,char * argv[]) //{ // FILE * fa,* fs; // //жǷȷ // if(argc < 2) // { // fprintf(stderr,"Usage:%s filename.\n",argv[0]); // exit(EXIT_FAILURE); // } // //ĿļԹд // if((fa = fopen(argv[1],"w")) == NULL) // { // fprintf(stderr,"Can not open file %s.\n",argv[1]); // exit(EXIT_FAILURE); // } // //ΪĿļ // if(setvbuf(fa,NULL,_IOFBF,BUFSIZE) != 0) // { // fprintf(stderr,"Fail to create output buff.\n"); // } // //Դļ // if((fs = fopen(argv[2],"r")) == NULL) // { // fprintf(stderr,"Can not open file %s.\n",argv[2]); // exit(EXIT_FAILURE); // } // else//Դļ򿪳ɹ // { // if(strcmp(argv[1],argv[2]) == 0)//ȽǷΪͬһļ // { // fprintf(stderr,"Can't copy it to itself.\n"); // exit(EXIT_FAILURE); // } // //ΪԴļ // if(setvbuf(fs,NULL,_IOFBF,BUFSIZE) != 0) // { // fprintf(stderr,"Fail to create input buff.\n"); // } // file_copy(fa,fs); // if(ferror(fa) != 0) // { // fprintf(stderr,"Error in writing file.\n"); // } // if(ferror(fs) != 0) // { // fprintf(stderr,"Error in reading file.\n"); // } // } // //رļ // fclose(fa); // fclose(fs); // return 0; //} ////ļ //void file_copy(FILE * dest,FILE * source) //{ // char ch; // // while((ch = getc(source)) != EOF && ch != '\0') // putc(toupper(ch),dest); //}
C
int range (int sensorval) { if (sensorval > 250) { return 0; } else if (sensorval > 150) { return 1; } else if (sensorval > 70) { return 2; } else if (sensorval > 45) { return 3; } else if (sensorval > 30) { return 4; } else { return 5; } } int angle (int left, int center, int right) { int rrange = range (right); int lrange = range (left); int crange = range (center); if (rrange >= 3 && lrange >= 3 && crange >= 3) { } if (lrange < 2 && rrange < 2 && crange < 2) { if (lrange > 0 && rrange == 0 && crange == 0) { return -45; } else if (lrange == 0 && rrange > 0 && crange == 0) { return 30; } else if (lrange == 0 && rrange == 0 && crange > 0) { return 0; } else if (lrange == 0 && rrange > 0 && crange > 0) { return 30; } else if (lrange > 0 && rrange == 0 && crange > 0) { return -30; } } }
C
// Standard Khalang Prompt System #include <stdio.h> #include <stdlib.h> #include <stdbool.h> static char input[2048]; int main (int argc, char** argv) { puts("Khalang"); puts("#blessup"); while (true) { fputs("lion:>>> ", stdout); fgets(input, 2048, stdin); printf("#blessed %s\n", input); } return 0; }
C
// Waldomiro Barbosa Romão 2018005655 #include <stdio.h> void troca(int *x, int *y) { int aux = *x; *x = *y; *y = aux; } void bubbleSort(int vetor[], int tam) { int aux; for (int i = 0; i < tam-1; i++) for (int j = 0; j < tam-i-1; j++) if (vetor[j] > vetor[j+1]) troca(&vetor[j], &vetor[j+1]); } void selectionSort(int vetor[], int tam) { int menor, aux; for (int i = 0; i < tam-1; i++) { menor = i; for (int j = i+1; j < tam; j++) if (vetor[j] < vetor[menor]) menor = j; if(menor != i) troca(&vetor[menor], &vetor[i]); } } void insertionSort(int vetor[], int tam) { int chave; for (int i = 1; i < tam; i++) { chave = vetor[i]; int j = i - 1; while (j >= 0 && vetor[j] > chave) { arr[j + 1] = vetor[j]; j = j - 1; } vetor[j + 1] = chave; } }
C
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <unistd.h> char *Read_file(char *filename) // Reads the content of a file { FILE *f = fopen(filename, "rt"); assert(f); fseek(f, 0, SEEK_END); long length = ftell(f); fseek(f, 0, SEEK_SET); char *buffer = (char *) malloc(length + 1); buffer[length] = '\0'; fread(buffer, 1, length, f); fclose(f); return buffer; } double Read_string(char* s, int in, int out) // Returns the double in position [in][out] of the string { size_t i = 0; size_t save; size_t scale = 0; while (out != 1) { if (s[i] == ")"[0]) { out--; } i++; } i++; while (in > 0) { if (s[i] == "|"[0]) { in--; } i++; } save = i; while (s[save] != "|"[0]) { scale += 1; save++; } char c[scale + 1]; save = 0; while (s[i] != "|"[0]) { c[save] = s[i]; i++; save++; } return atof(c); }
C
#include <stdio.h> #include <assert.h> int fits_bits(int x, int n) { unsigned val = (unsigned) x; unsigned w = sizeof(int) << 3; unsigned mask = ~0; return val <= (mask >> (w - n)); } int main(int argc, char* argv[]) { assert(!fits_bits(8, 3)); assert(fits_bits(8, 4)); assert(fits_bits(8, 5)); assert(fits_bits(0xFF, 8)); return 0; }
C
#include <stdlib.h> #include "holberton.h" /** * create_array - creates an array of chars, and initializes it with a specific * char *@size: size of the array *@c: the specific character * Return: pointer to a string */ char *create_array(unsigned int size, char c) { unsigned int i; char *p; if (size == 0) { return (0); } else { p = malloc(sizeof(char) * size); if (p == '\0') { return (0); } else { for (i = 0; i < size; i++) { p[i] = c; } return (p); } } }
C
#include <stdio.h> int main(){ // int num=0, divi =2,espar,primos=0,cantLeidos=-1,esc=-1; // // while( num != esc){ // divi = 2; // printf("introduzca numero para ver si es primo: "); // scanf("%d",&num); // // espar= num%divi; // while( espar!=0 && divi<num ){ // divi = divi+1; // } // // // if (divi == num ){ // printf(" es primo\n"); // primos++; // }else{ // printf("el numero no es primo\n"); // // } // cantLeidos++; // // } // printf("\nSe leyeron %d de los cuales %d son primos\n\n",cantLeidos,primos); //una empresa quiere procesar las ventas de sus vendedores, los vendedores son N //para cada vendedor se ingresa un numero determinado de veces una venta y la zona donde se realizo //el fin de la ventas de cada vendedor se aplica con -1 y no se lee zona //imprimir: de cada vendedor la cant total de ventas //una vez procesado todo el grupo indicar cuantos no vendierton nada //indicar total de ventas realizados en zona a por cualquier vendedor //emitr la maxima suma de ventas realizadas int cantVend=0,ventMax=0, cantVentas = -1,numVent=0,sumaVentas=0,ESC =-1,noVent=0,sumaZona=0,aux=0; char zona; printf("ingresar numero de vendedores: "); scanf("%d",&cantVend); for(int i=1;i<cantVend+1;i++){ printf("\nVendor numero %d \n",i); printf("Numero de ventas: "); scanf("%d",&cantVentas); for(int j=1;j<cantVentas+1;j++){ printf("venta numero %d: ",j); scanf("%d",&sumaVentas); printf("zona: "); fflush(stdin); scanf("%c",&zona); fflush(stdin); if(zona == 'a'){ sumaZona = sumaVentas+sumaZona; } aux = aux +sumaVentas; if(sumaVentas>ventMax){ ventMax = sumaVentas; } // } if(sumaVentas == 0){ noVent++; } printf("la suma de las ventas %d \n",aux); aux=0; sumaVentas=0; } printf("no vendieron nada: %d\n",noVent); printf("el total de las ventas en la zona a es: %d",sumaZona); printf("\nLa maxima venta es %d \n",ventMax); getchar(); return 0; }
C
#include "stdio.h" #include "stdlib.h" #include "dynamic_stack.h" #include "locale.h" /* [Estrutura de Dados - Exerccio] Ndio Dib - 201918579 Engenharia de Software */ /* Escreva uma funo que receba um vetor com vrios elementos e um ponteiro para uma pilha. Preencha a pilha passada como parmetro com os elementos do vetor. */ void PushArray(Stack *stack, char *array, int length) { for (int i = 0; i < length - 1; i++) Push(stack, array[i], "exemplo"); } int main() { setlocale(LC_ALL, "Portuguese"); Stack stack; char values[10] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' }; PushArray(&stack, values, sizeof(values) / sizeof(values[0])); }
C
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "asset_current_location.h" asset_current_location_t *asset_current_location_create( double latitude, char *location, double longitude, double speedMilesPerHour, long timeMs ) { asset_current_location_t *asset_current_location = malloc(sizeof(asset_current_location_t)); asset_current_location->latitude = latitude; asset_current_location->location = location; asset_current_location->longitude = longitude; asset_current_location->speedMilesPerHour = speedMilesPerHour; asset_current_location->timeMs = timeMs; return asset_current_location; } void asset_current_location_free(asset_current_location_t *asset_current_location) { listEntry_t *listEntry; free(asset_current_location->location); free(asset_current_location); } cJSON *asset_current_location_convertToJSON(asset_current_location_t *asset_current_location) { cJSON *item = cJSON_CreateObject(); // asset_current_location->latitude if(cJSON_AddNumberToObject(item, "latitude", asset_current_location->latitude) == NULL) { goto fail; //Numeric } // asset_current_location->location if(cJSON_AddStringToObject(item, "location", asset_current_location->location) == NULL) { goto fail; //String } // asset_current_location->longitude if(cJSON_AddNumberToObject(item, "longitude", asset_current_location->longitude) == NULL) { goto fail; //Numeric } // asset_current_location->speedMilesPerHour if(cJSON_AddNumberToObject(item, "speedMilesPerHour", asset_current_location->speedMilesPerHour) == NULL) { goto fail; //Numeric } // asset_current_location->timeMs if(cJSON_AddNumberToObject(item, "timeMs", asset_current_location->timeMs) == NULL) { goto fail; //Numeric } return item; fail: cJSON_Delete(item); return NULL; } asset_current_location_t *asset_current_location_parseFromJSON(char *jsonString){ asset_current_location_t *asset_current_location = NULL; cJSON *asset_current_locationJSON = cJSON_Parse(jsonString); if(asset_current_locationJSON == NULL){ const char *error_ptr = cJSON_GetErrorPtr(); if (error_ptr != NULL) { fprintf(stderr, "Error Before: %s\n", error_ptr); goto end; } } // asset_current_location->latitude cJSON *latitude = cJSON_GetObjectItemCaseSensitive(asset_current_locationJSON, "latitude"); if(!cJSON_IsNumber(latitude)) { goto end; //Numeric } // asset_current_location->location cJSON *location = cJSON_GetObjectItemCaseSensitive(asset_current_locationJSON, "location"); if(!cJSON_IsString(location) || (location->valuestring == NULL)){ goto end; //String } // asset_current_location->longitude cJSON *longitude = cJSON_GetObjectItemCaseSensitive(asset_current_locationJSON, "longitude"); if(!cJSON_IsNumber(longitude)) { goto end; //Numeric } // asset_current_location->speedMilesPerHour cJSON *speedMilesPerHour = cJSON_GetObjectItemCaseSensitive(asset_current_locationJSON, "speedMilesPerHour"); if(!cJSON_IsNumber(speedMilesPerHour)) { goto end; //Numeric } // asset_current_location->timeMs cJSON *timeMs = cJSON_GetObjectItemCaseSensitive(asset_current_locationJSON, "timeMs"); if(!cJSON_IsNumber(timeMs)) { goto end; //Numeric } asset_current_location = asset_current_location_create ( latitude->valuedouble, strdup(location->valuestring), longitude->valuedouble, speedMilesPerHour->valuedouble, timeMs->valuedouble ); cJSON_Delete(asset_current_locationJSON); return asset_current_location; end: cJSON_Delete(asset_current_locationJSON); return NULL; }
C
#include <stdio.h> float taxi_fare(int weekday, int start_time, int duration, int distance) { int fare = 3400; // keep as integer. We will divide by 1000 when returning double speed = (double)distance/duration; int curr_day = weekday; // When boarding if (start_time < 6*60) { // before 6am fare += 1700; // 50% of 3.4 } else if (start_time >= 18*60) { // after 6pm fare += 850; // 25% of 3.4 } else if (curr_day < 6 && start_time < 10*60) { // before 10am on weekday fare += 850; // 25% of 3.4 } printf("Time: %d %02d:%02d:00.00\t%dm\t+%dm\t%6.3f\n", curr_day, start_time/60, start_time%60, 0, 1001, fare/1000.0); double curr_time; int covered = 1001; while (covered <= distance) { // Compute the time at distance covered. // curr_time += stage/speed; // This is bad because it causes floating point inaccuracy curr_time = start_time + covered/speed; // instead compute from starting time // wrap around the time and day curr_day = weekday + (int)(curr_time / (24*60)); while (curr_day > 7) { curr_day -= 7; } curr_time = (int)(curr_time) % (24*60) + curr_time - (int)curr_time; // go back to 0 after midnight // check the surcharge int inc = 220; // 0.22 for each segment if (curr_time < 6*60) { // before 6am inc += 110; // 50% of 0.22 } else if (curr_time >= 18*60) { // after 6pm inc += 55; // 25% of 0.22 } else if (curr_day < 6 && curr_time < 9*60+30) { // before 9:30am on weekday inc += 55; // 25% of 0.22 } fare += inc; // track fare stage for display int stage; if (covered > 10000) { stage = 350; } else { stage = 400; } printf("Time: %d %02d:%02d:%05.2f\t%dm\t+%dm\t%6.3f\t+%.3f\n", curr_day, (int)curr_time/60, (int)curr_time%60, (curr_time-(int)curr_time)*60, covered, stage, fare/1000.0, inc/1000.0); // advance by stage distance covered += stage; } printf("Time: %d %02d:%02d:%05.2f\t%dm\t+%dm\t%6.3f\n", curr_day, (int)curr_time/60, (int)curr_time%60, (curr_time-(int)curr_time)*60, distance, 0, fare/1000.0); // Return the fare in dollars return fare/1000.0; } int main(void) { // You may change the inputs to the function for testing double fare = taxi_fare(1, 5*60 + 50, 30, 15000); printf("The taxi fare is: $%.3f\n", fare); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <locale.h> /* 6. Crie um programa que contenha um vetor de inteiros contendo 7 elementos. Utilizando apenas aritmética de ponteiros (ou seja, navegar o vetor utilizando a propriedade de ponteiros), leia esse vetor do teclado e imprima a soma dos elementos que estão em posição par. */ int main() { setlocale(LC_ALL, "Portuguese"); int v[7], s = 0; int *p = v; for (int i = 0; i < 7; i++) { scanf("%d", &v[i]); if (i%2) { s += *(p+i); } } printf("%d", s); return 0; }
C
//interactive dialog with serial device //http://en.wikibooks.org/wiki/Serial_Programming/Serial_Linux#termios #include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> int main(int argc,char** argv) { struct termios tio; struct termios stdio; struct termios old_stdio; int tty_fd; unsigned char c='D'; tcgetattr(STDOUT_FILENO,&old_stdio); printf("Please start with %s /dev/ttyS1 (for example)\n",argv[0]); memset(&stdio,0,sizeof(stdio)); stdio.c_iflag=0; stdio.c_oflag=0; stdio.c_cflag=0; stdio.c_lflag=0; stdio.c_cc[VMIN]=1; stdio.c_cc[VTIME]=0; //set stdout tcsetattr(STDOUT_FILENO,TCSANOW,&stdio); tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio); //set stdin fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // make the reads non-blocking memset(&tio,0,sizeof(tio)); tio.c_iflag=0; tio.c_oflag=0; tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information tio.c_lflag=0; tio.c_cc[VMIN]=1; tio.c_cc[VTIME]=5; tty_fd=open(argv[1], O_RDWR | O_NONBLOCK); cfsetospeed(&tio,B115200); // 115200 baud cfsetispeed(&tio,B115200); // 115200 baud //set serial device tcsetattr(tty_fd,TCSANOW,&tio); while (c!='q') { if (read(tty_fd,&c,1)>0) write(STDOUT_FILENO,&c,1); // if new data is available on the serial port, print it out if (read(STDIN_FILENO,&c,1)>0) write(tty_fd,&c,1); // if new data is available on the console, send it to the serial port } close(tty_fd); tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio); return EXIT_SUCCESS; }
C
#include "timer.h" /** Ecrit le résultat du calcul dans un fichier de sortie * @param noInstance le numéro d'instance utilisé lors du calcul * @param valeurSolution la fonction objectif de la meilleure solution trouvée pour cette instance * @param temps le temps de calcul pris par l'algorithme de résolution */ void timeFile(int noInstance, int valeurSolution, double temps){ FILE* sortie = NULL; if(noInstance != 1){ sortie = fopen("sortie.txt","a"); }else { sortie = fopen("sortie.txt","w+"); fprintf(sortie,"INSTANCE | SOLUTION | TEMPS CALCUL |\n"); } if(sortie == NULL){ printf("Problème pour écrire le temps dans sortie.txt"); exit(0); } fprintf(sortie," %.2d | %d | %f |\n", noInstance, valeurSolution, temps); fclose(sortie); } /** Démarre un timer * @return retourne une valeur de référence pour calculer le temps écoulé */ time_t timer_start(){ return clock(); } /** Démarre un timer * @param timer la valeur de référence du timer * @return retourne la différence entre le temps actuel et la valeur de référence passée en paramètre */ double timer_getTime(time_t timer){ double timeElapsed; timeElapsed = (clock()-timer)/(double)CLOCKS_PER_SEC; return timeElapsed; }
C
/* ヘッダファイルのインクルード */ #include <stdio.h> /* 標準入出力 */ #include <libxml/xmlreader.h> /* xmlreader */ /* main関数 */ int main(void){ /* 変数の宣言 */ xmlTextReaderPtr reader; /* XMLリーダreader */ /* XMLファイルを読み込み, XMLリーダを作成. */ reader = xmlNewTextReaderFilename("test.xml"); /* xmlNewTextReaderFilenameでtest.xmlを読み込み. */ if (reader != NULL){ /* 作成成功. */ printf("reader = 0x%08x\n", reader); /* readerのアドレスを出力. */ xmlFreeTextReader(reader); /* xmlFreeTextReaderでリソース解放. */ } /* プログラムの終了 */ return 0; /* 0を返して正常終了. */ }
C
// 连快速幂取模都用不到的暴力就可以解决。。 #include <stdio.h> #include <string.h> #define MOD 10000000000 int main() { long long ans=0; for(long long i=1,fac;i<=1000;++i) { fac=1; for(int j=1;j<=i;++j) { fac*=i; fac%=MOD; } ans+=fac; ans%=MOD; } printf("%lld\n",ans); return 0; }
C
#include <stdio.h> #include <string.h> #include <sys/socket.h> #include <netdb.h> int udp_sock; struct sockaddr_in dst; int main(int argc, char **argv) { udp_sock = socket(PF_INET,SOCK_DGRAM,0); dst.sin_family = PF_INET; dst.sin_port = htons(18093); dst.sin_addr.s_addr = INADDR_ANY; sendto(udp_sock, "Hello\n",6,0,(struct sockaddr*)&dst,sizeof(struct sockaddr)); close(udp_sock); return 0; }
C
#ifndef _NODE_H_ #define _NODE_H_ #include "typedef.h" R_Geode getBox_Geode_R() { R_Geode boxGeode = new osg::Geode; R_ShapeDrawable boxShape = new osg::ShapeDrawable; boxShape->setShape(new osg::Box(osg::Vec3(0.0f, 0.0f, 0.0f), 1.0f, 1.0f, 1.0f)); boxGeode->addDrawable(boxShape); return boxGeode; } R_Geometry createNode() { osg::ref_ptr<osg::Geode> geode = new osg::Geode(); osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array(8); (*vertices)[0].set(-0.5f, -0.5f, 0.5f); (*vertices)[1].set(0.5f, -0.5f, -0.5f); (*vertices)[2].set(0.5f, -0.5f, 0.5f); (*vertices)[3].set(-0.5f, -0.5f, -0.5f); (*vertices)[4].set(-0.5f, 0.5f, 0.5f); (*vertices)[5].set(0.5f, 0.5f, 0.5f); (*vertices)[6].set(-0.5f, 0.5f, -0.5f); (*vertices)[7].set(0.5f, 0.5f, -0.5f); osg::ref_ptr<osg::DrawElementsUInt> indices = new osg::DrawElementsUInt(GL_TRIANGLES, 36); (*indices)[0] = 0; (*indices)[1] = 1; (*indices)[2] = 2; (*indices)[3] = 0; (*indices)[4] = 3; (*indices)[5] = 1; (*indices)[6] = 4; (*indices)[7] = 2; (*indices)[8] = 5; (*indices)[9] = 4; (*indices)[10] = 0; (*indices)[11] = 2; (*indices)[12] = 6; (*indices)[13] = 5; (*indices)[14] = 7; (*indices)[15] = 6; (*indices)[16] = 4; (*indices)[17] = 5; (*indices)[18] = 3; (*indices)[19] = 7; (*indices)[20] = 1; (*indices)[21] = 3; (*indices)[22] = 6; (*indices)[23] = 7; (*indices)[24] = 5; (*indices)[25] = 2; (*indices)[26] = 1; (*indices)[27] = 5; (*indices)[28] = 1; (*indices)[29] = 7; (*indices)[30] = 4; (*indices)[31] = 3; (*indices)[32] = 0; (*indices)[33] = 4; (*indices)[34] = 6; (*indices)[35] = 3; osg::ref_ptr<osg::Geometry> geom = new osg::Geometry; geom->setVertexArray(vertices.get()); geom->addPrimitiveSet(indices.get()); return geom; } #endif //_NODE_H_
C
#include <stdio.h> int add(int a, int b) { return a * b; } int main() { int length, i, sum = 0, tmp; printf("Enter number of integers: "); scanf("%d", &length); for (i = 0; i < length; i++) { printf("Enter number %d: ", i + 1); scanf("%d", &tmp); printf("Number %d: %d\n", i + 1, tmp); sum = add(sum, tmp); } printf("The average is: %lf\n", (double)sum / length); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <SDL2/SDL.h> #include <SDL2/SDL_timer.h> #include <SDL2/SDL_image.h> #include <sys/types.h> #include <unistd.h> #include "testing.h" #define WINDOW_WIDTH (640) #define WINDOW_HEIGHT (480) #define BUTTON_WIDTH (175) #define BUTTON_HEIGHT (40) int makeGameWindow() { //makes window for the gameplay SDL_Window *game_window = SDL_CreateWindow("Battleship Gameplay",//make window SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN | //SDL_WINDOW_FULLSCREEN SDL_WINDOW_RESIZABLE //SDL_WINDOW_MINIMIZED ); SDL_Renderer *game_render = SDL_CreateRenderer(game_window, -1, SDL_RENDERER_PRESENTVSYNC); SDL_Surface *game_sf = SDL_GetWindowSurface(game_window); SDL_UpdateWindowSurface(game_window); SDL_Surface *game_surface = IMG_Load("sprites/battleship-grid.png"); SDL_Texture *game_texture = SDL_CreateTextureFromSurface(game_render, game_surface); SDL_Rect gamedest; gamedest.w = WINDOW_WIDTH; gamedest.h = WINDOW_HEIGHT; SDL_QueryTexture(game_texture, NULL, NULL, &gamedest.w, &gamedest.h); while (1) { SDL_Event game_event; while (SDL_PollEvent(&game_event)) { switch (game_event.type) { case SDL_QUIT: SDL_DestroyTexture(game_texture); SDL_DestroyRenderer(game_render); SDL_DestroyWindow(game_window); exit(0); break; } } SDL_RenderClear(game_render); SDL_RenderCopy(game_render, game_texture, NULL, NULL); SDL_RenderPresent(game_render); SDL_Delay(1000/60); } } int makeMainMenu(SDL_Window *window, SDL_Surface *window_surface, SDL_Renderer *render) { //makes window for main menu window = SDL_CreateWindow("Battleship Menu",//make window SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN | //SDL_WINDOW_FULLSCREEN SDL_WINDOW_RESIZABLE //SDL_WINDOW_MINIMIZED ); if (window == NULL) { printf("Error creating window: %s\n", SDL_GetError()); SDL_DestroyWindow(window); SDL_Quit(); return 1; } printf("Window created successfully\n"); window_surface = SDL_GetWindowSurface(window); if(!window_surface) { printf("Failed to get the surface from the window\n"); return -1; } SDL_UpdateWindowSurface(window); //SDL_Delay(5000); render = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC); if (render == NULL) { printf("Error rendering: %s\n", SDL_GetError()); SDL_DestroyRenderer(render); SDL_DestroyWindow(window); SDL_Quit(); return 1; } printf("Render successful\n"); }
C
int ft_strlen(); #include <stdio.h> int main() { char a[] = "12345"; printf("\n%d\n", ft_strlen(a)); }
C
#include <stdio.h> #include <stdlib.h> int main(void) { float amount; char currency; printf("Enter amount in CHF and currency [W] won, [$] dollar, [Y] yen, [L] pound : "); scanf("%f %c", &amount, &currency); switch (currency) { case 'W' : printf("%.2f in CHF is %.2f in KRW.\n", amount, (amount * 1176.44)); break; case '$' : printf("%.2f in CHF is %.2f in USD.\n", amount, (amount * 1.01)); break; case 'Y' : printf("%.2f in CHF is %.2f in JPY.\n", amount, (amount * 109.3)); break; case 'L' : printf("%.2f in CHF is %.2f in GBP.\n", amount, (amount * 0.78)); break; default: printf("Chosen currency is not available.\n"); break; } return 0; }
C
#include<stdio.h> #include<string.h> #include<sys/types.h> #include<sys/stat.h> #include<unistd.h> #include<fcntl.h> #include<stdlib.h> int main() { int fd = open("myfile1",O_RDONLY);//以只读的方式打开文件 if(fd < 0)//文件打开失败 { perror("open error"); exit(1); } char buf[1024]; const char* msg = "hello world\n"; while(1) { ssize_t s = read(fd,buf,strlen(msg)); if(s > 0) { buf[s] = 0; printf("%s",buf); sleep(1); } else if(s == 0)//文件到达结尾 { break; } } close(fd); return 0; ////close(0); ////close(2); //close(1); //int fd = open("myfile",O_WRONLY); //if(fd < 0) //{ // perror("open error"); // return 1; //} //printf("nakl %d\n",fd); //fork(); ////fflush(stdout); ////close(fd); //exit(0); ////int fd = open("myfile",O_RDONLY); ////if(fd < 0) ////{ //// perror("open error"); //// return 1; ////} ////const char* msg = "hello bit\n"; ////char buf[1024]; ////while(1) ////{ //// size_t s = read(0,buf,strlen(msg));//从标准输入读取内容到buf中 // //// size_t s = read(fd,buf,strlen(msg));//从文件fd中的读取内容到buf //// if(s > 0) //// { //// buf[s] = 0; //// printf("%s",buf); //// } //// else //// { //// break; //// } ////} ////close(fd); ////return 0; }
C
#include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h> #include <errno.h> #define BUFFSZ 4096 #define MSGSZ sizeof(struct chmsg) // use as massage from child to parent proccess struct chmsg{ int count; char letter; }; int procn = 26; // number of child-workers processes int caps = 'A'-'a'; int semCreate(key_t key, int semCount){ //union semun semopts; //in this case we can send simply integer struct sembuf semch; int semid; int i; semid = semget(key, semCount, IPC_CREAT|0660); if (semid==-1){ printf("Sem err open"); exit(1); } //semopts.val = 0; for(i=0; i<semCount; i++) semctl(semid, i, SETVAL, 0); return semid; } int semSet(int semid, int val){ semctl(semid, 0, SETVAL, val); return 0; } int semDelete(int semid){ semctl(semid, 0, IPC_RMID, 0); return 0; } int semOp(int semid, int val){ int err; struct sembuf semch; semch.sem_num = 0; semch.sem_op = val; // for case if we unrxpectedly stop and resume our prog // waiting of operation may drop do { err = semop(semid, &semch, 1); } while (err == -1 && errno == EINTR); return 0; } void info(){ printf("\nUsage: prog filename\n"); } int main(int argc, char *argv[]){ key_t key; // unic key for use System V IPC int semid; // id`s for using semophore and int shmid; // shared memory block char* buff; // ptr for shm block pid_t pid, ppid; int i, rc, count, err; char letter; struct chmsg msg, *msgp; char msgbuff[MSGSZ]; int letCount[procn]; // array of results of counting int fd[2]; // for pipe; FILE *fin; if (argc==1) { info(); return 0; } letter='a'; ppid = pid = getpid(); err = pipe(fd); // preparing for using System V IPC key = ftok(".", 'a'); semid = semCreate(key, 1); shmid = shmget( key, BUFFSZ, IPC_CREAT | 0660 ); buff = shmat(shmid, 0, 0); for(i=0; i<procn; i++){ letCount[i]=0; } // create child-workers and give each aim as letter for(i=0; i<procn; i++){ if (fork()==0){ pid = getpid(); break; } letter++; // after each fork this var will be copy with next val } // parent and child-workers braches: if (pid==ppid){ // parent process branch close(fd[1]); fin = fopen(argv[1], "r"); while(!feof(fin)){ rc = fread(buff, sizeof(char), BUFFSZ, fin); if (rc!=BUFFSZ){ buff[rc]='\0'; // end of file } semSet(semid, procn); // open semophore, for procn instances for(i=0; i<procn; i++){ rc = read(fd[0], msgbuff, MSGSZ); if (rc!=MSGSZ) exit(2); msgp = (struct chmsg*) msgbuff; letCount[msgp->letter-'a'] += msgp->count; } } semctl(semid, 0, IPC_RMID, 0); shmdt(buff); // deattach shmemory block shmctl(shmid, IPC_RMID, 0); // delete shm block close(fd[0]); fclose(fin); for (i=0; i<procn; i++){ printf("\nletter \"%c\": %d", 'a'+i, letCount[i]); } } else { // child-worker process bracnch close(fd[0]); while(1){ semOp(semid, -1); // decrement semophore count = 0; for(i=0; i<BUFFSZ; i++){ if (buff[i]==letter || buff[i]==letter+caps){ count++; } else if(buff[i]=='\0') { break; } } msg.count = count; msg.letter = letter; write(fd[1], &msg, MSGSZ); if (i!=BUFFSZ) break; semOp(semid, 0); // wait semophore set 0 } close(fd[1]); } // end child wait(NULL); return 0; }
C
#include <stdio.h> /* printf, fgets */ #include <stdlib.h> /* atoi */ #include <string.h> /* strlen */ const int LETTERS_NUM = 26; const char BASE_LETTER = 'a'; int main(int argc, char const *argv[]) { int characters[LETTERS_NUM] = {0}; const char *text = argv[1]; int i = 0; if(argc < 2){ printf("%s\n", "Usage:\n\t./a.out string"); return 1; } while(i < strlen(text)) { characters[text[i] - BASE_LETTER]++; i++; } for(int i = 0; i < LETTERS_NUM; i++) { if(characters[i] > 0){ printf("There was %d occurences of letter %c in %s.\n", characters[i], i + BASE_LETTER, text); } } return 0; }
C
#include <stdio.h> void swapEntero(int *a, int *b); void swapFlotante(float *a, float *b); int main(int argc, char const *argv[]) { int a = 1,b = 2; float p,q; printf("a: %d\nb: %d\n",a,b); swapEntero(&a,&b); printf("a: %d\nb: %d\n",a,b); return 0; } void swapEntero(int *a, int *b){ int aux; aux = *a; *a = *b; *b = aux; } void swapFlotante(float *a, float *b){ float aux; aux = *a; *a = *b; *b = aux; }
C
/* pnmrotate.c - read a portable anymap and rotate it by some angle ** ** Copyright (C) 1989, 1991 by Jef Poskanzer. ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, provided ** that the above copyright notice appear in all copies and that both that ** copyright notice and this permission notice appear in supporting ** documentation. This software is provided "as is" without express or ** implied warranty. */ #define _XOPEN_SOURCE /* get M_PI in math.h */ #include <math.h> #include <assert.h> #include "pm_c_util.h" #include "mallocvar.h" #include "shhopt.h" #include "ppm.h" #include "pnm.h" #define SCALE 4096 #define HALFSCALE 2048 struct cmdlineInfo { /* All the information the user supplied in the command line, in a form easy for the program to use. */ const char * inputFilespec; /* Filespecs of input file */ float angle; /* Angle to rotate, in radians */ unsigned int noantialias; const char * background; /* NULL if none */ unsigned int keeptemp; /* For debugging */ unsigned int verbose; }; enum rotationDirection {CLOCKWISE, COUNTERCLOCKWISE}; struct shearParm { /* These numbers tell how to shear a pixel, but I haven't figured out yet exactly what each means. */ long fracnew0; long omfracnew0; unsigned int shiftWhole; unsigned int shiftUnits; }; static void parseCommandLine(int argc, char ** const argv, struct cmdlineInfo * const cmdlineP) { /*---------------------------------------------------------------------------- Note that the file spec array we return is stored in the storage that was passed to us as the argv array. -----------------------------------------------------------------------------*/ optEntry *option_def = malloc(100*sizeof(optEntry)); /* Instructions to OptParseOptions3 on how to parse our options. */ optStruct3 opt; unsigned int backgroundSpec; unsigned int option_def_index; option_def_index = 0; /* incremented by OPTENTRY */ OPTENT3(0, "background", OPT_STRING, &cmdlineP->background, &backgroundSpec, 0); OPTENT3(0, "noantialias", OPT_FLAG, NULL, &cmdlineP->noantialias, 0); OPTENT3(0, "keeptemp", OPT_FLAG, NULL, &cmdlineP->keeptemp, 0); OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose, 0); opt.opt_table = option_def; opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */ opt.allowNegNum = TRUE; /* We may have parms that are negative numbers */ pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0); /* Uses and sets argc, argv, and some of *cmdlineP and others. */ if (!backgroundSpec) cmdlineP->background = NULL; if (argc-1 < 1) pm_error("You must specify at least one argument: the angle " "to rotate."); else { int rc; float angleArg; rc = sscanf(argv[1], "%f", &angleArg); if (rc != 1) pm_error("Invalid angle argument: '%s'. Must be a floating point " "number of degrees.", argv[1]); else if (angleArg < -90.0 || angleArg > 90.0) pm_error("angle must be between -90 and 90, inclusive. " "You specified %f. " "Use 'pamflip' for other rotations.", angleArg); else { /* Convert to radians */ cmdlineP->angle = angleArg * M_PI / 180.0; if (argc-1 < 2) cmdlineP->inputFilespec = "-"; else { cmdlineP->inputFilespec = argv[2]; if (argc-1 > 2) pm_error("Program takes at most two arguments " "(angle and filename). You specified %d", argc-1); } } } } static void storeImage(const char * const fileName, xel ** const xels, unsigned int const cols, unsigned int const rows, xelval const maxval, int const format) { FILE * ofP; ofP = pm_openw(fileName); pnm_writepnm(ofP, xels, cols, rows, maxval, format, 0); pm_close(ofP); } static void computeNewFormat(bool const antialias, int const format, xelval const maxval, int * const newformatP, xelval * const newmaxvalP) { if (antialias && PNM_FORMAT_TYPE(format) == PBM_TYPE) { *newformatP = PGM_TYPE; *newmaxvalP = PGM_MAXMAXVAL; pm_message("promoting from PBM to PGM - " "use -noantialias to avoid this"); } else { *newformatP = format; *newmaxvalP = maxval; } } static xel backgroundColor(const char * const backgroundColorName, xel * const topRow, int const cols, xelval const maxval, int const format) { xel retval; if (backgroundColorName) { retval = pnm_parsecolorxel(backgroundColorName, maxval, format); } else retval = pnm_backgroundxelrow(topRow, cols, maxval, format); return retval; } static void reportBackground(xel const bgColor) { pm_message("Background color %u/%u/%u", PPM_GETR(bgColor), PPM_GETG(bgColor), PPM_GETB(bgColor)); } static void shearX(xel * const inRow, xel * const outRow, int const cols, int const format, xel const bgxel, bool const antialias, float const shiftAmount, int const newcols) { /*---------------------------------------------------------------------------- Shift a the row inRow[] right by 'shiftAmount' pixels and return the result as outRow[]. The input row is 'cols' columns wide, whereas the output row is 'newcols'. The format of the input row is 'format'. We shift the row on a background of color 'bgxel'. The output row has the same format and maxval as the input. 'shiftAmount' may not be negative. 'shiftAmount' can be fractional, so we either just go by the nearest integer value or mix pixels to achieve the shift, depending on 'antialias'. -----------------------------------------------------------------------------*/ assert(shiftAmount >= 0.0); if (antialias) { unsigned int const shiftWhole = (unsigned int) shiftAmount; long const fracShift = (shiftAmount - shiftWhole) * SCALE; long const omfracShift = SCALE - fracShift; unsigned int col; xel * nxP; xel prevxel; for (col = 0; col < newcols; ++col) outRow[col] = bgxel; prevxel = bgxel; for (col = 0, nxP = &(outRow[shiftWhole]); col < cols; ++col, ++nxP) { xel const p = inRow[col]; switch (PNM_FORMAT_TYPE(format)) { case PPM_TYPE: PPM_ASSIGN(*nxP, (fracShift * PPM_GETR(prevxel) + omfracShift * PPM_GETR(p) + HALFSCALE) / SCALE, (fracShift * PPM_GETG(prevxel) + omfracShift * PPM_GETG(p) + HALFSCALE) / SCALE, (fracShift * PPM_GETB(prevxel) + omfracShift * PPM_GETB(p) + HALFSCALE) / SCALE ); break; default: PNM_ASSIGN1(*nxP, (fracShift * PNM_GET1(prevxel) + omfracShift * PNM_GET1(p) + HALFSCALE) / SCALE ); break; } prevxel = p; } if (fracShift> 0 && shiftWhole + cols < newcols) { switch (PNM_FORMAT_TYPE(format)) { case PPM_TYPE: PPM_ASSIGN(*nxP, (fracShift * PPM_GETR(prevxel) + omfracShift * PPM_GETR(bgxel) + HALFSCALE) / SCALE, (fracShift * PPM_GETG(prevxel) + omfracShift * PPM_GETG(bgxel) + HALFSCALE) / SCALE, (fracShift * PPM_GETB(prevxel) + omfracShift * PPM_GETB(bgxel) + HALFSCALE) / SCALE ); break; default: PNM_ASSIGN1(*nxP, (fracShift * PNM_GET1(prevxel) + omfracShift * PNM_GET1(bgxel) + HALFSCALE) / SCALE ); break; } } } else { unsigned int const shiftCols = (unsigned int) (shiftAmount + 0.5); unsigned int col; unsigned int outcol; outcol = 0; /* initial value */ for (col = 0; col < shiftCols; ++col) outRow[outcol++] = bgxel; for (col = 0; col < cols; ++col) outRow[outcol++] = inRow[col]; for (col = shiftCols + cols; col < newcols; ++col) outRow[outcol++] = bgxel; assert(outcol == newcols); } } static void shearXFromInputFile(FILE * const ifP, unsigned int const cols, unsigned int const rows, xelval const maxval, int const format, enum rotationDirection const direction, float const xshearfac, xelval const newmaxval, int const newformat, bool const antialias, const char * const background, xel *** const shearedXelsP, unsigned int * const newcolsP, xel * const bgColorP) { /*---------------------------------------------------------------------------- Shear X from input file into newly malloced xel array. Return that array as *shearedColsP, and its width as *tempColsP. Everything else about the sheared image is the same as for the input image. The input image on file 'ifP' is described by 'cols', 'rows', 'maxval', and 'format'. Along the way, figure out what the background color of the output should be based on the contents of the file and the user's directive 'background' and return that as *bgColorP. -----------------------------------------------------------------------------*/ unsigned int const maxShear = (rows - 0.5) * xshearfac + 0.5; unsigned int const newcols = cols + maxShear; xel ** shearedXels; xel * xelrow; xel bgColor; unsigned int row; shearedXels = pnm_allocarray(newcols, rows); xelrow = pnm_allocrow(cols); for (row = 0; row < rows; ++row) { /* The shear factor is designed to shear over the entire width from the left edge of of the left pixel to the right edge of the right pixel. We use the distance of the center of this pixel from the relevant edge to compute shift amount: */ float const xDistance = (direction == COUNTERCLOCKWISE ? row + 0.5 : (rows-0.5 - row)); float const shiftAmount = xshearfac * xDistance; pnm_readpnmrow(ifP, xelrow, cols, maxval, format); pnm_promoteformatrow(xelrow, cols, maxval, format, newmaxval, newformat); if (row == 0) bgColor = backgroundColor(background, xelrow, cols, newmaxval, format); shearX(xelrow, shearedXels[row], cols, newformat, bgColor, antialias, shiftAmount, newcols); } pnm_freerow(xelrow); *shearedXelsP = shearedXels; *newcolsP = newcols; assert(rows >= 1); /* Ergo, bgColor is defined */ *bgColorP = bgColor; } static void shearYNoAntialias(xel ** const inxels, xel ** const outxels, int const cols, int const inrows, int const outrows, int const format, xel const bgColor, struct shearParm const shearParm[]) { /*---------------------------------------------------------------------------- Shear the image in 'inxels' ('cols' x 'inrows') vertically into 'outxels' ('cols' x 'outrows'), both format 'format'. shearParm[X] tells how much to shear pixels in Column X (clipped to Rows 0 through 'outrow' -1) and 'bgColor' is what to use for background where there is none of the input in the output. We do not do any antialiasing. We simply move whole pixels. We go row by row instead of column by column to save real memory. Going row by row, the working set is only a few pages, whereas going column by column, it would be one page per output row plus one page per input row. -----------------------------------------------------------------------------*/ unsigned int inrow; unsigned int outrow; /* Fill the output with background */ for (outrow = 0; outrow < outrows; ++outrow) { unsigned int col; for (col = 0; col < cols; ++col) outxels[outrow][col] = bgColor; } /* Overlay that background with sheared image */ for (inrow = 0; inrow < inrows; ++inrow) { unsigned int col; for (col = 0; col < cols; ++col) { int const outrow = inrow + shearParm[col].shiftUnits; if (outrow >= 0 && outrow < outrows) outxels[outrow][col] = inxels[inrow][col]; } } } static void shearYColAntialias(xel ** const inxels, xel ** const outxels, int const col, int const inrows, int const outrows, int const format, xel const bgxel, struct shearParm shearParm[]) { /*----------------------------------------------------------------------------- Shear a column vertically. -----------------------------------------------------------------------------*/ long const fracnew0 = shearParm[col].fracnew0; long const omfracnew0 = shearParm[col].omfracnew0; int const shiftWhole = shearParm[col].shiftWhole; int outrow; xel prevxel; int inrow; /* Initialize everything to background color */ for (outrow = 0; outrow < outrows; ++outrow) outxels[outrow][col] = bgxel; prevxel = bgxel; for (inrow = 0; inrow < inrows; ++inrow) { int const outrow = inrow + shiftWhole; if (outrow >= 0 && outrow < outrows) { xel * const nxP = &(outxels[outrow][col]); xel const x = inxels[inrow][col]; switch ( PNM_FORMAT_TYPE(format) ) { case PPM_TYPE: PPM_ASSIGN(*nxP, (fracnew0 * PPM_GETR(prevxel) + omfracnew0 * PPM_GETR(x) + HALFSCALE) / SCALE, (fracnew0 * PPM_GETG(prevxel) + omfracnew0 * PPM_GETG(x) + HALFSCALE) / SCALE, (fracnew0 * PPM_GETB(prevxel) + omfracnew0 * PPM_GETB(x) + HALFSCALE) / SCALE ); break; default: PNM_ASSIGN1(*nxP, (fracnew0 * PNM_GET1(prevxel) + omfracnew0 * PNM_GET1(x) + HALFSCALE) / SCALE ); break; } prevxel = x; } } if (fracnew0 > 0 && shiftWhole + inrows < outrows) { xel * const nxP = &(outxels[shiftWhole + inrows][col]); switch (PNM_FORMAT_TYPE(format)) { case PPM_TYPE: PPM_ASSIGN(*nxP, (fracnew0 * PPM_GETR(prevxel) + omfracnew0 * PPM_GETR(bgxel) + HALFSCALE) / SCALE, (fracnew0 * PPM_GETG(prevxel) + omfracnew0 * PPM_GETG(bgxel) + HALFSCALE) / SCALE, (fracnew0 * PPM_GETB(prevxel) + omfracnew0 * PPM_GETB(bgxel) + HALFSCALE) / SCALE); break; default: PNM_ASSIGN1(*nxP, (fracnew0 * PNM_GET1(prevxel) + omfracnew0 * PNM_GET1(bgxel) + HALFSCALE) / SCALE); break; } } } static void shearImageY(xel ** const inxels, int const cols, int const inrows, int const format, xel const bgxel, bool const antialias, enum rotationDirection const direction, float const yshearfac, int const yshearjunk, xel *** const outxelsP, unsigned int * const outrowsP) { unsigned int const maxShear = (cols - 0.5) * yshearfac + 0.5; unsigned int const outrows = inrows + maxShear - 2 * yshearjunk; struct shearParm * shearParm; /* malloc'ed */ int col; xel ** outxels; outxels = pnm_allocarray(cols, outrows); MALLOCARRAY(shearParm, cols); if (shearParm == NULL) pm_error("Unable to allocate memory for shearParm"); for (col = 0; col < cols; ++col) { /* The shear factor is designed to shear over the entire height from the top edge of of the top pixel to the bottom edge of the bottom pixel. We use the distance of the center of this pixel from the relevant edge to compute shift amount: */ float const yDistance = (direction == CLOCKWISE ? col + 0.5 : (cols-0.5 - col)); float const shiftAmount = yshearfac * yDistance; shearParm[col].fracnew0 = (shiftAmount - (int)shiftAmount) * SCALE; shearParm[col].omfracnew0 = SCALE - shearParm[col].fracnew0; shearParm[col].shiftWhole = (int)shiftAmount - yshearjunk; shearParm[col].shiftUnits = (int)(shiftAmount + 0.5) - yshearjunk; } if (!antialias) shearYNoAntialias(inxels, outxels, cols, inrows, outrows, format, bgxel, shearParm); else { /* TODO: do this row-by-row, same as for noantialias, to save real memory. */ for (col = 0; col < cols; ++col) shearYColAntialias(inxels, outxels, col, inrows, outrows, format, bgxel, shearParm); } free(shearParm); *outxelsP = outxels; *outrowsP = outrows; } static void shearFinal(xel * const inRow, xel * const outRow, int const incols, int const outcols, int const format, xel const bgxel, bool const antialias, float const shiftAmount, int const x2shearjunk) { assert(shiftAmount >= 0.0); { unsigned int col; for (col = 0; col < outcols; ++col) outRow[col] = bgxel; } if (antialias) { long const fracnew0 = (shiftAmount - (int) shiftAmount) * SCALE; long const omfracnew0 = SCALE - fracnew0; unsigned int const shiftWhole = (int)shiftAmount - x2shearjunk; xel prevxel; unsigned int col; prevxel = bgxel; for (col = 0; col < incols; ++col) { int const new = shiftWhole + col; if (new >= 0 && new < outcols) { xel * const nxP = &(outRow[new]); xel const x = inRow[col]; switch (PNM_FORMAT_TYPE(format)) { case PPM_TYPE: PPM_ASSIGN(*nxP, (fracnew0 * PPM_GETR(prevxel) + omfracnew0 * PPM_GETR(x) + HALFSCALE) / SCALE, (fracnew0 * PPM_GETG(prevxel) + omfracnew0 * PPM_GETG(x) + HALFSCALE) / SCALE, (fracnew0 * PPM_GETB(prevxel) + omfracnew0 * PPM_GETB(x) + HALFSCALE) / SCALE); break; default: PNM_ASSIGN1(*nxP, (fracnew0 * PNM_GET1(prevxel) + omfracnew0 * PNM_GET1(x) + HALFSCALE) / SCALE ); break; } prevxel = x; } } if (fracnew0 > 0 && shiftWhole + incols < outcols) { xel * const nxP = &(outRow[shiftWhole + incols]); switch (PNM_FORMAT_TYPE(format)) { case PPM_TYPE: PPM_ASSIGN(*nxP, (fracnew0 * PPM_GETR(prevxel) + omfracnew0 * PPM_GETR(bgxel) + HALFSCALE) / SCALE, (fracnew0 * PPM_GETG(prevxel) + omfracnew0 * PPM_GETG(bgxel) + HALFSCALE) / SCALE, (fracnew0 * PPM_GETB(prevxel) + omfracnew0 * PPM_GETB(bgxel) + HALFSCALE) / SCALE); break; default: PNM_ASSIGN1(*nxP, (fracnew0 * PNM_GET1(prevxel) + omfracnew0 * PNM_GET1(bgxel) + HALFSCALE) / SCALE ); break; } } } else { unsigned int const shiftCols = (unsigned int)(shiftAmount + 0.5) - x2shearjunk; unsigned int col; for (col = 0; col < incols; ++col) { unsigned int const outcol = shiftCols + col; if (outcol >= 0 && outcol < outcols) outRow[outcol] = inRow[col]; } } } static void shearXToOutputFile(FILE * const ofP, xel ** const xels, unsigned int const cols, unsigned int const rows, xelval const maxval, int const format, enum rotationDirection const direction, float const xshearfac, int const x2shearjunk, xel const bgColor, bool const antialias) { /*---------------------------------------------------------------------------- Shear horizontally the image in 'xels' and write the result to file 'ofP'. 'cols', 'rows', 'maxval', and 'format' describe the image in 'xels'. They also describe the output image, except that it will be wider as dictated by the shearing parameters. Shear over background color 'bgColor'. Do a smooth pixel-mixing shear iff 'antialias' is true. -----------------------------------------------------------------------------*/ unsigned int const maxShear = (rows - 0.5) * xshearfac + 0.5; unsigned int const newcols = cols + maxShear - 2 * x2shearjunk; unsigned int row; xel * xelrow; pnm_writepnminit(ofP, newcols, rows, maxval, format, 0); xelrow = pnm_allocrow(newcols); for (row = 0; row < rows; ++row) { /* The shear factor is designed to shear over the entire width from the left edge of of the left pixel to the right edge of the right pixel. We use the distance of the center of this pixel from the relevant edge to compute shift amount: */ float const xDistance = (direction == COUNTERCLOCKWISE ? row + 0.5 : (rows-0.5 - row)); float const shiftAmount = xshearfac * xDistance; shearFinal(xels[row], xelrow, cols, newcols, format, bgColor, antialias, shiftAmount, x2shearjunk); pnm_writepnmrow(ofP, xelrow, newcols, maxval, format, 0); } pnm_freerow(xelrow); } int main(int argc, char *argv[]) { struct cmdlineInfo cmdline; FILE * ifP; xel ** shear1xels; xel ** shear2xels; xel bgColor; int rows, cols, format; int newformat; unsigned int newrows; int newRowsWithJunk; unsigned int shear1Cols; int yshearjunk, x2shearjunk; xelval maxval, newmaxval; float xshearfac, yshearfac; enum rotationDirection direction; pnm_init(&argc, argv); parseCommandLine(argc, argv, &cmdline); ifP = pm_openr(cmdline.inputFilespec); pnm_readpnminit(ifP, &cols, &rows, &maxval, &format); computeNewFormat(!cmdline.noantialias, format, maxval, &newformat, &newmaxval); xshearfac = fabs(tan(cmdline.angle / 2.0)); yshearfac = fabs(sin(cmdline.angle)); direction = cmdline.angle > 0 ? COUNTERCLOCKWISE : CLOCKWISE; /* The algorithm we use, for maximum speed, is 3 simple shears: A horizontal, a vertical, and another horizontal. */ shearXFromInputFile(ifP, cols, rows, maxval, format, direction, xshearfac, newmaxval, newformat, !cmdline.noantialias, cmdline.background, &shear1xels, &shear1Cols, &bgColor); pm_close(ifP); if (cmdline.verbose) reportBackground(bgColor); if (cmdline.keeptemp) storeImage("pnmrotate_stage1.pnm", shear1xels, shear1Cols, rows, newmaxval, newformat); yshearjunk = (shear1Cols - cols) * yshearfac; newRowsWithJunk = (shear1Cols - 1) * yshearfac + rows + 0.999999; x2shearjunk = (newRowsWithJunk - rows - yshearjunk - 1) * xshearfac; shearImageY(shear1xels, shear1Cols, rows, newformat, bgColor, !cmdline.noantialias, direction, yshearfac, yshearjunk, &shear2xels, &newrows); pnm_freearray(shear1xels, rows); if (cmdline.keeptemp) storeImage("pnmrotate_stage2.pnm", shear2xels, shear1Cols, newrows, newmaxval, newformat); shearXToOutputFile(stdout, shear2xels, shear1Cols, newrows, newmaxval, newformat, direction, xshearfac, x2shearjunk, bgColor, !cmdline.noantialias); pnm_freearray(shear2xels, newrows); pm_close(stdout); return 0; }
C
/* Custom effect that looks like popcorn. The 'popcorn' is color[0] and the background color is color[1]. If color[0] is the same as color[1], the 'popcorn' will be a random color. Keith Lord - 2018 LICENSE The MIT License (MIT) Copyright (c) 2018 Keith Lord 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, sub-license, 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. CHANGELOG 2018-11-13 initial version */ #ifndef Popcorn_h #define Popcorn_h #include <WS2812FX.h> #define MAX_NUM_POPCORN 10 #define GRAVITY 0.1 extern WS2812FX ws2812fx; typedef struct Kernel { float position; float velocity; int32_t color; } kernel; uint16_t popcorn(void) { WS2812FX::Segment* seg = ws2812fx.getSegment(); // get the current segment uint16_t seglen = seg->stop - seg->start + 1; uint32_t popcornColor = seg->colors[0]; uint32_t bgColor = seg->colors[1]; if(popcornColor == bgColor) popcornColor = ws2812fx.color_wheel(ws2812fx.random8()); bool isReverse = (seg->options & REVERSE) != 0; static kernel popcorn[MAX_NUM_POPCORN]; static float coeff = 0.0f; if(coeff == 0.0f) { // calculate the velocity coeff once (the secret sauce) coeff = pow((float)seglen, 0.5223324f) * 0.3944296f; } // reset all LEDs to background color for(uint16_t i=seg->start; i <= seg->stop; i++) { ws2812fx.setPixelColor(i, bgColor); } uint16_t ledIndex; for(int8_t i=0; i < MAX_NUM_POPCORN; i++) { bool isActive = popcorn[i].position >= 0.0f; if(isActive) { // if kernel is active, update its position popcorn[i].position += popcorn[i].velocity; popcorn[i].velocity -= GRAVITY; ledIndex = isReverse ? seg->stop - popcorn[i].position : seg->start + popcorn[i].position; if(ledIndex >= seg->start && ledIndex <= seg->stop) ws2812fx.setPixelColor(ledIndex, popcorn[i].color); } else { // if kernel is inactive, randomly pop it if(ws2812fx.random8() < 2) { // POP!!! popcorn[i].position = 0.0f; popcorn[i].velocity = coeff * (random(66, 100) / 100.0f); popcorn[i].color = popcornColor; ledIndex = isReverse ? seg->stop : seg->start; ws2812fx.setPixelColor(ledIndex, popcorn[i].color); ws2812fx.setCycle(); } } } return(seg->speed / seglen); } #endif
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h> //жϴС //С˴洢ֽдڵ͵ַ ˴洢෴ //int Storage_method() //{ // int a = 1; // return *(char*)&a; //} //int main() //{ // int ret = Storage_method(); // if (1 == ret) // printf("С˴洢\n"); // else // printf("˴洢\n"); // return 0; //} //int Storage_method() //{ // union // { // char a; // int c; // }u; // u.c = 1; // return u.a; //} //int main() //{ // int ret = Storage_method(); // if (1 == ret) // printf("С˴洢\n"); // else // printf("˴洢\n"); // return 0; //} //ö //enum //{ // MALE, // FMALE, // SERCET, //}; //struct S //{ // char name[20]; // short int age; // float score; //}S; //int main() //{ // struct S s = { "zhangsan",18,98 }; // FILE* pf = fopen("80.txt","w"); // if (pf == NULL) // return 0; // fread(&s, sizeof(struct S), 1, pf); // printf("%d %s %f\n", s.age, s.name, s.score); // //رļ // fclose(pf); // pf = NULL; // return 0; //} //int main() // //{ // // int a = 10000; // // FILE* pf = fopen("80.txt", "wb"); // // fwrite(&a, 4, 1, pf);//Ƶʽдļ // // fclose(pf); // // pf = NULL; // // return 0; // //}
C
#include <system/system.h> #include <system/timer.h> #include <system/task.h> #include <stddef.h> #include <stdio.h> void test() { printf("Timer 1 wake up at -> %d tick\n", system_get_tick_count()); } void test_2() { printf("Timer 2 wake up at -> %d tick\n", system_get_tick_count()); } void test_3() { printf("-----------------------------\n"); printf("Timer 3 wake up at -> %d tick\n", system_get_tick_count()); printf("-----------------------------\n"); } int main(void) { tmr_t test_timer, test_timer_2, test_timer_3; printf("System abstraction test - POSIX implementation\n"); system_init(); tmr_init(&test_timer, true, test, NULL); tmr_start(test_timer, 100); tmr_init(&test_timer_2, true, test_2, NULL); tmr_start(test_timer_2, 275); tmr_init(&test_timer_3, false, test_3, NULL); tmr_start(test_timer_3, 1000); tmr_stop(test_timer); tmr_reset(test_timer); system_start(); tmr_destroy(test_timer); tmr_destroy(test_timer_2); tmr_destroy(test_timer_3); return 0; }
C
#ifndef _PROFILE_ #define _PROFILE_ #include "Def.h" #include "myLib.h" #include "Prf.h" struct Profile; typedef double(Profile::*fFunction)(); typedef List(Profile::*vFunction)(); // struct to store all the calculated values for a profile. struct ProfRep { vector<double> x; // Values for all PDI's (in the order of fPDI) vector<List> vs; // List of winners (for each voting method) vector<idType> v; // The winner (for each voting method) vector<double> rg;// Regret values of voting methods (it is normalized: [0, 1]). bool isTie, isCW, isCC, isCCW; // There is: tie (for at least one voting method), Condorcet winner, Condorcet cycle, CC but no CW. }; struct regType { double v, min, max; regType() { v = 0; min = INF; max = 0;} }; // struct for the overall report of each index value for any PDI. struct indxRep { // 3: rnd, set, noTie !! double indx; // Value of the index int n; // Number of profiles with this index value. vector<int> tie; // Number of tie cases, for each voting rule and the last one is the number of cases with at least one tie. int cw, cc, ccw; // Number of cases of: Condorcet winner, Condorcet cycle, CC but no CW. vector<vector<double> > eq; // Number of cases with equal results: (for each pairs of methods and all together) // eq[0]: equal winner (maybe randomly), eq[1]:sum of degree of agreement, eq[2]: perfectly equal //!!?? vector< vector<regType> > rg; // min, max and sum of the regret value for each voting method indxRep(int nV = 0, int nEq = 0) { n = 0; cw = cc = ccw = 0; tie.resize(nV+1, 0); eq.resize(3, vector<double>(nEq, 0)); rg.resize(3, vector<regType>(nV)); } }; //:Total : 1 + (nV+1) + (3*nEq) + (3*nV*3) //:Calc. : 1 + (nV+1) + (3*nEq) + (1*nV*3) //:Out : 1 + (nV+1) + (3*nEq) + (1*nV*2) = 23 //range for (min, max) //:Chart : 1 + (nV+1) + (3*nEq) + (1*nV*1) = 20 //no range struct Profile { vector<Prf> p; // Preferences int n, m; vector<vector<int> > pr; // Pairwise comparison tbale (m * m). pr[i][j]: number of voters prefer i to j. vector<int> copV; // Copeland value of (m) alternatives. copV[i]: difference of pairwise wins (+) and loss (-) of i against others. setList sMG; // Set of Majority Graph relations. {i, j} in sMG <==> i beats j in pairwise comparison. vector<int> plV; // Plurality value of (m) alternatives. plV[i]: number of preferences with i at the top. Profile(vector<int>& f, vector<int>& v, int n0 = 0, int m0 = 0) { n = n0; m = m0; Reset(f, v); Prf::setHW(fillSeq<double>(m, m, -1)); } void reset(int n0 = 0, int m0 = 0) { n = n0; m = m0; p.clear(); p.resize(n, List(m, 0)); pr.clear(); copV.clear(); sMG.clear(); plV.clear(); } void reset(vector<Prf>& p0) { reset(p0.size(), p0[0].m); p = p0;} // Randomly generates a profile of n voters over m alternatives [IC]. Will use the current value of n and m as default. void rndGen(int n0 = 0, int m0 = 0); // Randomly chooses a sample of size n from the preferences of the population ppl. Will use the current value of n as default. void sampleGen(vector<List>& ppl, int n0 = 0); // Randomly swaps two adjacent alternatives of one of the preferences [RW]. void rndSwp(); // Produces the unanimous profile of n voters over m alternatives (the unanimous profile is: 0 > 1 > ... > m-1). void unanimous(int n, int m); // Calculates the sum of pairwise distances of the profile, the argument is the distance function. double df(double (*f)(Prf&, Prf&)); // Calculates the sum of compromise-based distances of the profile from the preference c, the argument is the distance function. double cb(Prf& c, double(*f)(Prf&, Prf&)); // Calculates the sum of compromise-based (Kendall tau) distances of the profile from the relation r. (Other distances are not applicable). double cr(setList& r); // Functions for different PDI's (not normalized, currently all the returned values are integer): // Distance-based PDI's: // Aggregation operator: Sum double dD() {return df(Prf::dD);} // Discrete double dK() {return df(Prf::dK);} // Kendall tau double dK3() {return df(Prf::dK3);} // 3_Kendall tau double dS() {return df(Prf::dS);} // Spearman footrule double dM() {return df(Prf::dM);} // Maximum displacement double dHam() { return df(Prf::dHam); } // Hamming double dWHam() { return df(Prf::dWHam); } // Weighted Hamming // Aggregation operator: max double dKmax(); // Kendall tau // Compromise-based PDI's: double cbPlK() {return cb(Prf(Rank(Plurality())), Prf::dK); } // Plurality double cbBrK() {return cb(Prf(Rank(Borda())), Prf::dK); } // Borda double cbCpK() {return cb(Prf(Rank(Copeland())), Prf::dK); } // Copeland double majK() { return cr(mgR()); } // Majority graph // Support-based PDI's: double Sup2() {return Sup(2);} double Sup3() {return Sup(3);} double Supm() {return Sup(m);} // = Sups // Is this really faster than Sups? why? !!?? double Sups() {setList s; for (int i = 0; i < n; i++) s.insert(p[i].p); return s.size();} // Simple support-based // A random dummy PDI! double Dummy() { return rand() % (100 * abs(p[0].p[0]-p[1].p[0]) + 1); } // Produces the majority graph (sMG). Also, calculates the pairwise comparison tbale (pr) and the Copeland values (copV). void prMaj(); // Returns the majority graph (sMG). setList& mgR(); // General function for support-based PDI's double Sup(int k); // Returns the (index of) member of v with highest value. If there are more than one, if noTie is 1 returns -1 otherwise returns one of them randomly. static idType Winner(const List& v, bool noTie = 0); // Returns the set of (indices of) members of v with highest value. static List Winners(const List& v); // Returns the sorted list of the alternatives based on their points (v). static List Rank(const List& v); // Voting methods: // Each function returns the points of alternatives based on the corresponding method. List Plurality(); List Borda(); List Copeland(); List Runoff(); // Checks the existence of Condorcet cycle. bool isCC(); // Calculates the overall regret of the voters if w is the winner. double regret(idType w); void Out(ostream& fout = cout); // Reports all the calculated parameters for the profile. // noTie is not used! ProfRep Report(bool noTie = 0); // Sets the lists of PDI's to be calculated and voting methods to be used for agreement between the methods and voters' regret. void Reset(vector<int>& f, vector<int>& v); vector<fFunction> fPDI; // PDI's to be calculated. vector<vFunction> vRule; // Voting rules to be used. // static void OutR(indxRep& r, ostream& f = cout); // static void OutRep(vector<ProfRep>& rep, string folderName = "", ostream& ff = cout); }; // list of all PDIs and voting methods static vector<pair<fFunction, string> > fAll = { { &Profile::dD, "dD" }, { &Profile::dK, "dK" }, { &Profile::dKmax, "dKmax" }, { &Profile::dK3, "dK3" }, { &Profile::dS, "dS" }, { &Profile::dM, "dM" }, { &Profile::Sup2, "Sup2" }, { &Profile::Sup3, "Sup3" }, { &Profile::Sups, "SupS" }, { &Profile::dHam, "dHam" }, { &Profile::dWHam, "dWHam" }, { &Profile::cbPlK, "cbPlK" }, { &Profile::cbBrK, "cbBrK" }, { &Profile::cbCpK, "cbCpK" }, { &Profile::majK, "majK" }, { &Profile::Dummy, "Dummy" } }; static vector<pair<vFunction, string> > vAll = { { &Profile::Plurality, "Plurality" }, { &Profile::Borda, "Borda" }, { &Profile::Copeland, "Copeland" } }; /* const vector<string> sfAll = { "dD", "dK", "dKmax", "dK3", "dS", "dM", "Sup2", "Sup3", "Sups", "dHam", "dWHam", "cbPlK", "cbBrK", "cbCpK", "majK", "Dummy" }; static fFunction fAll[] = {&Profile::dD, &Profile::dK, &Profile::dKmax, &Profile::dK3, &Profile::dS, &Profile::dM, &Profile::Sup2, &Profile::Sup3, &Profile::Sups, &Profile::dHam, &Profile::dWHam, &Profile::cbPlK, &Profile::cbBrK, &Profile::cbCpK, &Profile::majK, &Profile::Dummy}; const vector<string> svAll = { "Plurality", "Borda", "Copeland" }; static vFunction vAll[] = {&Profile::Plurality, &Profile::Borda, &Profile::Copeland}; */ #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* add_edge.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: marrow <marrow@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/11 05:01:01 by marrow #+# #+# */ /* Updated: 2020/11/11 05:01:48 by marrow ### ########.fr */ /* */ /* ************************************************************************** */ #include "lemin.h" /* ** Returns a pointer to the rooms we search for. We search for the room ** with ~name~ in the graph. */ static t_room *search(t_room *graph, char *name) { t_room *p; p = graph; while (p) { if (ft_strcmp(name, p->name) == 0) return (p); p = p->room_next; } return (NULL); } static int check_edge(t_room *one, t_room *two) { t_edge *edge; edge = one->edge_next; while (edge) { if (edge->to == two) return (1); edge = edge->edge_next; } return (0); } /* ** Adding connection between rooms. Making new copis of room(src) ** and room(dst). With function search we find every of these rooms, ** and using the add_room function add new copy to the end of the list ** of the rooms the src point to. The same we do in the another direction. */ void add_edge(t_lemin *lem, char *one, char *two) { t_room *one_room; t_room *two_room; one_room = search(lem->graph, one); two_room = search(lem->graph, two); if (check_edge(one_room, two_room)) return ; add_edges_to_rooms(one_room, two_room); }
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include "windows.h" void main(int argc,char *argv[]) { HANDLE hFile; DCB MyDcb; DCB GottenDcb; char *MyPort = "COM1"; if (argc > 1) { MyPort = argv[1]; } printf("Using port %s\n",MyPort); if ((hFile = CreateFile( MyPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL )) != ((HANDLE)-1)) { printf("We successfully opened the %s port.\n",MyPort); // // Get the state of the comm port and then // adjust the values to our liking. // if (!GetCommState( hFile, &MyDcb )) { printf("Couldn't get comm state: %d\n",GetLastError()); exit(1); } else { // // We immediately to a setcomm state on what we got // back. This will test that GetCommState can *ONLY* // return good data. // printf("Sanity check on GetCommState()\n"); if (!SetCommState( hFile, &MyDcb )) { printf("Bad GetCommState: %d\n",GetLastError()); exit(1); } printf("GetCommState is ok\n"); // // We've successfully opened the file. Set the state of // the comm device. // MyDcb.BaudRate = 19200; MyDcb.ByteSize = 8; MyDcb.Parity = NOPARITY; MyDcb.StopBits = ONESTOPBIT; MyDcb.XonChar = 20; MyDcb.XoffChar = 25; MyDcb.ErrorChar = 1; MyDcb.EofChar = 2; MyDcb.EvtChar = 3; if (SetCommState( hFile, &MyDcb )) { printf("We successfully set the state of the %s port.\n",MyPort); // // Now we get the comm state again and make sure // the adjusted values are as we like them. // if (!GetCommState( hFile, &GottenDcb )) { printf("Couldn't get the adjusted dcb: %d\n",GetLastError()); exit(1); } else { printf("Got the new state - checking\n"); if (MyDcb.BaudRate != GottenDcb.BaudRate) { printf("MyDcb.BaudRate != GottenDcb.BaudRate: %d %d\n",MyDcb.BaudRate,GottenDcb.BaudRate); } if (MyDcb.ByteSize != GottenDcb.ByteSize) { printf("MyDcb.ByteSize != GottenDcb.ByteSize: %d %d\n",MyDcb.ByteSize,GottenDcb.ByteSize); } if (MyDcb.Parity != GottenDcb.Parity) { printf("MyDcb.Parity != GottenDcb.Parity: %d %d\n",MyDcb.Parity,GottenDcb.Parity); } if (MyDcb.StopBits != GottenDcb.StopBits) { printf("MyDcb.StopBits != GottenDcb.StopBits: %d %d\n",MyDcb.StopBits,GottenDcb.StopBits); } if (MyDcb.XonChar != GottenDcb.XonChar) { printf("MyDcb.XonChar != GottenDcb.XonChar: %d %d\n",MyDcb.XonChar,GottenDcb.XonChar); } if (MyDcb.XoffChar != GottenDcb.XoffChar) { printf("MyDcb.XoffChar != GottenDcb.XoffChar: %d %d\n",MyDcb.XoffChar,GottenDcb.XoffChar); } if (MyDcb.ErrorChar != GottenDcb.ErrorChar) { printf("MyDcb.ErrorChar != GottenDcb.ErrorChar: %d %d\n",MyDcb.ErrorChar,GottenDcb.ErrorChar); } if (MyDcb.EofChar != GottenDcb.EofChar) { printf("MyDcb.EofChar != GottenDcb.EofChar: %d %d\n",MyDcb.EofChar,GottenDcb.EofChar); } if (MyDcb.EvtChar != GottenDcb.EvtChar) { printf("MyDcb.EvtChar != GottenDcb.EvtChar: %d %d\n",MyDcb.EvtChar,GottenDcb.EvtChar); } } } else { DWORD LastError; LastError = GetLastError(); printf("Couldn't set the %s device.\n",MyPort); printf("Status of failed set is: %d\n",LastError); } } } else { DWORD LastError; LastError = GetLastError(); printf("Couldn't open the %s device.\n",MyPort); printf("Status of failed open is: %d\n",LastError); } }
C
/* ============================================================================ Name : for_demo.c Author : J. Kaldeway ============================================================================ */ #include <stdio.h> int main(void) { for(int i = 11; i < 21; i++) { printf("%d ", i * i); } putchar('\n'); int i = 10; while(1) { i++; if(i == 15) { continue; // sla de rest van de lus over } printf("%d ", i * i); if(i == 20) { break; // verlaat de while-opdracht } } }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct{ int registro; // fixo 10 char cod_empregado[10]; char competencia[8]; char cod_evento[4]; int tipo_processo; char valor[9]; char cod_empresa[10]; }Lancamento; typedef struct{ int registro; //fixo 11 int dias_falta; }Falta; void verifica_arquivo(FILE *arquivo) { if(arquivo == NULL){ printf("Erro na abertura do arquivo!"); exit(0); } else{ printf("Arquivo aberto com sucesso!\n\n"); } } void lancamentos_folha(FILE *arquivo, Lancamento *lancamento, int n) { fclose(arquivo); fopen("lancamentos.txt","a"); int i = 0, tam_cod_empregado = 0; printf("\n =========REGISTRO DE LANCAMENTOS========\n\n"); for(i=1;i<=n;i++){ printf("Digite o codigo do empregado %d:\n", i); fflush(stdin); scanf("%s",&lancamento[i].cod_empregado); tam_cod_empregado = strlen(lancamento[i].cod_empregado); printf("Digite a data, formato 'AAAAMM'\n"); fflush(stdin); scanf("%s",&lancamento[i].competencia); printf("Digite o codigo do evento 'Rubrica'\n"); fflush(stdin); scanf("%s",&lancamento[i].cod_evento); printf("Digite o codigo do tipo de processo '11 - folha mensal'\n"); fflush(stdin); scanf("%d",&lancamento[i].tipo_processo); printf("Digite o valor Valor\n"); fflush(stdin); scanf("%s",&lancamento[i].valor); printf("Digite o codigo da empresa\n"); scanf("%s",&lancamento[i].cod_empresa); fflush(stdin); lancamento[i].registro = 10; fprintf(arquivo, "%d", lancamento[i].registro); fprintf(arquivo, "%010s", lancamento[i].cod_empregado); fprintf(arquivo, "%s", lancamento[i].competencia); fprintf(arquivo, "%04s", lancamento[i].cod_evento); fprintf(arquivo, "%d", lancamento[i].tipo_processo); fprintf(arquivo, "%09s", lancamento[i].valor); fprintf(arquivo, "%010s\n", lancamento[i].cod_empresa); } } void registro_faltas(FILE *arquivo, Falta *falta, int n){ fclose(arquivo); fopen("lancamentos.txt","a"); int i; printf("\n========REGISTRO DE FALTAS=========\n\n"); for(i=1;i<=n;i++){ printf("Digite a data da falta - FORMATO = 'AAAAMMDD'\n"); scanf("%d",&falta[i].dias_falta); fflush(stdin); falta[i].registro = 11; fprintf(arquivo, "%d", falta[i].registro); fprintf(arquivo, "%d\n", falta[i].dias_falta); } } void analisa_arquivo(FILE *arquivo){ fclose(arquivo); fopen("lancamentos.txt","r"); char texto[200]; printf("\n=============ANALISE DO ARQUIVO=============\n\n"); while(fgets(texto, 100, arquivo) != NULL){ printf("%s", texto); } } void menu(FILE *arquivo, Lancamento *lancamento, Falta *falta, int n){ int opcao; do { printf("\n========Escolha a opcao abaixo:=========\n\n"); printf("1 - REGISTRO DE LANCAMENTOS\n"); printf("2 - REGISTRO DE DIAS DE FALTAS\n"); printf("3 - ANALISE DO ARQUIVO\n"); printf("4 - GRAVAR E SAIR\n"); fflush(stdin); scanf("%d", &opcao); switch (opcao) { case 1 : lancamentos_folha(arquivo, lancamento, n);; break; case 2 : registro_faltas(arquivo, falta, n); break; case 3 : analisa_arquivo(arquivo); break; case 4 : printf("\n\nArquivo Salvo com sucesso!\n"); printf("Saindo do programa\n..."); fclose(arquivo); break; default : printf("Opcao invalida\n\n"); } } while (opcao != 4); } int main() { FILE *arquivo; arquivo = fopen("lancamentos.txt","a"); verifica_arquivo(arquivo); Lancamento lancamento[50]; Falta falta[50]; menu(arquivo, lancamento, falta, 1); }
C
#ifndef MJ808_BUTTON_C_ #define MJ808_BUTTON_C_ #include "mj808\mj808.h" #include "button\button_types_actual.c" // various __*button_t types - for convenience in one place for all LED devices extern void _debounce(__individual_button_t *in_button, event_handler_t * const in_event); // wrapper function for the debouncer static void _debounce_wrapper() { _debounce(&__Button.__button[Center], EventHandler); // one button -> no loop: call directly }; static uint8_t __ButtonCenterCaseTable[] = // array value at position #foo gets passed into __mjxxx_button_execution_function, where it is evaluated in a switch-case statement { 0x00, // 0 - not defined 0x00, // 1 - not defined 0x02, // 2 - jump case 0x02 - button Hold 0x01, // 3 - jump case 0x01 - error event }; static __individual_button_t __button_actual[] = // instantiate array of actual button struct { // index 0 - that one button... { .__PIN = (uint8_t *) 0x30, // 0x020 offset plus address - PIND register .__pin_number = 4, // sw1 is connected to pin D4 .__ButtonCaseptr = __ButtonCenterCaseTable // button press-to-case binding } }; // implementation of virtual constructor for buttons static button_t *_virtual_button_ctorMJ808() { __Button.__button = __button_actual; // assign pointer to button array __Button.__button_count = 1; // how many buttons are on this device? __Button.public.button = &__button_actual[Center].public; // pointer to public members of button actual __Button.public.deBounce = &_debounce_wrapper; // tie in debounce function return &__Button.public; // return address of public part; calling code accesses it via pointer }; #endif /* MJ808_BUTTON_C_ */
C
#include<stdio.h> #include<stdlib.h> #include"handlers.h" /*1. Declaration of global variable*/ char audioname[100]; /*5. A funtion to take care of showing an audiofile or saving an audiofile*/ void handleMenuEvent(int choice) { /*6. To take the input from user*/ printf("enter the audio filename "); scanf("%s",audioname); /*7. To get the output from choosen choice*/ switch(choice){ case 1: vdrawAudio(audioname); break; case 2: vsaveAudio(audioname); break; } printf("---------------------------------------\n"); } /*8. A funtion to display choices and call handleMenuEven funtion*/ void displayMenu() { int choice; /*3. To take the input from user*/ while(1) { printf("1.Show an Audiofile\n"); printf("2.Save an Audiofile\n"); printf("3.Exit\n"); printf("choice\n"); scanf("%d",&choice); if(choice>=3) exit(0); /*4. Calling funtion*/ handleMenuEvent(choice); } } int main() { /*2. calling a funtion*/ displayMenu(); return 0; }
C
/* name.c */ #include <ctype.h> /* isalpha */ #define NAME_SIZE_MAX 20 static char** name_list; static unsigned int name_count; static char* name_new(const char* name) { char* newName = malloc(sizeof (char) * NAME_SIZE_MAX +1); assert(newName); memset(newName, '\0', NAME_SIZE_MAX +1); memcpy(newName, name, NAME_SIZE_MAX); /* truncates long names */ name_list = realloc(name_list, (name_count +1) * sizeof (char*)); assert(name_list); name_list[name_count] = newName; return name_list[name_count++]; } static int name_delete(const char* name) { unsigned int i; for ( i=0; i<name_count; i++ ) if ( !strcmp(name, name_list[i]) ) { free(name_list[i]); for ( ; i<name_count-1; i++ ) name_list[i] = name_list[i+1]; name_count--; return 0; /* list collapsed over name */ } return -1; /* no such name */ } static int name_check(const char* name) { unsigned int i; char* checkedName; if ( !name || !strcmp(name, "") ) return -4; /* no null or empty */ if ( name[0] == 32 ) return -5; /* cannot start with a space */ for ( i=0; i<name_count; i++ ) if ( !strcmp(name, name_list[i]) ) return -3; /* name taken */ checkedName = name_new(name); if ( strcmp(checkedName, name) ) return -2; /* name was truncated because it was too long */ name_delete(checkedName); for ( i=0; i<strlen(name); i++ ) /* check for illegal chars */ if ( !isalpha(name[i]) && name[i] != 32 ) return -1; return 0; /* name is OK to use */ } /* end of file */
C
#include "stdio.h" #include "string.h" /* all calls are assumed to be written to the same file, unless the name changes */ static char gPreviousfile[2048]=""; static FILE *gFp = NULL; FILE *inventor_openfile(char *filename) { if (!gFp || strncmp(gPreviousfile, filename, 2048)) { strncpy(gPreviousfile, filename, 2047); if (gFp) { fclose(gFp); } gFp = fopen(filename, "w"); if (!gFp) { printf("Error in drawhex: could not open file %s\n", filename); } else { fprintf(gFp, "#Inventor V2.0 ascii\n"); fprintf(gFp, "Environment { ambientIntensity 1.1 \n"); fprintf(gFp, "ambientColor 1 1 1}\n"); } } return gFp; } int inventor_comment(char *filename, char *comment) { FILE *fp = inventor_openfile(filename); if (!fp) return 1; fprintf(gFp, "# %s\n", comment); return 0; } /* draw a hexahedron in Inventor 2.0 ascii format (use ivview to view). If same filename is given as previous, then just continues writing in the previous file. Else opens a new file. If x,y,z given, then assumes x, y and z are allocated to hold 8 floats each, one for each vertex, in standard HAR node configuration (0,1,2,3 on bottom, 4,5,6,7 on top, bottom and top nodes ordered so that bottom face has normal pointing IN by right hand rule and top face normal points out, and draws that hex. color is RGB float triplet, if color is NULL, then just use white return 0 if success */ int inventor_drawhex(char *filename, double *x, double *y, double *z, float *color) { float default_color[3] = {1,1,1}; int i=0; FILE *fp = inventor_openfile(filename); if (!fp) return 1; if (!x || !y || !z) { return 0; } fprintf(fp, "Separator {\n"); fprintf(fp, "DrawStyle { style LINES }\n"); if (!color) color = default_color; fprintf(fp, "Material { ambientColor %f %f %f\n", color[0], color[1], color[2]); fprintf(fp, "\tdiffuseColor 0 0 0 }\n"); fprintf(fp, "Coordinate3 { point [\n"); for (i=0; i<8; i++) { fprintf(fp, "%g %g %g,\n", x[i], y[i], z[i]); /* commas */ } /*fprintf(fp, "%g, %g, %g\n", x[i], y[i], z[i]); no comma */ fprintf(fp, " ] }\n"); fprintf(fp, "IndexedFaceSet { coordIndex [\n"); fprintf(fp, "0,1,2,3,-1,\n"); fprintf(fp, "4,7,6,5,-1,\n"); fprintf(fp, "0,4,5,1,-1,\n"); fprintf(fp, "1,5,6,2,-1,\n"); fprintf(fp, "2,6,7,3,-1,\n"); fprintf(fp, "3,7,4,0,-1,\n"); fprintf(fp, "] } }"); fprintf(fp, "\n"); return 0; } /* same as drawhex, but make a tet (duh), use four nodes instead of 8, duh -- again, assume base normal faces inward by right hand rule, but it really doesn't matter AFAICT */ int inventor_drawtet(char *filename, double *x, double *y, double *z, float *color) { float default_color[3] = {1,1,1}; int i=0; FILE *fp = inventor_openfile(filename); if (!fp) return 1; if (!x || !y || !z) { return 0; } fprintf(fp, "Separator {\n"); fprintf(fp, "DrawStyle { style LINES }\n"); if (!color) color = default_color; fprintf(fp, "Material { ambientColor %f %f %f\n", color[0], color[1], color[2]); fprintf(fp, "\tdiffuseColor 0 0 0 }\n"); fprintf(fp, "Coordinate3 { point [\n"); for (i=0; i<4; i++) { fprintf(fp, "%g %g %g,\n", x[i], y[i], z[i]); /* commas */ } fprintf(fp, " ] }\n"); fprintf(fp, "IndexedFaceSet { coordIndex [\n"); fprintf(fp, "0,1,2,-1,\n"); fprintf(fp, "0,3,1,-1,\n"); fprintf(fp, "1,3,2,-1,\n"); fprintf(fp, "0,2,3,-1,\n"); fprintf(fp, "] } }"); fprintf(fp, "\n"); return 0; } /* draw a polygon of numnodes, positions given by x,y,z, if color is NULL, then white*/ int inventor_drawpolygon(char *filename, double *x, double *y, double *z, int numnodes, float *color) { float default_color[3] = {1,1,1}; int i=0; FILE *fp = inventor_openfile(filename); if (!fp) return 1; if (!x || !y || !z) { return 0; } fprintf(fp, "Separator {\n"); fprintf(fp, "DrawStyle { style LINES }\n"); if (!color) color = default_color; fprintf(fp, "Material { ambientColor %f %f %f\n", color[0], color[1], color[2]); fprintf(fp, "\tdiffuseColor 0 0 0 }\n"); fprintf(fp, "Coordinate3 { point [\n"); for (i=0; i<numnodes; i++) { fprintf(fp, "%g %g %g,\n", x[i], y[i], z[i]); /* commas */ } fprintf(fp, " ] }\n"); fprintf(fp, "IndexedFaceSet { coordIndex [\n"); for (i=0; i< numnodes; i++) { fprintf(fp, "%d, ", i); } fprintf(fp, "0 -1, \n"); fprintf(fp, "] } }"); fprintf(fp, "\n"); return 0; } /* draw an X at the given point */ int inventor_drawXatPoint(char *filename, double x, double y, double z, float size, float *color) { float default_color[3] = {1,1,1}; FILE *fp = inventor_openfile(filename); if (!fp) return 1; fprintf(fp, "Separator {\n"); fprintf(fp, "DrawStyle { style LINES }\n"); if (!color) color = default_color; fprintf(fp, "Material { ambientColor %f %f %f\n", color[0], color[1], color[2]); fprintf(fp, "\tdiffuseColor 0 0 0 }\n"); fprintf(fp, "Coordinate3 { point [\n"); fprintf(fp, "%g %g %g,\n", x+size, y, z+size); /* commas */ fprintf(fp, "%g %g %g,\n", x+size, y, z-size); /* commas */ fprintf(fp, "%g %g %g,\n", x-size, y, z+size); /* commas */ fprintf(fp, "%g %g %g,\n", x-size, y, z-size); /* commas */ fprintf(fp, "%g %g %g,\n", x,y, z); /* commas */ fprintf(fp, " ] }\n"); fprintf(fp, "IndexedFaceSet { coordIndex [\n"); fprintf(fp, "0,1,4-1\n"); fprintf(fp, "0,3,4 -1,\n"); fprintf(fp, "2,1,4 -1,\n"); fprintf(fp, "2,3,4 -1,\n"); fprintf(fp, "] } }"); fprintf(fp, "\n"); return 0; }
C
/** * 查找 */ #include <stdio.h> #include <stdlib.h> // 有哨兵顺序查找 int Sequential_Search(int *a, int n, int key) { int i; a[0] = key; // 哨兵 i = n; // 循环从尾部开始 while(a[i] != key) i--; return i; // 返回0,没找到 } // 二分查找 int Binary_Search(int *a, int n, int key) { int low, high, mid; low = 1; // 定义最低下标为记录首位 high = n; // 定义最高下标为记录末尾 while(low <= high) { mid = (low+high) / 2; // 折半 // mid = low + (high - low) * (key - a[low]) / (a[high] - a[low]); // 插值查找 if (key < a[mid]) // 若查找值比中值小 high = mid - 1; // 最高下标调整到中位下标小一位 else if(key > a[mid]) // 若比中值大 low = mid + 1; // 最低下标调整到中位下标大一位 else return mid; // 找到的位置 } return 0; } // 斐波那契查找 int Fibonacci_Search(int *a, int n, int key) { int F[30] = {1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368}; int low, hight, mid, i, k; low = 1; hight = n; k = 0; while(n > F[k]- 1) // 计算n位于斐波那契数列中的位置 k++; for(i = n; i < F[k] - 1; i++) // 将不满的数值补全 a[i] = a[n]; while(low <= hight) { mid = low + F[k-1]-1; // 计算当前分隔的下标 if(key < a[mid]) // 若查找记录小于当前分隔记录 { hight = mid - 1; // 若查找记录小于当前分隔记录 k = k - 1; // 斐波那契数列下标减一位 } else if(key > a[mid]) // 若查找记录大于当前分隔记录 { low = mid + 1; // 最低下标调整到分隔下标mid+1处 k = k - 2; // 斐波那契数列下标减两位 } else { if(mid <= n) return mid; // 若相等则说明mid即为查找的位置 else return n; // 若 mid > n 说明是补全数值,返回 n } } }
C
/*--- CCITTOTF.C ------------------------- Listing 10-4 ------- * Compute CCITT-CRC on-the-fly. * Usage: ccittotf filename * * Based on a similar program by Nigel Cort in C Gazette 5.1 * (Autumn 1990). *------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #define DRIVER 1 /* DRIVER includes the file processing */ /* Compute single-byte CRC-CCITT on-the-fly */ unsigned short GetCCITT ( unsigned short crc, unsigned short ch ) { static unsigned int i; ch <<= 8; /* Move to MSB */ for ( i = 8; i > 0; i-- ) /* Go through 8 bits */ { if ( (ch ^ crc) & 0X8000 ) /* Perform CRC calc. */ crc = ( crc << 1 ) ^ 0x1021; else crc <<= 1; ch <<= 1; } return ( crc ); } #ifdef DRIVER int main ( int argc, char * argv[] ) { FILE *fin; /* file we're reading into buffer */ char *buffer; /* buffer we're working on */ size_t i, j; /* counters of bytes in buff */ unsigned short crc; /* the CRC value being computed */ if ( argc < 2 ) { fprintf ( stderr, "Error! Must specify filename.\n" ); return ( EXIT_FAILURE ); } if (( fin = fopen ( argv[1], "rb" )) == NULL ) { fprintf ( stderr, "Cannot open %s", argv[1] ); return ( EXIT_FAILURE ); } /*-------------------------------------------------- * Set up a very large input buffer of 32K bytes. * This program does no good if it doesn't fly! *-------------------------------------------------*/ if (( buffer = (char *) malloc ( 32766 )) == NULL ) { fprintf ( stderr, "Out of memory\n" ); return ( EXIT_FAILURE ); } crc = 0; for (;;) { i = fread ( buffer, 1, 32766, fin ); if ( i == 0 ) { if ( feof ( fin )) /* we're done, so show results */ { printf ( "CCITT CRC for %s is %04X\n", argv[1], crc ); return ( EXIT_SUCCESS ); } else /* read another 32K of file */ continue; } for ( j = 0 ; j < i; j ++ ) /* loop through the buffer */ crc = GetCCITT ( crc, buffer [j] ); } } #endif
C
#include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <stdio.h> //int a=10; //int b=20; main() { int a=10; int b=20; int semid,pid,i; struct sembuf sop; semid=semget(0x20,1,IPC_CREAT|0666); pid=fork(); if(pid==0) { sleep(5); printf("child before semop\n"); sop.sem_num=0; sop.sem_op=0; sop.sem_flg=0; semop(semid,&sop,1); for(i=0;i<10;i++) { printf("%d\n",a); } printf("child over\n"); } else { printf("parent before 1st semctl\n"); semctl(semid,0,SETVAL,1); printf("parent sleeping\n"); sleep(3); printf("parent before 2nd semctl\n"); semctl(semid,0,SETVAL,0); for(i=0;i<10;i++) { printf("%d\n",b); } printf("parent over\n"); } }
C
#include <stdio.h> #include <sys/syscall.h> #include <unistd.h> #include <sys/mman.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> /** * munmap 卸载通过 mmap 映射的内容 * @tags 系统调用函数 */ int munmap(void *addr, unsigned long len) { return syscall(SYS_munmap, addr, len); } int main(int argc, const char* argv[]) { if (argc < 2) { fprintf(stderr, "Need at least one argument to write to the file\n"); exit(EXIT_FAILURE); } size_t textsize = strlen(argv[1]) + 1; // 以仅写权限打开一个文件, 如果不存在则创建 const int fd = open("file", O_CREAT | O_RDWR, (mode_t)0600); if (fd == -1) { perror("Error opening file for writing"); exit(EXIT_FAILURE); } // 为文件分配物理页 if (write(fd, "", textsize) == -1) { close(fd); perror("Error writing last byte of the file"); exit(EXIT_FAILURE); } // 将文件通过 mmap 映射到仅写权限的内存中 char* buffer = mmap( NULL, textsize, PROT_WRITE | PROT_READ, MAP_SHARED, fd, 0 ); if (buffer == (char*)-1) { perror("mmap"); return -1; } strcpy(buffer, argv[1]); // 卸载映射的内存 if (munmap(buffer, textsize) == -1) { close(fd); perror("Error un-mmapping the file"); exit(EXIT_FAILURE); } return 0; }
C
#include <stdio.h> #include <ctype.h> #include <string.h> #include "fcgios.h" #define HGH_DBG(fmt, args...) printf("\033[40;33m HGH_DBG(%s %s %d):\t\033[0m"fmt, __FILE__, __func__, __LINE__, ## args) const char *unixPath = "/tmp/fcgi.sock"; int main(int argc, char const *argv[]) { int listenFd; char buf[1024]; int n; int i; // 1. create unix fd listenFd = OS_CreateLocalIpcFd(unixPath, 100); // 2. accept while (1) { int connFd; connFd = OS_Accept(listenFd, 1, NULL); if (connFd < 0) { HGH_DBG("Aceep Failed![%d]\n", connFd); break; } while (1) { memset(buf, 0, sizeof(buf)); n = OS_Read(connFd, buf, sizeof(buf)); if (n < 0) { perror("read error"); break; } else if(n == 0) { printf("EOF\n"); break; } HGH_DBG("Received: %s\n", buf); // for(i = 0; i < n; i++) { // buf[i] = toupper(buf[i]); // } OS_Write(connFd, buf, n); } OS_Close(connFd, 0); } // 3. close unix fd OS_Close(listenFd, 1); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "tree_function.h" #include "lifegame.h" #include "kadai2_ext.h" void init_cells(FILE *fp) { int w, h; char tmp[WIDTH+10]; if (fp == NULL) { for (w = 0; w < WIDTH; w++) { for (h = 0; h < HEIGHT; h++) { cells[h][w] = rand() % 2; } } } else { for (h = 0; fgets(tmp, WIDTH+10, fp) != NULL && h < HEIGHT; h++) { for (w = 0; tmp[w] != '\n' && w < WIDTH; w++) { cells[h][w] = (tmp[w] == '#') ? 1 : 0; } for (; w < WIDTH; w++) { cells[h][w] = 0; } } } for (; h < HEIGHT; h++) { for (w = 0; w < WIDTH; w++) { cells[h][w] = 0; } } } int number_life() { int life_num = 0; int i, j; for (i = 0; i < HEIGHT; i++) { for (j = 0; j < WIDTH; j++) { if (cells[i][j] != 0) { life_num++; } } } return life_num; } void plot_cells(FILE *p, int step) { int i, j; fprintf(p, "set title 'generation=%d'\n", step); fprintf(p, "plot '-' using 1:2 with points pt 5 ps 1\n"); for (i = 0; i < HEIGHT; i++) { for (j = 0; j < WIDTH; j++) { if (cells[i][j] == 1) { fprintf(p, "%d\t%d\n", j, i); } } } fprintf(p, "e\n"); } void update_cells(Node *rule) { int i, j; int new_cells[HEIGHT][WIDTH]; for (i = 0; i < HEIGHT; i++) { for (j = 0; j < WIDTH; j++) { new_cells[i][j] = calculate(rule, i, j); } } for (i = 0; i < HEIGHT; i++) { for (j = 0; j < WIDTH; j++) { cells[i][j] = new_cells[i][j]; } } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_cd_check.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: yjacques <yjacques@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/06/25 15:11:52 by yjacques #+# #+# */ /* Updated: 2014/06/25 15:11:53 by yjacques ### ########.fr */ /* */ /* ************************************************************************** */ #include <sys/stat.h> #include <unistd.h> #include <libft.h> #include <ftsh.h> #include <ftcd.h> int ft_cd_check(char *path) { struct stat infos; if (!path || ft_strlen(path) == 0) return (1); if (stat(path, &infos) < 0) return (ft_error("cd", "no such file or directory", path)); if (!S_ISDIR(infos.st_mode)) return (ft_error("cd", path, "is not a directory.")); if (access(path, F_OK) < 0) return (ft_error("cd", "permission denied", path)); if (chdir(path) < 0) return (ft_error("cd", "can not open directory", path)); return (0); }
C
/** ****************************************************************************** * @file led.c * @author LGG * @version V1.0.0 * @date 15-July-2019 * @brief This file is LED related functions. ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "led.h" /** * @brief LED Initialize * @param None * @retval None */ void LED_Init(void) { /* Initialize P1 as push-pull putput */ P1M0 = 0xff; P1M1 = 0x00; P1 = 0xff; /* Initialize P5^5 as push-pull putput */ P5M0 |= 0x20; P5M0 &= 0xdf; P55 = 0; } /** * @brief LED Flashing from left to right * @param None * @retval None */ void blink_left_to_right(void) { /* Initialize variables */ static unsigned char i = 0; static unsigned char temp = 0x80; /* Variable increase and prevent cross-border */ if(++i > 7) { i = 0; temp = 0x80; } /* Output and shifting */ P1 = ~temp; temp >>= 1; } /** * @brief LED Flashing from right to left * @param None * @retval None */ void blink_right_to_left(void) { /* Initialize variables */ static unsigned char i = 0; static unsigned char temp = 0x01; /* Variable increase and prevent cross-border */ if(++i > 7) { i = 0; temp = 0x01; } /* Output and shifting */ P1 = ~temp; temp <<= 1; } /** * @brief LED Flashing from inside to outside * @param None * @retval None */ void blink_inside_to_outside(void) { /* Initialize variables */ static unsigned char i = 0; static unsigned char temp_1 = 0x08; static unsigned char temp_2 = 0x10; /* Output and shifting */ P1 = ~((temp_2 << i) | (temp_1 >> i)); /* Variable increase and prevent cross-border */ if(++i > 3) { i = 0; temp_1 = 0x08; temp_2 = 0x10; } } /** * @brief LED Flashing from outside to inside * @param None * @retval None */ void blink_outside_to_inside(void) { /* Initialize variables */ static unsigned char i = 0; static unsigned char temp_1 = 0x01; static unsigned char temp_2 = 0x80; /* Output and shifting */ P1 = ~((temp_2 >> i) | (temp_1 <<i)); /* Variable increase and prevent cross-border */ if(++i > 3) { i = 0; temp_1 = 0x01; temp_2 = 0x80; } } /** * @brief According to the mode to determine the LED flashing mode * @param None * @retval None */ void led_mode_handle(en_led_mode mode) { /* Initialize variables */ static unsigned char i; if(++i > 200) i = 1; switch(mode) { case LED_MODE_0: //MODE0 break; //None case LED_MODE_1: //MODE1 blink_left_to_right(); //LED Flashing from left to right break; case LED_MODE_2: //MODE2 blink_right_to_left(); //LED Flashing from right to left break; case LED_MODE_3: //MODE3 if(i%2) blink_inside_to_outside(); //LED Flashing from inside to outside break; case LED_MODE_4: //MODE4 if(i%2) blink_outside_to_inside(); //LED Flashing from outside to inside break; default: //Other P1 = 0xff; //LED all exterminate break; } }
C
#include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdlib.h> #include <string.h> #include "../include/types.h" #define MSGKEY 90 /* chiave per la coda */ //#define MSGTYPE 1 /* tipo per il messaggio da inviare */ int main(int argc, char *argv[]) { /* puntatore alla struttura che rappresenta il messaggio. Il messaggio definito nel file def.h */ struct Message *m; int msgid; /* identificatore della coda */ char c = 'S'; /* allocazione memoria per il messaggio */ m = (struct Message *) malloc(sizeof(struct Message)); /* apertura della coda di messaggi corrispondente alla chiave MSGKEY */ if((msgid = msgget(MSGKEY, 0666)) == -1) { perror("Apertura della coda di messaggi fallita.\n"); exit(1); } int l=0; /* il processo cicla finch l'utente vuole inviare nuovi messaggi al server */ while(c == 'S' || c == 's') { long int tp; printf("Scegliere il tipo di messaggio: "); scanf("%li", &tp); /* creazione del messaggio da inviare */ m->mtype = tp; printf("tp vale: %li\n", m->mtype); printf("Scrivo: ciao %i\n", l); strcpy(m->text, "ciao"); /* la system call msgsnd spedisce il messaggio memorizzato nel buffer m verso la coda msgid. Il terzo parametro della funzione rappresenta la dimensione del messaggio ad esclusione dello spazio necessario a contenere il campo mtype della struttura. L'ultimo parametro indica che il processo deve rimanere in attesa se la coda piena finche' si libera spazio per inserire il messaggio. Vedere man msgsnd. */ if(msgsnd(msgid, m, sizeof(struct Message) - sizeof(m->mtype), 0) == -1) { perror("msgsnd"); exit(1); }; /* all'utente viene chiesto se vuole inviare un nuovo messaggio */ do { c = getchar(); printf("Altro messaggio? [S/N] "); c = getchar(); } while (c != 's' && c != 'n' && c != 'S' && c != 'N'); } return 0; }
C
#include <stdio.h> void one(void); void two(void); void main(void) { one( ); two( ); } void one() { int a=5,b=7; printf("A = %d, B = %d\n",a,b); } void two() { float p=4.5,q=3.5; printf("P = %6.2f, Q = %6.2f\n",p,q); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct Node { int row; int col; int level; // } TreeNode ; int main(){ //TRYING TO INPUT FILE* fin; fin= fopen("prefSum.txt", "r"); char buff[255]; int n; fscanf(fin, "%s", buff); n = atoi(buff); int t; int rows = (int)(log(n)/log(2.0)) + 1;//fix this later int tree[rows][n]; int l; int c; for(l = 1; l <=n; l++){ fscanf(fin, "%s", buff); tree[0][l] = atoi(buff); //printf("%d %d\n", tree[0][l], l); } //MAKES THE TREE for(int r = 1; r <= rows; r++){//start on the second to last row double cMax = pow(2, r); int end = (int)(n/pow(2.0, r)); #pragma omp parallel for private(c, t) for(c = 1; c <= end; c++){ t = c; tree[r][c]=tree[r-1][2*c-1] + tree[r-1][2*c]; //printf("%d\n", tree[r][c]); } } //TRIES TO SOLVE THE PREFIX int prefixSum[rows][n]; for(int r = rows; r>= 0; r--){ int end = (int)(n/pow(2.0, r)); #pragma omp parallel for private(c, t) for(c = 2; c <=end; c+=2){ t = c; prefixSum[r][c] = prefixSum[r+1][c/2]; } prefixSum[r][1] = tree[r][1]; #pragma omp parallel for private(c, t) for(c = 3; c <= end; c+=2){ t = c; prefixSum[r][c] = prefixSum[r+1][(c-1)/2]+tree[r][c]; } } //OUTPUT //#pragma omp parallel for private(c, t) for(int c = 1; c <=n; c++){ //t = c; printf("%d\n", prefixSum[0][c]); } //xmt pdf on website starting at page 20 /* 1. start with the operator (min) 2. prefix sum (prefix min) 3. pardo (parallel do) a. openMP - # program b. for loop for the levels --> don't do parallel c. cuDa - <<< >>>--> transfer data */ return 0; }
C
#include<stdio.h> #include<unistd.h> #include<stdlib.h> #include <sys/types.h> #include <sys/wait.h> int main(void) { pid_t pid; if ((pid = fork()) < 0) { printf("fork error"); } else if (pid == 0) { /*WAIT_PARENT(); parent goes first */ int gid=setsid(); if(gid==getpid()) printf("child: uid=>%d gid=>%d EQUAL And my session is %d \n",getpid(),gid,getsid(0)); } else { /*charatatime("output from parent\n");*/ waitpid(pid,NULL,0); printf("parent: child pid= %d my session id is %d \n",pid,getsid(0)); } return(0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_vecpush.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mbartole <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/12/03 17:58:28 by ehugh-be #+# #+# */ /* Updated: 2019/07/11 15:10:34 by mbartole ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" /* ** Add data of size s to the end of the vector resizing vector if needed. ** @param vec - vector to push data into ** @param data - data to be added to vector ** @param s - size of data to be added ** @return vector with added data it may be new vector */ t_vector *ft_vecpush(t_vector *vec, void *data, size_t s) { unsigned int it; if (!vec) return (t_vector*)(NULL); if (!data || !s) return (vec); it = vec->cap; while (s > it - vec->len) it *= 2; if ((it > vec->cap) && !(vec = ft_vecgrow(vec, it))) return (NULL); ft_memcpy(vec->data + vec->len, data, s); vec->len += s; vec->cap = it; return (vec); } /* ** Add data of size less or equals to long into vec (may be useful to insert ** constants or enums to vectors without need to create additional variable) ** ** @param vec - vector to push data into ** @param data - data to be added to vector ** @param s - size of data to be added ** @return - vector with added data it may be new vector */ t_vector *ft_vecpush_small(t_vector *vec, long data, size_t s) { return (ft_vecpush(vec, &data, s)); }
C
/* * Use the power of pointer arithmetic to mend a broken heart. * This function will skip the first six characters of the text message. */ #include <stdio.h> #include <stdlib.h> int main() { char *msg_from_amy = "Don't call me"; skip(msg_from_amy); return 0; } int skip(char *msg) { puts(msg + 6); return 0; } /* * C Header files: * http://en.cppreference.com/w/c/header * The C Preprocessor: * https://gcc.gnu.org/onlinedocs/gcc-3.0.2/cpp.html#SEC_Top */
C
#include<stdio.h> #include<conio.h> #include<math.h> #include<string.h> char * get_the_string(char * x){ return x; } int main(){ char Str[] = "Hello!"; char *a = get_the_string(Str); printf("%s" , a); getch(); return 0; }
C
#include "ft_printf.h" void treat_dec(va_list args, int *counter) { int num; char* str_num; int is_minus; is_minus = 0; size_t i; size_t len; i = 0; num = va_arg(args,int); if(num < 0) { is_minus = 1; num *= -1; } str_num = ft_ull_base(num,10); if(is_minus) str_num = ft_strjoin("-",str_num); len = ft_strlen(str_num); *counter += (int)len; while(i < len){ write(1,&str_num[i],1); i++; } free(str_num); } // int variadic(char *str,...) // { // va_list args; // va_start(args, str); // treat_dec(args); // return 0; // } // int main() // { // variadic("hello",-244452); // return(0); // }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #define DEFAULT_PORT 8000 #define MAXLINE 4096 int main(int argc, char** argv) { int sockHandle, conn; int port = -1; struct sockaddr_in servaddr; char sendBuff[4096], recvBuff[4086]; int msglen; if(argc != 2) { printf("need <listen port(1024~65535)>\n"); exit(0); } port = atoi(argv[1]); if(port < 1024 || port > 65535) { printf("invalid port, 1024~65535 is recommended.\n"); exit(0); } // ʼ if((sockHandle = socket(AF_INET, SOCK_STREAM, 0)) < 0) { // һ0ԶѡЭ printf("create socket error: %s(errno: %d)\n", strerror(errno), errno); exit(0); } // øö˿ int flag = 1; if (setsockopt(sockHandle, SOL_SOCKET, SO_REUSEPORT, &flag, sizeof(flag)) < 0) { perror("setsockopt error"); } // servaddrʼ memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY);//IPַóINADDR_ANY,ϵͳԶȡIPַ if(port > 0) servaddr.sin_port = htons(port);//õĶ˿Ϊs else servaddr.sin_port = htons(DEFAULT_PORT);//õĶ˿ΪDEFAULT_PORT // صַ󶨵socket if(bind(sockHandle, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) { printf("bind socket error: %s(errno: %d)\n", strerror(errno), errno); exit(0); } // if(listen(sockHandle, 10) < 0) { // ڶΪŶӵ printf("listen socket error: %s(errno: %d)\n", strerror(errno), errno); exit(0); } printf("waiting......\n"); // struct sockaddr_in cliaddr; socklen_t clilen = sizeof(cliaddr); if((conn = accept(sockHandle, (struct sockaddr*)&cliaddr, &clilen)) < 0) { printf("accept socket error: %s(errno: %d)\n", strerror(errno), errno); exit(0); // continue; } //ͻ˵ַ char ipbuff[INET_ADDRSTRLEN + 1] = {0}; inet_ntop(AF_INET, &cliaddr.sin_addr, ipbuff, INET_ADDRSTRLEN); uint16_t cli_port = ntohs(cliaddr.sin_port); printf("connection from %s, port %d\n", ipbuff, cli_port); // ȡsockӦں˽ջС int optVal = 0; int optLen = sizeof(optVal); getsockopt(conn, SOL_SOCKET, SO_RCVBUF, (char*)&optVal, &optLen); printf("sockServer, old recv buf is %d\n", optVal); // 8192 // sockServerӦں˽ջС optVal = 1024*1024; setsockopt(conn, SOL_SOCKET, SO_RCVBUF, (char*)&optVal, optLen); printf("set sockServer buf for %d\n", optVal); // ȡsockServerӦں˽ջС getsockopt(conn, SOL_SOCKET, SO_RCVBUF, (char*)&optVal, &optLen); printf("sockServer, new recv buf is %d\n", optVal); // 1024 getchar(); // read int n = 0; while(1){ if((msglen = read(conn, recvBuff, 1000)) <= 0) { printf("read socket error: (errno: %d)\n", msglen); exit(0); } else { n += 1000; recvBuff[msglen] = '\0'; printf("read from client %d bytes\n", n); getchar(); } } printf("Socket closed\n"); close(conn); close(sockHandle); return 0; }
C
#include <stdio.h> #define _XOPEN_SOURCE #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> //#include <Linux/limits.h> #include <time.h> #include <pty.h> // for openpty() & forkpty() #include <utmp.h> // for login_pty int main(int argc, char *argv[]) { int rtnVal = 0; int mpty, spty, c=0, dev=0; int in, out; char *pName=NULL; char ptyBuff[100]={'\0'}; char sptyname[20]={'\0'}; pid_t fpid; rtnVal = openpty(&mpty, &spty, sptyname, NULL, NULL); if(rtnVal != -1) { // pName = ptsname(mpty); // printf("slave name is %s, fd = %d.\n", pName, spty); // strcpy(sptyname, pName); printf("my sptyname is %s.\n", sptyname); /* * test write to and read from spty. */ char temp[50] = {"hello world!\n"}; char temp2[100] = {'\0'}; c = write(mpty, temp, strlen(temp)); if(c <= 0) { printf("error.\n"); } sleep(1); printf("write %d charactor to mpty.\n", c); sleep(1); printf("try to read from mpty.\n"); sleep(1); c = read(spty, temp2, strlen(temp)); if(c <= 0) { printf("error.\n"); } printf("read fro mpty %d charactors success.\n", c); printf("/n %s", temp2); /* * end */ /* * open file. */ in = open("input", O_RDWR); out = open("output", O_RDWR); /* * end */ char * temp3; char temp4[200] = {'\0'}; fpid = fork(); if(fpid<0) { printf("fail!\n"); } else if(fpid == 0) { dup2(spty, STDIN_FILENO); dup2(spty, STDOUT_FILENO); //dup2(mpty, STDERR_FILENO); close(mpty); printf("child\n"); //execl("/bin/sh", "sh", "-c", "vim file", (char *)0); execl("/bin/sh", "sh", "-c", "ls", (char *)0); //c = read(spty, temp3, strlen(temp3)); } else { //temp3 = ":wq\n"; //c = write(mpty, temp3, strlen(temp)); sleep(1); while(c = read(mpty, temp4, 200)) { //c = read(mpty, temp3, 100); //must use char temp4 = {'\0'}; //instead of char * temp3; printf("parent.\n"); printf("%s", temp4); } //sleep(1); //execl("/bin/sh", "sh", "-c", "ls -l", (char *)0); } } return 0; }
C
/* ** EPITECH PROJECT, 2020 ** my_compute_power_rec ** File description: ** Computes power recursively */ #include <my.h> static int may_overflow_if_multiplied(int number, int digit) { return (number > 2147483647 - (number * (digit - 1))); } int my_pow(int nb, int p) { if (p < 0) return (0); if (p == 0) return (1); int result = my_pow(nb, p - 1); if (may_overflow_if_multiplied(result, nb)) return (0); return (result * nb); }
C
#include <stdio.h> #include <stdlib.h> /** \brief esta funcion toma que funcion voy a realizar del menu * * \param mensaje "ingresar opcion" * \param mensaje de error de opcion. * \return retorno 0 * */ int tomarDato(char mensaje[], char mensajeError[], int* valor) { printf(mensaje); scanf("%d", valor); while(*valor>9 || *valor <= 0) { printf(mensajeError); scanf("%d", valor); } return 0; } /** \brief esta funcion toma el numero para la operacion matematica * * \param valor ingresado. * \param badera de estado de numero cargado o no. * \return retorno 0 si esta vacio o no esta cargado y 1 si esta cargado * */ int tomarOperando(float* valor, int* flagEstado, char mensaje[]) { int devolverCargadoNoCargado= 0; if(devolverCargadoNoCargado==0) { devolverCargadoNoCargado=1; printf("%s", mensaje); scanf("%f", valor); } *flagEstado=devolverCargadoNoCargado; return devolverCargadoNoCargado; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_reload_timers.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dlartigu <dlartigu@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/22 18:29:43 by jcharrou #+# #+# */ /* Updated: 2020/10/16 22:31:24 by dlartigu ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../../INCLUDES/prog.h" static void ft_reload_shotgun2(t_elem *floor) { if (floor->usable_ammo_shotgun + floor->max_ammo_shotgun > 4) { floor->max_ammo_shotgun = (floor->usable_ammo_shotgun + floor->max_ammo_shotgun) - 4; floor->usable_ammo_shotgun = 4; } else { floor->usable_ammo_shotgun = floor->usable_ammo_shotgun + floor->max_ammo_shotgun; floor->max_ammo_shotgun = 0; } } static uint32_t ft_reload_shotgun(t_elem *floor) { int amount; amount = 4 - floor->usable_ammo_shotgun; if (floor->max_ammo_shotgun > 3) { floor->max_ammo_shotgun = floor->max_ammo_shotgun - (4 - floor->usable_ammo_shotgun); floor->usable_ammo_shotgun = 4; } else ft_reload_shotgun2(floor); if (floor->shoot_delay) SDL_RemoveTimer(floor->shoot_delay); floor->shoot_delay = 0; return (100); } static uint32_t ft_reload_pistol(t_elem *floor) { if (floor->max_ammo_pistol > 7) { floor->max_ammo_pistol = floor->max_ammo_pistol - (8 - floor->usable_ammo_pistol); floor->usable_ammo_pistol = 8; } else { if (floor->usable_ammo_pistol + floor->max_ammo_pistol > 8) { floor->max_ammo_pistol = (floor->usable_ammo_pistol + floor->max_ammo_pistol) - 8; floor->usable_ammo_pistol = 8; } else { floor->usable_ammo_pistol = floor->usable_ammo_pistol + floor->max_ammo_pistol; floor->max_ammo_pistol = 0; } } if (floor->shoot_delay) SDL_RemoveTimer(floor->shoot_delay); floor->shoot_delay = 0; return (10); } uint32_t ft_reload_timer(uint32_t interval, void *param) { t_elem *floor; floor = param; if (floor->pistol_selected == 1) return (ft_reload_pistol(floor)); if (floor->shotgun_selected == 1) return (ft_reload_shotgun(floor)); return (interval); }
C
#ifndef CLM_LISTE_H #define CLM_LISTE_H typedef struct cell { char *word; int occurrences; struct cell *next; struct cell *previous; } Cell, *List; void displayWordsOfList(List list); Cell *getWord(List list, char *word); /** * Ajouter un mot à une liste. * Si le mot est déjà présent, son nombre d'occurrence est incrémenté. * @return Résultat (1 = succès, 0 = échec). */ int insertWord(List *list, char *word, int unique); int insertWordUnsorted(List *list, char *word); int insertWordAlphabetically(List *list, char *word); int insertWordByOccurrences(List *list, char *word); void freeList(List *list); #endif /* CLM_LISTE_H */
C
#include <stdio.h> int main() { const int a=20; int tab[a]; int i,n,S=0; printf("Saisie la taille du tableau"); scanf("%d",&n); for (i=0;i<n;i++) { printf("Saisie T[%d]",i); scanf("%d",&tab[i]); S=S+tab[i]; } printf("La moyenne des entiers de tableau= %d",S/n); return 0; }
C
#include<stdio.h> #include<string.h> #include<time.h> #include<stdlib.h> #include<errno.h> #include <sys/stat.h> #include <sys/types.h> #define PATH_SIZE 1024 void date_command_normal(); void date_command_utc(); void date_command_modified(char path[512]); void red() { printf("\033[1;31m"); // red color } void normal() { printf("\033[0m"); } void get_path_with_spaces(char dir_name[PATH_SIZE], char** args, int args_to_process) { int got_error=0; //error code for cd char path_with_spaces[PATH_SIZE]; // space for path int dir_index=0; int i=1; strcpy(path_with_spaces, *args); while(i<args_to_process) // dealing with spaces in the path { strcat(path_with_spaces, " \0"); strcat(path_with_spaces, *(args+i)); i++; } // Entire path in path_with_spaces if(**args=='/') // absolute path { strcpy(dir_name, path_with_spaces); } else if(**args=='~') { char absolute_dir[PATH_SIZE]; strcpy(absolute_dir, getenv("HOME")); //get home directory int home_length = strlen(absolute_dir); // length of home path strcat(absolute_dir, path_with_spaces+1); // skipping ~ strcpy(dir_name, absolute_dir); } else { strcpy(dir_name, path_with_spaces); } } int main(int argc, char **argv) { if(argc == 1) { date_command_normal(); } else if(argc==2 && !strcmp(*(argv+1), "-u\0")) { date_command_utc(); } else if(argc>2 && !strcmp(*(argv+1), "-r\0")) { char path[PATH_SIZE]; get_path_with_spaces(path, argv+2, argc-2); date_command_modified(path); } else { red(); puts("Invalid Option/Argument!"); normal(); } } void date_command_normal() // date { time_t now; time(&now); printf("The current local time is: %s", ctime(&now)); } void date_command_utc() // date -u { time_t now; time(&now); struct tm *utc_time = gmtime(&now); printf("The current UTC time is: %s", asctime(utc_time)); } void date_command_modified(char path[PATH_SIZE]) // date -r { struct stat file_info; if(!stat(path, &file_info)) // proper functioning { printf("Last modified time: %s", ctime(&file_info.st_mtime)); } else { red(); switch(errno) { case EACCES: puts("Permission denied!"); break; case ENOENT: puts("Path does not exist!"); break; case ENOTDIR: puts("Part of the path is not a directory!"); break; default: puts("Unexpected error occured!"); } normal(); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <ctype.h> #include <sys/ipc.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include "eightled.h" #define LED_ON 1 #define LED_OFF 0 #define MAX_LED_NO 8 void eightledWrite(int ledNo, int control) { // 0 0 ; all led off // 1 0 ; 1th led off // 2 0 ; 2th led off // 0 1 ; all led on // 1 1 ; 1th led on // 2 1 ; 2th led on // 3 1 ; 3th led on int wdata = 0; int rdata = 0; int temp ; if(ledNo == 0) { if(control == 1) wdata = 0xff; else wdata = 0; } else { read(fd[4], &rdata,4); temp = 1; if(control == 1) { temp <<= (ledNo - 1); wdata = rdata | temp; } else { temp = ~(temp<<(ledNo-1)); wdata = rdata & temp; } } write(fd[4], &wdata, 4); } void eightledOpen() { fd[4] = open(EIGHTLED_DEV,O_RDWR); if(fd[4] < 0) { perror("eightled open error\n"); exit(-1); } eightledWrite(0,0); } void eightledClose() { printf("eightled close()\n"); close(fd[4]); }
C
#include <stdio.h> #include <stdlib.h> struct node { char name[20]; int roll_no; float per; struct node *link; }; struct node *root = NULL; void append(void); void display(void); void main() { int ch; while (1) { printf("Enter element in the list:1\nExit:2\nDsplay:3"); scanf("%d", &ch); switch (ch) { case 1: append(); break; case 2: exit(0); case 3: display(); break; default: break; } } printf("List element are:"); display(); } void append() { struct node *temp, *p; temp = (struct node *)malloc(sizeof(struct node)); printf("Enter name"); scanf("%s", temp->name); printf("Enter rollNo"); scanf("%d", &temp->roll_no); printf("Enter Percentage"); scanf("%f", &temp->per); temp->link = NULL; if (root == NULL) { printf("list is empty here is the first record:\n"); root = temp; } else { p = root; while (p->link != NULL) { p = p->link; } p->link = temp; } } void display() { struct node *temp; int n = 0; temp = root; while (temp != NULL) { printf("Name:%s,RollNo:%d,Percentage:%f\n", temp->name, temp->roll_no, temp->per); if (temp->per >= 60.0) { n++; } temp = temp->link; } printf("NO of student who got 60 and more are:%d", n); }
C
#include "ConsolaKernel.h" void recibir_comandos() { while(morir == 0) { //0-> new, 1->ready, 2->execute, 3-> blocked, 4-> suspended, 9-> killed, char* entrada = leerCaracteresEntrantes(); if (*entrada!=NULL){ char** comando = string_split(entrada, " "); if(!strcmp(comando[0], "cola")) { if(comando[1] == NULL) { puts("-------TODOS LOS PROCESOS (INCLUYE EXIT)------"); pthread_mutex_lock(&mProcess); list_iterate(process, mostrarPorConsola); pthread_mutex_unlock(&mProcess); //MUTEX puts("-------TODOS LOS PROCESOS (INCLUYE EXIT)------"); } else if(!strcmp(comando[1], "new")) { puts("-------COLA NEW------"); mostrarProcesosEnEstado(0); puts("-------COLA NEW------"); } else if(!strcmp(comando[1], "ready")) { puts("-------COLA READY------"); pthread_mutex_lock(&mColaReady); list_iterate(colaReady->elements, mostrarPID); pthread_mutex_unlock(&mColaReady); puts("-------COLA READY------"); } else if(!strcmp(comando[1], "execute")) { puts("-------COLA EXECUTE------"); pthread_mutex_lock(&mListaExec); list_iterate(executeList, mostrarPID); pthread_mutex_unlock(&mListaExec); puts("-------COLA EXECUTE------"); } else if(!strcmp(comando[1], "blocked")) { puts("-------COLA BLOCKED------"); pthread_mutex_lock(&mListaBlocked); list_iterate(blockedList, mostrarPID); pthread_mutex_unlock(&mListaBlocked); puts("-------COLA BLOCKED------"); } else if(!strcmp(comando[1], "exit")) { puts("-------COLA EXIT------"); pthread_mutex_lock(&mColaFinished); list_iterate(colaFinished->elements, mostrarPID); pthread_mutex_unlock(&mColaFinished); puts("-------COLA EXIT------"); } } else if(!strcmp(comando[0], "rafagasEj")) { if(comando[1] != NULL) { int pid = atoi(comando[1]); ProcessControl* pc = PIDFind(pid); // ADENTRO TIENE MUTEX printf("[KERNEL]: PROCESO PID: %i LLEVA %i RAFAGAS EJECUTADAS\n", pc->pid, pc->rafagasEj); } } else if(!strcmp(comando[0], "tablaArchivos")) { if(comando[1]!=NULL){ if(!strcmp(comando[1], "global")) { puts("-------TABLA DE ARCHIVOS GLOBAL-------"); puts("|\tRUTA\t|\tINSTANCIAS\t|"); mostrarTablaDeArchivosGlobal(); puts("-------TABLA DE ARCHIVOS GLOBAL-------"); } else { int pid = atoi(comando[1]); pthread_mutex_lock(&mMaxPID); if(pid > maxPID | pid < 0) puts("PID INVALIDO"); else { printf("-------TABLA DE ARCHIVOS PID: %i-------\n", pid); puts("|\tFD\t|\tCURSOR\t|\tFLAGS\t|APUNTA A (RUTA)\t|"); mostrarTablaDeArchivosProceso(pid); printf("-------TABLA DE ARCHIVOS PID: %i-------\n", pid); } pthread_mutex_unlock(&mMaxPID); } } else{ puts("[KERNEL]: Argumento no puede ser null\n"); } } else if(!strcmp(comando[0], "multiprog")) { if(comando[1]!=NULL) { int multiprog = atoi(comando[1]); if(multiprog <= 0) puts("[CONFIG]: NO ES NU NUMERO VALIDO"); else { pthread_mutex_lock(&mMultiprog); config->GRADO_MULTIPROG = multiprog; pthread_mutex_unlock(&mMultiprog); printf("[CONFIG]: NUEVO GRADO DE MULTIPROGRAMACION: %i\n", config->GRADO_MULTIPROG); log_info(logFile, "[CONFIG]: NUEVO GRADO DE MULTIPROGRAMACION: %i\n", config->GRADO_MULTIPROG); enviarTodosLosNewAReady(); } } else{ puts("[KERNEL]: Argumento no puede ser null\n"); } } else if(!strcmp(comando[0], "syscalls")) { if(comando[1]!=NULL){ int pid = atoi(comando[1]); ProcessControl* pc = PIDFind(pid); printf("[KERNEL]: SYSCALLS PID: %i: %i\n", pc->pid, pc->syscalls); } } else if(!strcmp(comando[0], "heapInfo")) { if(comando[1]!=NULL){ int pid = atoi(comando[1]); ProcessControl* pc = PIDFind(pid); puts("---------HEAP INFO----------"); printf("CANTIDAD ALLOCS: %i | BYTES ALOCADOS: %i | PAGINAS ALOCADAS (CONTANDO LIBERADAS): %i\n", pc->cantAlocar, pc->heapBytes, pc->heapPages); printf("CANTIDAD FREES: %i | BYTES LIBERADOS: %i\n", pc->cantFree, pc->freedBytes); puts("---------HEAP INFO----------"); } } else if(!strcmp(comando[0], "mostrarPCB")) { if(comando[1]!=NULL) { int pid = atoi(comando[1]); //0-> new, 1->ready, 2->execute, 3-> blocked, 4-> suspended, 9-> killed, bool mismoPID(PCB* pcb) { return pcb->pid == pid; } pthread_mutex_lock(&mColaFinished); PCB* pcb = list_find(colaFinished->elements, mismoPID); pthread_mutex_unlock(&mColaFinished); if(pcb == NULL) puts("NO ESTA EN FINISHED"); else mostrarPCB(pcb); } } else if(!strcmp(comando[0], "kill")) { if(comando[1]!=NULL){ int pid = atoi(comando[1]); matarCuandoCorresponda(pid,-7); printf("SE ENVIO A AJUSTICIAR EL PROCESO PID: %i. SE AJUSTICIARA CUANDO CORRESPONDA.\n", pid); } else{ puts("[KERNEL]: Argumento no puede ser null\n"); } } else if(!strcmp(comando[0], "togglePlanif")) { pthread_mutex_lock(&mTogglePlanif); if(togglePlanif == 0) { log_error(logFile, "[PLANIFICACION]: DETIENDO PLANIFICACION"); togglePlanif = 1; pthread_mutex_unlock(&mTogglePlanif); } else { log_error(logFile, "[PLANIFICACION]: REANUDANDO PLANIFICACION"); togglePlanif = 0; pthread_mutex_unlock(&mTogglePlanif); matarTodosLosQueCorresponda(); enviarTodosLosNewAReady(); enviarTodosLosReadyAExecute(); } } else if(!strcmp(comando[0], "exit")) { morir = 1; getConnectedSocket(config->IP_PROPIA, config->PUERTO_PROG, CONSOLA_ID); } else if(!strcmp(comando[0], "help")) { puts("---------------COMANDOS---------------"); puts("cola [exit] [ready] [blocked] [new] [execute] [vacio]"); puts("rafagasEj [PID] | tablaArchivos [global] [PID]"); puts("multiprog [numero] | syscalls [PID] | heapInfo [PID]"); puts("mostrarPCB [PIDEnExit] | kill [PID] | togglePlanif"); puts("exit"); puts("---------------COMANDOS---------------"); } else puts("[KERNEL]: COMANDO INVALIDO"); free(comando[0]); free(comando[1]); free(comando); free(entrada); } } } void matarTodosLosQueCorresponda() { bool paraMatar(ProcessControl* pc) { return pc->toBeKilled != 0; } t_list* ajusticiados = list_filter(process, paraMatar); void matar(ProcessControl* pc) { matarSiCorresponde(pc->pid); } list_iterate(ajusticiados, matar); list_destroy(ajusticiados); } void mostrarPCB(PCB* pcb) { puts("----------------PCB----------------"); mostrarIndiceDeStack(pcb->indiceStack, pcb->nivelDelStack); printf("PID: %i | EXIT CODE: %i\n", pcb->pid, pcb->exitCode); puts("----------------PCB----------------"); } void enviarTodosLosNewAReady() { pthread_mutex_lock(&mColaNew); int new = queue_size(colaNew); pthread_mutex_unlock(&mColaNew); int i; for(i = 0;i<new;i++) readyProcess(); } void enviarTodosLosReadyAExecute() { pthread_mutex_lock(&mColaReady); int ready = queue_size(colaReady); pthread_mutex_unlock(&mColaReady); int i; for(i = 0;i<ready;i++) executeProcess(); } char* leerCaracteresEntrantes() { int i, caracterLeido; char* cadena = malloc(100); for(i = 0; (caracterLeido= getchar()) != '\n'; i++) cadena[i] = caracterLeido; cadena[i] = '\0'; return cadena; } //a void mostrarTablaDeArchivosProceso(int pid) { tablaDeProceso* tabla = encontrarTablaDelProceso(pid); if(tabla == NULL) puts("NO TIENE ARCHIVOS"); else list_iterate(tabla->entradasTablaProceo, &mostrarEntradaTablaArchivoProceso); } void mostrarEntradaTablaArchivoProceso(entradaTablaFSProceso* entrada) { printf("|\t%i\t|\t %i\t|\t%s\t|\t%s\t|\n", entrada->fd, entrada->cursor, entrada->flags, entrada->entradaGlobal->ruta); } void mostrarTablaDeArchivosGlobal() { //MUTEX list_iterate(tablaGlobalFS, mostrarEntradaTablaGlobalFS); //MUTEX } void mostrarEntradaTablaGlobalFS(entradaTablaGlobalFS* entrada) { printf("|\t%s\t|\t%i\t|\n",entrada->ruta, entrada->instancias); } void mostrarProcesosEnEstado(int estado) { bool mismoEstado(ProcessControl* pc) { return estado == pc->state; } pthread_mutex_lock(&mProcess); t_list* filtrados = list_filter(process, &mismoEstado); pthread_mutex_unlock(&mProcess); list_iterate(filtrados, &mostrarPorConsola); } void mostrarPorConsola(ProcessControl* pc) { printf("PID %i | ESTADO: %i\n", pc->pid, pc->state); }
C
/*.............Name:P Venkata Yashwanth Kumar............ ................Roll No:05AE1013........................ ................Program name:a5.c..................... ................PC No:17......................*/ #include<stdio.h> struct variable { int val; int op1,op2; char op; }; void readinput(struct variable vars[100],int n); void support(int y,struct variable vars[100]); int evaluate(int v,struct variable vars[100]); int x[100]; main() { struct variable vars[100]; int i,n,re,y,v; char c; for(i=0;i<100;i++) { x[i]=-1; } printf("\nEnter the number of variables(<100):"); scanf("%d",&n); c=getchar(); printf("\nEnter the record for the variables.For example,for x3=x2+x4,you should enter 3,2,4,+ in the record of x3"); do { printf("\nEnter the number of variable for which you are going to enter the record:"); scanf("%d",&re); c=getchar(); printf("\nEnter the record of variable x%d",re); vars[re-1].val=re; printf("\nEnter the 1st operand:"); scanf("%d",&vars[re-1].op1); c=getchar(); printf("\nEnter the 2nd operand:"); scanf("%d",&vars[re-1].op2); c=getchar(); printf("\nEnter the operator:"); scanf("%c",&vars[re-1].op); c=getchar(); printf("\nDo you want to enter one more relation?Y/N"); scanf("%c",&c); }while(c=='y' || c=='Y'); readinput(vars,n); xyz: printf("\nEnter the variable(for example,3 for x3)to find the variables that influence its value:"); scanf("%d",&y); c=getchar(); if(x[y-1]==(-1)) { printf("\n"); support(y,vars); } else { printf("\nx%d is an independent variable",y); } printf("\nDo you want to check the dependancy of one more variable?Y/N"); scanf("%c",&c); if(c=='y' || c=='Y') goto xyz; pqr: printf("\nEnter the variable(like 3 for x3)to find its value:"); scanf("%d",&y); c=getchar(); v=evaluate(y,vars); printf("\nThe value of x%d is %d",y,v); printf("\nDo you want to find the value of one more variable?Y/N"); scanf("%c",&c); if(c=='y' || c=='Y') goto pqr; } void readinput(struct variable vars[100],int n) { int i; char c; for(i=1;i<=n;i++) { if(vars[i-1].val!=i) { vars[i-1].val=i; vars[i-1].op1=0; vars[i-1].op2=0; vars[i-1].op='='; printf("\nEnter the value of x%d:",i); scanf("%d",&x[i-1]); c=getchar(); } } } void support(int y,struct variable vars[100]) { if(vars[y-1].op!='=') { if(vars[vars[y-1].op1-1].op=='=' && vars[vars[y-1].op2-1].op=='=') { printf("x%d x%d ",vars[y-1].op1,vars[y-1].op2); } else { if(vars[vars[y-1].op1-1].op=='=') { } else { printf("x%d ",vars[y-1].op1); support(vars[y-1].op1,vars); } if(vars[vars[y-1].op2-1].op=='=') { } else { printf("x%d ",vars[y-1].op2); support(vars[y-1].op2,vars); } } } else { printf("x%d x%d ",vars[y-1].op1,vars[y-1].op2); } } int evaluate(int v,struct variable vars[100]) { switch(vars[v-1].op) { case '=': return x[v-1]; break; case '+': return(evaluate(vars[v-1].op1,vars)+evaluate(vars[v-1].op2,vars)); break; case '*': return(evaluate(vars[v-1].op1,vars)*evaluate(vars[v-1].op2,vars)); break; default : return 0; break; } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> void Usage() { char buff[64]; sprintf(buff,"Usage: prog_* num\n"); write(1,buff,strlen(buff)); exit(1); } int main( int argc, char *argv[] ) { int i, num; char buf[80]; if (argc != 2) Usage(); num = atoi( argv[1] ); for (i = 0; i < num; i++) { sprintf(buf, "%c", 'A'+i); write(1, buf, 1); } write(1,"\n",1); return 0; }
C
#ifndef RAYCAST #define RAYCAST #include "ib_3dmath.h" #define RUN_SUCCESS 0 #define RUN_FAIL 1 #define MIN_ARGS 5 #define TRUE 1 #define FALSE 0 #define CAMERA 0 #define SPHERE 1 #define PLANE 2 #define LIGHT 3 #define CENTER_XY 0.0 #define SHINE_DEFAULT 20.0 #define MAX_RECURSION 7 // Type definitions typedef int bool; typedef struct rgb rgb; typedef struct obj obj; typedef struct obj_node obj_node; typedef struct rgb_node rgb_node; typedef struct linked_list linked_list; typedef struct rgb_list rgb_list; // Color in rgb format struct rgb { float r; float g; float b; }; // Create one central object that contains all variables for any object struct obj { int type; float width; float height; rgb color; ib_v3 position; float radius; ib_v3 normal; float radial_a0; float radial_a1; float radial_a2; float reflectivity; float refractivity; float ior; float theta; float angular_a0; ib_v3 direction; rgb diffuse_color; rgb specular_color; float ns; }; // Struct used used as a linked list node struct obj_node { obj_node *next; obj obj_ref; }; // Struct used as a node for an rgb value struct rgb_node { rgb_node *next; rgb color; }; // Linked list structure struct linked_list { obj_node *first; obj_node *last; obj_node *main_camera; int size; }; // Rgb list structure struct rgb_list { rgb_node *first; rgb_node *last; int size; }; // Forward declarations void create_node(obj *data, linked_list *list); #endif
C
#include "holberton.h" /** * _isdigit - function that checks for a digit through (0 -9) *@c: character to evaluate in ASCII code * * Return: 1 if c is a digit or 0 otherwise * */ int _isdigit(int c) { if ((c >= '0') && (c <= '9')) { return (1); } return (0); }
C
#include <idc.idc> static print_all_method(filename) { auto file = fopen(filename, "w"); if (file != 0) { auto addr = 0; for (addr = NextFunction(addr); addr != BADADDR; addr = NextFunction(addr)) { auto name = GetFunctionName(addr); auto end = GetFunctionAttr(addr, FUNCATTR_END); Message("0x%x\t0x%x\t%s\n", addr, end, name); fprintf(file, "0x%x\t0x%x\t%s\n", addr, end, name); } } fclose(file); } static main() { Wait(); print_all_method(ARGV[1]); Exit(0); }
C
#include<stdio.h> #include<stdlib.h> int main() { FILE *ptr; int a,b,c; ptr=fopen("28.txt","r"); fscanf(ptr,"%d%d%d",&a,&b,&c); printf("the values of a,b and c is %d,%d,%d",a,b,c); return 0; }
C
/** ****************************************************************************** * * @file : strconv.c * @brief : 字符串和数字间格式转换 * ****************************************************************************** */ #include "strconv.h" const uint8_t err_message_IA[] = "INVALID ADDR!\n"; /* error:无效地址 */ const uint8_t err_message_ID[] = "INVALID DATA!\n"; /* error:无效数据 */ extern UART_HandleTypeDef huart1; /** * @brief 将字符串转换成数字 * @param str 从PC端接收到的字符串 * @param typ 要求转换的数值类型 * @arg 1:addr ; 2:data * @retval 转换后的数值 * @arg 0:转换出现错误(输入字符串不合规) */ uint32_t str_to_int(uint8_t *str, uint8_t typ) { uint32_t tmp = 0; uint8_t i,ctmp,itmp; for (i = 1; i <= 8; i++) { ctmp = str[i]; if (ctmp <= '9' && ctmp >= '0') itmp = ctmp - '0'; else if (ctmp <= 'f' && ctmp >= 'a') itmp = ctmp - 'a' + 10; else if (ctmp <= 'F' && ctmp >= 'A') itmp = ctmp - 'A' + 10; else { /* 串口发送错误信息并直接返回 */ if (typ == 1) HAL_UART_Transmit(&huart1, (uint8_t *)err_message_IA, sizeof(err_message_IA), 5); else if (typ == 2) HAL_UART_Transmit(&huart1, (uint8_t *)err_message_ID, sizeof(err_message_ID), 5); return 0; } tmp += (uint32_t)(itmp << (4*(8-i))); } return tmp; }
C
#include<stdio.h> #include<unistd.h> #include<netinet/in.h> #include<string.h> #include<sys/socket.h> #include<sys/types.h> #define SERV_PORT 5576 main(int argc,char **argv) { int i,j; ssize_t n; FILE *fp; char s[80],f[80],command[50]; //strcpy(s,"file.txt"); struct sockaddr_in servaddr,cliaddr; int listenfd,connfd,clilen; listenfd=socket(AF_INET,SOCK_STREAM,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(SERV_PORT); bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); listen(listenfd,1); clilen=sizeof(cliaddr); connfd=accept(listenfd,(struct sockaddr*)&cliaddr,&clilen); printf("\n clinet connected"); int data2[100]; read(connfd,data2,100); int c1=(data2[3-1])^data2[5-1]^data2[7-1]^data2[9-1]^data2[11-1]^data2[1-1]; int c2=(data2[3-1])^data2[6-1]^data2[7-1]^data2[10-1]^data2[11-1]^data2[2-1]; int c3=data2[5-1]^data2[6-1]^data2[7-1]^data2[12-1]^data2[4-1]; int c4=data2[9-1]^data2[10-1]^data2[11-1]^data2[12-1]^data2[8-1]; printf("%d %d %d %d",c1,c2,c3,c4); if(c1==0&&c2==0&&c3==0&&c4==0) printf("No error!"); else printf("Error"); close(listenfd); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define u8 unsigned char int main(int argc, char *argv[]){ u8* mask; mask= (u8 *)malloc(sizeof(u8)*32); if(mask==NULL){ fprintf(stderr,"Allocate memory failed\n"); return 1; } memset(mask,0,32*sizeof(u8)); //mask[7]=~0; mask[7] = 0xff; //mask[7] |= 0x81; printf("%04x\n",mask[6]); printf("%04x\n",mask[8]); printf("%04x\n",mask[7]); return 0; }
C
/* sell.c by -Acme- */ inherit F_CLEAN_UP; private void create() { seteuid(getuid()); } int sell_item(object item) { int value; string name; if( item->query("money_id") ) return notify_fail("AnuvS\n"); if( item->query("no_sell") ) return notify_fail("o˪F褣C\n"); if( (value = item->query("value")) <=0 ) return notify_fail("o˪F褣ȿC\n"); if( item->query("keep_this") ) return notify_fail("o˪FAwg keep LkcC\n"); if( item->query("equipped") ) return notify_fail("o˪FAwg˳ƵۡALkcC\n"); value /= 2; name = ( item->query_amount() ? chinese_number(item->query_amount()) : "@" ); name += ( item->query("base_unit") ? item->query("base_unit") : ( item->query("unit") ? item->query("unit") : "" ) ); name += item->query("name"); if( !environment(this_player())->to_stock(item) ) return notify_fail("EG@Uo˪~C\n"); message_vision("$NH" + chinese_number(value) + "ȤlN" + name + "XhC\n", this_player() ); // N[Ȧ this_player()->add("bank", value); return 1; } int main(object me, string arg) { int amount; object item; if( !environment(me) ) return notify_fail("A{bBbADFI\n"); if( !environment(me)->is_hockshop() ) return notify_fail("AubEFC\n"); if( me->is_busy() ) return notify_fail("A{bSšI\n"); if( !arg ) return notify_fail("AQ椰FH\n"); if( arg == "all" ) { object *inv; inv = all_inventory(this_player()); foreach(item in inv) { if( !item ) continue; sell_item(item); } write("OkC\n"); return 1; } if( sscanf(arg, "%d %s", amount, arg) == 2 ) { object new_item; if( !(item = present(arg, me)) ) return notify_fail("AQn_򪫫~H\n"); if( amount <= 0 ) return notify_fail("AQnXӪ~H\n"); if( item->query_amount() < amount ) return notify_fail("AWSoh" + item->query("name") + "C\n"); // ۦPƶq if( amount == item->query_amount() ) return sell_item(item); if( !objectp(new_item = new(base_name(item))) ) return notify_fail("AGLkco˪~C\n"); new_item->set_amount(amount); item->add_amount(-amount); // LkXAhdest new_item, ñN쥻item amount_ if( !sell_item(new_item) ) { destruct(new_item); item->add_amount(amount); } return 1; } if( !(item = present(arg, me)) ) return notify_fail("AQn_򪫫~H\n"); return sell_item(item); } int help(object me) { write(@HELP O榡 : sell [ƶq] ~ oiOiHNAW~XhAq`ubEa~ c檫~CҡG sell blade NWĤ@MXh sell blade 2 NWĤGMXh sell 3 pill NWpillXTӡAq`ΩuƦX~vW sell 4 pill 2 NWĤG諸pillX| OG list, buy HELP); return 1; }
C
#include <stdbool.h> #include "networking.h" #include "generalMethods.h" #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <stdbool.h> #include "tmdl.h" #include <unistd.h> #include <pwd.h> #include "customParser.h" #include "experimental.h" #include <sys/types.h> #include <dirent.h> char *releasePage = "https://github.com/CookieAvenger/Tiny-Manga-Downloader/releases"; //current version - 0.1.1 long major = 0; long normal = 1; long minor = 1; char *currentVersion = "v0.1.1"; //Weather to continue even if there is an update bool continueAnyway = false; //To stop immedietly if there is an update bool stopAtUpdate = false; //Simple storage of if an error ever happened bool errorOccured = false; //Directory to download and update char *updateDirectory = NULL; char *get_update_directory() { return updateDirectory; } //Set up update diretory - only ever gets called once void setUpdateDirectory() { struct passwd *passwordEntry = getpwuid(getuid()); if (passwordEntry == NULL) { exit(21); } char *homeDirectory = passwordEntry->pw_dir; updateDirectory = concat(homeDirectory, "/.tmdl/"); //remove old files in case there are any then make new ones delete_folder(updateDirectory, -1); create_folder(updateDirectory); } //Set prompt to auto yes void set_yes() { continueAnyway = true; stopAtUpdate = false; } //Set prompt to auto no void set_no() { stopAtUpdate = true; continueAnyway = false; } //Find all flags and try to check em all for y's and n's void perform_flag_yes_no_checks(int argc, char **argv) { for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { if (argv[i][1] == '\0') { exit(1); } else { process_flag(argv[i] + 1); } } else if (strcmp(argv[i], "update") != 0) { exit(1); } } } //Print parsing error with regards to updating void print_parse_error() { fputs("Github parsing error, please report.\n", stderr); fputs("Failed to check for updates, continuing anyway.\n", stderr); errorOccured = true; } //Figures out if the string version is newer, older or the same long process_version(char *version) { char *leftOvers = '\0'; long newestMajor = strtol(version, &leftOvers, 10); if (leftOvers[0] != '.' || leftOvers[1] == '\0' || errno == ERANGE) { print_parse_error(); return 0; } char *secondPass = '\0'; long newestNormal = strtol(leftOvers + 1, &secondPass, 10); if (secondPass[0] != '.' || secondPass[1] == '\0' || errno == ERANGE) { print_parse_error(); return 0; } char *lastTry = '\0'; long newestMinor = strtol(secondPass + 1, &lastTry, 10); if (*lastTry != '\0' || errno == ERANGE) { print_parse_error(); return 0; } if (major != newestMajor) { return major - newestMajor; } else if (normal != newestNormal) { return normal - newestNormal; } else { return minor - newestMinor; } } //Prompts user for yes or no to continue or stop void continue_prompt() { if (continueAnyway) { return; } else if (stopAtUpdate) { exit(0); } printf("Would you like to continue anyway? [Y/n]:"); fflush(stdout); char response = fgetc(stdin); char end = fgetc(stdin); if (end != '\n' && end != EOF) { while (end != '\n' && end != EOF) { end = fgetc(stdin); } puts("Sorry that is not a recognised response, please try again"); fflush(stdout); continue_prompt(); } if (response == 'y' || response == 'Y') { return; } else if (response == 'n' || response == 'Y') { exit(0); } puts("Sorry that is not a recognised response, please try again"); fflush(stdout); continue_prompt(); } //Untar's the downloaded file and returns the path to the uncompressed folder char *untar_update(char *fileLocation) { char *folderToSend = make_bash_ready(updateDirectory); char *fileToSend = make_bash_ready(fileLocation); char *untarScript = (char *) malloc(sizeof(char) * (strlen(folderToSend) + strlen(fileToSend) + 30)); if (untarScript == NULL) { exit(21); } sprintf(untarScript, "(cd %s && tar --overwrite -xf %s)", folderToSend, fileToSend); char *scriptName = concat(updateDirectory, ".extract.sh"); (void) write_script(scriptName, untarScript, true); free(untarScript); //execute script frees scriptName //want to do tar -xvf, but -v in piping causes broken pipe :/ char *newFolderName = execute_script(scriptName, 34, true, '\n', get_verbose()); //atm just making magic happen, tried using find to duplicate -v effect //but that also threw broken pipe //to delete if (newFolderName != NULL) { free(newFolderName); } newFolderName = make_permenent_string("Tiny-Manga-Downloader/"); //end of to delete char *emptyFolderCheck = concat(updateDirectory, newFolderName); //this also returns if path doesn't exist if (newFolderName == NULL || is_directory_empty(emptyFolderCheck)) { exit(34); } free(emptyFolderCheck), free(folderToSend), free(fileToSend); char *finalFolder = concat(updateDirectory, newFolderName); free(newFolderName); return finalFolder; } void install_update(char *folderToRunIn) { char *folderToSend = make_bash_ready(folderToRunIn); size_t folderLength = strlen(folderToSend); puts("Configuring updating..."); fflush(stdout); char *configureScript = (char *) malloc(sizeof(char) * (folderLength + 26)); if (configureScript == NULL) { exit(21); } sprintf(configureScript, "(cd %s && bash ./configure)", folderToSend); char *scriptName = concat(updateDirectory, ".configure.sh"); (void) write_script(scriptName, configureScript, true); free(configureScript); (void) execute_script(scriptName, 35, false, EOF, get_verbose()); puts("Configuration complete"); puts("Compiling program..."); fflush(stdout); char *makeScript = (char *) malloc(sizeof(char) * (folderLength + 14)); if (makeScript == NULL) { exit(21); } sprintf(makeScript, "(cd %s && make)", folderToSend); scriptName = concat(updateDirectory, ".make.sh"); (void) write_script(scriptName, makeScript, true); free(makeScript); (void) execute_script(scriptName, 36, false, EOF, get_verbose()); puts("Compilation complete"); puts("Installing update..."); fflush(stdout); char *installScript = (char *) malloc(sizeof(char) * (folderLength + strlen(updateDirectory) + 70)); if (installScript == NULL) { exit(21); } sprintf(installScript, "(cd %s && sudo make install && rm -fr %s && echo" " 'Installation complete')", folderToSend, updateDirectory); free(folderToSend); scriptName = concat(updateDirectory, ".install.sh"); (void) write_script(scriptName, installScript, true); execlp("sh", "sh", scriptName, NULL); exit(37); } void full_update_installation_process(char *downloadLink, char *downloadName) { setUpdateDirectory(); //download into file char *downloadFile = concat(updateDirectory, downloadName); puts("Downloading File..."); fflush(stdout); int success = download_file(downloadLink, downloadFile); if (success != 0) { exit(33); } puts("Download complete\nUncompressing File..."); fflush(stdout); char *uncompressedFolder = untar_update(downloadFile); puts("Decompression complete"); fflush(stdout); install_update(uncompressedFolder); //stuff that never actually happens //free(downloadFile), free(uncompressedFolder); //delete_folder(updateDirectory, -1); } //Check for update, do it if asked and allowed to void perform_update_operations(bool update) { //geteuid == 0 means we have sudo rights if (update && geteuid() != 0) { exit(42); } if (get_verbose()) { puts("Checking for program update"); fflush(stdout); } char *page = curl_get_page(releasePage); if (page == NULL) { fputs("Failed to check for updates, continuing anyway.\n", stderr); return; } char *releaseLocation = strstr(page, "Latest release"); if (releaseLocation == NULL) { print_parse_error(); return; } char *version = get_substring(releaseLocation, "truncate-target\">" , "</span", -1); if (version == NULL || version[0] != 'v' || version[1] == '\0') { print_parse_error(); return; } //rn is fine, but remeber there can be a next page in releases!! char *lastOfUs = rstrstr(releaseLocation, currentVersion); if (lastOfUs != NULL) { char *nextLocation = releaseLocation; char *messageToProcess, *finalMessage, *lastLocation, *almostFinalMessage; size_t numberOfChanges = 0; while (lastLocation = nextLocation, nextLocation = strstr(nextLocation, "markdown-body"), (nextLocation != NULL) || (nextLocation - lastOfUs >= 0)) { messageToProcess = get_substring(nextLocation, "\">", "</div>", -1); if (messageToProcess == NULL) { break; } almostFinalMessage = continuous_find_and_replace(messageToProcess, "<", ">", ""); free(messageToProcess); finalMessage = replace_leading_whitespace(almostFinalMessage, "\t"); free(almostFinalMessage); char *nameSection = strstr(lastLocation, "release-title\">"); //if not null well.. if (nameSection != NULL) { char *skipABit = strstr(nameSection, "\">"); if (skipABit != NULL) { skipABit += 2; char *nameOfChangelogVersion = get_substring(skipABit, "\">", "</a>", -1); if (nameOfChangelogVersion != NULL) { char *version = strstr(nameOfChangelogVersion, "v"); if (version == NULL || strcmp(version, currentVersion) == 0) { break; } if (++numberOfChanges == 1) { puts("\n"); fflush(stdout); } printf("%s\n", nameOfChangelogVersion); fflush(stdout); free(nameOfChangelogVersion); } } //may be printed even if finalmessage is empty, I know, that's okay :) } if (finalMessage != NULL) { printf("%s\n", finalMessage); fflush(stdout); free(finalMessage); } //skip markdown body part of it nextLocation += 13; //insanity check - defenive programming if (nextLocation - lastOfUs >= 0) { break; } } if (numberOfChanges > 0) { printf("Number of Updates: %zu\n", numberOfChanges); fflush(stdout); } } char *downloadSection = strstr(releaseLocation, "Downloads"); if (downloadSection == NULL) { print_parse_error(); return; } char *downloadLink = get_substring(downloadSection, "<a href=\"", "\"", -1); if (downloadLink == NULL) { print_parse_error(); return; } char *downloadName = get_substring(downloadSection, "<strong>", "</strong>", -1); if (downloadName == NULL) { print_parse_error(); return; } free(page); decode_html_entities_utf8(downloadName, NULL); char *fullDownloadLink = concat("https://github.com", downloadLink);; free(downloadLink); int difference = process_version(version + 1); if (errorOccured) { return; } if (update) { if (difference == 0) { puts("Nothing to update, already on the latest stable release"); } else if (difference > 0) { puts("You are currently on a newer version that the latest stable," " continuing will downgrade to the latest stable."); continue_prompt(); //do update thing full_update_installation_process(fullDownloadLink, downloadName); } else { //do update thing full_update_installation_process(fullDownloadLink, downloadName); } } else { if (difference < 0) { printf("New stable version v%ld.%ld.%ld->%s of Tiny-Manga-Downloader is now " "available, it is highly recommended to update\n" "You can do that with \"sudo manga-dl update\"\n", major, normal, minor, version); fflush(stdout); continue_prompt(); } } free(version), free(fullDownloadLink), free(downloadName); }
C
#ifndef ROTATE_H_INCLUDED #define ROTATE_H_INCLUDED #include <stdlib.h> #ifndef ROTATEPIXEL_T_DEFINED #define ROTATEPIXEL_T_DEFINED #include <stdint.h> #if ROTATEPIXEL_T_BITS==8 typedef char RotatePixel_t; // Pixel type for rotation library //#define ROTATEPIXEL_T_BITS (8) #elif ROTATEPIXEL_T_BITS==16 typedef uint16_t RotatePixel_t; // Pixel type for rotation library //#define ROTATEPIXEL_T_BITS (16) #elif ROTATEPIXEL_T_BITS==24 typedef struct { char _[3]; } RotatePixel_t; // Pixel type for rotation library //#define ROTATEPIXEL_T_BITS (24) #else // 32 typedef uint32_t RotatePixel_t; // Pixel type for rotation library #define ROTATEPIXEL_T_BITS (32) #endif #endif /// <summary> Merge pixel function callback to merge old and new color </summary> typedef RotatePixel_t (*RotateColorMergerFunc_t)(RotatePixel_t newColor, RotatePixel_t oldColor, void *Param); #ifdef __cplusplus #define ROTATE_DEF_PARAM(val) = val #else #define ROTATE_DEF_PARAM(val) // None #endif /// <summary> /// Rotates source image and writes it to the destination, filling all the target. /// All destination filled by rotated and scaled copies of source tiles. /// </summary> /// <param name="pDstBase">Destination image data address</param> /// <param name="dstW">Destination image width in pixels</param> /// <param name="dstH">Destination image height in pixels</param> /// <param name="dstDelta">Destination image horizontal scan line size in bytes (AKA stride)</param> /// <param name="pSrcBase">Source image data address</param> /// <param name="srcW">Source image width in pixels</param> /// <param name="srcH">Source image height in pixels</param> /// <param name="srcDelta">Source image horizontal scan line size </param> /// <param name="fDstRotCenterX">Rotation center X location in destination image</param> /// <param name="fDstRotCenterY">Rotation center Y location in destination image</param> /// <param name="fSrcRotCenterX">Rotation center X location in source image</param> /// <param name="fSrcRotCenterY">Rotation center Y location in source image</param> /// <param name="fAngle">Angle of rotation in radians. (if Angle > 0 : CCW for top-bottom [normal] bmp, CW:for bottom-up [reverced] bmp)</param> /// <param name="fScale">Scale of source before apply to destination. (Scale = 1 : no scale)</param> extern void RotateDrawFill ( RotatePixel_t *pDstBase, int dstW, int dstH, int dstDelta, RotatePixel_t *pSrcBase, int srcW, int srcH, int srcDelta, float fDstRotCenterX, float fDstRotCenterY, float fSrcRotCenterX, float fSrcRotCenterY, float fAngle, float fScale ); /// <summary> /// Rotate source image and put it on destination image. /// One copy of rotated and scaled source drawn on target /// [Default version] [Now via RotateDrawClipExt2] /// </summary> /// <param name="pDstBase">Destination image data address</param> /// <param name="dstW">Destination image width in pixels</param> /// <param name="dstH">Destination image height in pixels</param> /// <param name="dstDelta">Destination image horizontal scan line size in bytes (AKA stride)</param> /// <param name="pSrcBase">Source image data address</param> /// <param name="srcW">Source image width in pixels</param> /// <param name="srcH">Source image height in pixels</param> /// <param name="srcDelta">Source image horizontal scan line size </param> /// <param name="fDstRotCenterX">Rotation center X location in destination image</param> /// <param name="fDstRotCenterY">Rotation center Y location in destination image</param> /// <param name="fSrcRotCenterX">Rotation center X location in source image</param> /// <param name="fSrcRotCenterY">Rotation center Y location in source image</param> /// <param name="fAngle">Angle of rotation in radians. (if Angle > 0 : CCW for top-bottom [normal] bmp, CW:for bottom-up [reverced] bmp)</param> /// <param name="fScale">Scale of source before apply to destination. (Scale = 1 : no scale)</param> extern void RotateDrawClip ( RotatePixel_t* pDstBase, int dstW, int dstH, int dstDelta, RotatePixel_t* pSrcBase, int srcW, int srcH, int srcDelta, float fDstRotCenterX, float fDstRotCenterY, float fSrcRotCenterX, float fSrcRotCenterY, float fAngle, float fScale ); /// <summary> /// Rotate source image and put it on destination image. /// One copy of rotated and scaled source drawn on target /// Optional external function may be provided for color merge /// [Default version] [Now via RotateDrawClipExt2] /// </summary> /// <param name="pDstBase">Destination image data address</param> /// <param name="dstW">Destination image width in pixels</param> /// <param name="dstH">Destination image height in pixels</param> /// <param name="dstDelta">Destination image horizontal scan line size in bytes (AKA stride)</param> /// <param name="pSrcBase">Source image data address</param> /// <param name="srcW">Source image width in pixels</param> /// <param name="srcH">Source image height in pixels</param> /// <param name="srcDelta">Source image horizontal scan line size </param> /// <param name="fDstRotCenterX">Rotation center X location in destination image</param> /// <param name="fDstRotCenterY">Rotation center Y location in destination image</param> /// <param name="fSrcRotCenterX">Rotation center X location in source image</param> /// <param name="fSrcRotCenterY">Rotation center Y location in source image</param> /// <param name="fAngle">Angle of rotation in radians. (if Angle > 0 : CCW for top-bottom [normal] bmp, CW:for bottom-up [reverced] bmp)</param> /// <param name="fScale">Scale of source before apply to destination. (Scale = 1 : no scale)</param> /// <param name="mergeFunc">Callback function to merge new and old pixel value [RotatePixel_t Merger(RotatePixel_t newColor, RotatePixel_t oldColor, void *Param)] NULL=not used</param> /// <param name="mergeParam">Callback function last parameter NULL=not used</param> extern void RotateDrawClipExt ( RotatePixel_t* pDstBase, int dstW, int dstH, int dstDelta, RotatePixel_t* pSrcBase, int srcW, int srcH, int srcDelta, float fDstRotCenterX, float fDstRotCenterY, float fSrcRotCenterX, float fSrcRotCenterY, float fAngle, float fScale, RotateColorMergerFunc_t mergeFunc ROTATE_DEF_PARAM(NULL), void* mergeParam ROTATE_DEF_PARAM(NULL) ); // Individual versions // -------------------------------------------------------- // (different implemenation alogorithms) -- for test only /// <summary> /// Rotate source image and put it on destination image. /// One copy of rotated and scaled source drawn on target /// [Standard prec version] /// </summary> /// <param name="pDstBase">Destination image data address</param> /// <param name="dstW">Destination image width in pixels</param> /// <param name="dstH">Destination image height in pixels</param> /// <param name="dstDelta">Destination image horizontal scan line size in bytes (AKA stride)</param> /// <param name="pSrcBase">Source image data address</param> /// <param name="srcW">Source image width in pixels</param> /// <param name="srcH">Source image height in pixels</param> /// <param name="srcDelta">Source image horizontal scan line size </param> /// <param name="fDstRotCenterX">Rotation center X location in destination image</param> /// <param name="fDstRotCenterY">Rotation center Y location in destination image</param> /// <param name="fSrcRotCenterX">Rotation center X location in source image</param> /// <param name="fSrcRotCenterY">Rotation center Y location in source image</param> /// <param name="fAngle">Angle of rotation in radians. (if Angle > 0 : CCW for top-bottom [normal] bmp, CW:for bottom-up [reverced] bmp)</param> /// <param name="fScale">Scale of source before apply to destination. (Scale = 1 : no scale)</param> extern void RotateDrawClip1 ( RotatePixel_t *pDstBase, int dstW, int dstH, int dstDelta, RotatePixel_t *pSrcBase, int srcW, int srcH, int srcDelta, float fDstRotCenterX, float fDstRotCenterY, float fSrcRotCenterX, float fSrcRotCenterY, float fAngle, float fScale ); /// <summary> /// Rotate source image and put it on destination image. /// One copy of rotated and scaled source drawn on target. /// Optional external function may be provided for color merge /// [Fast version] /// </summary> /// <param name="dst">Destination image data address</param> /// <param name="dstW">Destination image width in pixels</param> /// <param name="dstH">Destination image height in pixels</param> /// <param name="dstDelta">Destination image horizontal scan line size in bytes (AKA stride)</param> /// <param name="src">Source image data address</param> /// <param name="srcW">Source image width in pixels</param> /// <param name="srcH">Source image height in pixels</param> /// <param name="srcDelta">Source image horizontal scan line size </param> /// <param name="ox">Rotation center X location in destination image</param> /// <param name="oy">Rotation center Y location in destination image</param> /// <param name="px">Rotation center X location in source image</param> /// <param name="py">Rotation center Y location in source image</param> /// <param name="angle">Angle of rotation in radians. (if Angle > 0 : CCW for top-bottom [normal] bmp, CW:for bottom-up [reverced] bmp)</param> /// <param name="scale">Scale of source before apply to destination. (Scale = 1 : no scale)</param> /// <param name="mergeFunc">Callback function to merge new and old pixel value [RotatePixel_t Merger(RotatePixel_t newColor, RotatePixel_t oldColor, void *Param)] NULL=not used</param> /// <param name="mergeParam">Callback function last parameter NULL=not used</param> extern void RotateDrawClipExt1 ( RotatePixel_t *dst, int dstW, int dstH, int dstDelta, RotatePixel_t *src, int srcW, int srcH, int srcDelta, float ox, float oy, float px, float py, float angle, float scale, RotateColorMergerFunc_t mergeFunc ROTATE_DEF_PARAM(NULL), void *mergeParam ROTATE_DEF_PARAM(NULL) ); /// <summary> /// Rotate source image and put it on destination image. /// One copy of rotated and scaled source drawn on target. /// Optional external function may be provided for color merge /// [Fast version] [Double prec arguments] /// </summary> /// <param name="dst">Destination image data address</param> /// <param name="dstW">Destination image width in pixels</param> /// <param name="dstH">Destination image height in pixels</param> /// <param name="dstDelta">Destination image horizontal scan line size in bytes (AKA stride)</param> /// <param name="src">Source image data address</param> /// <param name="srcW">Source image width in pixels</param> /// <param name="srcH">Source image height in pixels</param> /// <param name="srcDelta">Source image horizontal scan line size </param> /// <param name="ox">Rotation center X location in destination image</param> /// <param name="oy">Rotation center Y location in destination image</param> /// <param name="px">Rotation center X location in source image</param> /// <param name="py">Rotation center Y location in source image</param> /// <param name="angle">Angle of rotation in radians. (if Angle > 0 : CCW for top-bottom [normal] bmp, CW:for bottom-up [reverced] bmp)</param> /// <param name="scale">Scale of source before apply to destination. (Scale = 1 : no scale)</param> /// <param name="mergeFunc">Callback function to merge new and old pixel value [RotatePixel_t Merger(RotatePixel_t newColor, RotatePixel_t oldColor, void *Param)] NULL=not used</param> /// <param name="mergeParam">Callback function last parameter NULL=not used</param> extern void RotateDrawClipExt1D ( RotatePixel_t* dst, int dstW, int dstH, int dstDelta, RotatePixel_t* src, int srcW, int srcH, int srcDelta, double ox, double oy, double px, double py, double angle, double scale, RotateColorMergerFunc_t mergeFunc ROTATE_DEF_PARAM(NULL), void* mergeParam ROTATE_DEF_PARAM(NULL) ); /// <summary> /// Rotate source image and put it on destination image. /// One copy of rotated and scaled source drawn on target. /// Optional external function may be provided for color merge /// [Extra Fast version] [Uses fixed point integers inside] /// </summary> /// <param name="dst">Destination image data address</param> /// <param name="dstW">Destination image width in pixels</param> /// <param name="dstH">Destination image height in pixels</param> /// <param name="dstDelta">Destination image horizontal scan line size in bytes (AKA stride)</param> /// <param name="src">Source image data address</param> /// <param name="srcW">Source image width in pixels</param> /// <param name="srcH">Source image height in pixels</param> /// <param name="srcDelta">Source image horizontal scan line size </param> /// <param name="ox">Rotation center X location in destination image</param> /// <param name="oy">Rotation center Y location in destination image</param> /// <param name="px">Rotation center X location in source image</param> /// <param name="py">Rotation center Y location in source image</param> /// <param name="angle">Angle of rotation in radians. (if Angle > 0 : CCW for top-bottom [normal] bmp, CW:for bottom-up [reverced] bmp)</param> /// <param name="scale">Scale of source before apply to destination. (Scale = 1 : no scale)</param> /// <param name="mergeFunc">Callback function to merge new and old pixel value [RotatePixel_t Merger(RotatePixel_t newColor, RotatePixel_t oldColor, void *Param)] NULL=not used</param> /// <param name="mergeParam">Callback function last parameter NULL=not used</param> extern void RotateDrawClipExt2 ( RotatePixel_t *dst, int dstW, int dstH, int dstDelta, RotatePixel_t *src, int srcW, int srcH, int srcDelta, float ox, float oy, float px, float py, float angle, float scale, RotateColorMergerFunc_t mergeFunc ROTATE_DEF_PARAM(NULL), void *mergeParam ROTATE_DEF_PARAM(NULL) ); #endif
C
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <string.h> // This program has errors. Check again bool valid(char number[]) { bool result = false; int length = strlen(number); int counter = 0; int s1 = 0; int s2 = 0; for(int i = length - 1; i >= 0; i--) { counter++; int digit = number[i] - '0'; if((counter%2)!=0) { s1 = s1 + digit; } else { digit = digit * 2; s2 = s2 + digit; } } if((s1 + s2)%10 == 0) { result = true; } return result; } int main (int argc, char *argv[]) { bool iscc = valid(argv[1]); if (iscc) { printf("It is a valid credit card."); } else { printf("Scammed."); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print_error.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hjeannin <hjeannin@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/11/24 18:20:17 by hjeannin #+# #+# */ /* Updated: 2015/12/18 14:25:02 by hjeannin ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "scop.h" #include <stdio.h> #include <stdlib.h> int print_error(char *msg, int code) { if (msg) ft_putstr_fd(msg, 2); return (code); } int check_gl_error(char const *file, int line) { GLenum err; err = glGetError(); if (err != GL_NO_ERROR) { if (err == GL_INVALID_ENUM) dprintf(2, "GL: Invalid enum in %s line %d\n", file, line); else if (err == GL_INVALID_VALUE) dprintf(2, "GL: Invalid value in %s line %d\n", file, line); else if (err == GL_INVALID_OPERATION) dprintf(2, "GL: Invalid operation in %s line %d\n", file, line); else if (err == GL_INVALID_FRAMEBUFFER_OPERATION) dprintf(2, "GL: Invalid framebuffer operation in %s line %d\n", file, line); else if (err == GL_OUT_OF_MEMORY) dprintf(2, "GL: Out of memory in %s line %d\n", file, line); exit(0); return (0); } return (1); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ /* Variables and functions */ double word_weight (int) ; double similarity (int *x, int *y, double *a, double *b) { *a = 0, *b = 0; int xi = 0, yi = 0; while (x[xi] || y[yi]) { if (x[xi] == y[yi]) { *a += 2.0 * word_weight (x[xi]); xi++; yi++; } else { if (x[xi] && (y[yi] == 0 || x[xi] < y[yi])) { *b += word_weight (x[xi]); xi++; } else { *b += word_weight (y[yi]); yi++; } } } if (*a + *b < 1e-9) { return -1.0; } return (*a - *b) * 1.0 / (*a + *b); }
C
/* Copyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com> Licensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "morn_math.h" #ifdef _MSC_VER #define stricmp _stricmp #else #define stricmp strcasecmp #endif struct CalculateFunction { char name[32]; union { double (*func1)(double); double (*func2)(double,double); double (*func3)(double,double,double); double (*func4)(double,double,double,double); double (*func5)(double,double,double,double,double); double (*func6)(double,double,double,double,double,double); double (*func7)(double,double,double,double,double,double,double); double (*func8)(double,double,double,double,double,double,double,double); }; }; struct CalculateFunction morn_calculate_function[128]; int morn_calculate_function_num=0; void m_CalculateFunction(const char *name,void *func) { mException(func==NULL,EXIT,"invalid input"); int num=morn_calculate_function_num; mException(num>128,EXIT,"calculate function register error"); morn_calculate_function_num+=1; strncpy(morn_calculate_function[num].name,name,32); morn_calculate_function[num].func1 = (double (*)(double))func; } struct CalculateInfo { char type; double value; }; double GetValue(char **ptr); double Calculate(char **ptr) { MArray *array = mArrayCreate(sizeof(struct CalculateInfo)); char *p = *ptr; struct CalculateInfo info; info.type=(*p=='-')?(p++,'-'):'+'; info.value = GetValue(&p); mArrayWrite(array,&info); while((*p>=32)&&(*p!=')')&&(*p!=',')) { if((*p!='+')&&(*p!='-')&&(*p!='*')&&(*p!='/')&&(*p!='%')&&(*p!='^')) return NAN; info.type=*p; p++; *ptr=p;info.value=GetValue(ptr);if(mIsNan(info.value)) return NAN; p=*ptr; mArrayWrite(array,&info); } struct CalculateInfo *adata = array->data; int num = array->num; for(int i=num-1;i>0;i--) { struct CalculateInfo *cal = adata+i; struct CalculateInfo *pre = adata+i-1; if(cal->type=='^') {cal->type='=';cal->value=pow(pre->value,cal->value);pre->value=cal->value;} } for(int i=1;i<num;i++) { struct CalculateInfo *cal = adata+i; struct CalculateInfo *pre = adata+i-1; if(cal->type=='=') {cal->value= pre->value;} else if(cal->type=='*') {cal->type='=';cal->value=pre->value*cal->value;} else if(cal->type=='/') {cal->type='=';cal->value=pre->value/cal->value;} else if(cal->type=='%') {cal->type='=';cal->value=fmod(pre->value,cal->value);} } for(int i=num-1;i>0;i--) { struct CalculateInfo *cal = adata+i; struct CalculateInfo *pre = adata+i-1; if(cal->type=='=') {pre->value=cal->value;} } double rst=0; for(int i=0;i<num;i++) { struct CalculateInfo *cal = adata+i; if(cal->type=='+') rst+=cal->value; else if(cal->type=='-') rst-=cal->value; } mArrayRelease(array); *ptr = p; return rst; } double GetValue(char **ptr) { char *p = *ptr; double value,v1,v2,v3,v4,v5,v6,v7,v8; int sign=0;if(*p=='-') {sign=1;p++;} else if(*p=='+') {sign=0;p++;} char *str=p; while((*p!=0)&&(*p!=')')&&(*p!=',')&&(*p!='+')&&(*p!='-')&&(*p!='*')&&(*p!='/')&&(*p!='%')&&(*p!='^')) { if(*p=='(') { p[0]=0;p=p+1;*ptr=p; if(p==str+1) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')?value:NAN;} if(stricmp(str,"abs" )==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? ABS(value):NAN;} if(stricmp(str,"sqrt" )==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? sqrt(value):NAN;} if(stricmp(str,"exp" )==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? exp(value):NAN;} if(stricmp(str,"ln" )==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? log(value):NAN;} if(stricmp(str,"log10")==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? log10(value):NAN;} if(stricmp(str,"sin" )==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? sin(value):NAN;} if(stricmp(str,"cos" )==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? cos(value):NAN;} if(stricmp(str,"tan" )==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? tan(value):NAN;} if(stricmp(str,"cot" )==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? 1/tan(value):NAN;} if(stricmp(str,"asin" )==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? asin(value):NAN;} if(stricmp(str,"acos" )==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? acos(value):NAN;} if(stricmp(str,"atan" )==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? atan(value):NAN;} if(stricmp(str,"acot" )==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')?atan(1/value):NAN;} if(stricmp(str,"ceil" )==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? ceil(value):NAN;} if(stricmp(str,"floor")==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? floor(value):NAN;} if(stricmp(str,"round")==0) {value=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')? round(value):NAN;} if(stricmp(str,"min")==0) {v1=Calculate(ptr);p=*ptr;if(*p!=','){return NAN;}*ptr=p+1;v2=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')?MIN(v1,v2):NAN;} if(stricmp(str,"max")==0) {v1=Calculate(ptr);p=*ptr;if(*p!=','){return NAN;}*ptr=p+1;v2=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')?MAX(v1,v2):NAN;} if(stricmp(str,"pow")==0) {v1=Calculate(ptr);p=*ptr;if(*p!=','){return NAN;}*ptr=p+1;v2=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')?pow(v1,v2):NAN;} if(stricmp(str,"log")==0) {v1=Calculate(ptr);p=*ptr;if(*p!=','){return NAN;}*ptr=p+1;v2=Calculate(ptr);p=*ptr;*ptr=p+1;return (*p==')')?(log(v2)/log(v1)):NAN;} for(int i=0;i<morn_calculate_function_num;i++) { if(stricmp(str,morn_calculate_function[i].name)==0) { v1=Calculate(ptr);p=*ptr;*ptr=p+1; if(*p==')') return morn_calculate_function[i].func1(v1); v2=Calculate(ptr);p=*ptr;*ptr=p+1; if(*p==')') return morn_calculate_function[i].func2(v1,v2); v3=Calculate(ptr);p=*ptr;*ptr=p+1; if(*p==')') return morn_calculate_function[i].func3(v1,v2,v3); v4=Calculate(ptr);p=*ptr;*ptr=p+1; if(*p==')') return morn_calculate_function[i].func4(v1,v2,v3,v4); v5=Calculate(ptr);p=*ptr;*ptr=p+1; if(*p==')') return morn_calculate_function[i].func5(v1,v2,v3,v4,v5); v6=Calculate(ptr);p=*ptr;*ptr=p+1; if(*p==')') return morn_calculate_function[i].func6(v1,v2,v3,v4,v5,v6); v7=Calculate(ptr);p=*ptr;*ptr=p+1; if(*p==')') return morn_calculate_function[i].func7(v1,v2,v3,v4,v5,v6,v7); v8=Calculate(ptr);p=*ptr;*ptr=p+1; if(*p==')') return morn_calculate_function[i].func8(v1,v2,v3,v4,v5,v6,v7,v8); return NAN; } } return NAN; } p++;*ptr=p; } if(((str[0]=='p')||(str[0]=='P'))&&((str[1]=='i')||(str[1]=='I'))) value=MORN_PI; else if((str[0]=='e')||(str[0]=='E')) value=MORN_E; else if((str[0]>='0')&&(str[0]<='9')) value = atof(str); else return NAN; return (sign==0)?value:(0-value); } double mCalculate(char *str) { int l = strlen(str)+1; char *buff = (char *)malloc(l*sizeof(char)); char *p=buff; int i=0,j=0;for(;i<l;i++) if(str[i]>' ') {buff[j]=str[i];j++;} double rst = Calculate(&p); free(buff); return rst; }
C
// Program: Ls.c -- Used to show the files inside a directory #include <dirent.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { DIR *dir; // Returned by opendir struct dirent *direntry; // Returned by readdir char thisDir[201]; char *dirName; // If there is no argument with the program name use current directory if (argc <= 1 ) { if (getcwd(thisDir, 200) == -1) { // Getting current directory perror("getcwd"); exit(1); } dirName = thisDir; } else // Use the directory name specified dirName = argv[1]; // Directory must exist and have read permission if ((dir = opendir(dirName)) == NULL) { perror("opendir"); exit(2); } // Till there are entries inside the directory while ((direntry = readdir(dir)) != NULL) printf("%10d %s\n", direntry->d_ino, direntry->d_name); closedir(dir); exit(0); }
C
// // Created by cuixin on 2019-12-22. // // // Created by cuixin on 2019-12-22. // #include <stdio.h> #include <string.h> //通过排序的最大文本行数 #define MAXLINES 5000 char *lineptr[MAXLINES]; //指向文本行的指针数组 int readlines(char *lineptr[], int nlines); int readlines_v2(char *lineptr[], int maxlines, char *storeArr, int fullLength, char *currentStoreArr); void writelines(char *lineptr[], int nlines); int getline_v1(char s[], int lim); void qsort(char *lineptr[], int left, int right); char *alloc(int n); void afree(char *p); #define ALLOCSIZE 10000 /* 可用空间大小 */ static char allocbuf[ALLOCSIZE]; /* alloc 使用的存储区域*/ static char *allocp = allocbuf; /* 保存下一个空闲的位置*/ char *alloc(int n) { /* 返回指向n个字符首字符地址的指针*/ if (allocbuf + ALLOCSIZE - allocp >= n) { /*有足够的空闲空间*/ allocp += n; return allocp - n; } else { return 0; //c语言保证0永远不会是有效的数据地址。 } } void afree(char *p) { /*释放从p指向的存储区*/ if (p >= allocbuf && p < allocbuf + ALLOCSIZE) { allocp = p; } } //对输入的文本行进行排序 int main() { // int nlines; //读取的输入行数目 // char storeArr[ALLOCSIZE]; // char *currentArr = storeArr; // if ((nlines = readlines_v2(lineptr, MAXLINES, storeArr, ALLOCSIZE, currentArr)) >= 0) { // qsort(lineptr, 0, nlines - 1); // printf("\n\n"); // writelines(lineptr, nlines); // return 0; // } else { // printf("error: input too big to sort"); // return 1; // } printf("%d", (0 == NULL) ? 1: -1); } #define MAXLEN 1000 //定义输入文本行的最大长度 //readlines函数,读取输入行 int readlines(char *lineptr[], int maxlines) { int len, nlines; char *p, line[MAXLEN]; nlines = 0; while ((len = getline_v1(line, MAXLEN)) > 0) { if (nlines >= maxlines || (p = alloc(len)) == NULL) { return -1; } else { line[len - 1] = '\0'; //删除换行符 strcpy(p, line); lineptr[nlines++] = p; } } return nlines; } //readlines函数,读取输入行 int readlines_v2(char *lineptr[], int maxlines, char *storeArr, int fullLength, char *currentStoreArr) { int len, nlines; char *p, line[MAXLEN]; nlines = 0; while ((len = getline_v1(line, MAXLEN)) > 0) { if (nlines >= maxlines || (storeArr + fullLength) < (currentStoreArr + len)) { return -1; } else { p = currentStoreArr; line[len - 1] = '\0'; //删除换行符 strcpy(p, line); currentStoreArr += len; lineptr[nlines++] = p; } } return nlines; } void writelines(char *lineptr[], int nlines) { int i; for (int i = 0; i < nlines; i++) { printf("%s\n", lineptr[i]); } } void writelines_v2(char *lineptr[], int nlines) { while (nlines-- > 0) { printf("%s\n", *lineptr++); } } void qsort(char *v[], int left, int right) { int i, last; void swap(char *v[], int i, int j); if (left >= right) { return; } swap(v, left, (left + right) / 2); last = left; //划分交换 for (int i = left + 1; i <= right; i++) { if (strcmp(v[i], v[left]) < 0) { swap(v, ++last, i); } } swap(v, left, last); qsort(v, left, last - 1); qsort(v, last + 1, right); } void swap(char *v[], int i, int j) { char *temp; temp = v[i]; v[i] = v[j]; v[j] = temp; } /** * 将一行读入s中并返回其长度 * @param s 读入s中 * @param lim * @return 当前行的长度 */ int getline_v1(char s[], int lim) { int c, i; for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) { s[i] = c; } if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; return i; }
C
# include <stdio.h> int main () { // Arreglo de enteros int integers[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Iterar arreglo int size = sizeof(integers)/sizeof(int); for (int i = 0; i < size; i++) { printf("%i\n", integers[i]); } return 0; }
C
#include "ls.h" int main(int ac, char **av) { if (ac != 3) return (1); char *path; size_t len; len = ft_strlen(av[1]) + 1 + ft_strlen(av[2]); path = ft_strnew(len); ft_strncpy(path, av[1], ft_strlen(av[1])); ft_strncpy(&path[ft_strlen(av[1])], "/", 1); ft_strncpy(&path[ft_strlen(av[1]) + 1], av[2], ft_strlen(av[2])); ft_putstr(path); free(path); return (0); }
C
//SUBSTITUTION #include <stdio.h> #include <cs50.h> #include <string.h> #include <ctype.h> bool check_string (string s) { int len = strlen(s); if (len != 26) { return true; } int f[26] = { 0 }; for (int i = 0; i < len; i++) { if (isdigit(s[i])) { return true; } int index = toupper(s[i]) - 'A'; if (f[index] > 0) { return true; } f[index]++; } return false; } int main (int argc, string argv[]) { if (argc != 2) { printf("Usage: ./substitution key\n"); return 1; } else if (check_string(argv[1])) { printf("Key must contain 26 characters.\n"); return 1; } string chars = argv[1]; string str = get_string("plaintext: "); printf("ciphertext: "); for (int i = 0; i < strlen(str); i++) { if (isalpha(str[i])) { if (isupper(str[i])) { int a = str[i] - 64; printf("%c", toupper(chars[a-1])); } else if (!isupper(str[i])) { int a = str[i] - 96; printf("%c", tolower(chars[a-1])); } } else { printf("%c", str[i]); } } printf("\n"); return 0; }