language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<stdio.h> int main() { int P,T; float R,simple_interest; printf("Enter the value of P,R,T: "); scanf("%d%d%f",&P,&T,&R); simple_interest = P*T*R/100; printf("The value of simple interest is %f ",simple_interest); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { float i =0.0,j=0.0; while(1){ if(scanf("%f %f",&i,&j) !=2) break; printf("MEDIA = %0.5f\n",((i*3.5)+(j*7.5))/11); } return 0; }
C
#include <unistd.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> int main() { if (chdir("/") < 0 && errno == ENXIO) exit(EXIT_SUCCESS); fprintf(stderr, "got errno=%m\n"); exit(EXIT_FAILURE); }
C
/***************************************************************************** |* |* Copyright: Copyright (c) 2009, Altium |* |* Description: pthread_attr_getname |* \*****************************************************************************/ #include <string.h> #include <pthread.h> #include <errno.h> #include "kernel.h" /** * @brief * gets the name attribute in the attr object * * The pthread_attr_getname() function gets the thread's name * attribute in the attr object. * The thread's name is set via pthread_attr_setname. * * @param attr * pointer to the thread's attribute object * @param name * Address of a character buffer to receive the name. (Must have a size of * atleast POSIX_THREAD_THREAD_NAME_MAX.) * * @return * Upon successful completion it shall return a value of 0; otherwise, an error number * shall be returned to indicate the error. */ int pthread_attr_getname(const pthread_attr_t *attr, char *name) { #if (__POSIX_THREAD_ATTR_NAME != 0) int ret =0; if (attr == NULL || name == NULL) { return EINVAL; } posix_scheduler_lock(); if (attr->init != _ATTR_INIT_KEY) { ret = EINVAL; } else { strncpy(name, attr->name, POSIX_THREADS_THREAD_NAME_MAX); } posix_scheduler_unlock(); return ret; #else if (attr == NULL || name == NULL) { return EINVAL; } name[0] = '\0'; return ENOTSUP; #endif }
C
typedef struct io_interface_node{ io_interface current; struct io_interface_node *next; } io_interface_node; typedef struct { io_interface_node *head; io_interface_node *tail; } io_interface_queue; int enqueue(io_interface_queue *queue, io_interface_node *node) { if (queue->head == NULL) { queue->head = node; queue->tail = node; queue->head->next = NULL; } else { queue->tail->next = node; queue->tail = node; queue->tail->next = NULL; } return 0; } io_interface_node *dequeue(io_interface_queue *queue) { if (queue->head != NULL) { io_interface_node *to_ret = queue->head; queue->head = queue->head->next; return to_ret; } else { return NULL; } }
C
#include <stdio.h> char farm[10][10]; int main(void) { int i, j; int barn_x, barn_y, obstacle_x, obstacle_y, water_x, water_y; int pig_number=0; for (i=0; i<10; i++){ for (j=0; j<10; j++){ farm[i][j]='.'; } } printf("Enter the X and Y values of the barn(B):\n"); scanf("%d%d",&i,&j); farm[i-1][j-1]='B'; barn_x=j-1; barn_y=i-1; printf("Enter the X and Y values of the obstacle(R):\n"); scanf("%d%d",&i,&j); farm[i-1][j-1]='R'; obstacle_x=j-1; obstacle_y=i-1; printf("Enter the X and Y values of the water(L):\n"); scanf("%d%d",&i,&j); farm[i-1][j-1]='L'; water_x=j-1; water_y=i-1; /*--------------------------------------------*/ if (water_x > barn_x){ water_x--; while (water_x > barn_x){ if (farm[water_x][water_y] == 'R'){ water_x++; if (water_y > barn_y ){ while(water_y> barn_y){ water_y--; pig_number++; farm[water_x][water_y] = 'P'; } pig_number--; } else if(water_y < barn_y){ while (water_y < barn_y){ water_y++; pig_number++; farm[water_x][water_y]='P'; } pig_number--; } else{ water_y--; pig_number++; farm[water_x][water_y]='P'; } } farm[water_x][water_y] = 'P'; pig_number++; water_x--; } if(water_y > barn_y){ water_x++; while (water_y > barn_y){ water_y--; pig_number++; farm[water_x][water_y]='P'; } } } /*--------------------------------------------*/ else if (water_x < barn_x){ water_x++; while (water_x < barn_x){ if (farm[water_x][water_y]=='R'){ water_x--; if (water_y > barn_y){ while(water_y > barn_y){ water_y--; pig_number++; farm[water_x][water_y]='P'; } pig_number--; } else if(water_y < barn_y){ while (water_y < barn_y){ water_y++; pig_number++; farm[water_x][water_y]='P'; } pig_number--; } else { water_y--; pig_number++; farm[water_x][water_y]='P'; } } farm[water_x][water_y] = 'P'; pig_number++; water_x++; } if (water_y > barn_y){ water_x++; while (water_y > barn_y){ water_y--; pig_number++; farm[water_x][water_y] = 'P'; } } else if (water_y < barn_y){ water_x++; while (water_y < barn_y){ water_y++; pig_number++; farm[water_x][water_y] = 'P'; } } } /*---------------------------------------------*/ else if (water_x==barn_x){ if (water_y > barn_y){ water_y--; while(water_y > barn_y){ if(farm[water_x][water_y] == 'R'){ water_x--; water_y++; if(water_y > barn_y){ while(water_y >= barn_y){ pig_number++; farm[water_x][water_y] = 'P'; water_y--; } } } else{ pig_number++; farm[water_x][water_y] = 'P'; water_y--; } } } if(water_y < barn_y){ water_y++; while(water_y < barn_y){ if(farm[water_x][water_y] == 'R'){ water_x--; water_y--; if(water_y < barn_y){ while(water_y <= barn_y){ pig_number++; farm[water_x][water_y] = 'P'; water_y++; } } } else { pig_number++; farm[water_x][water_y] = 'P'; water_y++; } } } } printf("\n \n"); for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { printf("%C", farm[i][j]); if (j == 9) printf("\n"); } } printf("\n \n Number of pigs %d", pig_number); return 0; }
C
/* * Implementation of the word_count interface using Pintos lists. * * You may modify this file, and are expected to modify it. */ /* * Copyright © 2019 University of California, Berkeley * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PINTOS_LIST #error "PINTOS_LIST must be #define'd when compiling word_count_l.c" #endif #include "word_count.h" void init_words(word_count_list_t *wclist) { list_init(wclist); } size_t len_words(word_count_list_t *wclist) { return list_size(wclist); } word_count_t *find_word(word_count_list_t *wclist, char *word) { /* TODO */ word_count_t *word_count; if(list_empty(wclist)){ word_count = NULL; } else{ word_count = list_entry(list_front(wclist),word_count_t,elem); while (!strcmp(word_count->word,word)){ /* Reach last elem of list */ if(word_count->elem.next == NULL){ word_count = NULL; break; } word_count = list_entry(list_next(&word_count->elem),word_count_t,elem); } } return word_count; } word_count_t *add_word(word_count_list_t *wclist, char *word) { /* TODO */ word_count_t *word_count; word_count = find_word(wclist,word); if(word_count == NULL){ word_count = (word_count_t *) malloc(sizeof(word_count_t)); word_count->count = 1; strcpy(word_count->word,word); list_insert(list_tail(wclist),&word_count->elem); } else{ word_count->count++; } return NULL; } void fprint_words(word_count_list_t *wclist, FILE *outfile) { /* TODO */ word_count_t *word_count; if(wclist!=NULL){ word_count = list_entry(list_begin(wclist),word_count_t,elem); for(word_count = list_entry(list_begin(wclist),word_count_t,elem);list_next(&word_count->elem)!=NULL;\ word_count = list_entry(list_next(&word_count->elem),word_count_t,elem)){ fprintf(outfile,"%i\t%s\n",word_count->count,word_count->word); } } } static bool less_list(const struct list_elem *ewc1, const struct list_elem *ewc2, void *aux) { /* TODO */ word_count_t *wc1,*wc2; wc1 = list_entry(list_next(ewc1),word_count_t,elem); wc2 = list_entry(list_next(ewc2),word_count_t,elem); if((wc1->count<wc2->count) || ((wc1->count==wc2->count) && (strcmp(wc1->word,wc2->word)<0))){ return true; } return false; } void wordcount_sort(word_count_list_t *wclist, bool less(const word_count_t *, const word_count_t *)) { list_sort(wclist, less_list, less); }
C
/* * 使用TLS,测试多线程效率 * gcc -g 4_pthread_key.c -pthread -openmp 测试并行模式下程序的执行时间 */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <omp.h> #include <sys/time.h> pthread_key_t key; #define THREAD_NUM 50 void *thread() { long i = 0; pthread_setspecific(key, &i); struct timeval start, end; float time_cost; long * count = (long *)pthread_getspecific(key); gettimeofday(&start, NULL); for ( i; i < 100000000; i++ ) (*count)++; gettimeofday(&end, NULL); time_cost = 1000000 * (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec); time_cost /= 1000000; printf("%u: *count = %ld, i = %ld, time_cost = %f\n", pthread_self(), *count, i, time_cost); } int main() { pthread_t tid[THREAD_NUM]; int i; pthread_key_create(&key, NULL); #pragma omp parallel for for ( i = 0; i < THREAD_NUM; i++ ) pthread_create(&tid[i], NULL, thread, NULL); #pragma omp parallel for for ( i = 0; i < THREAD_NUM; i++ ) pthread_join(tid[i], NULL); pthread_key_delete(key); return 0; }
C
#include<stdio.h> void f(char* c, char d){ *c = *c + 1; d = d + 1; printf("%d %d",c,d); } int main(){ char a = 'A', b = 'a'; f(&b, a); printf("%d %d", a, b); system("pause"); return 0; }
C
/* * * getint.c * * Ramiro Jordan * ECE 231 - Spring 2012 * Date: January 16, 2012 * */ /* Does what ?????? */ /* driver program */ #include <stdio.h> #define STOP -1 #define NONUM 1 #define YESNUM 0 void main() { int num, status; (void) printf ("\nThis program stops reading numbers if EOF is read.\n"); while ( (status = getint(&num) ) != STOP ) { if ( status == YESNUM ) { (void) printf ("The number %d has been accepted.\n", num); } else { (void) printf ("That was no integer! Try again.\n"); } } (void) printf ("\n\t>>> That is it!!! <<<\n\n"); } /* function getint() */ #include <stdio.h> #define LENGTH 81 #define STOP -1 #define NONUM 1 #define YESNUM 0 int getint (ptint) int *ptint; { char intarr[LENGTH]; int ch, ind, status; ind = 0; while (( ch = getchar() ) == '\n' || ch == ' ' || ch == '\t' ); while ( ch != EOF && ch != '\n' && ch != ' ' && ind < LENGTH ) { intarr[ind++] = ch; ch = getchar(); } intarr[ind] = '\0'; if ( ch == EOF ) { return (STOP); } else { status = stoi1 (intarr, ptint); return ( status ); } } /* function stoi1() */ #define NONUM 1 #define YESNUM 0 int stoi1 (string, intptr) char string[]; int *intptr; { int sign = 1; int index = 0; if ( string[index] == '-' || string[index] == '+') { sign = (string[index++] == '-') ? -1: 1; } *intptr = 0; while ( string[index] >= '0' && string[index] <= '9') { *intptr = 10 * (*intptr) + string[index++] - '0'; } if ( string[index] == '\0') { *intptr = sign * (*intptr); return (YESNUM); } else { return (NONUM); } }
C
/* check50 2015.fall.pset1.water water.c */ #include <stdio.h> #include <cs50.h> int main(void) { int n = 0; int btls = 0; printf("\nWater!\n\n"); printf("minutes: "); n = GetInt(); btls = 192/16 * n; printf("bottle: %i\n", btls); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "numberOfLinesLib.h" int numberOfLines(const int LINESIZE, const char *FNANAME) { FILE *fnaPointer; char singleCharLine[256]; fnaPointer = fopen(FNANAME, "r"); if(fnaPointer == NULL) { printf("%s", "Error: fnaPointer is null\n"); exit(EXIT_FAILURE); } int numberOfLines = 0; while (fgets(singleCharLine, 256, fnaPointer) != NULL) { numberOfLines++; } if(numberOfLines == 0) { printf("%s", "Error: No Lines in .fna file\n"); exit(EXIT_FAILURE); } fclose(fnaPointer); return numberOfLines; }
C
#include <stdio.h> #include <string.h> #include "redis_hash_commands.h" #include "redis_connect.h" #include "redis_io.h" int main() { return_code status; if((status = redis_connect("127.0.0.1", "6379")) == SUCCESS) printf("Connected.\n"); else { printf("Connection failed.\n"); return 1; } int response = -1; const char *key = "mykey"; const char *field1 = "myfield1"; const char *field2 = "myfield2"; const char *field3 = "myfield3"; const char *value1 = "my test value 1"; const char *value2 = "my test value 2"; const char *value3 = "my test value 3"; if(redis_hset(&response, key, field1, value1) == SUCCESS) printf("%s.%s=%s\n", key, field1, value1); if(redis_hset(&response, key, field2, value2) == SUCCESS) printf("%s.%s=%s\n", key, field2, value2); if(redis_hset(&response, key, field3, value3) == SUCCESS) printf("%s.%s=%s\n", key, field3, value3); if(redis_hdel(&response, key, 1, field1) == SUCCESS) printf("%d fields deleted\n", response); if(redis_hdel(&response, key, 2, field2, field3) == SUCCESS) printf("%d fields deleted\n", response); return 0; }
C
#pragma once #ifdef _MSC_VER #if (_MSC_VER <= MSVC_2003 ) #ifndef _ERRNO_T_DEFINED #define _ERRNO_T_DEFINED typedef int errno_t; #endif inline int_x memcpy_s(void * pDst, int_x iSize, const void * pSrc, int_x iCount) { iSize = Min(iSize, iCount); memcpy(pDst, pSrc, iSize); return iSize; } inline int_x memmove_s(void * pDst, int_x iSize, const void * pSrc, int_x iCount) { iSize = Min(iSize, iCount); memmove(pDst, pSrc, iSize); return iSize; } inline int_x _wsopen_s(int * pfh, const wchar_t * szFile, int oflag, int shflag, int pmode) { if(pfh) { *pfh = _wsopen(szFile, oflag, shflag, pmode); return errno; } else return EIO; } inline errno_t mbstowcs_s(size_t * _PtNumOfCharConverted, wchar_t * _DstBuf, size_t _SizeInWords, const char * _SrcBuf, size_t _MaxCount) { size_t size = mbstowcs(_DstBuf, _SrcBuf, _MaxCount); if(_PtNumOfCharConverted) *_PtNumOfCharConverted = size; return errno; } inline errno_t wcstombs_s(size_t * _PtNumOfCharConverted, char * _DstBuf, size_t _SizeInWords, const wchar_t * _SrcBuf, size_t _MaxCount) { size_t size = wcstombs(_DstBuf, _SrcBuf, _MaxCount); if(_PtNumOfCharConverted) *_PtNumOfCharConverted = size; return errno; } inline int vsprintf_s(char * _DstBuf, int_x _SizeInBytes, const char * _Format, char * _ArgList) { return vsprintf(_DstBuf, _Format, _ArgList); } inline int vswprintf_s(wchar_t * _DstBuf, int_x _SizeInBytes, const wchar_t * _Format, char * _ArgList) { return vswprintf(_DstBuf, _Format, _ArgList); } inline int_x _localtime64_s(struct tm * _Tm, const int_64 *_Time) { *_Tm = *_localtime64(_Time); return errno; } #endif #endif
C
#include<stdio.h> #include<math.h> double PI=3.1415926; double eps=1e-9; double x, y,l,d; double cal(double i) { return -(x-l*sin(i)-d/cos(i))/tan(i); } int fun() { double i, left=0, right=PI/2, lmid, rmid; while(fabs(right-left)<eps){ lmid=(2.0*left+right)/3; rmid=(left+2.0*right)/3; if(cal(lmid)<cal(rmid)) right=rmid; else left=lmid; } if(fabs(cal(right))<=y) return 1; else return 0; } int main() { while(scanf("%lf%lf%lf%lf",&x,&y,&l,&d)!=EOF){ printf("%s\n",fun()?"yes":"no"); } return 0; }
C
#include "blockchain/transaction.h" void write_transactiondata(TransactionData *transaction, int fd) { write(fd, &transaction->magic, sizeof(char)); write(fd, &transaction->type, sizeof(char)); BIO *pubkey = BIO_new(BIO_s_mem()); PEM_write_bio_RSAPublicKey(pubkey, transaction->sender_public_key); int rsa_size = BIO_pending(pubkey); write(fd, &rsa_size, sizeof(int)); char temp[1000]; BIO_read(pubkey, temp, rsa_size); write(fd, temp, rsa_size); BIO_free(pubkey); BIO *pubkey2 = BIO_new(BIO_s_mem()); PEM_write_bio_RSAPublicKey(pubkey2, transaction->receiver_public_key); rsa_size = BIO_pending(pubkey2); write(fd, &rsa_size, sizeof(int)); BIO_read(pubkey2, temp, rsa_size); write(fd, temp, rsa_size); BIO_free(pubkey2); write(fd, &transaction->amount, sizeof(size_t)); write(fd, &transaction->receiver_remaining_money, sizeof(size_t)); write(fd, &transaction->sender_remaining_money, sizeof(size_t)); write(fd, &transaction->transaction_timestamp, sizeof(time_t)); write(fd, transaction->cause, 512); write(fd, transaction->asset, 512); } void write_transaction(Transaction *transaction, int fd) { write_transactiondata(&transaction->transaction_data, fd); write(fd, transaction->transaction_signature, 256); } void get_transaction_data(Transaction *trans, char **buff, size_t *index) { *buff = realloc(*buff, *index + TRANSACTION_DATA_SIZE + 3000); memcpy(*buff + *index, &trans->transaction_data.magic, sizeof(char)); *index += sizeof(char); memcpy(*buff + *index, &trans->transaction_data.type, sizeof(char)); *index += sizeof(char); BIO *pubkey = BIO_new(BIO_s_mem()); PEM_write_bio_RSAPublicKey(pubkey, trans->transaction_data.sender_public_key); int rsa_size = BIO_pending(pubkey); memcpy(*buff + *index, &rsa_size, sizeof(int)); *index += sizeof(int); char temp[1000]; BIO_read(pubkey, temp, rsa_size); memcpy(*buff + *index, temp, rsa_size); *index += rsa_size; BIO *pubkey2 = BIO_new(BIO_s_mem()); PEM_write_bio_RSAPublicKey(pubkey2, trans->transaction_data.receiver_public_key); rsa_size = BIO_pending(pubkey2); memcpy(*buff + *index, &rsa_size, sizeof(int)); *index += sizeof(int); BIO_read(pubkey2, temp, rsa_size); memcpy(*buff + *index, temp, rsa_size); *index += rsa_size; BIO_free(pubkey); BIO_free(pubkey2); memcpy(*buff + *index, &trans->transaction_data.amount, sizeof(size_t)); *index += sizeof(size_t); memcpy(*buff + *index, &trans->transaction_data.receiver_remaining_money, sizeof(size_t)); *index += sizeof(size_t); memcpy(*buff + *index, &trans->transaction_data.sender_remaining_money, sizeof(size_t)); *index += sizeof(size_t); memcpy(*buff + *index, &trans->transaction_data.transaction_timestamp, sizeof(time_t)); *index += sizeof(time_t); memcpy(*buff + *index, trans->transaction_data.cause, 512); *index += 512; memcpy(*buff + *index, trans->transaction_data.asset, 512); *index += 512; } void convert_data_to_transactiondata(TransactionData *transactiondata, int fd) { read(fd, &transactiondata->magic, sizeof(char)); read(fd, &transactiondata->type, sizeof(char)); int RSAsize; read(fd, &RSAsize, sizeof(int)); char temp[1000]; read(fd, temp, RSAsize); BIO *pubkey = BIO_new(BIO_s_mem()); BIO_write(pubkey, temp, RSAsize); transactiondata->sender_public_key = PEM_read_bio_RSAPublicKey(pubkey, NULL, 0, NULL); BIO_free(pubkey); read(fd, &RSAsize, sizeof(int)); read(fd, temp, RSAsize); BIO *pubkey1 = BIO_new(BIO_s_mem()); BIO_write(pubkey1, temp, RSAsize); transactiondata->receiver_public_key = PEM_read_bio_RSAPublicKey(pubkey1, NULL, 0, NULL); BIO_free(pubkey1); read(fd, &transactiondata->amount, sizeof(size_t)); read(fd, &transactiondata->receiver_remaining_money, sizeof(size_t)); read(fd, &transactiondata->sender_remaining_money, sizeof(size_t)); read(fd, &transactiondata->transaction_timestamp, sizeof(time_t)); read(fd, transactiondata->cause, 512); read(fd, transactiondata->asset, 512); } void load_transaction(Transaction *transaction, int fd) { if (transaction == NULL) { errx(EXIT_FAILURE, "Load_transaction: transction is not malloc"); } convert_data_to_transactiondata(&transaction->transaction_data, fd); read(fd, transaction->transaction_signature, 256); } Transaction* load_pending_transaction(time_t timestamp) { char name[30] = {0}; sprintf(name, "data/pdt/%ld", timestamp); int transaction_file = open(name, O_RDONLY); if (transaction_file == -1) return NULL; Transaction *transaction = malloc(sizeof(Transaction)); load_transaction(transaction, transaction_file); close(transaction_file); return transaction; } void add_pending_transaction(Transaction *transaction) { char name[300] = {0}; struct stat st; if (stat("data/pdt", &st) == -1) { mkdir("data/pdt", 0700); } sprintf(name, "data/pdt/%ld", transaction->transaction_data.transaction_timestamp); int pending_transaction_fd = open(name, O_CREAT | O_WRONLY, 0644); write_transaction(transaction,pending_transaction_fd); close(pending_transaction_fd); } Transaction create_new_transaction(infos_st *infos, char type, RSA* receiver_public_key, size_t amount, char cause[512], char asset[512]){ Wallet *wallet = get_my_wallet(); Transaction new_trans; TransactionData *data = &new_trans.transaction_data; data->magic = 1; data->type = type; switch (type) { case T_TYPE_DEFAULT: { data->sender_public_key = wallet->pub_key; data->receiver_public_key = receiver_public_key; data->amount = amount; data->sender_remaining_money = wallet->amount - amount; data->receiver_remaining_money = get_receiver_remaining_money(infos, receiver_public_key) + amount; break; } case T_TYPE_WITHDRAW_STAKE: { data->sender_public_key = NULL; data->receiver_public_key = wallet->pub_key; data->amount = amount; data->sender_remaining_money = wallet->stake_amount - amount; data->receiver_remaining_money = wallet->amount + amount; break; } case T_TYPE_ADD_STAKE: { data->sender_public_key = wallet->pub_key; data->receiver_public_key = NULL; data->amount = amount; data->sender_remaining_money = wallet->amount - amount; data->receiver_remaining_money = wallet->stake_amount + amount; break; } default: break; } data->transaction_timestamp = time(NULL); memcpy(data->cause, cause, 512); memcpy(data->asset, asset, 512); return new_trans; } void flush_pending_transactions(Transaction **transactions, size_t nb_transactions) { for (size_t i = 0; i < nb_transactions; i++) { Transaction* trans = transactions[i]; if (trans->transaction_data.type != T_TYPE_REWARD_STAKE && trans->transaction_data.type != T_TYPE_PUNISH_STAKE) { char temp[200]; snprintf(temp, 200, "%li", trans->transaction_data.transaction_timestamp); remove(temp); } } }
C
#ifndef TERMCOLOR_H #define TERMCOLOR_H #include <stddef.h> typedef struct { unsigned char r; unsigned char g; unsigned char b; } termcolor; /* sets the terminal based on name, if name is NULL then the name is taken from the TERM environment variable. */ extern void termcolor_setup (const char * term); /* returns the n'th color from the terminal. */ extern termcolor termcolor_get (size_t n); /* returns the number of colors termcolor thinks is available for the currently set terminal. */ extern size_t termcolor_max_colors; #endif /* TERMCOLOR_H */
C
#include<stdio.h> void quicksort(int numar[20], int primul, int ultimul) { int i, j, pivot, aux; if (primul < ultimul) { pivot = primul; i = primul; j = ultimul; while (i < j) { while (numar[i] <= numar[pivot] && i < ultimul) i++; while (numar[j] > numar[pivot]) j--; if (i < j) { aux = numar[i]; numar[i] = numar[j]; numar[j] = aux; } } aux = numar[pivot]; numar[pivot] = numar[j]; numar[j] = aux; quicksort(numar, primul, j - 1); quicksort(numar, j + 1, ultimul); } } int main() { int i, n, numar[20]; printf("Introduceti numarul de elemente: "); scanf("%d", &n); for (i = 0; i < n; i++) { printf("numar[%d]= ", i); scanf("%d", &numar[i]); } quicksort(numar, 0, n - 1); printf("Sortare: "); for (i = 0; i < n; i++) printf(" %d ", numar[i]); system("pause"); return 0; }
C
// Lab de teste e configuracao do estimador de atitude do Drone #include "mbed.h" #include "crazyflie.h" #include "USBSerial.h" //Define serial object USBSerial serial; //Define serial command variable char command; //Define attitude estimator object AttitudeEstimador estimador; //Define Ticker object Ticker tic; //Define interrupt flag bool flag; //Define callback functions void callback() { flag=true; } //Main program int main() { //esperando alguns segundos para inicializar wait(2); //Inicia o objeto do estimador estimador.init(); //Inicia o objeto de interrupcao tic.attach(&callback, dt); while(true) { //Estimate attitude if(flag) { flag=false; estimador.estimate(); } //Print attitude if (serial.readable()) { command=serial.getc(); if(command=='p') { serial.printf("%f,%f,%f\n", estimador.phi, estimador.theta, estimador.psi); } } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> //Inicio da declaração das structs typedef struct data{ double turnaroundTime; double averageServiceTime; double CpuUsage; double averageResponseTime; double throughput; double averageWaitingTime; }Data; typedef struct process{ int pid; int submissionTime; int priority; int executionTime; int blockTime; int timeToBlock; }Process; typedef struct PCB{ Process *process; struct PCB *next; int activeTime; int totalTime; int blockedTime; int responseTime; int waitingTime; int creationTime; int finishTime; int _1priority; int fila; }PCB; typedef struct circular{ PCB *head; PCB *tail; }Circular; //Fim da declaração das structs //Inicio da declaração das variáveis globais int globalTime; //Fim da declaração das variáveis globais //Inicio da declaração de funcões //Controle.c void CheckNew(Circular *,Circular *,int *,int *,int ,int *); void CheckReady(Circular *,Circular *,int *,int *); int Clock(Circular **,Circular *,Circular *,Circular *,Circular *,PCB *,int *,int *,int *,int ); void IncrementBlockedTime(Circular *); void IncrementeTotalTime(Circular *); void IncrementWaitingTime(Circular *); //Data.c void dividir(Data *,float ); void measure(Circular *,int ,int ,Data *); void PrintData(Data *); void SaveData(Data *,int ,int ); void somar(Data *,Data *); void zerar(Data *); //Filas.c void FreeCircular(Circular *); void insertCircular(Circular *,PCB *); void PrintCircular(Circular *); void removeCircular(Circular *,PCB *); //HRRN.c PCB *GetHighestRatio(Circular *); Circular *HRRN(int , int ,PCB **); //Loterry.c PCB *Bet(Circular *,int ); Circular *Loterry(int , int ,PCB **); int UpdateTotalOdds(Circular *); //1-Loterry.c PCB *_1Bet(Circular *,int ); Circular *_1Loterry(int , int ,PCB **); int _1UpdateTotalOdds(Circular *,int ); int distance(Process *, Process *); //Multilevel_Feedback.c void CheckReadyMultilevel(Circular *,Circular **,int *,int *); Circular *MultiLevelFeedback(int , int ,PCB **, int ); //Processos.c PCB **createPCBList(int ,char *); int comparadorSubmissionTime(const void **, const void **); void PrintInfo(Process *); Process **ReadProcesses(int ,char *); //Round-robins.c Circular *PriorityRoundRobin(int , int ,PCB **); Circular *RatioRoundRobin(int , int ,PCB **); Circular *RoundRobin(int ,int ,PCB **); //Fim da declaração de funcões
C
#include <stdio.h> void fun(void) { printf("fun() called from a static library"); } int add_number(int x, int y) { return x+y; }
C
#include <stdio.h> void shellsort(int v[], int n); void shellsort1(int v[], int n); void shellsort2(int v[], int n); void main() { int v[23] = {263,4,3,352,28,2,55,20,100,87,348,32,211,1,34,12,23,22,19,102,8,90,49}; int i; shellsort(v,23); for(i = 0; i < 23; ++i) printf("a[%d]=%d ",i, v[i]); printf("\n"); } void shellsort1(int v[], int n) { int i, j, gap; //最内层循环只对当前组进行希尔排序 for(gap = n/2; gap > 0; gap/=2) for(i = 0; i < gap; ++i) { for(j = i + gap; j < n; j += gap) { if(a[j] < a[j-gap]) { int temp = a[j]; int k = j - gap; while(k >= 0 && a[k] > temp) { a[k+gap] = a[k]; k -= gap; } a[k+gap] = a[k]; } } } } void shellsort2(int v[], int n) { int i, gap; //第二层循环时每组依次都在进行希尔排序 for(gap = n/2; gap > 0; gap /= 2) for(i = gap; i < n; j++) if(a[i] < a[i-gap]) { int temp = a[i]; int j = i - gap; while(j >= 0 && a[j] > temp) { a[j+gap] = a[j]; j -= gap; } a[j+gap] = temp; } } void shellsort(int v[], int n) { int gap, i, j, temp; for(gap = n/2; gap > 0; gap /= 2) { for(i = gap; i < n; i++ ) { for(j = i - gap; j >= 0 && (v[j] > v[j+gap]) ; j -= gap) { temp = v[j]; v[j] = v[j+gap]; v[j+gap] = temp; } } } }
C
//To Check The ith bit is set or not #include<stdio.h> int main() { int t,n,f,i,res; f=1; printf("enter the no. of testcases\n"); scanf("%d",&t); while(t--) { printf("\nenter the no. and its ith bit\n"); scanf("%d%d",&n,&i); f=f<<i; res=n&f; if(res==0) { printf("\nTRUE\n"); } else { printf("\nFALSE\n"); } } return 0; }
C
#ifndef NET_EXPERIMENT_H #define NET_EXPERIMENT_H /**************************************************************************** * a net experiment consist of these steps * 1. make sure the size of the net [n] * <after_net_size> * 2. make sure the topo of the net [epsilon] * <after_net_connect> * 3. make sure the capacity of each node [alpha] * <after_net_capacity> * 4. make sure the inital attack number [p] * 5. make sure the count of experiments [rep] * 6. run the below loop for [rep] times: * (1) attack the net * <after_attack> * (2) loop the net * <after each loop> * (3) if in this loop, there are nodes broken, then back to (2) * (4) this loop end * <after net steady> * 5. clear the experiment * * usage: * when using net_experiment * you should first add your operaton package into the experiment * then use the specified config file to run the experiment * *********************************************************************/ #include "model/net.h" #include "statistic/betweenness.h" typedef struct net_exp_package Net_Exp_Pak; typedef struct exp_state{ net_size_t n; double epsilon; double alpha; double p; int repeat; int steps; }Exp_State; typedef int (*net_exp_oper)(Net *net, BC *bc, Exp_State *state, Net_Exp_Pak *ctx); enum operation{ OPER_AFTER_SIZE = 0, OPER_AFTER_CONNECT, OPER_AFTER_CAPACITY, OPER_ATTACK, OPER_AFTER_ATTACK, OPER_AFTER_EACH_LOOP, OPER_AFTER_STEADY, OPER_DESTROY, OPER_COUNT }; #define NET_EXP_PACKAGE_N 7 struct net_exp_package{ /* net_exp_oper after_net_size; net_exp_oper after_net_connect; net_exp_oper after_net_capcity; net_exp_oper attack; net_exp_oper after_attack; net_exp_oper after_each_loop; //this will be called after the net went steady net_exp_oper after_net_steady; net_exp_oper destroy_package; */ net_exp_oper opers[OPER_COUNT]; void *ctx; }; typedef struct net_experiment Net_Exp; //create a simple net experiment Net_Exp *net_experiment_create(); /** * add operations to these net experiment */ int net_experiment_add_package(Net_Exp_Pak *pak, Net_Exp *net_exp); //run the experiment, according to the config file int net_experiment_run(const char *config_file, Net_Exp *net_exp); //destroy the net experiment void net_experiment_destroy(Net_Exp *net_exp); #endif
C
#include <stdio.h> #include <stdlib.h> #include <signal.h> void SIGhandler(int); /* SIGUSR1 handler */ void sig_handler(int); void SIGhandler(int sig) { printf("\nReceived a SIGUSR1. \n" ); exit(0); } void sig_handler(int sig) { printf("\nReceived a SIGUSR2. \n" ); exit(0); } int main(void) { long fact= -2; signal(SIGUSR1, SIGhandler); signal(SIGUSR2,sig_handler); if (fact < 0) raise(SIGUSR1); else raise(SIGUSR2); }
C
/* public class ListNode { public int val; public ListNode next; public ListNode(int val=0, ListNode next=null) { this.val = val; this.next = next; } } */ public class Solution { public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { ListNode head = new ListNode(0); ListNode list1 = l1; ListNode list2 = l2; ListNode current = head; int carry = 0; int sum = 0; int x; int y; while (list1 != null || list2 != null) { if (list1 != null) x = list1.val; else x = 0; if (list2 != null) y = list2.val; else y = 0; sum = carry + x + y; current.next = new ListNode(sum % 10); carry = sum/10; current = current.next; if (list1 != null) list1 = list1.next; if (list2 != null) list2 = list2.next; } if (carry > 0) { current.next = new ListNode(carry); } return head.next; } }
C
#include<stdio.h> #include<string.h> void main() { char plain_text[20],cipher1[20],cipher2[10][10]; int key1,key2,no_r,start,i,j,n; printf("\nenter the plain text"); scanf("%s",plain_text); printf("\nenter the key for caesar"); scanf("%d",&key1); for(i=0;i<strlen(plain_text);i++) cipher1[i] = plain_text[i]+key1; printf("\nplain text after the first encryption is : %s",cipher1); printf("\nnow passing the first encrpted text through the keyless transposition cipher"); printf("\nenter the no of columns"); scanf("%d",&key2); no_r= strlen(cipher1)/key2+1; start=0; for(i=0;i<no_r;i++) { for(j=0;j<key2;j++) { cipher2[i][j] = cipher1[start++]; } } printf("\nFinal encrypted message is :"); for(i=0;i<no_r;i++) { for(j=0;j<key2;j++) { printf(" %c ",cipher2[j][i]); } } }
C
#include <stdio.h> void main() { int a = 10; int *pa; // //ּ ڷ pa = &a; //͸=&; printf("a=%d\n", a); printf("*pa%d\n", *pa); //, ּҷ printf("&a=%p\n", &a); printf("&pa=%p\n", &pa);//ͺ pa ּ printf("&pa=%p\n", pa);//ͺ pa =a ּ printf("&*pa=%p\n", &*pa); //ͺ pa (*) ּ(&) }
C
#include <stdio.h> #include <conio.h> #define N 5 void main() { int arr[N]; int i,j,max=-9999,min=9999,sum=0; clrscr(); for(j=0;j<N;j++) { printf("Enter element %d in the array",j+1); scanf("%d",&arr[j]); } for(i=0;i<N;i++) { if(arr[i]>max) max=arr[i]; if(arr[i]<min) min=arr[i]; sum=sum+arr[i]; } printf("max=%d\nmin=%d\nsum=%d\n",max,min,sum); getch(); }
C
/* The malloc Function */ // The malloc() function allocates a specified number of contiguous bytes in memory. #include <stdio.h> #include <stdlib.h> // includes memory management functions. #include <locale.h> int main() { setlocale(LC_ALL, "Portuguese"); int *ptr; // malloc returns a pointer to the allocated memory. // Notice that sizeof was applied to *ptr instead of int, making the code // more robust should the *ptr declaration be changed to a different data // type later. ptr = malloc(10*sizeof(*ptr)); /* a block of 10 ints */ if (ptr != NULL) { *(ptr+2) = 50; /* assign 50 to third int */ } printf("3rd elem equals to %d\n", *(ptr + 2)); // The free() function is a memory management function that is called to // release memory. By freeing memory, you make more available for use // later in your program. free(ptr); if (ptr != NULL) { *(ptr+2) = 40; } printf("3rd elem equals to %d\n", *(ptr + 2)); return 0; }
C
#include<stdio.h> long triangleSum(long n) { int sum=(n*(n+1))/2; return sum; } long checkDivisors(long n) { long exponent=1, count=0, i; for(i=2; i<=n; i++, count=0) { if(n%i==0) { while(n%i==0) { n=n/i; count++; } } exponent=exponent*(count+1); } return exponent; } int main() { long reqCount=500, triNum=1, reqSum; while(1) { reqSum=triangleSum(triNum); if(checkDivisors(reqSum)<=reqCount) { triNum++; } else break; } printf("%ld", triangleSum(triNum)); }
C
// Michael Bamesberger // CS344 Program 4 // otp_dec connects to otp_dec_d, asks to decrypt cipher #include <stdio.h> #include <unistd.h> #include <netdb.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> void keyHandler(int sockfd, char fileName[]); void textHandler(int sockfd, char fileName[]); int main(int argc, char *argv[]) { FILE *text, *key; struct sockaddr_in serv_addr; struct hostent *server; int textCount, keyCount; int n, portno, sockfd; if(argc < 2){ printf("Usage: otp_dec key port\n"); exit(1); } text = fopen(argv[1], "r"); key = fopen(argv[2], "r"); fseek(text, 0, SEEK_END); fseek(key, 0, SEEK_END); textCount = ftell(text); keyCount = ftell(key); fclose(text); fclose(key); if(keyCount < textCount) { //Check key length printf("Error: key is too short\n"); exit(1); } sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd < 0) { perror( "Error: error opening socket\n" ); exit(1); } portno = atoi(argv[3]); server = gethostbyname("localhost"); bzero((char *) &serv_addr, sizeof(serv_addr)); //Initialize server serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)); // connect to server char buffer[2]; bzero(buffer, 2); n = recv(sockfd,buffer,2,0); if(buffer[0] == 'd') { textHandler(sockfd, argv[1]); //Send text char confirmation[2]; bzero(confirmation, 2); n = recv(sockfd,confirmation,2,0); if(confirmation[0] == '1') { //If confirmation received send key keyHandler(sockfd, argv[2]); } char cipherMessage[textCount]; bzero(cipherMessage, textCount); int m = recv(sockfd,cipherMessage,textCount - 1,0); sprintf(cipherMessage, "%s\0", cipherMessage); printf("%s", cipherMessage); printf("\n"); } else { printf("Couldn't connect to otp_dec_d\n"); exit(2); } close(sockfd); return 0; } void textHandler(int sockfd, char fileName[]) { char buffer[10]; FILE *fs = fopen(fileName, "r"); bzero(buffer, 10); int fsSize, bytes; while((fsSize = fread(buffer, sizeof(char), 10, fs)) > 0) { if((bytes = send(sockfd, buffer, fsSize, 0)) < 0) { break; } bzero(buffer, 10); } if(bytes == 10) { send(sockfd, "0", 1, 0); // end server's transmission } fclose(fs); return; } void keyHandler(int sockfd, char fileName[]) { char buffer[10]; FILE *fs = fopen(fileName, "r"); bzero(buffer, 10); int fsSize, bytes; while((fsSize = fread(buffer, sizeof(char), 10, fs)) > 0) { if((bytes = send(sockfd, buffer, fsSize, 0)) < 0) { break; } bzero(buffer, 10); } if(bytes == 10) { send(sockfd, "0", 1, 0); } fclose(fs); return; }
C
#include <stdio.h> int main() { int n; float i=2, har=1; printf("Ingrese un numero: "); scanf("%d", &n); while(i<=n){ har=har + 1/i; ++i; } printf("El %dth numero armonico es: %.3f\n", n, har); return 0; }
C
#include <stdio.h> int main(void) { FILE *fp; fp = fopen("test.txt", "w"); fprintf(fp, "This string is written by the program."); fclose(fp); return 0; }
C
#include <minix/syslib.h> #include <minix/drivers.h> #include <minix/sysutil.h> #include "SerialPortClass.h" #define SP_DEBUG 0 struct serial_port_class { unsigned short baseAddr; char lcr; char lsr; char ier; char iir; bool transmitter; }; /////////////////////////////// PUBLIC /////////////////////////////////////// //============================= LIFECYCLE ==================================== SerialPortClass* newSerialPort() { SerialPortClass* SerialPort; SerialPort = (SerialPortClass*) malloc(sizeof(SerialPortClass)); return SerialPort; } void deleteSerialPort(SerialPortClass* SerialPort) { free(SerialPort); } bool SerialPortInitialize(SerialPortClass* SerialPort, unsigned short baseAddr, bool transmitter) { // Disable all interrupts SerialPortSetFlag(SerialPort, SP_REG_IER, SP_IER_RDI | SP_IER_TEI | SP_IER_LSI | SP_IER_MSI, false); // Check for errors char lsr; SerialPortReadReg(SerialPort, SP_REG_LSR, &lsr); if(SerialPortErrorDetection(lsr) != sp_none_error) return false; // Enable fifo SerialPortSetFlag(SerialPort, SP_REG_FCR, SP_FCR_EB | SP_FCR_CLEAR1 | SP_FCR_CLEAR2, true); SerialPort->baseAddr = baseAddr; SerialPort->transmitter = transmitter; return true; } void SerialPortShutdown(SerialPortClass* SerialPort) { // Disable fifo SerialPortSetFlag(SerialPort, SP_REG_FCR, SP_FCR_EB | SP_FCR_CLEAR1 | SP_FCR_CLEAR2, false); } //============================= OPERATIONS =================================== void SerialPortHandleInt(SerialPortClass* SerialPort, char data) { // Read IIR char iir; SerialPortReadReg(SerialPort, SP_REG_IIR, &iir); if(!(iir & SP_IIR_INTP_) && (iir & SP_IIR_THRE)) SerialPortTransmitByte(SerialPort, data); } bool SerialPortHandleFifo(SerialPortClass* SerialPort, char* data, unsigned long delay) { // Read LSR char lsr; SerialPortReadReg(SerialPort, SP_REG_LSR, &lsr); unsigned long i = 0; while(lsr & SP_LSR_THRE) { if(lsr & SP_LSR_FIFOE) { printf("\n\t FIFO Error \n"); return false; } SerialPortWriteReg(SerialPort, SP_REG_THR, data[i]); if(data[i] == '\0') return true; i++; SerialPortReadReg(SerialPort, SP_REG_LSR, &lsr); } return false; } void SerialPortTransmitData(SerialPortClass* SerialPort, char* data) { // If Divisor Latch Access bit is set to 1, then we need to set it to 0 SerialPortSetFlag(SerialPort, SP_REG_LCR, SP_LCR_DLAB, false); unsigned long i; for(i = 0; ; i++) { SerialPortTransmitByte(SerialPort, data[i]); if(data[i] == '\0') break; } } char* SerialPortReceiveData(SerialPortClass* SerialPort) { char strings[256]; char* data; // If Divisor Latch Access bit is set to 1, then we need to set it to 0 SerialPortSetFlag(SerialPort, SP_REG_LCR, SP_LCR_DLAB, false); if(SP_DEBUG) printf("\n\t Receiving data \n"); unsigned long i; char c; for(i = 0; ; i++) { if(!SerialPortReceiveByte(SerialPort, &c)) return 0; if(c == '\0') break; strings[i] = c; } strings[i] = '\0'; // Allocating memory for data data = (char*) malloc(sizeof(char) * i); strncpy(data, strings, i); return data; } void SerialPortShowConfig(SerialPortClass* SerialPort) { SerialPortLCRShow(SerialPort); SerialPortIERShow(SerialPort); } //============================= ACCESS =================================== unsigned short SerialPortGetBaseAddr(SerialPortClass* SerialPort) { return SerialPort->baseAddr; } /////////////////////////////// PRIVATE ////////////////////////////////////// //============================= OPERATIONS =================================== void SerialPortTransmitByteInt(SerialPortClass* SerialPort, char byte) { SerialPortWriteReg(SerialPort, SP_REG_THR, byte); } void SerialPortTransmitByte(SerialPortClass* SerialPort, char byte) { // Read Line Status Register char lsr; SerialPortReadReg(SerialPort, SP_REG_LSR, &lsr); SerialPort->lsr = lsr; // Waiting for transmitter ready while(!(lsr & SP_LSR_THRE)) { tickdelay(micros_to_ticks(SP_DELAY_US)); // Read LSR SerialPortReadReg(SerialPort, SP_REG_LSR, &lsr); } // Send byte SerialPortWriteReg(SerialPort, SP_REG_THR, byte); } bool SerialPortReceiveByte(SerialPortClass* SerialPort, char* byte) { // Setting RDI, TEI, LSI and MSI to 0 SerialPortSetFlag(SerialPort, SP_REG_IER, 0x0F, false); // Read Line Status Register char lsr; SerialPortReadReg(SerialPort, SP_REG_LSR, &lsr); // Error detection if(SerialPortErrorDetection(lsr) != sp_none_error) return false; // If Divisor Latch Access bit is set to 1, then we need to set it to 0 SerialPortSetFlag(SerialPort, SP_REG_LCR, SP_LCR_DLAB, false); // Waiting for Receiver Ready bit while(!(lsr & SP_LSR_RD)) { tickdelay(micros_to_ticks(SP_DELAY_US)); SerialPortReadReg(SerialPort, SP_REG_LSR, &lsr); } // Read character SerialPortReadReg(SerialPort, SP_REG_RBR, byte); return true; } bool SerialPortSetConfig(SerialPortClass* SerialPort, char bits, char stop, long parity, unsigned long rate) { char config = 0; if(!SerialPortSetBits(bits, &config)) return false; if(!SerialPortSetStop(stop, &config)) return false; SerialPortSetParity(parity, &config); // Writing LCR SerialPortWriteReg(SerialPort, SP_REG_LCR, config); // Setting rate SerialPortSetRate(SerialPort, rate); return 0; } inline bool SerialPortSetBits(char bits, char* byte) { if(bits < 5 || bits > 8) { printf("\n\t SerialPortClass.c :: SerialPortSetBits : bits out of range \n"); return false; } bits -= 5; *byte &= 0xFC; // bit 0 and 1 set to 0 *byte |= bits; return true; } inline bool SerialPortSetStop(char stop, char* byte) { if(stop != 1 || stop != 2) { printf("\n\t SerialPortClass.c :: SerialPortSetStop : stop out of range \n"); return false; } if(stop == 2) *byte |= SP_LCR_2STOP; return true; } inline void SerialPortSetParity(sp_parity parity, char* byte) { if(parity == sp_none_parity) return; *byte |= SP_LCR_NONE_; if(parity == sp_even_parity) *byte |= SP_LCR_EVEN; } void SerialPortSetRate(SerialPortClass* SerialPort, unsigned long rate) { // Calculating divisor unsigned long divisor; divisor = SP_BIT_RATE_NUM / rate; // Calculating LSB and MSB char lsb, msb; lsb = divisor & 0xFF; msb = (divisor >> 8) & 0xFF; // Setting DLAB to 1 SerialPortSetFlag(SerialPort, SP_REG_LCR, SP_LCR_DLAB, true); // Setting LSB SerialPortWriteReg(SerialPort, SP_REG_DLL, lsb); // Setting MSB SerialPortWriteReg(SerialPort, SP_REG_DLM, msb); // Setting DLAB to 0 SerialPortSetFlag(SerialPort, SP_REG_LCR, SP_LCR_DLAB, false); } void SerialPortLCRShow(SerialPortClass* SerialPort) { // Reading Line Control Register char reg_lcr; SerialPortReadReg(SerialPort, SP_REG_LCR, &reg_lcr); SerialPort->lcr = reg_lcr; // Calculating word-length char word_length; SerialPortLCRWordLength(SerialPort, &word_length); // Retrieving stop-bits unsigned long stop_bits; SerialPortLCRStopBits(SerialPort, &stop_bits); // Calculating bit-rate unsigned long bit_rate; SerialPortLCRBitRate(SerialPort, &bit_rate); // Calculating parity sp_parity parity; SerialPortLCRParity(SerialPort, &parity); // Retrieving set-break-enabled bool set_break_enabled; SerialPortLCRBreak(SerialPort, &set_break_enabled); // Retrieving DLAB bool dlab; SerialPortLCRDlab(SerialPort, &dlab); // Printing info printf("\n\t LCR Reg:\t\t\t0x%X", reg_lcr); // Printing word-length printf("\n\t Word Length:\t\t\t"); printf("%d", word_length); // Printing number of Stop Bits printf("\n\t No. Stop Bits:\t\t\t"); printf("%d", stop_bits); // Printing bit-rate printf("\n\t Bit Rate:\t\t\t"); printf("%d Hz", bit_rate); // Printing parity printf("\n\t Parity:\t\t\t"); if(parity == sp_none_parity) printf("None"); else if(parity == sp_even_parity) printf("Even"); else if(parity == sp_odd_parity) printf("Odd"); else printf("%d", parity); // Priting set-break-enabled printf("\n\t Set Break:\t\t\t"); if(set_break_enabled) printf("Enabled"); else printf("Disabled"); // Printing DLAB printf("\n\t DLAB:\t\t\t\t"); if(dlab) printf("Selects DL"); else printf("Selects Data"); printf("\n\n"); } inline void SerialPortLCRWordLength(SerialPortClass* SerialPort, char* wordLength) { *wordLength = (SerialPort->lcr & 0x3) + 5; } void SerialPortLCRBitRate(SerialPortClass* SerialPort, unsigned long* bitRate) { // Checking if DLAB is set and setting it if it is not if((SerialPort->lcr & SP_LCR_DLAB) == 0) { SerialPort->lcr |= SP_LCR_DLAB; SerialPortWriteReg(SerialPort, SP_REG_LCR, SerialPort->lcr); } // Read lsb and msb and calculating divisor char lsb; SerialPortReadReg(SerialPort, SP_REG_DLL, &lsb); char msb; SerialPortReadReg(SerialPort, SP_REG_DLM, &msb); unsigned long divisor; divisor = (msb << 8) | lsb; // Calculating bit-rate *bitRate = SP_BIT_RATE_NUM / divisor; // Resetting DLAB SerialPort->lcr &= ~SP_LCR_DLAB; SerialPortWriteReg(SerialPort, SP_REG_LCR, SerialPort->lcr); } inline void SerialPortLCRStopBits(SerialPortClass* SerialPort, unsigned long* stopBits) { if(SerialPort->lcr & SP_LCR_2STOP) *stopBits = 2; else *stopBits = 1; } inline void SerialPortLCRParity(SerialPortClass* SerialPort, sp_parity* parity) { if((SerialPort->lcr & SP_LCR_NONE_) == 0) { *parity = sp_none_parity; return; } if(SerialPort->lcr & SP_LCR_EVEN) *parity = sp_even_parity; else *parity = sp_odd_parity; } inline void SerialPortLCRBreak(SerialPortClass* SerialPort, bool* setBreakEnabled) { if(SerialPort->lcr & SP_LCR_BREAK) *setBreakEnabled = true; else *setBreakEnabled = false; } inline void SerialPortLCRDlab(SerialPortClass* SerialPort, bool* dlab) { if(SerialPort->lcr & SP_LCR_DLAB) *dlab = true; else *dlab = false; } void SerialPortIERShow(SerialPortClass* SerialPort) { // Reading IER Register char reg_ier; SerialPortReadReg(SerialPort, SP_REG_IER, &reg_ier); SerialPort->ier = reg_ier; // Retrieving data bool rdi, tei, lsi, msi; SerialPortIERRdi(SerialPort, &rdi); SerialPortIERTei(SerialPort, &tei); SerialPortIERLsi(SerialPort, &lsi); SerialPortIERMsi(SerialPort, &msi); // Printing data printf("\n\t IER Reg:\t\t\t0x%X", reg_ier); printf("\n\t Received Data Int:\t\t"); if(rdi) printf("Enabled"); else printf("Disabled"); printf("\n\t Transmitter Empty Int:\t\t"); if(tei) printf("Enabled"); else printf("Disabled"); printf("\n\t Receiver Line Status Int:\t"); if(lsi) printf("Enabled"); else printf("Disabled"); printf("\n\t Modem Status Int:\t\t"); if(msi) printf("Enabled"); else printf("Disabled"); printf("\n\n"); } inline void SerialPortIERRdi(SerialPortClass* SerialPort, bool* rdi) { if(SerialPort->ier & SP_IER_RDI) *rdi = true; else *rdi = false; } inline void SerialPortIERTei(SerialPortClass* SerialPort, bool* tei) { if(SerialPort->ier & SP_IER_TEI) *tei = true; else *tei = false; } inline void SerialPortIERLsi(SerialPortClass* SerialPort, bool* lsi) { if(SerialPort->ier & SP_IER_LSI) *lsi = true; else *lsi = false; } inline void SerialPortIERMsi(SerialPortClass* SerialPort, bool* msi) { if(SerialPort->ier & SP_IER_MSI) *msi = true; else *msi = false; } void SerialPortSetFlag(SerialPortClass* SerialPort, unsigned short spReg, char flag, bool enable) { char reg; SerialPortReadReg(SerialPort, spReg, &reg); if(enable) reg |= flag; else reg &= ~flag; SerialPortWriteReg(SerialPort, spReg, reg); } sp_error SerialPortErrorDetection(unsigned short reg_lsr) { sp_error error; if(reg_lsr & SP_LSR_OE) error = sp_overrun_error; else if(reg_lsr & SP_LSR_PE) error = sp_parity_error; else if(reg_lsr & SP_LSR_FE) error = sp_framing_error; else error = sp_none_error; if(error != sp_none_error) printf("\n\t SerialPortClass.c :: SerialPortErrorDetection : Error Detected: %d\n", error); return error; } static inline void SerialPortReadReg(SerialPortClass* SerialPort, unsigned short spReg, char* config) { char byte; unsigned short port = SerialPort->baseAddr + spReg; asm volatile ("inb %1, %0" : "=a" (byte) : "Nd" (port) ); *config = byte; } static inline void SerialPortWriteReg(SerialPortClass* SerialPort, unsigned short spReg, char config) { unsigned short port = SerialPort->baseAddr + spReg; asm volatile ("outb %0, %1" : : "a" (config), "Nd" (port) ); }
C
//#include "stm32f2xx.h" #include "ff.h" #include "fatfs_usr.h" FATFS FS; //ļϵͳṹ FIL fsr,fsw; //ļṹ //FILINFO fileinfo;//ļϢ //DIR dir; //Ŀ¼ FRESULT FAT_flag;//ļķ #if 0 /******************************************************************************* * : getfree * : -õʣ * : -drv :̱("0:"/"1:") * -total: * -free :ʣ * ֵ : 0,, *******************************************************************************/ u8 getfree(u8 *drv,u32 *total,u32 *free)//ȡд { FATFS *fs; u8 res; DWORD fre_clust=0, fre_sect=0, tot_sect=0; res = f_getfree((const TCHAR*)drv, &fre_clust, &fs);//"0:" or "" , ؽ, **FATFS if(res == FR_OK) { tot_sect = (fs->n_fatent - 2) * fs->csize;//=*ÿ fre_sect = fre_clust * fs->csize; //=д*ÿ *total=tot_sect>>1; //λΪKB *free=fre_sect>>1; //λΪKB printf("%lu KB total drive space.\n" "%lu KB available.\n", *total / 2,*free / 2);//ÿ512ֽڣ*0.5K = K } return res; } #endif
C
/* ************************************************************************** */ /* LE - / */ /* / */ /* path_x2.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: aurollan <marvin@le-101.fr> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2018/01/31 19:13:10 by aurollan #+# ## ## #+# */ /* Updated: 2018/01/31 19:13:10 by aurollan ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "../../Includes/libft.h" void ft_printh_width_04(t_struct *pattern, int len) { if (pattern->precision > len && pattern->width > len && pattern->precision == pattern->width && ft_strchr(pattern->flag, '0')) { if (ft_strchr(pattern->flag, '#')) ft_put_diese_hex(pattern); while (len < pattern->width) { ft_putchar_st('0', pattern); len++; } } if (ft_strchr(pattern->flag, '#') && pattern->precision > len && pattern->width > len && pattern->precision == pattern->width) { if (ft_strchr(pattern->flag, '#')) ft_put_diese_hex(pattern); while (len < pattern->width) { ft_putchar_st('0', pattern); len++; } } } void ft_printh_width_04b(t_struct *pattern, int len, uintmax_t nb) { if (pattern->width > len && pattern->precision < len && !ft_strchr(pattern->flag, '-')) { if (pattern->point == '.' && pattern->precision < len) { if (ft_strchr(pattern->flag, '#') && (nb != 0 || pattern->conv == 'p')) len = len + 2; while (len < pattern->width) { ft_putchar_st(' ', pattern); len++; } if (ft_strchr(pattern->flag, '#') && (nb != 0 || pattern->conv == 'p')) ft_put_diese_hex(pattern); } else ft_printh_width_04c(pattern, len, nb); } } void ft_printh_width_04c(t_struct *pattern, int len, uintmax_t nb) { if (ft_strchr(pattern->flag, '#') && (nb != 0 || pattern->conv == 'p')) { ft_put_diese_hex(pattern); len = len + 2; } while (len < pattern->width) { ft_putchar_st('0', pattern); len++; } } void ft_printh_prec_rev(t_struct *pattern, int len) { int a; a = pattern->width - pattern->precision; if (ft_strchr(pattern->flag, '-') && pattern->width > len && (pattern->width > pattern->precision && pattern->precision <= len && (ft_strchr(pattern->flag, '#')))) a = a - 2; if (pattern->precision > len && pattern->width > len && ft_strchr(pattern->flag, '-') && pattern->width > pattern->precision) { while (a > 0) { ft_putchar_st(' ', pattern); a--; } } if (pattern->width > len && ft_strchr(pattern->flag, '-') && pattern->precision <= len) { while (len < pattern->width) { ft_putchar_st(' ', pattern); len++; } } } void ft_put_diese_hex(t_struct *pattern) { if (pattern->conv == 'x' || pattern->conv == 'p') { ft_putchar_st('0', pattern); ft_putchar_st('x', pattern); } else { ft_putchar_st('0', pattern); ft_putchar_st('X', pattern); } }
C
#include <stdio.h> #include <stdlib.h> /* given any date, give the day of the week date can be in form of day month year Later, add ability to parse other date formats and things like now, today, etc. This generic date converter will be useful for many things. year 1900 has an offset of 0, this is useful Take someone born in 1965 1965 - 1900 = 65 65 is 5 short of 70, which leaves 2 65/4 = 16 with a remainder of 1. drop 14 because it is a multiple of 7 which leaves 2 2 for year + 2 for leap years + 9 for day + 6 for month = 19 drop 14 from that which leaves 5, So I was born on a Thursday. */ #define SAT 0 #define SUN 1 #define MON 2 #define TUE 3 #define WED 4 #define THU 5 #define FRI 6 #define JAN 1 #define FEB 4 #define MAR 4 #define APR 0 #define MAY 2 #define JUN 5 #define JUL 0 #define AUG 3 #define SEP 6 #define OCT 1 #define NOV 4 #define DEC 6 char * day_of_week[7] ={"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", }; char * months_of_year[12] = {"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" }; int monthoffset[12] = {1, 4, 4, 0, 2, 5, 0, 3, 6, 1, 4, 6}; int getdow(int day, int month, int year){ int result = year - 1900 ; result = result + result/4 + day + monthoffset[month] ; if (year % 4 == 0 && month <= 1) result -= 1; result %= 7; return (result); } #define END 2000 int main(){ int year = 1901, month, day = 1, result = 0; for (; year<=END; year++) for (month=0; month <12; month++) if (getdow(day, month, year) == SUN) { // printf ("1 %s %d was a %s\n", months_of_year[month], year, day_of_week[day] ); result++; } printf("Solution is %d\n", result); }
C
#ifndef SUPORTEESCRITABIBLIOTECA_H #define SUPORTEESCRITABIBLIOTECA_H void escrever_ordem_casas() { int matriz_location[TAMANHO_MATRIZ_JOGO][TAMANHO_MATRIZ_JOGO], ponteiro_matriz = 0; for (int linha = 0; linha < TAMANHO_MATRIZ_JOGO; linha++) for (int coluna = 0; coluna < TAMANHO_MATRIZ_JOGO; coluna++) { ponteiro_matriz = linha * TAMANHO_MATRIZ_JOGO + coluna; matriz_location[linha][coluna] = ponteiro_matriz + 1; } for (int linha = 0; linha < TAMANHO_MATRIZ_JOGO; linha++) { cout << "|"; for (int coluna = 0; coluna < TAMANHO_MATRIZ_JOGO; coluna++) cout << matriz_location[linha][coluna] << " |"; cout << endl; } } void escrever_matriz(string matriz_jogo[][TAMANHO_MATRIZ_JOGO]) { for (int linha = 0; linha < TAMANHO_MATRIZ_JOGO; linha++) { cout << "|"; for (int coluna = 0; coluna < TAMANHO_MATRIZ_JOGO; coluna++) cout << matriz_jogo[linha][coluna] << " |"; cout << endl; } cout << endl; } #endif // !SUPORTEESCRITABIBLIOTECA_H
C
/* Name: Vernon Meighan Date: 20200107 Project: This program will complete the following: #Student ages -Declare and zeroize an int array with a dimension equal to the number of students + 1 -Set index 0 with the age* of the instructor -Fill the elements of the array with the ages* of the students starting with index 1 -Print the array #Favorite quote -Declare and initialize a char array with your favorite saying -Ensure the last index is set to nul ('\0') -Separate each word in the array with a new line character ('\n' or decimal value 10) */ #include <stdio.h> #include <stdlib.h> void printArray(int arr[]) { printf("["); for (int y=0; y<=(int)sizeof(arr)/(int)sizeof(arr[0]); y++) { printf("%d", arr[y]); if (y == (int)sizeof(arr)/(int)sizeof(arr[0])) { printf("]\n"); } else { printf(", "); } } } void main() { // Declaring a 0 initialized array for ages int ages [3] = {0}; // Looping through each element of the array to input an age for (int y=0; y<(int)sizeof(ages)/(int)sizeof(ages[0]); y++) { // Initialize the variable for user input int x = 0; printf("Please provide the age of person %d:\n", (y+1) ); // Capture user input scanf("%d", &x); // Set element to user input ages[y] = x; } printArray(ages); char phrase [] = {"Know thyself!\0"}; for (int y=0; y<(int)sizeof(phrase)/(int)sizeof(phrase[0]); y++) { if((int)phrase[y] == 32) { printf("\n"); } else if ((int)phrase[y] == 0) { printf("\n"); } else { // print each character printf("%c", phrase[y]); } } //printf("%d\n", phrase[4]); //printf("%d\n", phrase[13]); }
C
#include <stdlib.h> #include <time.h> #include <stdio.h> #include "rsa.h" #define RSA_S (100) //Number of Miller-Rabin's tests void rsa_generate_keys(struct rsa_key**, struct rsa_key**); unsigned long rsa_convert(unsigned long, struct rsa_key*); unsigned short rsa_get_prime(); void rsa_get_keys(unsigned long*, unsigned long*, unsigned long, unsigned long); unsigned long rsa_exp(unsigned long, unsigned long, unsigned long); int rsa_witness(unsigned short, unsigned short); int rsa_miller_rabin(unsigned short, int); unsigned long rsa_phi(unsigned short, unsigned short); long rsa_ext_gcd(unsigned long, unsigned long, long*, long*, long*); void rsa_generate_keys(struct rsa_key **public_key, struct rsa_key **private_key) { unsigned short p, q; unsigned long n, e, d; *public_key = (struct rsa_key*) calloc(1, sizeof(struct rsa_key)); *private_key = (struct rsa_key*) calloc(1, sizeof(struct rsa_key)); srand(time(NULL)); p = rsa_get_prime(); q = rsa_get_prime(); //printf("prime 1: %d\n", p); //printf("prime 2: %d\n", q); n = (unsigned long) p * q; //printf("n: %lu\n", n); rsa_get_keys(&e, &d, n, rsa_phi(p, q)); (*private_key)->key = d; (*private_key)->n = n; (*public_key)->key = e; (*public_key)->n = n; } unsigned long rsa_convert(unsigned long msg, struct rsa_key *key) { return rsa_exp(msg, key->key, key->n); } unsigned short rsa_get_prime() { unsigned short prime; // srand(time(NULL)); while(13) { prime = (rand() % (1 << 8*sizeof(unsigned short)) - 1) + 1; if(rsa_miller_rabin(prime, RSA_S)) { break; } } return prime; } void rsa_get_keys(unsigned long *e, unsigned long *d, unsigned long n, unsigned long phi) { long gcd, x, y; //srand(time(NULL)); while(13) { *e = (rand() % (1 << 8*sizeof(unsigned short)) - 1) + 1; if(rsa_ext_gcd(*e, phi, &x, &y, &gcd) == 1) { break; } } if(x < 0) { x += phi; } *d = x; } unsigned long rsa_exp(unsigned long a, unsigned long b, unsigned long n) { unsigned long d; unsigned long long _d, _a; _d = 1; _a = a; while(b) { if(b & 1) { _d = (_a*_d) % n; } _a = (_a*_a) % n; b >>= 1; } d = _d; return d; } int rsa_witness(unsigned short a, unsigned short n) { unsigned short b, c; unsigned long _d, _a; _d = 1; b = n - 1; while(b) { if(b & 1) { _d = (_a*_d) % n; } c = _a; _a = (_a*_a) % n; b >>= 1; if(_a == 1 && c != 1 && c != (n - 1)) { return TRUE; } } if(_d == 1) { return FALSE; } return TRUE; } int rsa_miller_rabin(unsigned short n, int s) { unsigned short a; //srand(time(NULL)); while(s-- > 0) { a = (rand() % (n - 1)) + 1; if(rsa_witness(a, n) == TRUE) { return FALSE; } } return TRUE; } unsigned long rsa_phi(unsigned short p, unsigned short q) { return (unsigned long) (p - 1) * (q - 1); } long rsa_ext_gcd(unsigned long a, unsigned long b, long *x, long *y, long *d) { long tmp; if(!b) { *d = a; *x = 1; *y = 0; return *d; } rsa_ext_gcd(b, a%b, x, y, d); tmp = *x - (a/b)*(*y); *x = *y; *y = tmp; return *d; }
C
//////////////////////////////////////////////////////////////////// // // Name - Akshay Bhagwat // City - Pune (Maharashtra) // Email - akshay.bhagwat1003@gmail.com // /////////////////////////////////////////////////////////////////// #include<stdio.h> #include<stdlib.h> void LCM(int *ptr,int size) { int i = 0,j = 0,lcm = 1,min = 0; for(i = 0 ; i < size ; i++) { min = ptr[0]; if((ptr[i] == 0) || (ptr[i] < 0)) { lcm = 0; printf("\nLCM = %d\n",lcm); return ; } lcm *= ptr[i]; if(ptr[i] < min) { min = ptr[i]; } } for(i = min ; i <= lcm ; i++) { for(j = 0 ; j < size ; j++) { if(i % ptr[j] == 0) { if(j == (size - 1)) { printf("\nLCM = %d\n",i); return ; } } else { break; } } } } int main() { int size = 0,i = 0; int *ptr = NULL; printf("Enter size\n"); scanf("%d",&size); if(size <= 0) { printf("Enter valid size\n"); return 0; } ptr = (int*)malloc(size * sizeof(int)); if(ptr == NULL) { printf("MEMORY NOT ALLOCATED\n"); return 0; } printf("Enter %d elements\n",size); for(i = 0 ; i < size ; i++) { scanf("%d",&ptr[i]); } LCM(ptr,size); free(ptr); return 0; }
C
/* Filename: Stack.c */ /* */ /* EXPORT: Procedure Push: Put a search tree node onto the stack */ /* Procedure Pop: Delete a search tree node from the stack */ /* ************************************************************************* */ #include <stdlib.h> #include "datastruct.h" #include "table.h" #include "list.h" #include "stack.h" /* ************************************************************************* */ /* Procedure Push() */ /* */ /* INPUT : -/- */ /* */ /* FUNCTION: Put ActualNode onto the Stack */ /* ************************************************************************* */ void Push () { struct StackElement *NewElement; NewElement = (struct StackElement *) malloc(sizeof(struct StackElement)); NewElement->next = FirstOfStack; NewElement->node = ActualNode; FirstOfStack = NewElement; ActualNode = NIL; } /* ************************************************************************* */ /* Procedure Pop() */ /* */ /* INPUT : -/- */ /* */ /* FUNCTION: Delete ActualNode and assign the top of the stack to */ /* ActualNode */ /* ************************************************************************* */ void Pop () { struct StackElement *savestack; struct BlockList *blockhelp, *saveblock; struct BranchList *branchhelp, *savebranch; if (ActualNode != NIL) { blockhelp = ActualNode->blocks; while ( blockhelp != NIL ) { saveblock = blockhelp; blockhelp->elements = Makeempty(blockhelp->elements); blockhelp = blockhelp->next; free((void *) saveblock); } branchhelp = ActualNode->order; while (branchhelp != NIL) { savebranch = branchhelp; branchhelp = branchhelp->next; free((void *) savebranch); } free((void *) ActualNode); } ActualNode = FirstOfStack->node; savestack = FirstOfStack; FirstOfStack = FirstOfStack->next; free((void *) savestack); }
C
/* * input.c * irtouchd input function * * Created by David Keller on 09/11/08. * Copyright 2008 EFREI. All rights reserved. * */ #include <stdlib.h> #include <assert.h> #include <signal.h> #include <pthread.h> #include <string.h> #include <errno.h> #include <peach.h> #include <multitouch.h> struct _input_t { char * id; enum { INPUT_POLLING_STARTED, INPUT_POLLING_STOPPED } state; const mt_input_driver_t * driver; mt_input_driver_data_t * driver_data; mt_device_packet_process_t packet_process; void * extra_data; pthread_t polling_thread; int driver_must_stop_polling; peach_set_t * listeners; pthread_mutex_t listeners_lock; mt_chain_t * post_processing_chain; }; typedef struct { mt_device_packet_process_t process; void * data; } _listener_t; static int _polling_thread_run (mt_input_t * input); static int _polling_thread_stop (mt_input_t * input); static int _input_driver_commit (const mt_input_t * input, const mt_packet_t * packet); static int _give_packet_to_listeners (const mt_input_t * input, const char * from, const mt_packet_t * packet); static int _give_packet_to_listener (_listener_t * listener, va_list arguments); static int _driver_must_stop_polling (const mt_input_t * input); static void * _polling_thread (void * argument); static void _lock_listeners (const mt_input_t * input); static void _unlock_listeners (const mt_input_t * input); mt_input_t * mt_input_init (const char * input_id, const mt_input_driver_t * driver, const peach_hash_t * options) { mt_input_t * input; assert(input_id != 0); assert(driver != 0); input = calloc(1, sizeof(*input)); assert(input != 0); input->state = INPUT_POLLING_STOPPED; input->id = strdup(input_id); input->driver = driver; pthread_mutex_init(&input->listeners_lock, 0); if ((*input->driver->init)(input, &input->driver_data, options) != 0) goto clean; input->listeners = peach_set_init(10, 4); input->post_processing_chain = mt_chain_init(input, (mt_device_packet_process_t)_give_packet_to_listeners); _polling_thread_run(input); return input; clean: pthread_mutex_destroy(&input->listeners_lock); free(input->id); free(input); return 0; } void mt_input_destroy (mt_input_t * input) { assert(input != 0); if (input->state == INPUT_POLLING_STARTED) _polling_thread_stop(input); (*input->driver->destroy)(input, input->driver_data); peach_set_destroy(input->listeners, (peach_set_clean_t)free); free(input->id); pthread_mutex_destroy(&input->listeners_lock); mt_chain_destroy(input->post_processing_chain); free(input); } int mt_input_polling_start(mt_input_t * input) { if (input->state == INPUT_POLLING_STARTED) goto exit_with_failure; _polling_thread_run(input); return 0; exit_with_failure: return -1; } int mt_input_polling_stop(mt_input_t * input) { if (input->state == INPUT_POLLING_STOPPED) goto exit_with_failure; _polling_thread_stop(input); exit_with_failure: return -1; } const char * mt_input_get_id (const mt_input_t * input) { assert(input != 0); return input->id; } int mt_input_push_post_processing_engine (mt_input_t * input, const mt_chain_layer_driver_t * layer_driver, const peach_hash_t * options) { if (input->state == INPUT_POLLING_STARTED) { peach_log_debug(1, "Input '%s': could not push post processing engine " "while input is polling.", mt_input_get_id(input)); goto exit_with_failure; } return mt_chain_push_layer(input->post_processing_chain, layer_driver, options); exit_with_failure: return -1; } void mt_input_bind (mt_input_t * input, mt_device_packet_process_t process, void * data) { _listener_t * listener; assert(process != 0); listener = malloc(sizeof(*listener)); assert(listener != 0); listener->process = process; listener->data = data; _lock_listeners(input); peach_set_add(input->listeners, listener); _unlock_listeners(input); } static peach_hash_t * _drivers = 0; void mt_input_driver_loader_init(void) { assert(_drivers == 0); _drivers = peach_hash_init(20); } void mt_input_driver_loader_destroy(void) { assert(_drivers != 0); peach_hash_destroy(_drivers, 0); } int mt_input_driver_register (const char * name, const mt_input_driver_t * driver) { assert(name != 0); assert(driver != 0); assert(_drivers != 0); peach_log_debug(1, "Input: registering '%s' driver.\n", name); return peach_hash_add(_drivers, name, strlen(name), (mt_input_driver_t *)driver); } int mt_input_driver_unregister (const char * name) { assert(name != 0); assert(_drivers != 0); peach_log_debug(1, "Input: unregistering '%s' driver.\n", name); if (peach_hash_remove(_drivers, name, strlen(name)) == 0) goto exit_with_failure; return 0; exit_with_failure: return -1; } const mt_input_driver_t * mt_input_driver_get (const char * name) { assert(name != 0); return peach_hash_get(_drivers, name, strlen(name)); } static int _polling_thread_run (mt_input_t * input) { pthread_attr_t polling_thread_attribute; int result; pthread_attr_init(&polling_thread_attribute); pthread_attr_setdetachstate(&polling_thread_attribute, PTHREAD_CREATE_JOINABLE); input->driver_must_stop_polling = 0; if ((result = pthread_create(&input->polling_thread, &polling_thread_attribute, _polling_thread, input)) != 0) { char error_message_buffer [80]; peach_log_debug(1, "Input '%s': could not create polling thread: (%d\n", input->id, strerror_r(errno, error_message_buffer, sizeof(error_message_buffer))); } pthread_attr_destroy(&polling_thread_attribute); input->state = INPUT_POLLING_STARTED; return result; } static int _polling_thread_stop (mt_input_t * input) { input->driver_must_stop_polling = 1; if (pthread_kill(input->polling_thread, SIGUSR1) != 0) goto exit_with_failure; if (pthread_join(input->polling_thread, 0) != 0) goto exit_with_failure; input->state = INPUT_POLLING_STOPPED; return 0; exit_with_failure: return -1; } static int _input_driver_commit (const mt_input_t * input, const mt_packet_t * packet) { return mt_chain_transmit(input->post_processing_chain, mt_input_get_id(input), packet); } static int _give_packet_to_listeners (const mt_input_t * input, const char * from, const mt_packet_t * packet) { int result; _lock_listeners(input); result = peach_set_foreach(input->listeners, (peach_set_predicate_t)_give_packet_to_listener, from, packet); _unlock_listeners(input); return result; } static int _give_packet_to_listener (_listener_t * listener, va_list arguments) { const char * input_id; const mt_packet_t * packet; input_id = va_arg(arguments, const char *); packet = va_arg(arguments, const mt_packet_t *); peach_log_debug(3, "Input '%s': sending packet to listener.\n", input_id); return (*listener->process)(listener->data, input_id, packet); } static int _driver_must_stop_polling (const mt_input_t * input) { return input->driver_must_stop_polling; } static void * _polling_thread (void * argument) { sigset_t blocked_signal; mt_input_t * input; input = argument; sigemptyset(&blocked_signal); sigaddset(&blocked_signal, SIGTERM); sigaddset(&blocked_signal, SIGKILL); if (pthread_sigmask(SIG_BLOCK, &blocked_signal, 0) != 0) { char error_message_buffer [80]; peach_log_debug(1, "Input '%s': could not block SIGTERM & SIGKILL on " "the polling thread: '%s'\n", input->id, strerror_r(errno, error_message_buffer, sizeof(error_message_buffer))); goto exit; } (*input->driver->run)(input, input->driver_data, _input_driver_commit, _driver_must_stop_polling); exit: pthread_exit(0); } static void _lock_listeners (const mt_input_t * input) { pthread_mutex_lock(&((mt_input_t *)input)->listeners_lock); } static void _unlock_listeners (const mt_input_t * input) { pthread_mutex_unlock(&((mt_input_t *)input)->listeners_lock); }
C
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> typedef struct _stdobject_{ va_list args; void* morph; va_list _arguments(int n_args){ va_list this; va_start(this, n_args); return this; } void _end_arg(va_list a){ va_end(a); return; } void* _get_type(const char[] type){ void* deftype = NULL; char let = type[0]; int invalid = 0; do{ switch(let){ case i: return (int*)deftype; case c: if(type[1] == 'h') return (char*)deftype; else let = type[7]; invalid++; continue; case f: case d: case l: case s: case u: let = type[10]; invalid++; continue; case a: let = type[6]; invalid++; continue; } }while(invalid < 2); return deftype; } }object;
C
#include <stdio.h> #include "alloc.h" #define ALLOCSIZE 10000 static char allocbuf[ALLOCSIZE]; static char *allocp = allocbuf; char *alloc(int size) { if (allocbuf + ALLOCSIZE - allocp > size) { allocp += size; return allocp - size; } else return 0; } void freeit(char *p) { if (p >= allocbuf && p <= allocp) allocp = p; }
C
// // Ex1_Task2.c // Infor2_Exercise // // Created by 谭特 on 17/2/24. // Copyright © 2017年 谭特. All rights reserved. // #include <stdio.h> #include <math.h> #include <ctype.h> #define MAX 256 int main() { int A[MAX]; int num=0, index = 0, size =0; int sum = 0; double average; //read user input by loop printf("Please input values of A seperated by spaces(non number to stop): "); while(index < MAX){ if(!scanf("%d", &num)) { break; } A[index] = num; size++; sum += A[index++]; } //calculate average and closest value average = sum / size; int close_value = A[0]; for(int i = 1; i < size; i++) { if(fabs(A[i]-average) < fabs(close_value-average)){ close_value = A[i]; } } printf("Average: %f\nClosest Element: %d\n", average, close_value); return 0; }
C
#include<stdio.h> int n=10; int swap(int i,int min,int a[n]) { int temp = a[i]; a[i] = a[min]; a[min] = temp; } int heapify(int a[10],int i) { int l = (2*i)+1; int r = (2*i)+2; int min =-1; if(n>r) { if(a[l]>=a[r]) { min = r; } else { min = l; } } else if(n>l) { min = l; } if(a[i]>=a[min] && min!=-1) { swap(i,min,a); heapify(a,min); } } int main() { int a[10] = {4,3,2,1,4,3,21,6,7,8}; for(int i=n/2;i>=0;i--) { heapify(a,i); } for(int i=0;i<10;i++) { printf("%d ",a[i]); } }
C
#include "head.h" typedef struct matrizPNG{ int height; int width; int** image; } MatrizPNG; //Entrada: fileName <tipo: char*> (nombre del archivo a leer) //Lee una imagen .png MatrizPNG* readImage(char* fileName) { png_structp pngPtr; png_infop infoPtr; FILE* filePtr; png_uint_32 width; png_uint_32 height; int bitDepth; int colorType; int interlaceMethod; int compressionMethod; int filterMethod; int i, j; png_bytepp rows; filePtr = fopen (fileName, "rb"); if (!filePtr) { fprintf(stderr, "No pudo leer el archivo; %s .\n", fileName); return NULL; } // Creando punteros necesarios para el uso de libpng pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!pngPtr) { fprintf(stderr, "No se pudo crear \"pngPtr\".\n"); return NULL; } infoPtr = png_create_info_struct(pngPtr); if (!infoPtr) { fprintf(stderr, "No se pudo crear \"infoPtr\".\n"); return NULL; } if (setjmp(png_jmpbuf(pngPtr))) { fprintf(stderr, "Error durante png_init_io.\n"); return NULL; } png_init_io (pngPtr, filePtr); png_read_png (pngPtr, infoPtr, 0, 0); png_get_IHDR (pngPtr, infoPtr, & width, & height, & bitDepth, & colorType, & interlaceMethod, & compressionMethod, & filterMethod); // Iniciando lectura de pixeles // Si existe un problema con el archivo posterior a su metadata if (setjmp(png_jmpbuf(pngPtr))) { fprintf(stderr, "Error durante png_read_image.\n"); return NULL; } rows = png_get_rows (pngPtr, infoPtr); int rowbytes; rowbytes = png_get_rowbytes (pngPtr, infoPtr); MatrizPNG* matrizPNG; matrizPNG = (MatrizPNG*) malloc(sizeof(MatrizPNG)); matrizPNG->height = height; matrizPNG->width = width; matrizPNG->image = (int**) malloc(sizeof(int*) * matrizPNG->height); for (i = 0; i < matrizPNG->height; i++) { matrizPNG->image[i] = (int*) malloc(sizeof(int) * matrizPNG->width); } for (j = 0; j < height; j++) { png_bytep row; row = rows[j]; if (rowbytes > width) { int multiplier = rowbytes/width; for (i = 0; i < width; i++) { matrizPNG->image[j][i] = row[i*multiplier]; } } else { int accumulated = 0; for (i = 0; i < rowbytes; i++) { int k = width/rowbytes; while (k > 0) { matrizPNG->image[j][i + accumulated] = row[i]; accumulated++; k--; } accumulated--; } } } if (pngPtr && infoPtr) { png_destroy_read_struct(&pngPtr, &infoPtr, NULL); pngPtr = NULL; infoPtr = NULL; } fclose(filePtr); return matrizPNG; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> struct cell_f{ char *main_title; char *sub_title; char *date; char *path; int category; struct cell_f *next; }; struct cell_c{ int number; char *category; struct cell_c *next; }; #define MAXLEN 100 #define MAX 2000 void insert_cell_f(struct cell_f **pointer, char *main_title, char *sub_title, char *date, char *path, int category); struct cell_f **make_original_file_list(struct cell_f **pointer, FILE *fp); void insert_cell_c(struct cell_c **pointer, int new_number, char *new_category); struct cell_c **make_original_category_list(struct cell_c **pointer, FILE *fp); void insert_cell_file(struct cell_c **p, struct cell_f **pointer); void delete_file(struct cell_f **pointer); void insert_cell_category(struct cell_c **pointer); int search_n(struct cell_c *a, int n); int search_c(struct cell_c *a, char *category); void delete_category(struct cell_c **pointer); void replace_number(struct cell_c *pointer); void rename_file(struct cell_f **pointer); void sort(struct cell_f **pointer); struct cell_f *search(struct cell_f *pointer, int n); void change(struct cell_f *data, int x, int y); void category_a(struct cell_f **pointer); void downheap_category_a(struct cell_f *data, int v, int n); void category_d(struct cell_f **pointer); void downheap_category_d(struct cell_f *data, int v, int n); void date_a(struct cell_f **p); void downheap_date_a(struct cell_f *data, int v, int n); void date_d(struct cell_f **pointer); void downheap_date_d(struct cell_f *data, int v, int n); void m_a_sub_a(struct cell_f **pointer); void downheap_main_a_sub_a(struct cell_f *data, int v, int n); void m_a_sub_d(struct cell_f **pointer); void downheap_main_a_sub_d(struct cell_f *data, int v, int n); void m_d_sub_a(struct cell_f **pointer); void downheap_main_d_sub_a(struct cell_f *data, int v, int n); void m_d_sub_d(struct cell_f **pointer); void downheap_main_d_sub_d(struct cell_f *data, int v, int n); void path_a(struct cell_f **pointer); void downheap_path_a(struct cell_f *data, int v, int n); void path_d(struct cell_f **pointer); void downheap_path_d(struct cell_f *data, int v, int n); void print_f(struct cell_f *p); void print_c(struct cell_c *p); void search_f(struct cell_f **h_f, struct cell_f **pointer); struct cell_f **search_file(struct cell_f **h_f, struct cell_f *pointer, int number, char *key); void delete_cell(struct cell_f **pointer); void sub_function(struct cell_f **pointer); void insert_cell_new_category(struct cell_c **pointer, char *new_category);
C
#include <stdio.h> #include <SDL2/SDL.h> #include <string.h> void _copystr(int nStartIndex, int nEndIndex, char src[], char dst[]) { int count = 0; for(count = 0; nStartIndex < nEndIndex; count++, nStartIndex++) { dst[count] = src[nStartIndex]; } dst[count] = 0; printf("%s\n", dst); } int main(int argc, char *argv[]) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { printf("error initializing SDL: %s\n", SDL_GetError()); return 1; } char data[] = "kor, mat, eng, bio, pyh, earth"; char buf1[16]; char buf2[16]; char buf3[16]; char buf4[16]; char buf5[16]; char buf6[16]; _copystr(0, 3, data, buf1); _copystr(5, 8, data, buf2); _copystr(10, 13, data, buf3); _copystr(15, 18, data, buf4); _copystr(20, 23, data, buf5); _copystr(25, 30, data, buf6); SDL_Quit(); return 0; }
C
#include <arpa/inet.h> #include <errno.h> #include <netinet/in.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include "openssl/crypto.h" #include "openssl/err.h" #include "openssl/ssl.h" // To compile and run // gcc psk.c -lssl -lcrypto -DCLIENT -o client && gcc psk.c -lssl -lcrypto -o // server && ./server and run the client in another window // ./client #define MAX_BUF_SIZE 1024 #define MSG1_REQ "NVMe req 1\n" #define MSG1_RES "NVMe res 1\n" #define MSG2_REQ "NVMe req 2\n" #define MSG2_RES "NVMe res 2\n" #define SERVER_IP "127.0.0.1" // TCP port 4420 has been assigned for use by NVMe over Fabrics and TCP port // 8009 has been assigned by IANA #define SERVER_PORT 8009 int do_tcp_connection(const char* server_ip, uint16_t port); int do_tcp_listen(const char* server_ip, uint16_t port); int do_tcp_accept(int lfd); void check_and_close(int* fd); int do_tcp_connection(const char* server_ip, uint16_t port) { struct sockaddr_in serv_addr; int fd; int ret; fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { printf("Socket creation failed\n"); return -1; } printf("Client fd=%d created\n", fd); serv_addr.sin_family = AF_INET; if (inet_aton(server_ip, &serv_addr.sin_addr) == 0) { printf("inet_aton failed\n"); goto err_handler; } serv_addr.sin_port = htons(port); printf("Connecting to %s:%d...\n", server_ip, port); ret = connect(fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); if (ret) { printf("Connect failed, errno=%d\n", errno); goto err_handler; } printf("TLS connection succeeded, fd=%d\n", fd); return fd; err_handler: close(fd); return -1; } int do_tcp_listen(const char* server_ip, uint16_t port) { struct sockaddr_in addr; int optval = 1; int lfd; int ret; lfd = socket(AF_INET, SOCK_STREAM, 0); if (lfd < 0) { printf("Socket creation failed\n"); return -1; } addr.sin_family = AF_INET; if (inet_aton(server_ip, &addr.sin_addr) == 0) { printf("inet_aton failed\n"); goto err_handler; } addr.sin_port = htons(port); if (setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval))) { printf("set sock reuseaddr failed\n"); } ret = bind(lfd, (struct sockaddr*)&addr, sizeof(addr)); if (ret) { printf("bind failed %s:%d\n", server_ip, port); goto err_handler; } printf("TCP listening on %s:%d...\n", server_ip, port); ret = listen(lfd, 5); if (ret) { printf("listen failed\n"); goto err_handler; } printf("TCP listen fd=%d\n", lfd); return lfd; err_handler: close(lfd); return -1; } int do_tcp_accept(int lfd) { struct sockaddr_in peeraddr; socklen_t peerlen = sizeof(peeraddr); int cfd; printf("Waiting for TCP connection from client on listen fd=%d...\n", lfd); cfd = accept(lfd, (struct sockaddr*)&peeraddr, &peerlen); if (cfd < 0) { printf("accept failed, errno=%d\n", errno); return -1; } printf("TCP connection accepted fd=%d\n", cfd); return cfd; } void check_and_close(int* fd) { if (*fd < 0) { return; } if (*fd == 0 || *fd == 1 || *fd == 2) { printf("Trying to close fd=%d, skipping it !!!\n", *fd); } printf("Closing fd=%d\n", *fd); close(*fd); *fd = -1; } SSL_CTX* create_context() { SSL_CTX* ctx; #ifdef CLIENT ctx = SSL_CTX_new(TLS_client_method()); #else ctx = SSL_CTX_new(TLS_server_method()); #endif if (!ctx) { printf("SSL ctx new failed\n"); return NULL; } printf("SSL context created\n"); return ctx; } // The psk_identity field in the ClientKeyExchange message shall contain the // host NQN and the subsystem NQN separated by a space (‘ ‘=U+0020) character as // a UTF-8 string, including the terminating null (00h) character. // These values were concatenated as openssl had issues with long string #if 0 #define PSK_ID \ "nqn.2014-08.org.nvmexpress:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6 " \ "nqn.2014-08.org.nvmexpress:uuid:36ebf5a9-1df9-47b3-a6d0-e9ba32e428a2" #endif #define PSK_ID \ "nqn.2014-08.org.nvmexpress:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6 " \ "nqn.2014-08.org.nvmexpress:uuid:36ebf5a9-1df9-47b3-a6d0-e9" #define PSK_KEY "1234567890ABCDEF" unsigned int tls_psk_out_of_bound_serv_cb(SSL* ssl, const char* id, unsigned char* psk, unsigned int max_psk_len) { printf("Length of Client's PSK ID %lu\n", strlen(PSK_ID)); if (strcmp(PSK_ID, id) != 0) { printf("Unknown Client's PSK ID\n"); goto err; } printf("Length of Client's PSK KEY %u\n", max_psk_len); if (strlen(PSK_KEY) > max_psk_len) { printf("Insufficient buffer size to copy PSK_KEY\n"); goto err; } memcpy(psk, PSK_KEY, strlen(PSK_KEY)); return strlen(PSK_KEY); err: return 0; } SSL* create_ssl_object_server(SSL_CTX* ctx, int lfd) { SSL* ssl; int fd; fd = do_tcp_accept(lfd); if (fd < 0) { printf("TCP connection establishment failed\n"); return NULL; } ssl = SSL_new(ctx); if (!ssl) { printf("SSL object creation failed\n"); return NULL; } SSL_set_fd(ssl, fd); SSL_set_psk_server_callback(ssl, tls_psk_out_of_bound_serv_cb); printf("SSL object creation finished\n"); return ssl; } #ifndef CLIENT int do_data_transfer(SSL* ssl) { const char* msg_res[] = {MSG1_RES, MSG2_RES}; const char* res; char buf[MAX_BUF_SIZE] = {0}; int ret, i; for (int j = 0; j <= 131072000; j += 22) { for (i = 0; i < sizeof(msg_res) / sizeof(msg_res[0]); i++) { res = msg_res[i]; ret = SSL_read(ssl, buf, sizeof(buf) - 1); if (ret <= 0) { printf("SSL_read failed ret=%d\n", ret); return -1; } printf("SSL_read[%d] %s\n", ret, buf); ret = SSL_write(ssl, res, strlen(res)); if (ret <= 0) { printf("SSL_write failed ret=%d\n", ret); return -1; } printf("SSL_write[%d] sent %s\n", ret, res); } } return 0; } #endif // 1 Gbit = 125 megabytes = 131,072,000 bytes #ifdef CLIENT int do_data_transfer(SSL* ssl) { const char* msg_req[] = {MSG1_REQ, MSG2_REQ}; const char* req; char buf[MAX_BUF_SIZE] = {0}; int ret, i; int len_sent = 0; for (int j = 0; j <= 131072000; j += 22) { for (i = 0; i < sizeof(msg_req) / sizeof(msg_req[0]); i++) { req = msg_req[i]; const int this_len = strlen(req); ret = SSL_write(ssl, req, this_len); if (ret <= 0) { printf("SSL_write failed ret=%d\n", ret); return -1; } printf("SSL_write[%d] sent %s\n", ret, req); ret = SSL_read(ssl, buf, sizeof(buf) - 1); if (ret <= 0) { printf("SSL_read failed ret=%d\n", ret); return -1; } printf("SSL_read[%d] %s\n", ret, buf); len_sent += this_len; } } printf("%d bytes sent\n", len_sent); return 0; } #endif void do_cleanup(SSL_CTX* ctx, SSL* ssl) { int fd; if (ssl) { fd = SSL_get_fd(ssl); SSL_free(ssl); close(fd); } if (ctx) { SSL_CTX_free(ctx); } } void get_error() { unsigned long error; const char* file = NULL; int line = 0; error = ERR_get_error_line(&file, &line); printf("Error reason=%d on [%s:%d]\n", ERR_GET_REASON(error), file, line); } int tls_server() { SSL_CTX* ctx; SSL* ssl = NULL; int lfd; int ret; ctx = create_context(); if (!ctx) { return -1; } lfd = do_tcp_listen(SERVER_IP, SERVER_PORT); if (lfd < 0) { goto err_handler; } ssl = create_ssl_object_server(ctx, lfd); check_and_close(&lfd); if (!ssl) { goto err_handler; } ret = SSL_accept(ssl); if (ret != 1) { printf("SSL accept failed%d\n", ret); if (SSL_get_error(ssl, ret) == SSL_ERROR_SSL) { get_error(); } goto err_handler; } printf("SSL accept succeeded\n"); printf("Negotiated Cipher suite:%s\n", SSL_CIPHER_get_name(SSL_get_current_cipher(ssl))); if (do_data_transfer(ssl)) { printf("Data transfer over TLS failed\n"); goto err_handler; } printf("Data transfer over TLS succeeded\n"); SSL_shutdown(ssl); err_handler: do_cleanup(ctx, ssl); return 0; } #ifndef CLIENT int main() { printf("OpenSSL version: %s, %s\n", OpenSSL_version(OPENSSL_VERSION), OpenSSL_version(OPENSSL_BUILT_ON)); if (tls_server()) { printf("TLS server connection failed\n"); fflush(stdout); return -1; } return 0; } #endif unsigned int tls_psk_out_of_bound_cb(SSL* ssl, const char* hint, char* identity, unsigned int max_identity_len, unsigned char* psk, unsigned int max_psk_len) { if ((strlen(PSK_ID) + 1 > max_identity_len) || (strlen(PSK_KEY) > max_psk_len)) { printf("PSK ID or Key buffer is not sufficient\n"); goto err; } strcpy(identity, PSK_ID); memcpy(psk, PSK_KEY, strlen(PSK_KEY)); printf("Provided Out of bound PSK for TLS client\n"); return strlen(PSK_KEY); err: return 0; } SSL* create_ssl_object_client(SSL_CTX* ctx) { SSL* ssl; int fd; fd = do_tcp_connection(SERVER_IP, SERVER_PORT); if (fd < 0) { printf("TCP connection establishment failed\n"); return NULL; } ssl = SSL_new(ctx); if (!ssl) { printf("SSL object creation failed\n"); return NULL; } SSL_set_fd(ssl, fd); SSL_set_psk_client_callback(ssl, tls_psk_out_of_bound_cb); printf("SSL object creation finished\n"); return ssl; } int tls_client() { SSL_CTX* ctx; SSL* ssl = NULL; int ret; ctx = create_context(); if (!ctx) { return -1; } ssl = create_ssl_object_client(ctx); if (!ssl) { goto err_handler; } ret = SSL_connect(ssl); if (ret != 1) { printf("SSL connect failed%d\n", ret); if (SSL_get_error(ssl, ret) == SSL_ERROR_SSL) { get_error(); } goto err_handler; } printf("SSL connect succeeded\n"); printf("Negotiated Cipher suite: %s\n", SSL_CIPHER_get_name(SSL_get_current_cipher(ssl))); if (do_data_transfer(ssl)) { printf("Data transfer over TLS failed\n"); goto err_handler; } printf("Data transfer over TLS succeeded\n"); SSL_shutdown(ssl); err_handler: do_cleanup(ctx, ssl); return 0; } #ifdef CLIENT int main() { printf("OpenSSL version: %s, %s\n", OpenSSL_version(OPENSSL_VERSION), OpenSSL_version(OPENSSL_BUILT_ON)); if (tls_client()) { printf("TLS client connection failed\n"); fflush(stdout); return -1; } return 0; } #endif
C
#include <stdio.h> #include <stdlib.h> extern char **environ; int func(int arg) { printf("in func arg=%d\n", arg); return (arg); } void exit_func(void) { printf("exit_func\n"); } int main(int argc, char **argv) { int i = 2; printf("in main\n"); i = func(i); printf("func return %d add\n", i); // if (atexit(exit_func) != 0) // { // printf("atexit failed\n"); // } // for (i = 0; environ[i] != NULL; i++) // { // printf("%s\n", environ[i]); // } }
C
/* * Date: 12/12/2015 * Writter: Loc Pham * Description: This file contains function declarations for CMD */ #ifndef _CMD_H #define _CMD_H // Include header files #include "stm32f4xx.h" // Declare macros // Declare structs // Declare function prototypes /* * Name: CMD_IsValid * Module: cmd * Parameters: cmd_str (char*) * Description: Check if cmd is valid or not * An valid cmd is: * + not an empty cmd * + must have 'enter' at the end of cmd * Note: If cmd is ESC then it is valid without having 'enter' at the end * Return: uint8_t * 1 means cmd is valid * 0 means cmd is invalid */ uint8_t CMD_IsValid(char* cmd_str); /* * Name: CMD_IsValid * Module: cmd * Parameters: cmd_str (char*) * Description: Remove enter at the end string * Return: void */ void CMD_RemoveEnter(char* cmd_str); #endif /* End of file */
C
#include <stdio.h> #include <string.h> #define MAX 1010 #define debug 0 int is_font_valid(int font, int W, int H, char *str) { int i, j, no_of_words; // Find the total no of words in str no_of_words = 1; for (i=0; i < strlen(str); i++) if (str[i] == ' ') no_of_words++; // Declare 2 arrays, to store word sizes and fitting information int * word_fitting = (int*) malloc (no_of_words * sizeof(int)); int * word_sizes = (int*) malloc (no_of_words * sizeof(int)); // Initialize the two arrays for (i=0; i < no_of_words; i++) { word_sizes[i] = 0; word_fitting[i] = 0; } // Count the word sizes and fill the array word_sizes j=0; for (i=0; i < strlen(str); i++) { if (str[i] == ' ') j++; else word_sizes[j]++; } if (debug){ printf("\n The no of words in \"%s\" is = %d", str, no_of_words); for (i=0; i < no_of_words; i++) { printf("\n Word %d 's size = %d", i+1, word_sizes[i]); } } int avail_lines = H / font; int current_line = 0; int current_word = 0; int spaces_first_word = 0; // This is set to zero for the first word being fitted in a line int avail_width_current_line = W; while ((current_line < avail_lines) && (current_word < no_of_words)) { if (word_sizes[current_word] > W) return 0; // A word cannot fit in the line, font size invalid if ( (font*(spaces_first_word + word_sizes[current_word])) <= avail_width_current_line) { // current word can be fitted // do a fitting if (debug) { printf("\n avail_width_current_line = %d", avail_width_current_line); printf("\n to be deducted = %d", font*(spaces_first_word + word_sizes[current_word])); printf("\n current word = %d", current_word); printf("\n current line = %d", current_line); } word_fitting[current_word] = 1; avail_width_current_line = avail_width_current_line - (font*(spaces_first_word + word_sizes[current_word])); current_word++; // if this was the first word in the line, the next word and onwards will need a space if (spaces_first_word == 0) spaces_first_word = 1; } else { // move to next line current_line++; avail_width_current_line = W; spaces_first_word = 0; } } if (debug){ for (i = 0; i < no_of_words; i++) printf("\n word_fitting[%d] = %d", i, word_fitting[i]); printf("\n current line = %d", current_line); } if (current_line == avail_lines) { // all lines were used // the font size is invalid return 0; } else if (current_word == no_of_words) { // all words were fitted // the font size is valid return 1; } printf("\n Should not reach here !!!"); } int main() { int T, W, H, i, font = 3; char str[MAX]; FILE *pFile, *oFile; pFile = fopen ("billboards.txt","r"); //input_small input_large if (pFile == NULL){ printf("\n Error in opening file!!"); getchar(); return 1; } oFile = fopen ("billboards_result.txt","w"); //input_small input_large if (oFile == NULL){ printf("\n Error in opening file!!"); getchar(); return 1; } fscanf (pFile, "%d", &T); //fscanf (pFile, "\n"); //printf("T = %d\n", T); for (i = 1; i <= T; i++) { fscanf (pFile, "%d", &W); fscanf (pFile, "%d\n", &H); fgets(str, sizeof str, pFile); if (i != T) str[strlen(str)-1] = '\0'; /* printf("\nW = %d\n", W); printf("\nH = %d\n", H); printf("\nstr = %s, %d", str, strlen(str)); */ font = 1; while (is_font_valid(font, W, H, str) == 1) font++; printf("Case #%d: %d\n", i, font-1); fprintf(oFile, "Case #%d: %d\n", i, font-1); } fclose (pFile); fclose (oFile); //getchar(); getchar(); return 0; }
C
#include "TAD_Palavra.h" void inicializaPalavra(TPalavra *palavra) { palavra->Primeiro = INICIO; palavra->Ultimo = palavra->Primeiro; palavra->tamanho = 0; } void insereLetra(TPalavra *palavra, TLetra letra) { if (palavra->Ultimo > MAX_TAM_PALAVRA) return; //lista cheia else { palavra->palavra[palavra->Ultimo] = letra; palavra->Ultimo++; palavra->tamanho++; } } void removeLetra(TPalavra *palavra) { palavra->Ultimo--; palavra->tamanho--; //possivel erro } void imprimePalavra(TPalavra *palavra) { int i; for (i = palavra->Primeiro; i < palavra->Ultimo; i++) printf("%c", palavra->palavra[i].letra); } int tamanhoPalavra(TPalavra *palavra) { return palavra->tamanho; }
C
#include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include "termio.h" void panic(char* msg) { termio_clear_screen(); termio_fin(); fputs(msg, stderr); exit(EXIT_FAILURE); } int main() { if (termio_init()) panic("terminal setup failed"); int i = 0; while (true) { printf("fooooo %i", i); printf("\r"); i++; char c; if (termio_getch(&c)) { printf("\r%x \n", c); if (c == 'q') { termio_fin(); return EXIT_SUCCESS; } } } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* put_pile.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mbuclin <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/03/29 16:41:14 by mbuclin #+# #+# */ /* Updated: 2016/05/21 11:38:35 by mbuclin ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/push_swap.h" void print_pile_a(t_turn *node, int color, int ncmd) { t_pile *tmp; tmp = node->a; if (color) ft_putstr("\033[32mPile A :\033[0m"); else ft_putstr("Pile A :"); while (tmp) { if (color && (ncmd == RA || ncmd == RR) && !tmp->next) ft_printf("\033[32m %d\033[0m", tmp->num); else if (color && (ncmd == RRA || ncmd == SA || ncmd == PA ||\ ncmd == SS || ncmd == RRR) && tmp == node->a) ft_printf("\033[32m %d\033[0m", tmp->num); else if (color && (ncmd == SA || ncmd == SS) && tmp == node->a->next) ft_printf("\033[32m %d\033[0m", tmp->num); else ft_printf(" %d", tmp->num); tmp = tmp->next; } ft_putchar('\n'); } void print_pile_b(t_turn *node, int color, int ncmd) { t_pile *tmp; tmp = node->b; if (color) ft_putstr("\033[32mPile B :\033[0m"); else ft_putstr("Pile B :"); while (tmp) { if (color && (ncmd == RB || ncmd == RR) && !tmp->next) ft_printf("\033[32m %d\033[0m", tmp->num); else if (color && (ncmd == RRB || ncmd == SB || ncmd == PB ||\ ncmd == SS || ncmd == RRR) && tmp == node->b) ft_printf("\033[32m %d\033[0m", tmp->num); else if (color && (ncmd == SB || ncmd == SS) && tmp == node->b->next) ft_printf("\033[32m %d\033[0m", tmp->num); else ft_printf(" %d", tmp->num); tmp = tmp->next; } ft_putchar('\n'); } void put_piles(t_turn *node, const char *option, int cmd) { print_pile_a(node, option[COLOR], cmd); print_pile_b(node, option[COLOR], cmd); } void put_command(t_cmd *command, int n) { t_cmd *tmp; int i; tmp = command; i = 0; while (tmp) { ft_printf("%s", tmp->command); i++; tmp = tmp->next; if (tmp) ft_putchar(' '); } if (i) ft_putchar('\n'); if (n) ft_printf("It took %d turn(s) to sort it\n", i); }
C
#include<stdio.h> int main() { int i; int *p=NULL; int a[5]={1,2,3,4,5}; p=a;//p=&a[0] for(i=0;i<5;i++) { printf("%d ",*(p+i));//p[i] a[i] *(a+i) } return 0; }
C
/*finding a unique character*/ #include<stdio.h> #include<string.h> #include<limits.h> #define noofchars 256 int uni(char* str) { int i,res; int arr[noofchars]; for(i=0;i<noofchars;i++) arr[i]=-1; for(i=0;str[i];i++) { if(arr[str[i]]==-1) arr[str[i]]=i; else arr[str[i]]=-2; } res=INT_MAX; for(i=0;i<noofchars;i++) if(arr[i]>=0) res= minimum(res,arr[i]); return res; } int minimum(int res,int n) { if(res<n) return res; else return n; } int main() { char str[100]; int index;9 scanf("%[^\n]%*c",str); index=uni(str); if (index==INT_MAX) printf("No Unique Character"); else printf("%c",str[index]); return 0; }
C
typedef int Data; struct listnode { Data data; struct listnode *next; }; typedef struct listnode Listnode; typedef struct { Listnode *top; } Stack; void init_stack(Stack *s); int stack_full(Stack *s); int stack_empty(Stack *s); void push_stack(Stack *s, Data data); Data pop_stack(Stack *s);
C
#include <stdio.h> #include <math.h> int main(){ int c; float num1, num2, res; printf("\n\n=================================Calculadora====================================\n"); printf("\nEscolha a operação matemática desejada;\n"); printf("1.Adição\n"); printf("2.Subtração\n"); printf("3.Multiplicação\n"); printf("4.Divisão\n"); printf("5.Raiz Quadrada\n"); printf("6.Exponenciação\n\n"); scanf("%d", &c); printf("\nDigite as variáveis para realizar as operações;\n"); printf("\nVariável A:"); scanf("%f", &num1); printf("Variável B:"); scanf("%f", &num2); switch (c) { case 1: res = num1 + num2; printf("\nResultado da Adição = %.2f\n\n", res); break; case 2: res = num1 - num2; printf("\nResultado da Subtração = %.2f\n\n", res); break; case 3: res = num1 * num2; printf("\nResultado da Multiplicação = %.2f\n\n", res); break; case 4: if (num2 == 0) printf("\nA Divisão da 0\n\n"); else { res = num1 / num2; printf("\nResultado da Divisão = %.2f\n\n", res); } break; case 5: res = sqrt(num1); printf("\nO Resultado da Raiz Quadrada é = %f\n", res); break; case 6: res = (int)num1 % (int)num2; printf("\nResultado do Resto da Divisão = %.2f\n\n", res); break; default: printf("Esta opção não existe!"); } return 0; }
C
/* ************************************************************************** */ /* LE - / */ /* / */ /* get_fd_contents.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: fcordon <marvin@le-101.fr> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2019/03/13 22:19:34 by fcordon #+# ## ## #+# */ /* Updated: 2019/04/08 17:50:02 by fcordon ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "libft.h" static char *newalloc(char *s, char *buf, int len, int total_len) { char *new; new = malloc(total_len + len + 1); ft_memcpy(new, s, total_len); ft_memcpy(new + total_len, buf, len); free(s); return (new); } extern char *get_fd_contents(int fd, int *ptrlen) { char buf[2048]; char *s; int total_len; int len; s = NULL; total_len = 0; while ((len = read(fd, buf, 2047)) > 0) { s = (!s) ? ft_memdup(buf, len + 1) : newalloc(s, buf, len, total_len); total_len += len; } if (ptrlen) *ptrlen = total_len; if (s) s[total_len] = '\0'; return (s); }
C
//请设计一个算法,将顺序表中的所有元素逆置 #include<stdio.h> #define MaxSize 30 typedef struct{ int data[MaxSize]; //静态数组存放数据 int length; //定义当前顺序表长度 }SqList; /*倒置算法*/ void Inverse(SqList *list){ int temp; for (int i = 0, j = list->length - 1; i < j; i++, j--){ temp = list->data[i]; list->data[i] = list->data[j]; list->data[j] = temp; } } void show(SqList list){ for(int i=0;i<list.length;i++){ printf("%d ",list.data[i]); } printf("\n"); } int main(){ SqList a ; a.length = 0; for(int i=0;i<11;i++){ a.data[i]=i; a.length++; } show(a); Inverse(&a); show(a); return 0; }
C
/* Implement following programs to exhibit UNIX Process Control Parent process - sorts array elements in ascending order Child process - sorts array elements in descending order Demonstrate ZOMBIE state; where child process terminates and waits for parent process to collect its exit status */ #include <stdio.h> #include<sys/types.h> #include<sys/wait.h> #include<stdlib.h> #include<unistd.h> #define MAX 20 #include "defined_function.h" int main() { int arr[MAX], *status=NULL; pid_t cpid; fflush(stdout); accept_nos(arr); printf("\n\tThis is the parent process. PID: %d",getpid()); sort_asc(arr); cpid = fork(); if( cpid == 0 ) //CHILD PROCESS { sleep(5); printf("\n*************** This is child process ***************\n "); printf("\n\t My process id is : %d", getpid()); printf("\n\t My Parent process id is : %d", getppid()); sort_desc(arr); printf("\n*************** Child process terminates *************\n"); } else { printf("\n\tParent process sleeping!\n"); sleep(25); printf("\n\nSleep time complete!\n"); printf("\nWait returns: (cleanup zombie process from process table)"); }//end of if-else return 0; }//end of main /* Output Enter the number of elements:4 Enter the elements: Element 1 :243 Element 2 :54234 Element 3 :234 Element 4 :654 This is the parent process. PID: 2754 The Numbers In Ascending Order Are: 234 243 654 54234 Parent process sleeping! 234 243 654 54234 *************** This is child process *************** My process id is : 2755 My Parent process id is : 2754 The Numbers In Descending Order Are: 54234 654 243 234 *************** Child process terminates ************* Sleep time complete! Wait returns: (cleanup zombie process from process table) */
C
/* * main.c * * Copyright (c) 2013 Franck Jullien <elec4fun@gmail.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <stdio.h> #include <common.h> #include <i2c.h> #include <linux/i2c-dev.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <unistd.h> #include <sys/ioctl.h> #include <string.h> int i2c_stub_init(struct i2c_master *master) { int file; file = open("/dev/stub0", O_RDWR); if (!file) return -1; master->file = file; return 0; } int i2c_stub_get_msg(struct i2c_master *master, int *len, unsigned char *buffer) { int ret; int bytes; int rxlen; unsigned char *tmp; int i; bytes = read(master->file, &rxlen, 1); if (!bytes) { *len = 0; return 0; } tmp = malloc(rxlen - 1); if (!tmp) { *len = 0; return -1; } ret = read(master->file, tmp, rxlen - 1); if (ret <= 0) { *len = 0; return -1; } memcpy(buffer, &tmp[2], tmp[1]); *len = tmp[1]; free(tmp); return 0; } int i2c_stub_send_msg(struct i2c_master *master, int len, unsigned char *buffer) { unsigned char *_buf; int ret; _buf = malloc(len + 1); if (!_buf) return -1; memcpy(&_buf[1], buffer, len); _buf[0] = len; ret = write(master->file, _buf, len + 1); if (ret != (len + 1)) return -1; return 0; } struct i2c_master master = { .get_msg = i2c_stub_get_msg, .send_msg = i2c_stub_send_msg, .init = i2c_stub_init, };
C
#include <assert.h> #include <sys/time.h> static int omp_get_max_threads(void) { return 1; } static double omp_get_wtime(void) { struct timeval tp; int rc = gettimeofday(&tp, NULL); assert(rc==0); double t = tp.tv_sec + tp.tv_usec * 1.e-6; return t; }
C
// // Created by cout970 on 2017-07-15. // #include "macros.h" #include <string.h> #include "network.h" void network_signal(NetworkCard* network, Byte signal) { ((NetworkCard volatile*) network)->signal = signal; } Boolean network_is_internet_allowed(NetworkCard* network) { return network->internetAllowed; } Int network_get_max_sockets(NetworkCard* network) { return network->maxSockets; } Int network_get_active_sockets(NetworkCard* network) { return network->activeSockets; } Int network_get_mac(NetworkCard* network) { return network->targetMac; } Int network_get_target_mac(NetworkCard* network) { return network->targetMac; } void network_set_target_mac(NetworkCard* network, Int mac) { ((NetworkCard volatile*) network)->targetMac = mac; } void network_set_target_ip(NetworkCard* network, const String *ip) { Int lenPlusOne = 0, i; while (ip[lenPlusOne++]); if (lenPlusOne == 1 || lenPlusOne - 1 > NETWORK_IP_MAX_SIZE) { return; } volatile char *dst = network->targetIp; for (i = 0; i < lenPlusOne; i++) { dst[i] = ip[i]; } } void network_set_target_port(NetworkCard* network, Short port) { ((NetworkCard volatile*) network)->targetPort = port; } Boolean network_is_connection_open(NetworkCard* network) { return (Boolean) network->connectionOpen; } Int network_get_connection_error(NetworkCard* network) { return network->connectionError; } Int network_send(NetworkCard *network, ByteBuffer data, Int size) { network->hardwareLock = 1; // Bytes to copy into the buffer Int toMove = MIN(size, NETWORK_BUFFER_MAX_SIZE - network->outputBufferPtr); // Copy data to buffer memcpy(network->outputBuffer + network->outputBufferPtr, data, (UInt) toMove); // Increase buffer size network->outputBufferPtr += toMove; network->hardwareLock = 0; return toMove; } Int network_receive(NetworkCard *network, ByteBuffer data, Int size) { network->hardwareLock = 1; // Bytes to copy into the buffer Int toMove = MIN(size, network->inputBufferPtr); // Data that will remain in the internal buffer Int missingData = MAX(0, network->inputBufferPtr - toMove); // Copy data to buffer memcpy(data, network->inputBuffer, (UInt) toMove); // Move remaining data to the start of the buffer memcpy(network->inputBuffer, network->inputBuffer + toMove, (UInt) missingData); // Size of the buffer is the amount of bytes not moved network->inputBufferPtr = missingData; network->hardwareLock = 0; return toMove; }
C
/* Integrante 1 - Nome:Bruno Camilo ___________________________ RA:16080293 Integrante 2 - Iago Lourenço ________________________________ RA:15610116 Resultados obtidos: Com a resolucao do projeto obtivemos os resultados proposto pelo professor, conseguindo atraves de um programa inicializado junto ao programa obter as n palavras mais frequentes, procurar por uma palavra pedida pelo usuario , criar um arquivo em formato .txt com a tabela de codigos, e por fim com seguimos printar na tela a arvore binaria numa configuracao pedida pelo professor (modo arvore). Projeto básico: 100 % concluído - Obs: ____________________________________ (X) Opcional 1 - Obs: A funcao opcional so cria um novo arquivo e caso o usuario digite -r e -w so faz o -w, nao le um arquivo ja existente. (X) Opcional 2 - Obs: _____________________________________________________ ( ) Opcional 3 - Obs: _____________________________________________________ (X) Opcional 4 - Obs: A arvore printada nao esta completamente igual a do exemplo nos slides. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "item.h" #include "ST.h" #include <sys/time.h> int main(int argc, char *argv[]) { int nPalavra = 0, tamN = 0, i = 2, j = 0, k = 0, nivel = 1, numbuscaPalavraero = 0, aux = 0; struct timeval inicio; char num[50], palavra[50], ch, op, narquivo[50],tipo , tipo2; freq *Freq; Arv *ArvItem; FILE *Arquivo; op = argv[1][1];//pega a operacao requesitada pelo usuario criaArv(&ArvItem); criaLista(&Freq); if(op == 'n' && argc == 2)//printa as n palavras mais frequentes { while(argv[1][i] != '\0')//pega o numero de palavra que irao se repetir { num[j] = argv[1][i]; i++; j++; } num[j] = '\0'; tamN = atoi(num); scanf("%c", &ch); while(!feof(stdin))//vai retirando os caracteres do buffer e formando as palavras { if((ch > 64 && ch <91) || (ch >96 && ch < 123)) { palavra[k] = ch; k++; } else { palavra[k] = '\0'; k = 0; if(strlen(palavra) > 0)// evita de entrar \0 na arvore e na lista { insereArvore(&ArvItem, palavra);//insere a palvra na arvore insereLista(&Freq, palavra);//insere a palavra na lista } } scanf("%c", &ch); if(ch == EOF)//pega a ultima palavra do buffer { palavra[k] = '\0'; k = 0; } } maisFrequente(&Freq);//ordena a lista printfF(Freq, tamN);//printa as n palavras mais frequentes } else if(argc >= 3) { if(argc == 3) { if(op == 'n')//printa as n palavras mais frequentes { while(argv[1][i] != '\0')//pega o numero de palavra que irao se repetir { num[j] = argv[1][i]; i++; j++; } num[j] = '\0'; tamN = atoi(num); tipo = argv[2][1];//ve se e r ou w if(tipo == 'w') { i = 2; j = 0; while(argv[2][i] != '\0')//pega o nome do arquivo a ser salvo { narquivo[j] = argv[2][i]; i++; j++; } strcat(narquivo,".txt"); scanf("%c", &ch); while(!feof(stdin))//vai retirando os charcters do buffer e formando as palavras { if((ch > 64 && ch <91) || (ch >96 && ch < 123)) { palavra[k] = ch; k++; } else { palavra[k] = '\0'; k = 0; if(strlen(palavra) > 0)// evita de entrar \0 na arvore e na lista { insereArvore(&ArvItem, palavra);//insere a palvra na arvore insereLista(&Freq, palavra);//insere a palavra na lista } } scanf("%c", &ch); if(ch == EOF)//pega a ultima palavra do buffer { palavra[k] = '\0'; k = 0; } } maisFrequente(&Freq);//ordena a lista printfF(Freq, tamN);//printa as n palavras mais frequentes Arquivo = fopen(narquivo, "w"); if(Arquivo == NULL) { printf("Nao foi possivel criar o arquivo\n"); } else { salvaTabela(ArvItem, &Arquivo);//escreve a arvore binaria no arquivo; } fclose(Arquivo); } } } if(argc == 4) { if(op == 'n')//printa as n palavras mais frequentes { while(argv[1][i] != '\0')//pega o numero de palavra que irao se repetir { num[j] = argv[1][i]; i++; j++; } num[j] = '\0'; tamN = atoi(num); tipo = argv[2][1];//ve se e r ou w tipo2 = argv[3][1];//ve se e r ou w if(tipo == 'w' || tipo2 == 'w') { if(tipo == 'w' ) aux = 2; else aux = 3; i = 2; j = 0; while(argv[aux][i] != '\0')//pega o nome do arquivo a ser salvo { narquivo[j] = argv[aux][i]; i++; j++; } strcat(narquivo,".txt"); scanf("%c", &ch); while(!feof(stdin))//vai retirando os charcters do buffer e formando as palavras { if((ch > 64 && ch <91) || (ch >96 && ch < 123)) { palavra[k] = ch; k++; } else { palavra[k] = '\0'; k = 0; if(strlen(palavra) > 0)// evita de entrar \0 na arvore e na lista { insereArvore(&ArvItem, palavra);//insere a palvra na arvore insereLista(&Freq, palavra);//insere a palavra na lista } } scanf("%c", &ch); if(ch == EOF)//pega a ultima palavra do buffer { palavra[k] = '\0'; k = 0; } } maisFrequente(&Freq);//ordena a lista printfF(Freq, tamN);//printa as n palavras mais frequentes Arquivo = fopen(narquivo, "w"); if(Arquivo == NULL) { printf("Nao foi possivel criar o arquivo\n"); } else { salvaTabela(ArvItem, &Arquivo);//escreve a arvore binaria no arquivo; } fclose(Arquivo); } } } } else if(op == 's' && argc == 2)//printa uma palavra procurada { scanf("%c", &ch); while(!feof(stdin))//vai retirando os charcters do buffer e formando as palavras { if((ch > 64 && ch <91) || (ch >96 && ch < 123)) { palavra[k] = ch; k++; } else { palavra[k] = '\0'; k = 0; if(strlen(palavra) > 0)// evita de entrar \0 na arvore e na lista { insereArvore(&ArvItem, palavra);//insere a palvra na arvore } } scanf("%c", &ch); if(ch == EOF)//pega a ultima palavra do buffer { palavra[k] = '\0'; k = 0; } } while(argv[1][i] != '\0')//pega a palavra que o usuario deseja consultar { num[j] = argv[1][i]; i++; j++; } num[j] = '\0'; gettimeofday(&inicio,NULL); buscaPalavra(ArvItem, num, nivel, inicio); } else if (op == 'p') { while(argv[1][i] != '\0')//pega o numero de palavra que irao se repetir { num[j] = argv[1][i]; i++; j++; } num[j] = '\0'; scanf("%c", &ch); while(!feof(stdin))//vai retirando os charcters do buffer e formando as palavras { if((ch > 64 && ch <91) || (ch >96 && ch < 123)) { palavra[k] = ch; k++; } else { palavra[k] = '\0'; k = 0; if(strlen(palavra) > 0)// evita de entrar \0 na arvore e na lista { insereArvore(&ArvItem, palavra);//insere a palvra na arvore } } scanf("%c", &ch); if(ch == EOF)//pega a ultima palavra do buffer { palavra[k] = '\0'; k = 0; } } tamN = atoi(num); printArvore(ArvItem, tamN, nivel); } return 0; }
C
#include<stdio.h> int main() { int a[5],i,*p; p=&a[i]; printf("enter any five value:"); for(i=0;i<=4;i++) { scanf("%d",&a[i]); } printf("the value of array and its address is :\n"); for(i=0;i<=4;i++) { printf("the value of a[%d] is %d and address id a[%d] is %u \n",&a[i],p,i); p++; } return 0; }
C
// Lauro Cruz e Souza - RA: 156175 // laurocruzsouza@gmail.com | lauro.souza@students.ic.unicamp.br #include "bico.h" /* Robot control API */ /* Ronda */ unsigned int turn; void ronda(void); void forward(void); void turn90(void); void force_turn(void); /* Segue parede */ void segue_parede(void); void busca_parede_mode(void); void segue_parede_mode(void); /* main function */ void _start(void) { segue_parede(); while(1); } void ronda() { register_proximity_callback(3, 1000, force_turn); register_proximity_callback(4, 1000, force_turn); forward(); } void forward(void) { static unsigned int i = 40; set_motors_speed(40, 40); turn = get_time() + i; add_alarm(turn90, turn); i = (i % 2000) + 40; } void turn90() { unsigned int i; set_motor_speed(0,0); add_alarm(forward, get_time() + 40); } void force_turn(void) { set_time(turn - 1); } void segue_parede(void) { busca_parede_mode(); segue_parede_mode(); } void busca_parede_mode(void) { unsigned int d[16]; unsigned short s0, s1; set_motors_speed(40, 40); read_sonar(3, &s0); read_sonar(4, &s1); while (s0 > 900 && s1 > 900) { read_sonar(3, &s0); read_sonar(4, &s1); } set_motors_speed(0,0); read_sonar(0, &s0); read_sonar(15, &s1); set_motor_speed(1, 6); while ( (s0 > 750 && s1 > 750) || ((s0 - s1 >= 15) || (s1 - s0 >= 15)) ) { read_sonar(0, &s0); read_sonar(15, &s1); } set_motors_speed(0,0); } void segue_parede_mode(void) { unsigned short s0, s15; // register_proximity_callback(3, 900, end_wall); // register_proximity_callback(4, 900, end_wall); do { read_sonar(0, &s0); read_sonar(15, &s15); set_motors_speed(15, 15); if (s0 > s15) { // Vai se afastar ao seguir reto while ((s0 < 500 || s15 < 500)) { read_sonar(0, &s0); read_sonar(15, &s15); } set_motors_speed(5, 0); while (s0 - s15 > 10) { read_sonar(0, &s0); read_sonar(15, &s15); } set_motors_speed(0, 0); } else { // Vai se aproximar ao seguir reto while (s0 > 300 || s15 > 300) { read_sonar(0, &s0); read_sonar(15, &s15); } set_motors_speed(0, 5); while (s15 - s0 > 10) { read_sonar(0, &s0); read_sonar(15, &s15); } set_motors_speed(0, 0); } } while(1); }
C
/* * ===================================================================================== * * Filename: 086.c * * Description: 086 * * Version: 1.0 * Created: 06/19/2013 04:39:04 PM * Revision: none * Compiler: gcc * * Author: Zhang Dongsheng (mars), zhangdongsheng1224@gmail.com * Organization: HANGZHOU DIANZI UNIVERSITY * * ===================================================================================== */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/select.h> int kbhit(void) { struct timeval tv; fd_set read_fd; /* Do not wait at all, not even a microsecond */ tv.tv_sec=0; tv.tv_usec=0; /* Must be done first to initialize read_fd */ FD_ZERO(&read_fd); /* Makes select() ask if input is ready: * 0 is the file descriptor for stdin */ FD_SET(0,&read_fd); /* The first parameter is the number of the * largest file descriptor to check + 1. */ if(select(1, &read_fd,NULL, /*No writes*/NULL, /*No exceptions*/&tv) == -1) return 0; /* An error occured */ /* read_fd now holds a bit map of files that are * readable. We test the entry for the standard * input (file 0). */ if(FD_ISSET(0,&read_fd)) /* Character pending on stdin */ return 1; /* no characters were pending */ return 0; } struct time { int hour; int minute; int second; } t; int main() { FILE *fp; fp = fopen("Time", "r"); fread(&t, sizeof(struct time), 1, fp); while (!kbhit()) { rewind(fp); sleep(1); fread(&t, sizeof(struct time), 1, fp); if (t.second == 59) { t.minute++; if (t.minute == 60) { t.hour++; t.minute = 0; } t.second = 0; } else t.second++; printf("%d:%d:%d\n", t.hour, t.minute, t.second); fp = fopen("Time", "w"); fwrite(&t, sizeof(struct time), 1, fp); fclose(fp); } return 0; }
C
#include <stdio.h> // Build and run program given below. Examine the output. int main(void) { int a = 5, b, c, d, e; b = a++; c = ++a; d = a--; printf("a=%d\nb=%d\nc=%d\nd=%d\ne=%d\n", a, b, c, d, e); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fillit.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hmney <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/06 16:01:47 by hmney #+# #+# */ /* Updated: 2018/11/13 21:47:39 by hmney ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FILLIT_H # define FILLIT_H # include <stdlib.h> # include <unistd.h> # include <fcntl.h> # include "../libft/libft.h" typedef struct s_positions { int x; int y; } t_positions; typedef struct s_tetriminos { t_positions block[4]; char alphabet; struct s_tetriminos *next; } t_tetriminos; int valid_block(char *str, int counter); int valid_tetrimino(char *str); int valid_file(int fd, t_tetriminos **store); t_tetriminos *get_tetrimino(char *str, int counter); t_tetriminos *initialize_tetrimino(t_tetriminos *tetrimino); void store_tetrimino(t_tetriminos **store, t_tetriminos *tetrimino); int list_length(t_tetriminos *begin_list); int calcul_grid(t_tetriminos *store); char **create_grid(int size); void print_tetrimino(char **grid, t_tetriminos *tetrimino, int i, int j); void delete_tetrimino(char **grid, t_tetriminos *tetrimino, int i, int j); int check_place(char **grid, t_tetriminos *tetrimino, int i, int j); int fillit(char **grid, t_tetriminos *tetriminos); void print_result_final(char **grid); void re_fillit(char **grid, int size, t_tetriminos *store); #endif
C
#ifndef CSTRING_H #define CSTRING_H #include <inttypes.h> #include <stdbool.h> #include <stdlib.h> typedef struct cstring String; /* initialize string with \\0 on index 0 */ /* @param init_cap initial capacity of string */ /* @return empty string */ String* cs_init(size_t init_cap); /* create string from raw char pointer */ /* @param raw char array */ /* @return string with data from raw and closed with \\0 */ String* cs_create(const char* raw); /* string length getter */ /* @param self string */ /* @return copy of length field */ size_t cs_length(const String* self); /* string capacity getter */ /* @param self string */ /* @return copy of capacity field */ size_t cs_capacity(const String* self); /* string text getter */ /* @param self string */ /* @return readonly representation of raw text field */ const char* cs_raw(const String* self); /* free string's memory */ /* @param self string */ void cs_free(String* self); /* for access to raw field by index */ /* @param self string */ /* @param index index in char array */ /* @return char by index or -1, if index was out of range */ char cs_get(const String* self, size_t index); /* for access to raw field by index */ /* @param self string */ /* @param item character */ /* @param index index in char array */ void cs_set(const String* self, char item, size_t index); /* copy of string */ /* @param self string */ /* @return cloned string */ String* cs_clone(const String* self); /* compares string text field with raw char array */ /* @param str string */ /* @param value char array */ /* @param ignore_case ignore args case */ /* @return integer that indicates args position in the sort order */ int64_t cs_compare(const String* str, const char* raw, bool ignore_case); /* concatenates string with raw char array */ /* @param str string */ /* @param value char array */ void cs_concat(String* str, const char* value); /* append char to string */ /* @param str string */ /* @param item char */ void cs_append(String* str, char item); /* check if string contains substring */ /* @param str string */ /* @param value char array to seek */ /* @return true if the value occurs within this string, otherwise false */ bool cs_contains(String* str, const char* value); /* find the index of substring in string */ /* @param str string */ /* @param value char array to seek */ /* @return non negative value if string contains substring, otherwise -1 */ int64_t cs_indexof(String* str, const char* value); /* find the index of last substring in string */ /* @param str string */ /* @param value char array to seek */ /* @return non negative value if string contains substring, otherwise -1 */ int64_t cs_indexof_last(String* str, const char* value); /* find the index of the H-th substring */ /* @param str string */ /* @param value char array to seek */ /* @param start_index position number of substring in string */ /* @return non negative value if string contains substring, otherwise -1 */ int64_t cs_indexof_any(String* str, const char* value, size_t start_index); /* insert substring in string by index */ /* @param str string */ /* @param value char array to insertion */ /* @param index position of insertion */ void cs_insert(String* str, const char* value, size_t index); /* remove all elements after index */ /* @param str string */ /* @param index position to remove */ void cs_remove_all(String* str, size_t index); /* replace substring on new substring */ /* @param str string */ /* @param old_value old substring */ /* @param new_value new substring */ /* @return replaced string */ String* cs_replace(String* str, const char* old_value, const char* new_value); /* split string in array of strings by pattern */ /* @param str string */ /* @param pattern array of delimeters */ /* @param container address of string array */ /* @return length of container after split original string */ size_t cs_split(const String* str, const char* pattern, String*** container); /* clear string's data */ /* @param self string */ void cs_clear(String* self); #endif
C
#include "testharness.h" unsigned long x = 0xfffffffffffffffeUL; int main(){ /* CIL used to truncate unsigned long constants to 32-bits, even on * 64-bits machines */ if(sizeof(unsigned long) == 8 && x == 0xfffffffeUL) E(1); SUCCESS; return 0; }
C
#include "test.h" #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <pthread.h> #include <assert.h> char buf[0x400000]; void *tmain(void *arg) { int fd = open("/dev/crc0", O_RDWR); if (fd < 0) { perror("open"); return buf; } if (crcdev_ioctl_set_params(fd, 0xedb88320, 0xffffffff)) { perror("set_params"); return buf; } if (write(fd, buf, sizeof buf) != sizeof buf) { perror("write"); return buf; } uint32_t sum; if (crcdev_ioctl_get_result(fd, &sum)) { perror("get_result"); return buf; } sum ^= 0xffffffff; printf("%08x\n", sum); assert(sum == 0xc8402732); return 0; } #define NTHREADS 8 int main() { gen(buf, sizeof buf); int i; pthread_t thr[NTHREADS]; for (i = 0; i < NTHREADS; i++) { if (pthread_create(&thr[i], NULL, tmain, NULL)) { perror("pthread_create"); return 1; } } for (i = 0; i < NTHREADS; i++) { void *res; if (pthread_join(thr[i], &res)) { perror("pthread_create"); return 1; } } return 0; }
C
#ifndef _STACK_LINKED_LIST_H #define _STACK_LINKED_LIST_H #define MAX_CHARS 1000 #include "single_linked_list.h" #include <stdio.h> typedef struct { SingleLinkedList* list; int top; int largestString; } Stack_Linked_List; Stack_Linked_List* init_stack(size_t); // Integer init function Stack_Linked_List* init_stack_short(); Stack_Linked_List* init_stack_unsigned_short(); Stack_Linked_List* init_stack_int(); Stack_Linked_List* init_stack_unsigned_int(); Stack_Linked_List* init_stack_long(); Stack_Linked_List* init_stack_unsigned_long(); Stack_Linked_List* init_stack_long_long(); Stack_Linked_List* init_stack_unsigned_long_long(); // Float init function Stack_Linked_List* init_stack_float(); Stack_Linked_List* init_stack_double(); Stack_Linked_List* init_stack_long_double(); // Char init function Stack_Linked_List* init_stack_char(); Stack_Linked_List* init_stack_unsigned_char(); // Pointer init function Stack_Linked_List* init_stack_char_ptr(); // **** END: INIT FUNCTIONS *** // // **** START: SETUP FUNCTIONS **** // void setup_copy_value_funcs( SingleLinkedList*, void (*)(SingleLinkedListNode*, void*), void (*)(void*, SingleLinkedListNode*) ); void setup_print_node_value_func( SingleLinkedList*, int (*)(SingleLinkedListNode*) ); // **** END: SETUP FUNCTIONS **** // void push(Stack_Linked_List*, void*); void* pop(Stack_Linked_List*, void*); void print_stack(Stack_Linked_List*); void free_stack(Stack_Linked_List**); #endif
C
/* prog4_3, ϥprintf() */ #include <stdio.h> #include <stdlib.h> int main(void) { int num=25; printf("\"%d%%ǥͨӦۤpdax\"\n",num); /* LXr */ system("pause"); return 0; }
C
/* * TWI.c * * Created: 2/20/2021 8:57:13 PM * Author: karim */ #include "TWI.h" void TWI_MASTER_Init(void) { TWBR = 0x0C;/*Prescaler of the clock*/ SET_BIT(TWCR, TWEN);/*Enable Two wire Interface*/ } void TWI_SLAVE_Init(void) { /*Set address for slave*/ TWAR = (0x01 << 1); /*Disable general call*/ SET_BIT(TWCR, TWEA);/*Slave enable acknowledgment*/ SET_BIT(TWCR, TWEN);/*Enable Two wire Interface*/ } void TWI_START_Condition(void) { SET_BIT(TWCR, TWSTA);/*Start condition*/ SET_BIT(TWCR, TWINT);/*Hard set for flag waiting for dominant bit (0)*/ while(GET_BIT(TWCR, TWINT) != 0);/*When start condition finished*/ while((TWSR & 0xF8) != START_ACK);/*Waiting for master send start condition*/ } void TWI_REPEATED_Condition(void) { TWCR = (1 << 7) | (1 << 5) | (1 << 2); SET_BIT(TWCR, TWINT);/*Hard set for flag waiting for dominant bit (0)*/ while(GET_BIT(TWCR, TWINT) != 0);/*When start condition finished*/ while((TWSR & 0xF8) != REP_START_ACK);/*Waiting for master send start condition*/ } void TWI_SLAVE_WRITE_Data(uint8_t address) { TWDR = (address << 1) | (0x00);/*Send address of chosen slave, Write*/ TWCR = (1 << 7) | (1 << 2); while(GET_BIT(TWCR, TWINT) != 0);/*When start condition finished*/ while((TWSR & 0xF8) != SLAVE_ADD_AND_WR_ACK);/*Waiting for slave send start ACK*/ } void TWI_SLAVE_READ_Data(uint8_t address) { TWDR = (address << 1) | (0x01);/*Send address of chosen slave, Read*/ TWCR = (1 << 7) | (1 << 2); while(GET_BIT(TWCR, TWINT) != 0);/*When start condition finished*/ while((TWSR & 0xF8) != SLAVE_ADD_AND_RD_ACK);/*Waiting for slave send start ACK*/ } void TWI_TRANSMIT_Data(uint8_t data) { TWDR = data; TWCR = (1 << 7) | (1 << 2); while(GET_BIT(TWCR, TWINT) != 0);/*When start condition finished*/ while((TWSR & 0xF8) != WR_BYTE_ACK);/*Waiting for slave send start ACK*/ } uint8_t TWI_RECEIVE_Data(void) { TWCR = (1 << 7) | (1 << 2); while(GET_BIT(TWCR, TWINT) != 0);/*When start condition finished*/ while((TWSR & 0xF8) != RD_BYTE_WITH_ACK);/*Waiting for slave send start ACK*/ return TWDR; } void TWI_STOP_Condition(void) { SET_BIT(TWCR, TWSTO);/*Send stop condition*/ }
C
#include <stdio.h> int longitud(char c[]); int cuenta_y_sustitucion(char c[]); void main() { char condicion; char cadena[50]={'\0'}; puts("\t\t/*Programa encargado de tratar con cadenas de caracteres*/"); puts("Cuenta los caracteres, cuenta las palabras de 4 letras \ y sustituye las palabras de 4 letras por 4 asteriscos"); do { printf("\nProporcioname un cadena de texto (max 50 caracteres): "); gets(cadena); printf("Caracteres: %d\n", longitud(cadena)); printf("Palabras de 4 letras: %d\n", cuenta_y_sustitucion(cadena)); printf("Sustitucion: %s\n\n", cadena); do { printf("Otra? Si[s] No[n]: "); scanf("%c", &condicion); fflush(stdin); //limpia los datos residuales de entrada }while(condicion!='s' && condicion!='n'); }while(condicion != 'n'); } int longitud(char c[]) { int i; for(i=0; c[i]!='\0'; i++); return i; } int cuenta_y_sustitucion(char c[]) { int cont4=0, n=0; for(int i=0; c[i] != '\0'; i++) { if(c[i] != ' ') { if(isalpha(c[i])) cont4++; else cont4=0; } else cont4=0; if(cont4 == 4 && (c[i+1] == ' ' || c[i+1] == '\0')) { //n = cuenta palabra de 4 letras n++; //sustituye palabras de 4 letras por (****) for(int j=0; j<4; j++) c[i+j-3]='*'; } } return n; }
C
#include"sender.h" frame senderQueue[WINDOW_SIZE]; int nStartDataIndex; void runSender(); void createData(int count); int checkACK(); int bInitTimer; clock_t initStart, start, finish; CRITICAL_SECTION g_cs; void createSender() { InitializeCriticalSection(&g_cs); initStart = clock(); createData(WINDOW_SIZE); while (TRUE) { start = clock(); runSender(); finish = clock(); while (finish - start < TIME_OUT) { Sleep(SEND_INTERVAL); finish = clock(); } printf("-------------------TIME OUT---------------\n"); } } void receiveACK(int nACKIndex) { if (!checkACK()) { printf("ACK : %d is loss\n", nACKIndex); } else { printf("ACK : %d\n", nACKIndex); EnterCriticalSection(&g_cs); nStartDataIndex = nACKIndex; bInitTimer = TRUE; LeaveCriticalSection(&g_cs); } } void createData(int count) { for (int i = 0; i < count; i++) { frame newData; newData.header = i; senderQueue[i] = newData; } } void runSender() { EnterCriticalSection(&g_cs); int nStartIndex = nStartDataIndex; LeaveCriticalSection(&g_cs); for (int i = 0; i < WINDOW_SIZE; i++) { printf("%-10s %d data \n", "SENDER : ", nStartIndex); sendDataByGoBackN(senderQueue[nStartIndex]); nStartIndex = ++nStartIndex % WINDOW_SIZE; Sleep(SEND_INTERVAL); if (finish - initStart > TOTAL_RUN_TIME) { DeleteCriticalSection(&g_cs); exit(0); } EnterCriticalSection(&g_cs); if (bInitTimer) { bInitTimer = FALSE; i = 0; start = finish = clock(); } LeaveCriticalSection(&g_cs); } } int checkACK() { int num = rand() % 100; if (num < ERROR_RATIO) return FALSE; return TRUE; }
C
#include <stdio.h> union mem { float x; // 4byte unsigned char c[4]; //4byte }; int main(void) { union mem A; union mem B; A.x = -12.34; printf("%f\n",A.x); printf("%x %x %x %x\n",A.c[0], A.c[1], A.c[2], A.c[3]); printf("=======================\n"); B.c[0] = A.c[0]; B.c[1] = A.c[1]; B.c[2] = A.c[2]; B.c[3] = A.c[3]; printf("%x %x %x %x\n",B.c[0], B.c[1], B.c[2], B.c[3]); printf("%f\n",B.x); return 0; }
C
#include "lists.h" /** *sum_listint - Function returns the sum of all the data (n) of linked list. *@head: points to first node *Return: 0 is head is empty. */ int sum_listint(listint_t *head) { listint_t *temp_head = head; unsigned int sum = 0, count; for (count = 0; temp_head != NULL; count++) { sum = sum + temp_head->n; temp_head = temp_head->next; } return (sum); }
C
/* ** EPITECH PROJECT, 2019 ** NWP_mychap ** File description: ** init */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "handshake/handshake.h" #include "socket/socket.h" static char *get_by_key(arguments_t **args, char *key) { for (size_t args_index = 0; args[args_index] != NULL; args_index++) if (strcmp(args[args_index]->name, key) == 0) return args[args_index]->value; return NULL; } static int error_handling(char *response) { if (!response) { printf("KO\n"); return 1; } if (strcmp(response, ERROR_MSG) == 0) { printf("KO\n"); return 1; } if (strcmp(response, KO_MSG) == 0) { printf("KO\n"); return 1; } return 0; } int send_next_step( raw_socket_t *sock, int port, char *key ) { char *response; response = send_socket(port, sock, sha256(key)); if (error_handling(response)) return 0; printf("Secret: '%s'\n", response); return 1; } int init_handshake(arguments_t **args) { char *target = get_by_key(args, "target"); int port = atoi(get_by_key(args, "port")); char *password = get_by_key(args, "password"); char *response; char *key; raw_socket_t *sock = crate_raw_socket(); if (!sock) return 0; fill_server_info(&sock->server, target, port); response = send_socket(port, sock, PHASE1_MESG); if (error_handling(response)) return 0; key = calloc(NONCE_LENGTH + strlen(password), sizeof(char)); strcpy(key, response); strcat(key, password); return send_next_step(sock, port, key); }
C
#include <stdio.h> #include "general/GE_state.h" #include "general/GE_error.h" #include "general/GE_file_buffer.h" /* * prologue: Deal with all args at the program start and in consequence set the * programs initial state. */ int prologue(int argc, char *argv[], F_Buf **io, int st_prg) { char c; int files = 0; while (--argc > 0) { if ((*++argv)[0] == '-') { while ((c = *++argv[0])) { switch (c) { case 'c': state_unset(st_prg, DECOMPRESS); state_set(st_prg, COMPRESS); break; case 'f': state_set(st_prg, FORCE); break; case 'm': state_set(st_prg, MONO); break; case 'p': state_set(st_prg, PRINT); break; case 'v': state_set(st_prg, VERBOSE); break; case 'x': state_unset(st_prg, COMPRESS); state_set(st_prg, DECOMPRESS); break; default : break; } } --argc, ++argv; if (!argc && is_set(st_prg, DECOMPRESS)) { fprintf(stdout, "Please provide an archive name and at least one file to compress.\n"); return state_set(st_prg, ESC); } else if (!argc && is_set(st_prg, DECOMPRESS)) { fprintf(stdout, "Please provide an archive to decompress.\n"); return state_set(st_prg, ESC); } /* Open the first file for writing as an archive */ if (argc > 1 && is_set(st_prg, COMPRESS)) { if (GE_buffer_fopen_array(io, *argv, "wb", st_prg)) return state_set(st_prg, ESC); else --argc, ++argv, ++files; } else if (is_set(st_prg, COMPRESS)) { fprintf(stdout, "Please provide an archive name along with the files to be compressed.\n"); return state_set(st_prg, ESC); } } /* Open a readable file for every argument following the options given * and the initial write file */ if (argc && is_set(st_prg, COMPRESS)) { if (GE_buffer_fopen_array(io, *argv, "r", st_prg)) return state_set(st_prg, ESC); else ++files; } /* Open a file with text write enabled, to write the decompressed data * too */ if (argc && is_set(st_prg, DECOMPRESS)) { if (argc == 1) { if (GE_buffer_fopen_array(io, *argv, "rb", st_prg)) return state_set(st_prg, ESC); else ++files; } else { fprintf(stdout, "Only one file expected for decompression operation.\n"); return state_set(st_prg, ESC); } } } return st_prg; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <dirent.h> #include <string.h> #define BUFFSIZ 4096 int main (int argc, char *argv[]){ int status = EXIT_FAILURE; if (argc > 3){ printf("Too many arguments!\nusage: ./treecopy <sourcefile> <targetfile>"); } if (argc < 3){ printf("Not enough arguments!\nusage: ./treecopy <sourcefile> <targetfile>"); } int rfile = open(argv[1], O_RDONLY); //open first file to read if (rfile<0){ fprintf(stderr, "unable to open %s: %s\n", argv[1], strerror(errno)); //goto clean; exit(1); } int wfile = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC, 0666); if (wfile<0){ fprintf(stderr, "unable to open %s: %s\n", argv[2], strerror(errno)); } char buffer [BUFFSIZ]; //create buffer size 4096 int rread; int wwrite; int bytes = 0; while((rread = read(rfile, buffer, BUFFSIZ)) > 0){ int nwritten = 0; while (nwritten != rread){ wwrite = write(wfile, buffer + nwritten, rread - nwritten); if (wwrite <0){ fprintf(stderr, "unable to open %s: %s\n", argv[1], strerror(errno)); //goto clean; exit(2); } nwritten += wwrite; bytes += wwrite; //count # bytes copied } } close(rfile); close(wfile); printf("copied %d bytes from %s to %s\n", bytes, argv[1], argv[2]); //return 0; exit(status); }
C
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <stdbool.h> #include <sys/types.h> #include <sys/wait.h> #include <signal.h> #include "estructuras.h" #include "comunicacion.c" #include "operaciones.c" char *segmentoMemoria; struct globales *vglobales; /* generarRandom Funcion que genera ints aleatorios entre inicio y fin. Puede ser utilizada para la generacion de la dificultad (0 a 100) o para el tiempo aleatorio que espera cada Meeseek antes de decidir si puede completar la tarea o no (500 a 5000; en milisegundos). */ int generarRandom(int inicio, int fin){ return (rand() % (fin - inicio + 1)) + inicio; } char* leerSolicitud(){ char* tarea = malloc(sizeof(char)*1000); printf("Que necesita que haga Mr. Meeseeks? "); scanf("%[^\n]s", tarea); getchar(); printf("Mr. Meeseeks hara: %s\n",tarea); return tarea; } int leerDificultad(){ int dificultad; printf("Ingrese la dificultad de su solicitud (100:trivial, 0:imposible, -1:No sabe): "); scanf("%d", &dificultad); getchar(); if(dificultad == -1){ dificultad = generarRandom(0, 100); printf("Mr. Meeseeks dice que la dificultad es: %d\n", dificultad); }else { printf("Mr. Meeseeks hara la tarea con dificultad: %d\n", dificultad); } return dificultad; } double diluirDificultad(double dificultad, int numHIjos){ if(dificultad == 0){ return dificultad; } else{ double temp = generarRandom(1, (int) dificultad); //Random no mayor a la dificultad double reduc = temp * (dificultad / generarRandom(350,550)); //Se reduce a una milesima dictada por la dificultad double extra = (reduc * (numHIjos)); return dificultad + reduc + extra; } } bool intentarTarea(double dificultad){ int segundos = generarRandom(1, 5); //Para dormir entre 1s y 5s //El Mr. Meeseeks 'intenta' la tarea por un tiempo sleep(segundos); if(dificultad <= 85.01){ return false; //Necesita ayuda de otros Mr. Meeseeks } else{ return true; //Logro resolver la tarea facil } } int obtenerHijosPorCrear(double dificultad){ if (dificultad >= 0 & dificultad <= 45){ return generarRandom(1, 5); }else if(dificultad > 45 & dificultad <= 85){ //Crea entre uno y dos Meeseeks return generarRandom(1, 2); }else{ return 0; } } char* iniciar(char* tarea, double dificultad){ pid_t pid; vglobales = compartirGlobales(segmentoMemoria, vglobales); sem_init(&vglobales->sem_concluido, 1, 1); sem_init(&vglobales->sem_caos_planetario, 1, 1); int N = 1; int instancia = 1; int temp_instancia; //Para asignar la instancia a los hijos int primerMeeseek; int* pipe_a_padre; int* pipes_a_hijos; clock_t inicio = clock(); double tiempoTotal = 0.0; modificarConcluido(vglobales, 0); //concluido = false pid = fork(); //Primer Meeseek que crea la caja if(pid == 0){ primerMeeseek = getpid(); setpgid(0,0); printf("Hi I'm Mr Meeseeks! Look at Meeeee. (pid: %d, ppid: %d, N: %d, i: %d)\n", getpid(), getppid(), N, instancia ); while(true){ if(intentarTarea(dificultad)){ //Resuelve y notifica al padre para matar a los hijos if(vglobales->concluido == 0){ /*printf("HE FINALIZADO (pid: %d, ppid: %d, N: %d, i: %d) \n", //Temporal getpid(), getppid(), N, instancia );*/ modificarInformacionSolucionador(getpid(), getppid(), N, instancia, vglobales); modificarConcluido(vglobales, 1); //concluido = true } Reset_Color(); break; }else{ //Crea hijos int numHijos = obtenerHijosPorCrear(dificultad); N++; //Incrementa el nivel if(vglobales->instanciasFinalizadas >= 9000){ modificarCaos(vglobales, 1); //Se declara caos planetario } pipes_a_hijos = malloc(sizeof(int)*numHijos); for(int i = 0; i < numHijos; i++){ temp_instancia = i + 1; int* pipe_temp = malloc(sizeof(int)*2); pipe(pipe_temp); pid = fork(); if(pid == 0){ //Hace lo que hacen los nuevos Meeseeks vglobales->instanciasFinalizadas++; srand(time(NULL) ^ (getpid()<<16)); //Nueva semilla basada en el pid instancia = temp_instancia; printf( "Hi I'm Mr Meeseeks! Look at Meeeee. (pid: %d, ppid: %d, N: %d, i: %d)\n", getpid(), getppid(), N, instancia ); //printf("Meeseeks (pid: %d) asignando pipe_a_padre\n", getpid()); pipe_a_padre = pipe_temp; //Leer mensaje desde el pipe (la tarea) char* mensaje = malloc(sizeof(char)*500); close(pipe_a_padre[1]); read(pipe_a_padre[0], mensaje, sizeof(mensaje)); close(pipe_a_padre[0]); dificultad = diluirDificultad(dificultad, numHijos); break; }else{ //Guarda el pipe al hijo pipes_a_hijos[i] = pipe_temp; //Escribir la tarea a pipe_temp close(pipe_temp[0]); write(pipe_temp[1], tarea, sizeof(tarea)); close(pipe_temp[1]); } } if(pid != 0){ while (wait(NULL) > 0){} break; } } } } else{ //Codigo de proceso Meeseeks Box original, aqui se cuentan los tiempos de ejecucion while(vglobales->concluido == 0 && vglobales->caos_planetario == 0){} tiempoTotal = (double)(clock() - inicio) / CLOCKS_PER_SEC; kill(-pid, SIGTERM); sleep(2); kill(-pid, SIGKILL); wait(NULL); //Se fija si ha concluido o si hay caos if(vglobales->caos_planetario == 1){ printf("ALERTA! SE HA DECLARADO CAOS PLANETARIO\n"); impFailedTask(); }else{ impCloud( vglobales->pid, vglobales->ppid, vglobales->N, vglobales->i ); impMeeseek(); Reset_Color(); } printf( "The %d Mr Meeseeks lasted %f seconds\n", vglobales->instanciasFinalizadas, tiempoTotal ); //Escribe el mensaje que va a contener la bitacora char* mensaje = malloc(sizeof(char)*1000); char* dif = malloc(sizeof(char)*1000); strcat(mensaje, "Consulta Textual: "); strcat(mensaje, tarea); strcat(mensaje, ", Dificultad: "); snprintf(dif, 50, "%f", dificultad); strcat(mensaje, dif); strcat(mensaje, "\n"); return mensaje; } }
C
#include <stdio.h> int main() { int a,b,i,r,v,num; scanf("%d %d",&a,&b); for(i=a+1;i<b;++i) { v=i; num=0; while(v!=0) { r=(v%10); num+=r*r*r; v/=10; } if(i==num) { printf("%d ",i); } } return 0; }
C
#include "dnet_sgx_utils.h" #include "tree.h" #include "utils.h" #include "data.h" /* void change_leaves(tree *t, char *leaf_list) { list *llist = get_paths(leaf_list); char **leaves = (char **)list_to_array(llist); int n = llist->size; int i, j; int found = 0; for (i = 0; i < t->n; ++i) { t->leaf[i] = 0; for (j = 0; j < n; ++j) { if (0 == strcmp(t->name[i], leaves[j])) { t->leaf[i] = 1; ++found; break; } } } #ifdef DNET_SGX_DEBUG printf("Found %d leaves.\n", found); #endif } */ float get_hierarchy_probability(float *x, tree *hier, int c, int stride) { float p = 1; while (c >= 0) { p = p * x[c * stride]; c = hier->parent[c]; } return p; } void hierarchy_predictions(float *predictions, int n, tree *hier, int only_leaves, int stride) { int j; for (j = 0; j < n; ++j) { int parent = hier->parent[j]; if (parent >= 0) { predictions[j * stride] *= predictions[parent * stride]; } } if (only_leaves) { for (j = 0; j < n; ++j) { if (!hier->leaf[j]) predictions[j * stride] = 0; } } } int hierarchy_top_prediction(float *predictions, tree *hier, float thresh, int stride) { float p = 1; int group = 0; int i; while (1) { float max = 0; int max_i = 0; for (i = 0; i < hier->group_size[group]; ++i) { int index = i + hier->group_offset[group]; float val = predictions[(i + hier->group_offset[group]) * stride]; if (val > max) { max_i = index; max = val; } } if (p * max > thresh) { p = p * max; group = hier->child[max_i]; if (hier->child[max_i] < 0) return max_i; } else if (group == 0) { return max_i; } else { return hier->parent[hier->group_offset[group]]; } } return 0; }
C
#include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <float.h> #include <math.h> #include <string.h> #include <assert.h> #include "matrix.h" #define MAX(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a > _b ? _a : _b; }) #define MIN(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a < _b ? _a : _b; }) double ** init_data(unsigned int m, unsigned int n) { double **data = (double **)malloc(sizeof(double *) * m); for (int i = 0; i < m; i++) { data[i] = (double *)malloc(sizeof(double) * n); } return data; } matrix * matrix_create_empty(unsigned int m, unsigned int n) { matrix *M = (matrix *)malloc(sizeof(matrix)); matrix s = (matrix){NULL, m, n}; memcpy(M, &s, sizeof(matrix)); M->data = init_data(m, n); return M; } matrix * matrix_create_va(unsigned int m, unsigned int n, ...) { va_list ap; matrix *M = NULL; if ((M = matrix_create_empty(m, n))) { va_start(ap, n); for (unsigned int i = 0; i < m; i++) { for (unsigned int j = 0; j < n; j++) { M->data[i][j] = va_arg(ap, double); } } va_end(ap); } return M; } matrix * matrix_create_zeros(unsigned int m, unsigned int n) { matrix *M = NULL; if ((M = matrix_create_empty(m, n))) { matrix_fill(M, 0); } return M; } matrix * matrix_create_ones(unsigned int m, unsigned int n) { matrix *M = NULL; if ((M = matrix_create_empty(m, n))) { matrix_fill(M, 1); } return M; } matrix * matrix_copy(const matrix *A) { matrix *B = matrix_create_empty(A->m, A->n); for (int i = 0; i < B->m; i++) { for (int j = 0; j < B->n; j++) { B->data[i][j] = A->data[i][j]; } } return B; } matrix * matrix_mult_scalar(const matrix *A, double scalar) { matrix *B = matrix_copy(A); matrix_mult_scalar_inplace(B, scalar); return B; } matrix * matrix_add(const matrix *A, const matrix *B) { if (!matrix_same_order(A, B)) { return NULL; } matrix *C = matrix_copy(A); matrix_add_inplace(C, B); return C; } matrix * matrix_sub(const matrix *A, const matrix *B) { if (!matrix_same_order(A, B)) { return NULL; } matrix *C = matrix_copy(A); matrix_sub_inplace(C, B); return C; } matrix * matrix_mult(const matrix *A, const matrix *B) { if (!matrix_can_mult(A, B)) { return NULL; } matrix *C = matrix_create_zeros(A->m, B->n); for (int i = 0; i < C->m; i++) { for (int j = 0; j < C->n; j++) { for (int k = 0; k < A->n; k++) { C->data[i][j] += A->data[i][k] * B->data[k][j]; } } } return C; } void matrix_mult_scalar_inplace(matrix *A, double scalar) { for (int i = 0; i < A->m; i++) { for (int j = 0; j < A->n; j++) { A->data[i][j] *= scalar; } } } void matrix_add_inplace(matrix *A, const matrix *B) { assert(matrix_same_order(A, B)); if (!matrix_same_order(A, B)) { return; } for (int i = 0; i < A->m; i++) { for (int j = 0; j < A->n; j++) { A->data[i][j] += B->data[i][j]; } } } void matrix_sub_inplace(matrix *A, const matrix *B) { assert(matrix_same_order(A, B)); if (!matrix_same_order(A, B)) { return; } for (int i = 0; i < A->m; i++) { for (int j = 0; j < A->n; j++) { A->data[i][j] -= B->data[i][j]; } } } int matrix_same_order(const matrix *A, const matrix *B) { return A->m == B->m && A->n == B->n; } int matrix_can_mult(const matrix *A, const matrix *B) { return A->n == B->m; } int matrix_is_square(const matrix *A) { return A->m == A->n; } int matrix_eq(const matrix *A, const matrix *B) { if (A == B) { return 1; } if (!matrix_same_order(A, B)) { return 0; } for (int i = 0; i < A->m; i++) { for (int j = 0; j < A->n; j++) { if (fabs(A->data[i][j] - B->data[i][j]) > DBL_EPSILON) { return 0; } } } return 1; } int matrix_is_singular(const matrix *A) { return fabs(matrix_determinant(A)) <= DBL_EPSILON; } matrix * matrix_transpose(const matrix *A) { matrix *T = matrix_create_empty(A->n, A->m); for (int i = 0; i < T->m; i++) { for (int j = 0; j < T->n; j++) { T->data[i][j] = A->data[j][i]; } } return T; } matrix * matrix_diagonal(const matrix *A) { int dim = MIN(A->m, A->n); matrix *diagonal = matrix_create_empty(1, dim); for (int i = 0; i < dim; i++) { diagonal->data[0][i] = A->data[i][i]; } return diagonal; } matrix * matrix_row(const matrix *A, unsigned int r) { matrix *row = matrix_create_empty(1, A->n); for (int i = 0; i < A->n; i++) { row->data[0][i] = A->data[r][i]; } return row; } matrix * matrix_col(const matrix *A, unsigned int c) { matrix *col = matrix_create_empty(A->m, 1); for (int i = 0; i < A->m; i++) { col->data[i][0] = A->data[i][c]; } return col; } double matrix_minor(const matrix *A, unsigned int i, unsigned int j) { if (!matrix_is_square(A) || A->n <= 1 || i >= A->m || j >= A->n) { return 0; } matrix *B = matrix_delete_row(A, i); matrix *C = matrix_delete_col(B, j); double retVal = matrix_determinant(C); matrix_free(B); matrix_free(C); return retVal; } double matrix_cofactor(const matrix *A, unsigned int i, unsigned int j) { double minor = matrix_minor(A, i, j); int isEven = ((i + j) % 2 == 0); double multiplier = isEven ? 1.0 : -1.0; return multiplier * minor; } double matrix_determinant_1(const matrix *A) { return A->data[0][0]; } double matrix_determinant_2(const matrix *A) { double a = A->data[0][0]; double b = A->data[0][1]; double c = A->data[1][0]; double d = A->data[1][1]; return a * d - b * c; } double matrix_determinant_3(const matrix *A) { double a = A->data[0][0]; double b = A->data[0][1]; double c = A->data[0][2]; double d = A->data[1][0]; double e = A->data[1][1]; double f = A->data[1][2]; double g = A->data[2][0]; double h = A->data[2][1]; double i = A->data[2][2]; return ( a * e * i + b * f * g + c * d * h - c * e * g - b * d * i - a * f * h ); } double matrix_determinant_smaller_cases(const matrix *A) { double (*det)(const matrix *) = NULL; switch (A->n) { case 1: det = matrix_determinant_1; break; case 2: det = matrix_determinant_2; break; case 3: det = matrix_determinant_3; break; } return det(A); } double matrix_determinant_n(const matrix *A) { if (A->n <= 3) { return matrix_determinant_smaller_cases(A); } double acc = 0; int j = 0; for (int i = 0; i < A->n; i++) { double v = A->data[i][j]; if (v == 0) { continue; } acc += v * matrix_cofactor(A, i, j); } return acc; } double matrix_determinant(const matrix *A) { if (!matrix_is_square(A)) { return 0; } return matrix_determinant_n(A); } double matrix_norm_1(const matrix *A) { double max_sum = 0; for (int j = 0; j < A->n; j++) { double sum = 0; for (int i = 0; i < A->m; i++) { sum += fabs(A->data[i][j]); } if (sum > max_sum) { max_sum = sum; } } return max_sum; } double matrix_norm_inf(const matrix *A) { double max_sum = 0; for (int i = 0; i < A->m; i++) { double sum = 0; for (int j = 0; j < A->n; j++) { sum += fabs(A->data[i][j]); } if (sum > max_sum) { max_sum = sum; } } return max_sum; } matrix * matrix_delete_col(const matrix *A, unsigned int col) { if (col >= A->n) { return NULL; } matrix *B = matrix_create_empty(A->m, A->n - 1); for (int ai = 0, bi = 0; ai < A->m; ai++) { for (int aj = 0, bj = 0; aj < A->n; aj++) { if (aj == col) { continue; } B->data[bi][bj] = A->data[ai][aj]; bj++; } bi++; } return B; } matrix * matrix_delete_row(const matrix *A, unsigned int row) { if (row >= A->m) { return NULL; } matrix *B = matrix_create_empty(A->m - 1, A->n); for (int ai = 0, bi = 0; ai < A->m; ai++) { if (ai == row) { continue; } for (int aj = 0, bj = 0; aj < A->n; aj++) { B->data[bi][bj] = A->data[ai][aj]; bj++; } bi++; } return B; } void matrix_swap_col_inplace(matrix *A, unsigned int c1, unsigned int c2) { if (c1 >= A->n || c2 >= A->n || c1 == c2) { return; } for (int i = 0; i < A->n; i++) { double temp = A->data[i][c1]; A->data[i][c1] = A->data[i][c2]; A->data[i][c2] = temp; } } void matrix_swap_row_inplace(matrix *A, unsigned int r1, unsigned int r2) { if (r1 >= A->m || r2 >= A->m || r1 == r2) { return; } for (int i = 0; i < A->n; i++) { double temp = A->data[r1][i]; A->data[r1][i] = A->data[r2][i]; A->data[r2][i] = temp; } } void matrix_map(matrix *A, double (*f)(double)) { for (int i = 0; i < A->m; i++) { for (int j = 0; j < A->n; j++) { A->data[i][j] = f(A->data[i][j]); } } } void matrix_fill(matrix *A, double v) { for (int i = 0; i < A->m; i++) { for (int j = 0; j < A->n; j++) { A->data[i][j] = v; } } } void matrix_print(const matrix *M) { for (int i = 0; i < M->m; i++) { for (int j = 0; j < M->n; j++) { printf("%lf\t", M->data[i][j]); } printf("\n"); } } void matrix_free(matrix *M) { for (int i = 0; i < M->m; i++) { free(M->data[i]); } free(M->data); free(M); }
C
#include <stdio.h> #include <stdlib.h> #include "datastructure.h" #include "datetime.h" #include "tools.h" #include "calendar.h" #include "menu.h" #define BUF 255 int main() { int Anz = 7; // int Ende = 1; char Menu[50] = "TerminVerwaltung V 0.2"; char *Menupunkte[] = {"Neuen Termin anlegen", "Termin bearbeiten", "Termin loeschen", "Termin suchen", "Termine sortieren", "Termine auflisten", "Programm beenden"}; //TDate Date; //TTime Time; //char Input[20]; do { clearScreen(); int Wahl = getMenu( Menu , Menupunkte , Anz); printf("ToDo:"); switch(Wahl) { case 1: createAppointment(); break; case 2: editAppointment(); break; case 3: deleteAppointment(); break; case 4: searchAppointment(); break; case 5: sortCalendar(); break; case 6: listCalendar(); break; // case 7: printf("Das Programm wird beendet"); // Ende = 0; break; default: printf("Falsche Wahl\n\n"); } } while (askAgain("Moechten Sie noch einmal (j//n) ? ")); return 0; }
C
/* * Assignment 3 CS 344 Summer 2015 * Create a program to mimic the functionality of linux system command. * Design a shell. * */ #define _POSIX_C_SOURCE 200809L #define _BSD_SOURCE #define MAX_CMD_LEN 200 #define MAX_ENAME 133 #define block_size 1024 #include <sys/stat.h> #include <dirent.h> #include <sys/types.h> #include <stdio.h> #include <math.h> #include <signal.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include "curr_time.h" //static void outputError(Boolean useErr, int err, Boolean flushStdout, const char *format, va_list ap); //static void terminate(Boolean useExit3); //void errExit(const char *format, ...); void printWaitStatus(const char *msg, int status); int theSystem(const char *command); char **parser(const char *input); int changeDir(char **parsedArgs); void listDir(); void helperMayo(); void launchProg(char** parsedArgs); struct pipe { int pIn[2]; int pOut[2]; }; int main(int argc, char *argv[]) { char str[MAX_CMD_LEN]; /* Command to be executed by theSystem() */ int status; /* Status return from system() */ for (;;) { /* Read and execute a shell command */ char cwd[block_size]; if (getcwd(cwd, sizeof(cwd)) != NULL) fprintf(stdout, "%s ", cwd); printf("TELL ME WHAT TO DO: \n"); fflush(stdout); if (fgets(str, MAX_CMD_LEN, stdin) == NULL) break; /* end-of-file */ if(strcmp(str, "exit") == 0) { //exit out exit(EXIT_SUCCESS); } if(strcmp(str, " ") != 0) { status = theSystem(str); } printf("system() returned: status=0x%04x (%d,%d)\n", (unsigned int) status, status >> 8, status & 0xff); if (status == -1) { //errExit("system"); printf("The errExit function was simplified."); exit(EXIT_FAILURE); } else { if (WIFEXITED(status) && WEXITSTATUS(status) == 127) printf("(Probably) could not invoke shell\n"); else /* Shell successfully executed command */ printWaitStatus(NULL, status); } } exit(EXIT_SUCCESS); } int theSystem(const char *command) { sigset_t blockMask, origMask; struct sigaction saIgnore, saOrigQuit, saOrigInt, saDefault; pid_t childPid; int status, savedErrno; char ** parsedLine; //the parsed command if (command == NULL) /* Is a shell available? */ return system(":") == 0; /* The parent process (the caller of system()) blocks SIGCHLD and ignore SIGINT and SIGQUIT while the child is executing. We must change the signal settings prior to forking, to avoid possible race conditions. This means that we must undo the effects of the following in the child after fork(). */ sigemptyset(&blockMask); /* Block SIGCHLD */ sigaddset(&blockMask, SIGCHLD); sigprocmask(SIG_BLOCK, &blockMask, &origMask); saIgnore.sa_handler = SIG_IGN; /* Ignore SIGINT and SIGQUIT */ saIgnore.sa_flags = 0; sigemptyset(&saIgnore.sa_mask); sigaction(SIGINT, &saIgnore, &saOrigInt); sigaction(SIGQUIT, &saIgnore, &saOrigQuit); parsedLine = parser(command); // printf("[%s] \n", parsedLine[0]); if(strcmp(parsedLine[0],"cd") == 0) { changeDir(parsedLine); } else if(strcmp(parsedLine[0],"help\n") == 0) { helperMayo(); } else if(strcmp(parsedLine[0],"ls\n") == 0) { // printf("ls reads"); listDir(); } else if(strcmp(parsedLine[0],"exit\n") == 0) { printf("killing children...\n"); kill(childPid, SIGTERM); return 0; } else { switch (childPid = fork()) { case -1: /* fork() failed */ status = -1; break; /* Carry on to reset signal attributes */ case 0: /* Child: exec command */ /* We ignore possible error returns because the only specified error is for a failed exec(), and because errors in these calls can't affect the caller of system() (which is a separate process) */ saDefault.sa_handler = SIG_DFL; saDefault.sa_flags = 0; sigemptyset(&saDefault.sa_mask); if (saOrigInt.sa_handler != SIG_IGN) sigaction(SIGINT, &saDefault, NULL); if (saOrigQuit.sa_handler != SIG_IGN) sigaction(SIGQUIT, &saDefault, NULL); sigprocmask(SIG_SETMASK, &origMask, NULL); launchProg(parsedLine); // execl("/bin/sh", "sh", "-c", command, (char *) NULL); _exit(127); /* We could not exec the shell */ default: /* Parent: wait for our child to terminate */ /* We must use waitpid() for this task; using wait() could inadvertently collect the status of one of the caller's other children */ while (waitpid(childPid, &status, 0) == -1) { if (errno != EINTR) { /* Error other than EINTR */ status = -1; break; /* So exit loop */ } } break; } /* Unblock SIGCHLD, restore dispositions of SIGINT and SIGQUIT */ savedErrno = errno; /* The following may change 'errno' */ sigprocmask(SIG_SETMASK, &origMask, NULL); sigaction(SIGINT, &saOrigInt, NULL); sigaction(SIGQUIT, &saOrigQuit, NULL); errno = savedErrno; } return status; } char **parser(const char *input) //Will only parse by spaces { char ** cmnds = malloc(64 * sizeof(char *)); char * dummy; int i = 0; dummy = strtok((char*)input, " "); //parser while(dummy != NULL) { cmnds[i] = dummy; //pointer at each parsed command line thinger majiger. // printf("%s\n", cmnds[i]); dummy = strtok (NULL, " "); i++; } // printf("%s\n", cmnds[1]); return cmnds; } int changeDir(char **parsedArgs) { parsedArgs[1][strlen(parsedArgs[1])-1] = '\0'; // printf("%ld \n", strlen(parsedArgs[1])); printf("[%s] \n", parsedArgs[1]); if(parsedArgs[1] == NULL) { printf("no argument received"); } else { if(chdir(parsedArgs[1]) == -1) perror("error with directory"); } printf("cd succesful\n"); return 1; } void listDir() { DIR *curDir; struct dirent *dp; int i = 0; curDir = opendir("."); //open current directory while ((dp = readdir(curDir)) != NULL) //keeps pointing to the next thing in curDir { i++; printf(" %s ", dp->d_name); if(i % 5 == 0) printf("\n\n"); } printf("\n\n"); closedir(curDir); } void helperMayo() { printf(" VLADS HELPFUL LIST FOR HELPING PEOPLE \n\n"); printf("to exit shell: exit \n\n"); printf("to change directory: cd 'directory name' \n\n"); printf("to list files in current directory: ls \n\n"); printf("\n\n"); } void launchProg(char** parsedArgs) { // if (execve(parsedArgs[0], parsedArgs) == -1) // perror("Not a command mate!"); if (execvp(parsedArgs[0], parsedArgs) == -1) perror("Not a command mate!"); } void /* Examine a wait() status using the W* macros */ printWaitStatus(const char *msg, int status) { if (msg != NULL) printf("%s", msg); //non-zero value if status was returned for a child process that terminated normally. if (WIFEXITED(status)) { printf("child exited, status=%d\n", WEXITSTATUS(status)); //Evaluates to a non-zero value if status was returned for a child process that //terminated due to the receipt of a signal that was not caught } else if (WIFSIGNALED(status)) { printf("child killed by signal %d (%s)", WTERMSIG(status), strsignal(WTERMSIG(status))); #ifdef WCOREDUMP /* Not in SUSv3, may be absent on some systems */ if (WCOREDUMP(status)) printf(" (core dumped)"); #endif printf("\n"); //If the value of WIFSTOPPED(stat_val) is non-zero, //this macro evaluates to the number of the signal that caused the child process to stop. } else if (WIFSTOPPED(status)) { printf("child stopped by signal %d (%s)\n", WSTOPSIG(status), strsignal(WSTOPSIG(status))); #ifdef WIFCONTINUED /* SUSv3 has this, but older Linux versions and some other UNIX implementations don't */ } else if (WIFCONTINUED(status)) { printf("child continued\n"); #endif } else { /* Should never happen */ printf("what happened to this child? (status=%x)\n", (unsigned int) status); } } //Websites linked below were used as learning guides for this assignment. //http://stephen-brennan.com/2015/01/16/write-a-shell-in-c/
C
/** * \file threadPool_task.h * \author Federico Mariti * Si dichiara che il contenuto di questo file e' in ogni sua parte opera * originale dell' autore. */ #ifndef __THREADPOOL_TASK_H__ #define __THREADPOOL_TASK_H__ #include "taskResult.h" struct threadPool_task_t; typedef struct threadPool_task_t threadPool_task_t; /** alloca in memori heap la struttura che rappresenta un task, ovvero * una attivita' asincrona, di un thread pool. * * \param fun il riferimento alla funzione che definisce * l'attivita' asincrona * * \param arg il riferimento algi eventuali argomenti * * \param rslt il riferimento alla struttura ch rappresenta il * futuro risultato dell'attivita' asincrona * * \param returnErrVal il valore ritornato dalla funzione riferita * da fun che rappresenta una esecuzione non * corretta dell'attivita' asincrona * */ threadPool_task_t * threadPool_task_new(void * (* fun) (void *), void * arg, taskResult_t * rslt, void * returnErrVal); /** libera tutte le risorse occupate dalla struttura passata e * dealloca la memoria heap usata dalla struttura, mette a null il * riferimento alla struttura * */ void threadPool_task_free(threadPool_task_t ** task); /** inizializza i campi della struttura threadPool_task_t passata e * gia' allocata * */ int threadPool_task_init(threadPool_task_t * task, void * (* fun) (void *), void * arg, taskResult_t * rslt, void * rtnErrVl); /** funzione che crea una copia in memoria heap della struttura * threadPool_task_t passata * * \param a il riferimento alla struttura threadPool_task_t da * copiare * * \return il riferimento alla locazione di memoria heap in cui e' * stata copiata la nuova struttura * * \retval NULL in caso di errore, errno settato * */ void * threadPool_task_copy(void * a); /** funzione di comparazione tra due strutture threadPool_thread_t, la * comparazione e' effettuata verificaando il valore dei campi delle * due strutture passate * * \param a il riferimento alla prima struttura threadPool_thread_t * * \param b il riferimento alla seconda struttura * threadPool_thread_t * * \retval 0 le due strutture sono uguali * * \retval -1 altrimenti * */ int threadPool_task_compare(void * a, void * b); #endif /* __THREADPOOL_TASK_H__ */
C
/* ############################ */ /* ## PHYS 632 (Spring 2018) ## */ /* ## HW 03 Problem 03 ## */ /* ## Romberg Int. ## */ /* ############################ */ #include <stdio.h> #include <stdlib.h> #include <math.h> #define RN_SIZE 30 float targetFunc(float x){ return pow(sin(x),2); } int initRn(float Rn[RN_SIZE][RN_SIZE]){ int i,j; for(i=0; i<RN_SIZE; i++){ for(j=0; j<RN_SIZE; j++){ Rn[i][j] = 0; } } return 1; } int main(){ float h, a, b, Inum, err; float Rn[RN_SIZE][RN_SIZE], tmpf; float Iexact = 2 * M_PI; int N; int i, j, k; int SUCC_FLG = 0; FILE* fp; float eps; int order = 3; int rowMin; if (order == 3){ rowMin = 3; eps = 1e-5; }else{ rowMin = 4; eps = 1e-6; } a = 0.0; b = 4 * M_PI; /* fp = fopen("p2-ptc-data.txt", "w"); */ printf("Exact value is %.4f\n", Iexact); initRn(Rn); // Step 1 h = b - a; Rn[0][0] = 0.5 * (targetFunc(a) + targetFunc(b)); printf("%.4f\n", Rn[0][0]); i = 1; while (!SUCC_FLG){ h /= 2; tmpf = 0; for (j = 0; j < pow(2,i-1); j++){ tmpf += targetFunc(a + h * (2 * j + 1)); } tmpf *= h; Rn[i][0] = tmpf + .5 * Rn[i-1][0]; printf("%.4f", Rn[i][0]); for (j = 1; j<i+1; j++){ Rn[i][j] = Rn[i][j-1] + (Rn[i][j-1] - Rn[i-1][j-1]) / (pow(4,j) - 1.0); printf("\t%.4f", Rn[i][j]); } err = fabsf(Rn[i][i] - Rn[i-1][i-1]); printf("\t (err = %.4e)\n", err); if (err < eps && i > rowMin + 1) SUCC_FLG = 1; i++; } if (Rn[i-1][i-1] == Rn[i-2][i-2]) printf("equal\n"); return 1; }
C
/*********************************************************************** / / READ THE SPECTRUM TABLE / / written by: Ji-hoon Kim / date: February, 2010 / modified1: / / PURPOSE: / For RadiaitveTransferTraceSpectrum = TRUE, initialize the spectrum / table. The table must be tabulated against column density (rows), / and should contain (1) the fraction of photons left in the ray, and / (2) the mean energy of the spectrum at a given column density. / / RETURNS: SUCCESS or FAIL / ************************************************************************/ #ifdef TRANSFER #include <stdlib.h> #include <string.h> #include <stdio.h> #include <math.h> #include "ErrorExceptions.h" #include "macros_and_parameters.h" #include "typedefs.h" #include "global_data.h" #include "CosmologyParameters.h" int ReadRadiativeTransferSpectrumTable(float TemperatureUnits, float LengthUnits, float aUnits, float DensityUnits, float TimeUnits) { FILE *fptr; char line[MAX_LINE_LENGTH]; int i, nbins; float TemperatureRange[2]; // open the file if ((fptr = fopen(RadiativeTransferTraceSpectrumTable, "r")) == NULL) { ENZO_VFAIL("Error opening spectrum table %s\n", RadiativeTransferTraceSpectrumTable) } // The second line gives the number of lines in this file fgets(line, MAX_LINE_LENGTH, fptr); // pass the first line fgets(line, MAX_LINE_LENGTH, fptr); if ((sscanf(line, "# %"ISYM, &nbins)) != 1) { ENZO_FAIL("Error reading number of bins (line 2)\n"); } // Initialize RadiativeTransferSpectrumTable.NumberOfColumnDensityBins = nbins; RadiativeTransferSpectrumTable.columndensity_table = new float[nbins]; RadiativeTransferSpectrumTable.fractionphotons_table[0] = new float[nbins]; RadiativeTransferSpectrumTable.fractionphotons_table[1] = new float[nbins]; RadiativeTransferSpectrumTable.fractionphotons_table[2] = new float[nbins]; RadiativeTransferSpectrumTable.meanenergy_table = new float[nbins]; // Read the spectrum table for (i = 0; i < nbins; i++) { if (fscanf(fptr, "%"FSYM" %"FSYM" %"FSYM" %"FSYM" %f", &RadiativeTransferSpectrumTable.columndensity_table[i], &RadiativeTransferSpectrumTable.fractionphotons_table[0][i], &RadiativeTransferSpectrumTable.fractionphotons_table[1][i], &RadiativeTransferSpectrumTable.fractionphotons_table[2][i], &RadiativeTransferSpectrumTable.meanenergy_table[i]) != 5) { ENZO_VFAIL("Error reading RadiationData line %"ISYM"\n", i) } } fclose(fptr); #ifdef OUTPUT_SPECTRUM_FOR_CHECK // Write out the spectrum table for check FILE *fptr2; fptr2 = fopen("spectrum_table.out", "w"); for (i = 0; i < RadiativeTransferSpectrumTable.NumberOfColumnDensityBins; i++) fprintf(fptr2, "%g %"FSYM" %"FSYM" %"FSYM" %f\n", RadiativeTransferSpectrumTable.columndensity_table[i], RadiativeTransferSpectrumTable.fractionphotons_table[0][i], RadiativeTransferSpectrumTable.fractionphotons_table[1][i], RadiativeTransferSpectrumTable.fractionphotons_table[2][i], RadiativeTransferSpectrumTable.meanenergy_table[i]); fclose(fptr2); #endif return SUCCESS; } #endif
C
#include <stdio.h> #include <math.h> #include <stdlib.h> void base_Two(int a); void base_Eight(int a); void base_Sixteen(int a); int main(){ int a; printf("Enter a number:"); scanf("%d",&a); printf("Number in base 2: "); base_Two(a); printf("Number in base 8: "); base_Eight(a); printf("Number in base 16: "); base_Sixteen(a); return 0; } void base_Two(int a){ int *baseTwo = malloc (4*8); int i; for (i=7; i>=0; i--){ int c= (int)pow((double)2,(double)i); if (a/c == 1){ baseTwo[i] = 1; a -=c; } else{ baseTwo[i] = 0; } } for (i=7; i>=0; i--){ printf("%d",baseTwo[i]); } printf("\n"); free(baseTwo); } void base_Eight(int a){ int *base_eight= malloc(4*3); int i; for (i=2 ; i>=0; i--){ int power= (int)pow((double)8,(double)i); base_eight[i] = a/power; a -= (a/power)*power; } for (i=2; i>=0; i--){ printf("%d",base_eight[i]); } printf("\n"); free(base_eight); } void base_Sixteen(int a){ int *base_sixteen = malloc(4*2); int i; for (i=1; i>=0; i--){ int power= (int)pow((double)16,(double)i); if (a/power < 9){ base_sixteen[i] = a/power; printf("%d",base_sixteen[i]); a -= (a/power)*power; } else if (a/power == 11){ base_sixteen[i] = 66; a-= (a/power)*power; printf("%c",base_sixteen[i]); } else if (a/power == 12){ base_sixteen[i] = 67; a-= (a/power)*power; printf("%c",base_sixteen[i]); } else if (a/power == 13){ base_sixteen[i] = 68; a-= (a/power)*power; printf("%c",base_sixteen[i]); } else if (a/power == 14){ base_sixteen[i] = 69; a-= (a/power)*power; printf("%c",base_sixteen[i]); } else if (a/power == 15){ base_sixteen[i] = 70; a-= (a/power)*power; printf("%c",base_sixteen[i]); } } printf("\n"); free(base_sixteen); }
C
/** * Copyright (C) 2017, Hao Hou **/ /** * @brief The exotic object data type **/ #ifndef __PSS_EXOTIC_H__ #define __PSS_EXOTIC_H__ /** * @brief The data structure used for an exotic object **/ typedef struct _pss_exotic_t pss_exotic_t; /** * @brief The data used to create an exotic object **/ typedef struct { uint32_t magic_num; /*!< The magic number of the object */ const char* type_name;/*!< The name of the type */ /** * @brief Dispose a use exotic object * @param mem The memomry to dispose * @return status code **/ int (*dispose)(void* mem); void* data; /*!< The actual data */ } pss_exotic_creation_param_t; /** * @brief Initialize the callbacks for the exotic objects * @return status code **/ int pss_exotic_init(void); /** * @brief FInalize the type callbacks * @return status code **/ int pss_exotic_finalize(void); /** * @brief Get the actual data from the exotic object * @param obj The exotic object * @param magic_num The expected magic number * @return The pointer to the actual data **/ void* pss_exotic_get_data(pss_exotic_t* obj, uint32_t magic_num); #endif
C
#include<stdio.h> void main() { int c, no; printf("Enetr a no"); scanf("%d",&no); switch (no>0) { case 1: { printf("%d no is positive", no); }break; case 0 : {// condition ofr negative switch (no<0) { case 1: { printf("%d is negative",no); }break; case 0: { printf("%d is zero value", no); }break; } } } }
C
/* * @Description: In User Settings Edit * @Author: your name * @Date: 2019-10-17 17:29:46 * @LastEditTime: 2019-10-17 19:01:13 * @LastEditors: Please set LastEditors */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" #include "driver/gpio.h" #include "driver/hw_timer.h" #include "rom/ets_sys.h" #include "esp_log.h" #include "esp_system.h" #include "ds18b20.h" int DSPORT = GPIO_NUM_5; //(为gpio5接口) bool isInit = true; void Delay1ms(int y) { os_delay_us(y * 1000); } /******************************************************************************* * 函 数 名 : Ds18b20Init * 函数功能 : 初始化 * 输 入 : 无 * 输 出 : 初始化成功返回1,失败返回0 *******************************************************************************/ uint8_t Ds18b20Init(gpio_num_t num) { int i = 0; DSPORT = num; if (isInit) { gpio_config_t io_conf; //disable interrupt io_conf.intr_type = GPIO_INTR_DISABLE; //set as output mode io_conf.mode = (GPIO_MODE_OUTPUT); //bit mask of the pins that you want to set,e.g.GPIO15/16 io_conf.pin_bit_mask = (1ULL << DSPORT); //disable pull-down mode io_conf.pull_down_en = 0; //disable pull-up mode io_conf.pull_up_en = 0; //configure GPIO with the given settings gpio_config(&io_conf); isInit = false; } gpio_set_direction(DSPORT, GPIO_MODE_OUTPUT); gpio_set_level(DSPORT, 0); //将总线拉低480us~960us os_delay_us(642); //延时642us gpio_set_level(DSPORT, 1); //然后拉高总线,如果DS18B20做出反应会将在15us~60us后总线拉低 gpio_set_direction(DSPORT, GPIO_MODE_INPUT); while (gpio_get_level(DSPORT)) //等待DS18B20拉低总线 { Delay1ms(1); i++; if (i > 5) //等待>5MS { return 0; //初始化失败 } } return 1; //初始化成功 } /******************************************************************************* * 函 数 名 : Ds18b20WriteByte * 函数功能 : 向18B20写入一个字节 * 输 入 : com * 输 出 : 无 *******************************************************************************/ void Ds18b20WriteByte(uint8_t dat) { int i, j; gpio_set_direction(DSPORT, GPIO_MODE_OUTPUT); for (j = 0; j < 8; j++) { gpio_set_level(DSPORT, 0); //每写入一位数据之前先把总线拉低1us i++; gpio_set_level(DSPORT, dat & 0x01); //然后写入一个数据,从最低位开始 os_delay_us(70); //延时68us,持续时间最少60us gpio_set_level(DSPORT, 1); //然后释放总线,至少1us给总线恢复时间才能接着写入第二个数值 dat >>= 1; } } /******************************************************************************* * 函 数 名 : Ds18b20ReadByte * 函数功能 : 读取一个字节 * 输 入 : com * 输 出 : 无 *******************************************************************************/ uint8_t Ds18b20ReadByte() { uint8_t byte = 0, bi; int i, j; for (j = 8; j > 0; j--) { gpio_set_direction(DSPORT, GPIO_MODE_OUTPUT); gpio_set_level(DSPORT, 0); //先将总线拉低1us i++; gpio_set_level(DSPORT, 1); //然后释放总线 i++; i++; gpio_set_direction(DSPORT, GPIO_MODE_INPUT); //延时6us等待数据稳定 bi = gpio_get_level(DSPORT); //读取数据,从最低位开始读取 /*将byte左移一位,然后与上右移7位后的bi,注意移动之后移掉那位补0。*/ byte = (byte >> 1) | (bi << 7); os_delay_us(48); //读取完之后等待48us再接着读取下一个数 } return byte; } /******************************************************************************* * 函 数 名 : Ds18b20ChangTemp * 函数功能 : 让18b20开始转换温度 * 输 入 : com * 输 出 : 无 *******************************************************************************/ void Ds18b20ChangTemp() { Ds18b20Init(DSPORT); Delay1ms(1); Ds18b20WriteByte(0xcc); //跳过ROM操作命令 Ds18b20WriteByte(0x44); //温度转换命令 // Delay1ms(100); //等待转换成功,而如果你是一直刷着的话,就不用这个延时了 } /******************************************************************************* * 函 数 名 : Ds18b20ReadTempCom * 函数功能 : 发送读取温度命令 * 输 入 : com * 输 出 : 无 *******************************************************************************/ void Ds18b20ReadTempCom() { Ds18b20Init(DSPORT); Delay1ms(1); Ds18b20WriteByte(0xcc); //跳过ROM操作命令 Ds18b20WriteByte(0xbe); //发送读取温度命令 } /******************************************************************************* * 函 数 名 : Ds18b20ReadTemp * 函数功能 : 读取温度 * 输 入 : com * 输 出 : 无 *******************************************************************************/ int Ds18b20ReadTemp() { int temp = 0; uint8_t tmh, tml; Ds18b20ChangTemp(); //先写入转换命令 Ds18b20ReadTempCom(); //然后等待转换完后发送读取温度命令 tml = Ds18b20ReadByte(); //读取温度值共16位,先读低字节 tmh = Ds18b20ReadByte(); //再读高字节 temp = tmh; temp <<= 8; temp |= tml; return temp; }