language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "queue.h" void insertq(Queue* q, int item) { int size = q->size; if ((q->front == 0 && q->rear == size - 1) || (q->front == q->rear + 1)) { printf("queue is full to insert %d", item); display(q); return; } else if (q->rear == - 1) { q->rear++; q->front++; } else if (q->rear == size - 1 && q->front > 0) { q->rear = 0; } else { q->rear++; } q->arr[q->rear] = item; } void display(Queue* q) { int size = q->size; int i; printf("\n"); if (q->front > q->rear) { for (i = q->front; i < size; i++) { printf("%d ", q->arr[i]); } for (i = 0; i <= q->rear; i++) printf("%d ", q->arr[i]); }else if(q->front == -1){ printf("The queue is empty"); } else { for (i = q->front; i <= q->rear; i++) printf("%d ", q->arr[i]); } } bool hasNext(Queue *q){ if(q->front!=-1) return true; return false; } void popq(Queue* q) { int size = q->size; if (q->front == - 1) { printf("Queue is empty "); } else if (q->front == q->rear) { // printf("\n %d deleted", q->arr[q->front]); q->front = - 1; q->rear = - 1; } else { // printf("\n %d deleted", q->arr[q->front]); q->front = (q->front+1)%q->size; } } Queue* newQueue(int length){ Queue* q = calloc(1,sizeof(Queue)); q->arr = calloc(length,sizeof(int)); q->front = -1; q->rear = -1; q->byteSize = sizeof(int)*length; q->size = length; return q; } void delQueue(Queue **q){ if(*q==NULL) return; free((*q)->arr); // q->byteSize = -1; free(*q); *q = NULL; }
C
#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <string.h> #define STR_SIZE 19 int main() { int file = open("ex1.txt", O_RDWR); char str[19] = "This is a nice day"; char *map = mmap(NULL, STR_SIZE - 1, PROT_READ | PROT_WRITE, MAP_SHARED, file, 0); ftruncate(file, STR_SIZE-1); memcpy(map, str, STR_SIZE - 1); close(file); }
C
int len_list=0; //lunghezza della stringa formata dai nomi di tutti i file struct nomeFile { char nome[50]; struct nomeFile *next; }; void reverse(char s[]) //inverte l'ordine delle lettere di una stringa { int i, j; char c; for (i = 0, j = strlen(s)-1; i<j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } } void itoa(int n, char s[]) //Integer to ASCII { int i, sign; if ((sign = n) < 0) /* record sign */ n = -n; /* make n positive */ i = 0; do /* generate digits in reverse order */ { s[i++] = n % 10 + '0'; /* get next digit */ } while ((n /= 10) > 0); /* delete it */ if (sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s); } char* riceviMessaggio(int sk) { char buffer[1024]; char lens[5]; int ret=recv(sk,(void*)lens,5,0); int leni=atol(lens); ret=recv(sk,(void*)buffer,leni,0); char *msg=(char*) malloc(leni); int i; for(i=0;i<leni;i++) { msg[i]=buffer[i]; } msg[leni]='\0'; if(ret==-1 || ret<strlen(msg)) { printf("Errore nella ricezione dei dati\n"); return "NULL"; } return msg; } void inviaMessaggio(int sk,char msg[],int nbyte) //invia dimensione del dato e dato { char lis[5]; itoa(nbyte,lis); int ret=send(sk,(void*)lis,5,0); ret=send(sk,(void*)msg,nbyte,0); if(ret==-1 || ret<strlen(msg)) { printf("Errore nell'invio dei dati\n"); } return; } char* estraiNomeFile(char path[]) //estrae il nome del file dal path { char *temp=NULL; char *name; int i; int count=0; for(i=0;i<strlen(path);i++) //conto il numero di slash del path { if(path[i]=='/') { count++; } } if(count==0) { return path; } temp=strtok(path,"/"); if(count==1) { return temp; } else { while(temp!=NULL) { temp=strtok(NULL,"/"); if(temp!=NULL) { name=temp; } } return name; } } struct nomeFile *inserimentoInLista(struct nomeFile *lista,char nome[]) { struct nomeFile *p; struct nomeFile *temp; if(lista==NULL) { p=(struct nomeFile *)malloc(sizeof(struct nomeFile)); strcpy(p->nome,nome); len_list=len_list+strlen(p->nome); p->next=NULL; return p; } p=lista; if(strcmp(p->nome,nome)==0) //verifico che in lista non ci siano elementi con lo stesso nome { return lista; } while(p->next!=NULL) { if(strcmp(p->nome,nome)==0) { return lista; } p=p->next; } temp=(struct nomeFile *)malloc(sizeof(struct nomeFile)); strcpy(temp->nome,nome); len_list=len_list+strlen(temp->nome); temp->next=NULL; p->next=temp; return lista; } char *stampaLista(struct nomeFile *lista) { if(lista==NULL) { return "\0"; } struct nomeFile *p; char *listaCat=(char*) malloc(len_list); p=lista; while(p!=NULL) { strcat(listaCat,p->nome); strcat(listaCat," "); p=p->next; } return listaCat; } struct nomeFile *svuotaLista(struct nomeFile* lista) //elimina i file dall'elenco e dall'hd { char eliminazione[60]; struct nomeFile *p=lista; while(lista!=NULL) { strcpy(eliminazione,"rm "); lista=lista->next; p->next=NULL; system(strcat(eliminazione,p->nome)); free(p); p=lista; } return lista; } int invioFile(char pathFile[],int sk,char comando[]) { char csize[5]; int ret,size; FILE *fp; fp=fopen(pathFile,"r"); if(fp==NULL) { printf("Impossibile leggere il file\n"); return 1; } struct stat info; ret=stat(pathFile,&info); size=info.st_size; //grandezza del file in byte itoa(size,csize); if(strcmp(comando,"NULL")!=0) { inviaMessaggio(sk,comando,strlen(comando)); }; char path[50]; strcpy(path,estraiNomeFile(pathFile)); inviaMessaggio(sk,path,strlen(path)); inviaMessaggio(sk,csize,strlen(csize)); if(strcmp(riceviMessaggio(sk),"KO")==0) { return 2; } while(!feof(fp)) { char buffer[1024]; ret=fread(buffer,1,sizeof(buffer)-1,fp); buffer[ret]='\0'; inviaMessaggio(sk,buffer,ret); } printf("File %s inviato con successo\n",path); fclose(fp); return 0; } int scriviFile(char nome[],int sk,int size) { FILE *fp; int ret,i; fp=fopen(nome,"w"); if(fp==NULL) { inviaMessaggio(sk,"KO",2); //Impossibile scrivere il file return 1; } inviaMessaggio(sk,"OK",2); for(i=0;i!=size;) { int temp=size-(1023+i); if(temp<0) { temp=temp*(-1); ret=fwrite(riceviMessaggio(sk),1,size-i,fp); i=i+1023-temp; continue; } ret=fwrite(riceviMessaggio(sk),1,1023,fp); i=i+1023; } fclose(fp); return 0; } void stampaHelp() { printf("Nome: compressor-client\n"); printf("Sinossi: compressor-client <host-remoto> <porta>\n"); printf("Descrizione: client per la compressione di file\n"); printf("Comandi:\n\n"); printf("help: visualizza questa guida.\n\n"); printf("configure-compressor [compressor]: configura il server in modo da impostare l'algoritmo di compressione scelto (bzip2, gnuzip).\n\n"); printf("configure-name [name]: imposta il nome dell'archivio che si vuole ricevere dal server.\n\n"); printf("show-configuration: visualizza il nome dell'archivio e il compressore impostati.\n\n"); printf("send [file]: invia il file al server per la compressione. Se vengono inviati piu' file con lo stesso nome verra' immesso nell'archivio solo l'ultimo file inviato al server.\n\n"); printf("compress [path]: crea un file compresso con l'algoritmo specificato dal comando 'configure-compressor' e con il nome impostato tramite il comando 'configure-name'. Se nel path specificato e' presente un file con lo stesso nome ed estensione impostati nel programma esso sara' sovrascritto. Il file conterra' i file inviati al server. Il path deve terminare con il carattere '/' . Per utilizzare il path dal quale si esegue il client immettere come argomento '.'. \n\n"); printf("quit: termina l'esecuzione del programma.\n\n"); return; } //INIZIO SEZIONE DATI E METODI PER THREAD //semaforo globale inizializzato pthread_mutex_t request_mutex=PTHREAD_MUTEX_INITIALIZER; //variabile condition globale pthread_cond_t got_request=PTHREAD_COND_INITIALIZER; int num_requests=0; //numero delle richieste pendenti struct request //struttura di una richiesta { int socket; char ip[15]; struct request* next; }; struct request* list_requests=NULL; //prima richiesta struct request* last_request=NULL; //ultima richiesta void add_request(int request_num,char ip[],pthread_mutex_t* p_mutex,pthread_cond_t* p_cond_var) { int rc; struct request* a_request; a_request=(struct request*)malloc(sizeof(struct request)); if(!a_request) { printf("Errore\n"); exit(1); } a_request->socket=request_num; strcpy(a_request->ip,ip); a_request->next=NULL; //blocco il semaforo per assicurarmi accesso atomico alla lista rc=pthread_mutex_lock(p_mutex); if(num_requests==0) { list_requests=a_request; last_request=a_request; } else { last_request->next=a_request; last_request=a_request; } num_requests++; //sblocco il semaforo rc=pthread_mutex_unlock(p_mutex); //invio segnale alla variabile condition - c'è una nuova richiesta da gestire rc=pthread_cond_signal(p_cond_var); } struct request* get_request(pthread_mutex_t* p_mutex) { int rc; struct request* a_request; rc=pthread_mutex_lock(p_mutex); if(num_requests>0) { a_request=list_requests; list_requests=a_request->next; if(list_requests==NULL) { last_request=NULL; } num_requests--; } else { a_request=NULL; } rc=pthread_mutex_unlock(p_mutex); return a_request; } void handle_request(struct request* a_request,int thread_id) { char cread[10]; char sid[3]; itoa(thread_id,sid); strcpy(cread,"mkdir "); system(strcat(cread,sid)); if(a_request) { printf("Thread %d sta gestendo la richiesta del client %s\n",thread_id,a_request->ip); } struct nomeFile *lista; lista=NULL; char compType[7]; char confName[60]; strcpy(compType,"gnuzip"); strcpy(confName,"archivio"); while(1) { char *comando=riceviMessaggio(a_request->socket); //il server attende un comando dal client int deleted=0; //mi dice se i file utente sono già stati cancellati o no if(strcmp(comando,"help")==0) { printf("CLIENT %s eseguito comando help\n",a_request->ip); continue; } if(strcmp(comando,"configure-compressor")==0) { char *argomento=riceviMessaggio(a_request->socket); strcpy(compType,argomento); inviaMessaggio(a_request->socket,"Compressore configurato correttamente\n",strlen("Compressore configurato correttamente\n")); free(argomento); free(comando); printf("CLIENT %s eseguito comando configure-compressor %s\n",a_request->ip,compType); continue; } if(strcmp(comando,"configure-name")==0) { strcpy(confName,riceviMessaggio(a_request->socket)); inviaMessaggio(a_request->socket,"Nome configurato correttamente\n",strlen("Nome configurato correttamente\n")); free(comando); printf("CLIENT %s eseguito comando configure-name %s\n",a_request->ip,confName); continue; } if(strcmp(comando,"show-configuration")==0) { inviaMessaggio(a_request->socket,confName,strlen(confName)); inviaMessaggio(a_request->socket,compType,strlen(compType)); printf("CLIENT %s eseguito comando show-configuration\n",a_request->ip); continue; } if(strcmp(comando,"send")==0) { deleted=1; char nome[60]; itoa(thread_id,nome); strcat(nome,"/"); strcat(nome,riceviMessaggio(a_request->socket)); int size=atoi(riceviMessaggio(a_request->socket)); if(scriviFile(nome,a_request->socket,size)!=0) { strtok(nome,"/"); strcpy(nome,strtok(NULL,"/")); printf("SERVER: errore durante la scrittura del file %s inviato dal client %s\n",nome,a_request->ip); } else { lista=inserimentoInLista(lista,nome); strtok(nome,"/"); strcpy(nome,strtok(NULL,"/")); printf("SERVER: ricevuto il file %s dal client %s\n",nome,a_request->ip); } continue; } if(strcmp(comando,"compress")==0) { if(lista==NULL) //non ci sono file da comprimere { inviaMessaggio(a_request->socket,"NO",strlen("NO")); continue; } inviaMessaggio(a_request->socket,"SI",strlen("SI")); int i; printf("%d\n",len_list); char *comandi=(char*)malloc(sizeof(char)*(len_list+15)); char *estensioni[]={".tgz ",".bz2 ",NULL}; if(strcmp(compType,"gnuzip")==0) { strcpy(comandi,"tar -czf "); i=0; } else { strcpy(comandi,"tar -cjf "); i=1; } printf("SERVER: creazione del file compresso %s%s richiesta dal client %s\n",confName,estensioni[i],a_request->ip); system(strcat(strcat(strcat(comandi,confName),estensioni[i]),stampaLista(lista))); lista=svuotaLista(lista); if(invioFile(strncat(confName,estensioni[i],4),a_request->socket,"NULL")==0) { printf("SERVER: spedito il file %s richiesto dal client %s\n",confName,a_request->ip); inviaMessaggio(a_request->socket,confName,strlen(confName)); strcpy(comandi,"rm "); system(strcat(comandi,confName)); char *temp=strtok(confName,"."); strcpy(confName,temp); } free(comandi); free(comando); deleted=1; continue; } if(strcmp(comando,"quit")==0) { printf("SERVER: client %s disconnesso\n",a_request->ip); free(comando); if(deleted==0) { lista=svuotaLista(lista); } strcpy(cread,"rmdir "); system(strcat(cread,sid)); close(a_request->socket); return; } printf("Il client ha chiuso la connessione in modo anomalo, termino\n"); if(deleted==0) { lista=svuotaLista(lista); } strcpy(cread,"rmdir "); system(strcat(cread,sid)); close(a_request->socket); return; } } void* handle_request_loop(void* data) { int rc; struct request* a_request; int thread_id=*((int*)data); printf("Starting thread %d\n",thread_id); while(1) { rc=pthread_mutex_lock(&request_mutex); if(num_requests>0) { a_request=get_request(&request_mutex); if(a_request) { rc=pthread_mutex_unlock(&request_mutex); handle_request(a_request,thread_id); free(a_request); } } else { rc=pthread_cond_wait(&got_request, &request_mutex); } } }
C
/* * stack.c: a file that implements the fundamental operations on the stack such as * adding and deleting elements * * NOTE: mainly used the dynamic memory files as a guide :) * ANOTHER NOTE: this is the same stack from rpn but adapted for this hw * */ #include "stack.h" #include <stdio.h> #include <string.h> #include <stdlib.h> int size; void init_stack(stack *s) { s->top = NULL; size = 0; } void push(stack *s, int x) { stack_elt *elt; // allocate new mem elt = malloc(sizeof(*elt)); // if malloc fails fat L if (elt == NULL) { printf("Yikes boo boo ya ran outta memory :(\n"); exit(1); } elt->x = x; elt->next = s->top; s->top = elt; size++; } int pop(stack *s) { stack_elt *elt; int popped = 0; if (s->top != NULL) { elt = s->top; popped = elt->x; if (size == 1) { s->top = NULL; } else { s->top = elt->next; } size--; free(elt); } return popped; } int peek(stack *s) { stack_elt *elt; int peek = 0; if (s->top != NULL) { elt = s->top; peek = elt->x; } return peek; } void clear(stack *s) { while (s->top) { pop(s); } }
C
#include<stdio.h> int main() { int n,i,j,k,h,l,a,b[50]; while(scanf("%d",&a)==1) { for(j=1;j<=a;j++) { h=0; l=0; scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&b[i]); for(i=1;i<n;i++) {if(b[i]>b[i-1]) h=h+1; if(b[i-1]>b[i]) l=l+1;} printf("Case %d: %d %d\n",j,h,l); } } return 0; }
C
/***************************************************************************//** @file libstephen/log.h @author Stephen Brennan @date Created Sunday, 24 May 2015 @brief Logging facilities for libstephen. @copyright Copyright (c) 2015-2016, Stephen Brennan. Released under the Revised BSD License. See LICENSE.txt for details. *******************************************************************************/ #ifndef LIBSTEPHEN_LOG_H #define LIBSTEPHEN_LOG_H #include "base.h" /** @brief Most fine grained log level -- loggers will report everything. */ #define LEVEL_NOTSET 0 /** @brief Suggested log level for messages useful for debugging. */ #define LEVEL_DEBUG 10 /** @brief Suggested log level for informational messages. */ #define LEVEL_INFO 20 /** @brief Suggested log level for warning messages. */ #define LEVEL_WARNING 30 /** @brief Suggested log level for error messages. */ #define LEVEL_ERROR 40 /** @brief Suggested log level for critical, non-recoverable error messages. */ #define LEVEL_CRITICAL 50 /** @brief Max number of log handlers to be held by a logger. */ #define SMB_MAX_LOGHANDLERS 10 /** @brief The level that the default logger starts at. */ #define SMB_DEFAULT_LOGLEVEL LEVEL_NOTSET /** @brief The file that the default logger points at. */ #define SMB_DEFAULT_LOGDEST stderr /** @brief The format string for default loggers. This is kinda obnoxious because you can only change the formatting characters. The order of the arguments is set in stone, and you can't change that with a format string. The order is filename:line, function, level, message. */ #define SMB_DEFAULT_LOGFORMAT "%s: (%s) %s: %s\n" /** @brief Specifies a log handler. This struct contains the information necessary to deliver a log message to its destination. It has no memory management functions, since you should just pass it by value. */ typedef struct { /** @brief The minimum level this log handler accepts. */ int level; /** @brief The destination file to send to. */ FILE *dst; } smb_loghandler; /** @brief Specifies a logger. This struct represents a logger. You can create it dynamically, but it is entirely possible to create a "literal" for it and declare it statically. */ typedef struct { /** @brief List of log handlers. @see SMB_MAX_LOGHANDLERS */ smb_loghandler handlers[SMB_MAX_LOGHANDLERS]; /** @brief Format string to use for this logger. */ char *format; /** @brief The number of handlers actually contained in the handlers array. */ int num; } smb_logger; /** @brief Initialize a logger object. @param obj Logger to initialize. */ void sl_init(smb_logger *obj); /** @brief Allocate and return a logger object. @returns New logger. */ smb_logger *sl_create(); /** @brief Free resources held by a logger object. @param obj Logger to deinitialize. */ void sl_destroy(smb_logger *obj); /** @brief Free resources and deallocate a logger object. @param obj Logger to deallocate. */ void sl_delete(smb_logger *obj); /** @brief Set the minimum level this logger will report. All loghandlers have levels, but log messages are first filtered by the log level of the logger. If the logger is set to have a higher level, then messages won't even get sent to the handler. The level is inclusive. @param l The logger to set the level of. (NULL for default) @param level The level to set. Can be any integer, but specifically one of the `LEVEL_*` constants would be good. */ void sl_set_level(smb_logger *l, int level); /** @brief Add a log handler to the logger. Loggers have limited space for loghandlers, so this could fail. Loggers are not intended to be array lists containing arbitrary amounts of handlers, and they're not intended to provide convenient access, update, or removal. @param l Logger to add to. (NULL for default) @param h Handler to add to the logger. @param[out] status For error reporting. @exception SMB_INDEX_ERROR If there is no more space for any more handlers. */ void sl_add_handler(smb_logger *l, smb_loghandler h, smb_status *status); /** @brief Remove all handlers from the logger. @param l Logger to clear out. (NULL for default) */ void sl_clear_handlers(smb_logger *l); /** @brief Set the static default logger to be your own. When you use the `D*` logger macros, the default logger is the one you log to. The default logger will report everything to stderr, unless you modify it or set the default logger to a new one. @param l New logger. NULL to reset it to the original one. */ void sl_set_default_logger(smb_logger *l); /** @brief Log a message. This is the function that actually carries out any logging operation. All the logging macros expand to a call to this function. You really don't want to call this function directly, cause you have to provide a ton of information that you can't keep up to date in code, and it can all be provided by preprocessor macros. @param l Logger to send log message to. @param file Name of the code file the message originated from. @param line Line number of the log message. @param function Name of the function the message came from. @param level The log level of this message. @param ... Format string and format arguments, forming the actual message. */ void sl_log(smb_logger *l, char *file, int line, const char *function, int level, ...); /** @brief Log a message. This macro fills out the file, line, and function parameters of sl_log() so that you only need to figure out the logger, level, and message. @param logger Logger to log to. @param level Level the message is at. @param ... Format string and format arguments. */ #define LOG(logger, level, ...) sl_log(logger, __FILE__, __LINE__, __func__, level, __VA_ARGS__); /** @brief Log to default logger at LEVEL_DEBUG. @param ... Format string and format arguments. */ #define DDEBUG(...) LOG(NULL, LEVEL_DEBUG, __VA_ARGS__) /** @brief Log to default logger at LEVEL_INFO. @param ... Format string and format arguments. */ #define DINFO(...) LOG(NULL, LEVEL_INFO, __VA_ARGS__) /** @brief Log to default logger at LEVEL_WARNING. @param ... Format string and format arguments. */ #define DWARNING(...) LOG(NULL, LEVEL_WARNING, __VA_ARGS__) /** @brief Log to default logger at LEVEL_ERROR. @param ... Format string and format arguments. */ #define DERROR(...) LOG(NULL, LEVEL_ERROR, __VA_ARGS__) /** @brief Log to default logger at LEVEL_CRITICAL. @param ... Format string and format arguments. */ #define DCRITICAL(...) LOG(NULL, LEVEL_CRITICAL, __VA_ARGS__) /** @brief Log to any logger at LEVEL_DEBUG. @param logger Logger to log to. @param ... Format string and format arguments. */ #define LDEBUG(logger, ...) LOG(logger, LEVEL_DEBUG, __VA_ARGS__) /** @brief Log to any logger at LEVEL_INFO. @param logger Logger to log to. @param ... Format string and format arguments. */ #define LINFO(logger, ...) LOG(logger, LEVEL_INFO, __VA_ARGS__) /** @brief Log to any logger at LEVEL_WARNING. @param logger Logger to log to. @param ... Format string and format arguments. */ #define LWARNING(logger, ...) LOG(logger, LEVEL_WARNING, __VA_ARGS__) /** @brief Log to any logger at LEVEL_ERROR. @param logger Logger to log to. @param ... Format string and format arguments. */ #define LERROR(logger, ...) LOG(logger, LEVEL_ERROR, __VA_ARGS__) /** @brief Log to any logger at LEVEL_CRITICAL. @param logger Logger to log to. @param ... Format string and format arguments. */ #define LCRITICAL(logger, ...) LOG(logger, LEVEL_CRITICAL, __VA_ARGS__) #endif // LIBSTEPHEN_LOG_H
C
/*====================================================================== BVIS(A,n) BETA-digit vector insertion sort. Inputs A : An array of pointers to m vectors of n BETA-digits. m : A positive BETA-digit. n : A positive BETA-digit. Side Effects Rearranges the pointers in A so that the vectors to which they point are in sorted order. ======================================================================*/ #include "qepcad.h" extern Word BVC(Word *u_,Word *v_,Word n); void BVIS(Word **A, Word m, Word n) { Word i,j; Word *e; for(i = 1; i < m; i++) { e = A[i]; for(j = i-1; (j >= 0) && (BVC(e,A[j],n) < 0); j--) A[j+1] = A[j]; A[j+1] = e; } return; }
C
#include <unistd.h> #include <sys/stat.h> #include <fcntl.h> int main(void) { int out; out = open("file1B.in",O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR); for(int i = 0; i < 1; i++){ write(out,"a",1); } out = open("file4KB.in",O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR); for(int i = 0; i < 4096; i++){ write(out,"b",1); } out = open("file100KB.in",O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR); for(int i = 0; i < 102400; i++){ write(out,"c",1); } out = open("file2MB.in",O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR); for(int i = 0; i < 2097152; i++){ write(out,"d",1); } out = open("file1GB.in",O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR); for(int i = 0; i < 1073741824; i++){ write(out,"e",1); } return(0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> //definicao da estrutura typedef struct aluno { char* nome; int matricula; float p1; float p2; float p3; } Aluno; void imprime_aprovados (int n, Aluno** turma){ float mediaAluno; printf("\nAPROVADOS:\n"); for(int i=0; i<n; i++){ mediaAluno = ((turma[i]->p1 + turma[i]->p2 + turma[i]->p3)/3); if (mediaAluno >= 7){ printf("%s\n", turma[i]->nome); } } } float media_turma (int n, Aluno** turma){ float mediaTurma=0, mediaAluno; for(int i=0; i<n; i++){ mediaAluno = ((turma[i]->p1 + turma[i]->p2 + turma[i]->p3)/3); mediaTurma += mediaAluno; } mediaTurma = (mediaTurma/n); return mediaTurma; } int main (){ int n; printf("Informe o numero de alunos da turma: "); scanf("%d", &n); Aluno** turma = (Aluno**) malloc (n * sizeof(Aluno*)); //aloca vetor de structs for(int i=0; i<n; i++){ turma[i] = (Aluno*) malloc (sizeof(Aluno)); //aloca cada aluno } printf("Preencha as informacoes para cada aluno da turma:\n"); for(int i=0; i<n; i++){ char* nome = (char*) malloc (30*sizeof(char)); //variavel para capturar nome printf("\nALUNO %d:\n",(i+1)); printf("Nome: "); scanf(" %30[^\n]", nome); turma[i]->nome = strdup(nome); //aloca e copia printf("Matricula: "); scanf("%d", &turma[i]->matricula); printf("Nota P1: "); scanf("%f", &turma[i]->p1); printf("Nota P2: "); scanf("%f", &turma[i]->p2); printf("Nota P3: "); scanf("%f", &turma[i]->p3); } printf("\nDados Carregados!\n"); printf("\nTURMA:\n"); for(int i=0; i<n; i++){ //imprime dados da turma, um aluno por linha printf("%s | %d | P1=%.2f, P2=%.2f, P3=%.2f\n", turma[i]->nome, turma[i]->matricula, turma[i]->p1, turma[i]->p2, turma[i]->p3); } imprime_aprovados(n, turma); float media = media_turma(n, turma); printf("\nMEDIA DA TURMA: %.2f\n", media); //libera memoria antes de fechar o programa: for(int i=0; i<n; i++){ free (turma[i]->nome); free (turma[i]); } free(turma); return 0; }
C
// Replace tabs by \t, backspace by \b, backslash by \\ #include<stdio.h> #include<string.h> #define STATE0 0 #define STATE1 1 int main(void){ char str[50]; int len; int state = STATE0; printf("Enter the input string: "); gets(str); len = strlen(str); char *p = str; while(*p){ switch(*p){ case '\t': printf("\\t"); break; case '\b': printf("\\b"); break; case '\\': printf("\\\\"); break; default: printf("%c",*p); } p++; } return 0; }
C
/*ROUSSEAU ET GOUGEON*/ #include <stdio.h> #include <stdlib.h> #include "listchar.h" int main(/*int argc, char const *argv[]*/) { listchar listeTest = newListe(); if (isEmpty(listeTest)) { printf("Liste est vide\n"); } else { printf("Liste non vide\n"); } addCharNext(listeTest, 'c'); addCharNext(listeTest, ' '); addCharNext(listeTest, '1'); addCharNext(listeTest, ' '); addCharNext(listeTest, 't'); addCharNext(listeTest, 'e'); addCharNext(listeTest, 's'); addCharNext(listeTest, 't'); printList(listeTest); if (isEmpty(listeTest)) { printf("Liste est vide\n"); } else { printf("Liste non vide\n"); } gotoFirst(listeTest); mvNext(listeTest); addCharPrev(listeTest, 'e'); addCharPrev(listeTest, 's'); addCharPrev(listeTest, 't'); gotoFirst(listeTest); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "task_types.h" #include "edf/edf.h" #include "rm/rm.h" #include "dm/dm.h" #define RESULTS_FILE_EDF "out/results_edf.txt" #define RESULTS_FILE_RM "out/results_rm.txt" #define RESULTS_FILE_DM "out/results_dm.txt" /* * FORWARD DECLARATIONS */ ProgramInfo parseFile(char *filename); void writeFile(analysis_results results, FILE *file); /* * Function Bodies */ int main(int argc, char *argv[]) { ProgramInfo program = parseFile(argv[1]); FILE *results_edf = fopen(RESULTS_FILE_EDF, "w+"); FILE *results_rm = fopen(RESULTS_FILE_RM , "w+"); FILE *results_dm = fopen(RESULTS_FILE_DM , "w+"); for (int i = 0; i < program.num_task_sets; i++) { // fprintf(stderr, "%i\n", i); TaskSet task_set = program.task_sets[i]; writeFile(edf_analysis(&task_set), results_edf); writeFile( rm_analysis(&task_set), results_rm ); writeFile( dm_analysis(&task_set), results_dm ); } } ProgramInfo parseFile(char *filename) { // TODO: Too long. segment into multiple functions ProgramInfo program; FILE *file = (filename == NULL ? stdin : fopen(filename, "r")); char line[256]; // Should be long enough // First line designating number of task sets if(!fgets(line, sizeof(line), file)) exit(-1); program.num_task_sets = (int) strtoul(line, NULL, 10); program.task_sets = malloc(program.num_task_sets * sizeof(TaskSet)); // Task set declaration for (unsigned int i = 0; i < program.num_task_sets; i++) { TaskSet *task_set = &program.task_sets[i]; // Get line declaring task set if(!fgets(line, sizeof(line), file)) exit(-1); // Set up task set task_set->num_tasks = (unsigned int) strtol(line, NULL, 10); task_set->tasks = malloc(task_set->num_tasks * sizeof(Task)); // Task declaration for (unsigned int j = 0; j < task_set->num_tasks; j++) { // Get line declaring task if(!fgets(line, sizeof(line), file)) exit(-1); Task *task = &task_set->tasks[j]; char *state; // WCET task->wcet = strtod(line, &state); // Deadline task->deadline = strtod(state, &state); // Period task->period = strtod(state, &state); } } return program; } void writeFile(analysis_results results, FILE *file) { fprintf(file, "%i %f\n", results.is_schedulable, results.utilization); }
C
/* Name: cardtest4.c Author: Duy Nguyen Date: 4/26/2015 Assigiment 2 - CS 362 Program: Testing the VILLAGE card */ #include "assert.h" #include "dominion.h" #include <stdio.h> #include "rngs.h" #include <stdlib.h> #include <math.h> int main (int argc, char** argv) { struct gameState *q = newGame(); int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy}; int card = village; int p = rand(); int i; int handBe; int handAf; int deckBe; int deckAf; int r; initializeGame(2, k, p , q); q->hand[0][0] = card; //set the first card to be great hall handBe = q->handCount[0]; printf("_____________________TESTING VILLAGE____________________________\n"); printf("Card on hand (Before): %d \n",handBe); for (i = 0 ; i < handBe; i++) { if (q->hand[0][i] == card) printf ("village\n"); if (q->hand[0][i] == copper) printf ("copper\n"); if (q->hand[0][i] == estate) printf ("estate\n"); } printf("Cards in hand before call to smithy: %d\n", numHandCards(q)); printf("Actions before call to village: %d\n", q->numActions); r = playCard(0, 0, 0, 0, q); printf("r = %d\n",r); handAf = q->handCount[0]; printf("Card on hand (After): %d \n",handAf); for (i = 0 ; i < handAf; i++) { if (q->hand[0][i] == card) printf ("village\n"); if (q->hand[0][i] == copper) printf ("copper\n"); if (q->hand[0][i] == estate) printf ("estate\n"); } printf("Cards in hand after call to smithy: %d\n", numHandCards(q)); printf("Actions after call to village: %d\n", q->numActions); return 0; }
C
#include "rf.h" #include "../oled/oled.h" uint8_t rf_buffer[RF_BUFFER_SIZE]; uint8_t rf_length = 0; uint8_t rf_rssi = 0; uint8_t rf_crc = 0; uint8_t map(uint8_t x, uint8_t in_min, uint8_t in_max, uint8_t out_min, uint8_t out_max) { return (uint8_t)(((int)x - (int)in_min) * ((int)out_max - (int)out_min) / ((int)in_max - (int)in_min) + (int)out_min); } void rf_init() { DDRB |= _BV(PB4); // LED for status indication, ignore anything with "PB4" PORTB |= _BV(PB4); // LED OFF (HIGH = OFF, LOW = ON...) for (int i = 0; i < RF_BUFFER_SIZE; i++) { rf_buffer[i] = 0x00; // clear buffer } TRXPR |= _BV(TRXRST); // reset transceiver IRQ_MASK = 0x00; // disable interrupts TRX_STATE = _BV(TRX_CMD3); // turn off the transceiver // wait certain time _delay_ms(5); PHY_TX_PWR = 0x00; // max tx power (lowest = 0x0B) TRX_CTRL_1 |= _BV(TX_AUTO_CRC_ON); // auto crc calculation //RX_CTRL |= _BV(PDT_THRES1) | _BV(PDT_THRES0); TRX_CTRL_2 |= _BV(OQPSK_DATA_RATE1) | _BV(OQPSK_DATA_RATE1); // 2Mbit/s data rate // enable antenna diversity //ANT_DIV |= _BV(ANT_DIV_EN) | _BV(ANT_EXT_SW_EN) | _BV(ANT_CTRL0); IRQ_MASK = _BV(RX_START_EN) | _BV(RX_END_EN) | _BV(TX_END_EN); // enable interrupts PHY_CC_CCA |= _BV(CHANNEL3) | _BV(CHANNEL1) | _BV(CHANNEL0); // channel (1011) TRX_STATE = (TRX_STATE & ~_BV(TRX_CMD3)) | _BV(TRX_CMD2) | _BV(TRX_CMD1); // state = RX_ON // done initializing } void rf_transmit(uint8_t* frame, uint8_t length) { if (length > 127) { length = 127; } // make sure length is always less than 128 TRX_STATE = (TRX_STATE & ~(_BV(TRX_CMD2) | _BV(TRX_CMD1))) | _BV(TRX_CMD3) | _BV(TRX_CMD0); // state = PLL_ON (TX_ON) while(TRX_STATUS3 & TRX_STATUS0); // wait for PLL to lock on the right frequency PORTB &= ~_BV(PB4); // turn status led on TRXFBST = length + 2; // save the length of the frame in first byte of the transceiver buffer memcpy((void *)(&TRXFBST+1), frame, length); // copy content of the frame into the transceiver buffer TRXPR |= _BV(SLPTR); // send transceiver to sleep -> it will initiate the tx procedure TRXPR &= ~_BV(SLPTR); // it needs to be high for a little bit so lets pull it back down TRX_STATE = (TRX_STATE & ~(_BV(TRX_CMD3) | _BV(TRX_CMD0))) | _BV(TRX_CMD2) | _BV(TRX_CMD1); // switch back to receiver mode RX_ON } ISR(TRX24_TX_END_vect) // interrupt for the end of transmission { PORTB |= _BV(PB4); //display_cnprintf("TRANSMITTED!"); } ISR(TRX24_RX_START_vect) //interrupt for beginning receiving frame { PORTB &= ~_BV(PB4); rf_rssi = PHY_RSSI & 0x1F; // save signal strength 4:0RSSI rx strength (0 min, 28 max) } ISR(TRX24_RX_END_vect) // interrupt for finished receiving frame { rf_crc = (PHY_RSSI & 0x80) >> 7; if (rf_rssi && rf_crc) // if signal strength is more than -90 dBm and CRC is valid { rf_length = TST_RX_LENGTH; memcpy(&rf_buffer, (void*)&TRXFBST, rf_length); // copy content of the buffer to the variable //display_cnprintf("RSSI:%d%% CRC: %d", map(rssi, 0, 28, 0, 100), crc); } else // corrupted package { //display_ciprintf("RSSI:%d%% CRC: %d", map(rssi, 0, 28, 0, 100), crc); } PORTB |= _BV(PB4); } uint8_t rf_available() { if (rf_length) { return rf_length - 2; } return rf_length; } void rf_read(uint8_t* to) { memcpy(to, rf_buffer, rf_length-2); rf_length = 0; } uint8_t link_power() { return map(rf_rssi, 0, 28, 0, 100); } uint8_t crc_res() { return rf_crc; }
C
#include "binary_trees.h" /** * binary_tree_delete - delete a tree * @tree: address of the root * Return: a pointer to the new node, or NULL on failure */ void binary_tree_delete(binary_tree_t *tree) { if (tree != NULL) { if (tree->left != NULL) binary_tree_delete(tree->left); if (tree->right != NULL) binary_tree_delete(tree->right); free(tree); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf_d.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sdurr <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/12/27 15:23:28 by sdurr #+# #+# */ /* Updated: 2015/02/01 16:40:33 by getrembl ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdarg.h> #include "libftprintf.h" #include <limits.h> static int ft_point_space(char *s, int i, char **aff, size_t stop) { size_t j; char *tmp; tmp = ft_strnew(13); j = 0; if (s[i--] == '.') { while (s[i] >= '0' && s[i] <= '9') tmp[j++] = s[i--]; tmp = ft_revers(tmp); j = ft_atoi(tmp); while (j-- > stop) *aff = ft_strjoin(*aff, " "); } if (s[i] == ' ') return (1); return (0); } static void test_r(char **aff, int d, char s, int test) { if (test == -1) *aff = ft_strjoin(*aff, " "); if (s == '-') *aff = ft_strjoin(*aff, ft_itoa(d)); } static int ft_suite(int d, char s, char **aff, size_t j) { d = ft_max_plus_ascii(d); if (s == ' ' && j == 0 && d >= 0) *aff = ft_strjoin(*aff, " "); return (d); } int ft_print_d_h(va_list ap, char *s, int i, char **aff) { int d; char *tmp; size_t j; int test; test = 0; j = 0; if ((tmp = ft_strnew(13)) && (i--)) if (s[i] == 'h' && s[i - 1] == 'h' && (test = 1)) i--; while (s[i] >= '0' && s[i] <= '9') tmp[j++] = s[i--]; tmp = ft_revers(tmp); j = ft_atoi(tmp); d = va_arg(ap, int); if (test == 1) d = ft_suite(d, s[i], aff, j); test = ft_point_space(s, i, aff, j); test_r(aff, d, s[i], test); while (j-- > (ft_strlen(ft_itoa(d)))) (s[i] == '.' || s[i + 1] == '0') ? (*aff = ft_strjoin(*aff, "0")) : (*aff = ft_strjoin(*aff, " ")); if (s[i] != '-') *aff = ft_strjoin(*aff, ft_itoa(d)); return (0); }
C
// // main.c // 07project10 // // Created by cappuccino on 2020/11/26. // #include <stdio.h> #include <ctype.h> int main(int argc, const char * argv[]) { int num = 0; char ch; printf("Enter a sentence:"); while ((ch = getchar()) != '\n') { ch = toupper(ch); switch (ch) { case 'A':case 'E':case 'I':case 'O':case 'U': num += 1; break; default:break; } } printf("Your sentence contains %d vowels",num); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <glib.h> #include <string.h> #include "tm_internal.h" #include "tm_lib.h" struct tag* tma_tag_read(int id) { return (struct tag*) tma_read(TAG, id); } GSList* tma_tag_read_all() { return tma_list(TAG); } struct tag* tma_tag_create(char* description) { struct tag* t = malloc( sizeof( *t ) ); t->description = strdup(description); g_log("tma", G_LOG_LEVEL_DEBUG, "Created tag: %p - %s", t, t->description); tma_create(TAG, t); return t; } struct tag* tma_tag_update(int id, char* description) { struct tag* t = tma_read(TAG, id); if (t != NULL) { free(t->description); t->description = strdup(description); } return t; } int tma_tag_delete(int id) { return tma_delete(TAG, id); }
C
#include<stdio.h> #include<string.h> #include<math.h> void main() { int n,i,m; float sum=0,x,c,a[20]; printf("enter the order of polynomial1\n"); scanf("%d",&n); for(i=0;i<=n;i++) { printf("enter the coff. of x^%d\n",i); scanf("%f",&a[i]); } printf("enter the order of polynomial2\n"); scanf("%d",&m); for(i=0;i<=m;i++) { printf("enter the coff. of x^%d\n",i); scanf("%f",&a[i]); } for(i=n;i>=0;i--) { if(i>0) printf("%.2f*x^%d+",a[i],i); else printf("%.2f*x^%d=",a[i],i); } for(i=n;i>=0;i--) { sum+=a[i]*pow(x,i); } printf("%f",sum); return 0; }
C
/* ID: nasiles1 LANG: C TASK: comehome */ #include <stdio.h> #include <ctype.h> #include <string.h> #define INF 99999999 int a[60][60], p, visit[60], d[60]; int ord(char c) { if (islower(c)) return c - 'a'; else return c - 'A' + 26; } int main() { FILE *fin = fopen("comehome.in", "r"); FILE *fout = fopen("comehome.out", "w"); int i, j, k, u, v, sd, nd, wt, min, ans; char c1[10], c2[10]; for (i = 0; i < 52; i++) { for (j = 0; j < 52; j++) a[i][j] = INF; } fscanf(fin, "%d", &p); for (i = 0; i < p; i++) { fscanf(fin, "%s %s %d", c1, c2, &wt); u = ord(c2[0]); v = ord(c1[0]); k = (wt < a[u][v]) ? wt : a[u][v]; a[u][v] = a[v][u] = k; } memset(visit, 0, sizeof(visit)); for (i = 0; i < 60; i++) d[i] = INF; d[ord('Z')] = 0; while (1) { u = -1; sd = INF; for (i = 0; i < 52; i++) { if (!visit[i] && d[i] < sd) { sd = d[i]; u = i; } } if (u == -1) break; visit[u] = 1; for (v = 0; v < 52; v++) { if (u == v) continue; nd = d[u] + a[u][v]; if (nd < d[v]) d[v] = nd; } } ans = -1; min = INF; for (i = 26; i < 51; i++) { if (d[i] < min) { min = d[i], ans = i; } } fprintf(fout, "%c %d\n", 'A'+ans-26, min); return 0; }
C
/*====================================================================== PTRADV2(L; a,b,Lp) Advance 2. (assuming first two elts of L are pointers) Inputs L : a list of length 2 or more. (first two elts are pointers) Outputs a : the first element of L. b : the second element of L. Lp : the second reductum of L;(assuming a & b are pointers) ======================================================================*/ #include "saclib.h" void PTRADV2(L,a_,b_,Lp_) Word L, **a_, **b_, *Lp_; { Word Lp, *a, *b; PTRADV(Lp,&a,&Lp); PTRADV(Lp,&b,&Lp); *Lp_ = Lp; *a_ = a; *b_ = b; }
C
/* * This file is a part of the EpsiFlash Copyright (c) 2000-2007 Michal * Szwaczko, WireLabs Systems contact: [email protected] */ /*#include <ctype.h>*/ #include "chips.h" #include "hardware.h" extern struct chiptable chips[]; extern unsigned char control; extern void generic_probe(void); int chipindex; int bufferloaded = 0; unsigned char *buffer = NULL; unsigned int buffersize; unsigned short int pagesize; char *fileinthebuffer = NULL; void file_open(void); void file_save(void); void view_buffer(void); void show_help(void); void msg_ready(void); void quit(void); void read_chip(void); void erase_chip(void); void program_chip(void); void chip_selected(void); int probe_chip(void); void show_progress(unsigned long int adr, const char *msg); char *filename; int main(int argc, char *argv[]) { char *mode; if (argc == 1) { printf("Syntax: epsiflash erase|read|burn [filename]\n"); exit (1);} hardware_init(); filename = argv[2]; mode = argv[1]; probe_chip(); printf("Chip: %s - %dKB, %s\n", chips[chipindex].name, chips[chipindex].size / 1024, chips[chipindex].adapter); if (strcmp(chips[chipindex].name,"UNKNOWN")==0) { fprintf(stderr,"Chip is unsupported or not inserted properly\n"); exit(-1); } if (strcmp(mode,"burn")==0) { program_chip(); printf("\n"); exit(1); } if (strcmp(mode,"read")==0) { read_chip(); printf("\n"); exit(1); } if (strcmp(mode, "erase")==0) { erase_chip(); printf("\n"); exit(1); } return 0; } void msg_error(void) { fprintf(stderr, "ERROR ERROR ERROR\n"); } void quit(void) { if (buffer != NULL) free(buffer); power_down(); exit(1); } void chip_selected(void) { buffersize = chips[chipindex].size; pagesize = chips[chipindex].pagesize; if (buffer != NULL) free(buffer); buffer = malloc(buffersize); memset(buffer, 0xFF, buffersize); } void file_open(void) { int fd; size_t fsize; fd = open(filename, O_RDONLY); if (fd < 0) { printf("Error loading file '%s'\n", filename); exit(-1); }; if (buffer != NULL) free(buffer); buffer = malloc(buffersize); memset(buffer, 0xFF, buffersize); fsize = read(fd, buffer, buffersize); } void file_save(void) { int fd; size_t f; fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR); if (fd < 0) { printf( "Error saving file '%s'\n",filename); exit(-1); }; f = write(fd, buffer, buffersize); } void show_progress(long unsigned int adr, const char *mode) { printf("\r"); printf("[%s] Address: 0x%08lX ", mode, adr); fflush(stdout); } void read_chip(void) { int r; power_up(); r = chips[chipindex].read_func(buffersize, pagesize); file_save(); power_down(); } void erase_chip(void) { int r, b; power_up(); r = chips[chipindex].erase_func(buffersize, pagesize); b = generic_blank_check(buffersize, pagesize); power_down(); if (r < 0 || b < 0) msg_error(); } void program_chip(void) { int r, b, v; file_open(); power_up(); chips[chipindex].erase_func(buffersize, pagesize); b = generic_blank_check(buffersize, pagesize); r = chips[chipindex].burn_func(buffersize, pagesize); v = generic_verify(buffersize, pagesize); power_down(); if (r < 0 || b < 0 || v < 0) msg_error(); } int probe_chip (void) { int i; power_up (); for (i = 0; chips[i].name != NULL; i++) { chips[i].probe_func(); if ((chips[i].id1 == id1) && (chips[i].id2 == id2)) { chipindex = i; chip_selected (); power_down (); return 1; }; }; chipindex = i - 1; power_down (); return -1; }
C
#include<stdio.h> void main(){ int array[10]={11,21,21,41,41,61,71,71,91,91}; int i=0; int j; for(j=0;j<10;j++){ if(array[j] != array[i]){ i++; array[i]=array[j]; } } int n=i+1; for(int k=0;k<n;k++){ printf("%d ",array[k]); } }
C
#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <sys/wait.h> #include <stdlib.h> void *hilo(void *arg); void *hilo2(void *arg); void *hilo3(void *arg); int main(void) { pthread_t id_hilo; pid_t pid; int i=0,status; char *cad="Practica 5"; char *cad2=""; if((pid=fork())==0) { printf("Proceso=%u\n",getpid()); for(i=0;i<15;i++) { pthread_create(&id_hilo,NULL,(void*)hilo,NULL); pthread_join(id_hilo,NULL); } waitpid(pid,&status,0); exit(0); } waitpid(pid,&status,0); return 0; } void *hilo(void *arg) { int i; pthread_t id_hilo2; printf("Id hilo= %ld\n",(long) pthread_self()); for(i=0;i<10;i++) { pthread_create(&id_hilo2,NULL,(void*)hilo2,NULL); pthread_join(id_hilo2,NULL); } return NULL; } void *hilo2(void *arg) { int i; pthread_t id_hilo3; printf("Id hilo= %ld\n",(long) pthread_self()); for(i=0;i<5;i++) { pthread_create(&id_hilo3,NULL,(void*)hilo3,NULL); pthread_join(id_hilo3,NULL); } return NULL; } void *hilo3(void *arg) { printf("Practica 5\n"); return NULL; }
C
#include<stdio.h> main(){ int array[20] = {25,12,86,19,6,2,8,11,29,45,7,9,15,18,50,34,70,65,1,4}; int search, c, count = 0; int index[20]; for(c=0;c<20;c++){ printf("%d,",array[c]); } printf("\nmasukkan nilai yang dicari : "); scanf("%d",&search); for(c=0;c<20;c++){ if(array[c]==search){ index[count] = c; count++; } } printf("Nilai yang dicari = %d ada sejumlah = %d\n",search,count); printf("Nilai tersebut ada dalam indeks ke (indeks mulai dari 0) = \n"); printf("indeks ke "); for(c=0;c<count;c++){ printf("%d ",index[c]); } }
C
// ahnentafel.c implements the conversions of numbers and genealogy! // @author: exl2748 Erica LaBuono // // // // // // // // // // // // // // // // // // // // // // // // #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include <ctype.h> #include <string.h> #define MAXLENGTH 285 // mainMenu prints the main menu message when called. void mainMenu() { printf("\n1) description\n" "2) ahnentafel number (base 10)\n" "3) ahnentafel number (base 2)\n" "4) relation (e.g. mother's mother's father)\n" "5) exit\n\n> "); } // binaryToDecimal converts binary numbers to decimal numbers. // @param num is a proper binary number stored as a string // @return decimal is the converted, base 10 form unsigned int binaryToDecimal(char binary[]) { unsigned int num = strtol(binary, NULL, 10); int decimal = 0, i = 0, remainder; while(num != 0) { remainder = num % 10; num = num/10; decimal += remainder*pow(2,i); i++; } return decimal; } // decimalToBinary converts decimal numbers into binary numbers // adds the correct 0 or 1 remainder to the correct number place // conversion ends when there are no more number places to fill // @param decimal is a proper decimal stored as a string // @return binary is converted result as unsigned integer unsigned int decimalToBinary(char decimal[]) { unsigned int num = strtol(decimal, NULL, 10); unsigned int binary = 0; int numPlace = 1; int remainder; while (num != 0) { remainder = num % 2; num = num/2; binary = binary + (remainder * numPlace); //stores 0 or 1 in the correct spot numPlace = numPlace * 10; } return binary; } // stringToBinary takes an input array and generates the matching binary // using basic math starting from 1 and moving decimal places, adding 0 and 1s // @param input is a valid string of family relations unsigned int stringToBinary(char input[]) { char *token; unsigned int binary = 1; // we start at 1 for self token = strtok(input, " "); while (token != NULL) { if(strcmp(token, "mother's") == 0 || strcmp(token, "mother") == 0) { binary = binary * 10; binary = binary + 1; // add a one to the current decimal place instead of 0 } else if (strcmp(token, "father's") == 0 || strcmp(token, "father") == 0) { binary = binary * 10; } token = strtok(NULL, " "); } return binary; } // checkFamilyString verifies that the input is a valid mom-dad-self string. // @param input: a string taken from the user // @return true if the string is valid, false otherwise bool checkFamilyString(char input[]) { char inputCopy[MAXLENGTH]; // reserve the data in a new copy strncpy(inputCopy, input, MAXLENGTH); char *token; token = strtok(inputCopy, " "); while(token != NULL) { if (strcmp(token, "mother's") == 0 || strcmp(token, "mother") == 0 || strcmp(token, "father's") == 0 || strcmp(token, "father") == 0 || strcmp(token, "self") == 0) { // valid strings let us move on to the next token } else { return false; } token = strtok(NULL, " "); } return true; } // checkBinary takes a string and checks to see if it a valid binary number. // @param input is a null-terminated string // @return True if the string is a binary number, False otherwise bool checkBinary(char input[]) { for (int j = 0; j < strlen(input); j++) { if (input[j] != '0' && input[j] != '1' && input[j] != 'b') { return false; // any other numbers are wrong, b is acceptable for binary numbers } } return true; } // checkDecimal takes a string and checks to see if it is a decimal number. // @param input is a null-terminated string // @return True if decimal number, false otherwise bool checkDecimal(char input[]) { unsigned int decimal = strtol(input, NULL, 10); for (int j = 0; j < strlen(input); j++) { if (input[j] == 'b') { return false; // b is acceptable for binary numbers only } } if (decimal == 0) { // if the string has no numbers, or is just 0 return false; } return true; } // familyRelation takes a string of binary and prints the relationship // @param binary is an array repping a proper binary number void familyRelation(char binary[]) { unsigned int binaryNum = strtol(binary, NULL, 10); char binaryStrip[MAXLENGTH]; sprintf(binaryStrip, "%u", binaryNum); // strips the b int length = strlen(binaryStrip); if (length > 2) { // anything greater than mother/father/self printf("family relation: "); for (int i = 1; i < (length - 1); i++) { // ignoring the 1st char, stopping before last if (binaryStrip[i] == '0') { printf("father\'s "); } else if (binaryStrip[i] == '1') { printf("mother\'s "); } } // last word has no apostrophe if (binaryStrip[length - 1] == '0') { printf("father\n"); } else if (binaryStrip[length - 1] == '1') { printf("mother\n"); } } else if (length == 2) { if (binaryStrip[1] == '0') { printf("family relation: father\n"); } else if (binaryStrip[1] == '1') { printf("family relation: mother\n"); } } else if (length == 1) { printf("self\n"); } } // main handles user input for executing various functionality of ahnentafel // when there are no command arguments, a menu is shown and waits for user // the interaction closes when the user enters '5' // when there are command arguments, the program reads in and determines the type // of conversion necessary to give results to the user // @param argc: num of arguments in argv // @param argv: array of arguments // @return EXIT_SUCCESS on complete run int main(int argc, char* argv[]) { if (argc < 2) { char buff[MAXLENGTH]; while (1) { mainMenu(); fgets(buff, MAXLENGTH, stdin); if (strcmp(buff, "1\n") == 0) { printf("The Ahnentafel number is used to determine the relation\n" "between an individual and each of his/her direct ancestors.\n"); } else if (strcmp(buff, "2\n") == 0) { printf("Enter the ahnentafel number in base-10: "); char input[MAXLENGTH]; fgets(input, MAXLENGTH, stdin); unsigned int decimal = strtol(input, NULL, 10); if (decimal != 0) { // testing if the string actually has numbers in it unsigned int binary = decimalToBinary(input); printf("ahnentafel number in binary: %u\n", binary); char binaryStr[MAXLENGTH]; sprintf(binaryStr, "%u", binary); // turning it back to a string for conversion familyRelation(binaryStr); double generations = floor(log(decimal)/log(2.0)); printf("generations back: %.f\n", generations); } else { fprintf(stderr, "Invalid string!\n"); } } else if (strcmp(buff, "3\n") == 0) { printf("Enter the ahnentafel number in binary: "); char input[MAXLENGTH]; fgets(input, MAXLENGTH, stdin); unsigned int binaryStrip = strtol(input, NULL, 10); char binary[MAXLENGTH]; sprintf(binary, "%u", binaryStrip); if (checkBinary(binary)) { if(binaryStrip == 0) { fprintf(stderr, "Invalid string!\n"); continue; } unsigned int decimal = binaryToDecimal(binary); printf("base-10 value: %u\n", decimal); familyRelation(binary); double generations = floor(log(decimal)/log(2.0)); printf("generations back: %.f\n", generations); } else { fprintf(stderr, "Invalid string!\n"); } } else if (strcmp(buff, "4\n") == 0) { printf("Enter family relation (e.g.) \"father's mother\": "); char input[MAXLENGTH]; fgets(input, MAXLENGTH, stdin); input[strcspn(input, "\n")] = 0; // removes the pesky \n character if (checkFamilyString(input)) { unsigned int binary = stringToBinary(input); printf("ahnentafel number in binary: %u\n", binary); char binaryStr[MAXLENGTH]; sprintf(binaryStr, "%u", binary); // convert the binary into string unsigned int decimal = binaryToDecimal(binaryStr); //use string to get decimal printf("ahnentafel number in base-10: %u\n", decimal); double generations = floor(log(decimal)/log(2.0)); printf("generations back: %.f\n", generations); } else { fprintf(stderr, "Invalid string!\n"); } } else if (strcmp(buff, "5\n") == 0) { printf("Goodbye.\n"); return EXIT_SUCCESS; } else { fprintf(stderr, "Unknown operation!\n"); } } } else if(argc >= 2) { char input[MAXLENGTH]; strcpy(input, argv[1]); for (int i = 2; i < argc; i++) { strcat(input, " "); strcat(input, argv[i]); } if(!checkFamilyString(input)) { if (checkDecimal(input)) { unsigned int binary = decimalToBinary(input); printf("ahnentafel number in binary: %u\n", binary); char binaryStr[MAXLENGTH]; sprintf(binaryStr, "%u", binary); // turning it back to a string for conversion familyRelation(binaryStr); unsigned int decimal = strtol(input, NULL, 10); // conversion for gen math double generations = floor(log(decimal)/log(2.0)); printf("generations back: %.f\n", generations); return EXIT_SUCCESS; } else if (checkBinary(input)) { unsigned int decimal = binaryToDecimal(input); printf("base-10 value: %u\n", decimal); familyRelation(input); double generations = floor(log(decimal)/log(2.0)); printf("generations back: %.f\n", generations); return EXIT_SUCCESS; } fprintf(stderr, "Invalid string!\n"); return EXIT_FAILURE; } else if (checkFamilyString(input)) { unsigned int binary = stringToBinary(input); printf("ahnentafel number in binary: %u\n", binary); char binaryStr[MAXLENGTH]; sprintf(binaryStr, "%u", binary); // convert the binary into string unsigned int decimal = binaryToDecimal(binaryStr); //use string to get decimal printf("ahnentafel number in base-10: %u\n", decimal); double generations = floor(log(decimal)/log(2.0)); printf("generations back: %.f\n", generations); return EXIT_SUCCESS; } else { fprintf(stderr, "Invalid string!\n"); } } }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<time.h> char inputChar() { char c; c = (char)((rand() % 94) + 32); // produces a character b/w ( and } return c; } char *inputString() { char* consonants = "bcdfghjklmnpqrstvwxyz"; char* b = "aeioubt"; char* c = "aeioukhcr"; char* d = "aeioudg"; char* f = "aeiouf"; char* g = "aeioughn"; char* h = "aeiout"; char* j = "aeiou"; char* k = "aeioun"; char* l = "aeioudfl"; char* m = "aeioumbn"; char* n = "aeioung"; char* p = "aeioupshn"; char* q = "u"; char* r = "aeiourh"; char* s = "aeiousch"; char* t = "aeiouthc"; char* v = "aeiou"; char* w = "aeiourh"; char* x = "aeiou"; char* y = "aeiou"; char* z = "aeiouz"; char* start = "r"; char* str; str = malloc(6*sizeof(char)); memset(str, '\0', 6); int i; int len; char* nextPool = start; for(i=0; i<5; i++){ len = strlen(nextPool); str[i] = nextPool[rand()%strlen(nextPool)]; switch (str[i]){ case 'b': nextPool = b; break; case 'c': nextPool = c; break; case 'd': nextPool = d; break; case 'f': nextPool = f; break; case 'g': nextPool = g; break; case 'h': nextPool = h; break; case 'j': nextPool = j; break; case 'k': nextPool = k; break; case 'l': nextPool = l; break; case 'm': nextPool = m; break; case 'n': nextPool = n; break; case 'p': nextPool = p; break; case 'q': nextPool = q; break; case 'r': nextPool = r; break; case 's': nextPool = s; break; case 't': nextPool = t; break; case 'v': nextPool = v; break; case 'w': nextPool = w; break; case 'x': nextPool = x; break; case 'y': nextPool = y; break; case 'z': nextPool = z; break; default: // if vowel, next letter will be a consonant - inputstring does not support the use of dipthongs nextPool = consonants; } } return str; } void testme() { int tcCount = 0; char *s; char c; int state = 0; while (1) { tcCount++; c = inputChar(); s = inputString(); printf("Iteration %d: c = %c, s = %s, state = %d\n", tcCount, c, s, state); // to produce the error, c must reach the values in order exactly and the string must be "reset\0" if (c == '[' && state == 0) state = 1; if (c == '(' && state == 1) state = 2; if (c == '{' && state == 2) state = 3; if (c == ' '&& state == 3) state = 4; if (c == 'a' && state == 4) state = 5; if (c == 'x' && state == 5) state = 6; if (c == '}' && state == 6) state = 7; if (c == ')' && state == 7) state = 8; if (c == ']' && state == 8) state = 9; if (s[0] == 'r' && s[1] == 'e' && s[2] == 's' && s[3] == 'e' && s[4] == 't' && s[5] == '\0' && state == 9) { printf("error "); exit(200); } free(s); } } int main(int argc, char *argv[]) { srand(time(NULL)); testme(); return 0; }
C
#include "common_include.h" #include "ncode_hexa.h" #include "ncode_base64.h" #include "ncoder.h" int Ncode(NCODE_TYPE eNcodeType, void *pstArgs, int szArgs) { if (eNcodeType == NCODE_TYPE_HEXA) { if (sizeof(NCODE_TYPE_HEXA_ARGS) != szArgs) { fprintf(stderr, "sizeof(NCODE_TYPE_HEXA_ARGS) != szArgs (%ld != %d)\n", sizeof(NCODE_TYPE_HEXA_ARGS), szArgs); return -1; } return ((NCODE_TYPE_HEXA_ARGS *)pstArgs)->isEncode == 1 ? Encode_Hexa(pstArgs) : Decode_Hexa(pstArgs); } else if (eNcodeType == NCODE_TYPE_BASE64) { if (sizeof(NCODE_TYPE_BASE64_ARGS) != szArgs) { fprintf(stderr, "sizeof(NCODE_TYPE_BASE64_ARGS) != szArgs (%ld != %d)\n", sizeof(NCODE_TYPE_BASE64_ARGS), szArgs); return -1; } return ((NCODE_TYPE_BASE64_ARGS *)pstArgs)->isEncode == 1 ? Encode_Base64(pstArgs) : Decode_Base64(pstArgs); } else if (0) { // Add new NCODE_TYPE here... return -1; } else { fprintf(stderr, "Unknown eNcodeType. (eNcodeType:%d)\n", eNcodeType); return -1; } } static int ncoder_test(int argc, char **argv) { NCODE_TYPE eNcodeType; void *pArgs; int szArgs, isEncoding, rtVal; BYTE abInBuf[2048], abOutBuf[2048]; if (argc != 4) { fprintf(stdout, "> Ncoder Usage : ncoder [-worktype] [-algorithm] [string]\n\n"); fprintf(stdout, "[-worktype]\n"); fprintf(stdout, " 1. -e : Encoding work.\n"); fprintf(stdout, " 2. -d : Decoding work.\n"); fprintf(stdout, "[-algorithm]\n"); fprintf(stdout, " 1. -h : hexa converting.\n"); fprintf(stdout, " 2. -b64 : base64 converting.\n"); fprintf(stdout, "\n"); return -1; } memset(abInBuf, 0x00, sizeof(abInBuf)); memcpy(abInBuf, argv[3], strlen(argv[3])); memset(abOutBuf, 0x00, sizeof(abOutBuf)); isEncoding = (strcmp(argv[1], "-e") == 0 ? 1 : 0); if (strcmp(argv[2], "-h") == 0) { NCODE_TYPE_HEXA_ARGS stArgsHexa; eNcodeType = NCODE_TYPE_HEXA; szArgs = sizeof(NCODE_TYPE_HEXA_ARGS); stArgsHexa.isEncode = isEncoding; stArgsHexa.isLowercase = 0; stArgsHexa.pbInStream = abInBuf; stArgsHexa.pbOutBuf = abOutBuf; stArgsHexa.szInStream = strlen(argv[3]); stArgsHexa.szOutBuf = sizeof(abOutBuf); pArgs = (void *)&stArgsHexa; fprintf(stdout, "inArgs : [isEncode:%d, pbInStream:%s, szInStream:%d szOutBuf:%d]\n", stArgsHexa.isEncode, stArgsHexa.pbInStream, stArgsHexa.szInStream, stArgsHexa.szOutBuf); } else if (strcmp(argv[2], "-b64") == 0) { NCODE_TYPE_BASE64_ARGS stArgsBase64; eNcodeType = NCODE_TYPE_BASE64; szArgs = sizeof(NCODE_TYPE_BASE64_ARGS); stArgsBase64.isEncode = isEncoding; stArgsBase64.pbInStream = abInBuf; stArgsBase64.szInStream = strlen(abInBuf); stArgsBase64.pbOutBuf = abOutBuf; stArgsBase64.szOutBuf = sizeof(abOutBuf); pArgs = (void *)&stArgsBase64; fprintf(stdout, "inArgs : [isEncode:%d, pbInStream:%s, szInStream:%d szOutBuf:%d]\n", stArgsBase64.isEncode, stArgsBase64.pbInStream, stArgsBase64.szInStream, stArgsBase64.szOutBuf); } else if (0) { // ... } else { fprintf(stderr, "Error! Unkown ncode type '%s'.\n", argv[2]); return -1; } if ((rtVal = Ncode(eNcodeType, (void *)pArgs, szArgs)) <= 0) { fprintf(stderr, "Ncode() error. (return:%d)\n", rtVal); return -1; } fprintf(stdout, "outSteram : [%s] (rtVal:%d)\n", abOutBuf, rtVal); return 0; } int main(int argc, char **argv) { return ncoder_test(argc, argv); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "../jsmn.h" //구조체 타입 선언 typedef enum { C_FOOD = 0,//set C_SET =1 //food }mycategory_t; typedef struct { mycategory_t cat; //메뉴분류//cat=0이면 food char name[20]; // 메뉴명 char size[10]; // 사이즈 int price; //가격 }mymenu_t; void printmenu(mymenu_t *m[], int mcount); int makemymenu(const char *json, jsmntok_t *t, int tokcount, mymenu_t * m[]); char * readjsonfile(const char * filename); void printall(const char *json, jsmntok_t * t, int tokcount); static char * JSON_STRING; static int jsoneq(const char *json, jsmntok_t *tok, const char *s) { if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start && strncmp(json + tok->start, s, tok->end - tok->start) == 0) { return 0; } return -1; } int main(int argc,char * argv[]) { int i; int r; mymenu_t * mymenu[20]; char typename[5][20]= {"JSMN_UNDEFINED","JSMN_OBJECT","JSMN_ARRAY","JSMN_STRING","JSMN_PRIMITIVE"}; int keyarray[128], keyamount; int menucount =0 ; if(argc==1) JSON_STRING = readjsonfile("mymenu.json"); else JSON_STRING = readjsonfile(argv[1]); printf("%s \n",JSON_STRING); jsmn_parser p; jsmntok_t t[128]; /* We expect no more than 128 tokens */ #ifdef DEBUG_MODE printf("\n<JSON_STRING>\n"); printf("%s",JSON_STRING); printf("\n============\n"); #endif jsmn_init(&p); r = jsmn_parse(&p, JSON_STRING, strlen(JSON_STRING), t, sizeof(t)/sizeof(t[0])); #ifdef DEBUG_MODE for(i=0;i<r;i++){ printf("[%2d] (%d) %d~%d, size:%d\n", i, t[i].type, t[i].start,t[i].end, t[i].size); } #endif if (r < 0) { printf("Failed to parse JSON: %d\n", r); return 1; } /* Assume the top-level element is an object */ if (r < 1 || t[0].type != JSMN_OBJECT) { printf("Object expected\n"); return 1; } //-----------------------------------------------------------// menucount = makemymenu(JSON_STRING, t, r, mymenu); printmenu(mymenu, menucount); int n,w; int total=0; printf("We only take orders five times a day.\n"); printf("Please select the menu by number.\n"); for(w=0;w<5;w++) { printf("Ordwe %d :\n",w+1); scanf("%d",&n); if(n==w+1) total=total+ mymenu[w]->price; } printf("todays total: %d",total); //-----------------------------------------------------------// return EXIT_SUCCESS; } int makemymenu(const char *json, jsmntok_t *t, int tokcount, mymenu_t * m[]){ int i; int Num1=0; int Num2=0; char str[50]; /* Loop over all keys of the root object */ for (i = 1; i < tokcount; i++) { m[Num1]=(mymenu_t*)malloc(sizeof(mymenu_t)); Num1++; if (jsoneq(json, &t[i], "name") == 0) { strncpy(m[Num1]->name,json+ t[i+1].start,t[i].end-t[i].start); i++; } else if (jsoneq(json, &t[i], "size") == 0) { /* We may use strndup() to fetch string value */ strncpy(m[Num1]->size,json+ t[i+1].start,t[i].end-t[i].start); i++; } else if (jsoneq(json, &t[i], "price") == 0) { /* We may want to do strtol() here to get numeric value */ strncpy(str,json+ t[i+1].start,t[i].end-t[i].start); m[Num1]->price= atoi(str); i++; } else if (jsoneq(json, &t[i], "food") == 0) { int j; m[Num1]->cat =0; if (t[i+1].type != JSMN_ARRAY) { continue; /* We expect groups to be an array of strings */ } i += t[i+1].size + 1; }else if (jsoneq(json, &t[i], "set_menu") == 0) { int j; m[Num1]->cat =0; if (t[i+1].type != JSMN_ARRAY) { continue; /* We expect groups to be an array of strings */ } i += t[i+1].size + 1; } else { return Num1; } } return Num1; } void printmenu(mymenu_t *m[], int mcount){ int i; for(i=0;i<mcount;i++) { if(m[i]->cat==C_FOOD) printf("%d food :\n%s\n%s\n%d",i+1,m[i]->name,m[i]->size,m[i]->price); if(m[i]->cat==C_SET) printf("%d set_menu :\n%s\n%s\n%d",i+1,m[i]->name,m[i]->size,m[i]->price); } } /* typedef enum { C_FOOD = 0,//set C_SET =1 //food }mycategory_t; typedef enum { mycategory_t cat; //메뉴분류//cat=0이면 food char name[20]; // 메뉴명 char size[10]; // 사이즈 int price; //가격 }mymenu_t; */ void printall(const char *json, jsmntok_t * t, int tokcount){ int i; char typename[5][20]= {"JSMN_UNDEFINED","JSMN_OBJECT","JSMN_ARRAY","JSMN_STRING","JSMN_PRIMITIVE"}; printf("***** All Tokens *****\n"); for(i=1;i<tokcount;i++) { #ifdef JSMN_PARENT_LINKS printf("[%2d] %.*s (size=%d, %d~%d, %s) P=%d\n",i,t[i].end-t[i].start,json + t[i].start, t[i].size, t[i].start, t[i].end, typename[t[i].type],t[i].parent); #else printf("[%2d] %.*s (size=%d, %d~%d, %s) \n",i,t[i].end-t[i].start,json + t[i].start, t[i].size, t[i].start, t[i].end, typename[t[i].type]); #endif } printf("\n"); }; char * readjsonfile(const char * filename){ char * line; char temp[200]; line = (char *)malloc(sizeof(char)); FILE * fp; fp = fopen(filename, "rt"); while(fgets(temp, sizeof(temp), fp) != NULL){ temp[strlen(temp)-1]== '\n';//temp의 엔터값 삭제 하고 이어붙인다. line = (char*)realloc(line,strlen(line) + strlen(temp)); strcat(line,temp); } fclose(fp); return line; }
C
#pragma once #include <stdlib.h> #include "list.h" /* Linked list Stack */ /* ġ */ #define stack_peek(stack) ((stack)->head == NULL?NULL:(stack)->head->data) /* Push */ /* linked list head */ int stack_push(Stack* stack, const void* data) { return list_ins_next(stack, NULL, data); } /* pop */ /* linked list head retrieve */ int stack_pop(Stack* stack, void** data) { return list_rem_next(stack, NULL, data); }
C
#ifndef __TIMER_WRAP__ #define __TIMER_WRAP__ #include <signal.h> #include <time.h> #include <unistd.h> #include <stdbool.h> #include <stdint.h> #include <stdlib.h> typedef enum{ TIMER_INIT, TIMER_DELETED, TIMER_PAUSED, TIMER_CANCELLED, TIMER_RESUMED, TIMER_RUNNING, } TIMER_STATE_T; typedef enum{ SUCCESS, FAILURE, }RET; typedef struct Timer_{ /* Timer config */ timer_t posix_timer; void *user_arg; unsigned long exp_timer; /* in milli-sec */ unsigned long sec_exp_timer; /* in milli-sec */ uint32_t thresdhold; /* No of times to invoke the timer callback */ void (*cb)(struct Timer_ *, void *); /* Timer Callback */ bool exponential_backoff; /* place holder value to store * dynamic attributes of timer */ unsigned long time_remaining; /* Time left for paused timer for next expiration */ uint32_t invocation_counter; struct itimerspec ts; unsigned long exp_back_off_time; TIMER_STATE_T timer_state; } Timer_t; /* Returns NULL in timer creation fails, else * return a pointer to Timer object*/ Timer_t* setup_timer( void (*timer_cb)(Timer_t*, void *), /* Timer Callback with user data*/ unsigned long exp_timer, /* First expiration time interval in msec */ unsigned long sec_exp_timer, /* Subsequent expiration time interval in msec */ uint32_t threshold, /* Max no of expirations, 0 for infinite*/ void *user_arg, /* Arg to timer callback */ bool exponential_backoff); /* Is Timer Exp backoff*/ static inline void timer_delete_user_data(Timer_t *timer){ if(timer->user_arg) { free(timer->user_arg); timer->user_arg = NULL; } } static inline TIMER_STATE_T timer_get_current_state(Timer_t *timer){ return timer->timer_state; } static inline void timer_set_state(Timer_t *timer, TIMER_STATE_T timer_state){ timer->timer_state = timer_state; return SUCCESS; } void resurrect_timer(Timer_t *timer); RET start_timer(Timer_t *timer); RET delete_timer(Timer_t *timer); RET cancel_timer(Timer_t *timer); RET pause_timer(Timer_t *timer); RET resume_timer(Timer_t *timer); int execute_timer(Timer_t *timer, TIMER_STATE_T action); /* get remaining time in msec */ unsigned long timer_get_time_remaining_in_mill_sec(Timer_t *timer); RET restart_timer(Timer_t *timer); RET reschedule_timer(Timer_t *timer, unsigned long exp_ti, unsigned long sec_exp_ti); RET print_timer(Timer_t *timer); unsigned long timespec_to_millisec( struct timespec *time); void timer_fill_itimerspec(struct timespec *ts, unsigned long msec); bool is_timer_running(Timer_t *timer); #endif /* __TIMER_WRAP__ */
C
#include "expr_assert.h" #include "CRevision.h" #include <stdlib.h> #include <stdio.h> #include <string.h> void test_fibonacci_returns_1_for_1(){ int *array; array= (int *)malloc(sizeof(int)); assertEqual(fibo(1,array),1); assert(array[0]==0); assert(array[1]!=1); free(array); } void test_fibonacci_returns_0_for_0(){ int *array; array= (int *)malloc(sizeof(int)); assertEqual(fibo(0,array),0); free(array); } void test_fibonacci_returns_3_for_5(){ int *array; array= (int *)malloc(sizeof(int)*5); assertEqual(fibo(5,array),1); assert(array[0]==0); assert(array[1]==1); assert(array[2]==1); assert(array[3]==2); assert(array[4]==3); free(array); } void test_fibonacci_returns_0_for_negative_number(){ int *array; array= (int *)malloc(sizeof(int)); assertEqual(fibo(-3,array),0); free(array); } void test_fibonacci_works_for_decimal(){ int *array; array= (int *)malloc(sizeof(int)*5); assertEqual(fibo(4,array),1); assert(array[0]==0); assert(array[1]==1); assert(array[2]==1); assert(array[3]==2); free(array); } void test_concat_concats_two_arrays_with_length_also(){ int arr1[]={1,2,3}; int arr2[]={3,4,5,6,8}; int *arr3; arr3 = (int *)malloc(sizeof(int)*8); assertEqual(concat(arr1,3,arr2,5,arr3),1); free(arr3); } void test_concat_concats_two_arrays_with_elements(){ int arr1[]={1,2,3}; int arr2[]={3,4,5,6,8}; int *arr3; arr3 = (int *)malloc(sizeof(int)*8); concat(arr1,3,arr2,5,arr3); assert(arr3[2]==3); assert(arr3[3]==3); assert(arr3[7]==8); free(arr3); } void test_concat_concats_gives_0_for_empty_array(){ int arr1[0]; int arr2[]={3,4,5,6,8}; int *arr3; arr3 = (int *)malloc(sizeof(int)*8); assert(concat(arr1,0,arr2,5,arr3)==0); free(arr3); } void test_filter_filters_the_array_from_greter_than_threshold_85(){ int scores[3]={100,90,80}; int *filtered_array; assertEqual(filter(scores,3,85,&filtered_array), 2); assert(filtered_array[0]==100); assert(filtered_array[1]==90); free(filtered_array); } void test_filter_filters_the_array_and_returns_the_number_of_filtered_terms(){ int scores[3]={100,90,80}; int *filtered_array; assertEqual(filter(scores,3,85,&filtered_array), 2); assert(filtered_array[0]==100); assert(filtered_array[1]==90); free(filtered_array); } void test_filter_gives_0_for_negative_or_0_length(){ int scores[]={}, score1[0]; int *filtered_array; assertEqual(filter(scores,0,3,&filtered_array), 0); assertEqual(filter(scores,-9,3,&filtered_array), 0); } void test_reverse_the_array_itself(){ int array[4]; array[0] = 1; array[1] = 2; array[2] = 3; array[3] = 4; assert(reverse(array,4)==1); assert(array[0]==4); assert(array[1]==3); assert(array[2]==2); assert(array[3]==1); } void test_reverses_array_to_new_array(){ int *array; int reverse[4]; array = (int *)malloc(sizeof(int)*4); array[0] = 1; array[1] = 2; array[2] = 3; array[3] = 4; assert(reverseNew(array,4,reverse)==1); assert(reverse[0]==4); assert(reverse[1]==3); assert(reverse[2]==2); assert(reverse[3]==1); free(array); } void test_slice_gives_portion_of_array(){ int numbers[] = {5,6,7,8,9,0}; int *result; assertEqual(slice(numbers,6,1,5, &result), 4); assert(result[0]==6); assert(result[1]==7); assert(result[2]==8); assert(result[3]==9); free(result); } void test_slice_doesnt_modifies_array(){ int numbers[] = {5,6,7,8,0}; int *result; assertEqual(slice(numbers,5,1,3, &result), 2); assert(numbers[0]==5); assert(numbers[1]==6); assert(numbers[2]==7); assert(numbers[3]==8); assert(numbers[4]==0); free(result); } void test_primeNumber_gives_number_of_prime_numbers_in_given_range(){ int *primes; assertEqual(primeNumbers(1,100,&primes), 25); free(primes); } void test_primeNumber_gives_array_of_prime_numbers_in_given_range(){ int *primes; primeNumbers(1,100,&primes); assert(primes[0]==2); assert(primes[1]==3); assert(primes[24]==97); free(primes); } void test_strCompare_gives_0_for_same_strings(){ assertEqual(strCompare("vikas","vikas"),0); } void test_strCompare_gives_negative_2_of_char_for_different_strings_of_same_length(){ char str1[] = {'v','i','k','a','s','\0'}; char str2[] = {'v','i','k','c','u','\0'}; assert(strCompare(str1,str2)==-2); } void test_strCompare_gives_5_of_char_for_different_strings_of_same_length(){ char str1[] = {'v','i','k','f','t','\0'}; char str2[] = {'v','i','k','a','s','\0'}; assert(strCompare(str1,str2)==5); } void test_strCompare_gives_97_for_char_for_strings_of_different_length(){ char str1[] = {'v','i','k','a','s','\0'}; char str2[] = {'v','i','k','\0'}; assert(strCompare(str1,str2)==strcmp(str1,str2)); } void test_strCompare_gives_10_for_different_chars_if_first_string_has_more_length(){ char str1[] = {'v','i','k','a','\0'}; char str2[] = {'v','i','a','\0'}; char str3[] = {'a','b','c','d','\0'}; char str4[] = {'a','t','c','\0'}; assert(strCompare(str1,str2)==strcmp(str1,str2)); assert(strCompare(str3,str4)==strcmp(str3,str4)); } void test_strCompare_gives_negative_99_for_different_chars_if_second_string_has_more_length(){ char str1[] = {'a','b','\0'}; char str2[] = {'a','b','c','\0'}; char str3[] = {'a','s','\0'}; char str4[] = {'a','b','c','d','\0'}; assert(strCompare(str1,str2)==-99); assert(strCompare(str3,str4)==17); }; void test_strCompare_gives_difference_for_space_in_string(){ char *str1 = "viAas"; char *str2 = "vi as"; char *str3 = "vi as"; char *str4 = "vi as"; assertEqual(strCompare(str1,str2),33); assertEqual(strCompare(str3,str4),0); } void test_strCompare_gives_difference_for_special_character(){ assertEqual(strCompare("a ","a&"),-6); assert(strCompare("z","!")==89); } void test_for_each_gives_4_for_3_(){ int_int increment = Increment; int (*sqr)(int) = makesqr; assertEqual(for_each(3,increment), 4); assertEqual(for_each(3,sqr),27); } void test_when_makesqr_is_passed_to_for_each_gives_square_of_array_elements(){ int array[] = {1,2,3,4,5}; int_int fun = &makesqr; assertEqual(int_forEach(array,5,fun), 1); assert(array[0]==1); assert(array[1]==8); } void test_forEach_gives_0_for_empty_array_otherwise_1(){ int array[0]; int array2[1]; int_int sqr = &makesqr; assertEqual(int_forEach(array, 0, sqr),0); assertEqual(int_forEach(array2, 1, sqr),1); } void test_upper_case_gives_UPPERCASE_of_given_char(){ assert(upper_case('z')=='Z'); } void test_char_forEach_converts_to_upper_case_(){ char array[] = {'a','b','c','\0'}; char_char upper = upper_case; assertEqual(char_forEach(array,3,upper),1); assertEqual(array[0],'A'); assertEqual(array[1],'B'); assertEqual(array[2],'C'); } void test_float_forEach_increments_each_element(){ float numbers[] = {3.5, 6.75, 2.25, 10.00}; float_float inc = &increment; assertEqual(float_forEach(numbers, 4, inc),1); assert(numbers[0]==4.5); } void test_Filter_gives_0_for_empty_array_or_negative_length(){ int numbers[0]; int_int multiple_5 = giveMultipleof5; int *filtered_terms; assertEqual(int_filter(numbers, -1, multiple_5, &filtered_terms),0); } void test_Filter_doesnt_change_original_array(){ int numbers[] = {4,5,90,35,43,67}; int *filtered_terms; assertEqual(int_filter(numbers,6,giveMultipleof5,&filtered_terms),3); assertEqual(filtered_terms[0],5); assert(numbers[0]==4) ; free(filtered_terms); } void test_giveMultiplesof5_gives_1_for_multiples_of_5(){ assertEqual(giveMultipleof5(25),1); assertEqual(giveMultipleof5(24),0); } void test_int_Filter_gives_multiples_of_5(){ int numbers[] = {4,5,90,35,43,67}; int *filtered_terms; assertEqual(int_filter(numbers,6,giveMultipleof5,&filtered_terms),3); assertEqual(filtered_terms[0],5); assert(filtered_terms[1]==90); assert(filtered_terms[2]==35); assert(numbers[0]==4) ; free(filtered_terms); } void test_str_len_returns_5_for_vikas(){ assertEqual(str_len("vikas"), 5); assertEqual(str_len("*~#_"), 4); } void test_isCapital_gives_1_for_capital_letter(){ assert(isCapital('Q')==1); assert(isCapital('Z')==1); assert(isCapital('s')==0); } void test_charFilter_gives_filters_the_capital_letters(){ char word[] = {'a','B','c','D','F','h','u','j','H','y','\0'}; int_char isCap = isCapital; char *capitals; assertEqual(char_filter(word,10,isCap,&capitals),4); assertEqual(capitals[0],'B'); assertEqual(capitals[1],'D'); assertEqual(capitals[2],'F'); assert(capitals[3]=='H'); assert(word[0]=='a'); } void test_isLargeString_gives_1_for_string_greater_than_length_3(){ assertEqual(isLargeString("vikas"),1); assertEqual(isLargeString("vik"),0); } void test_stringFilter_returns_string_that_greater_than_3(){ string words[] = {"hii","vikas","suryavanshi","foo","five"}; int_string islarge= &isLargeString; string *filtered; int Filtered_number = string_filter(words,5,islarge,&filtered); assertEqual(Filtered_number, 3); assert(filtered[0]=="vikas"); assert(filtered[1]=="suryavanshi"); assert(filtered[2]=="five"); } void test_isSmallFloat_gives_1_for_9_(){ assert(isSmallFloat(9.9)==1); assert(isSmallFloat(11.8)==0); } void test_float_Filter_gives_numbers_less_than_10(){ float numbers[] = {1.5,8.25,1.75,90.0,45.5}; float *filtered_number; assertEqual(float_filter(numbers, 5, isSmallFloat, &filtered_number),3); assert(filtered_number[0]==1.5); assert(filtered_number[1]==8.25); assert(filtered_number[2]==1.75); } void test_intMap_gives_double_of_each_elements_of_array(){ int *result; int_int Double; int numbers[] = {1,2,3,4}; int expected[]= {2,4,6,8}; Double = &makeDouble; result = int_map(numbers,4,Double); assertEqual(result[0], expected[0]); assertEqual(result[1], expected[1]); assertEqual(result[2], expected[2]); assertEqual(result[3], expected[3]); } void test_intMap_doesnot_changes_the_original_array(){ int numbers[] = {1,2,3,4}; int_int Double; Double = &makeDouble; int_map(numbers,4,Double); assert(numbers[0]==1); assert(numbers[3]==4); } void test_charMap_gives_ascii_value_of_characters(){ char characters[] = {'a','b','A','\0'}; int_char ascii = give_ascii; int *result = char_map(characters, 3, ascii); assertEqual(result[0], 97); assertEqual(result[1], 98); assertEqual(result[2], 65); assertEqual(characters[0],'a'); } void test_stringMap_gives_strings_length_of_evry_string(){ string name[] = {"vikas","jeevan","suryavanshi","\0"}; int_string getLength = str_len; int *result = string_map(name,3,getLength); assertEqual(result[0],5); assertEqual(result[1],6); assertEqual(result[2],11); assert(name[0]=="vikas"); } void test_float_increment(){ assert(increment(4.5)==5.5); assert(increment(4.25)==5.25); } void test_float_Map_increments_float_values_(){ float numbers[]={1.25,5.5,6.75}; float_float inc = &increment; float *result = float_map(numbers, 3, inc); assert(result[0]==2.25); assert(result[1]==6.5); assert(result[2]==7.75); } void test_indexOf_gives_index_only_when_substring_is_present_in_exact_sequence_of_substrings_characters_in_main_string(){ string name="vikas"; assertEqual(indexOf(name, "vik"), 0); assertEqual(indexOf(name, "ika"), 1); assertEqual(indexOf(name, "s"), 4); } void test_indexOf_gives_minus_1_when_substrings_characters_are_present_but_not_in_substrings_chars_sequence(){ string name="vikas"; assertEqual(indexOf(name, "via"), -1); assertEqual(indexOf(name, "isa"), -1); assertEqual(indexOf(name, "si"), -1); } void test_indexOf_gives_minus_1_for_h_in_vikas(){ string name="vikas"; assertEqual(indexOf(name, "h"), -1); } void test_indexof_gives_2_for_k_in_vikas(){ string name="vikas"; assertEqual(indexof(name, 'k'), 2); assertEqual(indexof(name, 's'), 4); assertEqual(indexof(name, 'j'), -1); } void test_int_reduce_gives_maximum_number_from_the_array(){ int numbers[] = {3,5,23,6,3,9}; int(*max)(int,int) = &findMaximum; assertEqual(int_reduce(numbers, 6, max,12),23); } void test_float_reduce_gives_addition_of_array_elements_when_add_func_is_given(){ float numbers[] = {3.0,5.5,23.25,6.75,3.5}; float(*add)(float,float) = &addition; assert(abs(float_reduce(numbers,5,add,6.75)) == 48); assertEqual(abs(float_reduce(numbers,0,add,6.75)), 6); } void test_char_reduce_gives_maximum_number_from_the_array(){ char characters[] = {'n','a','y','v','s','k','\0'}; char(*max)(char,char) = &findmaxChar; assertEqual(char_reduce(characters, 6, max,'o'),'y'); } void test_reduce_returns_initial_value_when_empty_array_is_passed_or_length_is_0(){ char characters[0]; char(*max)(char,char) = &findmaxChar; assertEqual(char_reduce(characters, 0, max,'o'),'o'); } void test_reduce_returns_0_when_negative_length_is_passed(){ char characters[0]; char(*max)(char,char) = &findmaxChar; assertEqual(char_reduce(characters, -1, max,'o'),0); } void test_reduce_returns_smallest_string_when_findSmallest_reference_is_passed(){ string names1[] = {"hiii","twelve","z","suryavanshi","c"}; string names2[] = {"hiii","to","bye","by"}; string(*smallest)(string,string) = &findSmallest; assert(string_reduce(names1, 5, smallest, "vicky") == "z"); assert(string_reduce(names2, 5, smallest, "") == ""); } // void test_Slice_gives_VIK_for_VIKAS(){ // string name = "VIKAS"; // Slice(name,5,0,3); // assert(name=="VIK"); // } // void test_string__forEach_converts_string_array_to_lower_case(){ // string names[] = {"VIKAS","JEEVAN","SURYAVANSHI"}; // string(*first)(string*,int,int,int) = &Slice; // assertEqual(string_forEach(names, 3, first), 1); // assert(names[0]=="VIK"); // assert(names[1]=="JEE"); // assert(names[2]=="SUR"); // } // int array[] = {1,2}; // int *a =array; // a=&arrays // myfn(array); // char *array[2] = {"ananthu","dolly"}; // void test_isPrime_gives_0_for_negative_numbers() { // int expected; // expected = isPrime(-3); // assertEqual(expected,0); // }
C
#include<stdio.h> void main() { char *color[6] = { "red", "green", "blue", "white", "black", "yellow"}; printf("color gives base addres of given array of char pointers :%u\n", color); printf("(color+2) gives address of 3rd element of array of char pointers :%u\n",(color + 2)); printf("*color gives the 1st string :%s\n", *color); printf("*(color + 2) gives 3rd string :%s\n",*(color + 2)); printf("color[5] and *(color + 5) gives value(string) at 5th index of the array :%s %s",color[5],*(color + 5)); getch(); }
C
#include <stdio.h> #include <stdlib.h> #define OK 1 #define ERROR 0 typedef int Status; typedef int ElemType; typedef struct Gnode{ int tag:1; union{ int atom; struct Gnode *hp,*tp; }; } *Glist; int getLength(Glist G){ if(G!=NULL){ return 1 + getLength(G->tp); } return 0; } int getDepth(Glist G){ int max = 0; while(G!=NULL){ if(G->hp->tag==1){ int dep = getDepth(G->hp); if(dep>max)max=dep; } G = G->tp; } return 1+max; } Status revertList(Glist G){ if(G->tag && G->tp){ //switch Glist tmp = G->tp; G->tp = G->hp; G->hp = tmp; revertList(G->hp); revertList(G->tp); } return OK; } int main(){ Glist G; int len = getLength(G); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <ncurses.h> typedef struct node{ char c; int id; struct node *nextNode; int myx, myy; }node; int row, col; int x ,y; FILE *fp; WINDOW *topbar, *textbox, *bottombar, *textOuter; struct node* array = NULL, *end = NULL, *tmp = NULL; int total = 0; int posX, posY; void copy(struct node *ary, WINDOW *textbox, int x, int y); struct node* findNode(int ax, int ay); void highlight(struct node *a, struct node *b); void paste(int x, int y); struct node *copyTxt = NULL; int main(int argc,char *argv[]) { if(argc != 2){ printf("Please provide a file to read: %s <a file name>\n", argv[0]); return(1); } fp = fopen(argv[1], "r"); if(fp){ initscr(); noecho(); refresh(); getmaxyx(stdscr, row, col); topbar = newwin(1, col, 0, 0); //box(topbar, 0, 0); mvwprintw(topbar, 0, 1, "Group 6 | %s", argv[1]); wrefresh(topbar); textOuter = newwin(row-3, col, 1, 0); box(textOuter, 0, 0); wrefresh(textOuter); bottombar = newwin(2, col, row-2, 0); mvwprintw(bottombar, 0, 1, "Click Q to quit - row 0 | col 0"); mvwprintw(bottombar, 1, 1, "Normal Mode"); wrefresh(bottombar); char letter = '\0'; int counter = 0; wmove(textbox, 0, 0); textbox = newwin(row-5, col-2, 2, 1); while(fscanf(fp, "%c", &letter) != EOF){ total++; if(array == NULL){ array = (struct node*)malloc(sizeof(node)); array->c = letter; array->id = counter; array->nextNode = NULL; end = array; } else{ end->nextNode = (struct node*)malloc(sizeof(node)); end->nextNode->c = letter; end->nextNode->id = counter; end->nextNode->nextNode = NULL; end = end->nextNode; } wprintw(textbox, "%c", end->c); getyx(textbox, y, x); end->myx = x; end->myy = y; } wrefresh(textOuter); wrefresh(textbox); int c, quit = -1; wmove(textbox, 0, 0); wrefresh(textbox); int write = -1; while(quit == -1){ getyx(textbox, y, x); int localcopyx = x, localcopyy = y; c = getch(); if(write == -1){ switch(c){ case 'Q': endwin(); quit = 1; break; case 'q': endwin(); quit = 1; break; case 'I': write = 0; mvwprintw(bottombar, 1, 1, "Insert Mode"); break; case 'i': write = 0; mvwprintw(bottombar, 1, 1, "Insert Mode"); break; case 'z': getyx(textbox, posY, posX); copy(array, textbox, posX, posY); //mvwprintw(bottombar, 1, 1, "\n"); wrefresh(bottombar); break; case 'Z': getyx(textbox, posY, posX); copy(array, textbox, posX, posY); //mvwprintw(bottombar, 1, 1, "\n"); wrefresh(bottombar); break; case 'y': getyx(textbox, posY, posX); paste(posX, posY); break; case 'Y': getyx(textbox, posY, posX); paste(posX, posY); break; case '\033': getch(); switch(getch()){ case 'A'://arrow up if(y > 0){ localcopyy = localcopyy-1; localcopyx = localcopyx; } break; case 'B'://arrow down if(row-3 > y){ localcopyy = localcopyy+1; localcopyx = localcopyx; } break; case 'C'://arrow right if(col > x){ localcopyy = localcopyy; localcopyx = localcopyx+1; } break; case 'D'://arrow left if(x > 0){ localcopyy = localcopyy; localcopyx = localcopyx-1; } break; default: break; } mvwprintw(bottombar, 0, 1, "Click Q to quit - row %d | col %d", localcopyy, localcopyx); wrefresh(bottombar); wmove(textbox, localcopyy, localcopyx); wrefresh(textbox); break; } } else{ switch(c){ case '\033': nodelay(stdscr, TRUE); int a = getch(); //mvwprintw(bottombar, 1, 15, "pressed:: %d", a); if(a == 27){ mvwprintw(bottombar, 1, 1, "Normal Mode"); wrefresh(bottombar); write = -1; break; } nodelay(stdscr, FALSE); switch(getch()){ case 'A'://arrow up if(y > 0){ wmove(textbox, localcopyy-1, localcopyx); localcopyy = localcopyy-1; localcopyx = localcopyx; } wrefresh(textbox); break; case 'B'://arrow down if(row-3 > y){ wmove(textbox, localcopyy+1, localcopyx); localcopyy = localcopyy+1; localcopyx = localcopyx; } wrefresh(textbox); break; case 'C'://arrow right if(col > x){ wmove(textbox, localcopyy, localcopyx+1); localcopyy = localcopyy; localcopyx = localcopyx+1; } wrefresh(textbox); break; case 'D'://arrow left if(x > 0){ wmove(textbox, localcopyy, localcopyx-1); localcopyy = localcopyy; localcopyx = localcopyx-1; } wrefresh(textbox); break; default: mvwprintw(bottombar, 1, 1, "Normal Mode"); wrefresh(bottombar); write = -1; break; } mvwprintw(bottombar, 0, 1, "Click Q to quit - row %d | col %d",y, x); wrefresh(bottombar); wmove(textbox, localcopyy, localcopyx); wrefresh(textbox); break; default: tmp = array; struct node *prev; while(tmp != NULL){ //printf("%d %d %d %d", tmp->myx, x, tmp->myy, y); if(tmp->myx == x && tmp->myy == y){ //printf("in if of loop"); struct node *holder = tmp; tmp = (struct node*)malloc(sizeof(node)); tmp->c = c; tmp->id = prev->id + 1; tmp->nextNode = holder; //tmp->nextNode->myx = x+1; prev->nextNode = tmp; break; } prev = tmp; tmp = tmp->nextNode; } tmp = array; wclear(textbox); wrefresh(textbox); wmove(textbox, 0, 0); while(tmp != NULL){ getyx(textbox, y, x); wprintw(textbox, "%c", tmp->c); tmp->myy = y; tmp->myx = x; tmp = tmp->nextNode; } mvwprintw(bottombar, 0, 1, "Click Q to quit - row %d | col %d",y, x); wrefresh(bottombar); wmove(textbox, localcopyy, localcopyx); wrefresh(textbox); wmove(textbox, localcopyy, localcopyx+1); wrefresh(textbox); break; } } struct node *tmp = array; wclear(textbox); wrefresh(textbox); wmove(textbox, 0, 0); int tmpy, tmpx, tmpi = 0; while(tmp!=NULL){ getyx(textbox, tmpy, tmpx); wprintw(textbox, "%c", tmp->c); tmp->id = tmpi; tmp->myy = tmpy; tmp->myx = tmpx; tmpi++; tmp = tmp->nextNode; } wmove(textbox, localcopyy, localcopyx); wrefresh(textbox); } } else{ //bad filename } endwin(); fclose(fp); tmp = array; while(tmp != NULL){ printf("%c", tmp->c); tmp = tmp->nextNode; } return(0); } void paste(int x, int y){ struct node *tmp = array; while(tmp != NULL){ if(tmp->myy == y && tmp->myx == x){ struct node *holder = tmp->nextNode; struct node *copycopy = copyTxt; while(copycopy != NULL){ tmp->nextNode = (struct node *)malloc(sizeof(struct node)); tmp->nextNode->c = copycopy->c; tmp->nextNode->nextNode = NULL; tmp = tmp->nextNode; copycopy = copycopy->nextNode; } tmp->nextNode = holder; break; } tmp = tmp->nextNode; } } void copy(struct node *ary, WINDOW *textbox, int x, int y){ int localcopyy = y, localcopyx = x; struct node *start = NULL, *end = NULL; start = findNode(x, y); int repeat = 1; if(start != NULL){ mvwprintw(bottombar, 1, 1, "Copy Mode - Use arrows to move, and 'c' to copy"); wrefresh(bottombar); wmove(textbox, y, x); wrefresh(textbox); while(repeat == 1){ getyx(textbox, y, x); localcopyy = y; localcopyx = x; switch(getch()){ case '\033': getch(); switch(getch()){ case 'A'://arrow up if(y > 0){ wmove(textbox, localcopyy-1, localcopyx); localcopyy = localcopyy-1; localcopyx = localcopyx; } wrefresh(textbox); break; case 'B'://arrow down if(row-3 > y){ wmove(textbox, localcopyy+1, localcopyx); localcopyy = localcopyy+1; localcopyx = localcopyx; } wrefresh(textbox); break; case 'C'://arrow right if(col > x){ wmove(textbox, localcopyy, localcopyx+1); localcopyy = localcopyy; localcopyx = localcopyx+1; } wrefresh(textbox); break; case 'D'://arrow left if(x > 0){ wmove(textbox, localcopyy, localcopyx-1); localcopyy = localcopyy; localcopyx = localcopyx-1; } wrefresh(textbox); break; } copyTxt = NULL; end = findNode(localcopyx, localcopyy); if(start != NULL && end != NULL){ highlight(start, end); } wmove(textbox, localcopyy, localcopyx); wrefresh(textbox); break; case 'c': ; struct node *cpy = copyTxt; wmove(bottombar, 1, 1); while(cpy != NULL){ wprintw(bottombar, "%c", cpy->c); cpy = cpy->nextNode; } wrefresh(bottombar); repeat = -1; break; case 'C': repeat = -1; break; default: break; } } } } struct node* findNode(int ax, int ay){ struct node *tmp = array; while(tmp != NULL){ if(tmp->myx == ax && tmp->myy == ay){ break; } tmp = tmp->nextNode; } if(tmp != NULL){ struct node *find = (struct node*)malloc(sizeof(struct node)); find->c = tmp->c; find->id = tmp->id; find->nextNode = tmp->nextNode; find->myy = tmp->myy; find->myx = tmp->myx; return find; } else{ return NULL; } } void highlight(struct node *a, struct node *b){ struct node *tmp = array; int found = -2; wclear(textbox); wrefresh(textbox); wmove(textbox, 0, 0); struct node *tmp2 = NULL; while(tmp != NULL){ if(tmp->myy == a->myy && tmp->myx == a->myx || tmp->myy == b->myy && tmp->myx == b->myx){ found++; } if(found != -2 && found < 0){ wattron(textbox, A_STANDOUT); if(tmp2 == NULL){ copyTxt = (struct node*)malloc(sizeof(struct node)); copyTxt->c = tmp->c; copyTxt->nextNode = NULL; tmp2 = copyTxt; } else{ tmp2->nextNode = (struct node*)malloc(sizeof(struct node)); tmp2->nextNode->c = tmp->c; tmp2->nextNode->nextNode = NULL; tmp2 = tmp2->nextNode; } } else{ wattroff(textbox, A_STANDOUT); } if(found == 0){ tmp2->nextNode = (struct node*)malloc(sizeof(struct node)); tmp2->nextNode->c = tmp->c; tmp2->nextNode->nextNode = NULL; tmp2 = tmp2->nextNode; found++; } wprintw(textbox, "%c", tmp->c); tmp = tmp->nextNode; } wrefresh(textbox); }
C
///* // //######################### //# # //# OMANSAK # //# # //######################### // //Queue (First in,First Out) : https://www.tutorialspoint.com/data_structures_algorithms/dsa_queue.htm // //*/ // // // //#include <stdio.h> //#include <stdlib.h> //#define QUEUESIZE 10 // //struct Queue { // int Items[QUEUESIZE]; // int Front, Rear; //}; // // //int Empty(struct Queue *Ptr) //{ // if (Ptr->Front == Ptr->Rear) // return 1; // else // return 0; // //return Ptr->Front == Ptr->Rear ? 1 : 0; //} // //int Remove(struct Queue *Ptr) //{ // if (Empty(Ptr)) // { // puts("Queue is empty."); // } // else if (Ptr->Front == QUEUESIZE - 1) // Ptr->Front = 0; // else // Ptr->Front++; // // return Ptr->Items[Ptr->Front]; //} // //void Insert(struct Queue *Ptr, int Value) //{ // if (Ptr->Rear == QUEUESIZE - 1) // { // Ptr->Rear = 0; // } // else // { // Ptr->Rear++; // } // // // if (Ptr->Rear == Ptr->Front) // { // puts("Queue is overflow"); // } // else // { // Ptr->Items[Ptr->Rear] = Value; // } // //} // //void Display(struct Queue *Ptr) //{ // struct Queue *Clone = Ptr; // if (Empty(Ptr)) // puts("Queue is empty."); // else // for (int i = Clone->Front + 1; i != Clone->Rear; i++) // { // if (i == QUEUESIZE - 1) // { // i = 0; // } // else // { // printf("[%d] \t : \t %d\n", i, Clone->Items[i]); // } // // } //} // //main() //{ // struct Queue *_Queue = (struct Queue*)malloc(sizeof(struct Queue)); // _Queue->Front = -1; // _Queue->Rear = -1; // // Insert(_Queue, 1); // Insert(_Queue, 11); // Insert(_Queue, 111); // Insert(_Queue, 1111); // Insert(_Queue, 11111); // // puts("# # #"); // Display(_Queue); // puts("# # #"); // // printf("%d has been removed.\n", Remove(_Queue)); // printf("%d has been removed.\n", Remove(_Queue)); // // puts("# # #"); // Display(_Queue); // puts("# # #"); // // getch(); // //}
C
#ifndef _BOX_H #define _BOX_H #include "data.h" #include "nets.h" #define DEFOLT_DATA_ELEM_SIZE 4 //coord(i, j, k, n) -> (i * n_j * n_k + j * n_k + k) * n_n + n //coord(n, i, j, k) -> n * n_i * n_j * n_k + i * n_j * n_k + j * n_k + k typedef struct box_t{ point_t start; double step; int borders[3]; int nets_cnt; int dyn_nets_cnt; int dyn_data_size; data_t data; } box_t; typedef struct crd_t{ int crd[4]; } crd_t; //data[coord][nets.count] - массив, где нулевое число - его alloc-размер (c учётом этого числа), //а первое число - занятый размер (без учёта первых чисел) //return coordinates of block which content point "coord" of net with id "net_id" crd_t box_t_get_crd(box_t box, point_t coord, int net_id); //print spatial coords of block which content point "coord" void box_t_print_pnt_ids(box_t box, point_t pnt); //check whether point belongs to box int point_belong_box(point_t pnt, box_t box); //return end point of box, point that opposite the start point_t box_t_get_end(box_t box); //check crd is belongs to box int crd_is_acceptable(box_t box, crd_t crd); //convert crd to coord int crd_to_coord(box_t box, crd_t crd); //init box correspondingly static nets void init_static(nets_t nets, box_t* box); //create box for "nets" //step - set distance between neighbour box's blocks box_t box_t_construct(nets_t nets, double step); void box_t_destruct(box_t* box); //destructor //extend box to contain point crd void recreate_box(nets_t nets, box_t* box, crd_t crd); //update box correspondingly coords of nets nodes void nets_t_update_box(nets_t nets, box_t* box); //sets exactly which box blocks the element's surface intersects with //ATTENTION: expensive operation void box_t_set_elem_exact(nets_t nets, box_t* box); //debug print of crd_t object void crd_t_dump(crd_t crd); //debug print of box_t object void box_t_dump(box_t box); //debug print of box borders void print_brds(double brds[3][2]); //find projection of point to net if point is quite close to net //if (sqr_distance != NULL) set square of distance from point to the projection here void box_t_local_point_to_net_projection(box_t box, point_t point, net_t net, int net_id, double* sqr_distance); //find projection of node coord to net if point is quite close to net //if (sqr_distance != NULL) set square of distance from node to the projection here void box_t_local_node_to_net_projection(box_t box, node_t* node, net_t net, int net_id, double* sqr_distance); #endif
C
// https://www.urionlinejudge.com.br/judge/en/problems/view/2775 #include <stdio.h> void swap(int *a, int *b) { int c = *a; *a = *b; *b = c; } int main() { int N; int packets[1000], times[1000]; int i, swapped, total_time; while (scanf("%d", &N) != EOF) { total_time = 0; for (i = 0; i < N; ++i) scanf("%d", &packets[i]); for (i = 0; i < N; ++i) scanf("%d", &times[i]); do { swapped = 0; for (i = 0; i < N - 1; ++i) { if (packets[i] > packets[i + 1]) { total_time += times[i] + times[i + 1]; swap(&packets[i], &packets[i + 1]); swap(&times[i], &times[i + 1]); swapped = 1; } } } while (swapped); printf("%d\n", total_time); } return 0; }
C
int dfs(int row, int n, int col_used, int dia1_used, int dia2_used) { if (row == n) return 1; int res = 0, pos = 1 << n; for (int i = 0; i < n; ++i) { pos >>= 1; if (col_used & pos || dia1_used & pos || dia2_used & pos) continue; res += dfs(row + 1, n, col_used | pos, (dia1_used | pos) << 1, (dia2_used | pos) >> 1); } return res; } int totalNQueens(int n) { return dfs(0, n, 0, 0, 0); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <sys/time.h> #include "thingmodule.h" #define max(a,b) (((a) (b)) ? (a) : (b)) #define min(a,b) (((a) < (b)) ? (a) : (b)) /* Subtract the ‘struct timeval’ values X and Y, * storing the result in RESULT. * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract (struct timeval *result, struct timeval*x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]){ int m = 5000; int n = 5000; double **data, **fuzzed; struct timeval data_start, data_end, calc_start, calc_end, data_diff, calc_diff; gettimeofday(&data_start, NULL); data = malloc(m * sizeof(double *)); for (int i = 0; i < m; i++){ data[i] = malloc(n * sizeof(double)); } fuzzed = malloc(m * sizeof(double *)); for (int i = 0; i < m; i++){ fuzzed[i] = malloc(n * sizeof(double)); } printf("Generating sample data (%dx%d array), in C...\n", m, n); for (int j = 0; j < m; j++){ for (int k = 0; k < n; k++) { data[j][k] = pow(((float)j/10.0), 4) + pow(((float)k/20.0), 4); } } gettimeofday(&data_end, NULL); printf("Performing gradient calculation on data (%dx%d array), with results:\n", m, n); gettimeofday(&calc_start, NULL); del2(data, fuzzed, m, n); gettimeofday(&calc_end, NULL); for (int i = 0; i< min(m, n); i+=1000){ printf("%f\n", fuzzed[i][i]); } timeval_subtract(&data_diff, &data_end, &data_start); timeval_subtract(&calc_diff, &calc_end, &calc_start); printf("Summary:\n"); printf(" Data generation code segment (C) took %f seconds\n", data_diff.tv_sec + data_diff.tv_usec/1e6); printf(" Gradient calculation code segment (C) took %f seconds\n", calc_diff.tv_sec + calc_diff.tv_usec/1e6); printf(" Total time: %.3f seconds\n", (data_diff.tv_sec + data_diff.tv_usec/1e6) + (calc_diff.tv_sec + calc_diff.tv_usec/1e6)); // We should free() data, and fuzzed here. I'm lazy though. return 0; }
C
// opal.c // Yinghong Zhong #include <stdio.h> typedef struct { int day, mon, year; } Date; typedef struct { int hour, minute; } Time; typedef struct { int transaction_nb; char weekday[4]; //Mon, Tue...Sun Date date; Time time; char mode; // 'B', 'T' char start_stop[32]; char end_stop[32]; int journey_nb; char fare_applied[10]; float fare; float discount; float amount; } Ride; int main() { Ride myride; printf ("The Opal data structure requires %d byte.\n", sizeof(Ride)); return 0; } /* 3. memory requirement for one element of type of type Ride: 4 + 4 + 12 + 8 + 1 + (3 padding)+ 32*2 + 4 + 10 + (2padding) + 4*3 = 124 4. a. use integers to encode the possible "fare_applied" b. encode the start_stop and end_stop using unique stop IDs along with a lookup table that links the IDs to the stop name c. avoid the redundant information, like weekday which can be derived from date */
C
//updated by Circe 5/26/04 with new desc, lore, radiate magic, etc. #include <std.h> inherit POTION; int num; int side_effect(); void create() { ::create(); add_id("potion of raging heal"); add_id("raging heal"); add_id("reddish gold potion"); add_id("reddish gold"); set_obvious_short("%^RED%^A metallic vial containing a "+ "reddish %^YELLOW%^gold %^RESET%^%^RED%^potion%^RESET%^"); set_short("%^RED%^Potion of Raging Heal%^RESET%^"); set_long("%^RESET%^%^CYAN%^This smooth %^BOLD%^metallic vial "+ "%^RESET%^%^CYAN%^is rather small and tear-drop shaped. "+ "It is completely %^BOLD%^%^WHITE%^clear%^RESET%^%^CYAN%^, "+ "allowing you to see a %^BOLD%^%^RED%^reddish %^YELLOW%^"+ "gold potion %^RESET%^%^CYAN%^that swirls inside.") ; set_lore("This potion is one crafted by many healers of the land. "+ "Because of the ingredients used, such potions often have "+ "similar qualities, such as color and smell. The color of "+ "this potion suggests it might be used to heal, though "+ "it may have side effects of rage."); set_property("lore difficulty",12); set("color", "reddish gold"); set("effect_time", 0); set_value(200); } int do_effect() { int healing; set("effect_time",(random(5)*60)); if(drinker->query_hp() < drinker->query_max_hp()) { healing = random(8) + random(8) + random(8) + 3; tell_object(drinker, "%^BOLD%^%^CYAN%^You begin to feel refreshed.\n"); tell_object(drinker, "You have gained back "+healing+" hit points.\n"); say("%^BOLD%^%^CYAN%^"+TPQCN+" drinks the potion and looks refreshed.\n"); drinker->add_hp(healing); } else { tell_object(drinker, "You feel no different from before.\n"); say(TPQCN+" drinks the potion but appears uneffected.\n"); } call_out("side_effect",5); } int side_effect() { object *inven; int i,j; tell_object(drinker,"%^RED%^You begin to feel an uncontrollable RAGE!\n"); say("%^RED%^"+TPQCN+" appears to be enraged! (side effect maybe?)\n"); inven=all_inventory(environment(drinker)); j=sizeof(inven); for(i=0;i<j;i++) { if(living(inven[i])) { if(inven[i] != drinker) drinker->kill_ob(inven[i],1); } } return 1; } int do_wear_off() { object *attackers; tell_object(drinker,"You suddenly feel sedate."); tell_room(environment(drinker),drinker->query_cap_name()+" suddenly "+ "looks sedate.",drinker); /* attackers=drinker->query_attackers(); for(num=0;num<sizeof(attackers);num++) { attackers[num]->cease_all_attacks(); drinker->cease_all_attacks(); } */ return 1; } int isMagic(){ int magicpotion; magicpotion = ::isMagic(); magicpotion = magicpotion+1; return magicpotion; }
C
/***************************** MPEG-4 AAC File Parser ************************ Author(s): Arlon Lee Description: AAC File Parser interface *******************************************************************************/ #include <stdlib.h> #include <string.h> #include "aac_file_parser.h" #define MAX_CHANNELS 6 /* make this higher to support files with more channels */ /* A decode call can eat up to FAAD_MIN_STREAMSIZE bytes per decoded channel, so at least so much bytes per channel should be available in this stream */ #define FAAD_MIN_STREAMSIZE 768 /* 6144 bits/channel */ HANDLE_AAC_FILE AacFileParser_Open(const SCHAR *filename) { if ((filename == NULL) || (strlen(filename) <= 0) ) { return NULL; } HANDLE_AAC_FILE handler = (HANDLE_AAC_FILE)malloc(sizeof(struct AAC_File_Parser)); memset(handler, 0, sizeof(handler)); handler->reader.inFile = fopen(filename, "rb"); if (handler->reader.inFile == NULL) { free(handler); return NULL; } UCHAR* buffer = (UCHAR*)malloc(FAAD_MIN_STREAMSIZE*MAX_CHANNELS); memset(buffer, 0, FAAD_MIN_STREAMSIZE*MAX_CHANNELS); int size = fread(buffer, 1, FAAD_MIN_STREAMSIZE*MAX_CHANNELS, handler->reader.inFile); if (size <= 0) { free(buffer); free(handler); return NULL; } //printf("buffer first two bytes is 0x%hhx, 0x%hhx\n", buffer[0], buffer[1]); // AAC ADTS file if ((buffer[0] == 0xFF) && ((buffer[1] & 0xF0) == 0xF0)) { handler->reader.tt = TT_MP4_ADTS; } else if (memcmp(buffer, "ADIF", 4) == 0) { handler->reader.tt = TT_MP4_ADIF; } else { free(buffer); free(handler); //printf("failed to open %s file\n", filename); return NULL; } free(buffer); fseek(handler->reader.inFile, 0, SEEK_SET); return handler; } INT AacFileParser_Read( HANDLE_AAC_FILE hAacFile, UCHAR *inBuffer, UINT bufferSize, UINT *bytesValid ) { if (hAacFile == NULL) { return -1; } //reach end of file if (feof(hAacFile->reader.inFile)) { return -1; } *bytesValid = fread(inBuffer, 1, bufferSize, hAacFile->reader.inFile); if (0 == *bytesValid) { return -1; } return 0; } INT AacFileParser_Seek( HANDLE_AAC_FILE hAacFile, INT origin, INT offset ) { if (0 == origin) { return fseek(hAacFile->reader.inFile, offset, SEEK_SET); } else if (1 == origin) { return fseek(hAacFile->reader.inFile, offset, SEEK_CUR); } return 0; } TRANSPORT_TYPE AacFileParser_GetTransportType(HANDLE_AAC_FILE hAacFile) { if (hAacFile == NULL) { return TT_UNKNOWN; } return hAacFile->reader.tt; } INT AacFileParser_DecodeHeader( HANDLE_AAC_FILE hAacFile, UCHAR *inBuffer, UINT bufferSize ) { if (hAacFile == NULL ) { return -1; } // headers begin with FFFxxxxx... if ((inBuffer[0] == 0xff) && ((inBuffer[1] & 0xf0) == 0xf0)) { hAacFile->header.nSyncWord = (inBuffer[0] << 4) | (inBuffer[1] >> 4); hAacFile->header.nId = (inBuffer[1] & 0x08) >> 3; hAacFile->header.nLayer = (inBuffer[1] & 0x06) >> 1; hAacFile->header.nProtectionAbsent = inBuffer[1] & 0x01; hAacFile->header.nProfile = (inBuffer[2] & 0xc0) >> 6; hAacFile->header.nSfIndex = (inBuffer[2] & 0x3c) >> 2; hAacFile->header.nPrivateBit = (inBuffer[2] & 0x02) >> 1; hAacFile->header.nChannelConfiguration = (((inBuffer[2] & 0x01) << 2) | ((inBuffer[3] & 0xc0) >> 6)); hAacFile->header.nOriginal = (inBuffer[3] & 0x20) >> 5; hAacFile->header.nHome = (inBuffer[3] & 0x10) >> 4; hAacFile->header.nCopyrightIdentificationBit = (inBuffer[3] & 0x08) >> 3; hAacFile->header.nCopyrigthIdentificationStart = inBuffer[3] & 0x04 >> 2; hAacFile->header.nAacFrameLength = ((((inBuffer[3]) & 0x03) << 11) | ((inBuffer[4] & 0xFF) << 3) | (inBuffer[5] & 0xE0) >> 5); hAacFile->header.nAdtsBufferFullness = ((inBuffer[5] & 0x1f) << 6 | (inBuffer[6] & 0xfc) >> 2); hAacFile->header.nNoRawDataBlocksInFrame = (inBuffer[6] & 0x03); } else { return -1; } return 0; } INT AacFileParser_GetAudioSpecificConfig(UCHAR *inBuffer, UINT bufferSize, UCHAR *asc ) { if ((inBuffer[0] == 0xff) && ((inBuffer[1] & 0xf0) == 0xf0)) { asc[0] = (((inBuffer[2] & 0xc0) >> 6) + 1) << 3; asc[0] = asc[0] | (((inBuffer[2] & 0x3c) >> 2) >> 1); asc[1] = ((inBuffer[2] & 0x3c) >> 2) << 7 ; asc[1] = asc[1] | ( ((((inBuffer[2] & 0x01) << 2) | ((inBuffer[3] & 0xc0) >> 6))) << 3); return 0; } return -1; } AdtsHeader * AacFileParser_GetHeader(HANDLE_AAC_FILE hAacFile) { if (NULL == hAacFile) { return NULL; } return &hAacFile->header; } INT AacFileParser_GetRawDataBlockLength( HANDLE_AAC_FILE hAacFile, INT blockNum ) { if (NULL == hAacFile) { return -1; } INT length = -1; if (hAacFile->header.nNoRawDataBlocksInFrame == 0) { length = hAacFile->header.nAacFrameLength - 7; /* aac_frame_length subtracted by the header size (7 bytes). */ if (hAacFile->header.nProtectionAbsent == 0) length -= 2; /* substract 16 bit CRC */ } return length; } INT AacFileParser_Close(HANDLE_AAC_FILE hAacFile) { INT ret = 0; if (hAacFile == NULL || !hAacFile->reader.inFile) { return -1; } if (0 != fclose(hAacFile->reader.inFile)) { ret = -1; } free(hAacFile); hAacFile = NULL; return ret; }
C
/*****************************************************************************/ /*** fichier: testvar.c ***/ /*** Calcul de variance ***/ /*****************************************************************************/ #include <stdio.h> #include <math.h> #include "var.h" #define nb_val 5 int main () { int i; float var; int table[nb_val] = {2, 5, 7, 2, 9}; for (i=0; i<nb_val; i++) printf("table[%d] = %d\n", i, table[i]); printf("\n"); variance(table, nb_val, &var); printf("La variance du tableau est: %f\n", var); return 0; }
C
#include<stdio.h> #include<string.h> #include<stdbool.h> #include<stdlib.h> void subject(int index); void mention(float score); bool checkScore(int score); bool numOnly(char *score); void pass(float average); int main(){ char score[20]; int total = 0, points; for(int i = 0; i < 5; i++){ subject(i); scanf("%s", score); if(!numOnly(score)) goto fail; points = atoi(score); if(!checkScore(points)) goto fail; mention((float)(points)); total += points; } printf("\nTotal: %d\nAverage %.2f%%\n", total, (float)(total) / 5); mention((float)(total) / 5); pass((float)(total) / 5); exit(0); fail: printf("Input fail"); return 0; } void subject(int index){ char name[5][30]; strcpy(name[0], "Computer Architecture: "); strcpy(name[1], "Programming Methodology: "); strcpy(name[2], "English for Computing: "); strcpy(name[3], "Graphic Design: "); strcpy(name[4], "Math for Computing: "); printf("%s", name[index]); } void mention(float score){ float goal[] = {40, 45, 50, 65, 70, 80, 85, 100}; char grade[] = "FEDCcBbA"; int i; for(i = 0; i < 8; i++){ if(score < goal[i]){ break; } } printf("Mention: "); if(grade[i] == 'c'){ printf("C+\n"); }else if(grade[i] == 'b'){ printf("B+\n"); }else{ printf("%c\n", grade[i]); } } bool checkScore(int score){ return score > 100 ? false : true; } bool numOnly(char *score){ char num[10] = "0123456789"; int length, numLength, count = 0; length = strlen(score); numLength = strlen(num); for(int i = 0; i < length; i++){ for(int j = 0; j < numLength; j++){ if(*(score + i) == num[j]){ count++; } } } return length - count ? false : true; } void pass(float average){ if(average > 60) printf("PASS"); else printf("FAIL"); }
C
#ifndef _GC_H_ #define _GC_H_ // Ce fichier contient l'interface de votre ramasse-miettes // La fonction gcmalloc doit renvoyer un nouvel objet. // Vous vous servirez de la fonction pre_malloc qui se trouve dans // les fichiers alloc.h et alloc.c. // Si vous commencez à manquer de place, // vous devez déclancher une demande de collection ici. // Vous devrez modifier l'entête des objets pour ajouter les champs que vous jugerez // nécessaires (object_header qui se trouve dans alloc.h) void *gcmalloc(unsigned int size); // la fonction writeBarrier doit être appelée à chaque écriture. // Vous devez vous assurez que l'invariant tri-couleurs de Steel est respecté. // Pensez que plusieurs threads peuvent appeler writeBarrier en parallèle! void _writeBarrier(void *dst, void *src); #define doWriteRef(dst, src) ({ _writeBarrier(&(dst), src); dst = src; }) // la fonction handShake est appelée régulièrement pas un mutateur. Si une collection // est demandée suite à un manque de place en mémoire, cette fonction doit s'occuper // d'ajouter les racines de la pile à une liste pour que le collecteur puisse commencer une collection. // Cette fonction doit libérer le mutateur pendant une collection. // Pour augmenter la concurrence, vous utiliserez une variable locale (thread local storage, TLS, indiquée par __thread) // au thread pour stocker vos racines. void handShake(); // Cette fonction attache un nouveau thread. // Elle permet d'initialiser le TLS du thread et // d'enregistrer le nouveau thread auprès du mutateur. void attach_thread(); // Cette fonction détache un thread. void detach_thread(); // cette fonction est appelée à l'initialisation du programme. // Vous devrez créer un thread collecteur ici. // Ce thread attend qu'une collection soit demandée à l'aide d'une variable condition. void initialise_gc(); #endif
C
#include "types.h" #include "stat.h" #include "user.h" int main(int argc, char* argv[]){ if(fork()==0){ while(1){ write(1, "Child\n", 7); yield(); } } else{ while(1){ printf(1, "Parent\n", 8); yield(); } } return 0; }
C
/* ** EPITECH PROJECT, 2018 ** libmy ** File description: ** is_upper.c */ #include <criterion/criterion.h> #include "my/char.h" Test(Char, is_upper) { cr_expect(is_upper('\0') == false); cr_expect(is_upper('\t') == false); cr_expect(is_upper('\n') == false); cr_expect(is_upper(' ') == false); cr_expect(is_upper('!') == false); cr_expect(is_upper('$') == false); cr_expect(is_upper('(') == false); cr_expect(is_upper('1') == false); cr_expect(is_upper('=') == false); cr_expect(is_upper('@') == false); cr_expect(is_upper('B') == true); cr_expect(is_upper('H') == true); cr_expect(is_upper('[') == false); cr_expect(is_upper('a') == false); cr_expect(is_upper('z') == false); cr_expect(is_upper('}') == false); cr_expect(is_upper(127) == false); }
C
#include <stdio.h> #include <stdlib.h> #include <limits.h> #include <string.h> #define MAX_BS 1000 int bstoi(const char *); char * itobs(int, char *); char * tail(int n, char *); // remove n first char int main(int argc, char * argv[]) { int a, b; int lena, lenb; int len; char BS_result[MAX_BS]; if (argc != 3) { printf("Usage: %s 10100110 01010101\n", argv[0]); exit(EXIT_FAILURE); } lena = strlen(argv[1]); lenb = strlen(argv[2]); len = lena > lenb ? lena : lenb; a = bstoi(argv[1]); b = bstoi(argv[2]); printf("%d %d\n", a, b); printf("~ (%s) = (%s)\n", argv[1], tail(lena, itobs(~a, BS_result))); printf("~ (%s) = (%s)\n", argv[2], tail(lenb, (itobs(~b, BS_result)))); printf("(%s) & (%s) = (%s)\n", argv[1], argv[2], tail(len, itobs(a & b, BS_result))); printf("(%s) | (%s) = (%s)\n", argv[1], argv[2], tail(len, itobs(a | b, BS_result))); printf("(%s) ^ (%s) = (%s)\n", argv[1], argv[2], tail(len, itobs(a ^ b, BS_result))); return 0; } int bstoi(const char * bs) { int return_value = 0; for (int n = strlen(bs) - 1; n >= 0; --n) { if (*bs++ == '1') return_value += 1<<n; } return return_value; } char * itobs(int n, char * ps) { int i; const static int size = CHAR_BIT * sizeof(int); for (i = size - 1; i >= 0; i--, n >>=1) ps[i] = (1 & n) + '0'; ps[size] = '\0'; return ps; } char * tail(int n, char * ps) { int m = strlen(ps); for (int i = 0; i < n; ++i) ps[i] = ps[m+i-n]; ps[n] = '\0'; return ps; }
C
#include "../include/freq.h" /* needed for freq_t */ #include "../include/arbre.h" /* needed for arbre_t */ #include "../include/coding.h" /* constuirecodage */ #include <stdlib.h> /* exit, NULL */ #include <stdio.h> /* FILE*, fopen, fclose*/ void parcours_arbre(arbre_t arbre){ if(!arbre) return; parcours_arbre(left_child(arbre)); printf("%c : %d\n",get_lettre(arbre),get_code(arbre)); parcours_arbre(right_child(arbre)); } int teste_bit (unsigned char c, unsigned int pos){ return (c&(1<<pos))?1:0; } int main(){ freq_t freqs; arbre_t Arbrecodage; code_t codage; char code; int a=0; FILE * f = fopen("frequence.txt","r"); fread(freqs,sizeof(freq_t),1,f); Arbrecodage = construirecodage(freqs); tablecodage(Arbrecodage,codage); while(a<257){ printf("%c,%o\n",a,codage[a]); a++; }return 0; }
C
#include "threadPool.h" /* Data structure */ /* Internal methods */ static void* threadPoolThread(void* tp){ ThreadPool* pool = (ThreadPool*)(tp); for(;;) { pthread_mutex_lock(&(pool->lock)); /* Handle waiting for work RUNNING and SOFT_SHUTDOWN */ while ((pool->state == RUNNING) && (pool->queueSize == 0)) { pthread_cond_wait(&(pool->cnd), &(pool->lock)); } /* Handle SOFT_SHUTDOWN termination */ if ((pool->queueSize == 0) && (pool->state != RUNNING)) { pthread_mutex_unlock(&(pool->lock)); pthread_exit(NULL); return(NULL); } /* Handle HARD_SHUTDOWN termination */ if (pool->state == HARD_SHUTDOWN) { pthread_mutex_unlock(&(pool->lock)); pthread_exit(NULL); return(NULL); } /* Get and execute work */ ThreadPoolTask* task = osDequeue(pool->queue); pool->queueSize--; pthread_mutex_unlock(&(pool->lock)); (*(task->computeFunc))(task->param); free(task); } } ThreadPool* tpCreate(int numOfThreads) { ThreadPool* threadPool = malloc(sizeof(ThreadPool)); if(threadPool == NULL) return NULL; /* Initialize pool data*/ threadPool->state = RUNNING; threadPool->poolSize = numOfThreads; /* Initialize queue data*/ threadPool->queueSize = 0; threadPool->queue = osCreateQueue(); if (threadPool->queue == NULL) { } /* Initialize pthreads */ pthread_mutex_init(&(threadPool->lock), NULL); pthread_cond_init(&(threadPool->cnd), NULL); threadPool->threads = malloc(sizeof(pthread_t) * numOfThreads); if (threadPool->threads == NULL) { free(threadPool); return NULL; } int i, liveThreads = 0; for (i=0; i < numOfThreads; i++) { threadPool->threads[i] = malloc(sizeof(pthread_t)); } /* Start worker threads */ for(i = 0; i < threadPool->poolSize; i++) { pthread_create(&(threadPool->threads[i]), NULL, threadPoolThread, threadPool); liveThreads++; } /* Wait for worker threads to initialize */ while (liveThreads < threadPool->poolSize) {} return threadPool; } void tpDestroy(ThreadPool* threadPool, int shouldWaitForTasks) { pthread_mutex_lock(&(threadPool->lock)); /* Hand repeated call fr tpDestroy */ if (threadPool->state != RUNNING){ pthread_mutex_unlock(&(threadPool->lock)); return; } /* Assign new state */ if (shouldWaitForTasks == 0) threadPool->state = HARD_SHUTDOWN; else threadPool->state = SOFT_SHUTDOWN; pthread_mutex_unlock(&(threadPool->lock)); /* Wake all pool threads */ pthread_cond_broadcast(&(threadPool->cnd)); /* Wait for all threads to finish */ for(int i = 0; i < threadPool->poolSize; i++) { pthread_join(threadPool->threads[i], NULL); } /* Dealocate the queue */ osDestroyQueue(threadPool->queue); } int tpInsertTask(ThreadPool* threadPool, void (*computeFunc) (void *), void* param) { //printf("Adding task...\n"); if(threadPool == NULL || computeFunc == NULL) { return -1; } pthread_mutex_lock(&(threadPool->lock)); /* Check state and create ThreadPoolTask */ if (threadPool->state != RUNNING) return -1; ThreadPoolTask* newTask = malloc(sizeof(ThreadPoolTask)); if (newTask == NULL) return -1; newTask->computeFunc = computeFunc; newTask->param = param; /* Add task to queue */ osEnqueue(threadPool->queue, newTask); threadPool->queueSize++; pthread_cond_broadcast(&(threadPool->cnd)); pthread_mutex_unlock(&threadPool->lock); return 0; }
C
/* ** get_next_line.c for get_next_line.c in /home/ibanez_j/CPE_2016_getnextline ** ** Made by Jean-Alexandre IBANEZ ** Login <[email protected]> ** ** Started on Fri Jan 6 15:36:54 2017 Jean-Alexandre IBANEZ ** Last update Thu Feb 02 18:08:22 2017 Benjamin BRIHOUM */ #include <stdlib.h> #include <unistd.h> #include "get_next_line.h" static char *my_realloc(char *str, int nb) { char *new_str; int i; i = 0; if ((new_str = malloc(sizeof(char) * nb + 1)) == NULL) return (NULL); while (str[i] != '\0') { new_str[i] = str[i]; i++; } free(str); return (new_str); } static int treat_result(char **result, int i) { (*result)[i] = '\0'; (*result) = my_realloc((*result), i + READ_SIZE); if ((*result) == NULL) return (84); return (0); } int free_result(char *buffer) { free(buffer); return (84); } char *get_next_line(const int fd) { static int parseur = 0; static char buffer[READ_SIZE]; static int bytes_read = 0; char *result; int i; i = 0; if ((result = malloc(sizeof(char) * READ_SIZE + 1)) == NULL) return (NULL); if (bytes_read == 0 && (bytes_read = read(fd, buffer, READ_SIZE))) parseur = 0; if ((bytes_read == -1 && (bytes_read = 0) == 0) || bytes_read == 0) if (free_result(result) == 84 && (parseur = 0) == 0) return (NULL); while (buffer[parseur] != '\n' && buffer[parseur] != '\0') { result[i++] = buffer[parseur++]; if (--bytes_read == 0 && (bytes_read = read(fd, buffer, READ_SIZE))) if ((parseur = treat_result(&result, i)) == 84) return (NULL); } result[i] = '\0'; parseur++; bytes_read--; return (result); }
C
#include<stdio.h> void main(){ int point1,point2,point3,point4,point5; int val; printf("Points for point1,point2,point3,point4,point5\n"); scanf("%d,%d,%d,%d,%d" "&point1,&point2,&point3,&point4,&point5"); val = point1+point2+point3+point4+point5; printf("%f\n",val); } /* Output- pradnya@pradnya-Latitude-3480:~/Desktop/CodeSnippets/CodeSnippets29July$ gedit Prog10.c pradnya@pradnya-Latitude-3480:~/Desktop/CodeSnippets/CodeSnippets29July$ cc Prog10.c Prog10.c: In function ‘main’: Prog10.c:5:9: warning: missing terminating " character printf("Points for ^ Prog10.c:5:9: error: missing terminating " character printf("Points for ^~~~~~~~~~~ Prog10.c:6:35: error: stray ‘\’ in program point1,point2,point3,point4,point5\n"); ^ Prog10.c:6:35: error: expected ‘)’ before ‘n’ point1,point2,point3,point4,point5\n"); ^~ ) Prog10.c:6:37: warning: missing terminating " character point1,point2,point3,point4,point5\n"); ^ Prog10.c:6:37: error: missing terminating " character point1,point2,point3,point4,point5\n"); ^~~ Prog10.c:6:1: warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast [-Wint-conversion] point1,point2,point3,point4,point5\n"); ^~~~~~ In file included from Prog10.c:1: /usr/include/stdio.h:332:43: note: expected ‘const char * restrict’ but argument is of type ‘int’ extern int printf (const char *__restrict __format, ...); ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~ Prog10.c:10:21: error: expected ‘;’ before ‘}’ token printf("%f\n",val); ^ ; } ~ */
C
#include <stdio.h> int main( ) { FILE *fp ; char path[100]; char ch; printf("Enter the file path: "); scanf("%s",path); fp = fopen ( path, "r" ) ; while ( 1 ){ ch = fgetc ( fp ) ; if ( ch == EOF ) break ; printf ( "%c", ch ) ; } printf ( "\n" ) ; fclose ( fp ) ; }
C
#include <stdio.h> int ft_atoi(char *str) { int nombre; int signe; char *charptr; nombre = 0; signe = 1; charptr = str; while (*charptr == ' ' || (*charptr >= 9 && *charptr <= 13)) charptr++; while (*charptr == '-' || *charptr == '+') { if (*charptr == '-') signe *= -1; charptr++; } while (*charptr >= '0' && *charptr <= '9') { nombre *= 10; nombre += (int)(*charptr - '0'); charptr++; } return (nombre * signe); } int ft_atoi(char *str); int main(void) { printf("%d\n", ft_atoi(" ---+--+1234ab567")); return (0); }
C
#include "movement.h" int mod (int n, int div) { int r = n % div; return r < 0 ? r + div : r; // return (x % N + N) % N; } struct vector movement (enum direction d, struct vector v) { struct vector v2 = {v.x, v.y}; switch (d) { case UP: v2.y--; break; case RIGHT: v2.x++; break; case DOWN: v2.y++; break; case LEFT: v2.x--; break; } return v2; } int turn (enum directive i, enum direction d) { switch (i) { case PORT: return mod(d - 1, 4); case STARBOARD: return mod(d + 1, 4); case KEEP: default: return d; } } int vector_Eq(struct vector this, struct vector other) { return this.x == other.x && this.y == other.y; }
C
#include <sys/wait.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> int main() { pid_t pid; if((pid = fork()) < 0) { perror("fork error"); exit(1); } if(pid == 0) { sleep(30); exit(2); } else { int status; pid_t ret = waitpid(-1,&status,0); if(ret > 0 && (status & 0x7F)==0)//该进程有子进程退出 且 正常退出 { printf("child exit code: %d\n",(status>>8)&0xFF); //获取前八位的退出状态 } else if(ret > 0) // 该进程有子进程退出 , 非正常退出 { printf("sig code: %d",(status&0x7F)); } } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> char *ip2str(unsigned int ipv4, char *str_ip, unsigned int str_len) { if (str_ip == NULL || str_len < 16) { return NULL; } sprintf(str_ip, "%d.%d.%d.%d", (ipv4>>24)&0xff, (ipv4>>16)&0xff, (ipv4>>8)&0xff, ipv4&0xff); return str_ip; } unsigned int str2ip(const char *ipstr) { struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); inet_pton(AF_INET, ipstr, &addr.sin_addr); return addr.sin_addr.s_addr; }
C
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> int main(int argc, char **argv) { FILE *fp; char *line; char ssid[16]; char passwd[16]; size_t rlen; if(argc < 2){ printf("%s [FILE PATH]\n", argv[0]); return -1; } fp = fopen(argv[1], "r"); assert(fp); int r = getline(&line, &rlen, fp); memcpy(ssid, line, r); ssid[r-1] = '\0'; printf("read len = %d\n", r); printf("You Got the ssid: %s\n", ssid); if(line) free(line); fclose(fp); return 0; }
C
/***************************** FLAG - @ ESC - ! ****************************/ #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define MSGSZ 1024 #define FLAG '@' #define ESC '!' struct message_buf { long mtype; char s[MSGSZ]; }; void charCount(char* s,int a); void byteStuffing(char* s,int a); int main() { int msqid; int msgflg = 0666; key_t key; size_t buf_length; //buffer struct struct message_buf sbuf; key = 2929; if((msqid = msgget(key, msgflg )) < 0) { perror("msgget"); exit(1); } else printf("connected\n"); char c; printf("Press 1 for character count\n Press 2 for Byte Stuffing \n"); scanf("%c",&c); if(msgrcv(msqid, &sbuf, MSGSZ, 1, 0) < 0) { perror("msgrcv"); exit(1); } printf("Message: Received\n"); buf_length = strlen(sbuf.s); if(c == '1') { charCount(sbuf.s, buf_length); } else { byteStuffing(sbuf.s, buf_length); } return 0; } void charCount(char* s,int len) { int fsize,i,j; for(i=0; i < len ; ) { fsize=(s[i]-'0'); printf("Frame :\t"); for(j=i+1; j < i + fsize; j++) { printf("%c",s[j]); } printf("\n"); i += fsize; } } void byteStuffing(char* s,int len) { int fflag = 0, eflag = 0;; int i = 0; char t; for(i = 0; i < len; i++) { t = s[i]; if(eflag == 1) { //ignore printf("%c", t); eflag = 0; } else if(eflag == 0 && t == ESC) { eflag = 1; } else if(t == FLAG && fflag == 1) //ending flag { fflag = 0; printf("\n"); } else if(t == FLAG && fflag == 0) //starting flag { fflag = 1; printf("Frame :\t"); } else { printf("%c", t); } } }
C
#include "common.h" #define ETEST 7 void test(int level) { extern int item[3], scorearray[SCHSIZE][ASIZE], gobackstart; extern int TotalScore, O_X[MAX_Q]; extern char sch[SCHSIZE][SIZE]; char word[SIZE], input[SIZE]; int key, addtime = 0, num; int result, x; // resetOX(); // ̾ƿ system("cls"); drawline(21, 8, 75, 25); // 丮 gotoxy(32, 15); printf("մϴ"); Sleep(1000); gotoxy(32, 17); printf("%sб ƽϴ", sch[level]); Sleep(1000); gotoxy(32, 19); printf("%sб ̱⼼", sch[level]); Sleep(2000); system("cls"); if (item[ADDTIME]) { drawline(21, 8, 75, 25); drawitem(); gotoxy(32, 15); printf("ð ߰ ֽϴ."); Sleep(1000); gotoxy(32, 17); printf("Ͻðڽϱ? [y/n]"); key = _getch(); switch (key) { case 'y': gotoxy(32, 19); printf(" մϴ."); Sleep(1000); gotoxy(32, 21); printf("ѽð %d þϴ.", item[ADDTIME]); Sleep(1000); while (item[ADDTIME]) { item[ADDTIME]--; addtime++; } break; case 'n': gotoxy(32, 19); printf(" ʽϴ."); Sleep(1000); break; } } // for (num = 1; num <= 5; num++) { // ˻ if ((item[LIFE]) == 0) break; test_layout(level, num); // switch (level) { case E: x = 53; gotoxy(x, 19); random_word(ETEST, word); break; case M: x = 47; gotoxy(x, 19); word_short(word); break; case H: x = 40; gotoxy(x, 19); word_short_h(word); break; } // ߱ & result = game(x, input, word, T, level, addtime); if (result == 5) { num--; continue; } while (1) { if (result == 2) // ޴ ƿ { // ٽ test_layout(level, num); gotoxy(x, 19); printf("%s", word); result = game(x, input, word, T, level, addtime); } if (result == 4) { gobackstart = 1; break; } else break; } if (gobackstart) break; // ǥ O_X[scorearray[level][B_Q_SOLVED] - 1] = result; system("cls"); } }
C
#include "simulador_de_festa.h" #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include "aluno.h" void cria_threads_alunos(int numero_alunos); void cria_thread_seguranca(); void lanca_threads(); int global_max_tempo_chegada; int global_max_tempo_sala; int global_max_tempo_ronda; void simula(int numero_alunos, int max_alunos, int max_tempo_chegada, int max_tempo_sala, int max_tempo_ronda) { global_max_tempo_chegada = max_tempo_chegada; global_max_tempo_sala = max_tempo_sala; global_max_tempo_ronda = max_tempo_ronda; cria_threads_alunos(numero_alunos); cria_thread_seguranca(); lanca_threads(); } int get_max_tempo_chegada() { return global_max_tempo_chegada; } int get_max_tempo_sala() { return global_max_tempo_sala; } int get_max_tempo_ronda() { return global_max_tempo_ronda; } void cria_threads_alunos(int numero_alunos) { long i; pthread_t threads[numero_alunos]; int codigo_retorno; for (i = 0; i < numero_alunos; i++) { codigo_retorno = pthread_create(&threads[i], NULL, simula_aluno, (void *) i); if (codigo_retorno) { printf("ERROR; return code from pthread_create() is %d\n", codigo_retorno); exit(-1); } } for (i = 0; i < numero_alunos; i++) { pthread_join(threads[i], NULL); } printf("acabou\n"); /* Last thing that main() should do */ pthread_exit(NULL); } void cria_thread_seguranca() { } void lanca_threads() { }
C
#include <time.h> #include "timer.h" int start_time; void timer_start(){ start_time = time(NULL); } int timer_check(){ return difftime(time(NULL), start_time) > 3 ? 1 : 0; //Er det noe lurt som skjer her? Kommentar? }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_modif_len.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vburidar <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/12/14 15:48:09 by vburidar #+# #+# */ /* Updated: 2018/02/19 13:02:46 by vburidar ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> int ft_find_double(char *tab_flag, char c) { while (*tab_flag) { if (*tab_flag == c && *(tab_flag + 1) == c) { *tab_flag = ','; *(tab_flag + 1) = ','; return (1); } tab_flag++; } return (0); } int ft_find_single(char *tab_flag, char c) { while (*tab_flag) { if (*tab_flag == c) return (1); tab_flag++; } return (0); } unsigned long long ft_size_var(char *tab_flag, va_list *pt_ap) { unsigned long long valeur; if (ft_find_double(tab_flag, 'l')) valeur = (va_arg(*pt_ap, unsigned long long)); else if (ft_find_single(tab_flag, 'l')) valeur = (va_arg(*pt_ap, unsigned long)); else if (ft_find_single(tab_flag, 'j')) valeur = (va_arg(*pt_ap, uintmax_t)); else if (ft_find_single(tab_flag, 'z')) valeur = (va_arg(*pt_ap, size_t)); else if (ft_find_double(tab_flag, 'h')) valeur = (unsigned char)(va_arg(*pt_ap, int)); else if (ft_find_single(tab_flag, 'h')) valeur = (unsigned short)(va_arg(*pt_ap, int)); else valeur = (va_arg(*pt_ap, unsigned int)); return (valeur); }
C
#define MAXQUEUE 5 struct state_t { int a[MAXQUEUE]; int front; int rear; int size; }; #define assume_ibeta() \ __VERIFIER_assume(s1.front >= 0); \ __VERIFIER_assume(s1.front <= 5 -1);\ __VERIFIER_assume(s1.rear >= 0); \ __VERIFIER_assume(s1.rear <= 5 -1); \ __VERIFIER_assume(s1.size >= 0); \ __VERIFIER_assume(s1.size < 5); \ __VERIFIER_assume(s1.size == s1.rear - s1.front + 1); \ __VERIFIER_assume(s1.front == s2.front); \ __VERIFIER_assume(s1.rear == s2.rear); \ __VERIFIER_assume(s1.size == s2.size); \ for (int i = s1.front; i <= s1.rear; i++) { __VERIFIER_assume(s1.a[i] == s2.a[i]); } \ __VERIFIER_assume(s1.rear >= s1.front - 1); #define assert_ibeta() \ if (!( s1.rear >= s1.front - 1 )) __VERIFIER_error(); \ if (!( s1.front == s2.front )) __VERIFIER_error(); \ if (!( s1.rear == s2.rear )) __VERIFIER_error();\ if (!( s1.size == s2.size )) __VERIFIER_error();\ for (int i = s1.front; i <= s1.rear; i++) { \ if (s1.a[i] != s2.a[i]) __VERIFIER_error(); \ }
C
#include<dirent.h> #include<unistd.h> #include<sys/types.h> #include<stdlib.h> #include<stdio.h> int main(int argc,char *args[]){ DIR *sima; struct dirent *dalao; if(argc!=2) printf("usgae: directory_name"); sima=opendir(args[1]); if(sima==NULL) printf("Can't open %s",args[1]); while((dalao=readdir(sima))!=NULL){ printf("%s\n",dalao->d_name); } closedir(sima); exit(0); }
C
#include <stdio.h> #include <string.h> /*int main(void) { char *pc; int *pi; double *pd; printf("*pc ũ : %d\n", sizeof(pc)); printf("*pd ũ : %d\n", sizeof(pi)); printf("*pd ũ : %d\n", sizeof(pd)); printf("char* ũ : %d\n", sizeof(char*)); printf("short* ũ : %d\n", sizeof(short*)); printf("int* ũ : %d\n", sizeof(int*)); printf("float* ũ : %d\n", sizeof(float*)); printf("double* ũ : %d\n", sizeof(double*)); return 0; }*/ /*int main(void) { int x; int *p; p = &x; *p = 10; printf("*p = %d\n", *p); // 10 ð . printf("x = %d\n", x); // 10 ð . printf("p = %p\n", p); //x ּҰ . printf("&x = %p\n", &x); // .. printf("&p = %p\n", &p); return 0; }*/ /*int main(void) { char ch; char *pc = &ch; int x; int *y = &x; double dou; double *pd = &dou; int arr[3]; int i; for (i = 0; i < 3; i++) printf("*pc + %d = %p\n", i, pc + i); for (i = 0; i < 3; i++) printf("*y + %d = %p\n", i, y + 1); for (i = 0; i < 3; i++) printf("*pd + %d = %p\n", i, pd + i); return 0; }*/ /*int main(void) { int arr[5] = { 10,20,30,40,50 }; int *p = &arr[0]; // ּҴ 迭 ƿ. int i; for (i = 0; i < 5; i++, p++) printf("*p + %d = %d\n", i, *p); return 0; }*/ /*int main(void) { int arr[5] = { 10,20,30,40,50 }; int i; for (i = 0; i < 5; i++) { printf("&arr[%d] = %p\n", i, &arr[i]); printf("arr + %d = %p\n", i, arr + i); } for (i = 0; i < 5; i++) { printf("arr[%d] = %d\n", i, arr[i]); printf("*(arr+%d) = %d\n", i, *(arr + i)); } return 0; }*/ int main(void) { char arr1[99] = { 0 }; char arr2[99] = { 0 }; char *p; int i; printf("ڿ Էϼ : "); gets(arr1); p = arr1; for (i = 0; i < 99; i++,p++) { arr2[i] = *p; } puts(arr2); return 0; }
C
#include <vxWorks.h> #include <sysLib.h> #define nelem(x) (sizeof(x) / sizeof(x[0])) static void serialprint(const char *str) { int port; size_t i; port = 0x3f8; for (i = 0; str[i]; i++) sysOutByte(port, str[i]); } static int stoib(char *buf, unsigned long long val, unsigned long long base) { static const char alphabet[] = "0123456789abcdef"; int i, j, n; char c; n = 0; do { buf[n++] = alphabet[val % base]; val /= base; } while (val); for (i = 0; i < n / 2; i++) { j = n - i - 1; c = buf[i]; buf[i] = buf[j]; buf[j] = c; } buf[n] = '\0'; return n; } void printval(const char *name, unsigned long long val, unsigned long long base) { char buf[32]; stoib(buf, val, base); serialprint(name); serialprint(": "); serialprint(buf); serialprint("\n"); } void printptr(const char *name, void *ptr) { printval(name, (unsigned long long)ptr, 16); } void printstr(const char *str) { serialprint(str); } void printline(const char *str) { serialprint(str); serialprint("\n"); } void sysmemdesc(void) { static const struct { char name[32]; MEM_DESC_TYPE type; } desc[] = { {"MEM_DESC_RAM", MEM_DESC_RAM}, {"MEM_DESC_USER_RESERVED_RAM", MEM_DESC_USER_RESERVED_RAM}, {"MEM_DESC_PM_RAM", MEM_DESC_PM_RAM}, {"MEM_DESC_DMA32_RAM", MEM_DESC_DMA32_RAM}, {"MEM_DESC_ROM", MEM_DESC_ROM}, }; struct phys_mem_desc p; size_t i; int n; printstr("\n"); for (i = 0; i < nelem(desc); i++) { for (n = 0; sysMemDescGet(desc[i].type, n, &p) != ERROR; n++) { if (n == 0) printline(desc[i].name); printval("\tvirtual_address :", p.virtualAddr, 16); printval("\tphysical address :", p.physicalAddr, 16); printval("\tlength :", p.len, 16); printval("\tinitial state mask :", p.initialStateMask, 16); printval("\tinitial state :", p.initialState, 16); printstr("\n"); } printstr("\n"); } printstr("\n"); }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h> int leap_year(int year) { if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { return 1; } else return 0; } int main() { int y = 0; printf("ݣ"); scanf("%d", &y); if (leap_year(y) == 1) { printf("\n"); } else { printf("\n"); } system("pause"); return 0; }
C
/** * @file main.c * @author Jiangwen Su <[email protected]> * @date 2014-11-07 23:47:06 * * @brief * * */ #include "common.h" #include "daemon.h" #include "filesystem.h" #include "sysinfo.h" #include "logger.h" static char program_name[] = "edbroker"; typedef struct{ const char *frontend; const char *backend; int is_daemon; int log_level; } program_options_t; static struct option const long_options[] = { {"frontend", required_argument, NULL, 'f'}, {"backend", required_argument, NULL, 'b'}, {"threads", required_argument, NULL, 'u'}, {"daemon", no_argument, NULL, 'd'}, {"verbose", no_argument, NULL, 'v'}, {"trace", no_argument, NULL, 't'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0}, }; static const char *short_options = "f:b:u:dvth"; extern int run_broker(const char *frontend, const char *backend, int verbose); /* ==================== daemon_loop() ==================== */ int daemon_loop(void *data) { notice_log("In daemon_loop()"); const program_options_t *po = (const program_options_t *)data; return run_broker(po->frontend, po->backend, po->log_level >= LOG_DEBUG ? 1 : 0); } /* ==================== usage() ==================== */ static void usage(int status) { if ( status ) fprintf(stderr, "Try `%s --help' for more information.\n", program_name); else { printf("Usage: %s [OPTION] [PATH]\n", program_name); printf("Everdata Worker\n\ -f, --frontend specify the edbroker frontend endpoint\n\ -b, --backend specify the edbroker backend endpoint\n\ -u, --threads count of threads\n\ -d, --daemon run in the daemon mode. \n\ -v, --verbose print debug messages\n\ -t, --trace print trace messages\n\ -h, --help display this help and exit\n\ "); } exit(status); } int main(int argc, char *argv[]) { program_options_t po; memset(&po, 0, sizeof(program_options_t)); /*po.frontend = "tcp://127.0.0.1:19977";*/ /*po.backend = "tcp://127.0.0.1:19978";*/ po.frontend = "tcp://*:19977"; po.backend = "tcp://*:19978"; po.is_daemon = 0; po.log_level = LOG_INFO; int ch, longindex; while ((ch = getopt_long(argc, argv, short_options, long_options, &longindex)) >= 0) { switch (ch) { case 'f': po.frontend = optarg; break; case 'b': po.backend = optarg; break; case 'd': po.is_daemon = 1; break; case 'v': po.log_level = LOG_DEBUG; break; case 't': po.log_level = LOG_TRACE; break; case 'h': usage(0); break; default: usage(1); break; } } /* -------- Init logger -------- */ char root_dir[NAME_MAX]; get_instance_parent_full_path(root_dir, NAME_MAX); char log_dir[NAME_MAX]; sprintf(log_dir, "%s/log", root_dir); mkdir_if_not_exist(log_dir); char logfile[PATH_MAX]; sprintf(logfile, "%s/%s.log", log_dir, program_name); if (log_init(program_name, LOG_SPACE_SIZE, po.is_daemon, po.log_level, logfile)) return -1; if ( po.is_daemon ){ return daemon_fork(daemon_loop, (void*)&po); } else return run_broker(po.frontend, po.backend, po.log_level >= LOG_DEBUG ? 1 : 0); }
C
/** libsmacker - A C library for decoding .smk Smacker Video files Copyright (C) 2012-2021 Greg Kennedy See smacker.h for more information. smacker.c Main implementation file of libsmacker. Open, close, query, render, advance and seek an smk */ #include "smacker.h" #include "smk_malloc.h" #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> /* ************************************************************************* */ /* BITSTREAM Structure */ /* ************************************************************************* */ /* Wraps a block of memory and adds functions to read 1 or 8 bits at a time */ struct smk_bit_t { const unsigned char * buffer, * end; unsigned int bit_num; }; /* ************************************************************************* */ /* BITSTREAM Functions */ /* ************************************************************************* */ /** Initialize a bitstream wrapper */ static void smk_bs_init(struct smk_bit_t * const bs, const unsigned char * const b, const size_t size) { /* null check */ assert(bs); assert(b); /* set up the pointer to bitstream start and end, and set the bit pointer to 0 */ bs->buffer = b; bs->end = b + size; bs->bit_num = 0; } /* Reads a bit Returns -1 if error encountered */ static int smk_bs_read_1(struct smk_bit_t * const bs) { int ret; /* null check */ assert(bs); /* don't die when running out of bits, but signal */ if (bs->buffer >= bs->end) { fputs("libsmacker::smk_bs_read_1(): ERROR: bitstream exhausted.\n", stderr); return -1; } /* get next bit and store for return */ ret = (*bs->buffer >> bs->bit_num) & 1; /* advance to next bit */ if (bs->bit_num >= 7) { /* Out of bits in this byte: next! */ bs->buffer ++; bs->bit_num = 0; } else bs->bit_num ++; return ret; } /* Reads a byte Returns -1 if error. */ static int smk_bs_read_8(struct smk_bit_t * const bs) { /* null check */ assert(bs); /* don't die when running out of bits, but signal */ if (bs->buffer + (bs->bit_num > 0) >= bs->end) { fputs("libsmacker::smk_bs_read_8(): ERROR: bitstream exhausted.\n", stderr); return -1; } if (bs->bit_num) { /* unaligned read */ int ret = *bs->buffer >> bs->bit_num; bs->buffer ++; return ret | (*bs->buffer << (8 - bs->bit_num) & 0xFF); } /* aligned read */ return *bs->buffer++; } /* ************************************************************************* */ /* HUFF8 Structure */ /* ************************************************************************* */ #define SMK_HUFF8_BRANCH 0x8000 #define SMK_HUFF8_LEAF_MASK 0x7FFF struct smk_huff8_t { /* Unfortunately, smk files do not store the alloc size of a small tree. 511 entries is the pessimistic case (N codes and N-1 branches, with N=256 for 8 bits) */ size_t size; unsigned short tree[511]; }; /* ************************************************************************* */ /* HUFF8 Functions */ /* ************************************************************************* */ /* Recursive sub-func for building a tree into an array. */ static int _smk_huff8_build_rec(struct smk_huff8_t * const t, struct smk_bit_t * const bs) { int bit, value; assert(t); assert(bs); /* Make sure we aren't running out of bounds */ if (t->size >= 511) { fputs("libsmacker::_smk_huff8_build_rec() - ERROR: size exceeded\n", stderr); return 0; } /* Read the next bit */ if ((bit = smk_bs_read_1(bs)) < 0) { fputs("libsmacker::_smk_huff8_build_rec() - ERROR: get_bit returned -1\n", stderr); return 0; } if (bit) { /* Bit set: this forms a Branch node. what we have to do is build the left-hand branch, assign the "jump" address, then build the right hand branch from there. */ /* track the current index */ value = t->size ++; /* go build the left branch */ if (! _smk_huff8_build_rec(t, bs)) { fputs("libsmacker::_smk_huff8_build_rec() - ERROR: failed to build left sub-tree\n", stderr); return 0; } /* now go back to our current location, and mark our location as a "jump" */ t->tree[value] = SMK_HUFF8_BRANCH | t->size; /* continue building the right side */ if (! _smk_huff8_build_rec(t, bs)) { fputs("libsmacker::_smk_huff8_build_rec() - ERROR: failed to build right sub-tree\n", stderr); return 0; } } else { /* Bit unset signifies a Leaf node. */ /* Attempt to read value */ if ((value = smk_bs_read_8(bs)) < 0) { fputs("libsmacker::_smk_huff8_build_rec() - ERROR: get_byte returned -1\n", stderr); return 0; } /* store to tree */ t->tree[t->size ++] = value; } return 1; } /** Build an 8-bit Hufftree out of a Bitstream. */ static int smk_huff8_build(struct smk_huff8_t * const t, struct smk_bit_t * const bs) { int bit; /* null check */ assert(t); assert(bs); /* Smacker huff trees begin with a set-bit. */ if ((bit = smk_bs_read_1(bs)) < 0) { fputs("libsmacker::smk_huff8_build() - ERROR: initial get_bit returned -1\n", stderr); return 0; } /* OK to fill out the struct now */ t->size = 0; /* First bit indicates whether a tree is present or not. */ /* Very small or audio-only files may have no tree. */ if (bit) { if (! _smk_huff8_build_rec(t, bs)) { fputs("libsmacker::smk_huff8_build() - ERROR: tree build failed\n", stderr); return 0; } } else t->tree[0] = 0; /* huff trees end with an unset-bit */ if ((bit = smk_bs_read_1(bs)) < 0) { fputs("libsmacker::smk_huff8_build() - ERROR: final get_bit returned -1\n", stderr); return 0; } /* a 0 is expected here, a 1 generally indicates a problem! */ if (bit) { fputs("libsmacker::smk_huff8_build() - ERROR: final get_bit returned 1\n", stderr); return 0; } return 1; } /* Look up an 8-bit value from a basic huff tree. Return -1 on error. */ static int smk_huff8_lookup(const struct smk_huff8_t * const t, struct smk_bit_t * const bs) { int bit, index = 0; /* null check */ assert(t); assert(bs); while (t->tree[index] & SMK_HUFF8_BRANCH) { if ((bit = smk_bs_read_1(bs)) < 0) { fputs("libsmacker::smk_huff8_lookup() - ERROR: get_bit returned -1\n", stderr); return -1; } if (bit) { /* take the right branch */ index = t->tree[index] & SMK_HUFF8_LEAF_MASK; } else { /* take the left branch */ index ++; } } /* at leaf node. return the value at this point. */ return t->tree[index]; } /* ************************************************************************* */ /* HUFF16 Structure */ /* ************************************************************************* */ #define SMK_HUFF16_BRANCH 0x80000000 #define SMK_HUFF16_CACHE 0x40000000 #define SMK_HUFF16_LEAF_MASK 0x3FFFFFFF struct smk_huff16_t { unsigned int * tree; size_t size; /* recently-used values cache */ unsigned short cache[3]; }; /* ************************************************************************* */ /* HUFF16 Functions */ /* ************************************************************************* */ /* Recursive sub-func for building a tree into an array. */ static int _smk_huff16_build_rec(struct smk_huff16_t * const t, struct smk_bit_t * const bs, const struct smk_huff8_t * const low8, const struct smk_huff8_t * const hi8, const size_t limit) { int bit, value; assert(t); assert(bs); assert(low8); assert(hi8); /* Make sure we aren't running out of bounds */ if (t->size >= limit) { fputs("libsmacker::_smk_huff16_build_rec() - ERROR: size exceeded\n", stderr); return 0; } /* Read the first bit */ if ((bit = smk_bs_read_1(bs)) < 0) { fputs("libsmacker::_smk_huff16_build_rec() - ERROR: get_bit returned -1\n", stderr); return 0; } if (bit) { /* See tree-in-array explanation for HUFF8 above */ /* track the current index */ value = t->size ++; /* go build the left branch */ if (! _smk_huff16_build_rec(t, bs, low8, hi8, limit)) { fputs("libsmacker::_smk_huff16_build_rec() - ERROR: failed to build left sub-tree\n", stderr); return 0; } /* now go back to our current location, and mark our location as a "jump" */ t->tree[value] = SMK_HUFF16_BRANCH | t->size; /* continue building the right side */ if (! _smk_huff16_build_rec(t, bs, low8, hi8, limit)) { fputs("libsmacker::_smk_huff16_build_rec() - ERROR: failed to build right sub-tree\n", stderr); return 0; } } else { /* Bit unset signifies a Leaf node. */ /* Attempt to read LOW value */ if ((value = smk_huff8_lookup(low8, bs)) < 0) { fputs("libsmacker::_smk_huff16_build_rec() - ERROR: get LOW value returned -1\n", stderr); return 0; } t->tree[t->size] = value; /* now read HIGH value */ if ((value = smk_huff8_lookup(hi8, bs)) < 0) { fputs("libsmacker::_smk_huff16_build_rec() - ERROR: get HIGH value returned -1\n", stderr); return 0; } /* Looks OK: we got low and hi values. Return a new LEAF */ t->tree[t->size] |= (value << 8); /* Last: when building the tree, some Values may correspond to cache positions. Identify these values and set the Escape code byte accordingly. */ if (t->tree[t->size] == t->cache[0]) t->tree[t->size] = SMK_HUFF16_CACHE; else if (t->tree[t->size] == t->cache[1]) t->tree[t->size] = SMK_HUFF16_CACHE | 1; else if (t->tree[t->size] == t->cache[2]) t->tree[t->size] = SMK_HUFF16_CACHE | 2; t->size ++; } return 1; } /* Entry point for building a big 16-bit tree. */ static int smk_huff16_build(struct smk_huff16_t * const t, struct smk_bit_t * const bs, const unsigned int alloc_size) { struct smk_huff8_t low8, hi8; size_t limit; int value, i, bit; /* null check */ assert(t); assert(bs); /* Smacker huff trees begin with a set-bit. */ if ((bit = smk_bs_read_1(bs)) < 0) { fputs("libsmacker::smk_huff16_build() - ERROR: initial get_bit returned -1\n", stderr); return 0; } t->size = 0; /* First bit indicates whether a tree is present or not. */ /* Very small or audio-only files may have no tree. */ if (bit) { /* build low-8-bits tree */ if (! smk_huff8_build(&low8, bs)) { fputs("libsmacker::smk_huff16_build() - ERROR: failed to build LOW tree\n", stderr); return 0; } /* build hi-8-bits tree */ if (! smk_huff8_build(&hi8, bs)) { fputs("libsmacker::smk_huff16_build() - ERROR: failed to build HIGH tree\n", stderr); return 0; } /* Init the escape code cache. */ for (i = 0; i < 3; i ++) { if ((value = smk_bs_read_8(bs)) < 0) { fprintf(stderr, "libsmacker::smk_huff16_build() - ERROR: get LOW value for cache %d returned -1\n", i); return 0; } t->cache[i] = value; /* now read HIGH value */ if ((value = smk_bs_read_8(bs)) < 0) { fprintf(stderr, "libsmacker::smk_huff16_build() - ERROR: get HIGH value for cache %d returned -1\n", i); return 0; } t->cache[i] |= (value << 8); } /* Everything looks OK so far. Time to malloc structure. */ if (alloc_size < 12 || alloc_size % 4) { fprintf(stderr, "libsmacker::smk_huff16_build() - ERROR: illegal value %u for alloc_size\n", alloc_size); return 0; } limit = (alloc_size - 12) / 4; if ((t->tree = malloc(limit * sizeof(unsigned int))) == NULL) { perror("libsmacker::smk_huff16_build() - ERROR: failed to malloc() huff16 tree"); return 0; } /* Finally, call recursive function to retrieve the Bigtree. */ if (! _smk_huff16_build_rec(t, bs, &low8, &hi8, limit)) { fputs("libsmacker::smk_huff16_build() - ERROR: failed to build huff16 tree\n", stderr); free(t->tree); t->tree = NULL; return 0; } /* check that we completely filled the tree */ if (limit != t->size) { fputs("libsmacker::smk_huff16_build() - ERROR: failed to completely decode huff16 tree\n", stderr); free(t->tree); t->tree = NULL; return 0; } } else { if ((t->tree = malloc(sizeof(unsigned int))) == NULL) { perror("libsmacker::smk_huff16_build() - ERROR: failed to malloc() huff16 tree"); return 0; } t->tree[0] = 0; //t->cache[0] = t->cache[1] = t->cache[2] = 0; } /* Check final end tag. */ if ((bit = smk_bs_read_1(bs)) < 0) { fputs("libsmacker::smk_huff16_build() - ERROR: final get_bit returned -1\n", stderr); free(t->tree); t->tree = NULL; return 0; } /* a 0 is expected here, a 1 generally indicates a problem! */ if (bit) { fputs("libsmacker::smk_huff16_build() - ERROR: final get_bit returned 1\n", stderr); free(t->tree); t->tree = NULL; return 0; } return 1; } /* Look up a 16-bit value from a large huff tree. Return -1 on error. Note that this also updates the recently-used-values cache. */ static int smk_huff16_lookup(struct smk_huff16_t * const t, struct smk_bit_t * const bs) { int bit, value, index = 0; /* null check */ assert(t); assert(bs); while (t->tree[index] & SMK_HUFF16_BRANCH) { if ((bit = smk_bs_read_1(bs)) < 0) { fputs("libsmacker::smk_huff16_lookup() - ERROR: get_bit returned -1\n", stderr); return -1; } if (bit) { /* take the right branch */ index = t->tree[index] & SMK_HUFF16_LEAF_MASK; } else { /* take the left branch */ index ++; } } /* Get the value at this point */ value = t->tree[index]; if (value & SMK_HUFF16_CACHE) { /* uses cached value instead of actual value */ value = t->cache[value & SMK_HUFF16_LEAF_MASK]; } if (t->cache[0] != value) { /* Update the cache, by moving val to the front of the queue, if it isn't already there. */ t->cache[2] = t->cache[1]; t->cache[1] = t->cache[0]; t->cache[0] = value; } return value; } /* ************************************************************************* */ /* SMACKER Structure */ /* ************************************************************************* */ /* tree processing order */ #define SMK_TREE_MMAP 0 #define SMK_TREE_MCLR 1 #define SMK_TREE_FULL 2 #define SMK_TREE_TYPE 3 struct smk_t { /* meta-info */ /* file mode: see flags, smacker.h */ unsigned char mode; /* microsec per frame - stored as a double to handle scaling (large positive millisec / frame values may overflow a ul) */ double usf; /* total frames */ unsigned long f; /* does file have a ring frame? (in other words, does file loop?) */ unsigned char ring_frame; /* Index of current frame */ unsigned long cur_frame; /* SOURCE union. Where the data is going to be read from (or be stored), depending on the file mode. */ union { struct { /* on-disk mode */ FILE * fp; unsigned long * chunk_offset; } file; /* in-memory mode: unprocessed chunks */ unsigned char ** chunk_data; } source; /* shared array of "chunk sizes"*/ unsigned long * chunk_size; /* Holds per-frame flags (i.e. 'keyframe') */ unsigned char * keyframe; /* Holds per-frame type mask (e.g. 'audio track 3, 2, and palette swap') */ unsigned char * frame_type; /* video and audio structures */ /* Video data type: enable/disable decode switch, video info and flags, pointer to last-decoded-palette */ struct smk_video_t { /* enable/disable decode switch */ unsigned char enable; /* video info */ unsigned long w; unsigned long h; /* Y scale mode (constants defined in smacker.h) 0: unscaled 1: doubled 2: interlaced */ unsigned char y_scale_mode; /* version ('2' or '4') */ unsigned char v; /* Huffman trees */ unsigned long tree_size[4]; struct smk_huff16_t tree[4]; /* Palette data type: pointer to last-decoded-palette */ unsigned char palette[256][3]; /* Last-unpacked frame */ unsigned char * frame; } video; /* audio structure */ struct smk_audio_t { /* set if track exists in file */ unsigned char exists; /* enable/disable switch (per track) */ unsigned char enable; /* Info */ unsigned char channels; unsigned char bitdepth; unsigned long rate; long max_buffer; /* compression type 0: raw PCM 1: SMK DPCM 2: Bink (Perceptual), unsupported */ unsigned char compress; /* pointer to last-decoded-audio-buffer */ void * buffer; unsigned long buffer_size; } audio[7]; }; union smk_read_t { FILE * file; unsigned char * ram; }; /* ************************************************************************* */ /* SMACKER Functions */ /* ************************************************************************* */ /* An fread wrapper: consumes N bytes, or returns -1 on failure (when size doesn't match expected) */ static char smk_read_file(void * buf, const size_t size, FILE * fp) { /* don't bother checking buf or fp, fread does it for us */ size_t bytesRead = fread(buf, 1, size, fp); if (bytesRead != size) { fprintf(stderr, "libsmacker::smk_read_file(buf,%lu,fp) - ERROR: Short read, %lu bytes returned\n", (unsigned long)size, (unsigned long)bytesRead); perror("\tReason"); return -1; } return 0; } /* A memcpy wrapper: consumes N bytes, or returns -1 on failure (when size too low) */ static char smk_read_memory(void * buf, const unsigned long size, unsigned char ** p, unsigned long * p_size) { if (size > *p_size) { fprintf(stderr, "libsmacker::smk_read_memory(buf,%lu,p,%lu) - ERROR: Short read\n", (unsigned long)size, (unsigned long)*p_size); return -1; } memcpy(buf, *p, size); *p += size; *p_size -= size; return 0; } /* Helper functions to do the reading, plus byteswap from LE to host order */ /* read n bytes from (source) into ret */ #define smk_read(ret,n) \ { \ if (m) \ { \ r = (smk_read_file(ret,n,fp.file)); \ } \ else \ { \ r = (smk_read_memory(ret,n,&fp.ram,&size)); \ } \ if (r < 0) \ { \ fprintf(stderr,"libsmacker::smk_read(...) - Errors encountered on read, bailing out (file: %s, line: %lu)\n", __FILE__, (unsigned long)__LINE__); \ goto error; \ } \ } /* Calls smk_read, but returns a ul */ #define smk_read_ul(p) \ { \ smk_read(buf,4); \ p = ((unsigned long) buf[3] << 24) | \ ((unsigned long) buf[2] << 16) | \ ((unsigned long) buf[1] << 8) | \ ((unsigned long) buf[0]); \ } /* PUBLIC FUNCTIONS */ /* open an smk (from a generic Source) */ static smk smk_open_generic(const unsigned char m, union smk_read_t fp, unsigned long size, const unsigned char process_mode) { /* Smacker structure we intend to work on / return */ smk s; /* Temporary variables */ long temp_l; unsigned long temp_u; /* r is used by macros above for return code */ char r; unsigned char buf[4] = {'\0'}; /* video hufftrees are stored as a large chunk (bitstream) these vars are used to load, then decode them */ unsigned char * hufftree_chunk = NULL; unsigned long tree_size; /* a bitstream struct */ struct smk_bit_t bs; /** **/ /* safe malloc the structure */ if ((s = calloc(1, sizeof(struct smk_t))) == NULL) { perror("libsmacker::smk_open_generic() - ERROR: failed to malloc() smk structure"); return NULL; } /* Check for a valid signature */ smk_read(buf, 3); if (buf[0] != 'S' || buf[1] != 'M' || buf[2] != 'K') { fprintf(stderr, "libsmacker::smk_open_generic - ERROR: invalid SMKn signature (got: %s)\n", buf); goto error; } /* Read .smk file version */ smk_read(&s->video.v, 1); if (s->video.v != '2' && s->video.v != '4') { fprintf(stderr, "libsmacker::smk_open_generic - Warning: invalid SMK version %c (expected: 2 or 4)\n", s->video.v); /* take a guess */ if (s->video.v < '4') s->video.v = '2'; else s->video.v = '4'; fprintf(stderr, "\tProcessing will continue as type %c\n", s->video.v); } /* width, height, total num frames */ smk_read_ul(s->video.w); smk_read_ul(s->video.h); smk_read_ul(s->f); /* frames per second calculation */ smk_read_ul(temp_u); temp_l = (int)temp_u; if (temp_l > 0) { /* millisec per frame */ s->usf = temp_l * 1000; } else if (temp_l < 0) { /* 10 microsec per frame */ s->usf = temp_l * -10; } else { /* defaults to 10 usf (= 100000 microseconds) */ s->usf = 100000; } /* Video flags follow. Ring frame is important to libsmacker. Y scale / Y interlace go in the Video flags. The user should scale appropriately. */ smk_read_ul(temp_u); if (temp_u & 0x01) s->ring_frame = 1; if (temp_u & 0x02) s->video.y_scale_mode = SMK_FLAG_Y_DOUBLE; if (temp_u & 0x04) { if (s->video.y_scale_mode == SMK_FLAG_Y_DOUBLE) fputs("libsmacker::smk_open_generic - Warning: SMK file specifies both Y-Double AND Y-Interlace.\n", stderr); s->video.y_scale_mode = SMK_FLAG_Y_INTERLACE; } /* Max buffer size for each audio track - used to pre-allocate buffers */ for (temp_l = 0; temp_l < 7; temp_l ++) smk_read_ul(s->audio[temp_l].max_buffer); /* Read size of "hufftree chunk" - save for later. */ smk_read_ul(tree_size); /* "unpacked" sizes of each huff tree */ for (temp_l = 0; temp_l < 4; temp_l ++) smk_read_ul(s->video.tree_size[temp_l]); /* read audio rate data */ for (temp_l = 0; temp_l < 7; temp_l ++) { smk_read_ul(temp_u); if (temp_u & 0x40000000) { /* Audio track specifies "exists" flag, malloc structure and copy components. */ s->audio[temp_l].exists = 1; /* and for all audio tracks */ smk_malloc(s->audio[temp_l].buffer, s->audio[temp_l].max_buffer); if (temp_u & 0x80000000) s->audio[temp_l].compress = 1; s->audio[temp_l].bitdepth = ((temp_u & 0x20000000) ? 16 : 8); s->audio[temp_l].channels = ((temp_u & 0x10000000) ? 2 : 1); if (temp_u & 0x0c000000) { fprintf(stderr, "libsmacker::smk_open_generic - Warning: audio track %ld is compressed with Bink (perceptual) Audio Codec: this is currently unsupported by libsmacker\n", temp_l); s->audio[temp_l].compress = 2; } /* Bits 25 & 24 are unused. */ s->audio[temp_l].rate = (temp_u & 0x00FFFFFF); } } /* Skip over Dummy field */ smk_read_ul(temp_u); /* FrameSizes and Keyframe marker are stored together. */ smk_malloc(s->keyframe, (s->f + s->ring_frame)); smk_malloc(s->chunk_size, (s->f + s->ring_frame) * sizeof(unsigned long)); for (temp_u = 0; temp_u < (s->f + s->ring_frame); temp_u ++) { smk_read_ul(s->chunk_size[temp_u]); /* Set Keyframe */ if (s->chunk_size[temp_u] & 0x01) s->keyframe[temp_u] = 1; /* Bits 1 is used, but the purpose is unknown. */ s->chunk_size[temp_u] &= 0xFFFFFFFC; } /* That was easy... Now read FrameTypes! */ smk_malloc(s->frame_type, (s->f + s->ring_frame)); for (temp_u = 0; temp_u < (s->f + s->ring_frame); temp_u ++) smk_read(&s->frame_type[temp_u], 1); /* HuffmanTrees We know the sizes already: read and assemble into something actually parse-able at run-time */ smk_malloc(hufftree_chunk, tree_size); smk_read(hufftree_chunk, tree_size); /* set up a Bitstream */ smk_bs_init(&bs, hufftree_chunk, tree_size); /* create some tables */ for (temp_u = 0; temp_u < 4; temp_u ++) { if (! smk_huff16_build(&s->video.tree[temp_u], &bs, s->video.tree_size[temp_u])) { fprintf(stderr, "libsmacker::smk_open_generic - ERROR: failed to create huff16 tree %lu\n", temp_u); goto error; } } /* clean up */ smk_free(hufftree_chunk); /* Go ahead and malloc storage for the video frame */ smk_malloc(s->video.frame, s->video.w * s->video.h); /* final processing: depending on ProcessMode, handle what to do with rest of file data */ s->mode = process_mode; /* Handle the rest of the data. For MODE_MEMORY, read the chunks and store */ if (s->mode == SMK_MODE_MEMORY) { smk_malloc(s->source.chunk_data, (s->f + s->ring_frame) * sizeof(unsigned char *)); for (temp_u = 0; temp_u < (s->f + s->ring_frame); temp_u ++) { smk_malloc(s->source.chunk_data[temp_u], s->chunk_size[temp_u]); smk_read(s->source.chunk_data[temp_u], s->chunk_size[temp_u]); } } else { /* MODE_STREAM: don't read anything now, just precompute offsets. use fseek to verify that the file is "complete" */ smk_malloc(s->source.file.chunk_offset, (s->f + s->ring_frame) * sizeof(unsigned long)); for (temp_u = 0; temp_u < (s->f + s->ring_frame); temp_u ++) { s->source.file.chunk_offset[temp_u] = ftell(fp.file); if (fseek(fp.file, s->chunk_size[temp_u], SEEK_CUR)) { fprintf(stderr, "libsmacker::smk_open - ERROR: fseek to frame %lu not OK.\n", temp_u); perror("\tError reported was"); goto error; } } } return s; error: smk_free(hufftree_chunk); smk_close(s); return NULL; } /* open an smk (from a memory buffer) */ smk smk_open_memory(const unsigned char * buffer, const unsigned long size) { smk s = NULL; union smk_read_t fp; if (buffer == NULL) { fputs("libsmacker::smk_open_memory() - ERROR: buffer pointer is NULL\n", stderr); return NULL; } /* set up the read union for Memory mode */ fp.ram = (unsigned char *)buffer; if (!(s = smk_open_generic(0, fp, size, SMK_MODE_MEMORY))) fprintf(stderr, "libsmacker::smk_open_memory(buffer,%lu) - ERROR: Fatal error in smk_open_generic, returning NULL.\n", size); return s; } /* open an smk (from a file) */ smk smk_open_filepointer(FILE * file, const unsigned char mode) { smk s = NULL; union smk_read_t fp; if (file == NULL) { fputs("libsmacker::smk_open_filepointer() - ERROR: file pointer is NULL\n", stderr); return NULL; } /* Copy file ptr to internal union */ fp.file = file; if (!(s = smk_open_generic(1, fp, 0, mode))) { fprintf(stderr, "libsmacker::smk_open_filepointer(file,%u) - ERROR: Fatal error in smk_open_generic, returning NULL.\n", mode); fclose(fp.file); goto error; } if (mode == SMK_MODE_MEMORY) fclose(fp.file); else s->source.file.fp = fp.file; /* fall through, return s or null */ error: return s; } /* open an smk (from a file) */ smk smk_open_file(const char * filename, const unsigned char mode) { FILE * fp; if (filename == NULL) { fputs("libsmacker::smk_open_file() - ERROR: filename is NULL\n", stderr); return NULL; } if (!(fp = fopen(filename, "rb"))) { fprintf(stderr, "libsmacker::smk_open_file(%s,%u) - ERROR: could not open file\n", filename, mode); perror("\tError reported was"); goto error; } /* kick processing to smk_open_filepointer */ return smk_open_filepointer(fp, mode); /* fall through, return s or null */ error: return NULL; } /* close out an smk file and clean up memory */ void smk_close(smk s) { unsigned long u; if (s == NULL) { fputs("libsmacker::smk_close() - ERROR: smk is NULL\n", stderr); return; } /* free video sub-components */ for (u = 0; u < 4; u ++) { if (s->video.tree[u].tree) free(s->video.tree[u].tree); } smk_free(s->video.frame); /* free audio sub-components */ for (u = 0; u < 7; u++) { if (s->audio[u].buffer) smk_free(s->audio[u].buffer); } smk_free(s->keyframe); smk_free(s->frame_type); if (s->mode == SMK_MODE_DISK) { /* disk-mode */ if (s->source.file.fp) fclose(s->source.file.fp); smk_free(s->source.file.chunk_offset); } else { /* mem-mode */ if (s->source.chunk_data != NULL) { for (u = 0; u < (s->f + s->ring_frame); u++) smk_free(s->source.chunk_data[u]); smk_free(s->source.chunk_data); } } smk_free(s->chunk_size); smk_free(s); } /* tell some info about the file */ char smk_info_all(const smk object, unsigned long * frame, unsigned long * frame_count, double * usf) { /* null check */ if (object == NULL) { fputs("libsmacker::smk_info_all() - ERROR: smk is NULL\n", stderr); return -1; } if (!frame && !frame_count && !usf) { fputs("libsmacker::smk_info_all(object,frame,frame_count,usf) - ERROR: Request for info with all-NULL return references\n", stderr); goto error; } if (frame) *frame = (object->cur_frame % object->f); if (frame_count) *frame_count = object->f; if (usf) *usf = object->usf; return 0; error: return -1; } char smk_info_video(const smk object, unsigned long * w, unsigned long * h, unsigned char * y_scale_mode) { /* null check */ if (object == NULL) { fputs("libsmacker::smk_info_video() - ERROR: smk is NULL\n", stderr); return -1; } if (!w && !h && !y_scale_mode) { fputs("libsmacker::smk_info_all(object,w,h,y_scale_mode) - ERROR: Request for info with all-NULL return references\n", stderr); return -1; } if (w) *w = object->video.w; if (h) *h = object->video.h; if (y_scale_mode) *y_scale_mode = object->video.y_scale_mode; return 0; } char smk_info_audio(const smk object, unsigned char * track_mask, unsigned char channels[7], unsigned char bitdepth[7], unsigned long audio_rate[7]) { unsigned char i; /* null check */ if (object == NULL) { fputs("libsmacker::smk_info_audio() - ERROR: smk is NULL\n", stderr); return -1; } if (!track_mask && !channels && !bitdepth && !audio_rate) { fputs("libsmacker::smk_info_audio(object,track_mask,channels,bitdepth,audio_rate) - ERROR: Request for info with all-NULL return references\n", stderr); return -1; } if (track_mask) { *track_mask = ((object->audio[0].exists) | ((object->audio[1].exists) << 1) | ((object->audio[2].exists) << 2) | ((object->audio[3].exists) << 3) | ((object->audio[4].exists) << 4) | ((object->audio[5].exists) << 5) | ((object->audio[6].exists) << 6)); } if (channels) { for (i = 0; i < 7; i ++) channels[i] = object->audio[i].channels; } if (bitdepth) { for (i = 0; i < 7; i ++) bitdepth[i] = object->audio[i].bitdepth; } if (audio_rate) { for (i = 0; i < 7; i ++) audio_rate[i] = object->audio[i].rate; } return 0; } /* Enable-disable switches */ char smk_enable_all(smk object, const unsigned char mask) { unsigned char i; /* null check */ if (object == NULL) { fputs("libsmacker::smk_enable_all() - ERROR: smk is NULL\n", stderr); return -1; } /* set video-enable */ object->video.enable = (mask & 0x80); for (i = 0; i < 7; i ++) { if (object->audio[i].exists) object->audio[i].enable = (mask & (1 << i)); } return 0; } char smk_enable_video(smk object, const unsigned char enable) { /* null check */ if (object == NULL) { fputs("libsmacker::smk_enable_video() - ERROR: smk is NULL\n", stderr); return -1; } object->video.enable = enable; return 0; } char smk_enable_audio(smk object, const unsigned char track, const unsigned char enable) { /* null check */ if (object == NULL) { fputs("libsmacker::smk_enable_audio() - ERROR: smk is NULL\n", stderr); return -1; } object->audio[track].enable = enable; return 0; } const unsigned char * smk_get_palette(const smk object) { /* null check */ if (object == NULL) { fputs("libsmacker::smk_get_palette() - ERROR: smk is NULL\n", stderr); return NULL; } return (unsigned char *)object->video.palette; } const unsigned char * smk_get_video(const smk object) { /* null check */ if (object == NULL) { fputs("libsmacker::smk_get_video() - ERROR: smk is NULL\n", stderr); return NULL; } return object->video.frame; } const unsigned char * smk_get_audio(const smk object, const unsigned char t) { /* null check */ if (object == NULL) { fputs("libsmacker::smk_get_audio() - ERROR: smk is NULL\n", stderr); return NULL; } return object->audio[t].buffer; } unsigned long smk_get_audio_size(const smk object, const unsigned char t) { /* null check */ if (object == NULL) { fputs("libsmacker::smk_get_audio_size() - ERROR: smk is NULL\n", stderr); return 0; } return object->audio[t].buffer_size; } /* Decompresses a palette-frame. */ static char smk_render_palette(struct smk_video_t * s, unsigned char * p, unsigned long size) { /* Index into palette */ unsigned short i = 0; /* Helper variables */ unsigned short count, src; static unsigned char oldPalette[256][3]; /* Smacker palette map: smk colors are 6-bit, this table expands them to 8. */ const unsigned char palmap[64] = { 0x00, 0x04, 0x08, 0x0C, 0x10, 0x14, 0x18, 0x1C, 0x20, 0x24, 0x28, 0x2C, 0x30, 0x34, 0x38, 0x3C, 0x41, 0x45, 0x49, 0x4D, 0x51, 0x55, 0x59, 0x5D, 0x61, 0x65, 0x69, 0x6D, 0x71, 0x75, 0x79, 0x7D, 0x82, 0x86, 0x8A, 0x8E, 0x92, 0x96, 0x9A, 0x9E, 0xA2, 0xA6, 0xAA, 0xAE, 0xB2, 0xB6, 0xBA, 0xBE, 0xC3, 0xC7, 0xCB, 0xCF, 0xD3, 0xD7, 0xDB, 0xDF, 0xE3, 0xE7, 0xEB, 0xEF, 0xF3, 0xF7, 0xFB, 0xFF }; /* null check */ assert(s); assert(p); /* Copy palette to old palette */ memcpy(oldPalette, s->palette, 256 * 3); /* Loop until palette is complete, or we are out of bytes to process */ while ((i < 256) && (size > 0)) { if ((*p) & 0x80) { /* 0x80: Skip block (preserve C+1 palette entries from previous palette) */ count = ((*p) & 0x7F) + 1; p ++; size --; /* check for overflow condition */ if (i + count > 256) { fprintf(stderr, "libsmacker::palette_render(s,p,size) - ERROR: overflow, 0x80 attempt to skip %d entries from %d\n", count, i); goto error; } /* finally: advance the index. */ i += count; } else if ((*p) & 0x40) { /* 0x40: Color-shift block Copy (c + 1) color entries of the previous palette, starting from entry (s), to the next entries of the new palette. */ if (size < 2) { fputs("libsmacker::palette_render(s,p,size) - ERROR: 0x40 ran out of bytes for copy\n", stderr); goto error; } /* pick "count" items to copy */ count = ((*p) & 0x3F) + 1; p ++; size --; /* start offset of old palette */ src = *p; p ++; size --; /* overflow: see if we write/read beyond 256colors, or overwrite own palette */ if (i + count > 256 || src + count > 256) { fprintf(stderr, "libsmacker::palette_render(s,p,size) - ERROR: overflow, 0x40 attempt to copy %d entries from %d to %d\n", count, src, i); goto error; } /* OK! Copy the color-palette entries. */ memmove(&s->palette[i][0], &oldPalette[src][0], count * 3); i += count; } else { /* 0x00: Set Color block Direct-set the next 3 bytes for palette index */ if (size < 3) { fprintf(stderr, "libsmacker::palette_render - ERROR: 0x3F ran out of bytes for copy, size=%lu\n", size); goto error; } for (count = 0; count < 3; count ++) { if (*p > 0x3F) { fprintf(stderr, "libsmacker::palette_render - ERROR: palette index exceeds 0x3F (entry [%u][%u])\n", i, count); goto error; } s->palette[i][count] = palmap[*p]; p++; size --; } i ++; } } if (i < 256) { fprintf(stderr, "libsmacker::palette_render - ERROR: did not completely fill palette (idx=%u)\n", i); goto error; } return 0; error: /* Error, return -1 The new palette probably has errors but is preferrable to a black screen */ return -1; } static char smk_render_video(struct smk_video_t * s, unsigned char * p, unsigned int size) { unsigned char * t = s->frame; unsigned char s1, s2; unsigned short temp; unsigned long i, j, k, row, col, skip; /* used for video decoding */ struct smk_bit_t bs; /* results from a tree lookup */ int unpack; /* unpack, broken into pieces */ unsigned char type; unsigned char blocklen; unsigned char typedata; char bit; const unsigned short sizetable[64] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 128, 256, 512, 1024, 2048 }; /* null check */ assert(s); assert(p); row = 0; col = 0; /* Set up a bitstream for video unpacking */ smk_bs_init(&bs, p, size); /* Reset the cache on all bigtrees */ for (i = 0; i < 4; i++) memset(&s->tree[i].cache, 0, 3 * sizeof(unsigned short)); while (row < s->h) { if ((unpack = smk_huff16_lookup(&s->tree[SMK_TREE_TYPE], &bs)) < 0) { fputs("libsmacker::smk_render_video() - ERROR: failed to lookup from TYPE tree.\n", stderr); return -1; } type = ((unpack & 0x0003)); blocklen = ((unpack & 0x00FC) >> 2); typedata = ((unpack & 0xFF00) >> 8); /* support for v4 full-blocks */ if (type == 1 && s->v == '4') { bit = smk_bs_read_1(&bs); if (bit) type = 4; else { bit = smk_bs_read_1(&bs); if (bit) type = 5; } } for (j = 0; (j < sizetable[blocklen]) && (row < s->h); j ++) { skip = (row * s->w) + col; switch (type) { case 0: if ((unpack = smk_huff16_lookup(&s->tree[SMK_TREE_MCLR], &bs)) < 0) { fputs("libsmacker::smk_render_video() - ERROR: failed to lookup from MCLR tree.\n", stderr); return -1; } s1 = (unpack & 0xFF00) >> 8; s2 = (unpack & 0x00FF); if ((unpack = smk_huff16_lookup(&s->tree[SMK_TREE_MMAP], &bs)) < 0) { fputs("libsmacker::smk_render_video() - ERROR: failed to lookup from MMAP tree.\n", stderr); return -1; } temp = 0x01; for (k = 0; k < 4; k ++) { for (i = 0; i < 4; i ++) { if (unpack & temp) t[skip + i] = s1; else t[skip + i] = s2; temp = temp << 1; } skip += s->w; } break; case 1: /* FULL BLOCK */ for (k = 0; k < 4; k ++) { if ((unpack = smk_huff16_lookup(&s->tree[SMK_TREE_FULL], &bs)) < 0) { fputs("libsmacker::smk_render_video() - ERROR: failed to lookup from FULL tree.\n", stderr); return -1; } t[skip + 3] = ((unpack & 0xFF00) >> 8); t[skip + 2] = (unpack & 0x00FF); if ((unpack = smk_huff16_lookup(&s->tree[SMK_TREE_FULL], &bs)) < 0) { fputs("libsmacker::smk_render_video() - ERROR: failed to lookup from FULL tree.\n", stderr); return -1; } t[skip + 1] = ((unpack & 0xFF00) >> 8); t[skip] = (unpack & 0x00FF); skip += s->w; } break; case 2: /* VOID BLOCK */ /* break; if (s->frame) { memcpy(&t[skip], &s->frame[skip], 4); skip += s->w; memcpy(&t[skip], &s->frame[skip], 4); skip += s->w; memcpy(&t[skip], &s->frame[skip], 4); skip += s->w; memcpy(&t[skip], &s->frame[skip], 4); } */ break; case 3: /* SOLID BLOCK */ memset(&t[skip], typedata, 4); skip += s->w; memset(&t[skip], typedata, 4); skip += s->w; memset(&t[skip], typedata, 4); skip += s->w; memset(&t[skip], typedata, 4); break; case 4: /* V4 DOUBLE BLOCK */ for (k = 0; k < 2; k ++) { if ((unpack = smk_huff16_lookup(&s->tree[SMK_TREE_FULL], &bs)) < 0) { fputs("libsmacker::smk_render_video() - ERROR: failed to lookup from FULL tree.\n", stderr); return -1; } for (i = 0; i < 2; i ++) { memset(&t[skip + 2], (unpack & 0xFF00) >> 8, 2); memset(&t[skip], (unpack & 0x00FF), 2); skip += s->w; } } break; case 5: /* V4 HALF BLOCK */ for (k = 0; k < 2; k ++) { if ((unpack = smk_huff16_lookup(&s->tree[SMK_TREE_FULL], &bs)) < 0) { fputs("libsmacker::smk_render_video() - ERROR: failed to lookup from FULL tree.\n", stderr); return -1; } t[skip + 3] = ((unpack & 0xFF00) >> 8); t[skip + 2] = (unpack & 0x00FF); t[skip + s->w + 3] = ((unpack & 0xFF00) >> 8); t[skip + s->w + 2] = (unpack & 0x00FF); if ((unpack = smk_huff16_lookup(&s->tree[SMK_TREE_FULL], &bs)) < 0) { fputs("libsmacker::smk_render_video() - ERROR: failed to lookup from FULL tree.\n", stderr); return -1; } t[skip + 1] = ((unpack & 0xFF00) >> 8); t[skip] = (unpack & 0x00FF); t[skip + s->w + 1] = ((unpack & 0xFF00) >> 8); t[skip + s->w] = (unpack & 0x00FF); skip += (s->w << 1); } break; } col += 4; if (col >= s->w) { col = 0; row += 4; } } } return 0; } /* Decompress audio track i. */ static char smk_render_audio(struct smk_audio_t * s, unsigned char * p, unsigned long size) { unsigned int j, k; unsigned char * t = s->buffer; struct smk_bit_t bs; char bit; short unpack, unpack2; /* used for audio decoding */ struct smk_huff8_t aud_tree[4]; /* null check */ assert(s); assert(p); if (!s->compress) { /* Raw PCM data, update buffer size and perform copy */ s->buffer_size = size; memcpy(t, p, size); } else if (s->compress == 1) { /* SMACKER DPCM compression */ /* need at least 4 bytes to process */ if (size < 4) { fputs("libsmacker::smk_render_audio() - ERROR: need 4 bytes to get unpacked output buffer size.\n", stderr); goto error; } /* chunk is compressed (huff-compressed dpcm), retrieve unpacked buffer size */ s->buffer_size = ((unsigned int) p[3] << 24) | ((unsigned int) p[2] << 16) | ((unsigned int) p[1] << 8) | ((unsigned int) p[0]); p += 4; size -= 4; /* Compressed audio: must unpack here */ /* Set up a bitstream */ smk_bs_init(&bs, p, size); bit = smk_bs_read_1(&bs); if (!bit) { fputs("libsmacker::smk_render_audio - ERROR: initial get_bit returned 0\n", stderr); goto error; } bit = smk_bs_read_1(&bs); if (s->channels != (bit == 1 ? 2 : 1)) fputs("libsmacker::smk_render - ERROR: mono/stereo mismatch\n", stderr); bit = smk_bs_read_1(&bs); if (s->bitdepth != (bit == 1 ? 16 : 8)) fputs("libsmacker::smk_render - ERROR: 8-/16-bit mismatch\n", stderr); /* build the trees */ smk_huff8_build(&aud_tree[0], &bs); j = 1; k = 1; if (s->bitdepth == 16) { smk_huff8_build(&aud_tree[1], &bs); k = 2; } if (s->channels == 2) { smk_huff8_build(&aud_tree[2], &bs); j = 2; k = 2; if (s->bitdepth == 16) { smk_huff8_build(&aud_tree[3], &bs); k = 4; } } /* read initial sound level */ if (s->channels == 2) { unpack = smk_bs_read_8(&bs); if (s->bitdepth == 16) { ((short *)t)[1] = smk_bs_read_8(&bs); ((short *)t)[1] |= (unpack << 8); } else ((unsigned char *)t)[1] = (unsigned char)unpack; } unpack = smk_bs_read_8(&bs); if (s->bitdepth == 16) { ((short *)t)[0] = smk_bs_read_8(&bs); ((short *)t)[0] |= (unpack << 8); } else ((unsigned char *)t)[0] = (unsigned char)unpack; /* All set: let's read some DATA! */ while (k < s->buffer_size) { if (s->bitdepth == 8) { unpack = smk_huff8_lookup(&aud_tree[0], &bs); ((unsigned char *)t)[j] = (char)unpack + ((unsigned char *)t)[j - s->channels]; j ++; k++; } else { unpack = smk_huff8_lookup(&aud_tree[0], &bs); unpack2 = smk_huff8_lookup(&aud_tree[1], &bs); ((short *)t)[j] = (short)(unpack | (unpack2 << 8)) + ((short *)t)[j - s->channels]; j ++; k += 2; } if (s->channels == 2) { if (s->bitdepth == 8) { unpack = smk_huff8_lookup(&aud_tree[2], &bs); ((unsigned char *)t)[j] = (char)unpack + ((unsigned char *)t)[j - 2]; j ++; k++; } else { unpack = smk_huff8_lookup(&aud_tree[2], &bs); unpack2 = smk_huff8_lookup(&aud_tree[3], &bs); ((short *)t)[j] = (short)(unpack | (unpack2 << 8)) + ((short *)t)[j - 2]; j ++; k += 2; } } } } return 0; error: return -1; } /* "Renders" (unpacks) the frame at cur_frame Preps all the image and audio pointers */ static char smk_render(smk s) { unsigned long i, size; unsigned char * buffer = NULL, * p, track; /* null check */ assert(s); /* Retrieve current chunk_size for this frame. */ if (!(i = s->chunk_size[s->cur_frame])) { fprintf(stderr, "libsmacker::smk_render(s) - Warning: frame %lu: chunk_size is 0.\n", s->cur_frame); goto error; } if (s->mode == SMK_MODE_DISK) { /* Skip to frame in file */ if (fseek(s->source.file.fp, s->source.file.chunk_offset[s->cur_frame], SEEK_SET)) { fprintf(stderr, "libsmacker::smk_render(s) - ERROR: fseek to frame %lu (offset %lu) failed.\n", s->cur_frame, s->source.file.chunk_offset[s->cur_frame]); perror("\tError reported was"); goto error; } /* In disk-streaming mode: make way for our incoming chunk buffer */ if ((buffer = malloc(i)) == NULL) { perror("libsmacker::smk_render() - ERROR: failed to malloc() buffer"); return -1; } /* Read into buffer */ if (smk_read_file(buffer, s->chunk_size[s->cur_frame], s->source.file.fp) < 0) { fprintf(stderr, "libsmacker::smk_render(s) - ERROR: frame %lu (offset %lu): smk_read had errors.\n", s->cur_frame, s->source.file.chunk_offset[s->cur_frame]); goto error; } } else { /* Just point buffer at the right place */ if (!s->source.chunk_data[s->cur_frame]) { fprintf(stderr, "libsmacker::smk_render(s) - ERROR: frame %lu: memory chunk is a NULL pointer.\n", s->cur_frame); goto error; } buffer = s->source.chunk_data[s->cur_frame]; } p = buffer; /* Palette record first */ if (s->frame_type[s->cur_frame] & 0x01) { /* need at least 1 byte to process */ if (!i) { fprintf(stderr, "libsmacker::smk_render(s) - ERROR: frame %lu: insufficient data for a palette rec.\n", s->cur_frame); goto error; } /* Byte 1 in block, times 4, tells how many subsequent bytes are present */ size = 4 * (*p); /* If video rendering enabled, kick this off for decode. */ if (s->video.enable) smk_render_palette(&(s->video), p + 1, size - 1); p += size; i -= size; } /* Unpack audio chunks */ for (track = 0; track < 7; track ++) { if (s->frame_type[s->cur_frame] & (0x02 << track)) { /* need at least 4 byte to process */ if (i < 4) { fprintf(stderr, "libsmacker::smk_render(s) - ERROR: frame %lu: insufficient data for audio[%u] rec.\n", s->cur_frame, track); goto error; } /* First 4 bytes in block tell how many subsequent bytes are present */ size = (((unsigned int) p[3] << 24) | ((unsigned int) p[2] << 16) | ((unsigned int) p[1] << 8) | ((unsigned int) p[0])); /* If audio rendering enabled, kick this off for decode. */ if (s->audio[track].enable) smk_render_audio(&s->audio[track], p + 4, size - 4); p += size; i -= size; } else s->audio[track].buffer_size = 0; } /* Unpack video chunk */ if (s->video.enable) { if (smk_render_video(&(s->video), p, i) < 0) { fprintf(stderr, "libsmacker::smk_render(s) - ERROR: frame %lu: failed to render video.\n", s->cur_frame); goto error; } } if (s->mode == SMK_MODE_DISK) { /* Remember that buffer we allocated? Trash it */ smk_free(buffer); } return 0; error: if (s->mode == SMK_MODE_DISK) { /* Remember that buffer we allocated? Trash it */ smk_free(buffer); } return -1; } /* rewind to first frame and unpack */ char smk_first(smk s) { /* null check */ if (s == NULL) { fputs("libsmacker::smk_first() - ERROR: smk is NULL\n", stderr); return -1; } s->cur_frame = 0; if (smk_render(s) < 0) { fprintf(stderr, "libsmacker::smk_first(s) - Warning: frame %lu: smk_render returned errors.\n", s->cur_frame); return -1; } if (s->f == 1) return SMK_LAST; return SMK_MORE; } /* advance to next frame */ char smk_next(smk s) { /* null check */ if (s == NULL) { fputs("libsmacker::smk_next() - ERROR: smk is NULL\n", stderr); return -1; } if (s->cur_frame + 1 < (s->f + s->ring_frame)) { s->cur_frame ++; if (smk_render(s) < 0) { fprintf(stderr, "libsmacker::smk_next(s) - Warning: frame %lu: smk_render returned errors.\n", s->cur_frame); return -1; } if (s->cur_frame + 1 == (s->f + s->ring_frame)) return SMK_LAST; return SMK_MORE; } else if (s->ring_frame) { s->cur_frame = 1; if (smk_render(s) < 0) { fprintf(stderr, "libsmacker::smk_next(s) - Warning: frame %lu: smk_render returned errors.\n", s->cur_frame); return -1; } if (s->cur_frame + 1 == (s->f + s->ring_frame)) return SMK_LAST; return SMK_MORE; } return SMK_DONE; } /* seek to a keyframe in an smk */ char smk_seek_keyframe(smk s, unsigned long f) { /* null check */ if (s == NULL) { fputs("libsmacker::smk_seek_keyframe() - ERROR: smk is NULL\n", stderr); return -1; } /* rewind (or fast forward!) exactly to f */ s->cur_frame = f; /* roll back to previous keyframe in stream, or 0 if no keyframes exist */ while (s->cur_frame > 0 && !(s->keyframe[s->cur_frame])) s->cur_frame --; /* render the frame: we're ready */ if (smk_render(s) < 0) { fprintf(stderr, "libsmacker::smk_seek_keyframe(s,%lu) - Warning: frame %lu: smk_render returned errors.\n", f, s->cur_frame); return -1; } return 0; } unsigned char smk_palette_updated(smk s) { return s->frame_type[s->cur_frame] & 0x01; }
C
struct node { int info; struct node *next; }; struct node *create(struct node *head) { struct node *p=NULL,*temp=NULL; int i,n; printf("How many values\n"); scanf("%d",&n); temp=head; printf("Enter the actual value\n"); for(i=0;i<n;i++) { p=((struct node *)malloc(sizeof(struct node))); scanf("%d",&p->info); p->next=NULL; temp->next=p; temp=p; } return(head); } void display(struct node *head) { struct node *temp=NULL; temp=head->next; do { printf("%d\t",temp->info); temp=temp->next; }while(temp!=NULL); } struct node *insert(struct node *head) { struct node *p=NULL,*temp=NULL; int i,pos; printf("\n Enter the posion"); scanf("%d",&pos); for(temp=head,i=1;i<pos&&temp!=NULL;i++) { temp=temp->next; } if(temp!=NULL) { p=((struct node *)malloc(sizeof(struct node))); printf("Enter the value\n"); scanf("%d",&p->info); p->next=NULL; p->next=temp->next; temp->next=p; } else { printf("position out of order\n"); } return(head); } struct node *delete(struct node *head) { struct node *temp=NULL,*p=NULL; int i,pos; printf("Enter the position of element is to be delete\n"); scanf("%d",&pos); for(temp=head,i=1;i<pos&&temp->next!=NULL;i++) { temp=temp->next; } if(temp->next!=NULL) { p=temp->next; temp->next=p->next; printf("The deleted element is %d\n",p->info); free(p); } else { printf("position out of order\n"); } return(head); } int search(struct node *head,int key) { struct node *temp=NULL; int i; for(temp=head->next,i=1;temp->next!=NULL;temp=temp->next,i++) { if(temp->info==key) return (i); return (-1); } }
C
#include <stdio.h> int main(){ int n,count=0; int p=789456; scanf("%d",&n); int c[n]; for(int i=0;i<n;i++){ scanf("%d",&c[i]); } for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { if(c[i]==c[j]) { count++; c[j]=p; p++; break; } } } printf("%d",count); return 0; }
C
/*********************************************************************** ** ** REBOL [R3] Language Interpreter and Run-time Environment ** ** Copyright 2014 Atronix Engineering, Inc ** REBOL is a trademark of REBOL Technologies ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ************************************************************************ ** ** Module: f-int.c ** Summary: integer arithmetic functions ** Section: functional ** Author: Shixin Zeng ** Notes: Based on original code in t-integer.c ** ***********************************************************************/ #include "reb-c.h" #include "sys-int-funcs.h" REBOOL reb_i32_add_overflow(i32 x, i32 y, i32 *sum) { i64 sum64 = (i64)x + (i64)y; if (sum64 > MAX_I32 || sum64 < MIN_I32) return TRUE; *sum = (i32)sum64; return FALSE; } REBOOL reb_u32_add_overflow(u32 x, u32 y, u32 *sum) { u64 s = (u64)x + (u64)y; if (s > MAX_I32) return TRUE; *sum = (u32)s; return FALSE; } REBOOL reb_i64_add_overflow(i64 x, i64 y, i64 *sum) { *sum = (REBU64)x + (REBU64)y; /* never overflow with unsigned integers*/ if (((x < 0) == (y < 0)) && ((x < 0) != (*sum < 0))) return TRUE; return FALSE; } REBOOL reb_u64_add_overflow(u64 x, u64 y, u64 *sum) { *sum = x + y; if (*sum < x || *sum < y) return TRUE; return FALSE; } REBOOL reb_i32_sub_overflow(i32 x, i32 y, i32 *diff) { *diff = (i64)x - (i64)y; if (((x < 0) != (y < 0)) && ((x < 0) != (*diff < 0))) return TRUE; return FALSE; } REBOOL reb_i64_sub_overflow(i64 x, i64 y, i64 *diff) { *diff = (REBU64)x - (REBU64)y; if (((x < 0) != (y < 0)) && ((x < 0) != (*diff < 0))) return TRUE; return FALSE; } REBOOL reb_i32_mul_overflow(i32 x, i32 y, i32 *prod) { i64 p = (i64)x * (i64)y; if (p > MAX_I32 || p < MIN_I32) return TRUE; *prod = (i32)p; return FALSE; } REBOOL reb_u32_mul_overflow(u32 x, u32 y, u32 *prod) { u64 p = (u64)x * (u64)y; if (p > MAX_U32) return TRUE; *prod = (u32)p; return FALSE; } REBOOL reb_i64_mul_overflow(i64 x, i64 y, i64 *prod) { REBFLG sgn; u64 p = 0; if (y == 0 || x == 0) { *prod = 0; return FALSE; } sgn = (x < 0); if (sgn) { if (x == MIN_I64) { switch (y) { case 1: *prod = x; return 0; default: return 1; } } x = -x; /* undefined when x == MIN_I64 */ } if (y < 0) { sgn = !sgn; if (y == MIN_I64) { switch (x) { case 1: if (!sgn) { return 1; } else { *prod = y; return 0; } default: return 1; } } y = -y; /* undefined when y == MIN_I64 */ } if (REB_U64_MUL_OF(x, y, (u64 *)&p) || (!sgn && p > MAX_I64) || (sgn && p - 1 > MAX_I64)) return TRUE; /* assumes 2's complements */ if (sgn && p == (u64)MIN_I64) { *prod = MIN_I64; return FALSE; } *prod = sgn? -(i64)p : p; return FALSE; } REBOOL reb_u64_mul_overflow(u64 x, u64 y, u64 *prod) { u64 x0, y0, x1, y1; u64 b = U64_C(1) << 32; u64 tmp = 0; x1 = x >> 32; x0 = (u32)x; y1 = y >> 32; y0 = (u32)y; /* p = (x1 * y1) * b^2 + (x0 * y1 + x1 * y0) * b + x0 * y0 */ if (x1 && y1) return TRUE; /* (x1 * y1) * b^2 overflows */ tmp = (x0 * y1 + x1 * y0); /* never overflow, because x1 * y1 == 0 */ if (tmp >= b) return TRUE; /*(x0 * y1 + x1 * y0) * b overflows */ return REB_U64_ADD_OF(tmp << 32, x0 * y0, prod); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #define MAX_String 1024 int My_strlen (const char* str) { int size = sizeof(*str); const char* temp = str; while ((*str != '\0') && (*str != '\n')) { str++; } return ((str - temp)/size); } char* My_strncpy(char* dest, const char* str, int size) { int i = 0; for (i = 0; i < size && str[i] != '\0'; i++) dest[i] = str[i]; for (;i <= size; i++) dest[i] = '\0'; return dest; } char* My_strncat(char *dest, const char *src, int n) { int dest_len = My_strlen(dest); int i = 0; for (i = 0 ; i < n && src[i] != '\0' ; i++) dest[dest_len + i] = src[i]; dest[dest_len + i] = '\0'; return dest; } const char* My_strstr(const char* str, const char* find) { const char* f = &(*str); int i = 0, j = 0, n = My_strlen(find); for(; str[i] != '\0'; i++) { for(j = 0; str[i+j] == find[j] && j < n; j++) { } if (j == n) return f + i; } return 0; } int main() { char str1[MAX_String], str2[MAX_String]; int size = 0; fgets (str1, sizeof(str1)-1, stdin); printf("strlen = %d\n",size = My_strlen(str1)); My_strncpy(str2, str1, size); printf("strncpy = %s\n", str2); My_strncat(str2, str1, size); printf("strncat = %s\n",str2); printf("strstr = %p\n", My_strstr(str2, str1)); return 0; }
C
/* ---------------------------------------------------------------------------- FILE: lcdlib.c PROJECT: pinguino32 PURPOSE: LCD routines for use with pinguino 32X board Based on LiquidCrystal lib from Arduino project. PROGRAMER: Port by Marcus Fazzi ([email protected]) FIRST RELEASE: 30 May 2011 Updated: 05 Mar 2012 - Marcus Fazzi Changed function lcd to _lcd_pins & prefixed all other function names with _lcd_ Updated: 29 Apr 2012 - R. Blanchot Changed _lcd_begin() to get same syntax as Arduino's lib. Changed variable types unsigned char and unsigned long to Pinguino types u8 and u16 respectively and added #include <typedef.h> Updated: 01 May 2012 - M Harper Changed to deal more consistently with single line displays (changes identified by dated comments in code) Updated: 26 May 2012 - M Harper Reverted _lcd_begin() to syntax prior to x.3 r359 29 Apr 2012 for consistency with P8 and fix broken LCD examples ---------------------------------------------------------------------------- LiquidCrystal original Arduino site: http://www.arduino.cc/en/Tutorial/LiquidCrystal by David A. Mellis Pins, Schematics and more info: http://pinguino.koocotte.org/index.php/LCD_Example http://www.fazzi.eng.br */ #ifndef __LCDLIB_C__ #define __LCDLIB_C__ #include <delay.c> // Arduino like delays #include <digitalw.c> // Arduino like DigitalWrite and Read #include <typedef.h> // Pinguino's types (u8, u16, ...) 01 May 2012 #include <printf.c> // Pinguino printf (low footprint) #include <stdarg.h> // Variable Arguments #ifndef __LCDLIB_H__ #include <lcdlib.h> #endif /** Positive pulse on E */ void _lcd_pulseEnable(void) { digitalwrite(_enable_pin, LOW); Delayus(1); digitalwrite(_enable_pin, HIGH); Delayus(1); // enable pulse must be >450ns digitalwrite(_enable_pin, LOW); Delayus(50); // commands need > 37us to settle } /** Write using 4bits mode */ void _lcd_write4bits(u8 value) { int i; for (i = 0; i < 4; i++) { digitalwrite(_data_pins[i], (value >> i) & 0x01); } _lcd_pulseEnable(); } /** Write using 8bits mode */ void _lcd_write8bits(u8 value) { int i; for (i = 0; i < 8; i++) { digitalwrite(_data_pins[i], (value >> i) & 0x01); } _lcd_pulseEnable(); } /** Send data to LCD 8 or 4 bits */ void _lcd_send(u8 value, u8 mode) { digitalwrite(_rs_pin, mode); if (_displayfunction & LCD_8BITMODE) { _lcd_write8bits(value); } else { _lcd_write4bits(value>>4); _lcd_write4bits(value); } } /** Write a data character on LCD */ void _lcd_write(u8 value) { _lcd_send(value, HIGH); } /** Write a control command on LCD */ void _lcd_command(u8 value) { _lcd_send(value, LOW); } /** Setup line x column on LCD */ void _lcd_setCursor(u8 col, u8 row) { int row_offsets[] = { 0x00, 0x40, 0x14, 0x54 }; /* Added 01 May 2012 by MFH sets row_offsets for a single line display so that 80 column space divided in 4 equal 20 column sections. This means that if an n x 4 display is set to behave as a single line display lines 1 and 2 are displayed and lines 3 and 4 are 20 characters to the right.*/ if (_numlines==1) { row_offsets[1] = 0x14; row_offsets[2] = 0x28; row_offsets[3] = 0x3C; } /* Removed 01 May 2012 by MFH as did not treat row starts consistently for n x 2 and n x 4 displays if ( row > _numlines ) { row = _numlines-1; // we count rows starting w/0 } */ _lcd_command(LCD_SETDDRAMADDR | (col + row_offsets[row])); } /** Print a string on LCD */ void _lcd_print(char *string) { int i; for( i=0; string[i]; i++) { _lcd_write(string[i]); } } /** Write formated string on LCD **/ // added 23/02/2011 [email protected] void _lcd_printf(char *fmt, ...) { va_list args; va_start(args, fmt); pprintf(_lcd_write, fmt, args); va_end(args); } /** Print a number on LCD */ void _lcd_printNumber(u32 n, u8 base) { u8 buf[8 * sizeof(long)]; // Assumes 8-bit chars. u32 i = 0; if (n == 0) { _lcd_write('0'); return; } while (n > 0) { buf[i++] = n % base; n /= base; } for (; i > 0; i--) _lcd_write((char) (buf[i - 1] < 10 ? '0' + buf[i - 1] : 'A' + buf[i - 1] - 10)); } /** Print a float number to LCD */ void _lcd_printFloat(float number, u8 digits) { u8 i, toPrint; u32 int_part; float rounding, remainder; // Handle negative numbers if (number < 0.0) { _lcd_write('-'); number = -number; } // Round correctly so that print(1.999, 2) prints as "2.00" rounding = 0.5; for (i=0; i<digits; ++i) rounding /= 10.0; number += rounding; // Extract the integer part of the number and print it int_part = (u32)number; remainder = number - (float)int_part; _lcd_printNumber(int_part, 10); // Print the decimal point, but only if there are digits beyond if (digits > 0) _lcd_write('.'); // Extract digits from the remainder one at a time while (digits-- > 0) { remainder *= 10.0; toPrint = (u16)remainder; //Integer part without use of math.h lib, //I think better! (Fazzi) _lcd_printNumber(toPrint, 10); remainder -= toPrint; } } /** Move cursor to Home position */ void _lcd_home(){ _lcd_command(LCD_RETURNHOME); Delayus(2000); } /** Clear LCD */ void _lcd_clear() { _lcd_command(LCD_CLEARDISPLAY); // clear display, set cursor position to zero Delayus(2000); // this command takes a long time! } /** Turn the display on/off (quickly) */ void _lcd_noDisplay() { _displaycontrol &= ~LCD_DISPLAYON; _lcd_command(LCD_DISPLAYCONTROL | _displaycontrol); } void _lcd_display() { _displaycontrol |= LCD_DISPLAYON; _lcd_command(LCD_DISPLAYCONTROL | _displaycontrol); } /** Turns the underline cursor on/off */ void _lcd_noCursor() { _displaycontrol &= ~LCD_CURSORON; _lcd_command(LCD_DISPLAYCONTROL | _displaycontrol); } void _lcd_cursor() { _displaycontrol |= LCD_CURSORON; _lcd_command(LCD_DISPLAYCONTROL | _displaycontrol); } /** Turn on and off the blinking cursor */ void _lcd_noBlink() { _displaycontrol &= ~LCD_BLINKON; _lcd_command(LCD_DISPLAYCONTROL | _displaycontrol); } void _lcd_blink() { _displaycontrol |= LCD_BLINKON; _lcd_command(LCD_DISPLAYCONTROL | _displaycontrol); } /** These commands scroll the display without changing the RAM */ void _lcd_scrollDisplayLeft(void) { _lcd_command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT); } void _lcd_scrollDisplayRight(void) { _lcd_command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT); } /** This is for text that flows Left to Right */ void _lcd_leftToRight(void) { _displaymode |= LCD_ENTRYLEFT; _lcd_command(LCD_ENTRYMODESET | _displaymode); } /** This is for text that flows Right to Left */ void _lcd_rightToLeft(void) { _displaymode &= ~LCD_ENTRYLEFT; _lcd_command(LCD_ENTRYMODESET | _displaymode); } /** This will 'right justify' text from the cursor */ void _lcd_autoscroll(void) { _displaymode |= LCD_ENTRYSHIFTINCREMENT; _lcd_command(LCD_ENTRYMODESET | _displaymode); } /** This will 'left justify' text from the cursor */ void _lcd_noAutoscroll(void) { _displaymode &= ~LCD_ENTRYSHIFTINCREMENT; _lcd_command(LCD_ENTRYMODESET | _displaymode); } /** Initial Display settings! */ void _lcd_begin(u8 lines, u8 dotsize) { if (lines > 1) { _displayfunction |= LCD_2LINE; } _numlines = lines; _currline = 0; // Some one line displays can select 10 pixel high font if ((dotsize != 0) && (lines == 1)) { _displayfunction |= LCD_5x10DOTS; } Delayus(15); //Pinguino needs it? long delay on startup time! // Now we pull both RS and R/W low to begin commands digitalwrite(_rs_pin, LOW); digitalwrite(_enable_pin, LOW); //put the LCD into 4 bit or 8 bit mode if (! (_displayfunction & LCD_8BITMODE)) { // this is according to the hitachi HD44780 datasheet // figure 24, pg 46 // we start in 8bit mode, try to set 4 bit mode _lcd_write4bits(0x03); Delayus(4500); // wait min 4.1ms // second try _lcd_write4bits(0x03); Delayus(4500); // wait min 4.1ms // third go! _lcd_write4bits(0x03); Delayus(150); // finally, set to 8-bit interface _lcd_write4bits(0x02); } else { // this is according to the hitachi HD44780 datasheet // page 45 figure 23 // Send function set command sequence _lcd_command(LCD_FUNCTIONSET | _displayfunction); Delayus(4500); // wait more than 4.1ms // second try _lcd_command(LCD_FUNCTIONSET | _displayfunction); Delayus(150); // third go _lcd_command(LCD_FUNCTIONSET | _displayfunction); } // finally, set # lines, font size, etc. _lcd_command(LCD_FUNCTIONSET | _displayfunction); // turn the display on with no cursor or blinking default _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF; _lcd_display(); // clear it off _lcd_clear(); // Initialize to default text direction (for romance languages) _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT; // set the entry mode _lcd_command(LCD_ENTRYMODESET | _displaymode); } /** Init LCD * mode => 1 => 4 bits // 0 => 8 bits * rs , rw, enable * pins => D0 ~ D7. */ void _lcd_init(u8 fourbitmode, u8 rs, u8 rw, u8 enable, u8 d0, u8 d1, u8 d2, u8 d3, u8 d4, u8 d5, u8 d6, u8 d7){ int i; _rs_pin = rs; _rw_pin = rw; _enable_pin = enable; _data_pins[0] = d0; _data_pins[1] = d1; _data_pins[2] = d2; _data_pins[3] = d3; _data_pins[4] = d4; _data_pins[5] = d5; _data_pins[6] = d6; _data_pins[7] = d7; pinmode(_rs_pin, OUTPUT); pinmode(_enable_pin, OUTPUT); if (fourbitmode){ _displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_5x8DOTS; for (i = 0; i < 4; i++) { pinmode(_data_pins[i], OUTPUT); } } else { _displayfunction = LCD_8BITMODE | LCD_1LINE | LCD_5x8DOTS; for (i = 0; i < 8; i++) { pinmode(_data_pins[i], OUTPUT); } } } /** LCD 8 bits mode */ void _lcd_pins(u8 rs, u8 enable, u8 d0, u8 d1, u8 d2, u8 d3, u8 d4, u8 d5, u8 d6, u8 d7) { _lcd_init(((d4 + d5 + d6 + d7)==0), rs, 99, enable, d0, d1, d2, d3, d4, d5, d6, d7); } #endif
C
#include <stdio.h> #include <string.h> #include <ctype.h> #include <math.h> #include <cs50.h> int main(void) { int count = 0; int words = 1; int sentences = 0; //Prompt for text input string text = get_string("Text: "); // caclculate and print text length for (int i = 0, len = strlen(text); i <= len; i++) { char c = text[i]; //check for letters if (isalpha(c)) { count++; } //check for words if (isspace(c)) { words++; } //check for sentences if (c == '.' || c == '?' || c == '!') { sentences++; } } //Calculating Coleman-Liau index float L = (count * 100.0f) / words; float S = (sentences * 100.0f) / words; int index = round(0.0588 * L - 0.296 * S - 15.8); //scoring based on the index if (index < 1) { printf("Before Grade 1\n"); } else if (index >= 16) { printf("Grade 16+\n"); } else { printf("Grade %d\n", index); } //Test cases // printf("Letters: %i \n", count); // printf("Words: %i \n", words); // printf("Sentences: %i \n", sentences); // printf("Index: %i \n", index); return 0; }
C
#include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include "unity.h" #include "Token.h" #include "Error.h" #include "read_file.h" #include "Tokenizer.h" #include "Exception.h" #include "getStrToken.h" #include "linkedList.h" #include "handlePinMappingDesc.h" #include "handlePortDescription.h" #include "createAndGetTokenFromFile.h" #include "handleScanPortIdentification.h" #include "handleBoundaryRegisterDesc.h" void printBoundaryRegister(LinkedList *list){ Item *current; boundaryRegister *bs; current=list->head; if(current == NULL){ Token *token; token = createNullToken(0,NULL); throwException(ERR_PRINTING_BOUNDARY_REGISTER,token,"Boundary register is empty!!"); } while(current != NULL){ bs = ((boundaryRegister*)current->data); printf("%s ( %s, %s, %s, %s", bs->cellNumber,bs->cellName,bs->portId,bs->function,bs->safeBit); if(strlen(bs->ccell) > 0){ printf(", %s", bs->ccell); } if(strlen(bs->disval) > 0){ printf(", %s, %s",bs->disval,bs->disres ); } current=current->next; if(current == NULL){ printf(""); }else{ printf("),\n"); } } printf(");\n" ); } // input : bsinfo, fileTokenizer void handleBoundaryRegisterD(BSinfo *bsinfo, FileTokenizer *fileTokenizer){ Token *token; int i = 0; char *arr[5] = {"of",bsinfo->modelName,":","entity","is",}; int tokenType[5] = {8,8,4,8,8}; //compare all the string, throw error if fail while(i < 5){ token = getTokenFromFile(fileTokenizer); if(tokenType[i] == token->type){ if(strcmp(arr[i],token->str) != 0){ //string compare...if not same, throw error throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect %s but is %s",getCorrectReadLineNo(fileTokenizer->readLineNo,token),arr[i],token->str); } }else{ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect %s but is not",getCorrectReadLineNo(fileTokenizer->readLineNo,token),arr[i]); } i++; freeToken(token); } //check for NULL and comment line, if it is not then throw error token = getTokenFromFile(fileTokenizer); if(token->type != TOKEN_NULL_TYPE && token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect Null or CommentLine but is %s.",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else if(token->type == TOKEN_OPERATOR_TYPE){ if(strcmp("-",token->str) == 0){ checkAndSkipCommentLine(fileTokenizer); }else{ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Invalid comment line!!",getCorrectReadLineNo(fileTokenizer->readLineNo,token)); } } freeToken(token); handleBoundaryRegister(fileTokenizer,bsinfo->boundaryReg); } void handleBoundaryRegister(FileTokenizer *fileTokenizer, LinkedList *list){ Token *token; char *cellNumber,*cellName,*portId,*function,*safeBit,*ccell, *disval,*disres; int intFlag = 0; while(1){ intFlag = 0; token = getStringToken(fileTokenizer); // get the cellNumber if(token->type != TOKEN_INTEGER_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect integer but is %s\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else{ cellNumber = (char *)malloc(strlen(token->str)); strcpy(cellNumber,(token->str)); } // check for '(' symbol freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d .Expect '(' symbol but is %s\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else{ if(strcmp("(",token->str) != 0){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d .Expect '(' symbol but is %s\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } } // get the cellName freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_IDENTIFIER_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. %s is not a valid Cell Name\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else{ cellName = (char *)malloc(strlen(token->str)); strcpy(cellName,(token->str)); } // check "," symbol freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else{ if(strcmp(",",token->str) != 0){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } } // get portId portId = getPortId(fileTokenizer); // check "," symbol freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else{ if(strcmp(",",token->str) != 0){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } } // get the function freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_IDENTIFIER_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. %s is not a valid Function Name\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else{ if(checkFunctionName(token->str) != 1){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. %s is not a valid Function Name\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } function = (char *)malloc(strlen(token->str)); strcpy(function,(token->str)); } // check "," symbol freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else{ if(strcmp(",",token->str) != 0){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } } //get safe bit freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_IDENTIFIER_TYPE && token->type != TOKEN_INTEGER_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect 0/1/x but is %s\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else{ if((strcmp("0",token->str) == 0) || (strcmp("1",token->str) == 0) || (strcmp("X",token->str) == 0)){ safeBit = (char *)malloc(strlen(token->str)); strcpy(safeBit,(token->str)); }else{ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect 0/1/x but is %s\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } } // check "," and ")" symbol freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' or ')' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else if((strcmp(",",token->str) != 0) && (strcmp(")",token->str) != 0)){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' or ')' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else if(strcmp(")",token->str) == 0){ freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else if(strcmp(",",token->str) == 0){ listAddBoundaryRegister(list,cellNumber,cellName,portId,function,safeBit,"","",""); freeToken(token); continue; }else if(strcmp(";",token->str) == 0){ listAddBoundaryRegister(list,cellNumber,cellName,portId,function,safeBit,"","",""); freeToken(token); break; }else{ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } } // get ccell => input spec or fisable spec freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_INTEGER_TYPE && token->type != TOKEN_IDENTIFIER_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect integer or input spec but is %s\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else if(token->type == TOKEN_IDENTIFIER_TYPE){ if(checkInputSpec(token->str) != 1){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. %s is not a valid input spec\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } }else{ intFlag = 1; } ccell = (char *)malloc(strlen(token->str)); strcpy(ccell,(token->str)); // check "," and ")" symbol // , for disable spec and ) for input spec freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' or ')' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else if((strcmp(",",token->str) != 0) && (strcmp(")",token->str) != 0)){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' or ')' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else if(strcmp(")",token->str) == 0){ //for input spec only if(intFlag == 1){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else if(strcmp(",",token->str) == 0){ listAddBoundaryRegister(list,cellNumber,cellName,portId,function,safeBit,ccell,"",""); freeToken(token); continue; }else if(strcmp(";",token->str) == 0){ listAddBoundaryRegister(list,cellNumber,cellName,portId,function,safeBit,ccell,"",""); freeToken(token); break; }else{ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } }else{ // if "," if(intFlag == 0){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ')' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } } //get disable value freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_INTEGER_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect 0 or 1 but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else if((strcmp("0",token->str) != 0) && (strcmp("1",token->str) != 0)){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect 0 or 1 but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } disval = (char *)malloc(strlen(token->str)); strcpy(disval,(token->str)); // check "," symbol freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else{ if(strcmp(",",token->str) != 0){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } } //get disable result freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_IDENTIFIER_TYPE && token->type != TOKEN_IDENTIFIER_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. %s is not a valid disable result.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else if(checkDisableResult(token->str) != 1){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. %s is not a valid disable result.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } disres = (char *)malloc(strlen(token->str)); strcpy(disres,(token->str)); // check ")" symbol freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ')' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else{ if(strcmp(")",token->str) != 0){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ')' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } } // check wether is continue or not freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' or ';' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else{ if((strcmp(";",token->str)) != 0 && (strcmp(",",token->str) != 0)){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' or ';' but is %s.\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } } if(strcmp(";",token->str) == 0){ listAddBoundaryRegister(list,cellNumber,cellName,portId,function,safeBit,ccell,disval,disres); freeToken(token); break; }else{ listAddBoundaryRegister(list,cellNumber,cellName,portId,function,safeBit,ccell,disval,disres); freeToken(token); continue; } } } void listAddBoundaryRegister(LinkedList *list,char* cellNum,char*cellname,char*portid,char*function,char*safebit,char*ccell,char*disV,char*disR){ boundaryRegister *boundR; boundR = initBR(); boundR->cellNumber = malloc(sizeof(char)); strcpy(boundR->cellNumber,cellNum); boundR->cellName = malloc(sizeof(char)); strcpy(boundR->cellName,cellname); boundR->portId = malloc(sizeof(char)); strcpy(boundR->portId,portid); boundR->function = malloc(sizeof(char)); strcpy(boundR->function,function); boundR->safeBit = malloc(sizeof(char)); strcpy(boundR->safeBit,safebit); boundR->ccell = malloc(sizeof(char)); strcpy(boundR->ccell,ccell); boundR->disval = malloc(sizeof(char)); strcpy(boundR->disval,disV); boundR->disres = malloc(sizeof(char)); strcpy(boundR->disres,disR); Item *item; item = initItem(boundR); listAdd(list,item); } boundaryRegister *initBR(){ boundaryRegister *boundaryR; boundaryR = (boundaryRegister*)malloc(sizeof(boundaryRegister)); boundaryR->cellNumber = ""; boundaryR->cellName = ""; boundaryR->portId = ""; boundaryR->function = ""; boundaryR->safeBit = ""; boundaryR->ccell = ""; boundaryR->disval = ""; boundaryR->disres = ""; return boundaryR; } int checkFunctionName(char *str){ char *funcN[] = {"INPUT","OUTPUT2","OUTPUT3","CONTROL","CONTROLR","INTERNAL","CLOCK","BIDIR","OBSERVE_ONLY",NULL}; int i = 0; while(funcN[i] != NULL){ if(strcmp(funcN[i],str) == 0){ return 1; } i++; } return 0; } int checkInputSpec(char *str){ char *inputSpecName[] = {"EXTERN0","EXTERN1","PULL0","PULL1","OPEN0","OPEN1","KEEPER","OPENX","EXPECT1","EXPECT0",NULL}; int i = 0; while(inputSpecName[i] != NULL){ if(strcmp(inputSpecName[i],str) == 0){ return 1; } i++; } return 0; } int checkDisableResult(char *str){ char *disableResultName[] = {"WEAK0","WEAK1","PULL0","PULL1","OPEN0","OPEN1","KEEPER","Z",NULL}; int i = 0; while(disableResultName[i] != NULL){ if(strcmp(disableResultName[i],str) == 0){ return 1; } i++; } return 0; } char *getPortId(FileTokenizer *fileTokenizer){ Token *token; char *result; int startPos,endPos; token = getStringToken(fileTokenizer); if(token->type != TOKEN_IDENTIFIER_TYPE && token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. %s is not a valid port id\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } // If is '*' symbol, return the value if(token->type == TOKEN_OPERATOR_TYPE){ if(strcmp("*",token->str) != 0){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect \"*\" symbol but is %s\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else{ result = malloc(sizeof(char*) * strlen(token->str)); strcpy(result,token->str); free(token); return result; } }else if(checkVHDLidentifier(token->str) != 1){ //check for VHDL identifier throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. %s is not a valid port name\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } // If it is identifier type startPos = token->startColumn; endPos = startPos + token->length - 1; freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' or '(' symbol but is %s\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else if((strcmp(",",token->str) != 0) && (strcmp("(",token->str) != 0)){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ',' or '(' symbol but is %s\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } // if is ',', createcallback token and get the portId and return if(strcmp(",",token->str) == 0){ createCallBackToken(fileTokenizer->tokenizer,token); result = getSubString(token->originalStr,startPos,endPos); freeToken(token); return result; } // if is '(', check for (<number>) freeToken(token); token = getStringToken(fileTokenizer); //check for <number> if(token->type != TOKEN_INTEGER_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect integer but is %s\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); } // check for ')' freeToken(token); token = getStringToken(fileTokenizer); if(token->type != TOKEN_OPERATOR_TYPE){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ')' symbol but is %s\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else if(strcmp(")",token->str) != 0){ throwException(ERR_INVALID_BOUNDARY_REGISTER,token, \ "Error on line: %d. Expect ')' symbol but is %s\n",getCorrectReadLineNo(fileTokenizer->readLineNo,token),token->str); }else{ endPos = token->startColumn; } // obtain the portId and return result = getSubString(token->originalStr,startPos,endPos); freeToken(token); return result; } // get substring by using pointer char *getSubString(char *oriStr, int startPos, int endPos){ int totalLength = endPos - startPos + 1; return createSubstring(oriStr,startPos,totalLength); }
C
#include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> int CalcGCD(int); int GetMultiplicativeInverse(int); int main() { int i, j, k, gcd, alpha, beta, numstr[100], numcipher[100], alphaInverse; char str[100], cipher[100]; printf("Enter a string\n"); gets(str); for(i=0,j=0; i<strlen(str); i++) { if(str[i]!=' ') { str[j]=toupper(str[i]); j++; } else { str[j]=' '; j++; } } str[j]='\0'; printf("Entered string is : %s \n",str); printf("Enter Alpha value and must be between 1 and 25 both included\n"); scanf("%d",&alpha); if(alpha<1 || alpha>25) { printf("Alpha should lie in between 1 and 25\nSorry Try again !\n"); exit(0); } gcd=CalcGCD(alpha); if(gcd!=1) { printf("gcd(alpha,26)=1 but \n gcd(%d,26)=%d\nSorry Try again !\n",alpha,gcd); exit(0); } printf("Enter Beta value and must be between 0 and 25 both included\n"); scanf("%d",&beta); if(beta<0 || beta>25) { printf("Beta value should lie between 0 and 25\nSorry Try again !\n"); exit(0); } for(i=0; i<strlen(str); i++) { if(str[i]!=' ') numstr[i]=str[i]-'A'; else numstr[i]=-20; } alphaInverse=GetMultiplicativeInverse(alpha); printf("MI=%d\n",alphaInverse); printf("Affine Cipher text is\n"); for(i=0; i<strlen(str); i++) { if(numstr[i]!=-20) { numcipher[i]=(alphaInverse*(numstr[i]-beta))%26; if(numcipher[i]<0) numcipher[i]=numcipher[i]+26;//To avoid negative numbers printf("%c",(numcipher[i]+'A')); } else printf(" "); } printf("\n"); return 0; } int CalcGCD(int alpha) { int x; int temp1=alpha; int temp2=26; while(temp2!=0) { x=temp2; temp2=temp1%temp2; temp1=x; } return temp1; } int GetMultiplicativeInverse(int alpha) { int i,MI; for(i=1; i<=alpha; i++) { MI=((i*26)+1); if(MI%alpha==0) break; } MI=MI/alpha; return MI; }
C
#include <stdio.h> #include <string.h> #pragma warning(disable :4996) // //// ȯ ḮƮ //typedef int ElementType; //typedef struct tagNode //{ // ElementType Data; // struct tagNode* PrevNode; // struct tagNode* NextNode; //} Node; //Node* CreateNode(ElementType NewData) //{ // Node* NewNode = (Node*)malloc(sizeof(Node)); // NewNode->Data = NewData; // NewNode->PrevNode = NULL; // NewNode->NextNode = NULL; // return NewNode; //} // //// - ߰ *- //void AppendNode(Node** Head, Node* NewNode) //{ // if ((*Head) == NULL) // { // *Head = NewNode; // (*Head)->NextNode = *Head; // (*Head)->PrevNode = *Head; // } // else // { // Node* Tail = (*Head)->PrevNode; // tail : 2° // // Tail->NextNode->PrevNode = NewNode; // Խ: tail а, 忡 // Tail->NextNode = NewNode; // tail ٽ 2° Ű // NewNode->NextNode = (*Head); // NewNode->PrevNode = Tail; // } //} //int main(void) //{ // int i = 0; // int Count = 0; // Node* List = NULL; // Node* NewNode = NULL; // Node* Current = NULL; // // - 5 ߰ *- // for (i = 0; i < 5; i++) // ݺ 3 ޸ ׸ // { // NewNode = CreateNode(i); // AppendNode(&List, NewNode); // } //} // ------------------------------------------------------------------------------------------------------ // //// 迭 ñ //#define STACK_SIZE 5 // //typedef struct _node { // int key; // // other data... //} Node; // ////typedef struct _stack { //// int top; //// Node arr[]; ////} Stack; // //int top = -1; //Node *arr[STACK_SIZE]; // //void init() { top = -1; } // //int is_full() { return (top >= STACK_SIZE); } // //int is_empty() { return (top < 0); } // //void push(int data) { // Node *new_node = (Node *)malloc(sizeof(Node)); // new_node->key = data; // if (is_full()) { printf("full\n"); return; } // arr[++top] = new_node; //} // //int pop() { // int del; // if (is_empty()) { printf("empty\n"); return -1; } // del = arr[top]->key; // free(arr[top--]); // return del; //} // //int peek() { // if (is_empty()) { printf("empty\n"); return; } // return arr[top]->key; //} // //int main() { // init(); // push(8); // push(10); // push(5); // push(3); // for(size_t i = 0; i < 5; ) // printf("%d ", pop()); // // return 0; //} // //// ḮƮ ñ //typedef struct _node { // int key; // struct _node *link; //} Node; // //typedef struct _stack { // struct Node *top; //} Stack; // //void init(Stack *s) { // s->top = NULL; //} //---------------------------------------------------------------------------------------------------- // //void evaluate(char *in) { // if (/**/) { // push(in); // // } // else if (/**/) { // char *op1 = pop(); // char *op2 = pop(); // atoi(op1) in atoi(op2)); // } //} //------------------------------------------------------------------------------------------------------------------------------------------------- //#include <stdarg.h> typedef char * myva_list; #define _INTSIZEOF(n) ( (sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1) ) // x86 డ(x64 ϸ sizeof() ޶ ) #define va_start(ap,v) ( ap = (myva_list)&v + _INTSIZEOF(v) ) #define va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)) ) #define va_end(ap) ( ap = (myva_list)0 ) float average(int num, ...) { // ... : myva_list arg_ptr; // տ Ư¡ Ÿ ͵ int cnt, total = 0; // Ǹ޸𸮿 Ű (10<-1<-2<-...<-10)=> stack va_start(arg_ptr, num); for (cnt = 0; cnt < num; cnt++) total += va_arg(arg_ptr, int); va_end(arg_ptr); return ((float)total / num); } // //int main() { // float x; // x = average(10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // printf("first avg is %f\n", x); // return 0; //} //------------------------------------------------------------------------------------------------------------------------------------------------ #define STACK_SIZE 10 #define STR_SIZE 10 char stack[STACK_SIZE][STR_SIZE]; int currTop; int validTop; void init() { currTop = validTop = -1; } int isEmpty() { return (validTop < 0); } int isFull() { return (validTop >= STACK_SIZE); } void push(char *url) { if (isFull()) { printf("full\n"); return; } if (currTop < validTop) validTop = currTop; currTop++; strcpy(stack[++validTop], url); } char *pop() { if (isEmpty()) { printf("empty\n"); return NULL; } return stack[validTop--]; } void connectWebPage(char *url) { if (strcmp(stack[currTop], url)) push(url); } void viewWebPage() { int i, j; printf(" < ڷ ̵ ִ > \n"); printf("=====================================\n"); i = currTop; j = 1; while (0 < i) printf("%d. %s\n", j++, stack[--i]); if (j == 1) printf("ڷ ϴ.\n\n"); printf("\n < ̵ ִ > \n"); printf("=====================================\n"); i = currTop; j = 1; while (validTop > i) printf("%d. %s\n", j++, stack[++i]); if (j == 1) printf(" ϴ.\n\n"); } int main() { int user_m; char *menu[] = { "URL ", "湮 ", "ڷ", "", "" }; char first[] = "about:blank"; char url[STR_SIZE]; init(); while (1) { printf("\n : %s\n", first); printf("============================================\n"); for(size_t idx = 0; idx < 5; idx++) printf("%d. %s\n", idx + 1, menu[idx]); printf("============================================\n"); printf("޴ Էϼ: "); scanf("%d", &user_m); switch (user_m) { case 1: printf("\n ּҸ Էϼ: "); scanf("%s", url); connectWebPage(url); system("cls"); break; case 2: printf("\n2. 湮 ⸦ ϼ̽ϴ.\n"); viewWebPage(); getchar(""); getchar(""); system("cls"); break; case 3: if (currTop > 0) currTop--; system("cls"); break; case 4: if (currTop < validTop) currTop++; system("cls"); break; case 5: printf("\n\nմϴ.\n"); return 0; default: printf("\n\n\n"); } if (currTop >= 0 && currTop <= validTop) strcpy(first, stack[currTop]); } return 0; } // ----------------------------------------------------------------------------------------------------------------------------------------------
C
#ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <winsock2.h> #include <windows.h> #include <ws2tcpip.h> #include <iphlpapi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #pragma comment(lib, "Ws2_32.lib") #define BUFLEN 1024 char ADDRESS[16]; // 255.255.255.255, 15 characters int PORT; void cleanup(SOCKET listener) { if (listener) { closesocket(listener); } WSACleanup(); } int readFile(const char* filename, char **output) { // load input file FILE *fp = fopen("input.html", "r"); if (!fp) { return 0; } // get length // move cursor to the end fseek(fp, 0L, SEEK_END); // get remaining length int len = ftell(fp); // return to original position fseek(fp, 0, SEEK_SET); // read *output = malloc(len + 1); fread(*output, len, 1, fp); (*output)[len] = 0; fclose(fp); return len; } int main(int argc, char **argv) { printf("Hello, world!\n"); int res, sendRes; int running; WSADATA wsaData; SOCKET listener, client; struct sockaddr_in address, clientAddr; char recvbuf[BUFLEN]; char *inputFileContents; int inputFileLength; // initialization res = WSAStartup(MAKEWORD(2, 2), &wsaData); if (res) { printf("Startup failed: %d\n", res); return 1; } // read address if (argc < 3) { FILE *fp = NULL; if (argc == 2) { printf("%s: ", argv[1]); fp = fopen(argv[1], "r"); } else { printf(".env: "); fp = fopen(".env", "r"); } if (!fp) { printf("Could not read address file\n"); return 1; } fscanf(fp, "%s %d", ADDRESS, &PORT); fclose(fp); printf("Take in %s:%d through file\n", ADDRESS, PORT); } else { strcpy(ADDRESS, argv[1]); PORT = atoi(argv[2]); printf("Take in %s:%d through runtime arguments\n", ADDRESS, PORT); } // setup server listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listener == INVALID_SOCKET) { printf("Error with construction: %d\n", WSAGetLastError()); cleanup(0); return 1; } // bind server address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr(ADDRESS); address.sin_port = htons(PORT); res = bind(listener, (struct sockaddr *)&address, sizeof(address)); if (res == SOCKET_ERROR) { printf("Bind failed: %d\n", WSAGetLastError()); cleanup(listener); return 1; } // set as listener res = listen(listener, SOMAXCONN); if (res == SOCKET_ERROR) { printf("Listen failed: %d\n", WSAGetLastError()); cleanup(listener); return 1; } printf("Loading file\n"); inputFileLength = readFile("input.html", &inputFileContents); if (!inputFileLength || !inputFileContents) { printf("Could not read input form\n"); cleanup(listener); return 1; } // done setting up printf("Accepting on %s:%d\n", ADDRESS, PORT); running = 1; while (running) { // accept client int clientAddrLen; client = accept(listener, NULL, NULL); if (client == INVALID_SOCKET) { printf("Could not accept: %d\n", WSAGetLastError()); cleanup(listener); return 1; } // get client info getpeername(client, (struct sockaddr *)&clientAddr, &clientAddrLen); printf("Client connected at %s:%d\n", inet_ntoa(address.sin_addr)); // receive res = recv(client, recvbuf, BUFLEN, 0); if (res > 0) { // print message recvbuf[res] = '\0'; //printf("%s\n", recvbuf); // test if GET command if (!memcmp(recvbuf, "GET", 3 * sizeof(char))) { printf("Receive GET\n"); // return input file printf("Requested file\n"); sendRes = send(client, inputFileContents, inputFileLength, 0); if (sendRes == SOCKET_ERROR) { printf("Send failed: %d\n", WSAGetLastError()); } } // test if POST command else if (!memcmp(recvbuf, "POST", 4 * sizeof(char))) { printf("Receive POST\n"); // send file back sendRes = send(client, inputFileContents, inputFileLength, 0); if (sendRes == SOCKET_ERROR) { printf("Send failed: %d\n", WSAGetLastError()); } // get message // find new line int i = res - 1; for (; i >= 0; i--) { if (recvbuf[i] == '=') { i++; break; } } // content from cursor onwards contains data //printf("Received (%d, %d, %d): \n%s\n", res, i, res - i, recvbuf + i); // get length int len = 0; for (int j = i; j < res; j++) { len++; if (recvbuf[j] == '%') { j += 2; } } // read characters char *msg = malloc(len + 1); for (int cursor = 0, j = i; cursor < len; cursor++, j++) { char c = recvbuf[j]; if (c == '%') { // get hex val of next two characters msg[cursor] = 0; for (int k = 1; k <= 2; k++) { c = recvbuf[j + k]; if (c >= 'A') { c -= 'A' - 10; } else { c -= '0'; } msg[cursor] <<= 4; msg[cursor] |= c; } j += 2; } else if (c == '+') { msg[cursor] = ' '; } else { // output character directly msg[cursor] = c; } } msg[len] = 0; // terminator printf("Parsed (%d): %s\n", len, msg); // test message if (!memcmp(msg, "/quit", 5 * sizeof(char))) { printf("Quit message received\n"); running = 0; // false free(msg); break; } else { printf("%s\n", msg); } free(msg); } } else if (!res) { printf("Client disconnected\n"); } else { printf("Receive failed: %d\n", WSAGetLastError()); } // shutdown client shutdown(client, SD_BOTH); closesocket(client); client = INVALID_SOCKET; } cleanup(listener); printf("Shutting down.\nGood night.\n"); return 0; }
C
#include "uri/uri.h" #include <stdlib.h> typedef int (*yyrule)(); extern int yyparse(); extern int yyparsefrom(yyrule); extern int yy_start(); extern const char *charbuf; /* Buffer of characters to be parsed. */ extern uri_t *parse_result; /* Results of parse. */ uri_t *parse_uri(const char *input) { charbuf = input; int rc = yyparsefrom(yy_start); yyrelease(); charbuf = NULL; if (!rc) return NULL; uri_t *uri = parse_result; parse_result = NULL; return uri; } void free_uri(uri_t *uri) { if (!uri) return; if (uri->scheme) free(uri->scheme); if (uri->host) free(uri->host); if (uri->user) free(uri->user); if (uri->query) free(uri->query); if (uri->fragment) free(uri->fragment); if (uri->path) free(uri->path); free(uri); } void print_uri(uri_t *uri) { printf("uri {\n .scheme = %s\n .host = %s\n .port = %i\n .path = %s\n .user " "= %s\n .query = %s\n .fragment = %s\n}\n", uri->scheme, uri->host, uri->port, uri->path, uri->user, uri->query, uri->fragment); }
C
#include "ft_printf.h" /* ** @brief Reset buffer if size + len >= BUFFER_SIZE ** @param core ** @param len */ void reset_buffer(t_core *core, size_t len) { size_t size; size = ft_strlen(core->buffer); if ((size + len) >= BUFFER_SIZE) { write(core->fd, core->buffer, ft_strlen(core->buffer)); ft_bzero(core->buffer, BUFFER_SIZE); } } /* ** @brief ** @param core ** @param str */ void ft_core(t_core *core, char *str) { int i; i = 0; while (str[i]) { if (str[i] != '%') { reset_buffer(core, 1); ft_strcat(core->buffer, str + i); i++; } else ft_flag(str, &i, core); } }
C
#include <stdio.h> int main() { int x; for(x=100 ; x>=1 ; x--) printf("%d\n",x); }
C
/* * Ramp.c * * Created on: Mar 22, 2021 * Author: Rasmus Bank Mikkelsen */ /* Includes */ #include <math.h> #include <stdio.h> #include <stdint.h> #include "Throttle.h" #include "main.h" /* External Variables */ float f_dutyCapRAMP; uint16_t uint16_throttleCalcRAMP; /* Internal Variables */ float f_lastOutput=0.1; float f_gain1 = 1.00033f; /* Start Code Here */ // The Ramp function will receive the shecme as input. It will then use the output from throttle to calculate a ramp function float pfx_ramp() { uint16_throttleCalcRAMP = pfx_throttle(); // Calling Throttle function // Scheme 1 if ((f_lastOutput == 0) && (uint16_throttleCalcRAMP > 0)) // To ensure the throttle output only is zero when the throttle is not pulled { f_lastOutput = 0.1; } if (f_lastOutput < uint16_throttleCalcRAMP) // When throttle output is higher than our last output, increase our output { f_lastOutput = f_lastOutput*f_gain1; } else if (f_lastOutput >= uint16_throttleCalcRAMP) // When last output is less or equal to the throttle output, set output to throttle output { f_lastOutput = uint16_throttleCalcRAMP; } else { f_lastOutput = 0; } if (f_dutyCapRAMP > 0.9) // Capping the duty cycle to 0.9 { f_dutyCapRAMP = 0.9; } return f_dutyCapRAMP; }
C
//////////////////////////////////// // Problem Satement : Program to accept filename from user and write to it /////////////////////////////////// #include<stdio.h> #include<unistd.h> //universal standard library #include<fcntl.h> //file control open,close etc #include<string.h> int main(int argc, char *argv[]){ int fd = 0,ret = 0; char arr[10] = "Marvellous"; fd = open(argv[1],O_WRONLY); ret = write(fd, arr,strlen(arr)); return 0; }
C
#include <stdio.h> int t,r; double s; int main(void) { scanf("%d",&t); while(t--) { scanf("%d",&r); s=(8.0*(2.0-pow(2,0.5))*r*r*r); printf("%0.4lf\n",s); } // your code goes here return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> int maxInts(int numArgs, ...) { va_list args; va_start(args, numArgs); int i = 1; int max = va_arg (args, int); while (i < numArgs) { int maybe_max = va_arg (args, int); if (maybe_max > max){ max = maybe_max; } i++; } return max; } int main() { printf("%d\n", maxInts(5, 3, 2, 4, 1, 34)); printf("%d\n", maxInts(2, 12, 21)); return 0; }
C
/* ** buil.c for buil in /home/pignol_r/Epitech/rendu/PSU_2015_minishell2 ** ** Made by pignol_r ** Login <[email protected]> ** ** Started on Fri Apr 1 18:14:53 2016 pignol_r ** Last update Tue Apr 12 14:47:39 2016 pignol_r */ #include <stdlib.h> #include <unistd.h> #include "my.h" #include "prototype.h" void aff_tab(char **tab) { int i; i = 0; while (tab[i]) { my_putstr(tab[i]); my_putchar('\n'); ++i; } } void set_pwd(t_all *all, char *pwd) { free(all->elem.oldpwd); all->elem.oldpwd = all->elem.pwd; all->elem.pwd = pwd; } int buil_cd(t_all *all) { char *pwd; if (!all->elem.arg[1] && all->elem.home) { if (chdir(all->elem.home) == -1) return (my_error(9) - 1); } else if (all->elem.arg[2]) return (my_error(10) - 1); else if ((!my_strcmp("-", all->elem.arg[1]) && chdir(all->elem.oldpwd) == -1) || (my_strcmp("-", all->elem.arg[1]) && chdir(all->elem.arg[1]) == -1)) return (my_error(11) - 1); pwd = NULL; pwd = getcwd(pwd, 0); if (!(pwd = (realloc(pwd, my_strlen(pwd) + 1)))) return (my_error(25)); if (env_replace(all, "PWD", pwd, get_envstr(all->elem.env, "PWD=")) || env_replace(all, "OLDPWD", all->elem.pwd, get_envstr (all->elem.env, "OLDPWD="))) return (0); set_pwd(all, pwd); get_prompt(all); return (0); } int buil_setenv(t_all *all) { if (!all->elem.arg[1]) return (my_error(19) - 1); else if (all->elem.arg[2] && all->elem.arg[3]) return (my_error(51) - 1); else if (my_str_isalpha(all->elem.arg[1])) return (my_error(20) - 1); env_replace(all, all->elem.arg[1], all->elem.arg[2], get_envstr(all->elem.env, all->elem.arg[1])); get_path(all); return (0); } int buil_unsetenv(t_all *all) { int j; int i; if (!all->elem.arg[1]) return (my_error(23) - 1); j = 1; while (all->elem.arg[j]) { if (my_str_isalpha(all->elem.arg[j])) return (my_error(20) - 1); if ((i = get_envstr(all->elem.env, all->elem.arg[j])) > 0) env_delete(all, i); ++j; } get_path(all); return (0); }
C
#include<stdio.h> // programa que recebe a altura da piramide e imprime a mesma int main(void) { int i=0,j=0,altura=0; printf("digite a altura da piramide: \n"); scanf("%d", &altura); printf("\n"); for(i=0;i<altura;i++) // controla cada camada da piramide { for(j=0;j<=i;j++) // imprime o corpo da piramide { printf("%c",'*'); } printf("\n"); // pula para proxima linha } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_mlx_sphere.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: piquerue <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/05/17 23:35:28 by piquerue #+# #+# */ /* Updated: 2017/05/29 23:27:24 by piquerue ### ########.fr */ /* */ /* ************************************************************************** */ #include "../libft.h" void ft_pixel_put(t_fractol *fractol, t_point pt) { int chute; chute = (pt.x * 4) + (pt.y * fractol->img->size_line); fractol->img->img[chute] = (char)255; fractol->img->img[++chute] = 120; fractol->img->img[++chute] = 0; fractol->img->img[++chute] = 90; } void ft_pixel_put3(t_fractol *fractol, t_point pt, t_color_mlx color) { int chute; chute = (pt.x * 4) + (pt.y * fractol->img->size_line); fractol->img->img[chute] = color.red; fractol->img->img[++chute] = color.green; fractol->img->img[++chute] = color.blue; fractol->img->img[++chute] = 90; } void ft_sphere(t_fractol *fractol, t_point pt, int r) { t_point tmp; tmp = pt; tmp.y -= r; while (tmp.y <= pt.y + r) { tmp.x = pt.x - r; while (tmp.x <= pt.x + r) { if (r * r >= ft_power(tmp.x - pt.x, 2) + ft_power(tmp.y - pt.y, 2)) ft_pixel_put3(fractol, tmp, create_color(0x00, 0xFF, 0x00)); tmp.x++; } tmp.y++; } }
C
#include <stdio.h> #include <stdlib.h> double findMedianSortedArrays(int *nums1, int nums1Size, int *nums2, int nums2Size) { int mid = (nums1Size + nums2Size) / 2; if (mid == 0) { if (nums1Size == 0) return nums2[0]; if (nums2Size == 0) return nums1[0]; } int isOdd = (nums1Size + nums2Size) % 2 == 1; int i = 0, j = 0; int t1, t2; // 记录相邻大小的两个数 for (int index = 0; index <= mid; index++) { if (i == nums1Size) { if (index == 0) t2 = nums2[j]; else t1 = t2, t2 = nums2[j]; j++; } else if (j == nums2Size) { if (index == 0) t2 = nums1[i]; else t1 = t2, t2 = nums1[i]; i++; } else { if (nums1[i] < nums2[j]) { if (index == 0) t2 = nums1[i]; else t1 = t2, t2 = nums1[i]; i++; } else { if (index == 0) t2 = nums2[j]; else t1 = t2, t2 = nums2[j]; j++; } } } return isOdd ? t2 : (t2 + t1) / 2.0; } int main() { int arr1[] = {1, 3}; int arr2[] = {2, 4}; printf("%lf\n", findMedianSortedArrays(arr1, 2, arr2, 2)); return 0; }
C
void addPointers(int* res, int* b, int* a) { *res = *a + *b; }
C
#include <stdio.h> int main(int argc, char* argv[]){ FILE* input = fopen(input_ex2.txt, "r"); FILE* output = fopen(output_ex2.txt,"w"); char c; fseek(input,-1,SEEK_END); while((c=fgetc(input)) != EOF){ fputc(c,output); fseek(input,-2); } fseek(input,0,SEEK_SET); fputc(fgetc(input),output); fclose(input); fclose(output); return 0; }
C
/* ** utils.c for corewar in /home/flavian.gontier/Tek1/C_Prog_Elem/CPE_2016_corewar_vm/src/vm/virtual_machine ** ** Made by flavian gontier ** Login <[email protected]@epitech.net> ** ** Started on Sun Apr 02 15:39:13 2017 flavian gontier ** Last update Sun Apr 02 16:36:51 2017 flavian gontier */ #include "libmy.h" #include "virtual_machine.h" t_process *get_process_by_id(t_vm *virtual_machine, int id) { int index; index = 0; while (index < virtual_machine->process_count) { if (virtual_machine->processes[index].id == id) return (&virtual_machine->processes[index]); index += 1; } return (NULL); } void virtual_machine_write(t_vm *machine, int32_t address, int8_t *data, size_t n) { int tmp; int count; if (address > MEM_SIZE) address = address % MEM_SIZE; tmp = address + n; if (tmp > MEM_SIZE) { count = MEM_SIZE - address; my_memcpy(&machine->memory[address], data, count); my_memcpy(&machine->memory[0], data + count, n - count); } else { my_memcpy(&machine->memory[address], data, n); } }
C
//Call by reference #include<stdio.h> void cbr(int*,int*); int main(){ int a=2,b=3; printf("\t@@@@Call by reference@@@@"); printf("\nValues of a and b before calling function cbr(): a=%d b=%d",a,b); cbr(&a,&b); printf("\nValues of a and b after calling function cbr(): a=%d b=%d",a,b); return 0; } void cbr(int *x,int *y){ *x=*x-1; *y=*y+2; printf("\nValues of a and b inside the function cbr(): a=%d b=%d",*x,*y); }
C
/* * Logic: Print pyramid using *. * Sample output: Example 1: > /path/ ./a.out 5 * * * * * * * * * * * * * * * * * * * * * * * * * > /path/ */ #include <stdio.h> void func(int rows); int main() { int i,space,rows; scanf("%d",&rows); func(rows); return 0; } void func(int rows){ int i,space,k=0; for(i=1;i<=rows;++i) { for(space=1;space<=rows-i;++space) { printf(" "); } while(k!=2*i-1) { printf("* "); ++k; } k=0; printf("\n"); } }
C
#include <TF1.h> Double_t ArScintillationSpectrum( const Double_t* k, Double_t *par) { Double_t waveL; Double_t kk=k[0]; waveL =exp(-0.5*((kk-128.0)/(2.929))*((kk-128.0)/(2.929))); return waveL; } // Calculates the dielectric constant of LAr from the Bideau-Sellmeier formula. // See : A. Bideau-Mehu et al., "Measurement of refractive indices of Ne, Ar, // Kr and Xe ...", J. Quant. Spectrosc. Radiat. Transfer, Vol. 25 (1981), 395 Double_t LArEpsilon(const Double_t lambda) { Double_t epsilon; Double_t lowLambda=110.0; // lowLambda in nanometer if (lambda < lowLambda) return 1.0e4; // lambda MUST be > 110.0 nm epsilon = lambda / 1000; // switch to micrometers epsilon = 1.0 / (epsilon * epsilon); // 1 / (lambda)^2 epsilon = 1.2055e-2 * ( 0.2075/ (91.012 - epsilon) + 0.0415/ (87.892 - epsilon) + 4.3330 / (214.02 - epsilon) ); epsilon *= (8./12.); // Bideau-Sellmeier -> Clausius-Mossotti Double_t GArRho= 0.001784; // density in g/cm3 Double_t LArRho= 1.3954; // density in g/cm3 epsilon *= (LArRho / GArRho); // density correction (Ar gas -> LAr liquid) if (epsilon < 0.0 || epsilon > 0.999999) return 4.0e6 ; epsilon = (1.0 + 2.0* epsilon) / (1.0- epsilon); // solve Clausius-Mossotti return epsilon; } // Calculates the refractive index of LAr Double_t LArRefIndex(const Double_t *lam, Double_t *par) { Double_t lambda=lam[0]; return ( sqrt(LArEpsilon(lambda)) ); // square root of dielectric constant } void lArRoot() { TF1 *f1 = new TF1("myfunc",LArRefIndex,110.,1000.,0); // f1->Draw(); TF1 *f2 = new TF1("myfunc2",ArScintillationSpectrum,100.,150.,0); f2->Draw(); }
C
/* dmdo - this will become entry point for rd7 ?? */ /* receives dm file pointer, file opened with wb attribute, ** pointer to data buffer and length of input buffer ****************************************************/ /**************************************************************** ** header segment is based upon DATA MANAGER's encode modules. ** apparently(!) the header modules stuff their characters ** into an array, and then output the works. This module, therefore ** allocates a 1K buffer (tho 512 probably enuf), then ** calls encode. On return finds where "##DATA\r\n" is located, ** outputs complete header in one swoop, then outputs data ** in one swoop !! ** In encode, the game I am playing with KREC is to use the CDS KREC ** in place of the DM header, since it APPEARS they kept the same ** names *****************************************************************/ #include <stdlib.h> #include <string.h> #include <std.h> #include "spec.h" #include <io.h> #include <stdio.h> #define HDRBUF 1024 char far *spset(char far*,KREC far*); LOCAL KREC skrec; void encode(char far*,KREC far*, int *); void dmdo(char*filid, int dmhandle, char *inalloc, /* file read in */ LONG splength) /* length of file */ { char *spdata; /* only used in calls */ KREC far *pkrec; int i; char *hdralloc; int status; pkrec = &skrec; spdata = spset(inalloc,pkrec); /*********** now flip data, pointed to by spdata */ /****** === account for compression === */ if (!pkrec->dtype) /* just in case !! */ pkrec->dtype = 4; switch(pkrec->dtype) { case 1: /* single byte data, need no swap */ /* compression code = 1 */ break; case 2: /* 2 byte data, just swap bytes */ /* compression code = 6 */ swab(spdata,spdata,2 * pkrec->npts); break; case 3: /* 3byte data, don't swap, let compression code = 3 */ break; case 4: /* normal mode, compression code = 8 */ default: swapl (spdata, pkrec->npts); } /********* ready for encode ??????? *******************/ hdralloc = (char *)malloc(HDRBUF); if (hdralloc == NULL) { errorPrintf("insufficient memory for header, malloc \n"); exit(1); } memset(hdralloc,'\0',HDRBUF); /* zero fill */ encode(hdralloc,pkrec,&status); i = strlen(hdralloc); write(dmhandle,hdralloc,i); /* now write data */ i = pkrec->npts * pkrec->dtype; /* takes care of all compressions */ write(dmhandle,spdata,i); return; }
C
/* * UART.c * * Created on: 8 wrz 2014 * Author: MiCkl */ #include "UART.h" void USART_Init( unsigned int ubrr ) { /*Set baud rate */ UBRRH = (unsigned char)(ubrr>>8); UBRRL = (unsigned char)ubrr; /*Enable receiver and transmitter */ UCSRB = (1<<RXEN)|(1<<TXEN); /* Set frame format: 8data, 1stop bit */ UCSRC = (1<<URSEL)|(1<<USBS)|(3<<UCSZ0); } void USART_Transmit( unsigned char data ) { /* Wait for empty transmit buffer */ while ( !( UCSRA & (1<<UDRE)) ); /* Put data into buffer, sends the data */ UDR = data; } unsigned char USART_Receive( void ) { /* Wait for data to be received */ while ( !(UCSRA & (1<<RXC)) ); /* Get and return received data from buffer */ return UDR; } void USART_TransmitString( char* s ){ while( *s ) USART_Transmit( *s++ ); } void USART_ClearTerminal(){ USART_Transmit( 0x1B ); // <Esc> USART_TransmitString( "[2J"); USART_Transmit( 0x1B ); USART_TransmitString( "[H"); // Cursor to home } void USART_CursorPosition( int r, int c){ char temp[20]; USART_Transmit( 0x1B ); // <Esc> sprintf(temp, "[%d;%df", r, c); USART_TransmitString( temp ); } void USART_ForegroundColor( char *s ){ if ( s == "BLACK"){ USART_Transmit( 0x1B ); USART_TransmitString("[30m"); } if ( s == "RED"){ USART_Transmit( 0x1B ); USART_TransmitString("[31m"); } if ( s == "GREEN"){ USART_Transmit( 0x1B ); USART_TransmitString("[32m"); } if ( s == "YELLOW"){ USART_Transmit( 0x1B ); USART_TransmitString("[33m"); } if ( s == "BLUE"){ USART_Transmit( 0x1B ); USART_TransmitString("[34m"); } if ( s == "MAGNETA"){ USART_Transmit( 0x1B ); USART_TransmitString("[35m"); } if ( s == "CYAN"){ USART_Transmit( 0x1B ); USART_TransmitString("[36m"); } if ( s == "WHITE"){ USART_Transmit( 0x1B ); USART_TransmitString("[37m"); } }