language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <netinet/in.h> #include "../source_shared/protocol.h" #include "create_sockets.h" /* Connect to socket (TCP) Used by nodes */ int create_and_connect_socket(int baseport) { struct sockaddr_in server_addr; int client_socket = socket(AF_INET, SOCK_STREAM, 0); if (client_socket == -1) { perror("socket"); return EXIT_FAILURE; } server_addr.sin_family = AF_INET; server_addr.sin_port = htons(baseport); server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); fprintf(stdout, "Connecting to router ..........\n"); int ret = connect(client_socket, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)); if (ret == -1) { perror("connect"); exit(-2); } return client_socket; } /* Node receiving either response failure or response success. */ int hand_shake(int client_socket) { char buf[strlen(RESPONSE_SUCCESS)]; ssize_t bytes = receive_message(client_socket, buf, strlen(RESPONSE_SUCCESS)); //could be response_failure too if (bytes == -1) { fprintf(stdout, "Something wrong with receive message\n"); return EXIT_FAILURE; } if (bytes == 0) { fprintf(stdout, "Server has disconnected\n"); exit(EXIT_FAILURE); //No point to keep going if server has disconnected } buf[bytes] = '\0'; fprintf(stdout, "%s\n", buf); return EXIT_SUCCESS; } /* Creating and binding to socket (UDP) Used by nodes */ int create_and_connect_udp_socket(int baseport, int own_address) { struct sockaddr_in udp_sockaddr; int ret; int yes = -1; int udp_socket; udp_socket = socket(AF_INET, SOCK_DGRAM, 0); if (udp_socket == -1) { perror("socket"); exit(EXIT_FAILURE); } udp_sockaddr.sin_family = AF_INET; udp_sockaddr.sin_port = htons(baseport + own_address); udp_sockaddr.sin_addr.s_addr = INADDR_ANY; setsockopt(udp_socket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); if (own_address == 1) { sleep(1); } if (baseport + own_address > 65500) { printf("Invalid own address\n"); return EXIT_FAILURE; } ret = bind(udp_socket, (struct sockaddr*)&udp_sockaddr, sizeof(udp_sockaddr)); if (ret) { perror("bind"); close(udp_socket); return EXIT_FAILURE; } return udp_socket; }
C
/*Havanur Dervişoğlu 17011604*/ #include<stdio.h> #include<stdlib.h> #include<pthread.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <errno.h> #include<string.h> #define m_boyut 100 #define NUM_THREADS 100 /*bu programda giriş değerlerini bir structta tuttuk kullanıcı aranacak kelime sayısını belirliyor ve daha sonra keyword ve dizin kullanıcıdan girilmesi bekleniyor.Her giriş yeni bir thread oluşturuyor ve bu arama threadında verilen dizindeki txt uzantılı dosyalarda keywordu arayıp arama numarısı.txt adlı yeni dosyaya kaydediyor*/ //bu structta aranacak kelimeyi,bulunduğu dizini ve kaçıncı arama olduğunu tuttuk struct arama{ char keyword[m_boyut]; int index; char dizin[m_boyut]; }; //bu fonksiyon hataların nerelerden kaynaklı olduğunu gösterir void err_sys(const char *msg) { perror(msg); exit(EXIT_FAILURE); } void * f_arama(void *threadid){ FILE *fp1;//arama sonucu oluşturulacak olan file ın pointerı FILE *fp;//arama olunacak fileın pointerı struct arama *tid; tid=(struct arama*)threadid; DIR *dir; struct dirent *ent; struct stat finfo; char dosya[m_boyut];//dosya isimlendirmesi için aşağıda kullanılacak char ch;//aşağıda keyword bulmak için dosyadan kullanılcak int i=0,k=1;//satır sayısı ve keyword index int num=0;//dosyadaki keyword sayısını tutacak //arama sayısını bir arttırıyoruz tid->index++; //yeni oluşturulacak olan dosyanın isimlendirilmesi char i2[m_boyut]; i2[0]=tid->index+'0';//integerdan sayımızı char e convert etme i2[1]='.'; i2[2]='t'; i2[3]='x'; i2[4]='t'; if((fp1=fopen(i2,"w"))==NULL){ err_sys("fopen,write"); exit(0); } //girilen dizini açmak için opendir kullandık ve başarısızlık durumunu kontrol etme if ((dir = opendir(tid->dizin)) == NULL) err_sys("opendir"); //threadın çalışma dizini belirtilen dizin oldu,dizin değiştirme işlemidir,eklenmediğinde stat hata veriyor if (chdir(tid->dizin) < 0) err_sys("chdir"); //readdir fonksiyonuyla dizindeki elemanlar okunuyor ,ve stat fonksiyonu ile dosya bilgilerine ulaşılıyor while (errno = 0, (ent = readdir(dir)) != NULL) { if (stat(ent->d_name, &finfo) < 0) err_sys("stat"); if(strstr(ent->d_name,".txt")){//dosyanın .txt uzantılı olup olmadığını kontrol ediliyor strcpy(dosya,ent->d_name);//açılıp okunacak olan dosyanın adı belirlenir if((fp=fopen(dosya,"r"))==NULL){ err_sys("fopen:read"); exit(0); } else{ k=1;//satır saysını ilk satıra alsın diye yeniden txt dosyası açılınca num=0;//aynı dizine tekrardan giridiğinde saymaya baştan başlasın fprintf(fp1,"<----%s---->\n",dosya); while(!feof(fp)){ fscanf(fp,"%c",&ch);//keywordu karakter karakter okuyoruz if(tid->keyword[i]==ch){//burada ilk karakterleri keywordle karşılaştırıyoruz dosyadan if(i==(strlen(tid->keyword)-1)){//bu kelimenin dosyada bulunduğunu kontrol eder num++;//keyword sayısını arttırdık i=0;//keywordun karakter indisini sıfıra getirdik fprintf(fp1,"%d.satır\n",k);//hangi satırda olduğunu dosyaya yazdırdık } else i++;//eğer karakter sayısı eşleşmediyse keywordun karakter indisini bir arttırdım bir sonraki karakterleri karşılaştırmak için } else { i=0; if(ch=='\n'){//eğer karakter new line sa yeni satır demek k++;//satır sayısını arttırıyoruz } }//bir sonraki karşılaştırma için indisi 0lıyor eğer diğer karakterlerin eşlemesinde benzerlik yoksa baştan alır keyword indisi } fprintf(fp1,"%s :%s den %d tane var\n",dosya,tid->keyword,num);//yazmak için açtığımız dosyaya aradığımız kelimeden kaç tane olduğunu yazdırdık } fclose(fp);//okumak için açtığımız dosyayı kapattık } } if (errno) err_sys("readdir"); fclose(fp1);//yazdığımız dosyayı kapattık closedir(dir);//açtığımız dizini kapattık pthread_exit(NULL); } int main( void ){ struct arama *d; d=(struct arama*)malloc(sizeof(struct arama)); int num;//girilecek keyword sayısını tutar int j; int rc; pthread_t threads[NUM_THREADS]; d->index=0; printf("aranacak kelime sayısını giriniz:\n"); scanf("%d",&num); //aranacak keyword sayısı kadar thread oluşturduk for(j=0;j<num;j++){ scanf("%s",d->keyword); scanf("%s",d->dizin); rc=pthread_create(&threads[j],NULL,f_arama,d); if(rc){ err_sys("pthread_create"); return -1; } } for(j=0;j<num;j++){ pthread_join(threads[j],NULL); } return 0; }
C
#include "types.h" #include "stat.h" #include "user.h" void mutex_lock(int index) { acquire_mutex_spinlock(index); while(get_mutex_value(index)) cond_wait(1, index); set_mutex_value(index, 1); release_mutex_spinlock(index); } void mutex_unlock(int index) { acquire_mutex_spinlock(index); set_mutex_value(index, 0); cond_signal(1); release_mutex_spinlock(index); } int main() { int ret[10]; init_counters(); for (int i = 0; i < 10; i++) { ret[i] = fork(); for(int j = 0; j < 1000; j++) { mutex_lock(i); set_var(i, get_var(i)+1); mutex_unlock(i); } if (ret[i] == 0) break; } for (int i = 0; i < 10; i++) { if (ret[i] == 0) exit(); } for (int i = 0; i < 10; i++){ wait(); mutex_lock(i); int val = get_var(i); mutex_unlock(i); printf(1,"data[%d] = %d\n", i, val); } exit(); }
C
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include "tecnicofs-client-api.h" #define END_COMMAND "v v" #define MAX_STRING 101 int sockfd = -1; /* Estabelece uma sessao com o servidor TecnicoFS localizado no endereço passado como argumento. Devolve erro se o cliente já tiver uma sessao ativa com este servidor.*/ int tfsMount(char * address){ struct sockaddr_un serv_addr; socklen_t servlen; if((sockfd = socket (AF_UNIX, SOCK_STREAM,0)) < 0){ return TECNICOFS_ERROR_CONNECTION_ERROR; } /* Primeiro uma limpeza preventiva */ /*memset*/ bzero((char *) &serv_addr, sizeof(serv_addr)); /* Dados para o socket stream: tipo + nome que identifica o servidor */ serv_addr.sun_family = AF_UNIX; strcpy(serv_addr.sun_path, address); servlen = strlen(serv_addr.sun_path) + sizeof(serv_addr.sun_family); if(connect(sockfd,(struct sockaddr *) &serv_addr, servlen)){ return TECNICOFS_ERROR_CONNECTION_ERROR; } return 0; } /* Termina uma sessao ativa. Devolve erro caso não exista sessao ativa.*/ int tfsUnmount(){ int len = strlen(END_COMMAND); if (dprintf(sockfd, "%s%s", "v v", "\0") != strlen(END_COMMAND)){ return TECNICOFS_ERROR_CONNECTION_ERROR; } if (close(sockfd)){ return TECNICOFS_ERROR_NO_OPEN_SESSION; } return 0; } /* Cria um novo ficheiro com as permissoes indicadas, cujo dono e' o UID efetivo do processo cliente. Devolve erro caso já exista um ficheiro com o mesmo nome. */ int tfsCreate(char *filename, permission ownerPermissions, permission othersPermissions){ int code; int size= strlen(filename)+5; if (sockfd==-1){ return TECNICOFS_ERROR_NO_OPEN_SESSION; } if (dprintf(sockfd, "c %s %d%d%s", filename, ownerPermissions, othersPermissions, "\0") != size){ return TECNICOFS_ERROR_CONNECTION_ERROR; } int n = read(sockfd, &code, sizeof(int)); if (n < 0){ return TECNICOFS_ERROR_CONNECTION_ERROR; } return code; } /* Apaga o ficheiro indicado em argumento. Devolve erro caso o UID efetivo do processo cliente nao seja o mesmo do dono do ficheiro, caso o ficheiro nao exista ou esteja aberto. */ int tfsDelete(char *filename){ int code; int size= strlen(filename)+2; if (sockfd==-1){ return TECNICOFS_ERROR_NO_OPEN_SESSION; } if (dprintf(sockfd, "d %s%s", filename, "\0") != size){ return TECNICOFS_ERROR_CONNECTION_ERROR; } int n = read(sockfd, &code, sizeof(int)); if (n < 0){ return TECNICOFS_ERROR_CONNECTION_ERROR; } return code; } /* Renomeia o ficheiro com o nome indicado no 1 argumento para o novo nome no 2 argumento. Devolve erro caso nao exista um ficheiro com o nome antigo,o novo nome ja esteja atribuido a um ficheiro, o UID efetivo do processo cliente nao seja o mesmo do dono do ficheiro ou caso o ficheiro esteja aberto. */ int tfsRename(char *filenameOld, char *filenameNew){ int code; int size=strlen(filenameOld)+ strlen(filenameNew)+3; if (sockfd==-1){ return TECNICOFS_ERROR_NO_OPEN_SESSION; } if (dprintf(sockfd, "r %s %s%s", filenameOld, filenameNew, "\0") != size){ return TECNICOFS_ERROR_CONNECTION_ERROR; } int n = read(sockfd, &code, sizeof(int)); if (n < 0){ return TECNICOFS_ERROR_CONNECTION_ERROR; } return code; } /* Abre o ficheiro passado por argumento no modo indicado. Devolve erro caso o ficheiro nao exista, o UID efetivo do processo cliente nao tenha permissao para aceder ao ficheiro ou o processo cliente ja tenha esgotado o número máximo de ficheiros que pode abrir. Retorna o descritor do ficheiro aberto em caso de sucesso. */ int tfsOpen(char *filename, permission mode){ int code; int size= strlen(filename)+4; if (sockfd==-1){ return TECNICOFS_ERROR_NO_OPEN_SESSION; } if (dprintf(sockfd, "o %s %d%s", filename, mode, "\0") != size){ return TECNICOFS_ERROR_CONNECTION_ERROR; } int n = read(sockfd, &code, sizeof(int)); if (n < 0){ return TECNICOFS_ERROR_CONNECTION_ERROR; } return code; } /* Fecha o ficheiro previamente aberto com o descritor de ficheiro passado por argumento. Devolve erro caso o descritor não se refira a nenhum ficheiro aberto. */ int tfsClose(int fd){ int code; int size=3; if (sockfd==-1){ return TECNICOFS_ERROR_NO_OPEN_SESSION; } if (dprintf(sockfd, "x %d%s", fd, "\0") != size){ return TECNICOFS_ERROR_CONNECTION_ERROR; } int n = read(sockfd, &code, sizeof(int)); if (n < 0){ return TECNICOFS_ERROR_CONNECTION_ERROR; } return code; } /* Copia o conteudo do ficheiro aberto ​fd ​para ​buffer. Devolve erro caso o ficheiro nao esteja aberto ou nao tenha sido aberto em modo de leitura ou leitura/escrita. Retorna o numero de caracteres lidos em caso de sucesso. */ int tfsRead(int fd, char *buffer, int len){ int code; int size=5; if (sockfd==-1){ return TECNICOFS_ERROR_NO_OPEN_SESSION; } if (dprintf(sockfd, "l %d %d%s", fd, len -1, "\0") != size){ return TECNICOFS_ERROR_CONNECTION_ERROR; } int n = read(sockfd, &code, sizeof(int)); if (n < 0){ return TECNICOFS_ERROR_CONNECTION_ERROR; } if (code < 0){ return code; }else{ char recvline[101] = {0}; int len = read(sockfd, recvline, 100); if (len < 0){ return TECNICOFS_ERROR_CONNECTION_ERROR; } recvline[len]='\0'; strcpy(buffer,recvline); return len; } } /* Substitui o conteudo do ficheiro aberto por uma copia da ​string ​contida no ​buffer passado como argumento. Devolve erro caso o ficheiro nao esteja aberto ou nao tenha sido aberto em modo de escrita ou leitura/escrita. */ int tfsWrite(int fd, char *buffer, int len){ int code; int size= strlen(buffer)+ 4; char tmpBuffer[len]; if (sockfd==-1){ return TECNICOFS_ERROR_NO_OPEN_SESSION; } if (len>MAX_STRING){ return TECNICOFS_ERROR_OTHER; } tmpBuffer[len]='\0'; strncpy(tmpBuffer,buffer,len); if (dprintf(sockfd, "w %d %s%s", fd, tmpBuffer, "\0") != size){ return TECNICOFS_ERROR_CONNECTION_ERROR; } int n = read(sockfd, &code, sizeof(int)); if (n < 0){ return TECNICOFS_ERROR_CONNECTION_ERROR; } return code; }
C
#include<stdio.h> #include<conio.h> void main() { char a[100],b[100],d[100]; int i=0,x=0,z=0; clrscr(); printf("\nEnter First String: "); gets(a); printf("\nEnter Second String: "); gets(b); while(a[i]!=NULL){ x++; i++; } i=0; while(b[i]!=NULL){ x++; i++; } i=0; while(x!=0){ while(a[i]!=NULL){ d[i]=a[i]; i++; } while(b[z]!=NULL){ d[i]=b[z]; z++; i++; } x--; } d[i]=NULL; printf("\n%s",d); printf("\nThe length of Third String: %d",strlen(d)); getch(); }
C
/** @author yaishenka @date 10.03.2021 */ #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #include <string.h> #include "superblock.h" #include "defines.h" #include "../utils.h" void init_superblock_arrays(struct superblock* superblock) { superblock->reserved_blocks_mask = (bool*) calloc(superblock->fs_info->blocks_count, sizeof(bool)); superblock->reserved_inodes_mask = (bool*) calloc(superblock->fs_info->inodes_count, sizeof(bool)); } void init_superblock_fs_info(struct superblock* superblock) { superblock->fs_info = (struct fs_info*) calloc(1, sizeof(struct fs_info)); } size_t sizeof_superblock(const struct superblock* superblock) { return sizeof(struct fs_info) + sizeof(bool) * superblock->fs_info->inodes_count + sizeof(bool) * superblock->fs_info->blocks_count; } void init_super_block(struct superblock* superblock) { init_superblock_fs_info(superblock); superblock->fs_info->blocks_count_in_inode = BLOCKS_COUNT_IN_INODE; superblock->fs_info->blocks_count = BLOCKS_COUNT; superblock->fs_info->inodes_count = INODES_COUNT; superblock->fs_info->block_size = BLOCK_SIZE; superblock->fs_info->max_path_len = MAX_PATH_LEN; superblock->fs_info->descriptors_count = DESCRIPTORS_COUNT; superblock->fs_info->magic = MAGIC; init_superblock_arrays(superblock); } void destroy_super_block(struct superblock* superblock) { free(superblock->fs_info); free(superblock->reserved_blocks_mask); free(superblock->reserved_inodes_mask); } ssize_t read_super_block(const int fd, struct superblock* superblock) { init_superblock_fs_info(superblock); lseek(fd, 0, SEEK_SET); ssize_t total_read = read_while(fd, (char*) superblock->fs_info, sizeof(struct fs_info)); if (total_read == -1) { fprintf(stderr, "%s", strerror(errno)); free(superblock->fs_info); return -1; } init_superblock_arrays(superblock); ssize_t readed = read_while(fd, (char*) superblock->reserved_inodes_mask, superblock->fs_info->inodes_count); if (readed == -1) { fprintf(stderr, "%s", strerror(errno)); destroy_super_block(superblock); return -1; } total_read += readed; readed = read_while(fd, (char*) superblock->reserved_blocks_mask, superblock->fs_info->blocks_count); if (readed == -1) { fprintf(stderr, "%s", strerror(errno)); destroy_super_block(superblock); return -1; } total_read += readed; return total_read; } ssize_t write_super_block(const int fd, struct superblock* superblock) { lseek(fd, 0, SEEK_SET); ssize_t total_written = write_while(fd, (const char*) superblock->fs_info, sizeof(struct fs_info)); if (total_written == -1) { fprintf(stderr, "%s", strerror(errno)); return -1; } ssize_t written = write_while(fd, (const char*) superblock->reserved_inodes_mask, superblock->fs_info->inodes_count); if (written == -1) { fprintf(stderr, "%s\n", strerror(errno)); return -1; } total_written += written; written = write_while(fd, (const char*) superblock->reserved_blocks_mask, superblock->fs_info->blocks_count); if (written == -1) { fprintf(stderr, "%s\n", strerror(errno)); return -1; } total_written += written; return total_written; } uint16_t reserve_inode(const struct superblock* superblock) { for (uint16_t id = 0; id < superblock->fs_info->inodes_count; ++id) { if (!superblock->reserved_inodes_mask[id]) { superblock->reserved_inodes_mask[id] = true; return id; } } return superblock->fs_info->inodes_count; } uint16_t free_inode(const struct superblock* superblock, const uint16_t inode_id) { if (superblock->reserved_inodes_mask[inode_id]) { superblock->reserved_inodes_mask[inode_id] = false; return inode_id; } return superblock->fs_info->inodes_count; } uint16_t reserve_block(const struct superblock* superblock) { for (uint16_t id = 0; id < superblock->fs_info->blocks_count; ++id) { if (!superblock->reserved_blocks_mask[id]) { superblock->reserved_blocks_mask[id] = true; return id; } } return superblock->fs_info->blocks_count; } uint16_t free_block(const struct superblock* superblock, uint16_t block_id) { if (superblock->reserved_blocks_mask[block_id]) { superblock->reserved_blocks_mask[block_id] = false; return block_id; } return superblock->fs_info->blocks_count; }
C
// parse.c #include <stdio.h> #include <string.h> #include "symtypes.h" unsigned int parseLine( working_t *working, char *schematype ) { unsigned int element; char token[LEN]; int tokpos, linepos=0; for ( element = 0 ; element < MAX_ELEMENTS ; element++ ) { if ( working->line[linepos] == 0 ) break; // Grab the next token tokpos = 0; while ( working->line[linepos] != 0 && working->line[linepos] != ',' && working->line[linepos] != 10 && working->line[linepos] != 13 ) { token[tokpos++] = working->line[linepos++]; } token[tokpos] = 0; switch( schematype[ element ] ) { case 's': strcpy( working->parsedLine[ element ].u.s, token ); working->parsedLine[ element ].type = STRING; break; case 'g': if ( sscanf( token, "%lg", &working->parsedLine[ element ].u.g ) <= 0 ) { working->errorField = element; working->error = 1; } else { working->parsedLine[ element ].type = DOUBLE; } break; case 'd': if ( sscanf( token, "%d", &working->parsedLine[ element ].u.d ) <= 0 ) { working->errorField = element; working->error = 1; } else { working->parsedLine[ element ].type = INT; } break; default: working->errorField = element; working->error = 1; break; } if ( !working->error ) { AddElementToSummary( element, &working->parsedLine[ element ] ); } if ( working->line[linepos-1] == 0 ) break; else linepos++; } if ( element != strlen( schematype ) ) { working->error = 1; } return ( element-1 ); }
C
/* $Author: rr2b $ */ /* $Disclaimer: * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and that * both that copyright notice, this permission notice, and the following * disclaimer appear in supporting documentation, and that the names of * IBM, Carnegie Mellon University, and other copyright holders, not be * used in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. * * IBM, CARNEGIE MELLON UNIVERSITY, AND THE OTHER COPYRIGHT HOLDERS * DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT * SHALL IBM, CARNEGIE MELLON UNIVERSITY, OR ANY OTHER COPYRIGHT HOLDER * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. * $ */ /* ************************************************************ * Copyright (C) 1989, 1990, 1991 * by the Massachusetts Institute of Technology * For full copyright information see:'mit-copyright.h' * *************************************************************/ #include <mit-copyright.h> /* This is the sorting algorithm for the list of papers */ /* June 21 1990 -njw */ /* Version 1: Treesort */ /* The idea is, we build a sorted binary tree with the data * which is, I think O(n.log n) and then with the resultant tree, * go back through the list, rechaining it. (Using left-first traversal * of the tree.) * On the second run thru, where the original list is reordered, * the tree is freed from memory on the fly. */ typedef struct node * Tree; struct node { Tree left; Tree right; Tree parent; Paperlist data; int count; /* Used for the traversal of the tree */ }; void add_node(item, tree, data) Paperlist item; Tree *tree; int data; { Tree n = *tree; Tree oldnode = NULL; int direction; Tree newnode; if (n != NULL) { while (n != NULL) { oldnode = n; direction = compare(n->data, item, data); if (direction <= 0) n = n->left; else n = n->right; } newnode = (Tree) malloc(sizeof(struct node)); /* What if malloc fails? XXX */ newnode->data = item; newnode->left = newnode->right = NULL; newnode->parent = oldnode; if (direction <= 0) oldnode->left = newnode; else oldnode->right = newnode; newnode->count = 0; } else { *tree = (Tree) malloc(sizeof(struct node)); (*tree)->data = item; (*tree)->left = (*tree)->right = (*tree)->parent = NULL; (*tree)->count = 0; } } void sort(papers, data) Paperlist *papers; int data; { Paperlist item; Tree tree = NULL; Tree tmpnode = NULL; Tree nextnode = NULL; int direction = 0; /* 0=left, 1=right */ Paperlist *newlist = papers; /* This is the resorted list */ int firstitem = 1; /* Boolean flag to show when at top of list */ if (!papers || !*papers) return; for (item = *papers; item != NULL; item = item->next) add_node(item, &tree, data); /* We now do a left-first tree traversal, reordering the initial linked list to follow the order of the tree. A node is only ever looked at going down, so whenever there is a move up, the tree node is free'd */ tmpnode = tree; while (tmpnode != NULL) { tmpnode->count++; if (tmpnode->count == 2) { /* This is where we reorder the real list */ if (!firstitem) (*newlist)->next = tmpnode->data; else { *papers = tmpnode->data; firstitem = 0; } newlist = &(tmpnode->data); } if (tmpnode->count == 3) { nextnode = tmpnode->parent; free(tmpnode); /* We destroy the tree as we scan it */ tmpnode = nextnode; } else { if (direction == 0 /* left */) { nextnode = tmpnode->left; } else nextnode = tmpnode->right; if (nextnode) { tmpnode = nextnode; direction = 0 /* always try to go left */; } else if (direction == 1 /* right */) { nextnode = tmpnode->parent; free(tmpnode); /* We destroy the tree as we scan it */ tmpnode = nextnode; } else direction = 1 /* right */; } } /* Close the end of the list */ (*newlist)->next = NULL; }
C
/* TRABALHO 5 - ORGANIZAÇÃO DE ARQUIVOS Nome: Michelle Wingter da Silva nUSP: 10783243 Leonardo Rossi Luiz 10851691 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "funcionalidades.h" #include "rdados.h" #include "manipulaReg.h" #include "organizaArq.h" #include "indice.h" #include "arvoreB.h" /* Funcionalidade [1]: Permite a leitura de vários registros obtidos a partir de um arquivo de entrada (arquivo no formato CSV) e a gravação desses registros em um arquivo de dados de saída. */ void leCsv_SalvaBin(){ char nomeDoArquivo[MAX]; scanf(" %[^\n\r]", nomeDoArquivo); FILE *fp; fp = fopen (nomeDoArquivo, "r"); if (fp == NULL) { printf("Falha no carregamento do arquivo.\n"); return; } /*********CRIANDO REGISTRO DE CABEÇALHO********/ REGCAB *RC; RC = calloc (1, sizeof(REGCAB)); criaRegCabecalho(fp, RC); char nome_bin[MAX]; strcpy(nome_bin, "arquivoTrab1.bin"); FILE *arqBinario = fopen(nome_bin, "wb+"); regCabToArqBin(RC, arqBinario); int tamPag = 32000; int tamRegAnt = 0; /*********CRIANDO REGISTRO DE DADOS********/ REGDADOS* RD; RD = calloc (1, sizeof(REGDADOS)); while(!feof(fp)) { salvaRegistroNaStruct(fp, RD); structToBin(&tamPag, &tamRegAnt, RD, RC, arqBinario); free(RD); RD = calloc (1, sizeof(REGDADOS)); } atualizaStatus(RC, arqBinario); printf("%s",nome_bin); free(RD); free(RC); fclose(fp); fclose(arqBinario); } /* Funcionalidade [2]: Permite a recuperação dos dados, de todos os registros, armazenados no arquivo de dados, mostrando os dados de forma organizada na saída padrão para permitir a distinção dos campos e registros. */ void leBin_PrintBin(){ char nomeDoArquivo[MAX]; scanf(" %[^\n\r]", nomeDoArquivo); lePrintaArqBin(nomeDoArquivo); } /* Funcionalidade [3]: Permite a recuperação dos dados de todos os registros que satisfaçam um critério de busca determinado pelo usuário. */ void buscaBin_Print(){ char nomeBin[MAX], nomeCampo[MAX], valor[MAX]; scanf(" %s %s %[^\r\n]", nomeBin, nomeCampo, valor); FILE* bin = fopen(nomeBin, "rb"); if(bin == NULL){ printf("Falha no processamento do arquivo.\n"); return; } REGCAB* RC; RC = calloc(1, sizeof(REGCAB)); leCabecalho(bin, RC); //lendo o cabeçalho da primeira pagina do arquivo if (RC->status == '0') { printf("Falha no processamento do arquivo.\n"); free(RC); fclose(bin); return; } buscaRegBin(bin, RC, nomeCampo, valor); //buscando o registro free(RC); fclose(bin); } /* Funcionalidade [4]: Permite a remoção lógica de registros, baseado na abordagem dinâmica de reaproveitamento de espaços de registros logicamente removidos. */ void remove_registro(){ char nomeBin[MAX]; int n; //n = numero de vezes que a funcionalidade 4 será executada char nomeCampo[MAX]; char valorCampo[MAX]; scanf(" %s %d", nomeBin, &n); for (int i = 0; i < n; ++i){ scanf("%s", nomeCampo); scan_quote_string(valorCampo); busca_RemoveReg(nomeBin, nomeCampo, valorCampo); } binarioNaTela2(nomeBin); } /* Funcionalidade [5]: Permite a inserção de registros adicionais, baseado na abordagem dinâmica de reaproveitamento de espaços de registros logicamente removidos. */ void insere_registro(){ char nomeBin[MAX]; int n; //n = numero de vezes que a funcionalidade 4 será executada scanf(" %s %d", nomeBin, &n); char idStr[MAX], salStr[MAX], tel[MAX], nome[MAX], cargo[MAX]; REGDADOS *rd; long int ultimo_reg = -1; for (int i = 0; i < n; ++i){ scanf("%s ", idStr); scanf("%s ", salStr); scan_quote_string(tel); scan_quote_string(nome); scan_quote_string(cargo); rd = calloc(1, sizeof(REGDADOS)); criaNovoRegDados2(rd, idStr, salStr, tel, nome, cargo); firstFit_insere(nomeBin, rd, &ultimo_reg); free(rd); } binarioNaTela2(nomeBin); } /* Funcionalidade [6]: Permite a atualização de registros. Os registros a serem atualizados devem ser aqueles que satisfaçam um critério de busca determinado pelo usuário. */ void atualiza_registro(){ char nomeBin[MAX]; int n; //n = numero de vezes que a funcionalidade 4 será executada long int ultimo_reg = -1; scanf(" %s %d", nomeBin, &n); char nomeCampoBusca[MAX]; char valorCampoBusca[MAX]; char nomeCampoAtualiza[MAX]; char valorCampoAtualiza[MAX]; for (int i = 0; i < n; ++i){ scanf("%s", nomeCampoBusca); if(strcmp(nomeCampoBusca, "idServidor") == 0 || strcmp(nomeCampoBusca, "salarioServidor") == 0){ scanf("%s", valorCampoBusca); } else{ scan_quote_string(valorCampoBusca); } scanf("%s", nomeCampoAtualiza); if(strcmp(nomeCampoAtualiza, "idServidor") == 0 || strcmp(nomeCampoAtualiza, "salarioServidor") == 0){ scanf("%s", valorCampoAtualiza); } else{ scan_quote_string(valorCampoAtualiza); } if(strcmp(nomeCampoBusca, nomeCampoAtualiza) != 0 && strcmp(valorCampoBusca, valorCampoAtualiza) != 0){ //verifica se os campos são o mesmo, se for não faz nada busca_atualiza_campo(nomeBin, nomeCampoBusca, valorCampoBusca, nomeCampoAtualiza, valorCampoAtualiza, &ultimo_reg); } } binarioNaTela2(nomeBin); } /* Funcionalidade [7] Realiza a ordenação interna dos dados de um arquivo de dados, considerando os valores do campo idServidor. */ void ordenacao_interna(){ char nomeBin_in[MAX]; /*nome do arquivo binário de entrada que segue as mesmas especificações do primeiro trabalho prático, e que contém dados desordenados e registros logicamente removidos.*/ char nomeBin_out[MAX];/*nome do arquivo binário de saída que segue as mesmas especificações definidas no primeiro trabalho prático, e que contém dados ordenados de forma crescente nos valores do campo idServidor e não contém registros logicamente removidos.*/ scanf(" %s %s", nomeBin_in, nomeBin_out); ordena_por_id(nomeBin_in, nomeBin_out); binarioNaTela2(nomeBin_out); } /* Funcionalidade [8] Realiza a operação cosequencial de merging (união) de dois arquivos de dados, considerando os valores do campo idServidor. */ void merge_twoFiles(){ char nomeBin_in1[MAX]; /*- arquivoEntrada1.bin e arquivoEntrada2.bin são arquivos binários de entrada que seguem as mesmas especificações do primeiro trabalho prático, e que foram ordenados de acordo com as especificações da funcionalidade [7].*/ char nomeBin_in2[MAX]; char nomeBin_out[MAX]; /*nome do arquivo binário de saída que segue as mesmas especificações definidas no primeiro trabalho prático, e que contém dados ordenados de forma crescente nos valores do campo idServidor e não contém registros logicamente removidos.*/ scanf(" %s %s %s", nomeBin_in1, nomeBin_in2, nomeBin_out); read_andMerge(nomeBin_in1, nomeBin_in2, nomeBin_out); binarioNaTela2(nomeBin_out); } /* Funcionalidade [9] Realiza a operação cosequencial de matching (interesecção) de dois arquivos de dados, considerando os valores do campo idServidor. */ void match_twoFiles(){ char nomeBin_in1[MAX]; /*- arquivoEntrada1.bin e arquivoEntrada2.bin são arquivos binários de entrada que seguem as mesmas especificações do primeiro trabalho prático, e que foram ordenados de acordo com as especificações da funcionalidade [7].*/ char nomeBin_in2[MAX]; char nomeBin_out[MAX]; /*nome do arquivo binário de saída que segue as mesmas especificações definidas no primeiro trabalho prático, e que contém apenas todos os registros presentes em ambos arquivoEntrada1 e arquivoEntrada2 . Os registros de arquivoSaida .bin encontram-se ordenados de forma crescente nos valores do campo idServidor. Não devem existir registros repetidos no arquivo de saída..*/ scanf(" %s %s %s", nomeBin_in1, nomeBin_in2, nomeBin_out); read_andMatch(nomeBin_in1, nomeBin_in2, nomeBin_out); binarioNaTela2(nomeBin_out); } /* Funcionalidade [10]: Cria um arquivo de índice secundário fortemente ligado para um arquivo de dados de entrada já existente. O campo a ser indexado é nomeServidor.*/ void cria_arquivoIndice(){ char nomeBin_in[MAX]; char nomeBin_indice[MAX]; //arquivo binário de índice secundário fortemente ligado que indexa o campo nomeServidor. scanf(" %s %s", nomeBin_in, nomeBin_indice); novoIndice(nomeBin_in, nomeBin_indice); binarioNaTela2(nomeBin_indice); } /* Funcionalidade [11]: Permite a recuperação dos dados de todos os registros que satisfaçam um critério de busca determinado pelo usuário sobre o campo nomeServidor, usando o índice secundário fortemente ligado criado na funcionalidade [10].*/ void recuperaDados(){ char nomeBin_in[MAX]; char nomeBin_indice[MAX]; //arquivo binário de índice secundário fortemente ligado que indexa o campo nomeServidor. char nomeServidor[MAX]; char valor[MAX]; scanf(" %s %s %s %[^\r\n]", nomeBin_in, nomeBin_indice, nomeServidor, valor); busca_eRecupera(nomeBin_in, nomeBin_indice, nomeServidor, valor, 0); } /* Funcionalidade [12]: Estenda a funcionalidade [4] descrita no segundo trabalho prático de forma que, depois de cada remoção lógica no arquivo de dados, a chave de busca referente ao registro logicamente removido seja removida do índice secundário fortemente ligado criado na funcionalidade [10].*/ void removeChave(){ char nomeBin_in[MAX]; char nomeBin_indice[MAX]; //arquivo binário de índice secundário fortemente ligado que indexa o campo nomeServidor. int n = 0; //n = numero de vezes que a funcionalidade 12 será executada char nomeCampo[MAX]; char valorCampo[MAX]; scanf(" %s %s %d", nomeBin_in, nomeBin_indice, &n); FILE* bin_indice = fopen(nomeBin_indice, "rb"); check_file_status(bin_indice); //primeiro, carrega-se o indice do disco para a memoria primaria REGCABIND *rc_ind = calloc(1, sizeof(REGCABIND)); rewind(bin_indice); fread(&rc_ind->status,STATUS_TAM,1,bin_indice); fread(&rc_ind->nroRegistros,TAM_TAM,1,bin_indice); REGDADOSIND *rd_ind = calloc(rc_ind->nroRegistros, sizeof(REGDADOSIND)); fseek(bin_indice, TAM_PAG_DISCO, SEEK_SET); for (int i = 0; i < rc_ind->nroRegistros; ++i){ fread(&rd_ind[i].chaveBusca,TAM_CHAVE,1,bin_indice); fread(&rd_ind[i].byteOffset,TAM_BYTEOFFSET,1,bin_indice); } fclose(bin_indice); //============================================================= for (int i = 0; i < n; ++i){ scanf("%s", nomeCampo); if(strcmp(nomeCampo, "idServidor") == 0 || strcmp(nomeCampo, "salarioServidor") == 0){ scanf("%s", valorCampo); } else{ scan_quote_string(valorCampo); } busca_RemoveReg(nomeBin_in, nomeCampo, valorCampo); //rodando a funcionalidade 4 busca_RemoveChave_indice(rd_ind, rc_ind, valorCampo); } listaIndice_toArqIndice(nomeBin_indice, rd_ind, rc_ind); //reescrevendo o indice do zero free(rc_ind); free(rd_ind); binarioNaTela2(nomeBin_indice); } /* Funcionalidade [13]: Estende a funcionalidade [5] descrita no segundo trabalho prático de forma que, depois de cada inserção de registro adicional no arquivo de dados, a chave de busca referente ao registro inserido seja inserida no índice secundário fortemente ligado criado na funcionalidade [10]. */ void insereChave(){ char nomeBin[MAX]; char nomeBin_indice[MAX]; //arquivo binário de índice secundário fortemente ligado que indexa o campo nomeServidor. int n; //n = numero de vezes que a funcionalidade 4 será executada scanf(" %s %s %d", nomeBin, nomeBin_indice, &n); //primeiro, carrega-se o indice do disco para a memoria primaria FILE* bin_indice = fopen(nomeBin_indice, "rb"); check_file_status(bin_indice); REGCABIND *rc_ind = calloc(1, sizeof(REGCABIND)); rewind(bin_indice); fread(&rc_ind->status,STATUS_TAM,1,bin_indice); fread(&rc_ind->nroRegistros,TAM_TAM,1,bin_indice); REGDADOSIND *rd_ind = calloc(rc_ind->nroRegistros, sizeof(REGDADOSIND)); fseek(bin_indice, TAM_PAG_DISCO, SEEK_SET); for (int i = 0; i < rc_ind->nroRegistros; ++i){ fread(&rd_ind[i].chaveBusca,TAM_CHAVE,1,bin_indice); fread(&rd_ind[i].byteOffset,TAM_BYTEOFFSET,1,bin_indice); } fclose(bin_indice); //============================================================= char idStr[MAX], salStr[MAX], tel[MAX], nome[MAX], cargo[MAX]; REGDADOS *rd = NULL; REGDADOSIND *novo = NULL; long int ultimo_reg = -1; FILE *bin_in = fopen(nomeBin, "rb"); fseek(bin_in, 0, SEEK_END); long int pos = ftell(bin_in); fclose(bin_in); for (int i = 0; i < n; ++i){ scanf("%s ", idStr); scanf("%s ", salStr); scan_quote_string(tel); scan_quote_string(nome); scan_quote_string(cargo); if(strcmp(nome, "") != 0){ rd = calloc(1, sizeof(REGDADOS)); novo = calloc(1, sizeof(REGDADOSIND)); criaNovoRegDados2(rd, idStr, salStr, tel, nome, cargo); firstFit_insere(nomeBin, rd, &ultimo_reg); //inserindo no arquivo de dados strcpy(novo->chaveBusca, rd->nomeServidor); novo->byteOffset = pos; rc_ind->nroRegistros++; rd_ind = realloc(rd_ind, rc_ind->nroRegistros * sizeof(REGDADOSIND)); strcpy(rd_ind[rc_ind->nroRegistros - 1].chaveBusca, novo->chaveBusca); rd_ind[rc_ind->nroRegistros - 1].byteOffset = novo->byteOffset; pos = pos + rd->tamanhoRegistro; free(rd); free(novo); } } //ordenando a lista de indices MS_sort(rd_ind, rc_ind->nroRegistros, sizeof(REGDADOSIND), int_compare_byteOffset); MS_sort(rd_ind, rc_ind->nroRegistros, sizeof(REGDADOSIND), int_compare_chave); //passando a lista de indice para o arquivo de indice listaIndice_toArqIndice(nomeBin_indice, rd_ind, rc_ind); binarioNaTela2(nomeBin_indice); free(rc_ind); free(rd_ind); } /* Funcionalidade [14]: Permite a realização de estatísticas considerando a recuperação dos dados de todos os registros que satisfaçam um critério de busca determinado pelo usuário sobre o campo nomeServidor.*/ void estatisticas(){ char nomeBin_in[MAX]; char nomeBin_indice[MAX]; //arquivo binário de índice secundário fortemente ligado que indexa o campo nomeServidor. char nomeCampo[MAX]; char valorCampo[MAX]; scanf(" %s %s %s %[^\r\n]", nomeBin_in, nomeBin_indice, nomeCampo, valorCampo); calculaEstatisticas(nomeBin_in, nomeBin_indice, nomeCampo, valorCampo); } /* Funcionalidade [15]: Cria um arquivo de índice árvore-B para um arquivo de dados de entrada já existente. */ void cria_indice_arvoreB(){ char nomeBin_in[MAX]; char nomeBin_indice[MAX]; scanf(" %s %s", nomeBin_in, nomeBin_indice); cria_arvoreB(nomeBin_in, nomeBin_indice); binarioNaTela2(nomeBin_indice); } /* Funcionalidade [16]: Permite a recuperação dos dados de todos os registros que satisfaçam um critério de busca determinado pelo usuário sobre o campo idServidor, usando o índice árvore-B criado na funcionalidade [15].*/ void recuperaDados_arvoreB(){ char nomeBin_in[MAX]; char nomeBin_indice[MAX]; char idServidor[MAX]; int valor; scanf(" %s %s %s %d", nomeBin_in, nomeBin_indice, idServidor, &valor); FILE* bin_in = fopen(nomeBin_in, "rb"); check_file_status(bin_in); int nivel = 0; long int pos = busca_e_recupera_arvoreB(nomeBin_indice, valor, &nivel); if (pos != -1) { REGCAB *rc = calloc(1, sizeof(REGCAB)); rewind(bin_in); leCabecalho(bin_in, rc); fseek(bin_in, pos, SEEK_SET); int tam_pagina = 0; REGDADOS *rd = calloc(1, sizeof(REGDADOS)); leUmRegistroBin(bin_in, rd, &tam_pagina); printaRegEncontrado(rc, rd); printf("Número de níveis do índice árvore-B percorridos: %d\n", nivel); } else{ printf("Registro inexistente.\n"); } fclose(bin_in); }
C
#include<stdio.h> char lower(char c); int main() { return 0; } char lower(char c) { return (c >= 'A' && c <= 'Z') ? c + 'a' - 'A' : c; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #define BUFFSIZE 4096 int main(int argc, char *argv[]) { int read_len; int write_len; size_t pread_offset = 0; size_t pwrite_offset = 0; char buf[BUFFSIZE]; while((read_len = pread(STDIN_FILENO, buf, BUFFSIZE, pread_offset)) > 0) { pread_offset += read_len; if ((write_len = pwrite(STDOUT_FILENO, buf, read_len, pwrite_offset)) != read_len) { printf("write error"); exit(-1); } pwrite_offset += write_len; } if (read_len < 0) { printf("read error"); exit(-1); } exit(0); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #define N 40 //tamanho do buffer //struct para os elementos typedef struct no { char pal[20]; int urg; struct no *prox; }Elem; //prototipo das funções Elem *criaElemento(char pal[20], int urg); void criaLista(Elem **W, Elem **R); void preencheLista(Elem **W, Elem **R, Elem *elemento); void addElemento(Elem **W, Elem **R, char pal[20], int urg); void rmvElemento(Elem **W, Elem **R, Elem **removido); void liberaBuffer(Elem **W, Elem **R); int main() { //declara os principais ponteiros do programa: W e R Elem *W; Elem *R; //variaveis para armazenar os dados do arquivo int intA; int intB; char word[20]; //declarar as auxiliares para remover Elem *prevR; Elem *valor = (Elem*)malloc(sizeof(Elem)); //cria a lista vazia com os ENDEREÇOS dos ponteiros - passagem por referência altera o conteúdo original criaLista(&W, &R); //abrindo arquivo de entrada e saida FILE *arquivoL = fopen("lidos.dat", "w"); FILE *arquivoP; if((arquivoP = fopen("pacotes.dat", "r"))== NULL) { printf("Não foi possível abrir o arquivo pacotes.dat\nFechando o programa..."); fclose(arquivoP); return 0; } //percorre todo o arquivo fazendo leitura dos dados e copiando para as variaveis locais while(!feof(arquivoP)) { fscanf(arquivoP, "%d %s %d\n", &intA, word, &intB); //printf("%d %s %d\n", intA, word, intB); //logo que aparecer a palavra NULL, já fechamos o programa if(strcmp(word, "NULL") == 0) { break; } //Verificando qual operaçao será feita - 0: write, 1: read (remove) if(intA == 0) { //adiciona o elemento na lista addElemento(&W, &R, word, intB); } else { //guardamos a posiçao anterior ao ponteiro R (tail) na auxiliar prevR prevR = R; //armazena o elemento removido na variavel auxiliar valor rmvElemento(&W, &R, &valor); //ponteiro R nunca pode ser ultrapassado if(prevR != R) { //printamos no arquivo de saida fprintf(arquivoL, "%s\n", valor->pal); } } } //fechando os arquivos fclose(arquivoP); fclose(arquivoL); //ao final, precisamos liberar a memoria alocada para o buffer circular //usamos passagem por referência pois precisa liberar a variável original e não apenas uma copia liberaBuffer(&W, &R); return 0; } //cria novo elemento Elem *criaElemento(char pal[20], int urg) { //alocamos dinamicamente a memoria para o novo elemento Elem *novo = (Elem*)malloc(sizeof(Elem)); //copia todos os dados para a estrutura strcpy(novo->pal, pal); novo->urg = urg; novo->prox = NULL; //ao fim, retornamos o endereço do novo elemento return novo; } //cria lista com todos os campos como 0 void criaLista(Elem **W, Elem **R) { //inicializando as variaveis dos ponteiros como NULL int i; (*W) = NULL; (*R) = NULL; //preenche todos os campos da lista com 0 for(i=0; i<N; i++) { preencheLista(W, R, criaElemento("0", 0)); } //arruma os ponteiros de modo que a lista permaneça ligada (*R) = (*R)->prox; } //preenche a lista com os valores indicados pelo vetor void preencheLista(Elem **W, Elem **R, Elem *elemento) { //preenche a lista com os novos elementos if(!(*W)) //lista vazia { //W e R começam apontando para o mesmo elemento (*W) = elemento; (*R) = elemento; //o proximo elemento de elemento é ele mesmo - deixa a lista circular, mesmo que ela tenha apenas 1 elemento elemento->prox = elemento; } else //lista não vazia { //arruma os ponteiros para que os novos elementos inseridos mantenham a circularidade (*R)->prox = elemento; elemento->prox = (*W); (*R) = elemento; } } //operação de escrita (intA = 0) void addElemento(Elem **W, Elem **R, char pal[20], int urg) { //auxprox simula o próximo elemento de W, para que possamos prosseguir com o teste Elem *auxprox = (*W)->prox; //o ponteiro W nunca pode se encontrar com o ponteiro R - sempre uma posição antes if(auxprox == *R) { return; //printf("\nLista cheia!"); //nao recebe mais elementos } //copia todos os dados para a estrutura strcpy((*W)->pal, pal); (*W)->urg = urg; (*W) = auxprox; } //operação de remoção/leitura (intA = 1) void rmvElemento(Elem **W, Elem **R, Elem **removido) { //inicializando as variáveis locais int i; int salto; //auxprox simula o próximo elemento de R - R não pode passar de W, mas pode ficar em cima Elem *auxprox = (*R)->prox; if(*R == *W) //caso os ponteiros R e W fiquem na mesma posição { return; } //copia todos os dados do elemento removido na variavel removido strcpy((*removido)->pal, (*R)->pal); (*removido)->urg = (*R)->urg; (*removido)->prox = NULL; //caso o elemento lido seja do tipo PRTY, pulamos no máximo urg posiçoes if((strcmp((*R)->pal, "PRTY")) == 0) { //pega o tamanho do salto de PRTY salto = (*R)->urg; for(i=0; i<salto; i++) { if(*R == *W) //caso os ponteiros R e W cheguem na mesma posição { break; } //vai rodando com R (*R) = (*R)->prox; } } //caso não seja um elemento do tipo PRTY, fazemos a remoçao normal - ponteiro R anda uma posição else { (*R) = auxprox; } } //libera a memoria ocupada pelo buffer circular dinâmico void liberaBuffer(Elem **W, Elem **R) { //atual pega o valor de W Elem *atual = (*W); Elem *auxprox; //enquanto não ultrapassarmos o ponteiro W, podemos fazer a liberação - ponteiro R nao pode chegar no W while(atual->prox != (*W)) { //auxprox permite que a memoria seja liberada sem desconectar a lista auxprox = atual->prox; free(atual); atual = auxprox; } //saindo do while, setamos W e R como NULL (*W) = NULL; (*R) = NULL; }
C
#include<string.h> #include<getopt.h> #include<sys/socket.h> #include<arpa/inet.h> #include<netinet/in.h> #include<libev/ev.h> #include<fcntl.h> #include<errno.h> #include<sys/time.h> #include<time.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #define READ_BUF_LEN (4096) #define WRITE_BUF_LEN (4096) #define MAX_URL_LEN (256) #define MAX_HOST_LEN (128) #define ERROR_ON(fd) if(fd < 0) return -1; #define PRINT(format,args...) fprintf(stdout,"[DEBUG]%s:%d->"format,__func__,__LINE__,##args) #ifdef DEBUG #define DEBUG_PRINT(format,args...) fprintf(stdout,"[DEBUG]%s:%d->"format,__func__,__LINE__,##args) #else #define DEBUG_PRINT(format,args...) 1 #endif #define bool int #define true 1 #define false 0 extern char *optarg; extern int optopt; extern int opterr; struct global_data { struct connection ** conns; unsigned int conns_num; }; struct param { char *ip; char *path; char *postdata; char *method; char *headers[100]; unsigned int header_num; unsigned int port; unsigned int n; unsigned int rate; unsigned int intervalus; unsigned int concurrent; int pressure_start_timestamp; // 本connection开始的时间 }; struct connection { unsigned int id;// connection id int request_count; int request_start_timestamp; // 本connection开始的时间 int request_send_timestamp; // 每次发送更新这个时间戳 int request_total_time; // connection 处理请求的总时间,不含由于设置rate而引入的sleep时间 char url[MAX_URL_LEN]; char writebuf[WRITE_BUF_LEN ]; char readbuf[READ_BUF_LEN ]; char host[MAX_HOST_LEN]; unsigned int port; unsigned int fd; struct param * param; }; struct global_data global_data; struct param param; unsigned int g_connection_id = 0; struct connection * new_connection_chain(struct param * param,struct ev_loop *main_loop); int continue_connection(struct connection *conn, struct ev_loop *main_loop); long getCurrentTime() { struct timeval tv; gettimeofday(&tv,NULL); return tv.tv_sec * 1000 + tv.tv_usec / 1000; } void setaddress(const char* ip,int port,struct sockaddr_in* addr) { memset(addr,0, sizeof(*addr)); addr->sin_family=AF_INET; inet_pton(AF_INET,ip,&(addr->sin_addr)); addr->sin_port=htons(port); } int setnonblock(int sockfd) { if (fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFD, 0)|O_NONBLOCK) == -1) { DEBUG_PRINT("set non block err\n"); return -1; } DEBUG_PRINT("set non block ok\n"); return 0; } static int new_connection(const char *ip, unsigned int port) { int ret; struct sockaddr_in addr; int fd = socket(AF_INET, SOCK_STREAM, 0); ERROR_ON(fd); setaddress(ip, port , &addr); ret = connect(fd, (struct sockaddr*)(&addr), sizeof(addr)); if(ret < 0) { PRINT("Connect Error:%d errno:%d %s\n",ret,errno,strerror(errno)); return -2; } ret = setnonblock(fd); if (ret < 0) { PRINT("setnonblock:%d errno:%d %s\n",ret,errno,strerror(errno)); return ret; } DEBUG_PRINT("fd:%d\n",fd); return fd; } int build_http_request(struct connection * conn) { bool add_host = false; bool add_agent = false; bool add_accept = false; char * method = conn->param->method; char * path = conn->param->path; char * body = conn->param->postdata; char * ip = conn->param->ip; char * buf = conn->writebuf; strcpy(buf,method); strcat(buf," "); strcat(buf,path); strcat(buf," HTTP/1.1\r\n"); for(int i=0;i < conn->param->header_num;i++) { strcat(buf,conn->param->headers[i]); strcat(buf,"\r\n"); if (strstr(conn->param->headers[i],"Host: ")) { add_host = true; } if (strstr(conn->param->headers[i],"User-Agent: ")) { add_agent = true; } if (strstr(conn->param->headers[i],"Accept: ")) { add_accept = true; } } if(!add_host) { strcat(buf,"Host: "); strcat(buf,ip); strcat(buf,"\r\n"); } if(!add_accept) { strcat(buf,"Accept: */*\r\n"); } if(!add_agent) { strcat(buf,"User-Agent: hyc\r\n"); } if (strcmp("GET",method) == 0) { strcat(buf,"\r\n"); } else if(strcmp("POST",method) ==0) { strcat(buf,"Content-Length: "); char contentlen[10] = {0}; sprintf(contentlen,"%d",strlen(body)); strcat(buf,contentlen); strcat(buf,"\r\n\r\n"); strcat(buf,body); } else { DEBUG_PRINT("Current not supoorted method",""); return -1; } /* DEBUG_PRINT("request built:\n----------------------------"\ "------------------------------\n%s\n---------"\ "-------------------------------------------------\n",buf); */ return 0; } int flush_connection(struct connection * conn) { int send_index = 0; int total_send_len = strlen(conn->writebuf); conn->request_send_timestamp = getCurrentTime(); while(send_index < total_send_len) { int writelen = write(conn->fd,conn->writebuf+send_index ,total_send_len - send_index); DEBUG_PRINT("send:from %d len %d\n%s\n",send_index,total_send_len-writelen,conn->writebuf); send_index += writelen; if (errno == EAGAIN) { usleep(100); continue; } else if(errno == 0) { break; } else { PRINT("fd:%d writelen:%d errno:%d desc:%s\n",conn->fd, writelen,errno,strerror(errno)); exit(-1); } } return 0; } int receive_connection(struct connection *conn) { DEBUG_PRINT("recv data from fd[%d]\n",conn->fd); conn->request_count ++; int total_recv_len = 0; while(1) { int n = read(conn->fd,conn->readbuf, READ_BUF_LEN); DEBUG_PRINT("recv:%d\n"\ "------------------------------------------"\ "----------------\n%s\n--------------------"\ "--------------------------------------\n",n,conn->readbuf); if (n < 0) { if ( errno == EAGAIN) { DEBUG_PRINT("recv EAGIN ,ret:%d\n",n); break; } else { PRINT("recv err:%d %s %s:%d\n",errno,strerror(errno),conn->param->ip,conn->param->port) ; exit(-2); } } else if( n == 0) { return 0; } DEBUG_PRINT("recv data %d bytes\n",n); total_recv_len += n; } DEBUG_PRINT("conn[%d] http request cnt: %d\n",conn->id, conn->request_count); conn->request_total_time += (getCurrentTime()- conn->request_send_timestamp ); return total_recv_len; } void http_read(struct ev_loop *loop, ev_io *stat, int events) { struct connection *conn = stat->data; int n = receive_connection(conn); if (n >0) { usleep(conn->param->intervalus); if(conn->param->n > 0 && conn->request_count >= conn->param->n ) { PRINT("conn:%d run %d times quit,set :%d\n",conn->id, conn->request_count,conn->param->n); close(stat->fd); ev_io_stop(loop, stat); free(stat); return; } flush_connection(conn); } else { PRINT("remote closed client\n") ; close(stat->fd); ev_io_stop(loop, stat); free(stat); PRINT("reconnect to client:%s:%d\n",conn->param->ip,conn->param->port) ; continue_connection(conn ,loop); } } int continue_connection(struct connection *conn, struct ev_loop *main_loop) { int fd = new_connection(conn->host,conn->port); if (fd < 0 ) { PRINT("fd is %d\n",fd) ; return -1; } struct ev_io * http_readable = (struct ev_io*)malloc(sizeof(struct ev_io)); if (!http_readable) { PRINT("ev_io malloc err %d\n",http_readable) ; return -1; } ev_io_init(http_readable,http_read,fd,EV_READ); http_readable->data = conn; ev_io_start(main_loop,http_readable); conn->id = g_connection_id++ ; conn->fd = fd; flush_connection(conn); } struct connection * new_connection_chain(struct param * param,struct ev_loop *main_loop) { char * ip = param->ip; unsigned port = param->port; int fd = new_connection(ip,port); if (fd < 0 ) { PRINT("fd is %d\n",fd) ; return NULL; } struct ev_io * http_readable = malloc(sizeof(struct ev_io)); if (!http_readable) { PRINT("ev_io malloc err %d\n",http_readable) ; return NULL; } struct connection * conn = malloc(sizeof(struct connection)); if(!conn) { PRINT("conn malloc err \n") ; return NULL; } strncpy(conn->host, ip, MAX_HOST_LEN); conn->port = port; conn->fd = fd; conn->request_count = 0; conn->request_total_time = 0; conn->id = g_connection_id++ ; conn->param = param; ev_io_init(http_readable,http_read,fd,EV_READ); http_readable->data = conn; ev_io_start(main_loop,http_readable); build_http_request(conn); flush_connection(conn); return conn; } void summary(struct global_data *gdata) { int request_cnt = 0; int request_total_time = 0;//请求纯耗时,不含等待时间 float request_qps = 0; struct global_data * data = gdata; int http_pressure_time = getCurrentTime() - data->conns[0]->param->pressure_start_timestamp ;//压测时间 for(int i=0; i< data->conns_num; i++) { int request_cnt_tmp = data->conns[i]->request_count; int request_total_time_tmp = data->conns[i]->request_total_time; float request_qps_tmp = ((float)(request_cnt_tmp)/((float)(http_pressure_time)/1000.0f)); printf("\t\tConnection %3d\n",data->conns[i]->id); printf("Total SendRequest: %d\n",request_cnt_tmp); printf("Total Time : %d ms\n",request_total_time_tmp); printf("Total QPS : %f\n",request_qps_tmp); printf("Request Latency : %f ms\n",(float)request_total_time/request_cnt_tmp); request_qps += request_qps_tmp; request_cnt += data->conns[i]->request_count; request_total_time += data->conns[i]->request_total_time; } printf("\nSummary:\n"); printf("Total PressTime : %d ms\n",http_pressure_time); printf("Total SendRequest: %d\n",request_cnt); printf("Total Time : %d ms\n",request_total_time); printf("Total QPS : %f\n",request_qps); printf("Request Latency : %f ms\n",(float)request_total_time/request_cnt); } static void timer_callback(struct ev_loop *loop,ev_timer *w,int revents) { summary((struct global_data*)w->data); exit(0); } void stop(int sig) { summary(&global_data); exit(0); } int main(int argc , char ** argv) { int i = 0; int c ; int n = -1; unsigned int t = 0; unsigned int concurrent = 1; unsigned int port = 0; unsigned int rate = 0; char * url = NULL; char * host = NULL; char * method = NULL; char * postdata = NULL; char * args_pattern = "c:u:n:h:p:t:X:d:H:r:"; memset(&param, 0, sizeof(param)); opterr = 0; while( (c= getopt(argc, argv , args_pattern)) != -1 ) { switch(c) { case 'c': concurrent = atoi(optarg); // concurrency break; case 'p': port = atoi(optarg); // port break; case 'h': host = optarg; // host break; case 'n': n = atoi(optarg); // request number to send break; case 'H': param.headers[param.header_num++] = optarg; // header break; case 'X': method = optarg; // method break; case 'r': rate = atoi(optarg); // send rate break; case 'd': postdata = optarg; // post data break; case 't': t = atoi(optarg); // time break; case 'u': url = optarg; // url break; default: printf("Usage:%s\n",args_pattern); exit(0); } } if ( concurrent == 0 || url == NULL) { printf("args:%s\n",args_pattern); exit(-1); } signal(SIGINT, stop); param.ip = host; param.port = port; param.path = url; param.n = n; param.rate = rate; param.concurrent=concurrent; param.postdata= postdata; param.method = method?method:"GET"; param.pressure_start_timestamp = getCurrentTime(); if (rate*concurrent) { param.intervalus = 1000000/rate; } printf("HYC runs with %d concurrency, sleep intervalus:%d\n",concurrent,param.intervalus); struct ev_loop *main_loop = ev_default_loop(0); global_data.conns = malloc(sizeof(struct connection *)*concurrent); global_data.conns_num = concurrent; for(i = 0; i< concurrent; i++) { struct connection * conn= new_connection_chain(&param ,main_loop); if (NULL == conn) { printf("new_connection_chain error: %d\n",i); return -1; } global_data.conns[i] = conn; } if ( t > 0 ) { printf("add timer:%ds\n",t); ev_timer timer_watcher; ev_init(&timer_watcher,timer_callback); timer_watcher.data = &global_data; ev_timer_set(&timer_watcher,t,0);// t秒后开始执行,非周期 ev_timer_start(main_loop,&timer_watcher); } ev_run(main_loop, 0); summary(&global_data);// all events is topped ,will comes here free(global_data.conns); }
C
/* ** main.c for exit in /home/knocka_a/repositories/42sh/builtins/my_exit ** ** Made by antoine knockaert ** Login <knocka_a@epitech.net> ** ** Started on Sat May 5 13:57:46 2012 antoine knockaert ** Last update Fri May 18 16:02:36 2012 antoine knockaert */ #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "../../others/others.h" #include "../../42sh.h" #include "../../lib/my.h" void end_history(char *configname, t_hist *hist) { int fd; int flags; t_hist *tmp; char c; flags = O_RDWR | O_CREAT | O_APPEND | O_TRUNC; c = '\n'; tmp = hist; fd = open_configfile(configname, flags, 0644); while (tmp) { write(fd, tmp->cmd, my_strlen(tmp->cmd)); write(fd, &c, 1); tmp = tmp->next; } close(fd); } int my_exit(int ac, char **av, t_glob *glob) { reset_term(); glob->exit = 1; end_history(HISTORY_NAME, glob->hist); if (ac == 1) { glob->exit_code = EXIT_SUCCESS; return (1); } else if (ac == 2) { if (av && av[1]) glob->exit_code = my_getnbr(av[1]); else glob->exit_code = EXIT_SUCCESS; return (1); } return (1); }
C
#include "../lib.h" #include "../lib_list.h" void add_option(sll_s *p_sll, void *option, int is_required, void *data) { if (sizeof(p_sll) > 0) { sll_insert (p_sll, option, data, is_required); } else { my_error("add_option: pleas use a valid generic option list"); } } void **validate_options(char **option, sll_s *optionList) { int i; void *tmp; void ** res; if(is_required(option, optionList) == 0) return; for(i = 0; option, option++, i++) { tmp = check_option(option, optionList); if(tmp != NULL) res[i][] = tmp; } return (res); } void *check_option(char *option, sll_s *optionList) { sll_first(optionList); char *tmp; while (optionList->list != NULL) { tmp = (char*)sll_key(optionList); if (my_strcmp(option, tmp) == 0 ) { return (sll_data(optionList)); } else { sll_next (optionList); } } my_putstr("entry notre found in the option list\n"); return; } int is_required(char **option, sll_ *optionList) { int i; int j; sll_first(optionList); while(optionList->list != NULL) { if(sll_isreq(optionList) == 1) { for(i = 0; option; option++, i++) { if(my_strcmp((char*)sll_key(optionList), option[i][0]) != 0){ my_putstr("a required option is missing"); return (0) } } } sll_next(optionList); } return (1); }
C
/* * @explain: Copyright (c) 2020 WEI.ZHOU. All rights reserved. * The following code is only used for learning and communication, not for illegal and commercial use. * If the code is used, no consent is required, but the author has nothing to do with any problems * and consequences. * * In case of code problems, feedback can be made through the following email address. * <xiaoandx@gmail.com> * * @Description: * @Author: WEI.ZHOU * @Date: 2020-10-21 22:28:37 * @Version: V1.0 * @LastEditTime: 2020-10-24 10:41:10 * @LastEditors: WEI.ZHOU * @Others: * 运行结果: * (1). c1=a,c2=b * c1=97,c2=98 * (2). 如果将4,5行改成:c1=197;c2=198;运行结果如下: * c1=,c2= * c1=-59,c2=-58 * 因为:char只占一个字节,取值范围为 -128 ~ +127; * (3).如果将第3行改为:int c1,c2;运行结果: * c1=a,c2=b * c1=97,c2=98 * 因为:int表示整数,%c是输出字符,a的ASCLL代码为97,b的是98,所以输出c1=a,c2=b。 * %d表示输出十进制整数,所以输出c1=97,c2=98 */ #include <stdio.h> int main() { int c1,c2; c1 = 97; c2 = 98; printf("c1=%c,c2=%c\n", c1, c2); printf("c1=%d,c2=%d\n", c1, c2); return 0; }
C
/*) 2) Elaborar um programa que aceita e valida uma senha com 6 dgitos numricos, que deve ser armazenada em uma string. O usurio tem trs tentativas para acertar a senha, se ultrapassar esse limite, ele deve ser informado. O usurio tambm deve ser informado se ele acertou a senha em at trs tentativas. Dica: Considere que j existe uma senha armazenada na string senhaArmazenada[7]="123456"; */ #include <stdio.h> #include <ctype.h> #include <stdlib.h> int main(void) { char repetir; do { char senhaArmazenada[7]="123456",senhaDigitada[7]; int i,acesso=0,j,contagem=0; for (i=1; i<=3; i++) { printf("Informe a senha: "); setbuf(stdin,NULL); gets(senhaDigitada); for (j=0; j<6; j++) { // printf("%s\n",senhaDigitada); if (senhaDigitada[j]==senhaArmazenada[j]) { contagem++; } } if (contagem==6) { printf("Senha Valida!\n"); acesso=1; break; } } if (acesso==0) { printf("Acesso Negado!"); } printf("\n\nDeseja repetir o processo:(s ou n) "); setbuf(stdin,NULL); scanf("%c",&repetir); repetir=toupper(repetir); } while (repetir=='S'); return 0; }
C
/* * client.c: Write strings for printing in POSIX shared memory object * compile with: * gcc -o client logger_client.c -lpthread -lrt */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <time.h> #include <unistd.h> #include <semaphore.h> #include <sys/mman.h> // Buffer data structures #define MAX_BUFFERS 10 #define LOGFILE "/tmp/example.log" #define SEM_MUTEX_NAME "/sem-mutex" #define SEM_BUFFER_COUNT_NAME "/sem-buffer-count" #define SEM_SPOOL_SIGNAL_NAME "/sem-spool-signal" #define SHARED_MEM_NAME "/posix-shared-mem-example" struct shared_memory { char buf[MAX_BUFFERS][256]; int buffer_index; int buffer_print_index; }; void error(char * msg); int main(int argc, char** argv) { struct shared_memory *shared_mem_ptr; sem_t *mutex_sem, *buffer_count_sem, *spool_signal_sem; int fd_shm; char mybuf[256]; char buf[200], * cp; // mutual exclusion semaphore, mutex_sem if ((mutex_sem = sem_open(SEM_MUTEX_NAME, 0, 0, 0)) == SEM_FAILED) error("sem_open"); // Get shared memory if ((fd_shm = shm_open(SHARED_MEM_NAME, O_RDWR, 0)) == -1) error("shm_open"); if ((shared_mem_ptr = mmap(NULL, sizeof(struct shared_memory), PROT_READ | PROT_WRITE, MAP_SHARED, fd_shm, 0)) == MAP_FAILED) error("mmap"); // counting semaphore, indicating the number of available buffers. if ((buffer_count_sem = sem_open(SEM_BUFFER_COUNT_NAME, 0, 0, 0)) == SEM_FAILED) error("sem_open"); // counting semaphore, indicating the number of strings to be printed. Initial value = 0 if ((spool_signal_sem = sem_open(SEM_SPOOL_SIGNAL_NAME, 0, 0, 0)) == SEM_FAILED) error("sem_open"); printf("Please type a message: "); while (fgets(buf, 198, stdin)) { // remove newline from string int length = strlen(buf); if (buf[length - 1] == '\n') buf[length - 1] = '\0'; // get a buffer: P (buffer_count_sem); if (sem_wait(buffer_count_sem) == -1) error("sem_wait: buffer_count_sem"); /* There might be multiple producers. We must ensure that only one producer uses buffer_index at a time. */ // P (mutex_sem); if (sem_wait(mutex_sem) == -1) error("sem_wait: mutex_sem"); // Critical section time_t now = time(NULL); cp = ctime( & now); int len = strlen(cp); if (*(cp+len-1) == '\n') *(cp+len-1) = '\0'; sprintf(shared_mem_ptr->buf[shared_mem_ptr->buffer_index], "%d: %s %s\n", getpid(), cp, buf); (shared_mem_ptr->buffer_index) ++; if (shared_mem_ptr->buffer_index == MAX_BUFFERS) shared_mem_ptr->buffer_index = 0; // Release mutex sem: V (mutex_sem) if (sem_post(mutex_sem) == -1) error("sem_post: mutex_sem"); // Tell spooler that there is a string to print: V (spool_signal_sem); if (sem_post(spool_signal_sem) == -1) error("sem_post: (spool_signal_sem"); printf("Please type a message: "); } if (munmap(shared_mem_ptr, sizeof(struct shared_memory)) == -1) error("munmap"); exit(0); } // Print system error and exit void error(char * msg) { perror(msg); exit(1); }
C
/* * Author: Manuel Ángel Suárez Álvarez * E-mail Manuel_Angel99@outlook.com * Created: 2016-08-15 16:44:48 * * File: keyboard.h * Description: */ #ifndef KEYBOARD_H #define KEYBOARD_H #include <stdint.h> #include <stdbool.h> #ifdef _cplusplus extern "C" { #endif /* KEYBOARD STATUS REGISTER: Bit 0: Output Buffer Status 0: Output buffer empty, dont read yet 1: Output buffer full, please read me :) Bit 1: Input Buffer Status 0: Input buffer empty, can be written 1: Input buffer full, dont write yet Bit 2: System flag 0: Set after power on reset 1: Set after successfull completion of the keyboard controllers self-test (Basic Assurance Test, BAT) Bit 3: Command Data 0: Last write to input buffer was data (via port 0x60) 1: Last write to input buffer was a command (via port 0x64) Bit 4: Keyboard Locked 0: Locked 1: Not locked Bit 5: Auxiliary Output buffer full PS/2 Systems: 0: Determins if read from port 0x60 is valid If valid, 0=Keyboard data 1: Mouse data, only if you can read from port 0x60 AT Systems: 0: OK flag 1: Timeout on transmission from keyboard controller to keyboard. This may indicate no keyboard is present. Bit 6: Timeout 0: OK flag 1: Timeout PS/2: General Timeout AT: Timeout on transmission from keyboard to keyboard controller. Possibly parity error (In which case both bits 6 and 7 are set) Bit 7: Parity error 0: OK flag, no error 1: Parity error with last byte */ enum keyboard_control_status_masks { keyboard_mask_output_buffer = 1, //00000001 keyboard_mask_input_buffer = 2, //00000010 keyboard_mask_system = 4, //00000100 keyboard_mask_command_data = 8, //00001000 keyboard_mask_locked = 0x10, //00010000 keyboard_mask_auxiliar_buffer = 0x20, //00100000 keyboard_mask_timeout = 0x40, //01000000 keyboard_mask_parity = 0x80 //10000000 }; enum keyboard_commands { set_leds = 0xED, echo = 0xEE, scan_code = 0xF0, identify_kbd = 0xF2, telematics = 0xF3, enable_scanning = 0xF4, disable_scanning= 0xF5, default_params = 0xF6, set_autorepeat = 0xF7, set_make_release= 0xF8, set_make_only = 0xF9, set_all_to_all = 0xFA, set_key_telematic=0xFB, set_key_make_rel= 0xFC, set_key_make_only=0xFD, resend_last_byte =0xDE, reset_and_test = 0xFF }; enum keyboard_responses { ack = 0xFA, resend = 0xFE, test_ok = 0xAA, test_fail= 0xFC, test_error=0xFD }; enum key_codes { KEY_NULL, //0 KEY_BACKSLASH, //1 KEY_1, //2 KEY_2, //3 KEY_3, //4 KEY_4, //5 KEY_5, //6 KEY_6, //7 KEY_7, //8 KEY_8, //9 KEY_9, //10 KEY_0, //11 KEY_QUESTION, //12 KEY_OPEN_QUESTION, //13 KEY_BACKSPACE, //14 KEY_TAB, //15 KEY_Q, //16 KEY_W, //17 KEY_E, //18 KEY_R, //19 KEY_T, //20 KEY_Y, //21 KEY_U, //22 KEY_I, //23 KEY_O, //24 KEY_P, //25 KEY_OPEN_BRACKET, //26 KEY_CLOSE_BRACKED, //27 KEY_ENTER, //28 KEY_CAPS_LOCK, //29 KEY_A, //30 KEY_S, //31 KEY_D, //32 KEY_F, //33 KEY_G, //34 KEY_H, //35 KEY_J, //36 KEY_K, //37 KEY_L, //38 KEY_GNU, //39 KEY_OPEN_BRACE, //40 KEY_CLOSE_BRACE, //41 KEY_LEFT_SHIFT, //42 KEY_GREATER_SMALLER,//43 KEY_Z, //44 KEY_X, //45 KEY_C, //46 KEY_V, //47 KEY_B, //48 KEY_N, //49 KEY_M, //50 KEY_COMMA, //51 KEY_DOT, //52 KEY_UNDERSCORE, //53 KEY_RIGHT_SHIFT, //54 KEY_LEFT_CONTROL, //55 KEY_FUNCTION, //56 KEY_ALT, //57 KEY_SPACEBAR, //58 KEY_ALT_GR, //59 KEY_SUPER, //60 KEY_RIGHT_CLICK, //61 KEY_RIGHT_CONTROL, //62 KEY_ESC, //63 KEY_F1, //64 KEY_F2, //65 KEY_F3, //66 KEY_F4, //67 KEY_F5, //68 KEY_F6, //69 KEY_F7, //70 KEY_F8, //71 KEY_F9, //72 KEY_F10, //73 KEY_F11, //74 KEY_F12, //75 KEY_ARROW_LEFT, //76 KEY_ARROW_DOWN, //77 KEY_ARROW_RIGHT, //78 KEY_ARROW_UP //79 }; bool install_keyboard(void); void disable_keyboard(void); void keyboard_handler(); void reset_buffer(void); bool keyboard_check_key( unsigned char key_code); bool keyboard_get_key_pressed(void); uint16_t keyboard_getch(void); void disable_print(void); void enable_print(void); #ifdef _cplusplus } #endif #endif // KEYBOARD_H
C
#include "global.h" #include "moteur.h" #include "collisions.h" #include "city.h" #include "bender.h" #define NBROBOTS 3 // Number of robots #define NBBUILDINGS 12 // Number of buildings #define TURNING 0 // IA action #define MOVING 1 // IA action #define ARROW_UP 0 // Constants for arrow keys #define ARROW_DOWN 1 #define ARROW_LEFT 2 #define ARROW_RIGHT 3 // Controls int arrowKeys[4]; int mouseButton[3]; int speedBoost = 1; int mouse_pos_x = 0, mouse_pos_y = 0; // Camera double cameraPosition[3]; // Position of the camera double cameraDirection[3]; // Direction the camera looks in. double phi; // Vertical angle of the camera double theta; // Horizontal angle of the camera double sensitivity = .5; // Sensitivity of the mouse motion double cameraSpeed = 1.0; // Speed of the camera when it's moving int cameraKeys[4]; // Keys for controlling the camera int follows; // Associated to the robot currently being followed. // If equal to NBROBOTS, then no robot is being followed and the FreeFly camera mode is activated. // Robots Bender robot[NBROBOTS]; // Array of robots. // Buildings double buildingPosition[NBBUILDINGS][3]; // Array of buildings. int buildingType[NBBUILDINGS]; // Type of each building, either TYPE_BOX or TYPE_CYLINDER // Main function int main(int argc, char* argv[]) { int i; char *chemin; // Glut initializations glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(400, 400); glutInitWindowPosition(100, 100); glutCreateWindow("Projet OpenGl - Bender"); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glClearColor(0.5,0.5,0.5, 1); // Glut callback functions glutReshapeFunc(&window_reshape); glutDisplayFunc(&window_display); glutKeyboardFunc(&window_key); glutKeyboardUpFunc(&window_key_up); glutMouseFunc(&window_mouseFunc); glutMotionFunc(&window_motionFunc); glutSpecialFunc(&window_specialDownFunc); glutSpecialUpFunc(&window_specialUpFunc); glutTimerFunc(40, &window_timer, 0); // Program variables initialization initControls(); initCamera(); initBuildings(); // Fetching the path for the texture directory. chemin = (char*)malloc(100); chemin[0]='\0'; strcat(chemin, argv[0]); for(i=99;i>=0;i--) { if(chemin[i]=='/' || chemin[i]=='\\') { chemin[i+1]='\0'; i=-1; } } // Buildings and robots list initialization makeBender(chemin); createCity(chemin); free(chemin); glutMainLoop(); return EXIT_FAILURE; } // Initializes the program controls and the robots. void initControls() { int i; srand(time(NULL)); // Clock initialization // Control keys and mouse buttons initialization for(i=0; i<4; i++) arrowKeys[i] = 0; for(i=0; i<3; i++) mouseButton[i] = 0; // Robot initialization for (i=0; i<NBROBOTS; i++) { initBender(robot+i); robot[i].position[0] = 0+i*5; robot[i].position[1] = 0+i*5; robot[i].position[2] = 0; robot[i].direction[0] = 1.0; robot[i].direction[1] = 0.0; robot[i].direction[2] = 0.0; robot[i].angle = 0.0; robot[i].action = 1; robot[i].endActionTime = clock() - 1000; } } // Initializes the camera. void initCamera() { int i; for(i=0; i<4; i++) cameraKeys[i] = 0; cameraPosition[0] = 0; cameraPosition[1] = 2; cameraPosition[2] = 5; follows = NBROBOTS; // We start the camera in FreeFly mode phi = -20; theta = -90; processCameraChange(); // Computes the direction vector. } // Initializes the buildings. void initBuildings() { buildingType[0] = 11; buildingPosition[0][0] = 20; buildingPosition[0][1] = 0; buildingPosition[0][2] = 20; buildingType[1] = 12; buildingPosition[1][0] = 30; buildingPosition[1][1] = 0; buildingPosition[1][2] = -90; buildingType[2] = 13; buildingPosition[2][0] = 60; buildingPosition[2][1] = 0; buildingPosition[2][2] = 80; buildingType[3] = 14; buildingPosition[3][0] = -10; buildingPosition[3][1] = 0; buildingPosition[3][2] = -60; buildingType[4] = 15; buildingPosition[4][0] = -15; buildingPosition[4][1] = 0; buildingPosition[4][2] = -15; buildingType[5] = 16; buildingPosition[5][0] = -30; buildingPosition[5][1] = 0; buildingPosition[5][2] = 20; buildingType[6] = 17; buildingPosition[6][0] = -70; buildingPosition[6][1] = 0; buildingPosition[6][2] = -60; buildingType[7] = 18; buildingPosition[7][0] = 100; buildingPosition[7][1] = 0; buildingPosition[7][2] = 50; buildingType[8] = 19; buildingPosition[8][0] = -100; buildingPosition[8][1] = 0; buildingPosition[8][2] = -120; buildingType[9] = 20; buildingPosition[9][0] = -110; buildingPosition[9][1] = 0; buildingPosition[9][2] = 80; buildingType[10] = 21; buildingPosition[10][0] = -110; buildingPosition[10][1] = 0; buildingPosition[10][2] = 80; buildingType[11] = 22; buildingPosition[11][0] = -90; buildingPosition[11][1] = 0; buildingPosition[11][2] = -60; } // Renders the scene. void render_scene() { int i; glRotatef(-90, 1,0,0); // Robot rendering for(i=0; i<NBROBOTS; i++) { glPushMatrix(); glTranslatef(robot[i].position[0], robot[i].position[1], robot[i].position[2]); glRotatef((robot[i].angle+1.5) * 180.0 / M_PI, 0, 0, 1); // Draws Bender, with more or less precision, depending on // the expected rendering speed, and whether the robot is being controlled or not. if (i == follows || NBROBOTS <=3) drawBender(100, robot+i); else drawBender(50, robot+i); glPopMatrix(); } // Environment rendering glPushMatrix(); glCallList(10); // Displays the city glPopMatrix(); glutSwapBuffers(); } GLvoid window_display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); processCameraChange(); render_scene(); glFlush(); } GLvoid window_reshape(GLsizei width, GLsizei height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(70,(double)width/height,0.001,1000); glMatrixMode(GL_MODELVIEW); processCameraChange(); } // Handles the normal keys press events. GLvoid window_key(unsigned char key, int x, int y) { switch(key) { case 'z': // Camera move forward cameraKeys[ARROW_UP] = 1; break; case 's': // Camera move backward cameraKeys[ARROW_DOWN] = 1; break; case 'q': // Camera move to the left cameraKeys[ARROW_LEFT] = 1; break; case 'd': // Camera move to the right cameraKeys[ARROW_RIGHT] = 1; break; case 'c': // Change view, either to the next robot or to FreeFly camera view. follows = (follows+1)%(NBROBOTS+1); break; case ' ': // Exits the program. exit(EXIT_SUCCESS); break; default: break; } } // Handles the normal keys release events. GLvoid window_key_up(unsigned char key, int x, int y) { switch(key) { case 'z': // Camera move forward cameraKeys[ARROW_UP] = 0; break; case 's': // Camera move backward cameraKeys[ARROW_DOWN] = 0; break; case 'q': // Camera move to the left cameraKeys[ARROW_LEFT] = 0; break; case 'd': // Camera move to the right cameraKeys[ARROW_RIGHT] = 0; break; default: break; } } // Handles the mouse button events. GLvoid window_mouseFunc(int button, int state, int x, int y) { mouseButton[button] = (state==GLUT_DOWN) ? 1 : 0; if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON) { mouse_pos_x = x; mouse_pos_y = y; glPushMatrix(); } else glPopMatrix(); } // Handles the mouse motion events. GLvoid window_motionFunc(int x, int y) { if (follows == NBROBOTS && mouseButton[0]) // If the left mouse button is pressed { // then change the direction the camera is looking in. theta += (x - mouse_pos_x)*sensitivity; phi -= (y - mouse_pos_y)*sensitivity; mouse_pos_x = x; mouse_pos_y = y; processCameraChange(); glutPostRedisplay(); } } // Handles the special keys press events. void window_specialDownFunc(int key, int x, int y) { // If shift is pressed, then make the camera / robots move faster. speedBoost = (glutGetModifiers() == GLUT_ACTIVE_SHIFT) ? 2 : 1; switch(key) { case GLUT_KEY_UP: // Move forward arrowKeys[ARROW_UP] = 1; break; case GLUT_KEY_DOWN: // Move backward arrowKeys[ARROW_DOWN] = 1; break; case GLUT_KEY_LEFT: // Turn left arrowKeys[ARROW_LEFT] = 1; break; case GLUT_KEY_RIGHT: // Turn right arrowKeys[ARROW_RIGHT] = 1; break; default: break; } } // Handles the special keys release events. void window_specialUpFunc(int key, int x, int y) { // If shift is pressed, then make the camera / robots move faster. speedBoost = (glutGetModifiers() == GLUT_ACTIVE_SHIFT) ? 2 : 1; switch(key) { case GLUT_KEY_UP: // Move forward arrowKeys[ARROW_UP] = 0; break; case GLUT_KEY_DOWN: // Move backward arrowKeys[ARROW_DOWN] = 0; break; case GLUT_KEY_LEFT: // Turn left arrowKeys[ARROW_LEFT] = 0; break; case GLUT_KEY_RIGHT: // Turn right arrowKeys[ARROW_RIGHT] = 0; break; default: break; } } // Main updater function. // Is called every 40ms, and updates the position // of both the camera and the robots. GLvoid window_timer() { int i, robotIndex=0; double speed = .5; // Speed at which a robot moves. double angleIncrement = 1.0/18.0; // Speed at which a robot turns. double* leftDirection; // For the camera, direction when moving to the left. double tempPosition[3]; // Expected position of the robot, used to predict collisions. glutTimerFunc(40,&window_timer,0); // Call this function again over 40ms. // Robot control for(robotIndex=0; robotIndex<NBROBOTS; robotIndex++) // For every robot { if (robotIndex == follows) // If the robot is being controlled, then update its direction // and position based on the pressed keys. { if (arrowKeys[ARROW_LEFT] && !arrowKeys[ARROW_RIGHT]) { // Turn left robot[robotIndex].angle += angleIncrement; if (robot[robotIndex].angle>= M_PI) robot[robotIndex].angle -= 2*M_PI; robot[robotIndex].direction[0] = cos (robot[robotIndex].angle); robot[robotIndex].direction[1] = sin (robot[robotIndex].angle); } else if (arrowKeys[ARROW_RIGHT] && !arrowKeys[ARROW_LEFT]) { // Turn right robot[robotIndex].angle -= angleIncrement; if (robot[robotIndex].angle < -M_PI) robot[robotIndex].angle += 2*M_PI; robot[robotIndex].direction[0] = cos (robot[robotIndex].angle); robot[robotIndex].direction[1] = sin (robot[robotIndex].angle); } if (arrowKeys[ARROW_UP] && !arrowKeys[ARROW_DOWN]) { // Move forward tempPosition[0] = robot[robotIndex].position[0] + speed*robot[robotIndex].direction[0]*speedBoost; tempPosition[1] = robot[robotIndex].position[1] + speed*robot[robotIndex].direction[1]*speedBoost; if (checkCollision(tempPosition, robotIndex) == 0) // If the robot won't collide, move it forward. { robot[robotIndex].position[0] = tempPosition[0]; robot[robotIndex].position[1] = tempPosition[1]; setAllCoords(speedBoost, robot+robotIndex); // Animate the robot. } } else if (arrowKeys[ARROW_DOWN] && !arrowKeys[ARROW_UP]) { // Move backward tempPosition[0] = robot[robotIndex].position[0] - speed*robot[robotIndex].direction[0]*speedBoost; tempPosition[1] = robot[robotIndex].position[1] - speed*robot[robotIndex].direction[1]*speedBoost; if (checkCollision(tempPosition, robotIndex) == 0) // If the robot won't collide, move it backward { robot[robotIndex].position[0] = tempPosition[0]; robot[robotIndex].position[1] = tempPosition[1]; setAllCoords(-speedBoost, robot+robotIndex); // Animate the robot. } } } else // If the robot is not being controlled, then update its direction // based on the artificial intelligence's decisions. { // Explaining of how the artificial intelligence works. // Robots successively alternate between turning and moving forward. // They do each of these actions for a limited period of time. // If the robot collides with an other object, then it will keep on turning // until its action is set back to MOVING and is expected not to collide. if (robot[robotIndex].endActionTime < clock()) { // The following action will be finished in 300ms to 2 seconds. robot[robotIndex].endActionTime = clock() + (rand()%17 + 3) * 100; // We change the robot's action. robot[robotIndex].action = (robot[robotIndex].action == TURNING) ? MOVING : TURNING; if (robot[robotIndex].action == TURNING) // Determines the direction to which the robot will turn, left or right; robot[robotIndex].angleDirection = (rand() % 2) * 2 - 1; // -1 or +1. } if (robot[robotIndex].action == TURNING) // The robot turns. { // Updates its direction. robot[robotIndex].angle += angleIncrement * robot[robotIndex].angleDirection; if (robot[robotIndex].angle>= M_PI) robot[robotIndex].angle -= 2*M_PI; else if (robot[robotIndex].angle < -M_PI) robot[robotIndex].angle += 2*M_PI; robot[robotIndex].direction[0] = cos (robot[robotIndex].angle); robot[robotIndex].direction[1] = sin (robot[robotIndex].angle); } else // action == MOVING. The robot moves forward. { tempPosition[0] = robot[robotIndex].position[0] + speed*robot[robotIndex].direction[0]; tempPosition[1] = robot[robotIndex].position[1] + speed*robot[robotIndex].direction[1]; if (checkCollision(tempPosition, robotIndex) == 0) // If the robot won't collide, move it forward { robot[robotIndex].position[0] = tempPosition[0]; robot[robotIndex].position[1] = tempPosition[1]; setAllCoords(speedBoost, robot+robotIndex); // Animate the robot. } else { robot[robotIndex].endActionTime = clock() - 1000; robot[robotIndex].action = MOVING; // Will be set to TURNING at the next update. } } } } // Camera control if (cameraKeys[ARROW_LEFT] && !cameraKeys[ARROW_RIGHT]) { // Move left leftDirection = getDirectionToLeft(); for(i=0; i<3; i++) cameraPosition[i] += leftDirection[i]*cameraSpeed*speedBoost; free(leftDirection); } else if (cameraKeys[ARROW_RIGHT] && !cameraKeys[ARROW_LEFT]) { // Move right leftDirection = getDirectionToLeft(); for(i=0; i<3; i++) cameraPosition[i] -= leftDirection[i]*cameraSpeed*speedBoost; free(leftDirection); } if (cameraKeys[ARROW_UP] && !cameraKeys[ARROW_DOWN]) { // Move forward for (i=0; i<3; i++) cameraPosition[i] += cameraDirection[i]*cameraSpeed*speedBoost; } else if (cameraKeys[ARROW_DOWN] && !cameraKeys[ARROW_UP]) { // Move backward for (i=0; i<3; i++) cameraPosition[i] -= cameraDirection[i]*cameraSpeed*speedBoost; } // When the user presses on the right mouse button or on the mouse wheel button, // the camera will move up or downward. if (mouseButton[1] && !mouseButton[2]) // Downward cameraPosition[1] -= .5; else if (mouseButton[2] && !mouseButton[1]) // Upward cameraPosition[1] += .5; glutPostRedisplay(); } // Updates the camera position. void processCameraChange() { double r; if (follows != NBROBOTS) // If a robot is being followed // Then place the camera behind the robot. gluLookAt(robot[follows].position[0] - 10*robot[follows].direction[0], 10, - robot[follows].position[1] + 10*robot[follows].direction[1], robot[follows].position[0], robot[follows].position[2] + 5, -robot[follows].position[1], 0, 1, 0); else { // Limit the vertical angle. if (phi > 89) phi = 89; else if (phi < -89) phi = -89; // Compute the camera direction, then update the camera. r = cos(phi*M_PI/180); cameraDirection[0] = r * cos(theta*M_PI/180); cameraDirection[1] = sin(phi*M_PI/180); cameraDirection[2] = r * sin(theta*M_PI/180); gluLookAt(cameraPosition[0], cameraPosition[1], cameraPosition[2], cameraPosition[0] + cameraDirection[0], cameraPosition[1] + cameraDirection[1], cameraPosition[2] + cameraDirection[2], 0, 1, 0); } } // Returns the vector that would make the camera go left. // Warning : Return value must be freed. double* getDirectionToLeft() { double up[3] = {0, 1, 0}; double* left = (double*) malloc(sizeof(double) * 3); double norme=0; int i; left[0] = up[1]*cameraDirection[2] - up[2]*cameraDirection[1]; left[1] = up[2]*cameraDirection[0] - up[0]*cameraDirection[2]; left[2] = up[0]*cameraDirection[1] - up[1]*cameraDirection[0]; for(i=0; i<3; i++) norme += cameraDirection[i]*cameraDirection[i]; norme = sqrt(norme); for(i=0; i<3; i++) left[i] /= norme; return left; } // Checks if a robot is going to collide it is positionned at robotPosition. // robotPosition : Predicted position of the robot. // robotIndex : Index of the current robot in the robot array. // Returns 1 if there will be a collision, 0 otherwise. int checkCollision(double robotPosition[3], int robotIndex) { int i=0; int collision = 0; Object** bender = getBender(robotPosition); // Bounding shapes of the robot. One as a box, the other as a cylinder. // Each will be used for collisions with an object of the same type. Object** otherBender; // Represents the bounding shapes of other robots. Object* building; // Represents the bounding shape of the buildings. // Check if it collides with the other robots. for(i = 0; i<NBROBOTS && collision == 0; i++) { if (i != robotIndex) { otherBender = getBender(robot[i].position); if (inCollision(bender[TYPE_CYLINDER], otherBender[TYPE_CYLINDER])) collision = 1; free(otherBender[0]); free(otherBender[1]); free(otherBender); } } // Check if it collides with buildings. for(i = 0; i<NBBUILDINGS && collision == 0; i++) { building = getBuilding(buildingPosition[i], buildingType[i]); if (inCollision(bender[building->type], building)) collision = 1; free(building); } free(bender[0]); free(bender[1]); free(bender); return collision; }
C
/* * Leds.c * * Created: 4/13/2014 8:27:29 PM * Author: paul */ #include <util/delay.h> #include "Leds.h" #include "config/BoardConfig.h" static const uint8_t LedConfig_Pins[BOARDCONFIG_LEDCOUNT] = { LED0PIN, LED1PIN, LED2PIN, LED3PIN, LED4PIN, LED5PIN, LED6PIN, LED7PIN}; volatile static uint8_t *LedConfig_Ports[BOARDCONFIG_LEDCOUNT] = { LED0PORT, LED1PORT, LED2PORT, LED3PORT, LED4PORT, LED5PORT, LED6PORT, LED7PORT}; static Leds_Frame currentFrame; volatile static uint8_t *lastPort = LED0PORT; static uint8_t lastPin = LED0PIN; /************************************************************************/ /* PRIVATE FUNCTION DECLARATIONS */ /************************************************************************/ //... /************************************************************************/ /* PUBLIC FUNCTION IMPLEMENTATIONS */ /************************************************************************/ // Driver initialization void Leds_Init(void) { lastPort = LED0PORT; lastPin = LED0PIN; /* TODO: 2 is a magic number used through-out; let's abstract this into a global setting, so we can go up to BOARDCONFIG_LEDCOUNT colors, and possibly define this via USB feature setting */ Leds_SetWhite(); } // Main task; should be called often, i.e. in a main loop void Leds_Task(void) { uint8_t i; for(i = 0; i < 8; i++) { uint8_t bit = 0xff; uint8_t red = currentFrame.Colors[i].Red; uint8_t green = currentFrame.Colors[i].Green; uint8_t blue = currentFrame.Colors[i].Blue; if(red == 0 && green == 0 && blue == 0) { bit = 0x00; } RED = red; GRN = green; BLU = blue; //turn off last port-pin combo *lastPort &= ~(_BV(lastPin)); if(bit > 0x00) { // Turn on the current LED *LedConfig_Ports[i] |= _BV(LedConfig_Pins[i]); } //Set new last port-pin combo lastPort = LedConfig_Ports[i]; lastPin = LedConfig_Pins[i]; // TODO: add some microsecond delay here or not? _delay_us(200); } //turn off final port-pin combo *lastPort &= ~(_BV(lastPin)); } void Leds_Clear(void) { } void Leds_SetWhite(void) { int i = 0; for(i = 0; i < 24; i++) { currentFrame.RawData[i] = 0xff; } } void Leds_SetColor(uint8_t index, Leds_Color color) { //if(((color.Red == color.Green) == color.Blue) == 0x00) //{ //currentFrame.LedState.RawData &= ~(_BV(index)); //} //else //{ //currentFrame.LedState.RawData |= _BV(index); //} currentFrame.Colors[index] = color; } /************************************************************************/ /* PRIVATE FUNCTIONS */ /************************************************************************/ //...
C
#include "function_pointers.h" /** * array_iterator - perform an action on each element of an array * @array: the array to iterate over * @size: the size of array * @action: the action to perform on each array element * * Return: void */ void array_iterator(int *array, size_t size, void (*action)(int)) { if (array && action) { while (size--) action(*array++); } }
C
// Simple example of client. // Client prints received messages to stdout and sends from stdin. #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <signal.h> #include <unistd.h> #include <sys/select.h> #include <netinet/in.h> #include <stdlib.h> #include <string.h> #include "message.h" peer_t server; void shutdown_properly(int code); void handle_signal_action(int sig_number) { if (sig_number == SIGINT) { printf("SIGINT was catched!\n"); shutdown_properly(EXIT_SUCCESS); } else if (sig_number == SIGPIPE) { printf("SIGPIPE was catched!\n"); shutdown_properly(EXIT_SUCCESS); } } int setup_signals() { struct sigaction sa; sa.sa_handler = handle_signal_action; if (sigaction(SIGINT, &sa, 0) != 0) { perror("sigaction()"); return -1; } if (sigaction(SIGPIPE, &sa, 0) != 0) { perror("sigaction()"); return -1; } return 0; } int get_client_name(int argc, char **argv, char *client_name) { if (argc > 1) strcpy(client_name, argv[1]); else strcpy(client_name, "no name"); return 0; } int connect_server(peer_t *server) { // create socket server->socket = socket(AF_INET, SOCK_STREAM, 0); if (server->socket < 0) { perror("socket()"); return -1; } // set up addres struct sockaddr_in server_addr; memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(SERVER_IPV4_ADDR); server_addr.sin_port = htons(SERVER_LISTEN_PORT); server->addres = server_addr; if (connect(server->socket, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) != 0) { perror("connect()"); return -1; } printf("Connected to %s:%d.\n", SERVER_IPV4_ADDR, SERVER_LISTEN_PORT); return 0; } int build_fd_sets(peer_t *server, fd_set *read_fds, fd_set *write_fds, fd_set *except_fds) { FD_ZERO(read_fds); FD_SET(STDIN_FILENO, read_fds); FD_SET(server->socket, read_fds); FD_ZERO(write_fds); // there is smth to send, set up write_fd for server socket if (server->send_buffer.current > 0) FD_SET(server->socket, write_fds); FD_ZERO(except_fds); FD_SET(STDIN_FILENO, except_fds); FD_SET(server->socket, except_fds); return 0; } int handle_read_from_stdin(peer_t *server, char *client_name) { char read_buffer[DATA_MAXSIZE]; // buffer for stdin if (read_from_stdin(read_buffer, DATA_MAXSIZE) != 0) return -1; // Create new message and enqueue it. message_t new_message; prepare_message(client_name, read_buffer, &new_message); print_message(&new_message); if (peer_add_to_send(server, &new_message) != 0) { printf("Send buffer is overflowed, we lost this message!\n"); return 0; } printf("New message to send was enqueued right now.\n"); return 0; } /* You should be careful when using this function in multythread program. * Ensure that server is thread-safe. */ void shutdown_properly(int code) { delete_peer(&server); printf("Shutdown client properly.\n"); exit(code); } int handle_received_message(message_t *message) { printf("Received message from server.\n"); print_message(message); return 0; } int main(int argc, char **argv) { if (setup_signals() != 0) exit(EXIT_FAILURE); char client_name[256]; get_client_name(argc, argv, client_name); printf("Client '%s' start.\n", client_name); create_peer(&server); if (connect_server(&server) != 0) shutdown_properly(EXIT_FAILURE); /* Set nonblock for stdin. */ int flag = fcntl(STDIN_FILENO, F_GETFL, 0); flag |= O_NONBLOCK; fcntl(STDIN_FILENO, F_SETFL, flag); fd_set read_fds; fd_set write_fds; fd_set except_fds; printf("Waiting for server message or stdin input. Please, type text to send:\n"); // server socket always will be greater then STDIN_FILENO int maxfd = server.socket; while (1) { // Select() updates fd_set's, so we need to build fd_set's before each select()call. build_fd_sets(&server, &read_fds, &write_fds, &except_fds); int activity = select(maxfd + 1, &read_fds, &write_fds, &except_fds, NULL); switch (activity) { case -1: perror("select()"); shutdown_properly(EXIT_FAILURE); case 0: // you should never get here printf("select() returns 0.\n"); shutdown_properly(EXIT_FAILURE); default: /* All fd_set's should be checked. */ if (FD_ISSET(STDIN_FILENO, &read_fds)) { if (handle_read_from_stdin(&server, client_name) != 0) shutdown_properly(EXIT_FAILURE); } if (FD_ISSET(STDIN_FILENO, &except_fds)) { printf("except_fds for stdin.\n"); shutdown_properly(EXIT_FAILURE); } if (FD_ISSET(server.socket, &read_fds)) { if (receive_from_peer(&server, &handle_received_message) != 0) shutdown_properly(EXIT_FAILURE); } if (FD_ISSET(server.socket, &write_fds)) { if (send_to_peer(&server) != 0) shutdown_properly(EXIT_FAILURE); } if (FD_ISSET(server.socket, &except_fds)) { printf("except_fds for server.\n"); shutdown_properly(EXIT_FAILURE); } } printf("And we are still waiting for server or stdin activity. You can type something to send:\n"); } return 0; }
C
#include <stdio.h> /* for getline, stdin */ #include <memory.h> /* for strtok, strlen, strcmp */ #include <stdlib.h> /* for malloc, free, strtoll */ #include <stdbool.h> /* for bool, true, false */ #include "../include/commandParsing.h" bool isNumOfParametersCorrect(Command *command, int numOfParameters); bool parseCommandType(Command *command, char *firstpart); /** * Reads a single line of code, determines if it is a valid command * and if so updates `command` members accordingly. * This is the only function with global scope to be used by main code * @param command The command in which to store info. Namely, its type is set as an appropriate value from * `enum commandCodes` and if it was a valid command it also sets `numOfWords` and members of `words` attributes. * If it was not a valid command, `command.Type` is set to `_INVALID_`. * @return 0 if a valid command was parsed, non-zero otherwise */ int parseCommand(Command *command){ int i; // cleaning up memory from previous execution for (i=0; i< command->numOfWords; i++) free(command->words[i]); for (i=0; i<10; i++) command->words[i] = NULL; char *line = NULL; // buffer to store input line unsigned long inputSize=0; // setting its size 0 and line to NULL // will make getline to allocate space getline(&line, &inputSize, stdin); // read input line if (strlen(line) ==1){ // a single newline character command->type = BLNK; free(line); return 0; } char *firstpart, *part; // need them for strtok calls firstpart = strtok(line, " \t\n"); // store the first word to determine command type if (!firstpart){ // empty line free(line); return -5; } if (! parseCommandType(command, firstpart)){ // find what command it is by its first word // invalid first word free(line); return -1; } int numOfParameters = 0; while ((part = strtok(NULL, " \t\n")) != NULL){ // parse command parameters one by one if (++numOfParameters > 10) break; // more than 10 words, ignore the rest if (numOfParameters == 1 && command->type == TF){ // if we are dealing with a TF command command->paramId = (int) strtoll(part, NULL, 10); // first word should be the ID (int) }else{ // normalize term index // cause TF needs int as first arg so not a word int wordIndex = (command->type == TF) ? numOfParameters-2 : numOfParameters-1; command->words[wordIndex] = malloc((1+strlen(part))*sizeof(char)); strcpy(command->words[wordIndex], part); // store that word in command } } free(line); if (numOfParameters > 10) numOfParameters--; // if words are more than 10 its value will be 11 command->numOfWords = (command->type == TF) ? numOfParameters -1 : numOfParameters; // the same issue with TF if (! isNumOfParametersCorrect(command, numOfParameters)){ // malformed command return -2; } return 0; } /** * Use string comparisons to determine the type of each command * @param command The command to update its `Type` * @param firstpart the first word of the input * @return `true` if it was a valid command type, `false` otherwise */ bool parseCommandType(Command *command, char *firstpart){ if (!strcmp(firstpart, "/search")){ command->type = SRCH; }else if (!strcmp(firstpart, "/df")){ command->type = DF; }else if (!strcmp(firstpart, "/tf")){ command->type = TF; }else if (!strcmp(firstpart, "/exit")){ command->type = EXT; }else{ command->type = _INVALID_; return false; } return true; } /** * Check if the command has appropriate parameters. Namely: * - SRCH command should have at least one and at most 10 words * - DF command should have 0 or 1 word * - TF command should have an ID (int) param and a word * - EXT command should not have any words * @param command an already parsed command * @param numOfParameters how many parameters we encountered * @return `true` if the command meets the above criteria, `false` otherwise */ bool isNumOfParametersCorrect(Command *command, int numOfParameters){ if (command->type == SRCH && numOfParameters == 0){ return false; } if (command->type == EXT && numOfParameters != 0){ return false; } if (command->type == TF && numOfParameters != 2){ return false; } if (command->type == DF && numOfParameters > 1){ return false; } return true; }
C
#include<stdio.h> #include<math.h> #define MAX 1000001 int a[MAX]={0}; int main() {long m,n; int i,j,count; for(i=0;i<=MAX;i++) a[i]=i; a[0]=0;a[1]=0; for(i=2;i<sqrt(1.0*MAX);i++) {for(j=i+1;j<=MAX;j++) {if((a[i]!=0)&&(a[j]!=0)) if(a[j]%a[i]==0) a[j]=0; } } while(scanf("%ld%ld",&m,&n)==2) {count=0; for(i=m;i<=n;i++) if(a[i]!=0) count++; printf("%d\n",count); } }
C
#ifndef __DYNAMIC_LIST__ #define __DYNAMIC_LIST__ #include "../boolean/boolean.h" #include "../komponen/komponen.h" #define InitialSize 100 typedef int IdxType; typedef Komponen ListEl; typedef struct { ListEl *A; int Capacity; int Neff; } List; List MakeList(); /* I.S. sembarang F.S. Terbentuk List kosong dengan ukuran InitialSize */ void DeallocateList(List *list); /* I.S. List terdefinisi F.S. list->A terdealokasi */ boolean IsEmpty(List list); /* Fungsi untuk mengetahui apakah suatu list kosong. Prekondisi: list terdefinisi */ int Length(List list); /* Fungsi untuk mendapatkan banyaknya elemen efektif list, 0 jika tabel kosong. Prekondisi: list terdefinisi */ ListEl Get(List list, IdxType i); /* Mengembalikan elemen list L yang ke-I (indeks lojik). Prekondisi: list tidak kosong, i di antara 0..Length(list). */ int GetCapacity(List list); /* Fungsi untuk mendapatkan kapasitas yang tersedia. Prekondisi: list terdefinisi */ void InsertAt(List *list, ListEl el, IdxType i, int jumlah); /* Fungsi untuk menambahkan elemen baru di index ke-i Prekondisi: list terdefinisi, i di antara 0..Length(list). */ void InsertLast(List *list, ListEl el, int jumlah); /* Fungsi untuk menambahkan elemen baru di akhir list. Prekondisi: list terdefinisi */ void InsertFirst(List *list, ListEl el, int jumlah); /* Fungsi untuk menambahkan elemen baru di awal list. Prekondisi: list terdefinisi */ IdxType DoesComponentExist(List list, ListEl komponen); /* fungsi yang mengembalikan indeks dari komponen pada list, jika ada/ */ /* I.S. list mungkin kosong */ /* F.S. jika komponen ditemukan, indeks dari komponen tersebut menjadi parameter output. Jika tidak ditemukan, return -1 */ void PrintList(List L); /* mencetak isi list */ void DeleteComponent(List* L, ListEl X); /* menghapus komponen list */ boolean DoesBuildExists(List *L, ListEl *X); int Search(char* test,List list); #endif
C
#include <stdio.h> #include <sys/shm.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <fcntl.h> #include <sys/sem.h> #include <string.h> #include <time.h> void initSemValue(int semId, int n) { struct sembuf op; op.sem_op = 1; op.sem_flg = 0; op.sem_num = n; semop(semId, &op, 1); } void tryToGetSemOrWait(int semId, int n) { struct sembuf op; op.sem_op = -1; op.sem_flg = 0; op.sem_num = n; semop(semId, &op, 1); } void releaseSem(int semId, int n) { initSemValue(semId, n); } int main(int argc, char* argv[]) { const int N = atoi(argv[1]); const int min = atoi(argv[2]); const int max = atoi(argv[3]); int memId = shmget(IPC_PRIVATE, 4 * N, 0600 | IPC_CREAT | IPC_EXCL); if (memId <= 0) { printf("error with shmget()\n"); return -1; } int* memNumbers = (int *)shmat(memId, 0, 0); if (NULL == memNumbers) { printf("error with shmat()\n"); return -2; } printf("Initial data: \n"); srand((unsigned)(time(0))); for (int i = 0; i < N; i++) { memNumbers[i] = min + rand() % (max - min + 1); printf("%d ", memNumbers[i]); } printf("\n"); const size_t semCount = N; int semId = semget(IPC_PRIVATE, semCount, 0600 | IPC_CREAT); if (semId < 0) { perror("error with semget()"); return -1; } else { printf("semaphore set id = %i\n", semId); } pid_t childId = fork(); if (childId < 0) { perror("error with fork()\n"); } else if (childId > 0) { for (int i = 0; i < N; ++i) { printf("Parent: Freeing semaphore %i\n", i); releaseSem(semId, i); } int status = 0; int m = 1; while (waitpid(-1, &status, 0 | WNOHANG) == 0) { printf("Step %i: ", m); for (int i = 0; i < N; i++) { tryToGetSemOrWait(semId, i); printf("%d ", memNumbers[i]); releaseSem(semId, i); } printf("\n"); m++; } printf("\nSort completed\n"); for (int i = 0; i < N; i++) { tryToGetSemOrWait(semId, i); printf("%d\n", memNumbers[i]); releaseSem(semId, i); } shmctl(memId, IPC_RMID, NULL); semctl(semId, IPC_RMID, 0); } else if (childId == 0) { int key = 0; int first = 0; for (int second = 1; second < N; second++) { tryToGetSemOrWait(semId, second); key = memNumbers[second]; releaseSem(semId, second); first = second - 1; while (first>=0 && memNumbers[first]>key) { tryToGetSemOrWait(semId, first); tryToGetSemOrWait(semId, first+1); memNumbers[first + 1] = memNumbers[first]; releaseSem(semId, first); releaseSem(semId, first+1); first = first - 1; tryToGetSemOrWait(semId, first + 1); memNumbers[first + 1] = key; releaseSem(semId, first + 1); } } exit(0); } }
C
/* lookahead.c */ #include "globals.h" #include "rules.h" #include "tokensets.h" #include "lalr.h" #include "work.h" static TOKEN_SET new_context; static void compute_starters( ip ) ITEMPTR ip; { register TOKEN t, *rhsp; clear_set( &new_context ); rhsp = &( (ip->rule)->rhs[ip->pos+1] ); for( t = *rhsp++; t != NULLTOKEN; t = *rhsp++ ) { merge_sets( &new_context, t->starters ); if ( t->kind != NULLABLE_NT ) return; } /* run off RHS of the rule, .. so we hit this item's context */ merge_sets( &new_context, ip->context ); } static void check_lookaheads( sp ) STATEPTR sp; { register ITEMPTR ip; register RULE r; ITEMPTR cip, cpp; STATEPTR ssp; TOKEN t; while( not_empty_item_work_list(sp) ) { ip = remove_from_item_work_list(sp); t = ip->shiftsymbol; if (t == NULLTOKEN) continue; compute_starters( ip ); /* locate and check the completion items */ foreach_rule_with_lhs( t, r ) { if (!find_item(sp,r,0,&cip,&cpp)) internal_error( "check_lookaheads #2" ); if (test_merge_sets( &(cip->context), new_context )) add_to_item_work_list(sp,cip); } ssp = ip->shiftstate; if (ssp == NULLSTATE) continue; /* locate corresponding kernel item in shift state */ if ( ! find_item(ssp,ip->rule,ip->pos+1,&cip,&cpp) ) internal_error( "check_lookaheads #1" ); if (test_merge_sets( &(cip->context), ip->context )) { add_to_item_work_list(ssp,cip); add_to_state_work_list(ssp); } } } /* This routine assumes that the lookahead sets change only by having new elements ADDED to them. I.e., it is correct only after a new rule has been added to the grammar. */ void compute_lookahead_sets() { register STATEPTR sp; register ITEMPTR ip; /* This initialization of our work lists is clearly overkill */ clear_state_work_list(); foreach_state( sp ) { clear_item_work_list( sp ); add_to_state_work_list(sp); foreach_item( sp, ip ) add_to_item_work_list( sp, ip ); } while( not_empty_state_work_list() ) { sp = remove_from_state_work_list(); check_lookaheads(sp); } } /* Clears all lookahead sets to empty and then recomputes them from scratch. */ void totally_recompute_lookahead() { register STATEPTR sp; register ITEMPTR ip; clear_state_work_list(); foreach_state( sp ) { clear_item_work_list( sp ); add_to_state_work_list(sp); foreach_item( sp, ip ) { clear_set( &(ip->context) ); add_to_item_work_list( sp, ip ); } } while( not_empty_state_work_list() ) { sp = remove_from_state_work_list(); check_lookaheads(sp); } } void init_lookahead() { static BOOL initdone = FALSE; if (!initdone) { initialize_set( &new_context ); initdone = TRUE; } else clear_set( &new_context ); }
C
/************************************************************* * Předmět: IFJ / IAL * * Projekt: Implementace compilátoru imperativního jazyka * * Soubor: precedent.c * * Tým: 087 * * Varianta: 1 * * Autoři: Jan Pospíšil <xpospi94> * * Radek Sahliger <xsahli00> * * Michal Jireš <xjires02> * * Čermák Attila <xcerma38> * **************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "scanner.h" #include "symstack.h" #include "symtable.h" #include "precedent.h" Token* tokeng; tSymtable* global; tSymtable* local; bool in_function2 = false; void setGlobalVariables(Token* tok, tSymtable* glob){ tokeng = tok; global = glob; } void setLocTable(tSymtable* loc){ local = loc; } void setInFunction(bool in){ in_function2 = in; } int precedent_analys(Token* help){ symStack *stack = malloc(sizeof(symStack)); symstackInit(stack); symstackPush(stack, TOKEN_EOL); int a; // pushnuti prvni hodnoty EOL if(help != NULL){ if((a = idkfunkce(stack, help))){ return a; } } else { } if((a = idkfunkce(stack, tokeng))){ return a; } while(!(StackTopTerm(stack) == TOKEN_EOL && (tokeng->type == TOKEN_EOL || tokeng->type == TOKEN_COLON))) // cyklus pobezi dokud nenarazi na znak konce radku { get_token(tokeng); // ziskame token a = idkfunkce(stack, tokeng); // zavolame funkci pro zpracovani token if (a != SYNTAX_OK) return SEM_ERROR_OTHER; } return SYNTAX_OK; } int idkfunkce(symStack *stack, Token* token){ Token_type top = StackTopTerm(stack); // do top nahrajeme nejvyssi terminal ze stacku if (token->type == TOKEN_ID || token->type == TOKEN_INTEGER || token->type == TOKEN_STRING || token->type == TOKEN_FLOAT) //TODO je potreba zjitit co vse jsou identifikatory { if (top == TOKEN_R_BRACKET || top == TOKEN_ID || top == TOKEN_FLOAT || top == TOKEN_INTEGER || top == TOKEN_STRING) //pokud je na vrcholu ) nebo identifikator, tak se vypise chyba, protoze nejsou kompatibilni { return SEM_ERROR_OTHER; //nekompatibilni terminaly } else { if (token->type == TOKEN_INTEGER) { stackPushOpen(stack); // jinak posle zacatek rozvoje symstackPush(stack,TOKEN_INTEGER); // a znak identifikatoru stack->top->inte = token->attribute.integer; } else if (token->type == TOKEN_STRING) { stackPushOpen(stack); // jinak posle zacatek rozvoje symstackPush(stack,TOKEN_STRING); // a znak identifikatoru stack->top->string = token->attribute.string; } else if (token->type == TOKEN_FLOAT) { stackPushOpen(stack); // jinak posle zacatek rozvoje symstackPush(stack,TOKEN_FLOAT); // a znak identifikatoru stack->top->flt = token->attribute.flt; } else if (token->type == TOKEN_ID) { tBSTNodePtr promnena; int g = in_function2; if(g == 1) { promnena = symtableSearch(local, token->attribute.string->string); if(promnena == NULL) { promnena = symtableSearch(global, token->attribute.string->string); if(promnena == NULL) return SEM_ERROR_DEF; } } else { promnena = symtableSearch(global, token->attribute.string->string); if(promnena == NULL) return SEM_ERROR_DEF; } tInsideVariable* var_content; var_content = promnena->content; if(var_content->dataType == 0){ if(var_content->integer != 0){ var_content->dataType = 1; }else if(var_content->string->length != 0){ var_content->dataType = 3; }else if(var_content->flt != 0){ var_content->dataType = 2; } } int typ = var_content->dataType; if (typ == 0) //pokud neni zatim nic { return SYNTAX_ERROR; } else if (typ == 1) //pokud je integer { stackPushOpen(stack); // jinak posle zacatek rozvoje symstackPush(stack,TOKEN_INTEGER); // a znak identifikatoru stack->top->inte = var_content->integer; } else if (typ == 2) //pokud je float { stackPushOpen(stack); // jinak posle zacatek rozvoje symstackPush(stack,TOKEN_FLOAT); // a znak identifikatoru stack->top->flt = var_content->flt; } else if (typ == 3) // pokud je string { stackPushOpen(stack); // jinak posle zacatek rozvoje symstackPush(stack,TOKEN_STRING); // a znak identifikatoru stack->top->string = var_content->string; } else { return SYNTAX_ERROR; } char* lastidcko = malloc(token->attribute.string->length); strcpy(lastidcko, token->attribute.string->string); stack->top->nazev = lastidcko; } } } else if (token->type == TOKEN_L_BRACKET) // jako token dojde ( { if (top == TOKEN_R_BRACKET || top == TOKEN_PREC_ID) //pokud je na vrcholu ) nebo identifikator, tak se vypise chyba, protoze nejsou kompatibilni { return SEM_ERROR_OTHER; //nekompatibilni terminaly } else { stackPushOpen(stack); // jinak posle zacatek rozvoje symstackPush(stack,TOKEN_L_BRACKET); // a znak identifikatoru } } else if (token->type == TOKEN_R_BRACKET) // jako token dojde ) { if (top == TOKEN_EOL || top == TOKEN_COLON ) //pokud je na vrcholu EOL, tak se vypise chyba, protoze nejsou kompatibilni { return SEM_ERROR_OTHER; //nekompatibilni terminaly } else if (top == TOKEN_L_BRACKET ) //pokud na na vrchu ( { symstackPush(stack,TOKEN_R_BRACKET); // pushni ) symstackPush(stack,TOKEN_PREC_CLOSE); // pushni konec rozvoje > reduction(stack); // a proved redukci } else //pokud je cokoliv jineho { symstackPush(stack,TOKEN_PREC_CLOSE); //pushni konec rozvoje > reduction(stack); // proved redukci int b = idkfunkce(stack, token); // zavola sebe sama rekurzivne pro vyhodnoceni dalsich redukci if (b != SYNTAX_OK) { return SEM_ERROR_OTHER; } } } else if (token->type == TOKEN_EOL || token->type == TOKEN_COLON) // jako token dojde EOL TODO ZEPTAT SE NA EOL { if (top == TOKEN_EOL ) //pokud je na vrcholu eol tak jsme uspesne zredukovali celej vyraz { if (stack->top->tokenType == TOKEN_PREC_INTEGER) { token->attribute.keyword = RET_INT; } else if (stack->top->tokenType == TOKEN_PREC_FLOAT) { token->attribute.keyword = RET_FLOAT; } else if (stack->top->tokenType == TOKEN_PREC_STRING) { token->attribute.keyword = RET_STRING; } return SYNTAX_OK; } else if (top == TOKEN_L_BRACKET) //pokud je na vrcholu ( tak nastane chyba { return SEM_ERROR_OTHER; //nekompatibilni terminaly } else // rekurzivne tocime dokud nenastane stav $E$ nebo nenastane chyba { symstackPush(stack,TOKEN_PREC_CLOSE); //pushni konec rozvoje > reduction(stack); // proved redukci int b = idkfunkce(stack, token); // zavola sebe sama rekurzivne pro vyhodnoceni dalsich redukci if (b != SYNTAX_OK) { return SEM_ERROR_OTHER; } } } else if (token->type == TOKEN_PLUS || token->type == TOKEN_MINUS) // jako token dojde +- { if (top == TOKEN_PLUS || top == TOKEN_MINUS || top == TOKEN_MUL || top == TOKEN_FLOAT_DIV || top == TOKEN_INT_DIV || top == TOKEN_INTEGER || top == TOKEN_STRING || top == TOKEN_FLOAT || top == TOKEN_INTEGER || top == TOKEN_STRING || top == TOKEN_FLOAT || top == TOKEN_R_BRACKET) //pokud je top + - * / // i ) { symstackPush(stack,TOKEN_PREC_CLOSE); //pushni konec rozvoje > reduction(stack); // proved redukci int b = idkfunkce(stack, token); // zavola sebe sama rekurzivne pro vyhodnoceni dalsich redukci if (b != SYNTAX_OK) { return SEM_ERROR_OTHER; } } else { stackPushOpen(stack); // jinak posle zacatek rozvoje if (token->type == TOKEN_PLUS) { symstackPush(stack,TOKEN_PLUS); // a znak identifikatoru } else { symstackPush(stack,TOKEN_MINUS); // a znak identifikatoru } } } else if (token->type == TOKEN_MUL || token->type == TOKEN_FLOAT_DIV || token->type == TOKEN_INT_DIV) // jako token dojde * / // { if (top == TOKEN_R_BRACKET || top == TOKEN_INTEGER || top == TOKEN_STRING || top == TOKEN_FLOAT || top == TOKEN_MUL || top == TOKEN_FLOAT_DIV || top == TOKEN_INT_DIV) { symstackPush(stack,TOKEN_PREC_CLOSE); //pushni konec rozvoje > reduction(stack); // proved redukci int b = idkfunkce(stack, token); // zavola sebe sama rekurzivne pro vyhodnoceni dalsich redukci if (b != SYNTAX_OK) { return SEM_ERROR_OTHER; } } else { stackPushOpen(stack); if (token->type == TOKEN_MUL) { symstackPush(stack,TOKEN_MUL); } else if (token->type == TOKEN_FLOAT_DIV) { symstackPush(stack,TOKEN_FLOAT_DIV); } else { symstackPush(stack,TOKEN_INT_DIV); } } } else if (token->type == TOKEN_LESS || token->type == TOKEN_LEQ || token->type == TOKEN_MORE || token->type == TOKEN_MEQ || token->type == TOKEN_EQ || token->type == TOKEN_NEQ || token->type == TOKEN_ASSIGN) // jako token dojde < <= > >= == != = { if (top >= TOKEN_MEQ && top <= TOKEN_NEQ) { return SEM_ERROR_OTHER; //nekompatibilni terminaly } else if (top == TOKEN_L_BRACKET || top == TOKEN_EOL) { stackPushOpen(stack); if (token->type == TOKEN_LESS) { symstackPush(stack,TOKEN_LESS); } else if (token->type == TOKEN_LEQ) { symstackPush(stack,TOKEN_LEQ); } else if (token->type == TOKEN_MORE) { symstackPush(stack,TOKEN_MORE); } else if (token->type == TOKEN_MEQ) { symstackPush(stack,TOKEN_MEQ); } else if (token->type == TOKEN_EQ) { symstackPush(stack,TOKEN_EQ); } else if (token->type == TOKEN_NEQ) { symstackPush(stack,TOKEN_NEQ); } else if (token->type == TOKEN_ASSIGN) { symstackPush(stack,TOKEN_ASSIGN); } } else { symstackPush(stack,TOKEN_PREC_CLOSE); //pushni konec rozvoje > reduction(stack); // proved redukci int b = idkfunkce(stack, token); // zavola sebe sama rekurzivne pro vyhodnoceni dalsich redukci if (b != SYNTAX_OK) { return SEM_ERROR_OTHER; } } } return SYNTAX_OK; } Token_type StackTopTerm (symStack *stack){ symStack *temp = malloc(sizeof(symStack)); temp->top = stack->top; Token_type tokenhelp; if (temp->top == NULL) { return TOKEN_ERROR; } else { tokenhelp = stack->top->tokenType; while(tokenhelp > TOKEN_NEQ) { symStackItem* out = temp->top; if (out->next != NULL) { temp->top = out->next; tokenhelp = symstackTop(temp); } else { return TOKEN_ERROR; } } if (tokenhelp <= TOKEN_NEQ) { return tokenhelp; } else { return TOKEN_ERROR; } } } int stackPushOpen(symStack *stack){ if(StackTopTerm(stack) == symstackTop(stack)) { symstackPush(stack,TOKEN_PREC_OPEN); return 0; }else { symStackItem* temp = NULL; symStackItem* prev = NULL; symStackItem* nitem = (symStackItem*)malloc(sizeof(symStackItem)); Token_type topterm=StackTopTerm(stack); Token_type help=symstackTop(stack); temp = stack->top; while(topterm != help) { help = temp->tokenType; if (topterm == help) { nitem->tokenType = TOKEN_PREC_OPEN; nitem->next = temp; prev->next = nitem; return 0; }else { prev = temp; temp = prev->next; } } } return 0; } symStackItem* stackPosition(symStack *stack, int j){ symStackItem* temp = stack->top; for (int i = 0; i < j; ++i) { temp = temp->next; } return temp; } int reduction(symStack *stack){ symStackItem* temp = stack->top; Token_type topterm=StackTopTerm(stack); Token_type help=symstackTop(stack); int i=1; while(temp->tokenType != 26 || i >10) // zjisteni kolik zaznamu se nachazi v redukci pr < id + id > => 5 { i++; temp = temp->next; } if(topterm == TOKEN_INTEGER || topterm == TOKEN_FLOAT || topterm == TOKEN_STRING) // nutno dodelat nevim jak na to potreba roylisit lokalni a globalni promenou { if (i == 3) { symstackPop(stack); help=symstackTop(stack); symStackItem* temp2 = malloc(sizeof(symStackItem)); if(stack->top->nazev != NULL){ if(in_function2){ if(symtableSearch(local, stack->top->nazev) != NULL) printf("PUSHS LF@%s\n", stack->top->nazev); else if(symtableSearch(global, stack->top->nazev) != NULL) printf("PUSHS GF@%s\n", stack->top->nazev); else return SEM_ERROR_DEF; }else{ printf("PUSHS GF@%s\n", stack->top->nazev); } } if (help == TOKEN_INTEGER) { if(stack->top->nazev == NULL) printf("PUSHS int@%d\n", stack->top->inte); temp2->inte = stack->top->inte; symstackPopMore(stack, 2); symstackPush(stack,TOKEN_PREC_INTEGER); stack->top->inte = temp2->inte; } else if (help == TOKEN_FLOAT) { if(stack->top->nazev == NULL) printf("PUSHS float@%a\n", stack->top->flt); stack->top->flt = temp2->flt; symstackPopMore(stack, 2); symstackPush(stack,TOKEN_PREC_FLOAT); stack->top->flt = temp2->flt; } else if (help ==TOKEN_STRING) { if(stack->top->nazev == NULL){ printf("PUSHS string@"); for (int i = 0; i < stack->top->string->length; i++){ char c = stack->top->string->string[i]; int ascii = (int)c; if(ascii <= 32 || ascii == 35 || ascii == 92){ if(ascii < 10){ printf("\\00%d", ascii); }else{ printf("\\0%d", ascii); } }else{ printf("%c", c); } } printf("\n"); } temp2->string = stack->top->string; symstackPopMore(stack, 2); symstackPush(stack,TOKEN_PREC_STRING); stack->top->string = temp2->string; } else { free(temp2); return SYNTAX_ERROR; } free(temp2); } else { return SYNTAX_ERROR; } } else if (topterm == TOKEN_R_BRACKET) // hotovo provede redukci zavorek { if (i==5) { symStackItem* prvni = stackPosition(stack, 0); symStackItem* druhej = stackPosition(stack, 1); symStackItem* treti = stackPosition(stack, 2); symStackItem* ctvrtej = stackPosition(stack, 3); symStackItem* patej = stackPosition(stack, 4); symStackItem* temp2 = malloc(sizeof(symStackItem));; if (prvni->tokenType == TOKEN_PREC_CLOSE && patej->tokenType == TOKEN_PREC_OPEN && druhej->tokenType == TOKEN_R_BRACKET && ctvrtej->tokenType == TOKEN_L_BRACKET) { temp2->tokenType = treti->tokenType; temp2->inte = treti->inte; temp2->flt = treti->flt; temp2->string = treti->string; symstackPopMore(stack, 5); symstackPush(stack, temp2->tokenType); stack->top->inte = temp2->inte; stack->top->flt = temp2->flt; stack->top->string = temp2->string; free(temp2); return SYNTAX_OK; } else { free(temp2); return SYNTAX_ERROR; } } else { return SYNTAX_ERROR; } } else if (topterm == TOKEN_L_BRACKET || topterm == TOKEN_EOL) //hotovo vyhodi chybu protoze to je zakazany stav { return SYNTAX_ERROR; } else if (topterm >= TOKEN_PLUS && topterm <= TOKEN_NEQ) { if (topterm == TOKEN_PLUS) { if (i == 5) { symStackItem* prvni = stackPosition(stack, 0); symStackItem* druhej = stackPosition(stack, 1); symStackItem* treti = stackPosition(stack, 2); symStackItem* ctvrtej = stackPosition(stack, 3); symStackItem* patej = stackPosition(stack, 4); if (prvni->tokenType == TOKEN_PREC_CLOSE && patej->tokenType == TOKEN_PREC_OPEN && treti->tokenType == TOKEN_PLUS) { if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_INTEGER) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 420; printf("ADDS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_INTEGER) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_FLOAT); stack->top->flt = 42.0; printf("POPS GF@?AX?\n"); printf("INT2FLOATS\n"); printf("PUSHS GF@?AX?\n"); printf("ADDS\n"); } else if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType ==TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_FLOAT); stack->top->flt = 42.0; printf("INT2FLOATS\n"); printf("ADDS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_FLOAT); stack->top->flt = 420.0; printf("ADDS\n"); } else if (druhej->tokenType == TOKEN_PREC_STRING && ctvrtej->tokenType ==TOKEN_PREC_STRING) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_STRING); printf("POPS GF@?AX?\n"); printf("POPS GF@?BX?\n"); printf("CONCAT GF@?CX? GF@?BX? GF@?AX?\n"); printf("PUSHS GF@?CX?\n"); } else { return SYNTAX_ERROR; } } else { return SYNTAX_ERROR; } } else { return SYNTAX_ERROR; } } else if (topterm == TOKEN_MINUS) { if (i == 5) { symStackItem* prvni = stackPosition(stack, 0); symStackItem* druhej = stackPosition(stack, 1); symStackItem* treti = stackPosition(stack, 2); symStackItem* ctvrtej = stackPosition(stack, 3); symStackItem* patej = stackPosition(stack, 4); if (prvni->tokenType == TOKEN_PREC_CLOSE && patej->tokenType == TOKEN_PREC_OPEN && treti->tokenType == TOKEN_MINUS) { if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_INTEGER) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 420; printf("SUBS\n"); } else if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType ==TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_FLOAT); stack->top->flt = 42.0; printf("INT2FLOATS\n"); printf("SUBS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_INTEGER) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_FLOAT); stack->top->flt = 42.0; printf("POPS GF@?AX?\n"); printf("INT2FLOATS\n"); printf("PUSHS GF@?AX?\n"); printf("SUBS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_FLOAT); stack->top->flt = 42.0; printf("SUBS\n"); } else { return SEM_ERROR_TYPE; } } else { return SYNTAX_ERROR; } } else { return SYNTAX_ERROR; } } else if (topterm == TOKEN_FLOAT_DIV) { if (i == 5) { symStackItem* prvni = stackPosition(stack, 0); symStackItem* druhej = stackPosition(stack, 1); symStackItem* treti = stackPosition(stack, 2); symStackItem* ctvrtej = stackPosition(stack, 3); symStackItem* patej = stackPosition(stack, 4); if (prvni->tokenType == TOKEN_PREC_CLOSE && patej->tokenType == TOKEN_PREC_OPEN && treti->tokenType == TOKEN_FLOAT_DIV) { if (druhej->tokenType == TOKEN_PREC_INTEGER && druhej->inte == 0 ) { return ZERO_DIVISION; } else if (druhej->tokenType == TOKEN_PREC_FLOAT && druhej->flt == 0) { return ZERO_DIVISION; } if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_INTEGER) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_FLOAT); stack->top->flt = 42.0; printf("INT2FLOATS\n"); printf("POPS GF@?AX?\n"); printf("INT2FLOATS\n"); printf("PUSHS GF@?AX?\n"); printf("DIVS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_FLOAT); stack->top->flt = 42.0; printf("DIVS\n"); } else if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_FLOAT); stack->top->flt = 42.0; printf("INT2FLOATS\n"); printf("DIVS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_INTEGER) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_FLOAT); stack->top->flt = 42.0; printf("POPS GF@?AX?\n"); printf("INT2FLOATS\n"); printf("PUSHS GF@?AX?\n"); printf("DIVS\n"); } else { return SEM_ERROR_TYPE; } } } else { return SYNTAX_ERROR; } } else if (topterm == TOKEN_INT_DIV) { if (i == 5) { symStackItem* prvni = stackPosition(stack, 0); symStackItem* druhej = stackPosition(stack, 1); symStackItem* treti = stackPosition(stack, 2); symStackItem* ctvrtej = stackPosition(stack, 3); symStackItem* patej = stackPosition(stack, 4); if (prvni->tokenType == TOKEN_PREC_CLOSE && druhej->tokenType == TOKEN_PREC_INTEGER && treti->tokenType == TOKEN_INT_DIV && ctvrtej->tokenType == TOKEN_PREC_INTEGER && patej->tokenType == TOKEN_PREC_OPEN) { if (druhej->inte != 0) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 420; printf("IDIVS\n"); } else { return SEM_ERROR_TYPE; } } else { return SEM_ERROR_TYPE; } } else { return SYNTAX_ERROR; } } else if (topterm == TOKEN_MUL) { if (i == 5) { symStackItem* prvni = stackPosition(stack, 0); symStackItem* druhej = stackPosition(stack, 1); symStackItem* treti = stackPosition(stack, 2); symStackItem* ctvrtej = stackPosition(stack, 3); symStackItem* patej = stackPosition(stack, 4); if (prvni->tokenType == TOKEN_PREC_CLOSE && patej->tokenType == TOKEN_PREC_OPEN && treti->tokenType == TOKEN_MUL) { if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_INTEGER ) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 420; printf("MULS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_FLOAT); stack->top->flt = 42.0; printf("MULS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_INTEGER) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_FLOAT); stack->top->flt = 42.0; printf("POPS GF@?AX?\n"); printf("INT2FLOATS\n"); printf("PUSHS GF@?AX?\n"); printf("MULS\n"); } else if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_FLOAT); stack->top->flt = 42.0; printf("INT2FLOATS\n"); printf("MULS\n"); } else { return SEM_ERROR_TYPE; } } else { return SYNTAX_ERROR; } } else { return SYNTAX_ERROR; } } else if (topterm == TOKEN_MEQ) { if (i == 5) { symStackItem* prvni = stackPosition(stack, 0); symStackItem* druhej = stackPosition(stack, 1); symStackItem* treti = stackPosition(stack, 2); symStackItem* ctvrtej = stackPosition(stack, 3); symStackItem* patej = stackPosition(stack, 4); if (prvni->tokenType == TOKEN_PREC_CLOSE && patej->tokenType == TOKEN_PREC_OPEN && treti->tokenType == TOKEN_MEQ) { if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("INT2FLOATS\n"); printf("POPS GF@?AX?\n"); printf("POPS GF@?BX?\n"); printf("GT GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("EQ GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("ORS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_INTEGER) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("POPS GF@?AX?\n"); printf("INT2FLOATS\n"); printf("POPS GF@?BX?\n"); printf("GT GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("EQ GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("ORS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("POPS GF@?AX?\n"); printf("POPS GF@?BX?\n"); printf("GT GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("EQ GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("ORS\n"); } else if (druhej->tokenType== TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_INTEGER ) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("POPS GF@?AX?\n"); printf("POPS GF@?BX?\n"); printf("GT GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("EQ GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("ORS\n"); } else { return SEM_ERROR_TYPE; } } else { return SYNTAX_ERROR; } } else { return SYNTAX_ERROR; } } else if (topterm == TOKEN_MORE) { if (i == 5) { symStackItem* prvni = stackPosition(stack, 0); symStackItem* druhej = stackPosition(stack, 1); symStackItem* treti = stackPosition(stack, 2); symStackItem* ctvrtej = stackPosition(stack, 3); symStackItem* patej = stackPosition(stack, 4); if (prvni->tokenType == TOKEN_PREC_CLOSE && patej->tokenType == TOKEN_PREC_OPEN && treti->tokenType == TOKEN_MORE) { if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("INT2FLOATS\n"); printf("GTS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_INTEGER) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("POPS GF@?AX?\n"); printf("INT2FLOATS\n"); printf("PUSHS GF@?AX?\n"); printf("GTS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("GTS\n"); } else if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_INTEGER ) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("GTS\n"); } else { return SEM_ERROR_TYPE; } } else { return SYNTAX_ERROR; } } else { return SYNTAX_ERROR; } } else if (topterm == TOKEN_LEQ) { if (i == 5) { symStackItem* prvni = stackPosition(stack, 0); symStackItem* druhej = stackPosition(stack, 1); symStackItem* treti = stackPosition(stack, 2); symStackItem* ctvrtej = stackPosition(stack, 3); symStackItem* patej = stackPosition(stack, 4); if (prvni->tokenType == TOKEN_PREC_CLOSE && patej->tokenType == TOKEN_PREC_OPEN && treti->tokenType == TOKEN_LEQ) { if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("INT2FLOATS\n"); printf("POPS GF@?AX?\n"); printf("POPS GF@?BX?\n"); printf("LT GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("EQ GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("ORS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_INTEGER) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("POPS GF@?AX?\n"); printf("INT2FLOATS\n"); printf("POPS GF@?BX?\n"); printf("LT GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("EQ GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("ORS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("POPS GF@?AX?\n"); printf("POPS GF@?BX?\n"); printf("LT GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("EQ GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("ORS\n"); } else if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_INTEGER ) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("POPS GF@?AX?\n"); printf("POPS GF@?BX?\n"); printf("LT GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("EQ GF@?CX? GF@?AX? GF@?BX?\n"); printf("PUSHS GF@?CX?\n"); printf("ORS\n"); } else { return SEM_ERROR_TYPE; } } else { return SYNTAX_ERROR; } } else { return SYNTAX_ERROR; } } else if (topterm == TOKEN_LESS) { if (i == 5) { symStackItem* prvni = stackPosition(stack, 0); symStackItem* druhej = stackPosition(stack, 1); symStackItem* treti = stackPosition(stack, 2); symStackItem* ctvrtej = stackPosition(stack, 3); symStackItem* patej = stackPosition(stack, 4); if (prvni->tokenType == TOKEN_PREC_CLOSE && patej->tokenType == TOKEN_PREC_OPEN && treti->tokenType == TOKEN_LESS) { if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("INT2FLOATS\n"); printf("LTS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_INTEGER) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("POPS GF@?AX?\n"); printf("INT2FLOATS\n"); printf("PUSHS GF@?AX?\n"); printf("LTS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("LTS\n"); } else if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_INTEGER ) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("LTS\n"); } else { return SEM_ERROR_TYPE; } } else { return SYNTAX_ERROR; } } else { return SYNTAX_ERROR; } } else if (topterm == TOKEN_EQ) { if (i == 5) { symStackItem* prvni = stackPosition(stack, 0); symStackItem* druhej = stackPosition(stack, 1); symStackItem* treti = stackPosition(stack, 2); symStackItem* ctvrtej = stackPosition(stack, 3); symStackItem* patej = stackPosition(stack, 4); if (prvni->tokenType == TOKEN_PREC_CLOSE && patej->tokenType == TOKEN_PREC_OPEN && treti->tokenType == TOKEN_EQ) { if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("INT2FLOATS\n"); printf("EQS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_INTEGER) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("POPS GF@?AX?\n"); printf("INT2FLOATS\n"); printf("PUSHS GF@?AX?\n"); printf("EQS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("EQS\n"); } else if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_INTEGER ) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("EQS\n"); } else { return SEM_ERROR_TYPE; } } else { return SYNTAX_ERROR; } } else { return SYNTAX_ERROR; } } else if (topterm == TOKEN_ASSIGN) { return SYNTAX_ERROR; } else if (topterm == TOKEN_NEQ) //done { if (i == 5) { symStackItem* prvni = stackPosition(stack, 0); symStackItem* druhej = stackPosition(stack, 1); symStackItem* treti = stackPosition(stack, 2); symStackItem* ctvrtej = stackPosition(stack, 3); symStackItem* patej = stackPosition(stack, 4); if (prvni->tokenType == TOKEN_PREC_CLOSE && patej->tokenType == TOKEN_PREC_OPEN && treti->tokenType == TOKEN_NEQ) { if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("INT2FLOATS\n"); printf("EQS\n"); printf("NOTS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_INTEGER) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("POPS GF@?AX?\n"); printf("INT2FLOATS\n"); printf("PUSHS GF@?AX?\n"); printf("EQS\n"); printf("NOTS\n"); } else if (druhej->tokenType == TOKEN_PREC_FLOAT && ctvrtej->tokenType == TOKEN_PREC_FLOAT) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("EQS\n"); printf("NOTS\n"); } else if (druhej->tokenType == TOKEN_PREC_INTEGER && ctvrtej->tokenType == TOKEN_PREC_INTEGER ) { symstackPopMore(stack, 5); symstackPush(stack, TOKEN_PREC_INTEGER); stack->top->inte = 1; printf("EQS\n"); printf("NOTS\n"); } else { return SEM_ERROR_TYPE; } } else { return SYNTAX_ERROR; } } else { return SYNTAX_ERROR; } } else { return SYNTAX_ERROR; } } else { return SYNTAX_ERROR; } return 0; }
C
/* * Exercise 9.4 Kochan - Programming in C * * If you take the value of N as computed in exercise 2, subtract 621,049 from * it, and then take that result modulo 7, you get a number from 0 to 6 that * represents the day of the week (Sunday through Saturday, respectively) on * which the particular day falls. For example, the value of N computed for * August 8, 2004, is 732,239 as derived previously. 732,239 – 621,049 gives * 111,190, and 111,190 % 7 gives 2, indicating that this date falls on a * Tuesday. Use the functions developed in the previous exercise to develop a * program that displays the day of the week on which a particular date falls. * Make certain that the program displays the day of the week in English * (such as “Monday”). */ #include <stdio.h> struct date { int month; int day; int year; }; // prototypes int elapsedDays (struct date d); void printDayName (int x); // main function int main (void) { struct date date1, date2; int n1, n2; // n1 for date1, n2 for date2 printf ("Enter the first date (mm dd yyyy): "); scanf ("%i%i%i", &date1.month, &date1.day, &date1.year); printf ("Enter the second date (mm dd yyyy): "); scanf ("%i%i%i", &date2.month, &date2.day, &date2.year); n1 = elapsedDays (date1); n2 = elapsedDays (date2); printf ("The elapsed days between "); printDayName(n1); printf(" %i/%i/%i and ", date1.month, date1.day, date1.year); printDayName(n2); printf(" %i/%i/%i is %i days.\n ", date2.month, date2.day, date2.year, n2 - n1); return 0; } // function to calculate elapsed days int elapsedDays (struct date d) { /* n is the elapsed time integer, as follows: * N = 1461 x f(year, month) / 4 + 153 x g(month) / 5 + day * * Where, * f(year, month) = year - 1 if month <=2 year otherwise g(month) = month + 13 if month <=2 month + 1 otherwise */ int n, f, g; if (d.month <= 2) { f = d.year - 1; g = d.month + 13; } else { f = d.year; g = d.month + 1; } n = (1461 * f) / 4 + (153 * g) / 5 + d.day; return n; } // function to print the day's name void printDayName (int x) { int day = (( ( x - 621049) % 7)); switch (day) { case 0: printf ("Sunday"); break; case 1: printf ("Monday"); break; case 2: printf ("Tuesday"); break; case 3: printf ("Wednesday"); break; case 4: printf ("Thursday"); break; case 5: printf ("Friday"); break; case 6: printf ("Saturday"); break; } }
C
#include <stdio.h> int main(){ int aux = 0; int a; printf("Ingrese un numero: "); scanf("%d",&a); aux+=a; while(a!=0){ printf("Ingrese un numero: "); scanf("%d",&a); printf("\n"); } printf("%d", aux); return 0; }
C
#include<stdio.h> #include<stdlib.h> int main() { int *p; p = (int*)malloc(sizeof(int)); printf("done\n"); free(p); p = NULL; free(p); free(p); free(p); free(p); printf("done\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstnew.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: chyuen <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/03 10:56:20 by chyuen #+# #+# */ /* Updated: 2019/05/03 11:13:57 by chyuen ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" /* **linked list function of creating a new node **with assigning value (*content) and size (content_size) **keep content_size 0 in node if content is NULL */ t_list *ft_lstnew(void const *content, size_t content_size) { t_list *ret; if (!(ret = (t_list*)malloc(sizeof(t_list)))) return (NULL); ret->content = NULL; ret->content_size = 0; if (content) { if (!(ret->content = ft_memalloc((content_size)))) { free(ret); return (NULL); } ft_memcpy(ret->content, (void*)content, content_size); ret->content_size = content_size; } ret->next = NULL; return (ret); }
C
/** * Kostra programu pro 3. projekt IZP 2015/16 * * Jednoducha shlukova analyza: 2D nejblizsi soused. * Single linkage * http://is.muni.cz/th/172767/fi_b/5739129/web/web/slsrov.html */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> // sqrtf #include <limits.h> // INT_MAX /***************************************************************** * Ladici makra. Vypnout jejich efekt lze definici makra * NDEBUG, napr.: * a) pri prekladu argumentem prekladaci -DNDEBUG * b) v souboru (na radek pred #include <assert.h>) * #define NDEBUG */ #ifdef NDEBUG #define debug(s) #define dfmt(s, ...) #define dint(i) #define dfloat(f) #else // vypise ladici retezec #define debug(s) printf("- %s\n", s) // vypise formatovany ladici vystup - pouziti podobne jako printf #define dfmt(s, ...) printf(" - "__FILE__":%u: "s"\n",__LINE__,__VA_ARGS__) // vypise ladici informaci o promenne - pouziti dint(identifikator_promenne) #define dint(i) printf(" - " __FILE__ ":%u: " #i " = %d\n", __LINE__, i) // vypise ladici informaci o promenne typu float - pouziti // dfloat(identifikator_promenne) #define dfloat(f) printf(" - " __FILE__ ":%u: " #f " = %g\n", __LINE__, f) #endif /***************************************************************** * Deklarace potrebnych datovych typu: * * TYTO DEKLARACE NEMENTE * * struct objt_t - struktura objektu: identifikator a souradnice * struct cluster_t - shluk objektu: * pocet objektu ve shluku, * kapacita shluku (pocet objektu, pro ktere je rezervovano * misto v poli), * ukazatel na pole shluku. */ struct obj_t { int id; float x; float y; }; struct cluster_t { int size; int capacity; struct obj_t *obj; }; /***************************************************************** * Deklarace potrebnych funkci. * * PROTOTYPY FUNKCI NEMENTE * * IMPLEMENTUJTE POUZE FUNKCE NA MISTECH OZNACENYCH 'TODO' * */ /* Inicializace shluku 'c'. Alokuje pamet pro cap objektu (kapacitu). Ukazatel NULL u pole objektu znamena kapacitu 0. */ // TODO void init_cluster(struct cluster_t *c, int cap) { assert(c != NULL); assert(cap >= 0); c->size = 0; if (cap == 0) { c->capacity = 0; c->obj = NULL; } else { c->capacity = cap; c->obj = malloc(cap*sizeof(struct obj_t)); } } /* Odstraneni vsech objektu shluku a inicializace na prazdny shluk. */ // TODO void clear_cluster(struct cluster_t *c) { if (c->obj != NULL) { free(c->obj); init_cluster(c, 0); } } /// Chunk of cluster objects. Value recommended for reallocation. const int CLUSTER_CHUNK = 10; /* Zmena kapacity shluku 'c' na kapacitu 'new_cap'. */ struct cluster_t *resize_cluster(struct cluster_t *c, int new_cap) { // TUTO FUNKCI NEMENTE assert(c); assert(c->capacity >= 0); assert(new_cap >= 0); if (c->capacity >= new_cap) return c; size_t size = sizeof(struct obj_t) * new_cap; void *arr = realloc(c->obj, size); if (arr == NULL) return NULL; c->obj = arr; c->capacity = new_cap; return c; } /* Prida objekt 'obj' na konec shluku 'c'. Rozsiri shluk, pokud se do nej objekt nevejde. */ // TODO void append_cluster(struct cluster_t *c, struct obj_t obj) { if (c->size >= c->capacity) { resize_cluster(c, c->capacity + CLUSTER_CHUNK); } c->obj[c->size] = obj; c->size += 1; } /* Seradi objekty ve shluku 'c' vzestupne podle jejich identifikacniho cisla. */ void sort_cluster(struct cluster_t *c); /* Do shluku 'c1' prida objekty 'c2'. Shluk 'c1' bude v pripade nutnosti rozsiren. Objekty ve shluku 'c1' budou serazny vzestupne podle identifikacniho cisla. Shluk 'c2' bude nezmenen. */ // TODO void merge_clusters(struct cluster_t *c1, struct cluster_t *c2) { assert(c1 != NULL); assert(c2 != NULL); for (int i = 0; i < c2->size; i++) { append_cluster(c1, c2->obj[i]); } sort_cluster(c1); } /**********************************************************************/ /* Prace s polem shluku */ /* Odstrani shluk z pole shluku 'carr'. Pole shluku obsahuje 'narr' polozek (shluku). Shluk pro odstraneni se nachazi na indexu 'idx'. Funkce vraci novy pocet shluku v poli. */ // TODO int remove_cluster(struct cluster_t *carr, int narr, int idx) { assert(idx < narr); assert(narr > 0); clear_cluster(&carr[idx]); for (int i = idx; i < narr - 1; i++) { carr[i] = carr[i + 1]; } return narr - 1; } /* Pocita Euklidovskou vzdalenost mezi dvema objekty. */ // TODO float obj_distance(struct obj_t *o1, struct obj_t *o2) { assert(o1 != NULL); assert(o2 != NULL); float dx = o1->x - o2->x; float dy = o1->y - o2->y; return sqrt(dx*dx + dy*dy); } /* Pocita vzdalenost dvou shluku. Vzdalenost je vypoctena na zaklade nejblizsiho souseda. */ // TODO float cluster_distance(struct cluster_t *c1, struct cluster_t *c2) { assert(c1 != NULL); assert(c1->size > 0); assert(c2 != NULL); assert(c2->size > 0); float min = obj_distance(&c1->obj[0], &c2->obj[0]); float dist; for (int i = 0; i < c1->size; i++) { for (int j = 0; j < c2->size; j++) { dist = obj_distance(&c1->obj[i], &c2->obj[j]); if (dist < min) { min = dist; } } } return min; } /* Funkce najde dva nejblizsi shluky. V poli shluku 'carr' o velikosti 'narr' hleda dva nejblizsi shluky (podle nejblizsiho souseda). Nalezene shluky identifikuje jejich indexy v poli 'carr'. Funkce nalezene shluky (indexy do pole 'carr') uklada do pameti na adresu 'c1' resp. 'c2'. */ // TODO void find_neighbours(struct cluster_t *carr, int narr, int *c1, int *c2) { assert(narr > 0); if (narr > 1) { float min = cluster_distance(&carr[0], &carr[1]); float dist; for (int i = 0; i < narr; i++) { for (int j = 0; j < narr; j++) { if (i != j) { dist = cluster_distance(&carr[i], &carr[j]); if (dist < min) { *c1 = i; *c2 = j; min = dist; } } } } } } // pomocna funkce pro razeni shluku static int obj_sort_compar(const void *a, const void *b) { // TUTO FUNKCI NEMENTE const struct obj_t *o1 = a; const struct obj_t *o2 = b; if (o1->id < o2->id) return -1; if (o1->id > o2->id) return 1; return 0; } /* Razeni objektu ve shluku vzestupne podle jejich identifikatoru. */ void sort_cluster(struct cluster_t *c) { // TUTO FUNKCI NEMENTE qsort(c->obj, c->size, sizeof(struct obj_t), &obj_sort_compar); } /* Tisk shluku 'c' na stdout. */ void print_cluster(struct cluster_t *c) { // TUTO FUNKCI NEMENTE for (int i = 0; i < c->size; i++) { if (i) putchar(' '); printf("%d[%g,%g]", c->obj[i].id, c->obj[i].x, c->obj[i].y); } putchar('\n'); } /* Ze souboru 'filename' nacte objekty. Pro kazdy objekt vytvori shluk a ulozi jej do pole shluku. Alokuje prostor pro pole vsech shluku a ukazatel na prvni polozku pole (ukalazatel na prvni shluk v alokovanem poli) ulozi do pameti, kam se odkazuje parametr 'arr'. Funkce vraci pocet nactenych objektu (shluku). V pripade nejake chyby uklada do pameti, kam se odkazuje 'arr', hodnotu NULL. */ // TODO int load_clusters(char *filename, struct cluster_t **arr) { assert(arr != NULL); FILE *datafile = NULL; datafile = fopen(filename, "r"); if (datafile == NULL) { // Failed to open file // *arr pointer is set to NULL *arr = NULL; fprintf(stderr, "In function load_clusters:\nFailed to open the file %s.\n", filename); return -1; } int objectCount = 0; int loadCount = 0; float x = 0; float y = 0; char buffer[100]; fgets(buffer, 99, datafile); sscanf(buffer, "count=%d", &objectCount); *arr = malloc(objectCount*sizeof(struct cluster_t)); for (int i = 0; i < objectCount; i++) { init_cluster(&(*arr)[i], 1); if (fgets(buffer, 99, datafile) == NULL) { // Reached end of file - count given in file was greater than the amount of objects in file. fprintf(stderr, "In load_clusters:\nObject count stated by the first line (%d) is greater than the amount of objects in the file.\n", objectCount); return -1; } sscanf(buffer, "%d %f %f", &(*arr)[i].obj[0].id, &x, &y); if ((x >= 0 && x <= 1000) && (y >= 0 && y <= 1000)) { (*arr)[i].obj[0].x = x; (*arr)[i].obj[0].y = y; } else { // Loaded coordinate is out of range // *arr still has the adress of first member of the array fprintf(stderr, "In function load_clusters:\nThe #%d object's coordinates are out of range (0 <= COORDINATE <= 1000).\n", i); return -1; } (*arr)[i].size = 1; loadCount++; } if (fclose(datafile) == EOF) { // Failed to close file fprintf(stderr, "In function load_clusters:\nFailed to close the file %s.\n", filename); return -1; } return loadCount; } /* Tisk pole shluku. Parametr 'carr' je ukazatel na prvni polozku (shluk). Tiskne se prvnich 'narr' shluku. */ void print_clusters(struct cluster_t *carr, int narr) { printf("Clusters:\n"); for (int i = 0; i < narr; i++) { printf("cluster %d: ", i); print_cluster(&carr[i]); } } // TODO int main(int argc, char *argv[]) { if (argc > 1 && argc < 4) { struct cluster_t *clusters; int cluster1; int cluster2; int loadedClusters = load_clusters(argv[1], &clusters); if (loadedClusters == -1) { // Error loading clusters from file return 1; } int userInput = 1; if ((argc == 3) && (atoi(argv[2]) > userInput)) { userInput = atoi(argv[2]); } while (loadedClusters > userInput) { find_neighbours(clusters, loadedClusters, &cluster1, &cluster2); merge_clusters(&clusters[cluster1], &clusters[cluster2]); loadedClusters = remove_cluster(clusters, loadedClusters, cluster2); } print_clusters(clusters, loadedClusters); for (int i = 0; i < loadedClusters; i++) { free(clusters[i].obj); } free(clusters); return 0; } else { // Uncorrect arguments fprintf(stderr, "In function main:\nProgram was launched with %d arguments. Please launch the program with arguments ./proj3 filename.txt numberOfDesiredClusters (optional).\n", argc); return 1; } }
C
// ------------------------------------------------------------------ // exemple-mutex-type-3.c // Fichier d'exemple du livre "Developpement Systeme sous Linux" // (C) 2000-2010 - Christophe BLAESS -Christophe.Blaess@Logilin.fr // http://www.logilin.fr // ------------------------------------------------------------------ #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; int main (void) { int ret; fprintf(stderr, "Je deverrouille le mutex..."); ret = pthread_mutex_unlock(& mtx); fprintf(stderr, "retour %d\n", ret); pthread_exit(NULL); }
C
#include "Main.h" //socket variables int socket_desc; struct sockaddr_in server_addr; char msgBuffer[BUFLEN]; int main (int argc, char *argv[]) { initDataLists(); initSocket(); char *data; data = malloc(sizeof(char) * 255); int server_struct_length = sizeof(server_addr); while (1) { ProcessData(data); strcpy(msgBuffer, data); // Send the message to server: if(sendto(socket_desc, msgBuffer, BUFLEN, 0, (struct sockaddr*)&server_addr, server_struct_length) < 0){ printf("Unable to send message\n"); } memset(data, 0, (sizeof(char) * 255)); sleep(3); } free(data); close(socket_desc); } void initSocket () { socket_desc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(PORT); server_addr.sin_addr.s_addr = inet_addr(SERVERIP); if(socket_desc < 0){ printf("Error while creating socket\n"); } }
C
#include<stdio.h> int main() { int a = 3; //printf的计算顺序为从右往左 //后置--,在计算之前先保存一份 printf("%d %d %d\n",a--,a--,a--);//1,2,3 //前置--:待整个表达式计算完毕后才给出结果,之前的结果都不保存 printf("%d %d %d\n",--a,--a,--a);//-3,-3,-3 printf("%d %d %d\n",a--,--a,a--);//-5,-6,-3 return 0; }
C
/** * adc-sensor.h */ /** * adc sensor ϰϵģͨadcɼ * 1.ɱֵС2.ߴֵĴС */ #include "sensors.h" #include "stm8s_adc2.h" #include "adc-sensor.h" #include "stm8s_gpio.h" /** * ,ֵλ ŷķ * */ int get_resistance(int type, int adc) { long int r=0; if (type==ADC_TYPE_RW) {// r = 10000ul*adc/1024; } else if (type==ADC_TYPE_PHO) { r = 5000ul*adc/(1024-adc); } return (r); } static unsigned int state=0xff; int value(int type) { int ret = 0; if ((state==0xff)||(state==0x80)||(state==0x00)) { return (0x00); } if ((type==ADC_TYPE_RW)||(type==ADC_TYPE_PHO)) { ADC2_ConversionConfig(ADC2_CONVERSIONMODE_SINGLE, type, ADC2_CR2_ALIGN); ADC2_StartConversion(); while (!ADC2_GetFlagStatus()); ADC2_ClearFlag(); ret = get_resistance(type, ADC2_GetConversionValue()); } return (ret); } int configure(int type, int value) { int ret = 0; switch (type) { case SENSORS_HW_INIT://ʼadc state = 0x80; GPIO_Init(GPIOE, GPIO_PIN_7, GPIO_MODE_IN_FL_NO_IT); GPIO_Init(GPIOE, GPIO_PIN_6, GPIO_MODE_IN_FL_NO_IT); ADC2_Init(ADC2_CONVERSIONMODE_SINGLE, ADC2_CHANNEL_9, ADC2_PRESSEL_FCPU_D18, 0x00, DISABLE, ADC2_CR2_ALIGN, ADC2_CHANNEL_8, DISABLE); break; case SENSORS_ACTIVE://Ч state = value; if (state) { ADC2_Cmd(ENABLE); } else { ADC2_Cmd(DISABLE); } break; } return (ret); } int status(int type) { if (type==SENSORS_HW_INIT) { return (state==0x80); } else if (type==SENSORS_ACTIVE) { return (state); } return (0); } SENSORS_SENSOR(adc_sensor, ADC_SENSOR, value, configure, status);
C
#include<stdio.h> #include<string.h> void main() { char str[50]; int i,count=0; printf("enter the string:"); gets(str); for(i=0;str[i]!=NULL;i++) { if(str[i]=='.') { count++; } } printf("%d",count+1); }
C
#include "fractal.h" #include <inttypes.h> #include <math.h> #include <stdio.h> #include <time.h> #include <pthread.h> uint8_t gradient_pow(uint8_t gradient, uint8_t stepen) { uint8_t result; result = gradient; while (stepen-- != 1) { result *= gradient; } return (result); } t_color set_color(uint8_t r, uint8_t g, uint8_t b) { t_color color; color = r | (g << 8) | (b << 16) | 0xff000000; return (color); } int colors[1000]; void set_colors() { srand(time(0)); for (int i = 0; i < 1000; ++i) { // colors[i] = set_color(gradient_pow(i, g_colordepth.depth_r), // gradient_pow(i, g_colordepth.depth_g), // gradient_pow(i, g_colordepth.depth_b)); colors[i] = rand() % 256; colors[i] |= (rand() % 256) << 8; colors[i] |= (rand() % 256) << 16; colors[i] |= 0xff000000; } } void *fill_fractal_array(void *r) { // glClearColor(0.0, 0.0, 0.0, 0.0); t_complex c; t_rectangle *_r = (t_rectangle *)r; c.im = (long double)((-g_f->height) / 2 + g_f->y_0) / g_f->scale; long double delta = (long double)1 / g_f->scale; // printf("delta = %LG\n", delta); long double c_re_init = (long double)((-g_f->width) / 2 - g_f->x_0 + _r->x_0) / g_f->scale; for (int i = _r->y_0; i < _r->y_end; ++i) { c.im += delta; c.re = c_re_init; for (int j = _r->x_0; j < _r->x_end; ++j) { c.re += delta; size_t iterations = g_f->checker(c); if (iterations != g_f->iterations) { g_fractalarray->pixels_array[i][j] = colors[iterations]; } else { g_fractalarray->pixels_array[i][j] = 0; } } } return (NULL); } void draw(void) { fill_fractal(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Запомнить атрибут glPushAttrib(GL_CURRENT_BIT); //Вычислить предварительное положение начала вывода битового массива double x, y, z; //Видовая матрица GLdouble modelMatrix[16]; glGetDoublev(GL_MODELVIEW_MATRIX , modelMatrix); //Матрица проекций GLdouble projMatrix[16]; glGetDoublev(GL_PROJECTION_MATRIX, projMatrix); //Координаты области вывода GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); gluUnProject(viewport[0] + 1, viewport[1] + 1, 0, modelMatrix, projMatrix, viewport, &x, &y, &z); int dx, dy; dy = 0; dx = 0; int xp, yp; xp = g_f->x_pos; yp = g_f->y_pos; if (g_f->y_pos < y) { dy = y - g_f->y_pos; yp = y; } if (g_f->x_pos < x) { dx = x - g_f->x_pos; xp = x; } //Установить положение начала вывода битового массива glRasterPos2f(xp, yp); //Задать атрибуты вывода пикселов glPixelStorei(GL_UNPACK_ROW_LENGTH, g_f->width); //длина строки glPixelStorei(GL_UNPACK_SKIP_ROWS, dy); // сколько строк пропустить? glPixelStorei(GL_UNPACK_SKIP_PIXELS, dx); // сколько пикселов пропустить в каждой строке? //Отобразить пикселы на экране glDrawPixels(g_f->width - dx, g_f->height - dy, GL_RGBA, GL_UNSIGNED_BYTE, g_fractalarray->pixels_addr); //Вернуть исходные значения атрибутам вывода glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); //Вернуть атрибут glPopAttrib(); glFlush(); glutSwapBuffers(); } void fill_fractal(void) { const int thread_count = 1; glClearColor(0.0, 0.0, 0.0, 0.0); pthread_t pth[thread_count]; t_rectangle r[thread_count]; clock_t start, stop; start = clock(); for (int i = 0; i < thread_count; ++i) { r[i] = (t_rectangle){i * g_f->width / thread_count, 0, (i + 1) * g_f->width / thread_count, g_f->height}; if (0 != pthread_create(&pth[i], NULL, fill_fractal_array, &r[i])) { printf("%d error\n", i); } } for (int i = 0; i < thread_count; ++i) { pthread_join(pth[i], NULL); } stop = clock(); printf("FillTime = %f\n", (double)(stop - start) / CLOCKS_PER_SEC); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); g_f->x_pos = -g_f->width / 2; g_f->y_pos = -g_f->height / 2; g_f->is_keypressed = false; }
C
/**************************************** * Author: David Berman * * Last Update: 18/11/2019 * * Data structure: Sorted List * * Tester file. * * **************************************/ #include <stdio.h> #include <stdlib.h> /* for malloc */ #include <assert.h> /* for assert */ #include "pq.h" #include "tests.h" /******************************************************************************/ /*------------------------- Struct definition---------------------------------*/ typedef struct wrapper_for_cmp_func { int(*cmp_func)(void *, void *, void *); void *param; }cmp_wrapper; /******************************************************************************/ struct pq { sortlist_t *sortlist; cmp_wrapper *wrapper; }; /******************************************************************************/ /*------------------------- Auxilary function --------------------------------*/ static int IntCmp(void *data1, void *data2, void *param); static pq_t *TestingPQEnqueue(int data[], size_t data_len); static void TestingPQDequeue(pq_t *pq, size_t len); static void TestingPQSize(pq_t *pq, size_t expected); static void TestingPQIsEmpty(pq_t *pq, int expected); static int PrintIntList(void *data, void *param); static void PrintList(const sortlist_t *list); static int IsMatchIntFunc(const void *data, void *param); static void TestPQErase(pq_t *pq, void *data_to_erase); static void TestPQClear(pq_t *pq); /******************************************************************************/ /*------------------------- main function ------------------------------------*/ int main (void) { pq_t *pq1 = NULL; pq_t *pq2 = NULL; int(*cmp_func)(void *, void *, void *) = &IntCmp; int data[] = {10,4,7,3,2,6,5,1,9,8}; OpenTestFile("PQ.txt"); /* Testing Create */ pq1 = PQCreate(cmp_func, NULL); CheckResult(NULL != pq1, "TestPQCreateCreate"); PQDestroy(pq1); /* Testing Enqueue */ pq2 = TestingPQEnqueue(data, 10); PrintList(pq2->sortlist); TestingPQSize(pq2, 10); /* Testing Dequeue */ TestingPQDequeue(pq2, 10); PrintList(pq2->sortlist); TestingPQIsEmpty(pq2, 1); PQDestroy(pq2); /* Testing Erase */ pq2 = TestingPQEnqueue(data, 10); PrintList(pq2->sortlist); TestingPQSize(pq2, 10); TestPQErase(pq2, &data[3]); PrintList(pq2->sortlist); /* Testing Clear */ TestPQClear(pq2); PrintList(pq2->sortlist); PQDestroy(pq2); printf("Thank you Moran for testing my code :)\n"); printf(" Eize Rosh Yesh Lah :)\n"); TestResult(); return 0; } /******************************************************************************/ /*------------------------- TestingPQEnqueue function--------------------------*/ static pq_t *TestingPQEnqueue(int data[], size_t data_len) { pq_t *pq = NULL; size_t i = 0; assert(NULL != data); pq = PQCreate(IntCmp, NULL); for (; i < data_len ; ++i) { CheckResult(PQSize(pq) == i, "TestPQEnqueue"); PQEnqueue(pq, data + i); } return pq; } /******************************************************************************/ /*------------------------- TestingPQDequeue function-------------------------*/ static void TestingPQDequeue(pq_t *pq, size_t len) { size_t i = len; assert(NULL != pq); for (; 0 < i ; --i) { CheckResult(PQSize(pq) == i, "TestPQDequeue"); PQDequeue(pq); } } /******************************************************************************/ /*------------------------- TestingPQSize function----------------------------*/ static void TestingPQSize(pq_t *pq, size_t expected) { assert(NULL != pq); CheckResult(PQSize(pq) == expected, "TestPQSize"); } /******************************************************************************/ /*------------------------- TestingPQIsEmpty function-------------------------*/ static void TestingPQIsEmpty(pq_t *pq, int expected) { assert(NULL != pq); CheckResult(PQIsEmpty(pq) == expected, "TestPQIsEmpty"); } /******************************************************************************/ /*------------------------- IntCmp function ----------------------------------*/ static int IntCmp(void *data1, void *data2, void *param) { (void)param; assert(NULL != data1); assert(NULL != data2); return (*(int *)data1 - *(int *)data2); } /******************************************************************************/ /*------------------------- IsMatchIntFunc------------------------------------*/ static int IsMatchIntFunc(const void *data, void *param) { if (*(int *)data == *(int *)param) { return 1; } else { return 0; } } /******************************************************************************/ /*------------------------- TestPQClear function------------------------------*/ static void TestPQClear(pq_t *pq) { assert(NULL != pq); PQClear(pq); CheckResult(PQSize(pq) == 0, "TestPQClear"); } /******************************************************************************/ /*------------------------- TestPQErase function------------------------------*/ static void TestPQErase(pq_t *pq, void *data_to_erase) { void *res_of_erase = NULL; assert(NULL != pq); res_of_erase = PQErase(pq, IsMatchIntFunc, data_to_erase); CheckResult(*(int *)res_of_erase == *(int *)data_to_erase, "TestPQErase"); } /******************************************************************************/ /*------------------------- PrintIntList function-----------------------------*/ static int PrintIntList(void *data, void *param) { (void)param; printf(" %d <-->", *(int *)data); return 0; } /******************************************************************************/ /*------------------------- PrintList function--------------------------------*/ static void PrintList(const sortlist_t *list) { sortlist_iter_t start_of_list = {NULL}; sortlist_iter_t end_of_list = {NULL}; int (*print_func)(void *, void *) = &PrintIntList; assert(NULL != list); start_of_list = SortedListBegin(list); end_of_list = SortedListEnd(list); printf("NULL <-- DUMMY <-->"); SortedListForEach(start_of_list, end_of_list, print_func, NULL); printf(" DUMMY --> NULL\n\n"); }
C
/* ** ressources.c for keylogger in /home/azword/delivery/Perso/PSU/Keylogger/src ** ** Made by Nathan Tréhout | Az' ** Login <nathan.trehout@epitech.eu> ** ** Started on Sat Dec 31 15:07:23 2016 Nathan Trehout ** Last update Sat Dec 31 15:07:30 2016 Nathan Trehout */ #include "my.h" char retmaj(char dest) { char a; (dest >= 97 && dest <= 122) ? a = dest - 32 : 0; return (a); } char *retmaj_bis(char *dest) { char *a; (strcmp(dest, "&") == 0) ? a = "1" : 0; (strcmp(dest, "é") == 0) ? a = "2" : 0; (*dest == 34) ? a = "3" : 0; (strcmp(dest, "'") == 0) ? a = "4" : 0; (strcmp(dest, "(") == 0) ? a = "5" : 0; (strcmp(dest, "-") == 0) ? a = "6" : 0; (strcmp(dest, "è") == 0) ? a = "7" : 0; (strcmp(dest, "_") == 0) ? a = "8" : 0; (strcmp(dest, "ç") == 0) ? a = "9" : 0; (strcmp(dest, "à") == 0) ? a = "0" : 0; (strcmp(dest, ")") == 0) ? a = "°" : 0; (strcmp(dest, "=") == 0) ? a = "+" : 0; (strcmp(dest, "^") == 0) ? a = "¨" : 0; (strcmp(dest, "$") == 0) ? a = "£" : 0; (strcmp(dest, "ù") == 0) ? a = "%" : 0; (strcmp(dest, "*") == 0) ? a = "µ" : 0; (strcmp(dest, "<") == 0) ? a = ">" : 0; (strcmp(dest, ",") == 0) ? a = "?" : 0; (strcmp(dest, ";") == 0) ? a = "." : 0; (strcmp(dest, ":") == 0) ? a = "/" : 0; (strcmp(dest, "!") == 0) ? a = "§" : 0; return (a); } char *convert_to_key(int nb) { char **dest; dest = malloc(sizeof(char *) * 128); dest[4] = malloc(sizeof(char)); dest[1] = "ECHAP"; dest[59] = "F1"; dest[60] = "F2"; dest[61] = "F3"; dest[62] = "F4"; dest[63] = "F5"; dest[64] = "F6"; dest[65] = "F7"; dest[66] = "F8"; dest[67] = "F9"; dest[68] = "F10"; dest[87] = "F11"; dest[88] = "F12"; dest[110] = "INSERT"; dest[99] = "IMPR. ECRAN"; dest[111] = "SUPPR."; dest[41] = "²"; dest[2] = "&"; dest[3] = "é"; *dest[4] = 34, dest[4][1] = '\0'; dest[5] = "'"; dest[6] = "("; dest[7] = "-"; dest[8] = "è"; dest[9] = "_"; dest[10] = "ç"; dest[11] = "à"; dest[12] = ")"; dest[13] = "="; dest[14] = "BACKSPACE"; dest[102] = "ORIGINE"; dest[15] = "TAB"; dest[16] = "a"; dest[17] = "z"; dest[18] = "e"; dest[19] = "r"; dest[20] = "t"; dest[21] = "y"; dest[22] = "u"; dest[23] = "i"; dest[24] = "o"; dest[25] = "p"; dest[26] = "^"; dest[27] = "$"; dest[28] = "ENTREE"; dest[104] = "PREVPG"; dest[58] = "MAJ"; dest[30] = "q"; dest[31] = "s"; dest[32] = "d"; dest[33] = "f"; dest[34] = "g"; dest[35] = "h"; dest[36] = "j"; dest[37] = "k"; dest[38] = "l"; dest[39] = "m"; dest[40] = "ù"; dest[43] = "*"; dest[109] = "NXTPG"; dest[42] = "LSHIFT"; dest[86] = "<"; dest[44] = "w"; dest[45] = "x"; dest[46] = "c"; dest[47] = "v"; dest[48] = "b"; dest[49] = "n"; dest[50] = ","; dest[51] = ";"; dest[52] = ":"; dest[53] = "!"; dest[54] = "RSHIFT"; dest[107] = "END"; dest[29] = "LCTRL"; dest[125] = "DEM"; dest[56] = "ALT"; dest[57] = "SPACE"; dest[100] = "ALTGR"; dest[127] = "CR.DR"; dest[97] = "RCTRL"; dest[105] = "LEFT"; dest[103] = "UP"; dest[108] = "DOWN"; dest[106] = "RIGHT"; return (dest[nb]); } char *retaltgr(char *dest) { char *a; a = malloc(sizeof(char) * 2); (strcmp(dest, "é") == 0) ? a = "~" : 0; (*dest == 34) ? a = "#": 0; (strcmp(dest, "'") == 0) ? a = "{" : 0; (strcmp(dest, "(") == 0) ? a = "[" : 0; (strcmp(dest, "-") == 0) ? a = "|" : 0; (strcmp(dest, "è") == 0) ? a = "`" : 0; (strcmp(dest, "_") == 0) ? *a = 92, a[1] = '\0' : 0; (strcmp(dest, "ç") == 0) ? a = "^" : 0; (strcmp(dest, "à") == 0) ? a = "@" : 0; (strcmp(dest, ")") == 0) ? a = "]" : 0; (strcmp(dest, "=") == 0) ? a = "}" : 0; (strcmp(dest, "$") == 0) ? a = "ø" : 0; return (a); }
C
//LCD (PortB) #define E LATAbits.LATA0 //#define R_W LATBbits.LATB6 #define RS LATAbits.LATA1 #define LCDdata LATB #define rw_delay 20 void command(unsigned char); void write(unsigned char); void Nybble(unsigned char); void Lcd_init(void); void Lcd_PutMessage(rom char *); void Lcd_PutMessageArray(unsigned char[]); void Lcd_PutMessageChar(unsigned char); //Write a string to the LCD void Lcd_PutMessage(rom char *Message){ rom char *Pos = Message; while(*Pos!=0) write(*Pos++); } void Lcd_PutMessageChar(unsigned char Message){ unsigned char *Pos = Message; while(*Pos!=0) write(*Pos++); } void Lcd_PutMessageArray(unsigned char m[]){ unsigned char Pos = 0; while(m[Pos]!=0) { write(m[Pos]); Pos++; } } /**********************************************************/ //4-bit methods for LCD /**********************************************************/ void command(unsigned char i) { RS =0; //R_W =0; //R/W=LOW : Write Nybble(i); //Send upper 4 bits Nybble(i<<4); //Send lower 4 bits Delay1KTCYx(2); //must wait at least 2mS (2*1000*4/1e6 = 8ms used) } void write(unsigned char i) { RS =1; //R_W =0; //R/W=LOW : Write Nybble(i); //Send upper 4 bits Nybble(i<<4); //Send lower 4 bits Delay1KTCYx(2); //must wait 2mS } /**********************************************************/ void Nybble(unsigned char dat) { dat &= 0xf0; //clear bottom bits of dat LCDdata &= 0x0f; //clear top bits of port (interested only in DB7-DB4) LCDdata |= dat; //or the two and store at port E = 1; Delay1TCY(); //enable pulse width >= 300ns (used 4uS) E = 0; //Clock enable: falling edge } /**********************************************************/ void Lcd_init(void) { LCDdata=0x00; Delay1KTCYx(15); //Wait >15 msec after power is applied (used 20mS) Nybble(0x3); //command 0x30 = Wake up Delay1KTCYx(5); //must wait 160us, busy flag not available (used 160uS) Nybble(0x3); //command 0x30 = Wake up #2 Delay1KTCYx(5); //must wait 160us, busy flag not available (used 160uS) command(0x20); //Function set: 4-bit/2-line Delay1KTCYx(1); command(0x2c); //Function set: 4-bit/2-line Delay1KTCYx(1); command(0x10); //Set cursor Delay1KTCYx(1); command(0x01); //Clear Display (Added) Delay1KTCYx(1); command(0x06); //Entry Mode set Delay1KTCYx(1); command(0x0c); } void Lcd_clearDisplay(void) { command(0x01); Delay1KTCYx(1); } void Lcd_cursorHome(void) { command(0x02); Delay1KTCYx(1); } void Lcd_newLine(void) { command(0xc0); Delay1KTCYx(1); } /**********************************************************/ //End methods for LCD /**********************************************************/
C
#include <avr/io.h> #include <avr/eeprom.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include "structs.h" #include "eeproms.h" #include "library/LUFA/Version.h" #include "library/LUFA/Drivers/USB/USB.h" #include "hardware/rtc.h" #include "hardware/led.h" #include "ISS-Notify.h" #include "commands.h" /******************************************************************************* * COMMANDS *******************************************************************************/ /** * Acknowledge. Lets a client know that it's here and talking. * Replies: 'ack' to the USB serial stream */ void ack(void) { fputs("ack", &USBSerialStream); } /** * Say milliseconds * Replies: current number of milliseconds since boot. For debug purposes. */ void say_ms(void) { fprintf(&USBSerialStream, "%lu", millis()); } /** * Set the user defined color for diplaying passes * Replies: 'set' if successfull */ void set_color(void) { int color; if (fscanf(&USBSerialStream,"%d", &color) == 1) { eeprom_update_word((uint16_t*) &NonVolatileColor, (uint16_t)color); fputs("set", &USBSerialStream); } else fputs("err", &USBSerialStream); } /** * Say Time. Will repsond with a date time stamp from the RTC * Replies: timestamp */ void say_time(void) { time now = get_time(); fprintf(&USBSerialStream, "Y%02dM%02dD%02dH%02dM%02dS%02d", now.year, now.month, now.day, now.hour, now.minute, now.second); } /** * Set upcoming passes. Writes the incoming pass data to EEPROM storage */ void set_passes(void) { // Parse incoming data uint8_t i; int num; ipass block[MAXPASS]; if (fscanf(&USBSerialStream,"%d\n", &num) == 1) { // Loop through incoming data for (i=0;i<num;i++) { uint32_t t; uint16_t d; ipass p; if (fscanf(&USBSerialStream, "%lu,%u,", &t, &d) == 2) { p.time = t; p.duration = d; block[i] = p; } } // Write to eeprom eeprom_update_block((const void * ) &block, (void*) &StoredISSPasses, sizeof(ipass)*num); eeprom_update_byte((uint8_t*) &NumOfStoredISSPasses, (uint8_t) num); fputs("set", &USBSerialStream); } else fputs("err", &USBSerialStream); } /** * Dump Current Memory. Dumps the EEPROM blocks over USB stream * Mostly for debug. */ void dump_mem(void) { uint8_t i; uint16_t color; color = eeprom_read_word((uint16_t*) &NonVolatileColor); uint8_t npass; npass = eeprom_read_byte((uint8_t*) &NumOfStoredISSPasses); if (npass > MAXPASS) npass = MAXPASS; // Echo data fprintf(&USBSerialStream, "0x00 - color: %d|", (int) color); fprintf(&USBSerialStream, "0x01 - npasses: %d|", (int) npass); ipass block[MAXPASS]; eeprom_read_block((void*) &block, (const void *) &StoredISSPasses, sizeof(ipass)*npass); for (i=0;i<npass;i++) { fprintf(&USBSerialStream, "0x%02d - pass: %lu:%u|", i+2, block[i].time, block[i].duration); } } /** * Set The Date and Time on the RTC. */ void set_clock(void) { reset_rtc(); // set time int year, month, day, hour, min, sec; if (fscanf(&USBSerialStream,"Y%dM%dD%dH%dM%dS%d", &year, &month, &day, &hour, &min, &sec) == 6) { time t = mktime((uint8_t) year, (uint8_t) month, (uint8_t) day, (uint8_t) hour, (uint8_t) min, (uint8_t) sec); set_time(t); fputs("set", &USBSerialStream); } else fputs("err", &USBSerialStream); } /** * Show a red value of for whitebalance */ void wb_red(void) { uint8_t i; int v; if (fscanf(&USBSerialStream,"%d", &v) == 1) { for (i=0;i<8;i++) { show[i][0] = 0xffff; show[i][1] = 0xffff; show[i][2] = 0xffff; } TLC_Red_WB = v; led(show); fputs("set", &USBSerialStream); } else fputs("err", &USBSerialStream); } /** * Show a green value of for whitebalance */ void wb_green(void) { uint8_t i; int v; if (fscanf(&USBSerialStream,"%d", &v) == 1) { for (i=0;i<8;i++) { show[i][0] = 0xffff; show[i][1] = 0xffff; show[i][2] = 0xffff; } TLC_Green_WB = v; led(show); fputs("set", &USBSerialStream); } else fputs("err", &USBSerialStream); } /** * Show a blue value of for whitebalance */ void wb_blue(void) { uint8_t i; int v; if (fscanf(&USBSerialStream,"%d", &v) == 1) { for (i=0;i<8;i++) { show[i][0] = 0xffff; show[i][1] = 0xffff; show[i][2] = 0xffff; } TLC_Blue_WB = v; led(show); fputs("set", &USBSerialStream); } else fputs("err", &USBSerialStream); } /** * Set the whitebalance. */ void set_wb(void) { uint8_t i; int b,g,r; if (fscanf(&USBSerialStream,"%d,%d,%d", &b,&g,&r) == 3) { for (i=0;i<8;i++) { show[i][0] = 0; show[i][1] = 0; show[i][2] = 0; } TLC_Blue_WB = b; TLC_Green_WB = g; TLC_Red_WB = r; eeprom_update_byte((uint8_t*) &NonVolatile_Blue_WB, (uint8_t) b); eeprom_update_byte((uint8_t*) &NonVolatile_Green_WB, (uint8_t) g); eeprom_update_byte((uint8_t*) &NonVolatile_Red_WB, (uint8_t) r); led(show); fputs("set", &USBSerialStream); } else fputs("err", &USBSerialStream); } /** * Updates all the LEDs to a user defined color */ void show_color(void) { int b,g,r,i; if (fscanf(&USBSerialStream,"%d,%d,%d", &b,&g,&r) == 3) { for (i=0;i<8;i++) { show[i][0] = b; show[i][1] = g; show[i][2] = r; } led(show); } else fputs("err", &USBSerialStream); } /** * Easteregg: Toggle Rainbow mode. */ void toggle_rainbow(void) { int i; if (do_rainbow) { do_rainbow = false; for (i=0;i<8;i++) { show[i][0] = 0; show[i][1] = 0; show[i][2] = 0; } led(show); } else do_rainbow = true; } /** TODO: // set alarm if (fscanf(&USBSerialStream,"AY%dM%dD%dH%dM%dS%d", &year, &month, &day, &hour, &min, &sec) == 6) { time t = mktime((uint8_t) year, (uint8_t) month, (uint8_t) day, (uint8_t) hour, (uint8_t) min, (uint8_t) sec); set_alarm0(t); fputs("set", &USBSerialStream); } char ra; if (fscanf(&USBSerialStream,"ra%c", &ra) == 1) { // Echo clear_alarm0(); fputs("reset alarm", &USBSerialStream); } */
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include "msgQueue.h" queue* CreateQueue() { queue* obj = (queue*)malloc(sizeof(queue)); if (obj == NULL) return NULL; obj->front = 0; obj->rear = 0; obj->len = 0; memset(obj->data, 0, sizeof(obj->data)); return obj; } void DestoryQueue(queue* obj) { int i; int front = obj->front; int rear = obj->rear; for (i = front; i != rear; i = (i + 1) % MAX) { if (obj->data[i] != NULL) { free(obj->data[i]); obj->data[i] = NULL; } } free(obj); } void Push(queue* obj, char* data) { int len = obj->len + 1; if (len >= MAX) { //Ҫ return; } obj->len++; int size = strlen(data); obj->data[obj->rear] = (char*)malloc(size + 1); int i; for (i = 0; i <= size; i++) { obj->data[obj->rear][i] = data[i]; //'\0'Ҳ } obj->rear++; obj->rear %= MAX; return; } void Pop(queue* obj) { obj->len--; free(obj->data[obj->front]); obj->data[obj->front] = NULL; obj->front++; obj->front %= MAX; } char* Front(const queue* obj) { return obj->data[obj->front]; } char* Rear(const queue* obj) { int i = (obj->rear - 1 + MAX) % (MAX); return obj->data[i]; } int QueueLenth(const queue* obj) { return obj->len; } int Empty(const queue* obj) { if (obj->len == 0) return 1; else return 0; } int Full(const queue* obj) { if (obj->len == MAX - 1) { return 1; } else { return 0; } } int frontIndex(const queue* obj) { return obj->front; } int nextIndex(const queue* obj) { return obj->rear ; } int QueueMod(int index) { return (index + MAX) % MAX; }
C
/** * @file dpatch/status.c * * `dpatch/status.c` defines functions for querying the status of dpatch. * * @author H Paterson. * @copyright BSL-1.0. * @date November 2020. */ #include "status.h" char* status_strings[] = { [DPATCH_STATUS_OK] = "Success", [DPATCH_STATUS_ERROR] = "General, unspecified, or unknown error", [DPATCH_STATUS_ENOMEM] = "Memory (re)allocation failed", [DPATCH_STATUS_EMPROT] = "Failed to modify memory protection", [DPATCH_STATUS_EUNKNOWN] = "Unsupported or unknown patch operation", [DPATCH_STATUS_EDYN] = "Error accessing dynamic symbols", [DPATCH_STATUS_EFILE] = "File I/O error", [DPATCH_STATUS_ESYNTAX] = "Script parsing error" }; /** * Get a human readable string describing a status code. * * @param status Status code to translate. * @return Pointer to a string describing the error. */ const char* str_status(dpatch_status status) { return status_strings[status]; }
C
int toten(int,char *); void tento(int,char *,int); int main() { int a,b,sum; char x[100]; scanf("%d %s %d",&a,x,&b); sum=toten(a,x); tento(sum,x,b); puts(x); return 0; } int toten(int a,char *x) { int n=strlen(x); char as[100]; int sum=0,i,j,c,b[100]; for(i=0;i<n;i++) { if('a'<=x[i]&&x[i]<='z') b[i]=x[i]-'a'+10; if('A'<=x[i]&&x[i]<='Z') b[i]=x[i]-'A'+10; if('0'<=x[i]&&x[i]<='9') b[i]=x[i]-'0'; sum+=b[i]*pow(a*1.0,n-i-1); } return sum; } void tento(int sum,char *x,int b) { int a[100],i=0,j,c[100]; i=0; if(sum==0) {x[0]='0'; x[1]='\0';} else { while(sum>0) { a[i]=sum%b; sum=(sum-a[i])/b; i++; } for(j=0;j<i;j++) { c[j]=a[i-1-j]; } for(j=0;j<i;j++) { if(c[j]<=9) x[j]=c[j]+'0'; else x[j]=c[j]-10+'A'; } x[i]='\0'; } }
C
#include<stdio.h> void main() { int n,c,i; printf("\n enter the number"); scanf("%d",&n); for(i=1;i<=n;i++) { if(n%i==0) { c++; } } if(c!=2) { printf("\n composite"); } getch(); }
C
#include <stdarg.h> #include <stdio.h> #include "sls_buffer.h" #include "sls_tinytest.h" static int read_known_string(sls_buffer* b) { TINYTEST_ASSERT(sls_buffer_getc(b) == 'a'); TINYTEST_ASSERT(sls_buffer_getc(b) == 'b'); TINYTEST_ASSERT(sls_buffer_getc(b) == 'c'); TINYTEST_ASSERT(sls_buffer_getc(b) == 'd'); TINYTEST_ASSERT(sls_buffer_getc(b) == 'e'); TINYTEST_ASSERT(sls_buffer_getc(b) == 'f'); TINYTEST_ASSERT(sls_buffer_getc(b) == 'g'); TINYTEST_ASSERT(sls_buffer_getc(b) == EOF); return 1; } static int read_from_string(const char* pName) { sls_buffer* b = sls_buffer_create_from_str("abcdefg", 2); read_known_string(b); sls_buffer_destroy(b); return 1; } static int peek_does_not_advance_stream(const char* pname) { sls_buffer* b = sls_buffer_create_from_str("abcdefg", 2); int i = 0; while ( i++ < 1000 ) sls_buffer_peek(b); read_known_string(b); sls_buffer_destroy(b); return 1; } static int read_from_file(const char* pName) { sls_buffer* b = sls_buffer_create_from_file("data/citylots.json", 4096); char c = 0; while((c = sls_buffer_getc(b)) != EOF); sls_buffer_destroy(b); return 1; } TINYTEST_START_SUITE(buffer); TINYTEST_ADD_TEST(read_from_string, NULL, NULL); TINYTEST_ADD_TEST(peek_does_not_advance_stream, NULL, NULL); TINYTEST_ADD_TEST(read_from_file, NULL, NULL); TINYTEST_END_SUITE(); TINYTEST_MAIN_SINGLE_SUITE(buffer);
C
# include <stdio.h> # include <stdlib.h> # include "BinaryTree.h" int pos = 0; void menu() { char menu[12][50] = { "************************************", "** Binary Tree **", "************************************", "** 1.Initialize binary tree **", "** 2.Destroy binary tree **", "** 3.Creat binary tree **", "** 4.Pre-order traverse **", "** 5.In-order traversal **", "** 6.Post-order traversal **", "** 7.Level order traverse **", "** 8.Calculate prefix expression**", "************************************" }; printf("\n\n"); for(int i=0; i<12; i++) printf("%s\n",menu[i]); printf("\n\n"); } void operatFun(BiTree T) { Status init = ERROR;//用于判断是否已初始化 Status isCreat = ERROR; int Operand; printf("input operand(1-8,0 to quit):"); while(1) { if(!scanf("%d",&Operand)) { while(getchar()!='\n') continue; printf("not a number,you need to enter a number between 1 and 8.\ntry again:"); continue; } else if(Operand < 1 || Operand >8) { if(Operand == 0) { printf("byb~\n"); break; } printf("wrong range,you need to enter a number between 1 and 8.\ntry again:"); continue; } switch(Operand) { case 1: init = InitBiTree(&T); if(init) printf("initialization successful.\n"); break; case 2: if(init) { if(DestroyBiTree(&T)); printf("destroy the binary tree successfully.\n"); } else printf("please initialize first.\n"); break; case 3: { if(init) { printf("input expression to creat binary tree(Use '#' to indicate an empty subtree):\n"); char a[100]; scanf("%s",a); int count=0,length = 0;//计算输入的'#'数目,判断是否输入正确 for(int i=0; a[i]!='\0';i++) { if(a[i] == '#') count++; length++; } if(length/2+1 == count)//输入正确 isCreat = CreateBiTree(&T,a); else { printf("wrong enter,try again.\n"); break; } if(isCreat) printf("constructing a binary tree successfully.\n"); } else printf("please initialize first.\n"); break; } case 4: if(isCreat) { if(PreOrderTraverse(T,visit)) printf("\ntraversal completed.\n"); } else printf("please creat a binary tree first.\n"); break; case 5: if(isCreat) { if(InOrderTraverse(T,visit)) printf("\ntraversal completed.\n"); } else printf("please creat a binary tree first.\n"); break; case 6: if(isCreat) { if(PostOrderTraverse(T,visit)) printf("\ntraversal completed.\n"); } else printf("please creat a binary tree first.\n"); break; case 7: if(isCreat) { if(LevelOrderTraverse(T,visit)) printf("\ntraversal completed.\n"); } else printf("please creat a binary tree first.\n"); break; case 8: { int result = Value(T); if(result > 1000 || result < -1000) { printf("wrong enter,try again.\n"); break; } printf("=%d\n",result); break; } } printf("input operand(1-8,0 to quit):"); } } //二叉树初始化 Status InitBiTree(BiTree *T) { *T = NULL; pos = 0; return SUCCESS; } //构建二叉树 Status CreateBiTree(BiTree *T, char* definition) { char c = definition[pos++]; (*T) = (BiTree)malloc(sizeof(BiTNode)); (*T)->data = c; (*T)->lchild = NULL; (*T)->rchild = NULL; if(c!='#') { CreateBiTree(&((*T)->lchild),definition); CreateBiTree(&((*T)->rchild),definition); } return SUCCESS; } //销毁二叉树 Status DestroyBiTree(BiTree *T) { if(*T != NULL) { DestroyBiTree(&((*T)->lchild)); DestroyBiTree(&((*T)->rchild)); free(*T); } return SUCCESS; } //遍历函数 Status visit(TElemType e) { if(e != '#') printf("%c",e); return SUCCESS; } //先序遍历 Status PreOrderTraverse(BiTree T, Status (*visit)(TElemType e)) { if(T) { visit(T->data); PreOrderTraverse(T->lchild,visit); PreOrderTraverse(T->rchild,visit); } return SUCCESS; } //中序遍历 Status InOrderTraverse(BiTree T, Status (*visit)(TElemType e)) { if(T) { InOrderTraverse(T->lchild,visit); visit(T->data); InOrderTraverse(T->rchild,visit); } return SUCCESS; } //后序遍历 Status PostOrderTraverse(BiTree T, Status (*visit)(TElemType e)) { if(T) { PostOrderTraverse(T->lchild,visit); PostOrderTraverse(T->rchild,visit); visit(T->data); } return SUCCESS; } //层序遍历 Status LevelOrderTraverse(BiTree T, Status (*visit)(TElemType e)) { Queue Q; initQueue(&Q); if(T) { EnQueue(&Q,T->data); visit(T->data); } while(Q.length != 0) { DeQueue(&Q); if(T->lchild) { visit(T->lchild->data); EnQueue(&Q,T->lchild->data); } if(T->rchild) { visit(T->rchild->data); EnQueue(&Q,T->rchild->data); } if(T->lchild) T = T->lchild; else if(T->rchild) T = T->rchild; } return SUCCESS; } //初始化队列 void initQueue(Queue * Q) { Q->front = Q->rear = (QueNode*)malloc(sizeof(QueNode)); Q->length = 0; } //入队操作 void EnQueue(Queue *Q,TElemType e) { Q->rear->next = (QueNode*)malloc(sizeof(QueNode)); Q->rear = Q->rear->next; Q->rear->data = e; Q->length ++; } //出队操作 void DeQueue(Queue *Q) { QueNode *p = Q->front; Q->front = Q->front->next; free(p); (Q->length) --; } //输入前缀表达式并计算结果 int Value(BiTree T) { InitBiTree(&T); printf("input prefix expression(Use '#' to indicate an empty subtree):\n"); char a[100]; scanf("%s",a); //创建二叉树 int result;//计算结果 int count=0,length = 0;//计算输入的'#'数目,判断是否输入正确 for(int i=0; a[i]!='\0';i++) { if(a[i] == '#') count++; length++; } if(length/2+1 == count)//输入正确 { CreateBiTree(&T,a); if(isOper(T->data)) result = cal(T); //以中缀输出表达式 InOrderTraverse(T,visit); } return result; } //计算,类似中序遍历 int cal(BiTree T) { int result; char c = T->data; if(isOper(T->data))//若为操作符,分别计算左右子树 { switch(c) { case '+': result = cal(T->lchild) + cal(T->rchild); break; case '*': result = cal(T->lchild) * cal(T->rchild); break; case '-': result = cal(T->lchild) - cal(T->rchild); break; case '/': result = cal(T->lchild) / cal(T->rchild); break; } } if(isNum(T->data)) //数字为叶子节点,直接返回 { result = T->data - '0'; } return result; } //判断是否数字 Status isNum(TElemType e) { if(e >= '1' && e <= '9') return SUCCESS; return ERROR; } //判断是否操作符 Status isOper(TElemType e) { char oper[4] = {'+','-','*','/'}; for(int i=0; i<4; i++) { if(e == oper[i]) return SUCCESS; } return ERROR; }
C
#include <stdio.h> #include <stdlib.h> #include <mpi.h> #define MASTER 0 int main(int argc, char* argv[]) { if (argc!=3){ printf("\n Usage %s input file, output file \n",argv[0]); return -1; } int rank,size,n,chunk; MPI_Status status; MPI_Datatype rowtype; MPI_Datatype coltype; MPI_Datatype matrixtype; MPI_Init (&argc, &argv); MPI_Comm_rank (MPI_COMM_WORLD, &rank); MPI_Comm_size (MPI_COMM_WORLD, &size); /*Initialize the matrices*/ double** A; double** B; double** C; int* send_counts; int* displs; /*Read the input file and create the matrices A and B*/ if(rank==MASTER){ FILE *input=fopen(argv[1],"r"); fscanf(input,"%d",&n); A=(double **)malloc(n*sizeof(double*)); B = (double **)malloc(n*sizeof(double*)); C=(double **)malloc(n*sizeof(double*)); for(int i=0;i<n;i++){ A[i] = (double*)malloc(n*sizeof(double)); B[i] = (double*)malloc(n*sizeof(double)); C[i] = (double*)malloc(n*sizeof(double)); } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ fscanf(input,"%lf",&A[i][j]); } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ fscanf(input,"%lf",&B[i][j]); } } fclose(input); } MPI_Scatter(&n,1,MPI_INT,&n,1,MPI_INT,MASTER,MPI_COMM_WORLD); chunk = n/size; double** block_A = (double **)malloc(n*sizeof(double*)); double** block_C = (double **)malloc(n*sizeof(double*)); for(int i=0;i<n;i++){ block_A[i] = (double*)malloc(chunk*sizeof(double)); block_C[i] = (double*)malloc(chunk*sizeof(double)); } if(rank!=MASTER){ B = (double **)malloc(n*sizeof(double*)); for(int i=0;i<n;i++){ B[i] = (double*)malloc(n*sizeof(double)); } } //MPI_Scatter(B,n*n,MPI_DOUBLE,B,n*n,MPI_DOUBLE,MASTER,MPI_COMM_WORLD); /* if(rank == 1){ printf("B: %lf \n", B[0][0]); }*/ /*Print the input matrices*/ //if(rank==1){ /*for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ printf("%lf ",A[i][j]); } printf("\n "); }*/ /* printf("\n "); printf("\n "); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ printf("%lf ",B[i][j]); } printf("\n "); }*/ // } /*partition A row wise and B column wise*/ MPI_Type_vector(chunk,n,n, MPI_DOUBLE, &rowtype); MPI_Type_vector(n,chunk,n, MPI_DOUBLE, &coltype); MPI_Type_vector(n,n,1,MPI_DOUBLE, &matrixtype); MPI_Type_commit(&rowtype); MPI_Type_commit(&coltype); MPI_Type_commit(&matrixtype); if(rank==MASTER){ for(int i=1; i<size;i++){ MPI_Send(&A[i*chunk][0], 1,rowtype,i, 111,MPI_COMM_WORLD); MPI_Send(&B[0][0],1,matrixtype,i,333,MPI_COMM_WORLD); } /*for (int i=0;i<chunk; i++) { for (int j=0;j<n;j++) { for(int k=0;k<n;k++){ C[i][j]+= A[i][k]*B[k][j]; } } }*/ C[0][0]=19; C[0][1]=22; for(int i=1;i<size;i++){ MPI_Recv(&C[i*chunk][0],1,rowtype, i, 222, MPI_COMM_WORLD, &status); } } else{ MPI_Recv(&block_A[0][0],1,rowtype, 0, 111, MPI_COMM_WORLD, &status); MPI_Recv(&B[0][0],1,matrixtype, 0, 333, MPI_COMM_WORLD, &status); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ printf("%lf ",B[i][j]); } printf("\n"); } //printf("first: %lf second: %lf \n", block_A[0][0], block_A[0][1]); for (int i=0; i<chunk; i++) { for (int j=0;j<n;j++) { for(int k=0;k<n;k++){ printf("Test print %lf \n", B[k][j]); block_C[i][j] += block_A[i][k]*B[k][j]; } } } //block_C[0][0]=43; //block_C[0][1]=50; MPI_Send(&block_C[0][0], 1,rowtype,0, 222,MPI_COMM_WORLD); } if(rank==MASTER){ printf("\n "); printf("\n "); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ printf("%lf ",C[i][j]); } printf("\n "); } } MPI_Finalize(); return 0; }
C
#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main() { int n,fd; char buff[50]; fd=open("test.txt",O_RDONLY); //opens test.txt in read mode and the file descriptor is saved in integer fd. printf("The file descriptor of the file is: %d\n,fd); // the value of the file descriptor is printed. n=read(fd,buff,10);//read 10 characters from the file pointed to by file descriptor fd and save them in buffer (buff) write(1,buff,n); //write on the screen from the buffer }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> int main() { pid_t child_pid; child_pid = fork(); if (child_pid != 0) { printf("A\n"); child_pid = fork(); if (child_pid != 0) { child_pid = fork(); if (child_pid != 0) {} else printf("D\n"); } else printf("C\n"); } else printf("B\n"); return 0; }
C
#include<stdio.h> #include<string.h> struct gift { char str[20]; int p; }; int main() { struct gift group[15]; char str1[20]; int i,j,k,l,m,n,g,f=0; while(scanf("%d",&n)!=EOF) { for(i=0;i<n;i++) scanf("%s",group[i].str); for(i=0;i<n;i++) group[i].p=0; for(l=0;l<n;l++) { scanf("%s%d%d",str1,&g,&m); if(m==0) { continue; } for(i=0;i<n;i++) { if(strcmp(str1,group[i].str)==0) { k=i; break; } } while((g%m)!=0) { g=g-1; } group[k].p=(group[k].p)-g; g=g/m; for(i=0;i<m;i++) { scanf("%s",str1); for(j=0;j<n;j++) { if(strcmp(str1,group[j].str)==0) { group[j].p=group[j].p+g; break; } } } } if(f==1) printf("\n"); for(i=0;i<n;i++) { printf("%s %d\n",group[i].str,group[i].p); } f=1; } }
C
#include <stdio.h> #include <stdlib.h> //A C example about functions void printSomething(); int main() { //calls the function printSomething and prints out the statement printSomething(); return 0; } void printSomething() { printf("Hello World!"); return; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <pwd.h> int main (int argc, const char *argv[]) { const uid_t uid = getuid(); struct passwd *pw_uid = getpwuid(uid); const char *name = pw_uid->pw_name; struct passwd *pw_nam = getpwnam(name); if (strcmp(pw_uid->pw_dir,pw_nam->pw_dir) == 0) { printf("%s\n", pw_uid->pw_dir); return EXIT_SUCCESS; } else { printf("%s\n", "Returns from getpwuid and getpwnam did not match!"); printf("%s: %s\n", "getpwuid", pw_uid->pw_dir); printf("%s: %s\n", "getpwnam", pw_nam->pw_dir); return EXIT_FAILURE; } }
C
#include <stdio.h> #include <stdlib.h> int foo(int*a,int*b) { return *a-*b; } int main() { int tab[] = {0,2,-3,0,-3,3,3}; int *wsk=tab-1; int b = *(wsk+=4); //b=0 int c = b+2; // b=0 , c=2 int d = foo(&b,&c); // b=0 , c=2 , d=-2 int e = (wsk+=-1)[3]; // b=0 , c=2 , d=-2 , e=3 e = (d -= 2) + (c += 2); // b=0 , c=4 , d=-4 , e=0 c = d - (b+=3); // b=3 , c=-7 , d=-4 , e=0 b = *wsk + 3; // b=0 , c=-7 , d=-4 , e=0 b= (--c)-(d++); // b=-4 , c=-8 , d=-3 , e=0 return 0; }
C
/* * operations.c * * Created on: Oct 5, 2020 * Author: Training */ #include <functions.h> #include "main.h" /* * @Breif Description - Switch On the LED to show the system is On and turn off the LED to indicate * @Function - system begin and initialise * * @Param1- FLAG which is an interuppt raised when the switch is pressed * * @Retval - None * * @Deigned By- Rahul L * * @Date and Time- 05/10/2020 */ void sysbegin(uint8_t FLAG) { HAL_GPIO_WritePin(Led_GPIO_Port, Led_Pin, FLAG); } /* * @Breif Description - Function to initialise, start conversion and return a converted value * @Function Reading the ADC * * @Param1- handle of the adc 1 * * * @Retval - Converted digital value * * @Deigned By- Rahul L * * @Date and Time- 05/10/2020 */ uint16_t AdcRead(ADC_HandleTypeDef hadc1) { uint16_t DigitalValue; HAL_ADC_Start(&hadc1); if(HAL_ADC_PollForConversion(&hadc1, 5)== HAL_OK) { DigitalValue = HAL_ADC_GetValue(&hadc1); //adc value is stored in adcvalue } return DigitalValue; }
C
#include <avr/io.h> void Master_begin(){ TWSR = 0x03; TWBR = 0xFF; //frequencia do clock } void Master_Send(uint8_t data){ TWDR = data; TWCR = (1<<TWINT) | (1<<TWEN); while(!(TWCR & 1<<TWINT)); } void Master_Start(){ TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN); while(!(TWCR & 1<<TWINT)); } void Master_Stop(){ TWCR = (1<<TWINT) | (1<<TWSTO) | (1<<TWEN); } uint8_t Master_Receive(){ TWCR = (1<< TWINT) | (1<<TWEN); // lê apenas um byte while(!(TWCR & 1 <<TWINT)); return TWDR; }
C
#include "utils_en_comun.h" #include "datos_comanda.h" // ENVIO void enviar_respuesta(bool respuestaBool, uint32_t socketCliente){ t_paquete* paquete_a_enviar = crear_paquete(CONFIRMAR_PEDIDO); t_respuesta2 respuesta; if(respuestaBool){ respuesta = OK2; } else{ respuesta = FAIL2; } serializar_respuesta(respuesta, paquete_a_enviar->buffer); int tamanio_a_enviar = 0; void* a_enviar = serializar_paquete(paquete_a_enviar, &tamanio_a_enviar); send(socketCliente, a_enviar, tamanio_a_enviar, 0); free(paquete_a_enviar->buffer); free(paquete_a_enviar); free(a_enviar); } void enviar_datos_pedido_comanda(t_estado2 estadoPedido, t_list* infoPedido, uint32_t socketCliente){ t_paquete* paquete_a_enviar = crear_paquete(DATOS_PEDIDO_COMANDA); serializar_datos_pedido_comanda(estadoPedido, infoPedido, paquete_a_enviar->buffer); int tamanio_a_enviar = 0; void* a_enviar = serializar_paquete(paquete_a_enviar, &tamanio_a_enviar); send(socketCliente, a_enviar, tamanio_a_enviar, 0); free(paquete_a_enviar->buffer->stream); free(paquete_a_enviar->buffer); free(paquete_a_enviar); free(a_enviar); } // SERIALIZACION void serializar_respuesta(t_respuesta2 rta, t_buffer* buffer){ //1. Respuesta buffer->size = sizeof(t_respuesta2); buffer->stream = malloc(buffer->size); int offset = 0; memcpy(buffer->stream + offset, &(rta), sizeof(t_respuesta2)); } void serializar_datos_pedido_comanda(t_estado2 estadoPedido, t_list* infoPedido, t_buffer* buffer){ //0. Estado //1. Cantidad de elementos //2. tamanioNombre //3. NombrePlato //4. cantidadTotal //5. cantidadLista int cant = list_size(infoPedido); int offset = 0; if(cant > 0){ buffer->size = sizeof(uint32_t) + sizeof(uint32_t) + (sizeof(uint32_t)*3*cant); for (int i = 0; i < cant; i++) { int tamanioNombre = strlen(((t_pagina*) list_get(infoPedido, i))->nombrePlato)+1; buffer->size += tamanioNombre; } buffer->stream = malloc(buffer->size); memcpy(buffer->stream + offset, &estadoPedido, sizeof(uint32_t)); offset += sizeof(uint32_t); memcpy(buffer->stream + offset, &cant, sizeof(uint32_t)); offset += sizeof(uint32_t); for (int i = 0; i < cant; ++i) { t_pagina* pagina = (t_pagina*) list_get(infoPedido, i); int tamanioNombre = strlen(pagina->nombrePlato) +1; memcpy(buffer->stream + offset, &tamanioNombre, sizeof(uint32_t)); offset += sizeof(uint32_t); memcpy(buffer->stream + offset, pagina->nombrePlato, tamanioNombre); offset += tamanioNombre; memcpy(buffer->stream + offset, &pagina->cantidadPlato, sizeof(uint32_t)); offset += sizeof(uint32_t); memcpy(buffer->stream + offset, &pagina->cantidadLista, sizeof(uint32_t)); offset += sizeof(uint32_t); } } } // DESERIALIZACION guardar_pedido* deserializar_guardar_pedido(int socket_cliente) { //------------ORDEN------------ //1. idPedido //2. tamanioNombre //3. nombreRestaurante //----------------------------- guardar_pedido* msg_recibido = malloc(sizeof(guardar_pedido)); recv(socket_cliente, &(msg_recibido->idPedido), sizeof(uint32_t), MSG_WAITALL); recv(socket_cliente, &(msg_recibido->tamanioNombre), sizeof(uint32_t), MSG_WAITALL); msg_recibido->nombreRestaurante = malloc(msg_recibido->tamanioNombre); recv(socket_cliente, msg_recibido->nombreRestaurante, msg_recibido->tamanioNombre, MSG_WAITALL); return msg_recibido; } guardar_plato* deserializar_guardar_plato(int socket_cliente) { //------------ORDEN------------ //1. Tamanio Nombre Restaurante //2. Nombre Restaurante; //3. Tamanio Nombre Plato //4. Plato //5. Cantidad //6. Id Pedido //----------------------------- guardar_plato* msg_recibido = malloc(sizeof(guardar_plato)); recv(socket_cliente, &(msg_recibido->tamanioNombre), sizeof(uint32_t), 0); msg_recibido->nombreRestaurante = malloc(msg_recibido->tamanioNombre); recv(socket_cliente, msg_recibido->nombreRestaurante, msg_recibido->tamanioNombre, 0); recv(socket_cliente, &(msg_recibido->tamanioNombrePlato), sizeof(uint32_t), 0); msg_recibido->nombrePlato = malloc(msg_recibido->tamanioNombrePlato); recv(socket_cliente, msg_recibido->nombrePlato, msg_recibido->tamanioNombrePlato, 0); recv(socket_cliente, &(msg_recibido->cantidadPlato), sizeof(uint32_t), 0); recv(socket_cliente, &(msg_recibido->idPedido), sizeof(uint32_t), 0); return msg_recibido; } confirmar_pedido* deserializar_confirmar_pedido(int socket_cliente){ //------------ORDEN------------ //1. Id Pedido //2. Tamanio Nombre Restaurante //3. Nombre Restaurante; //----------------------------- confirmar_pedido* msg_recibido = malloc(sizeof(confirmar_pedido)); recv(socket_cliente, &(msg_recibido->idPedido), sizeof(uint32_t), 0); recv(socket_cliente, &(msg_recibido->tamanioNombre), sizeof(uint32_t), 0); msg_recibido->nombreRestaurante = malloc(msg_recibido->tamanioNombre); recv(socket_cliente, (msg_recibido->nombreRestaurante), msg_recibido->tamanioNombre, 0); return msg_recibido; } obtener_pedido* deserializar_obtener_pedido(int socket_cliente){ //------------ORDEN------------ //1. Tamanio nombre restaurante //2. Nombre restaurante //3. ID Pedido //----------------------------- obtener_pedido* msg_recibido = malloc(sizeof(obtener_pedido)); recv(socket_cliente, &(msg_recibido->tamanioNombre), sizeof(uint32_t), 0); msg_recibido->nombreRestaurante = malloc(msg_recibido->tamanioNombre); recv(socket_cliente, (msg_recibido->nombreRestaurante), msg_recibido->tamanioNombre, 0); recv(socket_cliente, &(msg_recibido->idPedido), sizeof(uint32_t), 0); return msg_recibido; } plato_listo* deserializar_plato_listo(int socket_cliente){ //------------ORDEN------------ //1. Tamanio Nombre Restaurante //2. Nombre Restaurante; //3. Tamanio Nombre Plato //4. Plato //5. id Pedido //----------------------------- plato_listo* msg_recibido = malloc(sizeof(plato_listo)); recv(socket_cliente, &(msg_recibido->tamanioNombre), sizeof(uint32_t), 0); msg_recibido->nombreRestaurante = malloc(msg_recibido->tamanioNombre); recv(socket_cliente, (msg_recibido->nombreRestaurante), msg_recibido->tamanioNombre, 0); recv(socket_cliente, &(msg_recibido->tamanioNombrePlato), sizeof(uint32_t), 0); msg_recibido->nombrePlato = malloc(msg_recibido->tamanioNombrePlato); recv(socket_cliente, (msg_recibido->nombrePlato), msg_recibido->tamanioNombrePlato, 0); recv(socket_cliente, &(msg_recibido->idPedido), sizeof(uint32_t), 0); return msg_recibido; } finalizar_pedido* deserializar_finalizar_pedido(int socket_cliente){ //------------ORDEN------------ //1. idPedido //2. tamanioNombre //3. nombreRestaurante //----------------------------- finalizar_pedido* msg_recibido = malloc(sizeof(finalizar_pedido)); recv(socket_cliente, &(msg_recibido->idPedido), sizeof(uint32_t), 0); recv(socket_cliente, &(msg_recibido->tamanioNombre), sizeof(uint32_t), 0); msg_recibido->nombreRestaurante = malloc(msg_recibido->tamanioNombre); recv(socket_cliente, (msg_recibido->nombreRestaurante), msg_recibido->tamanioNombre, 0); return msg_recibido; }
C
#include "gabor.h" #include <math.h> #include <assert.h> #include <stdlib.h> #include "inline.h" #include "libdwt.h" float complex gabor_atom( float t, ///< time around 0 float alpha, ///< Gaussian envelope parameter float omega ///< frequency in radians ) { assert( alpha >= 0.f ); #if 0 return sqrtf(alpha/(float)M_PI) * expf(-alpha*t*t) * cexpf(-I*omega*t); #else return sqrtf(alpha/(float)M_PI) * expf(-alpha*t*t) * cexpf(+I*omega*t); #endif } float complex gabor_function( float t, ///< time, centered at 0 float sigma, ///< standard deviation float f ///< frequency in radians ) { assert( sigma > 0.f ); float alpha = 1.f/2.f/sigma/sigma; return gabor_atom(t, alpha, f); } float complex gabor_wavelet( float t, ///< time, centered at 0 float sigma, ///< standard deviation float f, ///< frequency in radians float a ///< scale ) { assert( sigma > 0.f ); assert( a > 0.f ); float alpha = 1.f/2.f/sigma/sigma; t /= a; return 1.f/fabsf(a) * gabor_atom(t, alpha, f); } float gabor_freq(float f, float a) { assert( a != 0.f ); return f / a; } // f_c .. frequency of the mother wavelet // f .. (0; +pi] // returns the scale "a" float gabor_scale(float f_c, float f) { assert( f != 0.f ); return f_c / f; } // 3*sigma rule float gaussian_limit( float sigma, float a ) { return (4.f*sigma)*a; } int gaussian_size( float sigma, float a ) { return (int)ceilf( 1.f + 2.f*gaussian_limit(sigma, a) ); } int gaussian_center( float sigma, float a ) { return gaussian_size(sigma, a) / 2; } static int saturate_i(int val, int lo, int hi) { if( val < lo ) return lo; if( val > hi ) return hi; return val; } static float complex cdot1_s( const float *func, int func_size, int func_stride, int func_center, const float complex *kern, int kern_size, int kern_stride, int kern_center ) { const int left = -( min( func_center, kern_center) ); const int right = +( min( func_size-func_center-1, kern_size-kern_center-1) ); float complex sum = 0.f; for(int i = left; i <= right; i++) { const int func_idx = saturate_i(func_center+i, 0, func_size-1); const int kern_idx = saturate_i(kern_center+i, 0, kern_size-1); const float func_sample = *addr1_const_s (func, func_idx, func_stride); const float complex kern_sample = *addr1_const_cs(kern, kern_idx, kern_stride); sum += func_sample * conjf(kern_sample); } return sum; } float complex dwt_util_cdot1_s( const float *func, int func_size, int func_stride, int func_center, const float complex *kern, int kern_size, int kern_stride, int kern_center ) { return cdot1_s(func, func_size, func_stride, func_center, kern, kern_size, kern_stride, kern_center); } void timefreq_line( float *dst, int dst_stride, const float *src, int src_stride, int size, const float complex *kern, int kern_stride, int kern_size, int kern_center ) { for(int i = 0; i < size; i++) { *addr1_s(dst, i, dst_stride) = cabsf( cdot1_s( src, size, src_stride, i, kern, kern_size, kern_stride, kern_center)); } } void timefreq_arg_line( float *dst, int dst_stride, const float *src, int src_stride, int size, const float complex *kern, int kern_stride, int kern_size, int kern_center ) { for(int i = 0; i < size; i++) { *addr1_s(dst, i, dst_stride) = cargf( cdot1_s( src, size, src_stride, i, kern, kern_size, kern_stride, kern_center)); } } void dwt_util_vec_creal_cs( float *dst, int dst_stride, const float complex *src, int src_stride, int size ) { for(int i = 0; i < size; i++) { *addr1_s(dst, i, dst_stride) = creal(*addr1_const_cs(src, i, src_stride)); } } void dwt_util_vec_cabs_cs( float *dst, int dst_stride, const float complex *src, int src_stride, int size ) { for(int i = 0; i < size; i++) { *addr1_s(dst, i, dst_stride) = cabs(*addr1_const_cs(src, i, src_stride)); } } float dwt_util_band_lpnorm_cs( const void *ptr, int stride_x, int stride_y, int size_x, int size_y, float p ) { float sum = 0.0f; if( +INFINITY == p ) dwt_util_error("unimplemented\n"); for(int y = 0; y < size_y; y++) { for(int x = 0; x < size_x; x++) { const float complex c = *addr2_const_cs(ptr, y, x, stride_x, stride_y); sum += powf(cabsf(c), p); } } return powf(sum, 1.f/p); } float complex dwt_util_band_mean_cs( const void *ptr, int stride_x, int stride_y, int size_x, int size_y ) { float complex sum = 0.0f; for(int y = 0; y < size_y; y++) { for(int x = 0; x < size_x; x++) { float complex coeff = *addr2_const_cs(ptr, y, x, stride_x, stride_y); sum += coeff; } } sum /= size_x * size_y; return sum; } // Gabor transform void gabor_gen_kernel( float complex **ckern, int stride, float sigma, float freq, float a ) { int size = gaussian_size(sigma, a); int center = gaussian_center(sigma, a); *ckern = realloc(*ckern, stride * size); for(int i = 0; i < size; i++) { *addr1_cs(*ckern, i, stride) = gabor_wavelet(i-center, sigma, freq, a); } #if 0 float complex mean = dwt_util_band_mean_cs(*ckern, 0, sizeof(const float complex), size, 1); dwt_util_log(LOG_DBG, "gabor_gen_kernel: 1-norm=%f 2-norm=%f mean/abs=%f size=%i\n", dwt_util_band_lpnorm_cs( *ckern, 0, sizeof(const float complex), size, 1, 1.f // p ), dwt_util_band_lpnorm_cs( *ckern, 0, sizeof(const float complex), size, 1, 2.f // p ), cabsf(mean), size ); #endif } // sigma of Gaussian for S transform float s_sigma(float f) { assert( f != 0.f ); const float alpha = f * f; const float sigma = sqrtf(1.f/2.f/alpha); return sigma; } // kernel of S transform void s_gen_kernel( float complex **ckern, int stride, float f ///< 0..1 ) { // FIXME: zero frequency implies an infinitely long window assert( f != 0.f ); // Gaussian function: g(t) = C1 * e^(-alpha * t^2) const float alpha = f * f; // Gaussian function: g(t) = C2 * e^(-1/2/sigma/sigma * t^2) const float sigma = sqrtf(1.f/2.f/alpha); const float omega = 2.f * (float)M_PI * f; // scale const float a = 1.f; const int size = gaussian_size(sigma, a); const int center = gaussian_center(sigma, a); *ckern = realloc(*ckern, stride * size); for(int i = 0; i < size; i++) { const int t = i-center; *addr1_cs(*ckern, i, stride) = gabor_atom(t, alpha, omega); } #if 0 float complex mean = dwt_util_band_mean_cs(*ckern, 0, sizeof(const float complex), size, 1); dwt_util_log(LOG_DBG, "s_gen_kernel: 1-norm=%f 2-norm=%f mean/abs=%f size=%i\n", dwt_util_band_lpnorm_cs( *ckern, 0, sizeof(const float complex), size, 1, 1.f // p ), dwt_util_band_lpnorm_cs( *ckern, 0, sizeof(const float complex), size, 1, 2.f // p ), cabsf(mean), size ); #endif } void test_signal( float **dest, int stride, int size, int type ) { *dest = (float *)realloc(*dest, stride * size); for(int i = 0; i < size; i++) { switch(type) { // constant chirp, two parts case 0: { float f0 = 1.f/3.f * (size-1)/2.f; float f1 = 2.f/3.f * (size-1)/2.f; const float omega0 = 2.f * (float)M_PI * f0; const float omega1 = 2.f * (float)M_PI * f1; const float t = (float)i/size; *addr1_s(*dest, i, stride) = 0.f; if( i < 2*size/3 ) *addr1_s(*dest, i, stride) += +cos( t * omega0 ); if( i > 1*size/3 ) *addr1_s(*dest, i, stride) += +cos( t * omega1 ); } break; // constant chirp, two parts case 1: { float f0 = 1.f/3.f * (size-1)/2.f; float f1 = 2.f/3.f * (size-1)/2.f; const float omega0 = 2.f * (float)M_PI * f0; const float omega1 = 2.f * (float)M_PI * f1; const float t = (float)i/size; if( i < size/2 ) *addr1_s(*dest, i, stride) = +cos( t * omega0 ); else *addr1_s(*dest, i, stride) = +cos( t * omega1 ); } break; // linear chirp case 2: { const float f = (size-1)/2.f; const float omega = 2.f * (float)M_PI * f; const float t = (float)i/size; *addr1_s(*dest, i, stride) = +cos( 0.5f * t * t * omega ); } break; // two linear chirps case 3: { const float f = (size-1)/4.f; const float omega = 2.f * (float)M_PI * f; const float t = (float)i/size; *addr1_s(*dest, i, stride) = +cos( 0.5f * t * t * omega ) +cos( 0.5f * t * t * omega + 0.4f*t*omega ); } break; // two linear chirps case 4: { const float f = (size-1)/2.f; const float omega = 2.f * (float)M_PI * f; const float t0 = (float)i/size; const float t1 = 1.0f - t0; *addr1_s(*dest, i, stride) = +cos( 0.5f * t0 * t0 * omega ) +cos( 0.5f * t1 * t1 * omega ); } break; // hyperbolic chirp case 5: { const float f = (size-1)/2.f; const float a = 2.0f * 0.5f * 2.f * (float)M_PI * f; const float b = 2.0f; const float t = (float)i/size; *addr1_s(*dest, i, stride) = +cos( a / (b - t) ); } break; // two hyperbolic chirps case 6: { const float f = (size-1)/2.f; const float a0 = 1.0f * 0.5f * 2.f * (float)M_PI * f; const float a1 = 2.0f * 0.5f * 2.f * (float)M_PI * f; const float b = 2.0f; const float t = (float)i/size; *addr1_s(*dest, i, stride) = +cos( a0 / (b - t) ) +cos( a1 / (b - t) ); } break; // Gabor function case 7: { const float center = size/2; const float sigma = size/8; const float freq = 0.5f; *addr1_s(*dest, i, stride) = creal(gabor_function(-center+i, sigma, freq)); } break; // two Gabor functions case 8: { const float center0 = 1*size/4; const float center1 = 3*size/4; const float sigma = size/16; const float freq = 1.0f; *addr1_s(*dest, i, stride) = +creal(gabor_function(-center0+i, sigma, freq)) +creal(gabor_function(-center1+i, sigma, 2.f*freq)); } break; default: dwt_util_abort(); } } } void gabor_ft_s( // input const float *sig, ///< the analysed signal int sig_stride, ///< the stride of the signal int sig_size, ///< the length of the signal, the width of the plane // output void *plane, ///< put the plane here int stride_x, ///< stride of rows of the plane int stride_y, ///< stride of columns of the plane int bins, ///< the height of the plane // params float sigma ///< std. deviation of the baseline kernel (implies the window size) ) { assert( plane ); float complex *ckern = 0; int ckern_stride = sizeof(float complex); int size_y = bins; for(int y = 0; y < size_y; y++) { float norm_y = y/(float)size_y; // TF-plane float *row = dwt_util_addr_coeff_s( plane, size_y-y-1, 0, stride_x, stride_y ); // gen. kernel float freq = norm_y * 1.0f * (float)M_PI; float a = 1.0f; gabor_gen_kernel(&ckern, ckern_stride, sigma, freq, a); int kern_size = gaussian_size(sigma, a); int kern_center = gaussian_center(sigma, a); // response timefreq_line(row, stride_y, sig, sig_stride, sig_size, ckern, ckern_stride, kern_size, kern_center); } free(ckern); } void gabor_ft_arg_s( // input const float *sig, ///< the analysed signal int sig_stride, ///< the stride of the signal int sig_size, ///< the length of the signal, the width of the plane // output void *plane, ///< put the plane here int stride_x, ///< stride of rows of the plane int stride_y, ///< stride of columns of the plane int bins, ///< the height of the plane // params float sigma ///< std. deviation of the baseline kernel (implies the window size) ) { assert( plane ); float complex *ckern = 0; int ckern_stride = sizeof(float complex); int size_y = bins; for(int y = 0; y < size_y; y++) { float norm_y = y/(float)size_y; // TF-plane float *row = dwt_util_addr_coeff_s( plane, size_y-y-1, 0, stride_x, stride_y ); // gen. kernel float freq = norm_y * 1.0f * (float)M_PI; float a = 1.0f; gabor_gen_kernel(&ckern, ckern_stride, sigma, freq, a); int kern_size = gaussian_size(sigma, a); int kern_center = gaussian_center(sigma, a); // response timefreq_arg_line(row, stride_y, sig, sig_stride, sig_size, ckern, ckern_stride, kern_size, kern_center); } free(ckern); } // wavelet transform void gabor_wt_s( // input const float *sig, ///< the analysed signal int sig_stride, ///< the stride of the signal int sig_size, ///< the length of the signal, the width of the plane // output void *plane, ///< put the plane here int stride_x, ///< stride of rows of the plane int stride_y, ///< stride of columns of the plane int bins, ///< the height of the plane // params float sigma, ///< std. deviation of the baseline kernel (implies the window size) float freq ///< frequency of the baseline kernel, in radians ) { assert( plane ); // dwt_util_log(LOG_DBG, "analytic wavelet: (sigma^2)*(eta^2) >> 1 = %f\n", sigma*sigma*freq*freq); { const float f = 1.f/(float)bins * 0.5f * 2.f * (float)M_PI; const float a = gabor_scale(freq, f); dwt_util_log(LOG_DBG, "min: kernel_size=%i scale=%f freq=%f\n", gaussian_size(sigma, a), a, f); } { const float f = 1.f * 0.5f * 2.f * (float)M_PI; const float a = gabor_scale(freq, f); dwt_util_log(LOG_DBG, "max: kernel_size=%i scale=%f freq=%f\n", gaussian_size(sigma, a), a, f); } float complex *ckern = 0; int ckern_stride = sizeof(float complex); int size_y = bins; for(int y = 0; y < size_y; y++) { //float norm0_y = (y+0.f)/(float)size_y; // [0; 1) float norm1_y = (y+1.f)/(float)size_y; // (0; 1] // TF-plane float *row = dwt_util_addr_coeff_s( plane, size_y-y-1, 0, stride_x, stride_y ); // gen. kernel float f = norm1_y * 0.5f * 2.f*(float)M_PI; // (0; +pi] float a = gabor_scale(freq, f); // dwt_util_log(LOG_DBG, "y=%i, freq(a=%f) = %f, freq*a = %f\n", size_y-y-1, a, gabor_freq(freq, a), gabor_freq(freq, a)*a); gabor_gen_kernel(&ckern, ckern_stride, sigma, freq, a); int kern_size = gaussian_size(sigma, a); int kern_center = gaussian_center(sigma, a); // response timefreq_line(row, stride_y, sig, sig_stride, sig_size, ckern, ckern_stride, kern_size, kern_center); } free(ckern); } // S transform void gabor_st_s( // input const float *sig, ///< the analysed signal int sig_stride, ///< the stride of the signal int sig_size, ///< the length of the signal, the width of the plane // output void *plane, ///< put the plane here int stride_x, ///< stride of rows of the plane int stride_y, ///< stride of columns of the plane int bins ///< the height of the plane // no params ) { assert( plane ); float complex *ckern = 0; int ckern_stride = sizeof(float complex); int size_y = bins; for(int y = 0; y < size_y; y++) { //float norm0_y = (y+0.f)/(float)size_y; float norm1_y = (y+1.f)/(float)size_y;; // TF-plane float *row = dwt_util_addr_coeff_s( plane, #if 1 size_y-y-1, #else y, #endif 0, stride_x, stride_y ); // frequencies (0; 0.5] => (0; pi] #if 1 float f = norm1_y * 0.5f; #else float f = norm1_y; #endif float a = 1.f; float sigma = s_sigma(f); // dwt_util_log(LOG_DBG, "S transform: y=%i, freq = %f\n", y, f); s_gen_kernel(&ckern, ckern_stride, f); int kern_size = gaussian_size(sigma, a); int kern_center = gaussian_center(sigma, a); // response timefreq_line(row, stride_y, sig, sig_stride, sig_size, ckern, ckern_stride, kern_size, kern_center); } free(ckern); } void gabor_st_arg_s( // input const float *sig, ///< the analysed signal int sig_stride, ///< the stride of the signal int sig_size, ///< the length of the signal, the width of the plane // output void *plane, ///< put the plane here int stride_x, ///< stride of rows of the plane int stride_y, ///< stride of columns of the plane int bins ///< the height of the plane // no params ) { assert( plane ); float complex *ckern = 0; int ckern_stride = sizeof(float complex); int size_y = bins; for(int y = 0; y < size_y; y++) { //float norm0_y = (y+0.f)/(float)size_y; float norm1_y = (y+1.f)/(float)size_y;; // TF-plane float *row = dwt_util_addr_coeff_s( plane, #if 1 size_y-y-1, #else y, #endif 0, stride_x, stride_y ); // frequencies (0; 0.5] => (0; pi] #if 1 float f = norm1_y * 0.5f; #else float f = norm1_y; #endif float a = 1.f; float sigma = s_sigma(f); s_gen_kernel(&ckern, ckern_stride, f); int kern_size = gaussian_size(sigma, a); int kern_center = gaussian_center(sigma, a); // response timefreq_arg_line(row, stride_y, sig, sig_stride, sig_size, ckern, ckern_stride, kern_size, kern_center); } free(ckern); } void gabor_wt_arg_s( // input const float *sig, ///< the analysed signal int sig_stride, ///< the stride of the signal int sig_size, ///< the length of the signal, the width of the plane // output void *plane, ///< put the plane here int stride_x, ///< stride of rows of the plane int stride_y, ///< stride of columns of the plane int bins, ///< the height of the plane // params float sigma, ///< std. deviation of the baseline kernel (implies the window size) float freq ///< frequency of the baseline kernel, in radians ) { assert( plane ); float complex *ckern = 0; int ckern_stride = sizeof(float complex); int size_y = bins; for(int y = 0; y < size_y; y++) { //float norm0_y = (y+0.f)/(float)size_y; // [0; 1) float norm1_y = (y+1.f)/(float)size_y; // (0; 1] // TF-plane float *row = dwt_util_addr_coeff_s( plane, size_y-y-1, 0, stride_x, stride_y ); // gen. kernel float f = norm1_y * 0.5f * 2.f*(float)M_PI; // (0; +pi] float a = gabor_scale(freq, f); gabor_gen_kernel(&ckern, ckern_stride, sigma, freq, a); int kern_size = gaussian_size(sigma, a); int kern_center = gaussian_center(sigma, a); // response timefreq_arg_line(row, stride_y, sig, sig_stride, sig_size, ckern, ckern_stride, kern_size, kern_center); } free(ckern); } void phase_derivative_s( const void *angle, void *derivative, int stride_x, int stride_y, int size_x, int size_y, float limit ) { assert( limit > 0.f ); for(int y = 0; y < size_y; y++) { for(int x = 0; x < size_x; x++) { float *out = addr2_s(derivative, y, x, stride_x, stride_y); if( 0 == x ) { *out = 0.f; } else { *out = - *addr2_const_s(angle, y, x-1, stride_x, stride_y) + *addr2_const_s(angle, y, x, stride_x, stride_y); while( *out > +limit ) *out -= 2.f*(float)M_PI; while( *out < -limit ) *out += 2.f*(float)M_PI; } } } } void detect_ridges1_s( const void *magnitude, void *ridges, int stride_x, int stride_y, int size_x, int size_y, float threshold ) { for(int y = 0; y < size_y; y++) { for(int x = 0; x < size_x; x++) { float *out = addr2_s(ridges, y, x, stride_x, stride_y); *out = 0.f; if( x > 0 && x < size_x-1 ) { float mag_val = *addr2_const_s(magnitude, y, x, stride_x, stride_y); float mag_line[3] = { *addr2_const_s(magnitude, y, x-1, stride_x, stride_y), *addr2_const_s(magnitude, y, x, stride_x, stride_y), *addr2_const_s(magnitude, y, x+1, stride_x, stride_y), }; float mag_factor = -1.f * (mag_line[0] - mag_line[1]) * (mag_line[1] - mag_line[2]); if( mag_factor > 0.f && mag_val > threshold ) { // dwt_util_log(LOG_DBG, "ridge point: y=%i x=%i mag=%f\n", y, x, mag_val); #if 0 *out = 1.f; #else *out = mag_val/2.f/(float)M_PI; #endif } } } } } void detect_ridges2_s( const void *inst_freq, void *ridges, int stride_x, int stride_y, int size_x, int size_y, float threshold ) { for(int y = 0; y < size_y; y++) { for(int x = 0; x < size_x; x++) { float *out = addr2_s(ridges, y, x, stride_x, stride_y); *out = 0.f; if( x > 0 && x < size_x-1 ) { float arg_val = *addr2_const_s(inst_freq, y, x, stride_x, stride_y); if( arg_val < 0.f && fabsf(arg_val) > threshold ) { // dwt_util_log(LOG_DBG, "ridge point: y=%i x=%i arg=%f\n", y, x, arg_val); #if 0 *out = 1.f; #else *out = fabsf(arg_val)/2.f/(float)M_PI; #endif } } } } } // difference of two samples float coeff_diff_s( const void *ptr, int stride_x, int stride_y, int pos0_x, int pos0_y, int pos1_x, int pos1_y ) { float a = *dwt_util_addr_coeff_const_s( ptr, pos1_y, pos1_x, stride_x, stride_y ); float b = *dwt_util_addr_coeff_const_s( ptr, pos0_y, pos0_x, stride_x, stride_y ); return a - b; } // angle (-pi; +pi) of gradient at position (x,y) float grad_angle_s( const void *ptr, int stride_x, int stride_y, int pos_x, int pos_y ) { float dx = coeff_diff_s(ptr, stride_x, stride_y, pos_x-1, pos_y, pos_x+1, pos_y) / 2.f; float dy = coeff_diff_s(ptr, stride_x, stride_y, pos_x, pos_y-1, pos_x, pos_y+1) / 2.f; // dwt_util_log(LOG_DBG, "angle: d=(%f,%f)\n", dx, dy); return atan2f(dy, dx); } // magnitude in the direction of gradient const float *addr_coeff_in_grad_dir_const_s( const void *ptr, int stride_x, int stride_y, int pos_x, int pos_y ) { float angle = grad_angle_s( ptr, stride_x, stride_y, pos_x, pos_y ); const float ampl = 1.f; const float half = ampl / 2.f; float dir_x = ampl * cosf(angle); float dir_y = ampl * sinf(angle); // right-to-left associativity of ?: int next_x = ( dir_x < -half ) ? -1 : ( dir_x > +half ) ? +1 : 0; int next_y = ( dir_y < -half ) ? -1 : ( dir_y > +half ) ? +1 : 0; // dwt_util_log(LOG_DBG, "pos=(%i,%i) angle=%f grad=(%i,%i)\n", pos_x, pos_y, angle, next_x, next_y); // if( 0 == next_x && 0 == next_y ) // dwt_util_log(LOG_DBG, "pos=(%i,%i) angle=%f grad=(%i,%i) => plane\n", pos_x, pos_y, angle, next_x, next_y); return dwt_util_addr_coeff_const_s( ptr, pos_y+next_y, pos_x+next_x, stride_x, stride_y ); } // is maximum in direction of gradient int grad_max_s( const void *ptr, int stride_x, int stride_y, int pos_x, int pos_y ) { const float this = *dwt_util_addr_coeff_const_s( ptr, pos_y, pos_x, stride_x, stride_y ); const float next = *addr_coeff_in_grad_dir_const_s( ptr, stride_x, stride_y, pos_x, pos_y ); return this >= next; } void detect_ridges3_s( const void *magnitude, void *ridges, int stride_x, int stride_y, int size_x, int size_y, float threshold ) { for(int y = 0; y < size_y; y++) { for(int x = 0; x < size_x; x++) { float *out = addr2_s(ridges, y, x, stride_x, stride_y); *out = 0.f; if( x > 0 && x < size_x-1 && y > 0 && y < size_y-1 ) { float mag_val = *addr2_const_s(magnitude, y, x, stride_x, stride_y); const int is_max = grad_max_s( magnitude, stride_x, stride_y, x, y ); if( is_max && mag_val > threshold ) { // dwt_util_log(LOG_DBG, "ridge point: y=%i x=%i arg=%f\n", y, x, arg_val); #if 0 *out = 1.f; #else *out = mag_val/2.f/(float)M_PI; #endif } } } } }
C
/** * * Considerações sobre compilar o código fonte pelo terminal do Linux: * algumas funções matemáticas não são reconhecidas pelo gcc, por isso * sugerimos usar o g++ para compilar o arquivo.c * No CodeBlocks, Windows, nenhum cuidado extra se mostrou necessário. * * Trabalho de Probabilidade e Estatística II * Professor José Fontebasso Neto * Felipe Ferreira - Ciência da Computação 7223057 * Maurício Freire - Ciência da Computação 2671844 * * Código fonte estará disponível em github.com/Dombrauskas após a data final de entrega. */ #include <stdio.h> #include <math.h> #include <stdbool.h> #include <ctype.h> #include <string.h> // Matriz que armazenará a Tabela Normal double TabelaNormal[60][10]; double calculoIntervalo(double); double Simpson(double); void pp(char); void bateu(); void intersec(double, char); double Abaixo(); double Acima(); void Meio(double *); void FGM(); bool isValid(double); double intersecMedio(double, char); void graph1(); void graph2(); void graph3(); int main() { int it = 0, i, j; double x; char tipo_tabela, calc = 'q'; bool pass = true, finalizar = false; double z; while (pass) { do { printf("Qual formato de tabela quer gerar, Acumulativa (A) ou Normal (N)? "); scanf(" %c", &tipo_tabela); tipo_tabela = toupper(tipo_tabela); if (tipo_tabela == 'N' || tipo_tabela == 'A') pass = true; else pass = false; } while (!pass); pass = !pass; } FGM(); pp(tipo_tabela); while (!finalizar) { printf("\nDeseja calcular? S/N\t"); scanf(" %c", &calc); calc = toupper(calc); if (calc == 'S') { int tipo_calculo = 0, x = 1; char lixo[100]; while (tipo_calculo < 1 || tipo_calculo > 3) { printf("Qual tipo de calculo quer fazer?\n"); printf("1 - Abaixo da Media"); graph1(); printf("2 - Acima da Media "); graph2(); printf("3 - Meio da curva? "); graph3(); // Evita que digitação de letras sejam válidas. scanf(" %99s[^\n]", lixo); sscanf(lixo, "%d", &tipo_calculo); } switch (tipo_calculo) { case 1: z = Abaixo(); if (!isValid(z)) { printf("\nValor obtido excede os limites da tabela!\n\n"); break; } printf("z = %.2lf\n", z); printf("Interseccao na Tabela: "); intersec(z, tipo_tabela); break; case 2: z = Acima(); if (!isValid(z)) { printf("\nValor obtido excede os limites da tabela!\n\n"); break; } printf("z = %.2lf\n", z); printf("Interseccao na Tabela: "); intersec(z, tipo_tabela); break; case 3: z = 0; double media[2], soma = 0; int m; bool flag = true; Meio(media); for (m = 0; m < 2; m++) { if (!isValid(media[m])) { printf("\nValor obtido excede os limites da tabela!\n\n"); flag = false; break; } } if (flag) { printf("Media[1] = %.2lf\nMedia[2] = %.2lf\n", media[0], media[1]); for (m = 0; m < 2; m++) soma += intersecMedio(media[m], tipo_tabela); printf("Soma dois intervalos: %.10lf\n", (1 - soma) < 0 ? (1 - soma) * - 1 : soma); } break; } } else if (calc == 'N') { printf("Digite \'S\' para sair ou \'N\' para gerar outra tabela _"); scanf(" %c", &calc); calc = toupper(calc); if (calc == 'S') finalizar = true; else if (calc == 'N') { /* * Automaticamente gera uma nova tabela diferente da anterior, * se a primeira tabela escolhido foi a Acumulada, então será * gerada uma Tabela Normal e vice-versa. */ if (tipo_tabela == 'A') tipo_tabela = 'N'; else tipo_tabela = 'A'; /* * Como a FGM() cria uma tabela baseada na normal 0.0000000000 * não é preciso chamá-la de novo, apenas exibir a TabelaNormal * como ela é ou somar 0.5000000000 aos valores no printf já * é o suficiente. */ pp(tipo_tabela); } } } //bateu(); return 0; } /* * Função Geradora da Matriz. * Salva os valores na tabela após serem calculados os intervalos com base na * tabela de normal (iniciada em 0.0000000000). */ void FGM() { int i, j; double x; for (i = 0; i < 60; i++) { for (j = 0; j < 10; j++) { x = (i / 10.0) + (j / 100.0); TabelaNormal[i][j] = Simpson(x); } } } // Teste de precisão inicial - Não mais usada. void bateu() { if (TabelaNormal[0][1] == 0.0039893563) printf("\n\nBateu!!\n"); else printf("\n\nAinda falta %.10lf\n", TabelaNormal[0][1] - 0.0039893563); } // Exibe a Tabela de Distribuição Normal. void pp(char tt) { int i, j; char espaco[] = {" "}; // Numeração colunas parte superior da tabela. printf("%s", espaco); for (i = 0; i < 10; i++) printf(" %d ", i); printf("\n"); // Imprime na tela a Tabela Acumulada (Iniciada em 0.5000000000). if (tt == 'A') { // Imprime o conteúdo da tabela. for (i = 0; i < 60; i++) { printf("%.1f ", i / 10.0); for (j = 0; j < 10; j++) { printf("%.10lf ", TabelaNormal[i][j] + 0.5); } printf("\n"); } } // Imprime na tela a Tabela Normal (Iniciada em 0.0000000000). else { // Imprime o conteúdo da tabela. for (i = 0; i < 60; i++) { printf("%.1f ", i / 10.0); for (j = 0; j < 10; j++) { printf("%.10lf ", TabelaNormal[i][j]); } printf("\n"); } } // Numeração colunas parte inferior da tabela. printf("%s", espaco); for (i = 0; i < 10; i++) printf(" %d ", i); printf("\n"); } // Regra de Simpson para aproximação da curva. double Simpson(double x) { int i; double valor_tabela = 0.0; double a = 0, b = x; double h = (b - a) / 1000; // 1000 é mínimo necessário para de iterações para chegar aos valores corretos. valor_tabela += calculoIntervalo(a) + calculoIntervalo(b); for (i = 1; i <= (1000 / 2); i++) valor_tabela += calculoIntervalo(a + h * (2 * i - 1)) * 4; for (i = 1; i <= (1000 / 2) - 1; i++) valor_tabela += calculoIntervalo(a + h * (2 * i)) * 2; return valor_tabela * ((b - a) / 3000); } // Calcula os intervalos da tabela pelo calculo da Distribuição Normal. double calculoIntervalo(double x) { return exp(-pow(x / sqrt(2), 2)) / sqrt(2 * 3.14159265359); } // Exibe o valor correspondente na Tabela Normal para o z calculado. void intersec(double z, char tt) { if (z < 0) // Se o z for negativo será convertido para seu correspondente positivo. z *= - 1; int lin = z * 10; // Faz os 2 primeiros digitos em inteiro para achar a linha. - 1.43 = 14; int col = z * 100 - lin * 10; // Pega o último digito para a coluna. - 1.43 = 3; /* * Como a tabela gerada é baseada apenas na normal 0.0000000000, para exibir * o valor da intersecção da Acumulada é preciso somar 0.5000000000 ao valor * contido na TabelaNormal. */ if (tt == 'N') printf("%.10lf\n", TabelaNormal[lin][col]); else printf("%.10lf\n", TabelaNormal[lin][col] + 0.5); } // Idem intersec - Não mais usada. double intersecMedio(double z, char tt) { if (z < 0) z *= - 1; int lin = z * 10; int col = z * 100 - lin * 10; if (tt == 'N') return TabelaNormal[lin][col]; else return TabelaNormal[lin][col] + 0.5; } /* * Calcula a área em porcentagem do gráfico. * Calcula uma área sob a curva que esteja após o ponto médio. */ double Acima() { bool coerente = true; double desvio, media, x; char lixo[100], lx[10]; // Evitam que caracteres não numéricos entrem no cálculo. while (coerente) { printf("Informe a media: "); scanf(" %9s[^\n]", lx); strcpy(lixo, lx); printf("Informe o desvio: "); scanf(" %9s[^\n]", lx); strcat(lixo, " "); // Separa a digitação anterior da atual. strcat(lixo, lx); printf("Informe o valor procurado: "); scanf(" %9s[^\n]", lx); strcat(lixo, " "); // Separa a digitação anterior da atual. strcat(lixo, lx); /* * Passam-se os valores informados para os formatos corretos, caso * algum formato não seja atendido como o esperado todo processo * será refeito. */ if ((sscanf(lixo, "%lf %lf %lf", &media, &desvio, &x)) < 3) printf("\nDigitação Invalida!\n\n"); else { coerente = x > media ? false : true; if (coerente) printf("\nO valor procurado deve ser " "MAIOR que a media (> %lf)!\n\n", media); } } return (x - media) / desvio; } /* * Calcula a área em porcentagem do gráfico. * Calcula uma área sob a curva que esteja antes do ponto médio. */ double Abaixo() { bool coerente = true; double desvio, media, x; char lixo[100], lx[10]; while (coerente) { printf("Informe a media: "); scanf(" %9s[^\n]", lx); strcpy(lixo, lx); printf("Informe o desvio: "); scanf(" %9s[^\n]", lx); strcat(lixo, " "); // Separa a digitação anterior da atual strcat(lixo, lx); printf("Informe o valor procurado: "); scanf(" %9s[^\n]", lx); strcat(lixo, " "); // Separa a digitação anterior da atual strcat(lixo, lx); /* * Passam-se os valores informados para os formatos corretos, caso * algum formato não seja atendido como o esperado todo processo * será refeito. */ if ((sscanf(lixo, "%lf %lf %lf", &media, &desvio, &x)) < 3) printf("\nDigitação Invalida!\n\n"); else { coerente = x < media ? false : true; if (coerente) printf("\nO valor procurado deve ser " "MENOR que a media (< %lf)!\n\n", media); } } return ((x - media) / desvio) * - 1; } /* * Calcula a área em porcentagem do gráfico. * Calcula uma área sob a curva que compreenda o ponto médio. */ void Meio(double * z) { bool coerente = true; double desvio, media, x1, x2; char lixo[100], lx[10]; while (coerente) { printf("Informe a media: "); scanf(" %9s[^\n]", lx); strcpy(lixo, lx); printf("Informe o desvio: "); scanf(" %9s[^\n]", lx); strcat(lixo, " "); // Separa a digitação anterior da atual strcat(lixo, lx); printf("Informe dois valores\nPrimeiro valor: "); scanf(" %9s[^\n]", lx); strcat(lixo, " "); // Separa a digitação anterior da atual strcat(lixo, lx); printf("Segunda valor: "); scanf(" %9s[^\n]", lx); strcat(lixo, " "); // Separa a digitação anterior da atual strcat(lixo, lx); /* * Passam-se os valores informados para os formatos corretos, caso * algum formato não seja atendido como o esperado todo processo * será refeito. */ if ((sscanf(lixo, "%lf %lf %lf %lf", &media, &desvio, &x1, &x2)) < 4) printf("\nDigitacao Invalida!\n\n"); else { // Faz com que x1 seja menor que a média e x2 seja maior. if (x1 > x2) { int aux = x1; x1 = x2; x2 = aux; } coerente = (x1 < media && x2 > media) ? false : true; } } z[0] = (x1 - media) / desvio; z[1] = (x2 - media) / desvio; //return z; } /* * Verifica se o valor de z é um intervalo válido * presente na tabela (entre 0.0 e 5.9) */ bool isValid(double z) { if (z < 0 && z > -6.0) z *= -1; if (z < -5.9 || z > 5.9) return false; else return true; } // Decoração void graph1() { printf(" 1 _________ |2 _________ |3 _________ \n"); } // Decoração void graph2() { printf(" / ##M|e \\ | / M|e## \\ | / |#M|e#| \\ \n"); } // Decoração void graph3() { printf(" _/__##dia____\\_ | _/____dia##__\\_ | _/__|#dia#|__\\_ \n\n"); }
C
#include <stdio.h> #include <stdbool.h> #include "int_set.h" #include "tests.h" void test_basic_behavior() { struct IntSet set = new_int_set(); assert_false(int_set_includes(&set, 0), "A new set should not include 0."); int_set_add(&set, 0); assert_true(int_set_includes(&set, 0), "A set with 0 added should include 0."); } void test_prepending_values() { struct IntSet new_set = new_int_set(); int_set_add(&new_set, 100); int_set_add(&new_set, 10); int_set_add(&new_set, 4); assert_true(int_set_includes(&new_set, 4), "Set should include 4."); assert_true(int_set_includes(&new_set, 10), "Set should include 10."); assert_true(int_set_includes(&new_set, 100), "Set should include 100."); assert_false(int_set_includes(&new_set, 1), "Set should not include 1."); } void test_even_odd_values() { struct IntSet set = new_int_set(); int_set_add(&set, 1); int_set_add(&set, 2); int_set_add(&set, 3); int_set_add(&set, 4); assert_true(int_set_includes(&set, 1), "Set should include 1."); assert_true(int_set_includes(&set, 2), "Set should include 2."); assert_true(int_set_includes(&set, 3), "Set should include 3."); assert_true(int_set_includes(&set, 4), "Set should include 4."); } void test_large_set() { struct IntSet set = new_int_set(); for (int i = 0; i <= 4096; i++) { int_set_add(&set, i); } assert_true(int_set_includes(&set, 100), "A set with 4,096 numbers should include 100."); assert_true(int_set_includes(&set, 513), "A set with 4,096 numbers should include 513."); assert_true(int_set_includes(&set, 4095), "A set with 4,096 numbers should include 4095."); assert_false(int_set_includes(&set, 4097), "A set with 4,096 numbers should not include 4097."); } int main(int argc, char* argv[]) { RUN_TESTS(test_basic_behavior); RUN_TESTS(test_prepending_values); RUN_TESTS(test_even_odd_values); RUN_TESTS(test_large_set); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main(void) { printf("\033[31m"); puts("赤い文字"); printf("\033[0m"); printf("\033[43m"); puts("黄色い背景"); printf("\033[0m"); printf("\033[31;43m"); puts("赤い文字;黄色い背景"); printf("\033[0m"); puts("元通り"); puts("元通り2"); return EXIT_SUCCESS; }
C
#include <assert.h> #include <stddef.h> #include "warnp.h" #include "scryptenc.h" #include "scryptenc_print_error.h" /** * scryptenc_print_error(rc, infilename, outfilename): * Print the error corresponding to ${rc}. If relevant, use ${infilename} * or ${outfilename} to display an error about reading or writing; these * arguments can be NULL to indicate standard input or output. */ void scryptenc_print_error(int rc, const char * infilename, const char * outfilename) { /* Sanity check: this should only be used for errors. */ assert(rc != SCRYPT_OK); /* Display error. */ switch (rc) { case SCRYPT_ELIMIT: warnp("Error determining amount of available memory"); break; case SCRYPT_ECLOCK: warnp("Error reading clocks"); break; case SCRYPT_EKEY: warnp("Error computing derived key"); break; case SCRYPT_ESALT: warnp("Error reading salt"); break; case SCRYPT_EOPENSSL: warnp("OpenSSL error"); break; case SCRYPT_ENOMEM: warnp("Error allocating memory"); break; case SCRYPT_EINVAL: warn0("Input is not valid scrypt-encrypted block"); break; case SCRYPT_EVERSION: warn0("Unrecognized scrypt format version"); break; case SCRYPT_ETOOBIG: warn0("Decrypting file would require too much memory"); break; case SCRYPT_ETOOSLOW: warn0("Decrypting file would take too much CPU time"); break; case SCRYPT_EBIGSLOW: warn0("Decrypting file would require too much memory" " and CPU time"); break; case SCRYPT_EPASS: warn0("Passphrase is incorrect"); break; case SCRYPT_EWRFILE: warnp("Error writing file: %s", (outfilename != NULL) ? outfilename : "standard output"); break; case SCRYPT_ERDFILE: warnp("Error reading file: %s", (infilename != NULL) ? infilename : "standard input"); break; case SCRYPT_EPARAM: warn0("Error in explicit parameters"); break; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "config.h" #include "puredb_p.h" #include "puredb_read.h" #include "puredb_write.h" /************************************************************************/ /* */ /************************************************************************/ /************************************************************************/ /* */ /************************************************************************/ int main(int argc, char* argv[]) { PureDBW dbw; char key[42]; char data[42]; if (puredbw_open(&dbw, "puredb.index", "puredb.data", "puredb.pdb") != 0) { perror("Can't create the database"); return 0; } for(int i = 0; i < 3000; i++) { snprintf(key, sizeof key, "%u", i); snprintf(data, sizeof data, "%u", i + 10); if (puredbw_add_s(&dbw, key, data) != 0) { return 0; } } if (puredbw_close(&dbw) != 0) { return 0; } puredbw_free(&dbw); PureDB db; off_t retpos; size_t retlen; char *founddata; if (puredb_open(&db, "puredb.pdb") != 0) { perror("Can't open the database"); return 0; } for(int i = 0; i < 100; i++) { snprintf(key, sizeof key, "%u", i); snprintf(data, sizeof data, "%u", i + 10); if (puredb_find_s(&db, key, &retpos, &retlen) != 0) { fprintf(stderr, "The key wasn't found\n"); return 0; } if ((founddata = puredb_read(&db, retpos, retlen)) != NULL) { printf("founddata %s\n", founddata); if (strcmp(founddata, data) != 0) { fprintf(stderr, "Wrong data\n"); return 0; } puredb_read_free(founddata); } } if (puredb_close(&db) != 0) { perror("The database couldn't be properly closed"); } return 0; }
C
#include<stdio.h> #include<stdlib.h> struct n { int a; struct n *p; }*h=NULL,*t; void insert(); void delete(); void display(); int main() { int i; do { printf("\n\tMENU\n\n1.Insert\n2.Delete\n3.Display\n4.Exit\n\nEnter your choice -"); scanf("%d",&i); printf("\n"); switch(i) { case 1: insert(); break; case 2: delete(); break; case 3: display(); break; case 4: printf("\n\nTHANK YOU"); break; default: printf("\nInvalid Input\n"); } }while(i!=4); return(0); } void insert() { int y=0; struct n *l=(struct n *)malloc(sizeof(struct n)); printf("\nEnter the integer-"); scanf("%d",&y); l->a=y; l->p=NULL; l->p=h; h=l; } void delete() { if(h==NULL) { printf("\nList is empty" ); } else { printf("\n%d",h->a); h=h->p; } } void display() { t=h; printf("\nThe list is-" ); while(t != NULL) { printf("\n%d",(t->a)); t=t->p; } }
C
#include <stdio.h> #include <stdlib.h> void transpose (int a[][3], int row, int col); int main() { int a[3][3]={{1,2,3},{4,5,6},{7,8,9}}; transpose(a,3,3); int i,j,temp; for (i=0;i<3;i++) { for (j=0;j<3;j++) printf("%d\t",a[i][j]); printf("\n"); } } void transpose (int a[][3], int row, int col) { int i,j,temp; int (*t)[3]=malloc(row*col*sizeof(int)); for (i=0;i<row;i++) for (j=0;j<col;j++) t[i][j]=a[i][j]; for (j=0;j<row;j++) for (i=0;i<col;i++) { a[j][i]=t[i][j]; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* color_inter.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: htorp <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/19 18:00:11 by htorp #+# #+# */ /* Updated: 2019/02/19 18:00:14 by htorp ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" void ci_str1(t_image *image, int x, int y) { char *s; int c; c = 0xFFFFFF; s = "Base color gradient:"; mlx_string_put(image->mlx_ptr, image->win_ptr, 1698, 390, c, s); s = "Base color map:"; mlx_string_put(image->mlx_ptr, image->win_ptr, 1698, 70, c, s); s = "- top color"; mlx_string_put(image->mlx_ptr, image->win_ptr, 1728, 460, c, s); s = "- bottom color"; mlx_string_put(image->mlx_ptr, image->win_ptr, 1728, 500, c, s); s = "To choose base color use keys:"; mlx_string_put(image->mlx_ptr, image->win_ptr, x, y, c, s); s = "1. 'R' - for red base"; mlx_string_put(image->mlx_ptr, image->win_ptr, x + 15, y + 20, c, s); s = "2. 'G' - for green base"; mlx_string_put(image->mlx_ptr, image->win_ptr, x + 15, y + 40, c, s); s = "3. 'B' - for blue base"; mlx_string_put(image->mlx_ptr, image->win_ptr, x + 15, y + 60, c, s); } void ci_str2(t_image *image, int x, int y) { char *s; int c; c = 0xFFFFFF; ci_str1(image, x, y); s = "To set top color use key 'H' and then"; mlx_string_put(image->mlx_ptr, image->win_ptr, x, y + 100, 0xFFFFFF, s); s = "click at the choosen color on the color map."; mlx_string_put(image->mlx_ptr, image->win_ptr, x, y + 120, 0xFFFFFF, s); s = "To set bottom color use key 'L' and then"; mlx_string_put(image->mlx_ptr, image->win_ptr, x, y + 160, 0xFFFFFF, s); s = "click at the choosen color on the color map."; mlx_string_put(image->mlx_ptr, image->win_ptr, x, y + 180, 0xFFFFFF, s); s = "To set base color hue click at the "; mlx_string_put(image->mlx_ptr, image->win_ptr, x, y + 220, 0xFFFFFF, s); s = "choosen color on the color gradient."; mlx_string_put(image->mlx_ptr, image->win_ptr, x, y + 240, 0xFFFFFF, s); s = "To show color changes use key 'S'."; mlx_string_put(image->mlx_ptr, image->win_ptr, x, y + 280, 0xFFFFFF, s); s = "To exit use 'E'."; mlx_string_put(image->mlx_ptr, image->win_ptr, x, y + 320, 0xFFFFFF, s); } void color_interface(t_image *image) { int i; int pos_x; int pos_y; i = 0; while (i < 1000) { mlx_pixel_put(image->mlx_ptr, image->win_ptr, 1140, i, 0xFFFFFF); i++; } pos_x = 1200; pos_y = 70; ci_str1(image, pos_x, pos_y); ci_str2(image, pos_x, pos_y); }
C
int main() { int arr[2]; int *p; arr[0] = 2; arr[1] = 3; p = &arr[0]; if(*(p++) != 2) return 1; if(*(p++) != 3) return 2; p = &arr[1]; if(*(p--) != 3) return 1; if(*(p--) != 2) return 2; p = &arr[0]; if(*(++p) != 3) return 1; p = &arr[1]; if(*(--p) != 2) return 1; return 0; }
C
#include <inttypes.h> #include <stdio.h> #include <stdlib.h> extern int j1; extern int l1; extern int j2; extern int l2; extern int j3; extern int l3; extern int j4; extern int l4; extern int j5; extern int l5; extern int j6; extern int l6; extern int j7; extern int l7; extern int j8; extern int l8; extern int j9; extern int l9; extern int j10; extern int l10; extern int j11; extern int l11; extern int j12; extern int l12; extern int j13; extern int l13; extern int j14; extern int l14; extern int ji; extern int l15; extern int ij1; extern int ij; extern int ji1; typedef float real; extern real t; extern real * restrict b; void loop() { #pragma scop for(j1 = 2; j1 <= l1; j1 += 2) for(j2 = j1; j2 <= l2; j2 += l1) for(j3 = j2; j3 <= l3; j3 += l2) for(j4 = j3; j4 <= l4; j4 += l3) for(j5 = j4; j5 <= l5; j5 += l4) for(j6 = j5; j6 <= l6; j6 += l5) for(j7 = j6; j7 <= l7; j7 += l6) for(j8 = j7; j8 <= l8; j8 += l7) for(j9 = j8; j9 <= l9; j9 += l8) for(j10 = j9; j10 <= l10; j10 += l9) for(j11 = j10; j11 <= l11; j11 += l10) for(j12 = j11; j12 <= l12; j12 += l11) for(j13 = j12; j13 <= l13; j13 += l12) for(j14 = j13; j14 <= l14; j14 += l13) for(ji = j14; ji <= l15; ji += l14) { ij1 = ij - 1; ji1 = ji - 1; if(ij - ji < 0) { t = b[ij1 - 1]; b[ij1 - 1] = b[ji1 - 1]; b[ji1 - 1] = t; t = b[ij1]; b[ij1] = b[ji1]; b[ji1] = t; } ij += 2; } #pragma endscop }
C
#include<stdio.h> #include<stdlib.h> #include"sqlist.h" int main() { sqlist *list; datatype arr[] = {1,2,3,4,5}; datatype arr1[] = {11,22,33,44,55}; int i,err; //list = sqlist_create(); sqlist_create1(&list); if(NULL == list) { fprintf(stderr, "sqlist_create failed!\n"); exit(1); } for(i=0; i<sizeof(arr)/sizeof(arr[0]); i++) { if( (err = sqlist_insert(list, 0, &arr[i])) != 0) { if(-1 == err) fprintf(stderr, "insert failed, arr is full!\n"); else if(-2 == err) fprintf(stderr, "insert failed, bad insert position!\n"); else fprintf(stderr, "insert failed, unknown error!\n"); exit(1); } } // sqlist *list1; sqlist_create1(&list1); if(NULL == list1) { fprintf(stderr, "sqlist_create failed!\n"); exit(1); } for(i=0; i<sizeof(arr1)/sizeof(arr1[0]); i++) { if( (err = sqlist_insert(list1, i, &arr1[i])) != 0) { if(-1 == err) fprintf(stderr, "insert failed, arr is full!\n"); else if(-2 == err) fprintf(stderr, "insert failed, bad insert position!\n"); else fprintf(stderr, "insert failed, unknown error!\n"); exit(1); } } // sqlist_display(list); sqlist_display(list1); sqlist_delete(list,1); sqlist_display(list); sqlist_display(list1); sqlist_union(list, list1); sqlist_display(list); sqlist_destroy(list); sqlist_destroy(list1); exit(0); }
C
/* Brandon Mord Csci 451 Hw 4 9/23/18 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <stdbool.h> bool reading = true; bool printable = false; pthread_mutex_t lock; pthread_t tid[2]; pthread_cond_t handled; int number=0; void* Producer(void * arg){ pthread_mutex_lock(&lock); FILE *inpt = fopen("hw4.in","r"); while((fscanf(inpt,"%d\n",&number))!= EOF){ printable = true; pthread_mutex_unlock(&lock); pthread_cond_wait(&handled,&lock); } pthread_mutex_unlock(&lock); reading=false; fclose(inpt); return NULL; } void* Consumer(void *arg){ FILE *out = fopen("hw4.out","w"); do{ pthread_mutex_lock(&lock); if(printable){ if(number % 2 == 0){ fprintf(out,"%d\n",number); fprintf(out,"%d\n",number); } else{ fprintf(out,"%d \n",number); } printable=false; } pthread_mutex_unlock(&lock); pthread_cond_signal(&handled); }while(reading); fclose(out); return NULL; } int main(){ pthread_mutex_init(&lock,NULL); pthread_cond_init(&handled,NULL); pthread_create(&(tid[0]),NULL,Producer,NULL); pthread_create(&(tid[1]),NULL,Consumer,NULL); int i; for(i=0;i<2;i++){ pthread_join(tid[i],NULL); } return 0; }
C
#define _CRT_SECURE_NO_WARNINGS 1 #pragma warning(disable:4996) //1ĸ #include <stdio.h> #include <windows.h> #include <math.h> #include <assert.h> #include <stdarg.h> int count(int num); int main() { int num = 1231; printf("%d\n", count(num)); system("pause"); return 0; } int count(int num) { unsigned char* p = &(unsigned char)num; int i = 0, count = 0; for (; i < 4; i++) { while (*p != 0) { if ((*p & 1) == 1) { count++; } *p = *p >> 1; } p++; } return count; }
C
#include "../../Librerie/Lista/lista.h" #include <stdio.h> #include <assert.h> lista carica_lista(char* nome_file) { int elementi, i; float valore; lista l = crea_lista(); FILE* fp = fopen(nome_file, "r"); assert(fp != NULL); fscanf(fp, "%d", &elementi); for (i = 0; i < elementi; i++) { fscanf(fp, "%f", &valore); aggiungi_in_coda(&l, valore); } return l; }
C
/* * mm_alloc.c * * Stub implementations of the mm_* routines. */ #include "mm_alloc.h" #include <stdlib.h> #include <sys/resource.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <memory.h> #include <unistd.h> struct metadata* first_metadata; struct metadata* metadata_init(size_t new_size, struct metadata* prev) { struct metadata *meta; meta = (struct metadata *) sbrk(new_size); if (meta == (void *) -1) { return NULL; } meta->size = new_size; meta->free = false; meta->prev = prev; meta->next = NULL; meta->current_block = meta + sizeof(struct metadata); memset(meta->current_block, 0, meta->size); if (prev != NULL) { prev->next = meta; } return meta; } void *mm_malloc(size_t size) { if (size == 0) { return NULL; } size_t new_size = (sizeof(struct metadata) + size); if (first_metadata == NULL) { first_metadata = metadata_init(new_size, NULL); if (first_metadata == NULL) { return NULL; } return first_metadata->current_block; } struct metadata *meta_head = first_metadata; while (true) { while (meta_head->next != NULL && meta_head->free == false) { meta_head = meta_head->next; } if (meta_head->free == true) { if (meta_head->size >= size) { struct metadata *meta; meta = meta_head; size_t size_diff = meta->size - size; meta->free = false; if (size_diff > sizeof(struct metadata)) { meta->size = size; struct metadata *split_meta = (meta->current_block + size); split_meta->next = meta->next; meta->next = split_meta; split_meta->prev = meta; split_meta->free = true; split_meta->size = size_diff - sizeof(struct metadata); split_meta->current_block = split_meta + sizeof(struct metadata); memset(split_meta->current_block, 0, (size_diff - sizeof(struct metadata))); } memset(meta->current_block, 0, meta->size); return meta->current_block; } else if (meta_head->next != NULL) { meta_head = meta_head->next; continue; } } if (meta_head->next == NULL) { struct metadata *meta = metadata_init(new_size, meta_head); if (meta == NULL) { return NULL; } else { memset(meta->current_block, 0, size); return meta->current_block; } } } return NULL; } void *mm_realloc(void *ptr, size_t size) { struct metadata *meta = (struct metadata*) ptr - sizeof(struct metadata); size_t len = meta->size; mm_free(ptr); void *new_place = mm_malloc(size); if (len > size) { len = size; } memcpy(new_place, ptr, len); return NULL; } void mm_free(void *ptr) { if (ptr == NULL) { return; } struct metadata *meta = first_metadata; bool found = false; if (meta == NULL) { return; } while(!found && (meta != NULL)) { if (meta->current_block == ptr) { found = true; } else { if (meta->next != NULL) { meta = meta->next; } else { return; } } } if (meta == NULL) { return; } bool prev_free = false; bool next_free = false; if (meta != NULL) { if (meta->prev != NULL) { if (meta->prev->free == true) { prev_free = true; } } if (meta->next != NULL) { if (meta->next->free == true) { next_free = true; } } } else { return; } size_t freeing_block_size = meta->size; if (prev_free && next_free) { size_t top_block_size = meta->next->size; size_t bottom_block_size = meta->prev->size; meta->prev->next = meta->next->next; meta = meta->prev; if (meta->next != NULL) { meta->next->prev = meta; } meta->size = freeing_block_size + sizeof(struct metadata) + bottom_block_size + sizeof(struct metadata) + top_block_size; meta->free = true; } else if (next_free) { size_t top_block_size = meta->next->size; meta->next = meta->next->next; if (meta->next != NULL) { meta->next->prev = meta; } meta->size = freeing_block_size + sizeof(struct metadata) + top_block_size; meta->free = true; } else if (prev_free) { size_t bottom_block_size = meta->prev->size; meta->prev->next = meta->next; meta = meta->prev; if (meta->next != NULL) { meta->next->prev = meta; } meta->size = freeing_block_size + sizeof(struct metadata) + bottom_block_size; meta->free = true; } else { meta->free = true; } }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int gfp_t ; /* Variables and functions */ unsigned int PAGE_ALLOC_COSTLY_ORDER ; int __GFP_NOFAIL ; int __GFP_NORETRY ; int __GFP_REPEAT ; __attribute__((used)) static inline int should_alloc_retry(gfp_t gfp_mask, unsigned int order, unsigned long pages_reclaimed) { /* Do not loop if specifically requested */ if (gfp_mask & __GFP_NORETRY) return 0; /* * In this implementation, order <= PAGE_ALLOC_COSTLY_ORDER * means __GFP_NOFAIL, but that may not be true in other * implementations. */ if (order <= PAGE_ALLOC_COSTLY_ORDER) return 1; /* * For order > PAGE_ALLOC_COSTLY_ORDER, if __GFP_REPEAT is * specified, then we retry until we no longer reclaim any pages * (above), or we've reclaimed an order of pages at least as * large as the allocation's order. In both cases, if the * allocation still fails, we stop retrying. */ if (gfp_mask & __GFP_REPEAT && pages_reclaimed < (1 << order)) return 1; /* * Don't let big-order allocations loop unless the caller * explicitly requests that. */ if (gfp_mask & __GFP_NOFAIL) return 1; return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> void * run( void * data ){ //(void)data; size_t thread_num = (size_t)data; printf( "HELLO WORLD from secondary thread %zu\n", thread_num ); return NULL; } int main( int argc, char* argv[] ){ size_t t_count = sysconf(_SC_NPROCESSORS_ONLN); if( argc >= 2 ) t_count = strtoull( argv[1], NULL, 10 ); pthread_t * threads = malloc( t_count * sizeof(pthread_t) ); for( size_t index = 0; index < t_count; ++index ) pthread_create( &threads[index], NULL, run, (void *)index ); printf( "HELLO WORLD from main thread\n" ); for( size_t index = 0; index < t_count; ++index ) pthread_join( threads[index], NULL ); free(threads); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include "sorting.h" #define KB (1024) #define MB (1024 * KB) #define GB (1024 * MB) #define LARGEST_CACHE_SZ (3 * MB) #define NUM_SORTS 4 #define VEC_SIZE 200000 static unsigned char dummy_buffer[LARGEST_CACHE_SZ]; void cache_clean() { unsigned long long i; for (i=0; i<LARGEST_CACHE_SZ; i++) dummy_buffer[i] += 1; } int fill(int *v, int size){ for (int i = 0; i < size; i++) { v[i] = rand()%VEC_SIZE; } } int isordered(int *v, int size){ for (int i = 1; i < size; i++) { if(v[i] < v[i-1]){ return 0; } printf("%d ", v[i]); } return 1; } int main(int argc, char *argv[]) { srand(2); int *v = malloc(sizeof(int)*VEC_SIZE); fill(v, VEC_SIZE); // a function that fills an array with values between 0 and array.size cache_clean(); // a funtion that cleans the cache before running sorting algorithm radixsort(v, VEC_SIZE);//O(n) printf("radix"); fill(v, VEC_SIZE); // a function that fills an array with values between 0 and array.size cache_clean(); // a funtion that cleans the cache before running sorting algorithm heapsort(v, VEC_SIZE);//O(nlogn) printf("heap"); fill(v, VEC_SIZE); // a function that fills an array with values between 0 and array.size cache_clean(); // a funtion that cleans the cache before running sorting algorithm mergesort(v, 0,VEC_SIZE);//O(nlogn) printf("merge"); fill(v, VEC_SIZE); // a function that fills an array with values between 0 and array.size cache_clean(); // a funtion that cleans the cache before running sorting algorithm bubblesort(v, VEC_SIZE);//O(n²) printf("bubble"); free(v); return 0; }
C
#include<stdio.h> int main() { int n,i,count; printf("\n Enter the value:"); scanf("%d",&n); for(i=0;i<n;i++) { if(i%2==0) { count++; } } if(i==2) { printf("yes"); } else { printf("no"); } }
C
/* Problem 10598 - Find the Latitude */ #include <stdio.h> #include <math.h> #ifndef M_PI #define M_PI 3.141592653589793238462643383279 #endif int main() { int t = 1, k; double n, R; while (1) { scanf("%lf %lf", &R, &n); if (!R && !n) break; printf("Case %d:\n", t++); for (k = 1; k < 11; k++) { printf("%.5lf\n", 360/(2*M_PI)*acos(n/(2*M_PI*R*k))-n*180/(M_PI*R)); } } return 0; }
C
/* #include<stdio.h> #include<string.h> main() { FILE *fp; char f[15],str[15]; int c=0; printf("enter the word to be checked\n"); gets(f); fp=fopen("file3.txt","r"); if(fp=NULL) { printf("file cannot open"); exit(1); } while(!feof(fp)) { fscanf(fp,"%s",str); if(strcmp(str,f)==0) c++; } printf("frequency is %d ",c); fclose(fp); } */ /*#include<stdio.h> #include<string.h> main() { char s[]="abcd"; char *s1[]="abcd"; printf("%d%d%d",strlen(s1),strlen(s),strlen("abcd")); } */
C
//Program to swap two numbers without using third variable //Author Aakash Date 18 Dec 2020 #include<stdio.h> int main() { int a,b; printf("Enter first number :"); scanf("%d",&a); printf("Enter second number :"); scanf("%d",&b); a=a+b; b=a-b; a=a-b; printf("After calculation :- \n First number is %d and second number is %d",a,b); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <sys/wait.h> #define CHILD 0 int main(int argc, char *const argv[], char *const envp[]) { puts("Opening a pipe."); int pipe_fd[2]; int pipe_res = pipe(pipe_fd); if (pipe_res < 0) { puts("Error in opening pipe."); exit(errno); } puts("About to split."); pid_t pid = fork(); int status; char buf[1]; ssize_t size; char *const _argv[] = {"/bin/ls", "-l", "./", NULL}; switch (pid){ case -1: // error puts("Failed to fork."); exit(errno); case CHILD: //child close(pipe_fd[0]); if (dup2(pipe_fd[1], STDOUT_FILENO) == -1) { puts("failed to replace stdout."); exit(errno); } write(STDOUT_FILENO, "Greetings from the child process!\n", 34); if (execve(_argv[0], &_argv[0], envp) == -1) { puts("Failed to execute ls."); exit(errno); } close(STDOUT_FILENO); return 0; default: //parent close(pipe_fd[1]); if (dup2(pipe_fd[0], STDIN_FILENO) == -1) { puts("failed to replace stdin."); exit(errno); } write(STDOUT_FILENO, "\t", 1); while((size = read(STDIN_FILENO, buf, 1)) > 0) { if (buf[0] == '\n') { write(STDOUT_FILENO, "\n\t", 2); } else { write(STDOUT_FILENO, buf, size); } } waitpid(pid, &status, 0); close(STDIN_FILENO); puts("\nDone."); return WEXITSTATUS(status); } } // A disadvantage to using switch is that all of the variables need to be // declared in advance before the switch statement - i.e. variable // declerations can not be made inside the case statements.
C
#include <stdio.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include "job.h" int nextjid = 1; /* 清除job,把job的值恢复为默认值 */ void clearjob(job_t *job) { job->pid = 0; job->jid = 0; job->state = UNDEF; job->cmdline[0] = '\0'; } /* 初始化job_table */ void initjob_table(job_t *job_table) { int i; for (i = 0; i < MAXJOBS; i++) clearjob(&job_table[i]); } /* 返回当前已经分配的最大jid */ int maxjid(job_t *job_table) { int i, max = 0; for (i = 0; i < MAXJOBS; i++) if (job_table[i].jid > max) max = job_table[i].jid; return max; } /* 向job_table新增一个job */ int addjob(job_t *job_table, pid_t pid, int state, char *cmdline) { int i; if (pid < 1) return 0; for (i = 0; i < MAXJOBS; i++) { if (job_table[i].pid == 0) { job_table[i].pid = pid; job_table[i].state = state; job_table[i].jid = nextjid++; if (nextjid > MAXJOBS) nextjid = 1; strcpy(job_table[i].cmdline, cmdline); return 1; } } printf("Tried to create too many jobs\n"); return 0; } /* 从job_table里删除对应pid号的job */ int deletejob(job_t *job_table, pid_t pid) { int i; if (pid < 1) return 0; for (i = 0; i < MAXJOBS; i++) { if (job_table[i].pid == pid) { clearjob(&job_table[i]); nextjid = maxjid(job_table) + 1; return 1; } } return 0; } /* 返回当前属于foreground的job的pid,没有的话返回0 */ pid_t fgpid(job_t *job_table) { int i; for (i = 0; i < MAXJOBS; i++) if (job_table[i].state == FG) return job_table[i].pid; return 0; } /* 根据pid得到对应的job */ job_t *getjobpid(job_t *job_table, pid_t pid) { int i; if (pid < 1) return NULL; for (i = 0; i < MAXJOBS; i++) if (job_table[i].pid == pid) return &job_table[i]; return NULL; } /* 根据jid得到对应的job */ job_t *getjobjid(job_t *job_table, int jid) { int i; if (jid < 1) return NULL; for (i = 0; i < MAXJOBS; i++) if (job_table[i].jid == jid) return &job_table[i]; return NULL; } /* 从pid转换为jid */ int pid2jid(job_t *job_table, pid_t pid) { int i; if (pid < 1) return 0; for (i = 0; i < MAXJOBS; i++) if (job_table[i].pid == pid) { return job_table[i].jid; } return 0; } /* 显示job_table */ void listjob_table(job_t *job_table) { int i; for (i = 0; i < MAXJOBS; i++) { if (job_table[i].pid != 0) { printf("[%d] (%d) ", job_table[i].jid, job_table[i].pid); switch (job_table[i].state) { case BG: printf("Running "); break; case FG: printf("Foreground "); break; case ST: printf("Stopped "); break; default: printf("listjob_table: Internal error: job[%d].state=%d ", i, job_table[i].state); } printf("%s\n", job_table[i].cmdline); } } }
C
#include <stdio.h> #include <math.h> #define S (a+b+c)/2 #define H s*(s-a)*(s-b)*(s-c) #define M sqrt(H)*4/3 #define P2 printf("%.3lf\n",m) ///AC int main() { double a,b,c,s,m; while(scanf("%lf%lf%lf",&a,&b,&c)==3) { s=S; if(H<=0) m=-1; else m=M; P2; } return 0; }
C
#include "isi_hash.h" /* * This hash function code is taken from Robert Jenkins. See * http://burtleburtle.net/bob/hash/evahash.html */ /** * @param _k the key * @param len the length of the key in bytes * @param initval the previous hash, or an arbitrary value */ uint32_t isi_hash32(const void *_k, size_t len, uint32_t initval) { #define mix(a, b, c) \ do { \ a -= b; a -= c; a ^= (c >> 13); \ b -= c; b -= a; b ^= (a << 8); \ c -= a; c -= b; c ^= (b >> 13); \ a -= b; a -= c; a ^= (c >> 12); \ b -= c; b -= a; b ^= (a << 16); \ c -= a; c -= b; c ^= (b >> 5); \ a -= b; a -= c; a ^= (c >> 3); \ b -= c; b -= a; b ^= (a << 10); \ c -= a; c -= b; c ^= (b >> 15); \ } while (0) const uint8_t *k = _k; uint32_t a = 0x9e3779b9, b = 0x9e3779b9, c = initval; /* Hash chunks of 12 bytes. */ while (len >= 12) { a += *(const uint32_t *)&k[0]; b += *(const uint32_t *)&k[4]; c += *(const uint32_t *)&k[8]; mix(a, b, c); k += 12; len -= 12; } /* * Hash the remainder byte-by-byte, until it reaches a multiple of * 4 bytes. */ switch (len) { case 11: c += (uint32_t)k[10] << 16; case 10: c += (uint32_t)k[9] << 8; case 9: c += (uint32_t)k[8]; case 8: b += *(const uint32_t *)&k[4]; a += *(const uint32_t *)&k[0]; break; case 7: b += (uint32_t)k[6] << 16; case 6: b += (uint32_t)k[5] << 8; case 5: b += (uint32_t)k[4]; case 4: a += *(const uint32_t *)&k[0]; break; case 3: a += (uint32_t)k[2] << 16; case 2: a += (uint32_t)k[1] << 8; case 1: a += (uint32_t)k[0]; } mix(a, b, c); return c; #undef mix } /** * @param _k the key * @param len the length of the key in bytes * @param level the previous hash, or an arbitrary value */ uint64_t isi_hash64(const void *_k, size_t len, uint64_t level) { #define mix(a, b, c) \ do { \ a -= b; a -= c; a ^= (c >> 43); \ b -= c; b -= a; b ^= (a << 9); \ c -= a; c -= b; c ^= (b >> 8); \ a -= b; a -= c; a ^= (c >> 38); \ b -= c; b -= a; b ^= (a << 23); \ c -= a; c -= b; c ^= (b >> 5); \ a -= b; a -= c; a ^= (c >> 35); \ b -= c; b -= a; b ^= (a << 49); \ c -= a; c -= b; c ^= (b >> 11); \ a -= b; a -= c; a ^= (c >> 12); \ b -= c; b -= a; b ^= (a << 18); \ c -= a; c -= b; c ^= (b >> 22); \ } while (0) const uint8_t *k = _k; uint64_t a = level, b = level, c = 0x9e3779b97f4a7c13ULL; /* Hash chunks of 24 bytes. */ while (len >= 24) { a += *(const uint64_t *)&k[0]; b += *(const uint64_t *)&k[8]; c += *(const uint64_t *)&k[16]; mix(a, b, c); k += 24; len -= 24; } /* * Hash the remainder byte-by-byte, until it reaches a multiple of * 8 bytes. */ switch (len) { case 23: c += ((uint64_t)k[22] << 48); case 22: c += ((uint64_t)k[21] << 40); case 21: c += ((uint64_t)k[20] << 32); case 20: c += *(const uint32_t *)&k[16]; b += *(const uint64_t *)&k[8]; /* 8 .. 15 */ a += *(const uint64_t *)&k[0]; /* 0 .. 7 */ break; case 19: c += ((uint64_t)k[18] << 16); case 18: c += ((uint64_t)k[17] << 8); case 17: c += ((uint64_t)k[16]); case 16: b += *(const uint64_t *)&k[8]; a += *(const uint64_t *)&k[0]; break; case 15: b += ((uint64_t)k[14] << 48); case 14: b += ((uint64_t)k[13] << 40); case 13: b += ((uint64_t)k[12] << 32); case 12: b += *(const uint32_t *)&k[8]; /* 8 .. 11 */ a += *(const uint64_t *)&k[0]; /* 0 .. 7 */ break; case 11: b += ((uint64_t)k[10] << 16); case 10: b += ((uint64_t)k[9] << 8); case 9: b += ((uint64_t)k[8]); case 8: a += *(const uint64_t *)&k[0]; break; case 7: a += ((uint64_t)k[6] << 48); case 6: a += ((uint64_t)k[5] << 40); case 5: a += ((uint64_t)k[4] << 32); case 4: a += *(const uint32_t *)&k[0]; /* 0 .. 3 */ break; case 3: a += ((uint64_t)k[2] << 16); case 2: a += ((uint64_t)k[1] << 8); case 1: a += ((uint64_t)k[0]); } mix(a, b, c); return c; #undef mix }
C
/* * Erich Kramer Concurrency Homework 3 CS444 * Problem 2, * * */ #include <pthread.h> #include <semaphore.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <time.h> #define THREAD_COUNT 10 typedef struct{ }arg; arg* argGen(){ arg* tmp = (arg*)malloc(sizeof(arg) ); /*Important population goes here*/ return tmp; } void *thread_exec( void* args){ printf("thread execution began\n"); return NULL; } void spawn(pthread_t* thr, int size, void* (*runThread)(void*), arg* args ){ int i, check; for( i = 0; i < size; i++){ check = pthread_create(&thr[i], NULL, runThread, (void*) args); if( check != 0){ fprintf(stderr, "Thread Creation Failure\n"); exit(1); } } } void join(pthread_t* thr, int size ){ int i; for( i=0; i< size; i++){ pthread_join(thr[i], NULL); } } void init(){ } int main(int argc, char** argv){ init(); pthread_t threads[THREAD_COUNT]; arg* param = argGen(); spawn(threads, 1, thread_exec, param); join(threads, 1); return 0; }
C
/* Tim M. Lael CS4280 p1 26-FEB 2017 */ /* testScanner.c source file containing scanner testing functions */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "testScanner.h" #include "token.h" #include "scanner.h" /* Token name array to display on terminal feedback Mapped to token enumeration order */ char *tokenNames[35] = { "End of File", "Error", "Identifier", "Number", "Equal Sign", "Double Equal Sign", "Equal Bang", "Double Left Arrow", "Double Right Arrow", "Colon", "Plus Sign", "Minus Sign", "Asterisk", "Slash", "Ampersand", "Percent Sign", "Period", "Left Parenthesis", "Right Parenthesis", "Comma", "Left Brace", "Right Brace", "Semicolon", "Left Bracket", "Right Bracket", "start Keyword", "stop Keyword", "decision Keyword", "while Keyword", "void Keyword", "int Keyword", "return keyword", "read Keyword", "print Keyword", "program Keyword" }; /* testScanner function calls scanner while input file !eof iand reports returned token values*/ void testScanner (FILE *infile){ token_t temp; int lineNo = 1; do{ temp = scan(infile, &lineNo); if(strcmp(tokenNames[temp.tkIdentifier], "Error") == 0){ printf("Scanner Error: %s Not Allowed At Line: %i.\n", temp.tkString, temp.lineNo); printf("Exiting\n"); exit(EXIT_FAILURE); } else{ printf("Read %s Token With Value: %s At Line %i.\n", tokenNames[temp.tkIdentifier], temp.tkString, temp.lineNo); } } while(!feof(infile)); }
C
/*----------------------------------------------------------------------------------------------- * Author : Rammya Dharshini K * Date : Fri 23 Jul 2021 19:30:04 * File : C_Sample_Chapter-1_Program-31_arith_oper_pre_post.c * Title : Operators - Arithmetic - Pre and Post * Description : Symbols that instructs the compiler to perform specific arithmetic or * logical operation on operands. All C operators do 2 things * - Operates on its operands * - Returns a value * Operators play a very crucial role in controlling the system behaviour in * general. There are different types of Operators available in C Programming * Language. This example demonstrates the behaviour of post and pre * increment operators. *---------------------------------------------------------------------------------------------*/ #include<stdio.h> int main() { int x = 0; /* The value gets incremented but not reflected to x */ if (x++) puts("Yes :)"); else puts("Huh :("); printf("x = %dn", x); /* The value gets decremented and reflected to x on the same expression */ if (--x) puts("Yes :)"); else puts("Huh :("); printf("x = %dn", x); return 0; }
C
/* * Eli-Henry Dykhne * 0996524 * 04/03/2019 * A3 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/timeb.h> #include "A3.h" int main(){ FILE *file = fopen("data_5.txt", "r"); struct timeb *start = malloc(sizeof(struct timeb)); struct timeb *stop = malloc(sizeof(struct timeb)); int num; int i = 0; int cap = 0; int size = 500; char buf; char *str = malloc(500); int shifts; //reading in the file char by char while(EOF != (buf = fgetc(file))){ str[i] = buf; i++; if(size<=i){ size+=500; str = realloc(str, sizeof(char)*size); } } str[i] = '\0'; str = realloc(str, sizeof(char)*(strlen(str)+1)); printf("Num Chars: %d\n", i); fclose(file); char word[1000]; printf("Enter a string: "); while((buf = getc(stdin)) != '\n'){ word[cap] = buf; cap++; } word[cap] = '\0'; ftime(start); num = bruteNumOcurances(str, word, i, strlen(word), &shifts); ftime(stop); printf("Brute string search\n--------------------------\nNumber of occurances: %d\nNum pattern shifts: %d\nTime: %f\n", num, shifts, elapse(stop, start)); ftime(start); num = horspoolNumOcurances(str, word, i, strlen(word), &shifts); ftime(stop); printf("\n\n\nHorspool string search\n--------------------------\nNumber of occurances: %d\nNum pattern shifts: %d\nTime: %f\n", num, shifts, elapse(stop, start)); ftime(start); num = boyerMooreNumOcurances(str, word, i, strlen(word), &shifts); ftime(stop); printf("\n\n\nBoyer-Moore string search\n--------------------------\nNumber of occurances: %d\nNum pattern shifts: %d\nTime: %f\n", num, shifts, elapse(stop, start)); //boyerMooreTableGenerator("BAOBAB", 6); free(str); free(start); free(stop); return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_5__ TYPE_1__ ; /* Type definitions */ typedef scalar_t__ vnode_t ; struct filedesc {scalar_t__ fd_cdir; scalar_t__ fd_rdir; } ; struct cdirargs {scalar_t__ olddp; scalar_t__ newdp; } ; typedef TYPE_1__* proc_t ; struct TYPE_5__ {struct filedesc* p_fd; } ; /* Variables and functions */ int PROC_RETURNED ; int /*<<< orphan*/ proc_fdlock (TYPE_1__*) ; int /*<<< orphan*/ proc_fdunlock (TYPE_1__*) ; int /*<<< orphan*/ vnode_ref (scalar_t__) ; int /*<<< orphan*/ vnode_rele (scalar_t__) ; __attribute__((used)) static int checkdirs_callback(proc_t p, void * arg) { struct cdirargs * cdrp = (struct cdirargs * )arg; vnode_t olddp = cdrp->olddp; vnode_t newdp = cdrp->newdp; struct filedesc *fdp; vnode_t tvp; vnode_t fdp_cvp; vnode_t fdp_rvp; int cdir_changed = 0; int rdir_changed = 0; /* * XXX Also needs to iterate each thread in the process to see if it * XXX is using a per-thread current working directory, and, if so, * XXX update that as well. */ proc_fdlock(p); fdp = p->p_fd; if (fdp == (struct filedesc *)0) { proc_fdunlock(p); return(PROC_RETURNED); } fdp_cvp = fdp->fd_cdir; fdp_rvp = fdp->fd_rdir; proc_fdunlock(p); if (fdp_cvp == olddp) { vnode_ref(newdp); tvp = fdp->fd_cdir; fdp_cvp = newdp; cdir_changed = 1; vnode_rele(tvp); } if (fdp_rvp == olddp) { vnode_ref(newdp); tvp = fdp->fd_rdir; fdp_rvp = newdp; rdir_changed = 1; vnode_rele(tvp); } if (cdir_changed || rdir_changed) { proc_fdlock(p); fdp->fd_cdir = fdp_cvp; fdp->fd_rdir = fdp_rvp; proc_fdunlock(p); } return(PROC_RETURNED); }
C
/** * Reading-Transmitter * @author [David Tolbert](npm.merlin@gmail.com) * @see https://curl.haxx.se/libcurl/c/ * @todo refactor code and add more functions */ #ifndef HEADER_FILE #define HEADER_FILE #include <curl/curl.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <unistd.h> #define URL_AUTH "http://127.0.0.1:3000/test-hook/auth/" // Login route #define URL_TRANSMISSION "http://127.0.0.1:3000/test-hook/transmissions/" // Transmission route #define BUFFER_SIZE (256 * 1024) // Receive buffer (256kB) #define API_KEY "Ks9lkns5Lsskaa781satU8jsab8245s33" // API Key #define SEPERATOR "&" // Parameter separator. #define API_KEY_PREFIX "apiKey=" #define TOKEN_PREFIX "token=" #define READING_PREFIX "reading=" #define DUMMY_READING "12.75 mV" #define VERIFY 1 #define TRANSMIT 0 // STRUCTURES // Result of write callback. struct write_result { char *data; int pos; }; // Device step specifications. struct device_specs { int step; float tol1; float tol2; }; // HELPER FUNCTIONS /** * Allocate the receive buffer */ char * allocReceiveBuffer(); /** * Fake token generator */ char * gen_random(char *s, const int len); // CLIENT FUNCTIONS /** * Generate client token * @parame {const char *} api_key - API Key */ char * generateClientToken(const char *api_key); /** * Connect device * @parame {const char *} api_key - API Key */ char * verifyClient(CURL *curl, const char *api_key); /** * Transmit reading * @parame {const char *} reading - reading of measurement device */ char * transmitReading(CURL *curl, const char *reading); /** * Set device properties. * @parame {const char *} name - Device name * @device_name {const char *} version - Device version * @device_name {int} mtype - Type of measurement */ int setDeviceProperties(const char *name, const char *version, int mtype); #endif
C
#include<stdlib.h> #include<stdio.h> #include<math.h> #include<GL/glut.h> void init() { gluOrtho2D(-300, 300, -300, 300); } //Desenha os 8 pontos da circuferência dado um ponto (x,y) void CirclePoints(int x, int y) { glColor3f(1, 0, 0); glBegin(GL_POINTS); glVertex2i(x,y); glVertex2i(x,-y); glVertex2i(-x,y); glVertex2i(-x,-y); glVertex2i(y,x); glVertex2i(y,-x); glVertex2i(-y,x); glVertex2i(-y,-x); glEnd(); glFlush(); } void desenhaCircunferencia(int r) { //Valores utilizados int x,y; float d; //Valores iniciais x = 0; y = r; d = (5 / 4) - r; //Pintando os pontos iniciais(Neste caso, pinta apenas 4 pontos) [(0,R),(0,-R),(-0,R),(-0,-R),(R,0),(R,-0),(-R,0),(-R,-0)] CirclePoints(x,y); //Começando iterações while(y > x) { if(d < 0) { //Escolhemos E d += 2 * x + 3; //Incrementador de E = "2x + 3" x++; } else { //Escolhemos SE d += 2 * (x - y) + 5; //Incrementador de SE = "2x - 2y + 5" x++; y--; } //Pintando os novos pontos CirclePoints(x,y); } } void Display() { glClear(GL_COLOR_BUFFER_BIT); glClearColor(0, 0, 0, 1); desenhaCircunferencia(200); glEnd(); glFlush(); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitWindowPosition(0, 0); glutInitWindowSize(300, 300); glutCreateWindow("Desenho de circunferencia"); init(); glutDisplayFunc(Display); glutMainLoop(); return 0; }
C
int* get_value-wrong() { int x = 20; return &x; } int add_value(int y) { int a = 99; return a + y; } int main(void) { int *a, b; a = get_value_wrong(); printf("First result %d\n", *a); b = add_value(7); printf("Second value %d\n", b); printf("First result (changed?) %d\n", *a); }
C
#include "useful.h" /** * Ӽ̶ȡһַ浽buff * 룺ŵbuffַ飬鳤 * ȡַ */ int mygetline(char* buff, int length){ int i = 0; char c; while((c = getchar()) != EOF && c != '\n' && i < length - 1){ buff[i++] = c; } buff[i] = '\0'; return i; } int myisblank(char c){ return c == ' ' || c == '\n' || c == '\t'; } int isNum(char c){ return c >= '0' && c <= '9'; } int myatoi(char c){ if(isNum(c)){ return c - '0'; }else { printf("error: not a number.\n"); return -1; } } int str2i(char *str){ char c; int sum = 0; while ((c = *str)) { if(isNum(c)){ sum = sum * 10 + myatoi(c); }else{ printf("error: %c is not a number.\n", c); return -1; } str++; } return sum; }
C
/** * *@author Israel Schimitz *@date 23/04/2013 *@brief Tabalho I - Sistemas Embarcados UCS *@details Deverá ler um vetor de 20 caracteres, ordenar crescentemente, calcular a média, o desvio padrão e a variância * *@version 1.0 */ #include <stdio.h> #include <math.h> int i=0; ///Variável do tipo inteiro para rodar os laços "for" int j=0; ///Variável do tipo inteiro para rodar os laços "for" /** *@brief Função para imprimir em tela os valores de um vetor do tipo "inteiro" *@param x Vetor com os dados de entrada que serão manipulados *@return Retorna 0 se ocorrer tudo certo */ int imprime_valores (int x[]) { for (j=0;j<20;j++) { printf("%d""\n",x[j]); } j=0; return 0; } /** *@brief Função para inserir dados no vetor x (tipo inteiro) a partir do teclado *@param x Vetor com os dados de entrada que serão manipulados *@return Retorna 0 se ocorrer tudo certo */ int leitura_dados (int x[]) { printf("Digite os vinte valores:\n"); for (i=0;i<20;i++) { scanf("%d",&x[i]); } i=0; return 0; } /** *@brief Função que ordena de forma crescente os dados de um vetor do tipo "inteiro" *@param x Vetor com os dados de entrada que serão manipulados *@return Retorna 0 se ocorrer tudo certo */ int ordena_crescente (int x[]) { int aux=0; for (i=0;i<20;i++) { for (j=1;j<20;j++) { if (x[j] < x[j-1]) { aux=x[j]; x[j]=x[j-1]; x[j-1]=aux; } } } i=0; j=0; return 0; } /** *@brief Função que calcula a média entre os valores de um vetor do tipo "inteiro" *@param x Vetor com os dados de entrada que serão manipulados *@return Retorna o valor da média entre os valores do vetor x */ float calcula_media (int x[]) { int aux1=0; float m=0; for (i=0;i<20;i++) { aux1 = aux1+x[i]; } i=0; m=aux1/20; return (m); } /** *@brief Função que calcula o desvio padrão entre os valores de um vetor (inteiro) e a média (float), previamente calculada *@param x Vetor com os dados de entrada que serão manipulados *@param y Valor com o valor da média (tipo - float) *@return Retorna o valor do desvio padrão entre os dados do vetor "x" e a média "y" */ float calcula_dsvpd (int x[], float y) { float m=0; float n=0; for (i=0;i<20;i++) { n=n+pow((x[i]-y),2); } i=0; m=sqrt(n/19); return (m); } /** *@brief Função que calcula a variância de um desvio padrão préviamente calculado *@param x Entrada - valor do Desvio padrão *@return Retorna o valor da variancia do desvio padrão x */ float calcula_variancia (float x) { float m=0; m=pow(x,2); return (m); } /** *@brief Função principal do sistema *@return Retorna 0 se tudo ocorrer de acordo */ int main () { int vector [20]; float media=0; float dsvpd=0; float var=0; system("clear"); leitura_dados (vector); printf("Valores digitados:\n"); imprime_valores (vector); ordena_crescente (vector); printf("Valores em ordem crecente:\n"); imprime_valores (vector); media = calcula_media(vector); printf("A média é: %f\n", media); dsvpd = calcula_dsvpd (vector,media); printf("O desvio padrão é: %f\n", dsvpd); var = calcula_variancia (dsvpd); printf("A variância é: %f\n", var); }
C
typedef struct { char nombre[50]; char dni[15]; int edad; int estado; }ePersona; ePersona agregarPersona(ePersona[], int); /** \brief Agrega una persona al array. * * \param Un array del tipo ePersona. * \param Entero que representa el tamao del array. * \return Devuelve la persona ingresada. * */ int pedirDatoEnteroValidado(int, char[], int); /** \brief Pide y valida un valor entero entre 2 limites. * * \param limite 1. * \param Qu se va a validar, por ejemplo, "edad". * \param limite 2. * \return Devuelve el numero entero validado. * */ const char* pedirCadenaNumerosValidada(char[], int); /** \brief Pide una cadena de slo nmeros. * * \param Qu se va a ingresar, por ejemplo, "DNI". * \param El largo deseado de la cadena. * \return Devuelve la cadena validada, y se asigna usando strcmp. * */ const char* pedirDatoCadenaValidado(char[], int); /** \brief Pide una cadena de slo nmeros. * * \param Qu se va a ingresar, por ejemplo, "Nombre". * \param El largo deseado de la cadena. * \return Devuelve la cadena validada, y se asigna usando strcmp. * */ ePersona borrarPersona(ePersona[], int); /** \brief Borra un elemento del array ePersona. * * \param Array de ePersona. * \param Tamao del array. * \return El elemento dado de baja. * */ void ordenarYMostrarPorNombre(ePersona[], int); /** \brief Ordena por nombre los elementos del array y muestra solo aquellos que estan cargados. * * \param Array de ePersona. * \param Tamao de dicho array. * \return No devuelve nada. * */ void grafico(ePersona[], int); /** \brief Grafico vertical que muestra las edades de los elementos cargados dl array de ePersona. * * \param Array de ePersona. * \param Tamao de dicho array. * \return No devuelve nada. * */ int buscarxDNI(ePersona[], int); /** \brief Busca en el array una coincidencia con el dni ingresado. * * \param Array de ePersona. * \param Tamao de dicho array. * \return Devuelve la posicion del array en la que se encontr dicha coincidencia. * */ int buscarLugar(ePersona[], int); /** \brief Busca un lugar disponible para la carga de datos del array. * * \param Array de ePersona * \param Tamao de dicho array. * \return Devuelve la primera posicion disponible para cargar. * */
C
#include <stdio.h> #include <math.h> long penta(long num){ long num2; num2 = (1+sqrt(1+24*num))/6; if((num2*(3*num2-1))/2 == num) return num2; return 0; } long hexa(long num){ long num2; num2 = (1+sqrt(1+8*num))/4; if(num2*(2*num2-1) == num) return num2; return 0; } int main(){ long tri = 40755, n = 285, p, h; while(1){ n++; tri += n; h = hexa(tri); if(h){ p = penta(tri); if(p){ printf("T(%ld) = P(%ld) = H(%ld) = %ld\n", n, p, h, tri); return 0; } } } return 0; }
C
//60070501054 //60070501064 #include <mpi.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #define MatrixA "matAlarge.txt" #define MatrixB "matBlarge.txt" #define MatrixOut "matBlockOut.txt" float **malloc2d(int row, int col) { float *data = malloc(col * row * sizeof(float)); float **arr = malloc(row * row * sizeof(float)); int i; for (i = 0; i < row; i++) arr[i] = &(data[col * i]); return arr; } void writeToFile(float **InMatrix, char *path, int row, int col) { int i, j; FILE *fp = fopen(path, "w"); fprintf(fp, "%d %d\n", row, col); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { fprintf(fp, "%.1f ", InMatrix[i][j]); } fputs("\n", fp); } fclose(fp); } void readToMatrix(float **matrix, char *path) { int i, j; int row, col; FILE *fp = fopen(path, "r"); fscanf(fp, "%d %d", &row, &col); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { fscanf(fp, "%f", &matrix[i][j]); } } fclose(fp); } void checkMatrixSize(char *path, int *row, int *col) { FILE *fp = fopen(path, "r"); fscanf(fp, "%d %d", row, col); fclose(fp); } float *plusMatrix(float *matrix1, float *matrix2, float blockSize) { float *result = (float *)malloc(blockSize * sizeof(float)); int i; for (i = 0; i < blockSize; i++) { result[i] = matrix1[i] + matrix2[i]; } return result; } float main(int argc, char *argv[]) { // mpi rank and size variable int p, id; int i; int row, col; MPI_Status status; MPI_Request req[2]; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &p); MPI_Comm_rank(MPI_COMM_WORLD, &id); double startTime, endTime; if (id == 0) { checkMatrixSize(MatrixA, &row, &col); // printf("Start MPI... Master Node \n"); float **matrix1 = malloc2d(row, col); float **matrix2 = malloc2d(row, col); float **result = malloc2d(row, col); // Load data from file to matrix printf("Reading from file\n"); readToMatrix(matrix1, MatrixA); readToMatrix(matrix2, MatrixB); printf("Complete reading\n"); int blockSize = (row * col) / (p); int SizeWithRemainder = blockSize + ((row * col) % blockSize); startTime = MPI_Wtime(); // send data to anathor node for (i = 1; i < p; i++) { //printf("Send to Node %d\n", i); int Size = i == p - 1 ? SizeWithRemainder : blockSize; MPI_Send(&Size, 1, MPI_INT, i, 0, MPI_COMM_WORLD); MPI_Send(&matrix1[0][0] + blockSize * i, Size, MPI_FLOAT, i, 1, MPI_COMM_WORLD); MPI_Send(&matrix2[0][0] + blockSize * i, Size, MPI_FLOAT, i, 2, MPI_COMM_WORLD); } // calculate memcpy(&result[0][0], plusMatrix(&matrix1[0][0], &matrix2[0][0], blockSize), sizeof(float) * blockSize); for (i = 1; i < p; i++) { int Size = i == p - 1 ? SizeWithRemainder : blockSize; MPI_Recv(&result[0][0] + blockSize * i, Size, MPI_FLOAT, i, 0, MPI_COMM_WORLD, &status); } endTime = MPI_Wtime(); printf("End >> Time usage: %lf\n", endTime - startTime); printf("Waiting for write to file\n"); writeToFile(result, MatrixOut, row, col); } else { int Size = 0; //printf("start received Size\n"); MPI_Recv(&Size, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status); float *matrix1 = (float *)malloc(Size * sizeof(float)); float *matrix2 = (float *)malloc(Size * sizeof(float)); float *result = (float *)malloc(Size * sizeof(float)); //printf("start receive\n"); MPI_Recv(matrix1, Size, MPI_FLOAT, 0, 1, MPI_COMM_WORLD, &status); MPI_Recv(matrix2, Size, MPI_FLOAT, 0, 2, MPI_COMM_WORLD, &status); MPI_Send(plusMatrix(matrix1, matrix2, Size), Size, MPI_FLOAT, 0, 0, MPI_COMM_WORLD); //printf("complete send back\n"); } MPI_Finalize(); }