language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <unistd.h>
#include <stdbool.h>
#include <signal.h>
#include <sys/syscall.h>
#include <sys/types.h>
#define RECORD_SIZE 1024
pthread_t * ids; //identyfikatory wątków
char * plik = "test.txt";
int fl; //plik z rekordami
bool threadFlag = false; //flaga utworzenia wątków
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //standardowa blokada mutex
int iloscRekordow = 3; //ilość rekordów czytanych przez wątek
int iloscWatkow = 4; //ilosc uruchomionych wątków
char *slowo = "bi";
bool dzieleniePrzezZero = false;
struct sigaction sigact; //nowa akcja dla sygnału
void *threadFunc(void *);
void atexitFunc();
void handler(int, siginfo_t *, void *);
struct rekord{
int id;
char * txt;
}; // struktura do przechowywania rekordów
int main(int argc, char const *argv[])
{
atexit(atexitFunc);
int c;
sigact.sa_sigaction = handler; //przypisanie acji handler dla sygnału
ids = malloc(sizeof(pthread_t)*iloscWatkow);
fl = open(plik,O_RDONLY);
if(fl == -1){
printf("Blad otwierania pliku\n%s\n",strerror(errno));
exit(-1);
}
for(int i=0; i<iloscWatkow; i++){
//tworzenie wątków
//id,atrybuty,funkcja,arg funkcji
c = pthread_create(ids+i,NULL,threadFunc,slowo);
if(c!=0){
printf("Blad podczas tworzenia watku nr %d\n%s\n",i,strerror(c));
exit(-1);
}
}
sigaction(SIGFPE, &sigact, NULL); //obsługa sygnału dpowiadającego m.in. za dzielenie przez zero
threadFlag = true;
for(int i=0; i<iloscWatkow; i++){
//czekanie aż wątki zakończą co mają do zrobienia
c = pthread_join(ids[i],NULL);
if(c!=0){
printf("Blad podczas joinowania watku nr %d\n%s\n",i,strerror(c));
exit(-1);
}
}
return 0;
}
void * threadFunc(void * slowo){
int czytaj = 1;
struct rekord bufor[iloscRekordow]; //tablica rekordów
int c;
//może być odwołany w każdej chwili
c = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
if(c!=0) {
printf("Blad podczas ustawiania typu\n%s\n",strerror(c));
exit(-1);
}
while(!threadFlag); //czekanie na utworzenie wątków
char *tmp = malloc(sizeof(char)*RECORD_SIZE); //zmienna tymczasowa na identyfikator rekordu
char *strtmp = malloc(sizeof(char)*RECORD_SIZE);
char *nmb = malloc(sizeof(char)*3);
int j;
int k;
while(czytaj>0) { //czytaj = 0 na końcu pliku
pthread_mutex_lock(&mutex); //blokowanie pliku
if(!dzieleniePrzezZero){
printf("Watek %lu dzieli przez zero",(unsigned long)pthread_self());
dzieleniePrzezZero = true;
int num = 1/0;
}
for (int i = 0; i<iloscRekordow; i++) {
j = 0;
czytaj = read(fl,tmp,RECORD_SIZE+1);
if(czytaj == -1){
printf("Blad podczas czytania z pliku\n%s\n",strerror(errno));
exit(-1);
}
while((int)tmp[j]!=32) { // 32 = spacja
nmb[j] = tmp[j];
j++;
} //przeczytano id rekordu
bufor[i].id = atoi(nmb);
bufor[i].txt = malloc(sizeof(char)*(RECORD_SIZE));
j++; //przecodzę do pierwszego znaku tekstu rekordu
k = 0;
while((int)tmp[j]!=0){ // 0 = koniec napisu
strtmp[k] = tmp[j];
j++;
k++;
} //przeczytano tekst
j++;
strcpy(bufor[i].txt,strtmp);
}
pthread_mutex_unlock(&mutex); //zwalnianie blokady mutexu
char * szukacz; // wskaznik na znalezione wystapienie danego slowa w buforze
for(int i=0; i<iloscRekordow; i++) {
szukacz = strstr(bufor[i].txt,slowo);
if (szukacz != NULL){ //znaleziono
for (int l = 0; l < iloscWatkow; l++) { //zamykanie pozostałych wątków
if(ids[l]!=pthread_self()){
pthread_cancel(ids[l]);
}
}
printf("Watek o TID: %lu Znalazl slowo w rekordzie o identyfikatorze %d\n",(unsigned long)pthread_self(),bufor[i].id);
exit(1);
}
}
} //koniec while'a
return NULL;
}
void handler(int sign, siginfo_t *info, void *ptr) {
pid_t tid = syscall(SYS_gettid); //pobieranie unikalnego ID dla wątku
printf("Zlapalem sygnal: %d, TID: %ld\n",sign,(long)tid);
}
void atexitFunc(){
free(ids);
close(fl);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
char* genstring (char *s, int c, int n, int inc);
int main(){
char* str = malloc ((8) * sizeof(char));
char* ret = genstring(str, 'a', 6, 1);
printCharArray(str);
}
void printCharArray(char* c){
for(int i = 0; i < 7;i++){
printf("%c %i\n",c[i], (int) c[i]);
}
}
|
C
|
/**********************************************************************************************************
天穹飞控 —— 致力于打造中国最好的多旋翼开源飞控
Github: github.com/loveuav/BlueSkyFlightControl
技术讨论:bbs.loveuav.com/forum-68-1.html
* @文件 drv_flash.c
* @说明 单片机Flash读写驱动
* @版本 V1.0
* @作者 BlueSky
* @网站 bbs.loveuav.com
* @日期 2018.05
**********************************************************************************************************/
#include "drv_flash.h"
/**********************************************************************************************************
*函 数 名: Flash_ReadByte
*功能说明: 从flash中读取一个字节
*形 参: 起始地址 地址偏移量
*返 回 值: 读取到的字节
**********************************************************************************************************/
uint8_t Flash_ReadByte(uint32_t start_addr, uint16_t cnt)
{
return *(__IO uint8_t*)(start_addr+cnt);
}
/**********************************************************************************************************
*函 数 名: Flash_ReadWord
*功能说明: 从flash中读取一个字(32位)
*形 参: flash地址
*返 回 值: 读取到的字
**********************************************************************************************************/
uint32_t Flash_ReadWord(uint32_t addr)
{
return *(vu32*)addr;
}
/**********************************************************************************************************
*函 数 名: Flash_GetSector
*功能说明: 获取某个地址所在的flash扇区
*形 参: flash地址
*返 回 值: addr所在的扇区(0-11)
**********************************************************************************************************/
uint16_t Flash_GetSector(uint32_t addr)
{
if(addr<ADDR_FLASH_SECTOR_1)
return FLASH_Sector_0;
else if(addr<ADDR_FLASH_SECTOR_2)
return FLASH_Sector_1;
else if(addr<ADDR_FLASH_SECTOR_3)
return FLASH_Sector_2;
else if(addr<ADDR_FLASH_SECTOR_4)
return FLASH_Sector_3;
else if(addr<ADDR_FLASH_SECTOR_5)
return FLASH_Sector_4;
else if(addr<ADDR_FLASH_SECTOR_6)
return FLASH_Sector_5;
else if(addr<ADDR_FLASH_SECTOR_7)
return FLASH_Sector_6;
else if(addr<ADDR_FLASH_SECTOR_8)
return FLASH_Sector_7;
else if(addr<ADDR_FLASH_SECTOR_9)
return FLASH_Sector_8;
else if(addr<ADDR_FLASH_SECTOR_10)
return FLASH_Sector_9;
else if(addr<ADDR_FLASH_SECTOR_11)
return FLASH_Sector_10;
return FLASH_Sector_11;
}
/**********************************************************************************************************
*函 数 名: Flash_WriteByte
*功能说明: 在Flash的某个区域写入数据
*形 参: 写入地址 写入数据缓冲区指针 写入长度
*返 回 值: 写入状态
**********************************************************************************************************/
bool Flash_WriteByte(uint32_t dest,uint8_t *src,uint32_t length)
{
FLASH_Status status = FLASH_COMPLETE;
bool return_value = false;
uint32_t start_addr = 0;
uint32_t end_addr = 0;
if(dest<FLASH_BASE_START_ADDR || dest>FLASH_BASE_END_ADDR) //非法地址
return false;
FLASH_Unlock(); //解锁
FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |
FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR);
FLASH_DataCacheCmd(DISABLE);//FLASH擦除期间,必须禁止数据缓存
start_addr = dest; //写入的起始地址
end_addr = dest + length; //写入的结束地址
while(start_addr < end_addr)
{
if(Flash_ReadWord(start_addr) != 0XFFFFFFFF)//有非0XFFFFFFFF的地方,要擦除这个扇区
{
status = FLASH_EraseSector(Flash_GetSector(start_addr),VoltageRange_3);//VCC=2.7~3.6V之间!!
if(status != FLASH_COMPLETE) //发生错误了
{
return_value = false; //发生错误了
break;
}
}
else
start_addr+=4;
}
if(status == FLASH_COMPLETE)
{
while(dest < end_addr)//写数据
{
if(FLASH_ProgramByte(dest,*src) != FLASH_COMPLETE)//写入数据
{
return_value = false; //发生错误了
break;
}
else
{
if (*(vu8*)dest != *src) // 检查复制到Flash的数据是否正确
{
return_value = false; // 不匹配
break;
}
else
return_value = true;
}
dest++;
src++;
}
}
FLASH_DataCacheCmd(ENABLE); //FLASH擦除结束,开启数据缓存
FLASH_Lock();//上锁
return return_value;
}
|
C
|
#include <stdio.h>
int convert(const char*num)
{
int a=0;
const char *ptr=num;
if(*num=='-'||*num=='+'){
num++;
}
while(*num!='\0')
{
if((*num < '0')||(*num > '9')){
break;
}
a = a*10 + (*num - '0');
num++;
}
if(*ptr=='-'){
a = -a;
}
return a;
}
int main()
{
int num = 0;
char str[10];
printf("please input string:");
gets(str);
num = convert(str);
printf("output:%d\n",num);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "s_ring_buffer.h"
/**
* 默认元素池构造器
*/
unsigned char* s_ring_buffer_element_pool_constructor_malloc(unsigned int element_size,
unsigned int element_pool_cap,
void* other_arg)
{
return (unsigned char*)s_ring_buff_malloc(sizeof(unsigned char) * (element_size * element_pool_cap));
}
/**
* 默认元素池析构器
*/
void s_ring_buffer_element_pool_destructor_malloc(unsigned char* element_pool_addr)
{
if(element_pool_addr != NULL) {
s_ring_buff_free(element_pool_addr);
}
return;
}
/**
* 环形缓冲区构造器
* element_size:元素大小,单位 byte
* element_pool_cap:元素存储池容量
* element_pool_constructor:环形缓冲区元素存储池构造器,为NULL,采用默认方式构造,需要与element_pool_destructor匹配
* other_arg:环形缓冲区元素存储池构造器的第三参数
*/
s_ring_buffer_t* s_ring_buffer_constructor(unsigned int element_size,
unsigned int element_pool_cap,
s_ring_buffer_element_pool_constructor_t element_pool_constructor,
void* other_arg)
{
s_ring_buffer_t* r_buf = NULL;
if(element_size == 0 || element_pool_cap == 0) {
goto s_ring_buffer_constructor_out;
}
r_buf = (s_ring_buffer_t*)s_ring_buff_malloc(sizeof(s_ring_buffer_t));
if(r_buf == NULL) {
goto s_ring_buffer_constructor_out;
}
if(element_pool_constructor == NULL) {
r_buf->element_pool = s_ring_buffer_element_pool_constructor_malloc(element_size, element_pool_cap, NULL);
} else {
r_buf->element_pool = element_pool_constructor(element_size, element_pool_cap, other_arg);
}
if(r_buf->element_pool == NULL) {
s_ring_buff_free(r_buf);
r_buf = NULL;
goto s_ring_buffer_constructor_out;
}
r_buf->element_size = element_size;
r_buf->element_pool_cap = element_pool_cap;
r_buf->element_could_read_num = 0;
s_ring_buffer_unlock(&r_buf->element_read_lock);
r_buf->element_read_index = 0;
r_buf->element_could_write_num = element_pool_cap;
s_ring_buffer_unlock(&r_buf->element_write_lock);
r_buf->element_write_index = 0;
s_ring_buffer_constructor_out:
return r_buf;
}
/**
* 环形缓冲区析构构器
* s_ring_buffer_p:环形缓冲区指针
* element_pool_destructor:环形缓冲区元素存储池析构器,为NULL,采用默认方式析构,需要与element_pool_constructor匹配
* */
void s_ring_buffer_destructor(s_ring_buffer_t* s_ring_buffer_p,
s_ring_buffer_element_pool_destructor_t element_pool_destructor)
{
if(s_ring_buffer_p == NULL) {
goto s_ring_buffer_destructor_out;
}
if(element_pool_destructor == NULL) {
s_ring_buffer_element_pool_destructor_malloc(s_ring_buffer_p->element_pool);
} else {
element_pool_destructor(s_ring_buffer_p->element_pool);
}
s_ring_buff_free(s_ring_buffer_p);
s_ring_buffer_destructor_out:
return;
}
/**
* 清空环形缓冲区
* s_ring_buffer_p:环形缓冲区指针
*/
void s_ring_buffer_clear(s_ring_buffer_t* s_ring_buffer_p)
{
if(s_ring_buffer_p == NULL || s_ring_buffer_p->element_pool == NULL) {
goto s_ring_buffer_clear_out;
}
s_ring_buffer_lock(&s_ring_buffer_p->element_read_lock);
s_ring_buffer_lock(&s_ring_buffer_p->element_write_lock);
s_ring_buffer_p->element_could_read_num = 0;
s_ring_buffer_p->element_could_write_num = s_ring_buffer_p->element_pool_cap;
s_ring_buffer_p->element_read_index = 0;
s_ring_buffer_unlock(&s_ring_buffer_p->element_read_lock);
s_ring_buffer_p->element_write_index = 0;
s_ring_buffer_unlock(&s_ring_buffer_p->element_write_lock);
s_ring_buffer_clear_out:
return;
}
/**
* 写数据进环形缓冲区,返回实际写入元素数量
* s_ring_buffer_p: 环形缓冲区指针
* p_elements_start_addr: 元素起始地址
* elements_num: 元素数量
* time_out: 超时时间,单位 ms
* err_p: 错误信息;正常返回0;参数输入错误,-1;超时,-2
*/
unsigned int s_ring_buffer_write_elements(s_ring_buffer_t* s_ring_buffer_p,
void* p_elements_start_addr,
unsigned int elements_num,
unsigned int time_out,
int* err_p)
{
unsigned int res = 0;
unsigned int elements_ture_write_num = 0;
unsigned int elements_current_write_num = 0;
unsigned int element_could_write_num = 0;
unsigned char* p_elements_cpy_addr = (unsigned char*)p_elements_start_addr;
unsigned int time_out_in = time_out;
if(s_ring_buffer_p == NULL ||
p_elements_start_addr == NULL ||
s_ring_buffer_p->element_pool == NULL) {
*err_p = -1;
goto s_ring_buffer_write_elements_out;
}
time_out++;
do {
if(s_ring_buffer_try_lock(&s_ring_buffer_p->element_write_lock) == 1) {
element_could_write_num = s_ring_buffer_p->element_could_write_num;
elements_ture_write_num = (elements_num >= element_could_write_num)?(element_could_write_num):(elements_num);
res = elements_ture_write_num;
while(elements_ture_write_num > 0) {
elements_current_write_num = ((s_ring_buffer_p->element_write_index + elements_ture_write_num) > s_ring_buffer_p->element_pool_cap)?
(s_ring_buffer_p->element_pool_cap - s_ring_buffer_p->element_write_index):(elements_ture_write_num);
s_ring_buff_memcpy(s_ring_buffer_p->element_pool + (s_ring_buffer_p->element_size * s_ring_buffer_p->element_write_index),
p_elements_cpy_addr,
(s_ring_buffer_p->element_size * elements_current_write_num));
p_elements_cpy_addr += (s_ring_buffer_p->element_size * elements_current_write_num);
elements_ture_write_num -= elements_current_write_num;
s_ring_buffer_p->element_could_write_num -= elements_current_write_num;
s_ring_buffer_p->element_write_index = (s_ring_buffer_p->element_write_index + elements_current_write_num)%(s_ring_buffer_p->element_pool_cap);
}
s_ring_buffer_unlock(&s_ring_buffer_p->element_write_lock);
s_ring_buffer_lock(&s_ring_buffer_p->element_read_lock);
s_ring_buffer_p->element_could_read_num += res;
s_ring_buffer_unlock(&s_ring_buffer_p->element_read_lock);
*err_p = 0;
goto s_ring_buffer_write_elements_out;
}
if(--time_out > 0) {
s_ring_buff_sleep(1);
}
} while(time_out > 0);
if(time_out_in != time_out && time_out == 0) {
*err_p = -2;
}
s_ring_buffer_write_elements_out:
return res;
}
/**
* 自环形缓冲区读取数据,返回实际读取元素数量
* s_ring_buffer_p: 环形缓冲区指针
* p_elements_save_start_addr: 元素存放起始地址
* elements_num: 元素数量
* time_out: 超时时间,单位 ms
* err_p: 错误信息;正常返回0;参数输入错误,-1;超时,-2
*/
unsigned int s_ring_buffer_read_elements(s_ring_buffer_t* s_ring_buffer_p,
void* p_elements_save_start_addr,
unsigned int elements_num,
unsigned int time_out,
int* err_p)
{
unsigned int res = 0;
unsigned int elements_ture_read_num = 0;
unsigned int elements_current_read_num = 0;
unsigned int element_could_read_num = 0;
unsigned char* p_elements_cpy_addr = (unsigned char*)p_elements_save_start_addr;
unsigned int time_out_in = time_out;
if(s_ring_buffer_p == NULL ||
p_elements_save_start_addr == NULL ||
s_ring_buffer_p->element_pool == NULL) {
*err_p = -1;
goto s_ring_buffer_read_elements_out;
}
time_out++;
do {
if(s_ring_buffer_try_lock(&s_ring_buffer_p->element_read_lock) == 1) {
element_could_read_num = s_ring_buffer_p->element_could_read_num;
elements_ture_read_num = (elements_num >= element_could_read_num)?(element_could_read_num):(elements_num);
res = elements_ture_read_num;
while(elements_ture_read_num > 0) {
elements_current_read_num = ((s_ring_buffer_p->element_read_index + elements_ture_read_num) > s_ring_buffer_p->element_pool_cap)?
(s_ring_buffer_p->element_pool_cap - s_ring_buffer_p->element_read_index):(elements_ture_read_num);
s_ring_buff_memcpy(p_elements_cpy_addr,
s_ring_buffer_p->element_pool + (s_ring_buffer_p->element_size * s_ring_buffer_p->element_read_index),
(s_ring_buffer_p->element_size * elements_current_read_num));
p_elements_cpy_addr += (s_ring_buffer_p->element_size * elements_current_read_num);
elements_ture_read_num -= elements_current_read_num;
s_ring_buffer_p->element_could_read_num -= elements_current_read_num;
s_ring_buffer_p->element_read_index = (s_ring_buffer_p->element_read_index + elements_current_read_num)%(s_ring_buffer_p->element_pool_cap);
}
s_ring_buffer_unlock(&s_ring_buffer_p->element_read_lock);
s_ring_buffer_lock(&s_ring_buffer_p->element_write_lock);
s_ring_buffer_p->element_could_write_num += res;
s_ring_buffer_unlock(&s_ring_buffer_p->element_write_lock);
*err_p = 0;
goto s_ring_buffer_read_elements_out;
}
if(--time_out > 0) {
s_ring_buff_sleep(1);
}
} while(time_out > 0);
if(time_out_in != time_out && time_out == 0) {
*err_p = -2;
}
s_ring_buffer_read_elements_out:
return res;
}
/**
* 获取环形缓冲区容量
* s_ring_buffer_p:环形缓冲区指针
*/
unsigned int s_ring_buffer_cap_get(s_ring_buffer_t* s_ring_buffer_p)
{
unsigned int res = 0;
if(s_ring_buffer_p == NULL) {
goto s_ring_buffer_cap_get_out;
}
res = s_ring_buffer_p->element_pool_cap;
s_ring_buffer_cap_get_out:
return res;
}
/**
* 获取环形缓冲区可读元素数量
* s_ring_buffer_p:环形缓冲区指针
*/
unsigned int s_ring_buffer_could_read_num_get(s_ring_buffer_t* s_ring_buffer_p)
{
unsigned int res = 0;
if(s_ring_buffer_p == NULL) {
goto s_ring_buffer_could_read_num_get_out;
}
res = s_ring_buffer_p->element_could_read_num;
s_ring_buffer_could_read_num_get_out:
return res;
}
/**
* 获取环形缓冲区可写元素数量
* s_ring_buffer_p:环形缓冲区指针
*/
unsigned int s_ring_buffer_could_write_num_get(s_ring_buffer_t* s_ring_buffer_p)
{
unsigned int res = 0;
if(s_ring_buffer_p == NULL) {
goto s_ring_buffer_could_write_num_get_out;
}
res = s_ring_buffer_p->element_could_write_num;
s_ring_buffer_could_write_num_get_out:
return res;
}
|
C
|
/*
ļ BBSHOME/.BOARDS ļ
籾ļÿİ ;pp
*/
/* gcc -O2 -I../../include -o SortBoard SortBoard.c ../../src/record.c */
#include "bbs.h"
struct boardheader fh;
void report()
{}
;
int main(void)
{
FILE *fp;
int i = 1;
char src[STRLEN], des[STRLEN];
sprintf(src, "%s/.BOARDS", BBSHOME);
strcpy(des, ".BOARDS.new");
while (1)
{
if (get_record(src, &fh, sizeof(fh), i) == -1)
break;
if (fh.filename[0] == '\0')
{
printf("No.%2d invalidation, ship...\n", i);
}
else
{
fh.BM[0] = '\0';
append_record(des, &fh, sizeof(fh));
}
i++;
}
printf("Total boards %d .\n", i - 1);
}
|
C
|
#include "analyze.h"
#include "backtrack.h"
#include "bump.h"
#include "deduce.h"
#include "inline.h"
#include "learn.h"
#include "minimize.h"
#include <inttypes.h>
#define INVALID_LEVEL UINT_MAX
static bool
one_literal_on_conflict_level (kissat * solver,
clause * conflict,
unsigned *conflict_level_ptr)
{
assert (conflict);
assert (conflict->size > 1);
unsigned conflict_level = INVALID_LEVEL;
unsigned literals_on_conflict_level = 0;
unsigned forced_lit = INVALID_LIT;
assigned *all_assigned = solver->assigned;
unsigned *lits = conflict->lits;
const unsigned conflict_size = conflict->size;
const unsigned *end_of_lits = lits + conflict_size;
for (const unsigned *p = lits; p != end_of_lits; p++)
{
const unsigned lit = *p;
assert (VALUE (lit) < 0);
const unsigned idx = IDX (lit);
const unsigned level = all_assigned[idx].level;
if (conflict_level == level)
{
if (++literals_on_conflict_level > 1 && level == solver->level)
break;
}
else if (conflict_level == INVALID_LEVEL || conflict_level < level)
{
forced_lit = lit;
conflict_level = level;
literals_on_conflict_level = 1;
}
}
assert (conflict_level != INVALID_LEVEL);
assert (literals_on_conflict_level);
LOG ("found %u literals on conflict level %u",
literals_on_conflict_level, conflict_level);
*conflict_level_ptr = conflict_level;
if (!conflict_level)
{
solver->inconsistent = true;
LOG ("learned empty clause from conflict at conflict level zero");
CHECK_AND_ADD_EMPTY ();
ADD_EMPTY_TO_PROOF ();
return false;
}
if (conflict_level < solver->level)
{
LOG ("forced backtracking due to conflict level %u < level %u",
conflict_level, solver->level);
kissat_backtrack (solver, conflict_level);
}
if (conflict_size > 2)
{
for (unsigned i = 0; i < 2; i++)
{
const unsigned lit = lits[i];
const unsigned lit_idx = IDX (lit);
unsigned highest_position = i;
unsigned highest_literal = lit;
unsigned highest_level = all_assigned[lit_idx].level;
for (unsigned j = i + 1; j < conflict_size; j++)
{
const unsigned other = lits[j];
const unsigned other_idx = IDX (other);
const unsigned level = all_assigned[other_idx].level;
if (highest_level >= level)
continue;
highest_literal = other;
highest_position = j;
highest_level = level;
if (highest_level == conflict_level)
break;
}
if (highest_position == i)
continue;
reference ref = INVALID_REF;
if (highest_position > 1)
{
ref = kissat_reference_clause (solver, conflict);
kissat_unwatch_blocking (solver, lit, ref);
}
lits[highest_position] = lit;
lits[i] = highest_literal;
if (highest_position > 1)
kissat_watch_blocking (solver, lits[i], lits[!i], ref);
}
}
if (literals_on_conflict_level > 1)
return false;
assert (literals_on_conflict_level == 1);
assert (forced_lit != INVALID_LIT);
LOG ("reusing conflict as driving clause of %s", LOGLIT (forced_lit));
kissat_backtrack (solver, solver->level - 1);
if (conflict_size == 2)
{
assert (conflict == &solver->conflict);
const unsigned other = lits[0] ^ lits[1] ^ forced_lit;
kissat_assign_binary (solver, conflict->redundant, forced_lit, other);
}
else
{
const reference ref = kissat_reference_clause (solver, conflict);
kissat_assign_reference (solver, forced_lit, ref, conflict);
}
return true;
}
static void
mark_literal_as_analyzed (kissat * solver, assigned * all_assigned,
unsigned lit, const char *type)
{
const unsigned idx = IDX (lit);
assigned *a = all_assigned + idx;
if (a->analyzed == ANALYZED)
return;
a->analyzed = ANALYZED;
LOG ("marking %s literal %s as analyzed", type, LOGLIT (lit));
PUSH_STACK (solver->analyzed, idx);
(void) type;
}
static inline void
analyze_reason_side_literals (kissat * solver)
{
assert (!solver->probing);
if (!GET_OPTION (bumpreasons))
return;
assigned *all_assigned = solver->assigned;
for (all_stack (unsigned, lit, solver->clause.lits))
all_assigned[IDX (lit)].analyzed = ANALYZED;
word *arena = BEGIN_STACK (solver->arena);
for (all_stack (unsigned, lit, solver->clause.lits))
{
const unsigned idx = IDX (lit);
assigned *a = all_assigned + idx;
assert (a->level > 0);
assert (a->reason != UNIT);
if (a->reason == DECISION)
continue;
if (a->binary)
mark_literal_as_analyzed (solver, all_assigned, a->reason,
"reason side");
else
{
assert (a->reason < SIZE_STACK (solver->arena));
clause *c = (clause *) (arena + a->reason);
for (all_literals_in_clause (lit, c))
if (IDX (lit) != idx)
mark_literal_as_analyzed (solver, all_assigned, lit,
"reason side");
}
}
}
static void
reset_levels (kissat * solver)
{
LOG ("reset %zu marked levels", SIZE_STACK (solver->levels));
frame *frames = BEGIN_STACK (solver->frames);
for (all_stack (unsigned, level, solver->levels))
{
assert (level < SIZE_STACK (solver->frames));
frame *f = frames + level;
assert (f->used > 0);
f->used = 0;
}
CLEAR_STACK (solver->levels);
}
static void
reset_markings (kissat * solver)
{
LOG ("unmarking %zu analyzed variables", SIZE_STACK (solver->analyzed));
assigned *all_assigned = solver->assigned;
for (all_stack (unsigned, idx, solver->analyzed))
all_assigned[idx].analyzed = 0;
}
static void
reset_analyze (kissat * solver)
{
LOG ("reset %zu analyzed variables", SIZE_STACK (solver->analyzed));
CLEAR_STACK (solver->analyzed);
LOG ("reset %zu learned literals", SIZE_STACK (solver->clause.lits));
CLEAR_STACK (solver->clause.lits);
}
static void
update_trail_average (kissat * solver)
{
assert (!solver->probing);
const unsigned size = SIZE_STACK (solver->trail);
const unsigned assigned = size - solver->unflushed;
const unsigned active = solver->active;
const double filled = kissat_percent (assigned, active);
LOG ("trail filled %.0f%% (size %u, unflushed %u, active %u)",
filled, size, solver->unflushed, active);
UPDATE (trail, filled);
}
int
kissat_analyze (kissat * solver, clause * conflict)
{
assert (!solver->inconsistent);
START (analyze);
if (!solver->probing)
{
update_trail_average (solver);
UPDATE (level, solver->level);
}
int res;
do
{
LOGCLS (conflict, "analyzing conflict %" PRIu64, CONFLICTS);
unsigned conflict_level;
if (one_literal_on_conflict_level (solver, conflict, &conflict_level))
res = 1;
else if (!conflict_level)
res = -1;
else if ((conflict = kissat_deduce_first_uip_clause (solver, conflict)))
{
reset_markings (solver);
reset_analyze (solver);
reset_levels (solver);
res = 0;
}
else
{
kissat_minimize_clause (solver);
if (!solver->probing)
analyze_reason_side_literals (solver);
reset_markings (solver);
kissat_learn_clause (solver);
// MAB
if (!solver->probing && (!solver->stable || solver->heuristic==0))
kissat_bump_variables (solver);
if(!solver->probing && solver->stable && (solver->heuristic==1))
kissat_update_conflicted_chb (solver);
reset_analyze (solver);
reset_levels (solver);
res = 1;
}
}
while (!res);
STOP (analyze);
return res > 0 ? 0 : 20;
}
|
C
|
#include <stdio.h>
/* page 92 my_strcat: concatenate t to the end of s; pointer version */
void my_strcat(char *s, char *t)
{
while(*s)
s++;
while(*s++ = *t++)
;
}
void main(void)
{
char s[] = "ad";
char t[] = "AdolphLWQ";
my_strcat(s, t);
printf("s is %s\n", s);
}
|
C
|
/*
Sarah Kazi
skazi3
CS 361
LAB 7
MandelDisplay-skazi3.cpp
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>
struct msg_buf {
long int mtype; /* message type, must be > 0 */
char mtext[200]; /* message data */
}rcv, snd;
int *data;
int imageProcessed = 0;
void sig_handler(int signal){
//if SIGUSR1, exit with non-neg code = to # of images calculated
if(signal == SIGUSR1){
if(shmdt(data) == -1){
perror("shmdt");
exit(1);
}
exit(imageProcessed);
}
}
int main (int argc, char **argv) {
if(argc >= 1){
signal(SIGUSR1, sig_handler);
int nColors = 15;
char filename[100];
FILE *fp;
int msgqid1, msgqid2, shmid, rc, nRows, nCols, maxIters;
shmid = atoi(argv[1]);
msgqid1 = atoi(argv[2]);
msgqid2 = atoi(argv[3]);
double xMin, xMax, yMin, yMax;
char colors[] = ".-~:+*%08&?$@#X";
data = (int*)shmat(shmid, NULL, 0);
if(data == (int*)-1){
perror("shmat fail in child2");
exit(-1);
}
while(true){
scanf("%d", &nRows);
scanf("%d", &nCols);
scanf("%lf", &xMin);
scanf("%lf", &xMax);
scanf("%lf", &yMin);
scanf("%lf", &yMax);
scanf("%d", &maxIters);
/*debugging purposes*/
/*-----------------------------read filename from message queue 2------------------------------------*/
ssize_t result;
rcv.mtype = 1;
int length = sizeof(struct msg_buf) - sizeof(long int);
if((result = msgrcv(msgqid2, (void*)&rcv, length, 0,0)) == -1){
perror("msgrcv child2 failed");
exit(-1);
}
/*------------open file, if file opened properly save data to file--------------------------*/
fp = fopen(rcv.mtext, "w");
/*------------read data from shared mem and display image on screen--------------------------*/
int r, c, n;
for(r = nRows -1; r > 0; r--){
for(c = 0; c < nCols-1; c++){
n = *(data + r * nCols+ c);
fprintf(fp, " %d", n);
if(n < 0){
printf(" ");
}
else{
printf("%c", colors[n %nColors]);
}
}
printf("\n");
fprintf(fp, "\n");
}
fclose(fp);
/*-----------------------------send done to message queue 1------------------------------------*/
snd.mtype = 1;
sprintf(snd.mtext, "done\n");
if((rc = msgsnd(msgqid1, (void *)&snd, length, 0)) == -1){
perror("msgsnd child1 fail");
exit(1);
}
imageProcessed++;
}
}
return 1;
}
|
C
|
/*
* write a program that converts all characters of a file to uppercase and
* write the results out to a temporary file. Then rename the temporary file
* to the original filename and remove the temporary filename
*
* use fgetc and fputc
* use rename and remove functions
* use the islower function
* can convert a character to upper case by subtracting 32 from it
*
* display the contents of the original file to standard output
* in uppercase
*/
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *inputPath = "Data/assn20.input.txt";
char *tempPath = "Data/assn20.temp.txt";
char *outputPath = "Data/assn20.output.txt";
FILE *pInput;
FILE *pTemp;
FILE *pOutput;
char ch;
pInput = fopen(inputPath, "r");
pTemp = fopen(tempPath, "w");
if (pInput == NULL || pTemp == NULL) {
printf("Error: could not open file(s)");
return -1;
}
while((ch=fgetc(pInput)) != EOF) {
int isLower = islower(ch);
char outChar = isLower ? ch - 32 : ch;
fputc(outChar, pTemp);
}
fclose(pInput);
fclose(pTemp);
rename(tempPath, outputPath);
remove(tempPath);
pOutput = fopen(outputPath, "r");
char *output;
fgets(output, 200, pOutput);
printf("%s", output);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
int main (int argc, char *argv[]){
const char* short_options = "xyz:";
const struct option long_options[] = {
{"xlong",no_argument,NULL,'x'},
{"ylong",no_argument,NULL,'y'},
{"zlong",required_argument,NULL,'z'},
{NULL,0,NULL,0}
};
int rez;
int option_index = -1;
int flag_x=0;
int flag_y=0;
int flag_z=0;
while ((rez=getopt_long(argc,argv,short_options,
long_options,&option_index))!=-1){
switch(rez){
case 'x': {
if (flag_x == 0) {
flag_x=1;
printf("Arg: \"x\", ");
if(option_index<0)
printf("type: short\n");
else
printf("type: long\n");
}
break;
};
case 'y': {
if (flag_y == 0) {
flag_y=1;
printf("Arg: \"y\", ");
if(option_index<0)
printf("type: short\n");
else
printf("type: long\n");
}
break;
};
case 'z': {
if (flag_z == 0) {
flag_z=1;
printf("Arg: \"z\", ");
if(option_index<0)
printf("type: short, ");
else
printf("type: long, ");
printf("value: %s\n",optarg);
}
break;
};
case '?': default: {
printf("Found unknown option\n");
break;
};
};
option_index = -1;
};
return 0;
};
|
C
|
#include <math.h>
#include "xf.h"
#include "solver.h"
#include "array2f.h"
#define SWAP(x0,x) {array2f * tmp=x0;x0=x;x=tmp;}
void add_source(const array2f *array, const array2f *source, float dt )
{
for (size_t y = 0; y < array->resolution.height; y++) {
for (size_t x = 0; x < array->resolution.width; x++) {
array2f_set(
array, x, y,
array2f_get(array, x, y) + array2f_get(source, x, y) * dt);
}
}
}
void set_neutral_edges(const array2f *x) {
const size_t w = x->resolution.width;
const size_t h = x->resolution.height;
for (size_t j = 0; j < h; j++) {
ARRAY2F_AT(x, 0, j) = array2f_get(x, 1, j);
ARRAY2F_AT(x, w - 1, j) = array2f_get(x, w - 2, j);
}
for (size_t i = 0; i < w; i++) {
ARRAY2F_AT(x, i, 0) = array2f_get(x, i, 1);
ARRAY2F_AT(x, i, h - 1) = array2f_get(x, i, h - 2);
}
}
void mirror_bnd(const array2f *x, const array2f *m, int dx, int dy) {
// Always set the edges to closest value
set_neutral_edges(x);
const size_t w = x->resolution.width;
const size_t h = x->resolution.height;
for (size_t j = 0; j < h; j++) {
for (size_t i = 0; i < w; i++) {
const float d = array2f_get(m, i, j);
const int di = signf(d);
array2f_set(x, i, j,
lerpf(array2f_get(x, i, j), -array2f_get(x, i + dx * di, j + dy * di), fabs(d)));
}
}
}
void set_bnd(const array2f *x, const bounds_t *bounds)
{
// Always set the edges to closest value
set_neutral_edges(x);
// Check dynamic boundaries
const size_t w = x->resolution.width;
const size_t h = x->resolution.height;
for (size_t j = 0; j < h; j++) {
for (size_t i = 0; i < w; i++) {
const float dx = array2f_get(&bounds->bx, i, j);
const float dy = array2f_get(&bounds->by, i, j);
const int dxi = signf(dx);
const int dyi = signf(dy);
array2f_set(x, i, j, array2f_get(x, i + dxi, j + dyi));
}
}
}
void lin_solve(const array2f *x, const array2f *x0, float a, float c)
{
const size_t w = x->resolution.width;
const size_t h = x->resolution.height;
for (size_t k = 0; k < 20; k++) {
for (size_t j = 1; j < h - 1; j++) {
for (size_t i = 1; i < w - 1; i++) {
ARRAY2F_AT(x, i, j) = (array2f_get(x0, i,j) + a * (
array2f_get(x, i - 1, j) +
array2f_get(x, i + 1, j) +
array2f_get(x, i, j - 1) +
array2f_get(x, i, j + 1))) / c;
}
}
}
}
void diffuse(const array2f *x, const array2f *x0, float diff, float dt )
{
float a = dt * diff * array2f_area(x);
lin_solve(x, x0, a, 1 + 4 * a);
}
void advect(const array2f *d, const array2f *d0, const array2f *u, const array2f *v, float dt)
{
const size_t w = d0->resolution.width;
const size_t h = d0->resolution.height;
for (size_t j = 1; j < h - 1; j++) {
for (size_t i = 1; i < w - 1; i++) {
float x = i - (dt * (w - 2)) * array2f_get(u, i, j);
if (x < 0.5f) x = 0.5f;
if (x > w-2 + 0.5f) x = w-2 + 0.5f;
float y = j - (dt * (h - 2)) * array2f_get(v, i, j);
if (y < 0.5f) y = 0.5f;
if (y > h-2+0.5f) y = h-2 + 0.5f;
size_t i0=(int)x, i1 = i0 + 1;
size_t j0=(int)y, j1 = j0 + 1;
float s1 = x - i0, s0 = 1 - s1;
float t1 = y - j0, t0 = 1 - t1;
ARRAY2F_AT(d, i, j) =
s0 * (t0 * array2f_get(d0, i0, j0) + t1 * array2f_get(d0, i0, j1)) +
s1 * (t0 * array2f_get(d0, i1, j0) + t1 * array2f_get(d0, i1, j1));
}
}
}
void project(const array2f *u, const array2f *v, const array2f *p, const array2f *divergence, const bounds_t *bounds)
{
const size_t w = u->resolution.width;
const size_t h = u->resolution.height;
const size_t N = (w + h - 4) / 2; // TODO: Should this be sqrt instead?
for (size_t j = 1; j < h - 1; j++) {
for (size_t i = 1; i < w - 1; i++) {
ARRAY2F_AT(divergence, i, j) = -0.5f * (
array2f_get(u, i + 1, j) - array2f_get(u, i - 1, j) +
array2f_get(v, i, j + 1) - array2f_get(v, i, j - 1)) / N;
ARRAY2F_AT(p, i, j) = 0;
}
}
set_bnd(divergence, bounds); set_bnd(p, bounds);
lin_solve(p, divergence, 1, 4);
set_bnd(p, bounds);
for (size_t j = 1; j < h - 1; j++) {
for (size_t i = 1; i < w - 1; i++) {
ARRAY2F_AT(u, i, j) -= 0.5f * (w-2) * (array2f_get(p, i + 1, j) - array2f_get(p, i - 1, j));
ARRAY2F_AT(v, i, j) -= 0.5f * (h-2) * (array2f_get(p, i, j + 1) - array2f_get(p, i, j - 1));
}
}
mirror_bnd(u, &bounds->bx, 1, 0); mirror_bnd(v, &bounds->by, 0, 1);
}
void density_step(array2f *x, array2f *x0, array2f *u, array2f *v, const bounds_t *bounds, float diffusion, float dt)
{
add_source(x, x0, dt);
SWAP(x0, x); diffuse(x, x0, diffusion, dt); set_bnd(x, bounds);
SWAP(x0, x); advect(x, x0, u, v, dt); set_bnd(x, bounds);
}
void velocity_step(array2f *u, array2f *v, array2f *u0, array2f *v0, const bounds_t *bounds, float viscosity, float dt)
{
add_source(u, u0, dt); add_source(v, v0, dt);
SWAP(u0, u); diffuse(u, u0, viscosity, dt); mirror_bnd(u, &bounds->bx, 1, 0);
SWAP(v0, v); diffuse(v, v0, viscosity, dt); mirror_bnd(v, &bounds->by, 0, 1);
project(u, v, u0, v0, bounds);
SWAP(u0, u); SWAP(v0, v);
advect(u, u0, u0, v0, dt); mirror_bnd(u, &bounds->bx, 1, 0);
advect(v, v0, u0, v0, dt); mirror_bnd(v, &bounds->by, 0, 1);
project(u, v, u0, v0, bounds);
}
|
C
|
/*
A simple client in the internet domain using UDP
Usage: ./client hostname port filename
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> // define structures like hostent
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
int print_message (int, short, char*);
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd; // socket descriptor
int portno, n;
struct sockaddr_in serv_addr;
socklen_t servlen;
struct hostent *server; // contains tons of information, including the server's IP address
//char *hostname;
char *filename;
char filename_buffer[1025];
FILE *datafile;
char buffer[1025];
int flag = 0;
int result;
char data[31][1023];
int tracker[31];
int seq_min = 0;
int seq_max = 5;
int shift;
if (argc < 4) {
fprintf(stderr,"usage %s hostname port filename\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
filename = argv[3];
sockfd = socket(AF_INET, SOCK_DGRAM, 0); // create a new socket
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]); // takes a string like "www.yahoo.com", and returns a struct hostent which contains information, as IP address, address type, the length of the addresses...
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET; //initialize server's address
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
//if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) //establish a connection to the server
// error("ERROR connecting");
strncpy(filename_buffer, filename, strlen(filename));
filename_buffer[strlen(filename)] = '\0';
servlen = sizeof(struct sockaddr_in);
//send request filename to server
n = sendto(sockfd, &filename_buffer, strlen(filename_buffer), 0, (struct sockaddr*) &serv_addr, servlen);
if(n < 0){
error("ERROR sending requested file to server\n");
}
//open a file to store data received from server
// datafile = fopen("result.txt", "wb");
result = open("received.data", O_TRUNC | O_CREAT | O_RDWR);
//initialize a tracker to track whether packet after the current window is waiting to be write to file
int index;
index = 0;
while(index < 30){
tracker[index] = 0;
index++;
}
//wait for server to send packets
while(1){
memset(buffer, 0, 1024);
int receive = recvfrom(sockfd, &buffer, sizeof(buffer), 0, (struct sockaddr*) &serv_addr, &servlen);
if(receive < 0){
error("ERROR receiving data from server\n");
}
char seq_buffer[2];
strncpy(seq_buffer, buffer, 2);
short seq = (((short)seq_buffer[0]) << 8) | seq_buffer[1];
//print out the sending/receiving process
flag = print_message(flag, seq, buffer);
//if FIN is received, exit the program
if(flag == 2){
close(sockfd);
fclose(datafile);
return 0;
}
//send ACK reply to server
n = sendto(sockfd, &seq_buffer, 2, 0, (struct sockaddr*) &serv_addr, servlen);
if(n < 0){
error("ERROR sending ACK to server\n");
}
//Keep tracker of packets in receiver window and write to file when appropriate
short seq_num = seq/1024;
if(seq_num == seq_min && seq_min > seq_max){
shift = 31;
}
else{
shift = 0;
}
memset(data[seq_num], 0, 1022);
memcpy(data[seq_num], buffer+2, 1022);
int index;
int n;
//int temp;
if(seq_num == seq_min){
// fwrite(&data[seq_num], 1, sizeof(data[seq_num]), datafile);
n = write(result, &data[seq_num], receive - 2);
tracker[seq_num] = 0;
int i;
for(i = seq_min + 1; i < seq_max + shift; i++){
index = i % 31;
if(tracker[index]==0){
break;
}
// fwrite(&data[index], 1, sizeof(data[index]), datafile);
n = write(result, &data[index], receive - 2);
tracker[index] = 0;
}
seq_min = i % 31;
seq_max = (seq_min + 5) % 31;
}
//if later packet arrives first, use tracker to tracker packets
else{
tracker[seq_num] = 1;
}
}
close(sockfd); // close socket
fclose(datafile);
return 0;
}
//function to print sending/receiving process for debug purposes
int print_message (int flag, short seq, char* buffer){
if(flag == 0){
printf("Receiving packet SYN\n");
printf("Sending packet SYN\n");
printf("Receiving packet %d\n", seq);
printf("Sending packet %d\n", seq);
return 1;
}
else{
//the first 2 slots are used to store sequence number
if(buffer[2] == 'F' && buffer[3] == 'I' && buffer[4] == 'N'){
printf("Receiving packet FIN\n");
printf("Sending packet FIN\n");
return 2;
}
else{
printf("Receiving packet %d\n", seq);
printf("Sending packet %d\n", seq);
return 1;
}
}
}
|
C
|
// RGB LED Circle Wave Breathing LED
int led_pins[4] = {3,5,6};
int jj = 0; // 0 = red, 1 = green, 2 = blue
float smoothness_pts = 500;//larger=slower change in brightness
void setup() {
Serial.begin(9600);
for (int ii = 0;ii<sizeof(led_pins)/sizeof(int);ii++){
pinMode(led_pins[ii],OUTPUT);
}
}
void circsmooth(){
for (int ii=0;ii<smoothness_pts;ii++){
float pwm_val = 255.0*sqrt(1.0 - pow(abs((2.0*(ii/smoothness_pts))-1.0),2.0));
analogWrite(led_pins[jj],int(pwm_val));
delay(5);
Serial.println(int(pwm_val));
}
}
// RGB LED Gaussian Wave Breathing LED
int led_pins[4] = {3,5,6};
int jj = 1; // 0 = red, 1 = green, 2 = blue
float smoothness_pts = 500;//larger=slower change in brightness
float gamma = 0.14; // affects the width of peak (more or less darkness)
float beta = 0.5; // shifts the gaussian to be symmetric
float pwm_val = 255.0*(exp(-(pow(((ii/smoothness_pts)-beta)/gamma,2.0))/2.0));
|
C
|
#include<stdio.h>
main()
{
int n=1;
do
{
printf("\n\nMultification table of %d \n",n);
int i=1;
do
{
printf("%d*%d=%d\n",n,i,n*i);
i++;
}
while(i<=10);
n++;
}
while(n<=10);
}
|
C
|
/*
composite.h
Description routines, composite sentences
*/
#ifndef _sys_composite_h
#define _sys_composite_h
#define COMPOSITE_FILE "/sys/global/composite"
/*
* Standard composite descriptions for living and dead objects
*
* Usable in 2.4.6 and in 3.0
*
*/
#define COMPOSITE_LIVE(x) call_other(COMPOSITE_FILE,"desc_live",x)
#define COMPOSITE_DEAD(x) call_other(COMPOSITE_FILE,"desc_dead",x)
/* This is only usable in 3.0
*
* Function: composite
* Description: Creates a composite description of objects
* Arguments: x: Array of the objects to describe
* sf: Function to call in objects to get its <name>
* Objects with the same <names> are described together
* df: Function to call to get the actual description of
* a group of 'same objects' i.e objects whose
* 'sf' returned the same value.
* ob: Object to call df in.
*
* Returns: A description string on the format:
* <desc>, <desc> and <desc>
* Where <desc> is what ob->df() returns
*
*/
#define COMPOSITE(x,sf,df,ob) call_other(COMPOSITE_FILE,"composite",x,sf,df,ob)
/*
* Returns the array of unique objects from the last call to COMPOSITE
*
* Usable only in 3.0
*/
#define COMPOSITE_OBLAST call_other(COMPOSITE_FILE,"get_last_objects")
#endif
|
C
|
/*
Author: Kellan Loew
Date: 11/5/2018
Project operation: From a list of IP addresses, it prints those that belong to the same network and OS.
Directions:
- Ask the user to enter an IP address in the IP format x:y:z:w
- Ask the user to enter the length of the network part of the IP address.
- Ask the user to enter an os, or enter \?" for all operating systems.
- Print all IP addresses that belong to the same network and are assigned to hosts running the same operating
system.
*/
#include<stdio.h>
#include <string.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable: 4996)
typedef struct { //Host structure
int x, y, z, w;
char os[8];
}host;
host convert_IP(char s[]); //Function declarations
void print_host(host *h);
void find_hosts(host *net, int size, host t, int len);
long int decimalToEightBinary(int in);
long int power(int base, int exp);
int main(void) {
FILE* inp;
host myhost[20];
int size = 0;
int length;
inp = fopen("hosts.txt", "r");
char targetString[30];
host targetIP;
int i = 0;
while (fscanf(inp, "%d.%d.%d.%d %s", &myhost[i].x, &myhost[i].y, &myhost[i].z, &myhost[i].w, myhost[i].os) != EOF) {//Reads each line of host file
++i;
++size; //Keeps track of number of IP addresses
}
printf("Enter target IP: ");
scanf("%s", targetString); //Stores target IP address
targetIP = convert_IP(targetString); //Converts target string to a binary host type for the function call later
printf("Enter the operating system:");
scanf("%s", targetIP.os); //Stores OS
printf("Enter the length of the network part of the IP address:");
scanf("%d", &length); //Stores number of significant binary digits of network part
find_hosts(myhost, size, targetIP, length); //Calls function to find matching hosts
fclose(inp);
return 0;
}
host convert_IP(char s[]) {
host temp;
char network[3];
long int out;
int i, k, l;
int counter = 0;
for (i = 0; i < 4; ++i) { //This loop goes over each of the four parts of IP address
k = 0;
while ((s[counter] != '.') && (s[counter] != '\0')) { //Reads numbers from input string until a period is reached, or the end of the input string
network[k] = s[counter];
++k;
++counter;
}
out = atoi(network);//The string is trasnformed into an integer
switch (i) {
case 0:
temp.x = decimalToEightBinary(out); //Depending on which part of the IP address we're on, that part is copied into a temp host var as binary
break;
case 1:
temp.y = decimalToEightBinary(out);
break;
case 2:
temp.z = decimalToEightBinary(out);
break;
case 3:
temp.w = decimalToEightBinary(out);
break;
default:
temp.w = 666666666;
}
for (l = 0; l < 3; ++l) { //Deletes members of network string for next loop
network[l] = '\0';
}
++counter; //Skips over period
}
return temp;
}
long int decimalToEightBinary(int in) { //Converts an integer less than 256 to a binary number
int counter = 0;
int out = 0;
char binary[9];
long int binaryInt;
int k = 128; //The largest possible integer factor
while (k >= 1) {
if ((k + out) <= in) { //If the sum of the output + successivley smaller powers of 128 fit into the original, that power of two gets a '1'
out = out + k;
binary[counter] = '1';
}
else //else it gets a '0'
binary[counter] = '0';
k = k / 2;
++counter;
}
binary[8] = '\0';
binaryInt = atoi(binary);//String is turned into an integer
return binaryInt;
}
void print_host(host *h) {
printf("%d.%d.%d.%d %s", h->x, h->y, h->z, h->w, h->os);
printf("\n");
}
void find_hosts(host *net, int size, host t, int len) {
int i, k;
int counter = 0;
int match = 0;
host binary[20];
for (i = 0; i < size; ++i) { //This loop copies the list of input addresses to a temporary host array
for (k = 0; k < 4; ++k) {
switch (k) { //This part changes the first three parts of the addresses to binary
case 0:
binary[i].x = decimalToEightBinary(net[i].x);
break;
case 1:
binary[i].y = decimalToEightBinary(net[i].y);
break;
case 2:
binary[i].z = decimalToEightBinary(net[i].z);
break;
}
}
}
for (k = 0; k < size; ++k) {//This loop checks for matches between target address and given addresses, running as many times as there possible string matches scanned in through the file
counter = 0;
if (len <= 8) { //If length is <= 8,
for (i = 8; i >= (8 - len); --i) { //Starts with 8 and decrements as long as the length is
if ((binary[k].x / power(10, i)) == (t.x / power(10, i))) { //This divides coressponding binary numbers by succesively smaller powers of 10 and checks if they're equal
++counter;
}
}
}
else if (len <= 16) { //If length is <= 16, then
if (binary[k].x == t.x) //This checks if previous part is also equal
counter = 8; //Removes the length that coressponds to previous part of IP address
for (i = 8; i >= (8 - (len - 8)); --i) { //Starts with 8 and decrements as long as the excess length is
if ((binary[k].y / power(10, i)) == (t.y / power(10, i))) {//As above
++counter;
}
}
}
else { //If length is <= 24, then
if ((binary[k].y == t.y) && (binary[k].x == t.x)) //This checks if previous parts are also equal
counter = 16; //Removes the length that coressponds to previous parts of IP address
for (i = 8; i >= (8 - (len - 16)); --i) {
if ((binary[k].z / power(10, (i - 1)) == (t.z / power(10, (i - 1)))))
++counter;
}
}
if ((counter >= len) && ((strcmp(net[k].os, t.os) == 0) || (strcmp(t.os, "?") == 0))) { //Prints elements of given host if equivalent and the OS is the either the same or unknown
print_host(&net[k]);
++match; //Keeps track of times when no match is found
}
}
if (match == 0)
printf("No matches.\n"); //Prints message if no matches
}
long int power(int base, int exp) {
int output = 1;
int i;
if (exp > 0) {
for (i = 0; i < exp; ++i) {
output = output * base;
}
}
else //If exponent is 0, output is always 1
output = 1;
return output;
}
|
C
|
#include<stdio.h>
#include<conio.h>
int main()
{
int n,i,j,temp,tower,height,a,count,arr[1000];
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
a = 0;
tower = 0;
height = 1;
while(a<n)
{
count = 1;
for(i=a;i<n-1;i++)
{
if(arr[i]==arr[i+1])
count++;
else
break;
}
if(height<count)
height = count;
a = i+1;
tower++;
}
printf("%d %d",height,tower);
//getch();
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int n, r, i, per = 1;
printf("n : ");
scanf_s("%d", &n);
printf("r : ");
scanf_s("%d", &r);
for (i = 0; i < r; i++)
{
per *= n - i;
}
printf(" %dԴϴ.", per);
return 0;
}
|
C
|
#include "sm32f030_spi.h"
void SPI_DeInit(void)
{
SYSCON_AHBPeriphResetCmd(SYSCON_AHBRESET_SPI, ENABLE);
SYSCON_AHBPeriphResetCmd(SYSCON_AHBRESET_SPI, DISABLE);
}
void SPI_StructInit(SPI_InitTypeDef* SPI_InitStruct)
{
SPI_InitStruct->SPI_Mode = SPI_Mode_Master;
SPI_InitStruct->SPI_DataSize = SPI_DataSize_8b;
SPI_InitStruct->SPI_CPOL = SPI_CPOL_Low;
SPI_InitStruct->SPI_CPHA = SPI_CPHA_1Edge;
SPI_InitStruct->SPI_NssIdleLevel = SPI_NSS_Idle_High;
SPI_InitStruct->SPI_ClockPrescaler = 12;
}
void SPI_Init(SPI_InitTypeDef* SPI_InitStruct)
{
uint32_t tmpreg;
/* Check the parameters */
assert_param(CNF_SPI_MODE(SPI_InitStruct->SPI_Mode));
assert_param(CNF_SPI_DATA_SIZE(SPI_InitStruct->SPI_DataSize));
assert_param(CNF_SPI_CPOL(SPI_InitStruct->SPI_CPOL));
assert_param(CNF_SPI_CPHA(SPI_InitStruct->SPI_CPHA));
assert_param(CNF_SPI_NSS_IDLE(SPI_InitStruct->SPI_NssIdleLevel));
tmpreg = SPI->CR0;
/* Clear DSS, CPOL and CPHA bits */
tmpreg &= 0x0030;
tmpreg |= (SPI_InitStruct->SPI_DataSize |
SPI_InitStruct->SPI_CPOL | SPI_InitStruct->SPI_CPHA);
SPI->CR0 = tmpreg;
tmpreg = SPI->CR1;
/* Clear MS and CSFL bits */
tmpreg &= 0x006B;
tmpreg |= (SPI_InitStruct->SPI_Mode | SPI_InitStruct->SPI_NssIdleLevel);
SPI->CR1 = tmpreg;
SPI->CPSR = SPI_InitStruct->SPI_ClockPrescaler;
}
void SPI_Cmd(FunctionalState NewState)
{
/* Check the parameters */
assert_param(CNF_FUNCTIONAL_STATE(NewState));
if(NewState != DISABLE)
{
/* Enable the SPI peripheral */
SPI->CR1 |= SPI_CR1_SSE;
}
else
{
/* Disable the SPI peripheral */
SPI->CR1 &= (~SPI_CR1_SSE);
}
}
// 向SPI的发送FIFO写入nWrite个数据
void SPI_WriteFIFO(uint16_t* pBuffer, uint8_t nWrite)
{
while((SPI->SR & SPI_SR_TNF) && (nWrite))
{
/* Write data to FIFO */
SPI->DR = *pBuffer;
++pBuffer;
}
}
// 读取SPI的接收FIFO
// 返回实际读取的数据个数
uint8_t SPI_ReadFIFO(uint16_t* pBuffer, uint8_t nBuffer)
{
uint8_t cnt = 0;
while((SPI->SR & SPI_SR_RNE) && (nBuffer))
{
/* Read data from FIFO */
pBuffer[cnt] = SPI->DR;
++cnt; --nBuffer;
}
return cnt;
}
// 向SPI的FIFO写入一个数据
// 返回1 表示写入成功
// 返回0 表示FIFO已满
uint8_t SPI_WriteOneData(uint16_t data)
{
if(SPI->SR & SPI_SR_TNF)
{
SPI->DR = data;
return 1; //Success
}
return 0; //Failed
}
// 从SPI的接收FIFO读取一个数据
// 若FIFO中没有数据 返回0
uint16_t SPI_ReadOneData(void)
{
if(SPI->SR & SPI_SR_RNE)
{
return SPI->DR;
}
return 0;
}
// 进行一次SPI的数据传输
uint16_t SPI_ReadWriteData(uint16_t data)
{
/* Wait until the transmit buffer is empty */
while(!(SPI->SR & SPI_SR_TFE));
/* Clear RX FIFO */
SPI->CR1 |= SPI_CR1_RSFR;
SPI->CR1 &= (~SPI_CR1_RSFR);
/* Write data to FIFO */
SPI->DR = data;
/* Wait until the transmit buffer is empty */
while(!(SPI->SR & SPI_SR_RNE));
/* Read data from FIFO */
return SPI->DR;
}
|
C
|
#include "Headers.h"
void createModels() {
FILE* fiTrainSet;
FILE* fiModel;
FILE* fiModelMen;
FILE* fiModelWomen;
// Chaine correspondant a la premier ligne dans les fichier csv
char firstLineString[] = "movement, acceleration, acceleration, acceleration, ..., acceleration\n";
fopen_s(&fiTrainSet, TRAINSET, "r");
fopen_s(&fiModel, MODEL, "w");
fopen_s(&fiModelMen, MODELMEN, "w");
fopen_s(&fiModelWomen, MODELWOMEN, "w");
if (fiTrainSet != NULL && fiModel != NULL && fiModelMen != NULL && fiModelWomen != NULL) {
// Ecriture de la premire ligne
fwrite(&firstLineString, strlen(firstLineString), 1, fiModel);
fwrite(&firstLineString, strlen(firstLineString), 1, fiModelMen);
fwrite(&firstLineString, strlen(firstLineString), 1, fiModelWomen);
// On passe la premire ligne dans le fichier trainSet
while (fgetc(fiTrainSet) != '\n');
DatasetFileLine* datasetFileLines = malloc(LINES_COUNT_TRAINSET * sizeof(DatasetFileLine));
// Initialisation par scurit
datasetLinesInitialisation(datasetFileLines);
char value[MAX_VALUE_STRING_SIZE];
int movement, gender;
double acceleration;
int lineTrainSet = 0;
while (!feof(fiTrainSet)) {
// Lecture par ligne
readValueDataSet(fiTrainSet, value);
sscanf_s(value, "%d", &movement);
datasetFileLines[lineTrainSet].movement = movement;
readValueDataSet(fiTrainSet, value);
sscanf_s(value, "%d", &gender);
datasetFileLines[lineTrainSet].gender = gender;
// On passe l'ID
readValueDataSet(fiTrainSet, value);
int iVac = 0;
bool hasValue = !readValueDataSet(fiTrainSet, value);
while (!feof(fiTrainSet) && iVac < NB_VAC_READ && hasValue) {
sscanf_s(value, "%lf", &acceleration);
datasetFileLines[lineTrainSet].accelerations[iVac] = acceleration;
iVac++;
hasValue = !readValueDataSet(fiTrainSet, value);
}
// On sort de la boucle quand les 600 vAcs sont lu ou si le curseur est la ligne suivante
lineTrainSet++;
}
int iMovement = 1;
while (iMovement <= NB_MOVEMENTS) {
char charMovement[3];
snprintf(charMovement, 3, "%d,", iMovement);
fwrite(&charMovement, strlen(charMovement), 1, fiModel);
fwrite(&charMovement, strlen(charMovement), 1, fiModelWomen);
fwrite(&charMovement, strlen(charMovement), 1, fiModelMen);
int iTime = 0;
while (iTime < 600) {
int iLine = 0;
double totalAccMen = 0, totalAccWomen = 0;
int totalLinesMen = 0, totalLinesWomen = 0;
while (iLine < LINES_COUNT_TRAINSET) {
if (datasetFileLines[iLine].movement == iMovement && datasetFileLines[iLine].accelerations[iTime] > 0) {
if (datasetFileLines[iLine].gender == 1) {
totalAccWomen += datasetFileLines[iLine].accelerations[iTime];
totalLinesWomen++;
}
else {
totalAccMen += datasetFileLines[iLine].accelerations[iTime];
totalLinesMen++;
}
}
iLine++;
}
double averageAcc = (totalAccMen + totalAccWomen) / (totalLinesMen + totalLinesWomen);
double averageAccWomen = totalAccWomen / totalLinesWomen;
double averageAccMen = totalAccMen / totalLinesMen;
char charAverage[20];
// Ecriture fiModel
snprintf(charAverage, 20, "%lf,", averageAcc);
fwrite(&charAverage, strlen(charAverage), 1, fiModel);
// Ecriture fiModelWomen
snprintf(charAverage, 20, "%lf,", averageAccWomen);
fwrite(&charAverage, strlen(charAverage), 1, fiModelWomen);
// Ecriture fiModelMen
snprintf(charAverage, 20, "%lf,", averageAccMen);
fwrite(&charAverage, strlen(charAverage), 1, fiModelMen);
iTime++;
}
fwrite("\n", sizeof(char), 1, fiModel);
fwrite("\n", sizeof(char), 1, fiModelMen);
fwrite("\n", sizeof(char), 1, fiModelWomen);
iMovement++;
}
free(datasetFileLines);
fclose(fiTrainSet);
fclose(fiModel);
fclose(fiModelMen);
fclose(fiModelWomen);
}
else {
if (fiTrainSet == NULL) {
printf("trainset failed to open %s\n", TRAINSET);
}
if (fiModel == NULL) {
printf("fiModel failed to open %s\n", MODEL);
}
if (fiModelMen == NULL) {
printf("fiModelMen failed to open %s", MODELMEN);
}
if (fiModelWomen == NULL) {
printf("fiModelWomen failed to open %s", MODELWOMEN);
}
}
}
bool readValueDataSet(FILE* file, char result[]) {
strcpy_s(result, MAX_VALUE_STRING_SIZE, "");
char character = fgetc(file);
while (!feof(file) && character != '\n' && character != ',') {
strncat_s(result, MAX_VALUE_STRING_SIZE, &character, 1);
character = fgetc(file);
}
// On saute directement la ligne ou la virgule et la valeur de retour varie si il y a eu changement de ligne
return character == '\n';
}
void datasetLinesInitialisation(DatasetFileLine* datasetFileLines) {
for (int i = 0; i < LINES_COUNT_TRAINSET; i++) {
datasetFileLines[i].movement = -1;
datasetFileLines[i].gender = -1;
for (int j = 0; j < NB_VAC_READ; j++) {
datasetFileLines[i].accelerations[j] = -1;
}
}
}
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
void sig_catcher(int sig) {
printf("You interrupted the program.");
exit(1);
}
int main()
{
signal(SIGINT, sig_catcher);
while(1)
{
printf("Program is running...\n");
sleep(1);
}
return 0;
}
|
C
|
/**
*
* C(m,n)%p,p可以不为素数
*
*
**/
ll POW(ll a,ll b,ll mod)
{
ll ans=1;
while(b)
{
if(b&1) ans=ans*a%mod;
a=a*a%mod;
b>>=1;
}
return ans;
}
ll POW(ll a,ll b)
{
ll ans=1;
while(b)
{
if(b&1) ans=ans*a;
a=a*a;
b>>=1;
}
return ans;
}
ll exGcd(ll a,ll b,ll &x,ll &y)
{
ll t,d;
if(!b)
{
x=1;
y=0;
return a;
}
d=exGcd(b,a%b,x,y);
t=x;
x=y;
y=t-a/b*y;
return d;
}
bool modular(ll a[],ll m[],ll k)
{
ll d,t,c,x,y,i;
for(i=2;i<=k;i++)
{
d=exGcd(m[1],m[i],x,y);
c=a[i]-a[1];
if(c%d) return false;
t=m[i]/d;
x=(c/d*x%t+t)%t;
a[1]=m[1]*x+a[1];
m[1]=m[1]*m[i]/d;
}
return true;
}
ll reverse1(ll a,ll b)
{
ll x,y;
exGcd(a,b,x,y);
return (x%b+b)%b;
}
ll C(ll n,ll m,ll mod)
{
if(m>n) return 0;
ll ans=1,i,a,b;
for(i=1;i<=m;i++)
{
a=(n+1-i)%mod;
b=reverse1(i%mod,mod);
ans=ans*a%mod*b%mod;
}
return ans;
}
ll C1(ll n,ll m,ll mod)
{
if(m==0) return 1;
return C(n%mod,m%mod,mod)*C1(n/mod,m/mod,mod)%mod;
}
ll cal(ll n,ll p,ll t)
{
if(!n) return 1;
ll x=POW(p,t),i,y=n/x,temp=1;
for(i=1;i<=x;i++) if(i%p) temp=temp*i%x;
ll ans=POW(temp,y,x);
for(i=y*x+1;i<=n;i++) if(i%p) ans=ans*i%x;
return ans*cal(n/p,p,t)%x;
}
ll C2(ll n,ll m,ll p,ll t)
{
ll x=POW(p,t);
ll a,b,c,ap=0,bp=0,cp=0,temp;
for(temp=n;temp;temp/=p) ap+=temp/p;
for(temp=m;temp;temp/=p) bp+=temp/p;
for(temp=n-m;temp;temp/=p) cp+=temp/p;
ap=ap-bp-cp;
ll ans=POW(p,ap,x);
a=cal(n,p,t);
b=cal(m,p,t);
c=cal(n-m,p,t);
ans=ans*a%x*reverse1(b,x)%x*reverse1(c,x)%x;
return ans;
}
//计算C(n,m)%mod
ll Lucas(ll n,ll m,ll mod)
{
ll i,t,cnt=0;
ll A[100],M[100];
for(i=2;i*i<=mod;i++) if(mod%i==0)
{
t=0;
while(mod%i==0)
{
t++;
mod/=i;
}
M[++cnt]=POW(i,t);
if(t==1) A[cnt]=C1(n,m,i);
else A[cnt]=C2(n,m,i,t);
}
if(mod>1)
{
M[++cnt]=mod;
A[cnt]=C1(n,m,mod);
}
modular(A,M,cnt);
return A[1];
}
|
C
|
#include "lists.h"
/**
* free_dlistint - free doubly linked list.
* @head: beginning of list.
*/
void free_dlistint(dlistint_t *head)
{
dlistint_t *tmp = head, *tmp1;
while (tmp)
{
tmp1 = tmp->next;
free(tmp);
tmp = tmp1;
}
}
|
C
|
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void sort (int *a, int l, int r)
{
if (l > r){
return;
}
int i, j;
i = l;
j = r;
int key = a[l];
while (i < j){
while (i < j && key <= a[j]){
j--;
}
a[i] = a[j];
while (i < j && key >= a[i]){
i++;
}
a[j] = a[i];
}
a[i] = key;
sort(a, l, i - 1);
sort(a, i + 1, r);
}
int main()
{
int b[1000000] = {0};
for (int i = 0; i < 1000000; i++){
scanf("%d", &b[i]);
}
sort(b, 0, 999999);
for (int i = 0; i < 1000000; i++){
printf("%d ", b[i]);
if (i % 15 == 0){
printf("\n");
}
}
printf("\nThe time is : %2.lf", (double)clock()/CLOCKS_PER_SEC);
return 0;
}
|
C
|
#include<stdio.h>
void CreateHeap(int [], int);
void SortHeap(int [],int);
int main(void)
{
int arr[50],child,parent,q,key,n,t,i;
printf("\n enter the no. of elements: ");
scanf(" %d",&n);
printf("\n Now enter the array elements: ");
for(i=1;i<=n;i++)
scanf(" %d",&arr[i]);
CreateHeap(arr,n);
SortHeap(arr,n);
return(0);
}
void CreateHeap(int arr[],int n)
{
int i,q, parent,child,temp;
for(q=2;q<=n;q++)
{
child=q;
parent=(int)child/2;
while(child >1 && arr[child] > arr[parent])
{
temp=arr[child];
arr[child]= arr[parent];
arr[parent]=temp;
child=parent;
parent=(int)child/2;
if(parent < 1)
parent=1;
}
}
printf("\n Now the array in heap form is: ");
for(i=1;i<=n;i++)
printf(" %3d",arr[i]);
}
/* function to sort a heap */
void SortHeap(int arr[],int n)
{
int current,parent,child,i,maxnodes, med;
for(maxnodes=n;maxnodes>=2;maxnodes--)
{
current=arr[maxnodes];;
arr[maxnodes]=arr[1];
/* adjust the array to be a heap of size n-1 */
parent=1;
/* obtain the larger of the root's children */
if (maxnodes-1 >= 3 && arr[3] > arr[2])
child=3;
else
child = 2;
/* move keys upwards to find place for current */
while (child<=maxnodes-1 && arr[child]>=current)
{
arr[parent]=arr[child];
parent=child;
child=child*2;
if(child+1 <= maxnodes-1 && arr[child+1] > arr[child])
child = child + 1;
}
arr[parent]=current;
} /* end of for */
printf("\n The sorted array is : ");
for(i=1;i<=n;i++)
printf("%4d",arr[i]);
/* calculation of median */
if ( n % 2 == 0)
med = (arr[n/2] + arr[n/2+1])/2.0 ;
else
med = arr[n/2 + 1];
printf("\n\nMedian value is: %d\n", med);
}
|
C
|
/*
* Task.c
*
* Created: 2/23/2019 6:14:09 PM
* Author: AVE-LAP-005
*/
#include "Types.h"
#include "BitwiseOperations.h"
#include "Task.h"
#include "DIO_Interface.h"
/* array of tasks to check every task */
void (*Tasks[NO_OF_TASKS])(void)={led1_task,led2_task,led3_task};
/*Task Number one */
void led1_task(){
DIO_WritePin(12,High);
}
/*Task Number TWo */
void led2_task(){
DIO_WritePin(13,High);
}
/*Task Number Three */
void led3_task(){
DIO_WritePin(14,High);
}
|
C
|
// Author: Stewart A.
// Matric: 40345422
// Last Edit: 01.03.2019
/*
This code will take a .c input file and will output to a .o file while removing comments & adding all header file methods.
This is given that the header files that are given are also in the same directory as the target file.
DO NOT COMPILE BY ITSELF -- SEE README.TXT FOR MORE INFORMATION!!!
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINE_LENGTH 1000
int main(int argc, char *argv[])
{
char *input_file;
if (argc == 3)
{
if (strcmp(argv[0], "-i"))
{
input_file = argv[2];
FILE* input = fopen(input_file, "r"); // Input file for read access only.
char line[LINE_LENGTH];
int nonEmptyLines = 0;
int commentedLines = 0;
int i = 0;
while (input_file[i] != '\0') // Loops over the string until the end of the string is reached. Cited from: https://cboard.cprogramming.com/c-programming/146390-trim-last-character-string.html#post1091577
{
i++;
}
input_file[i - 2] = '\0'; // Awaiting the .o file extension -- See below.
FILE* output = fopen(strcat(input_file, ".o"), "w"); // Adds a .o file extension to the file // Output file for write access // generates if it doesn't exist.
while (fgets(line, LINE_LENGTH, input) != NULL) // To iterate over the whole file
{
if (!((line[0] == '\t')
|| (line[0] == '\n')
|| (line[0] == ' '))) // If the line isn't completely empty
{
nonEmptyLines++;
}
for (int i = 0; i < strlen(line); i++) // Iterate over the line by character
{
if ((line[i] == '#' && line[i + 1] == 'i')
|| (line[i] == '#' && line[i + 1] == ' ' && line[i + 2] == 'i')) // Checking for the start of a #include block.
{
char buffer[LINE_LENGTH];
int counter = 0;
for (int j = 10; j < strlen(line) - 1; j++) // Start at where we think the first quote is
{
buffer[counter] = line[j];
counter++;
}
printf("%s\n", buffer);
int k = 0;
while (buffer[k] != '\0') // Takes the line until there is a null terminator
{
k++;
}
buffer[k - 1] = '\0'; // Removes the last quote from the string -- Waiting to open .h
printf("%s\n", buffer);
line[i] = '\n';
line[i + 1] = '\0'; // Removes the #include from the document.
char header_line[LINE_LENGTH];
FILE* header_file = fopen(buffer, "r"); // Opens the header file for read-only access.
while (fgets(header_line, LINE_LENGTH, header_file) != NULL) // Iterates over the header file.
{
fputs(header_line, output);
}
fclose(header_file);
}
if ((line[i] == '/') && (line[i + 1] == '/')) // If a comment is found
{
commentedLines++;
line[i] = '\n';
line[i + 1] = '\0'; // Remove the comment from the file.
}
}
fputs(line, output);
}
int total_lines = 0;
total_lines = nonEmptyLines + commentedLines;
fclose(input);
fclose(output);
printf("The total number of lines without comments: %d\n", nonEmptyLines);
printf("The total number of line with comments (inline & standard): %d\n", commentedLines);
printf("The total number of lines in this file: %d\n", total_lines);
}
}
else if (argc == 4)
{
if (strcmp(argv[0], "-i") && strcmp(argv[2], "-c"))
{
input_file = argv[2];
FILE* input = fopen(input_file, "r"); // Input file for read access only.
char line[LINE_LENGTH];
int nonEmptyLines = 0;
int commentedLines = 0;
int i = 0;
while (input_file[i] != '\0') // Takes the line until there is a null terminator
{
i++;
}
input_file[i - 2] = '\0'; // Removes the file extension from the file -- Waiting to append .o below.
FILE* output = fopen(strcat(input_file, ".o"), "w"); // Output file for write access // generates if it doesn't exist.
while (fgets(line, LINE_LENGTH, input) != NULL) // To iterate over the whole file
{
if (!((line[0] == '\t')
|| (line[0] == '\n')
|| (line[0] == ' '))) // If the line isn't completely empty
{
nonEmptyLines++;
}
for (int i = 0; i < strlen(line); i++) // Iterate over the line by character
{
if ((line[i] == '#' && line[i + 1] == 'i')
|| (line[i] == '#' && line[i + 1] == ' ' && line[i + 2] == 'i')) // Checking for the start of a #include block.
{
char buffer[LINE_LENGTH];
int counter = 0;
for (int j = 10; j < strlen(line) - 1; j++) // Start at where we think the first quote is
{
buffer[counter] = line[j];
counter++;
}
printf("%s\n", buffer);
int k = 0;
while (buffer[k] != '\0') // Takes the line until there is a null terminator
{
k++;
}
buffer[k - 1] = '\0'; // Removes the last quote from the string -- Waiting to open .h
printf("%s\n", buffer);
line[i] = '\n';
line[i + 1] = '\0'; // Removes the #include from the document.
char header_line[LINE_LENGTH];
FILE* header_file = fopen(buffer, "r"); // Opens the header file for read-only access.
while (fgets(header_line, LINE_LENGTH, header_file) != NULL) // Iterates over the header file.
{
fputs(header_line, output);
}
fclose(header_file);
}
if ((line[i] == '/') && (line[i + 1] == '/')) // If the line is a comment
{
commentedLines++;
}
}
fputs(line, output);
}
int total_lines = 0;
total_lines = nonEmptyLines + commentedLines;
fclose(input);
fclose(output);
printf("The total number of lines without comments: %d\n", nonEmptyLines);
printf("The total number of line with comments (inline & standard): %d\n", commentedLines);
printf("The total number of lines in this file: %d\n", total_lines);
}
}
return 0;
}
|
C
|
/**
* https://www.spoj.pl/problems/CMEXPR/
* Schier Michael
*/
#include <stdio.h>
#define bool int
#define true 1
#define false 0
// input to read
unsigned char expression[250];
int len;
unsigned int openParenStack[125]; // stores the positions of openin parenthesis
unsigned char operatorStack[125]; // stores the inner operators of the corresponding parenthesis pairs: - overrides + overrides / overrides *
unsigned char lastOper; // helps when there are multiple closing parenthesis
int stackTop; // the size of the stack
// check whether we can remove this parenthesis pair
// preOper ( ...... innerOper ..... ) postOper
void closingParenthesis(int endPos)
{
char innerOper = operatorStack[stackTop];
operatorStack[stackTop] = 0;
int startPos = openParenStack[--stackTop];
char preOper = startPos > 0 ? expression[startPos-1] : 0;
if(preOper == '(')
preOper = 0;
char postOper = endPos < len - 1 ? expression[endPos+1] : 0;
if(postOper == ')')
postOper = 0;
if(innerOper != 0)
lastOper = innerOper;
else
innerOper = lastOper;
switch(innerOper)
{
case '-': // ( expr - expr )
case '+': // ( expr + expr )
if(preOper == '-' || preOper == '*' || preOper == '/' || postOper == '*' || postOper == '/')
return;
break;
case '/': // ( expr / expr )
case '*': // ( expr * expr )
if(preOper == '/')
return;
break;
default: // (x) or ((expr))
break;
}
// passed the check -> remove parenthesis
expression[startPos] = 0;
expression[endPos] = 0;
}
void transform()
{
stackTop = 0;
int i;
for(i = 0; i < len; i++)
{
switch(expression[i])
{
case '(':
openParenStack[stackTop++] = i;
lastOper = 0;
break;
case ')':
closingParenthesis(i);
break;
case '-':
operatorStack[stackTop] = '-';
break;
case '+':
if(operatorStack[stackTop] != '-')
operatorStack[stackTop] = '+';
case '/':
if(operatorStack[stackTop] != '-' && operatorStack[stackTop] != '+')
operatorStack[stackTop] = '/';
case '*':
if(operatorStack[stackTop] != '-' && operatorStack[stackTop] != '+' && operatorStack[stackTop] != '/')
operatorStack[stackTop] = '*';
break;
default:
break;
}
}
}
void readInput()
{
len = 0;
unsigned char c;
while(true)
{
c = getchar();
if(c == '\n' || c == EOF)
return;
expression[len++] = c;
}
}
void printOutput()
{
int i;
for(i = 0; i < len; i++)
if(expression[i] != 0)
putchar(expression[i]);
putchar('\n');
}
int main(int argc, char** args)
{
int t;
scanf("%i\n", &t);
while(t-->0)
{
readInput();
transform();
printOutput();
}
return 0;
}
|
C
|
#include "libs/test_queue.h"
#include "libs/test_stack.h"
// main function
int main(int argc, char **argv)
{
if (test_cq() == TRUE) // test cq
{
puts("Queue Test Passed."); // print success
}
else // test failed
{
puts("Queue Test Failed."); // print failure
}
puts("Test stack:"); // print test stack
if (test_list() == TRUE) // test list
{
puts("Stack Test Passed"); // print success
}
else // test failed
{
puts("Stack test Failed"); // print failure
}
return 0; // return
}
|
C
|
#include"kt.h"
void delete(st** ,int);
main()
{
st *hptr=0;
char ch;
int n;
do{
add(&hptr);
printf("add other (Y/N)\n");
scanf(" %c",&ch);
}while((ch=='y')||(ch=='Y'));
printf("before delete....\n");
traverse(hptr);
printf("No delete..");
scanf("%d",&n);
delete(&hptr,n);
printf("after delete..\n");
traverse(hptr);
}
void delete(st**ptr,int n)
{
st *t,*t1,*temp;
t=t1=*ptr;
int i=0,count=0;
while(count!=n)
{
i++;
t=t->next;
count++;
}
if(t){
while(t->next)
{
count++;
t=t->next;
t1=t1->next;
}
if(i==n)
{
temp=t1->next;
t1->next=temp->next;
free(temp);
temp==NULL;
}
}
else
{
temp=(*ptr);
*ptr=temp->next;
free(temp);
temp=NULL;
}
// printf("%d------%d\n",t->i,t1->i);
}
|
C
|
/*####################################################################
#
# TSCAT - A "cat" Command Which Can Reprodude the Timing of Flow
#
# USAGE : tscat [-c|-e|-z] [-Z] [-u] [-y] [-p n] [file [...]]
# Args : file ........ Filepath to be send ("-" means STDIN)
# The file MUST be a textfile and MUST have
# a timestamp at the first field to make the
# timing of flow. The first space character
# <0x20> of every line will be regarded as
# the field delimiter.
# And, the string from the top of the line to
# the charater will be cut before outgoing to
# the stdout.
# Options : -c,-e,-z .... Specify the format for timestamp. You can choose
# one of them.
# -c ... "YYYYMMDDhhmmss[.n]" (default)
# Calendar time (standard time) in your
# timezone (".n" is the digits under
# second. You can specify up to nano
# second.)
# -e ... "n[.n]"
# The number of seconds since the UNIX
# epoch (".n" is the same as -x)
# -z ... "n[.n]"
# The number of seconds since this
# command has startrd (".n" is the same
# as -x)
# -Z .......... Define the time when the first line came as 0.
# For instance, imagine that the first field of
# the first line is "20200229235959," and the
# second line's one is "20200301000004." when
# "-c" option is given. In this case, the first
# line is sent to stdout immediately, and after
# five seconds, the second line is sent.
# -u .......... Set the date in UTC when -c option is set
# (same as that of date command)
# -y .......... "Typing mode": Do not output the LF character
# at the end of each line in the input file unless
# the line has no other letters. This mode is
# useful to resconstruct the timing of key typing
# recorded by as in the following.
# $ typeliner -e | linets -c3 > mytyping.txt
# $ tscat -ycZ mytyping.txt
# [The following option is for professional]
# -p n ........ Process priority setting [0-3] (if possible)
# 0: Normal process
# 1: Weakest realtime process (default)
# 2: Strongest realtime process for generic users
# (for only Linux, equivalent 1 for otheres)
# 3: Strongest realtime process of this host
# Larger numbers maybe require a privileged user,
# but if failed, it will try the smaller numbers.
# Retuen : Return 0 only when finished successfully
#
# How to compile : cc -O3 -o __CMDNAME__ __SRCNAME__ -lrt
# (if it doesn't work)
# How to compile : cc -O3 -o __CMDNAME__ __SRCNAME__
#
# Written by Shell-Shoccar Japan (@shellshoccarjpn) on 2022-07-19
#
# This is a public-domain software (CC0). It means that all of the
# people can use this for any purposes with no restrictions at all.
# By the way, We are fed up with the side effects which are brought
# about by the major licenses.
#
# The latest version is distributed at the following page.
# https://github.com/ShellShoccar-jpn/misc-tools
#
####################################################################*/
/*####################################################################
# Initial Configuration
####################################################################*/
/*=== Initial Setting ==============================================*/
/*--- headers ------------------------------------------------------*/
#if defined(__linux) || defined(__linux__)
/* This definition is for strptime() on Linux */
#define _XOPEN_SOURCE 700
#endif
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <sys/select.h>
#include <time.h>
#include <fcntl.h>
#include <signal.h>
#include <locale.h>
#if defined(_POSIX_PRIORITY_SCHEDULING) && !defined(__OpenBSD__) && !defined(__APPLE__)
#include <sched.h>
#include <sys/resource.h>
#endif
/*--- macro constants ----------------------------------------------*/
/* Some OSes, such as HP-UX, may not know the following macros whenever
<limit.h> is included. So, this source code defines them by itself. */
#ifndef LONG_MAX
#define LONG_MAX 2147483647
#endif
#ifndef LLONG_MAX
#define LLONG_MAX 9223372036854775807
#endif
/*--- prototype functions ------------------------------------------*/
void get_time_data_arrived(int iFd, struct timespec *ptsTime);
int read_1st_field_as_a_timestamp(FILE *fp, char *pszTime);
int read_and_write_a_line(FILE *fp);
int skip_over_a_line(FILE *fp);
int parse_calendartime(char* pszTime, struct timespec *ptsTime);
int parse_unixtime(char* pszTime, struct timespec *ptsTime);
void spend_my_spare_time(struct timespec *ptsTo, struct timespec *ptsOffset);
int change_to_rtprocess(int iPrio);
/*--- global variables ---------------------------------------------*/
char* gpszCmdname; /* The name of this command */
int giTypingmode; /* Typing mode by option -y is on if >0 */
int giVerbose; /* speaks more verbosely by the greater number */
struct timespec gtsZero; /* The zero-point time */
/*=== Define the functions for printing usage and error ============*/
/*--- exit with usage ----------------------------------------------*/
void print_usage_and_exit(void) {
fprintf(stderr,
#if defined(_POSIX_PRIORITY_SCHEDULING) && !defined(__OpenBSD__) && !defined(__APPLE__)
"USAGE : %s [-c|-e|-z] [-Z] [-u] [-y] [-p n] [file [...]]\n"
#else
"USAGE : %s [-c|-e|-z] [-Z] [-u] [-y] [file [...]]\n"
#endif
"Args : file ........ Filepath to be send (\"-\" means STDIN)\n"
" The file MUST be a textfile and MUST have\n"
" a timestamp at the first field to make the\n"
" timing of flow. The first space character\n"
" <0x20> of every line will be regarded as\n"
" the field delimiter.\n"
" And, the string from the top of the line to\n"
" the charater will be cut before outgoing to\n"
" the stdout.\n"
"Options : -c,-e,-z .... Specify the format for timestamp. You can choose\n"
" one of them.\n"
" -c ... \"YYYYMMDDhhmmss[.n]\" (default)\n"
" Calendar time (standard time) in your\n"
" timezone (\".n\" is the digits under\n"
" second. You can specify up to nano\n"
" second.)\n"
" -e ... \"n[.n]\"\n"
" The number of seconds since the UNIX\n"
" epoch (\".n\" is the same as -c)\n"
" -z ... \"n[.n]\"\n"
" The number of seconds since this\n"
" command has started (\".n\" is the same\n"
" as -c)\n"
" -Z .......... Define the time when the first line came as 0.\n"
" For instance, imagine that the first field of\n"
" the first line is \"20200229235959,\" and the\n"
" second line's one is \"20200301000004.\" when\n"
" \"-c\" option is given. In this case, the first\n"
" line is sent to stdout immediately, and after\n"
" five seconds, the second line is sent.\n"
" -u .......... Set the date in UTC when -c option is set\n"
" (same as that of date command)\n"
" -y .......... \"Typing mode\": Do not output the LF character\n"
" at the end of each line in the input file unless\n"
" the line has no other letters. This mode is\n"
" useful to resconstruct the timing of key typing\n"
" recorded by as in the following.\n"
" $ typeliner -e | linets -c3 > mytyping.txt\n"
" $ tscat -ycZ mytyping.txt\n"
#if defined(_POSIX_PRIORITY_SCHEDULING) && !defined(__OpenBSD__) && !defined(__APPLE__)
" [The following option is for professional]\n"
" -p n ........ Process priority setting [0-3] (if possible)\n"
" 0: Normal process\n"
" 1: Weakest realtime process (default)\n"
" 2: Strongest realtime process for generic users\n"
" (for only Linux, equivalent 1 for otheres)\n"
" 3: Strongest realtime process of this host\n"
" Larger numbers maybe require a privileged user,\n"
" but if failed, it will try the smaller numbers.\n"
#endif
"Version : 2022-07-19 04:33:38 JST\n"
" (POSIX C language)\n"
"\n"
"Shell-Shoccar Japan (@shellshoccarjpn), No rights reserved.\n"
"This is public domain software. (CC0)\n"
"\n"
"The latest version is distributed at the following page.\n"
"https://github.com/ShellShoccar-jpn/misc-tools\n"
,gpszCmdname);
exit(1);
}
/*--- print warning message ----------------------------------------*/
void warning(const char* szFormat, ...) {
va_list va;
va_start(va, szFormat);
fprintf(stderr,"%s: ",gpszCmdname);
vfprintf(stderr, szFormat, va);
va_end(va);
return;
}
/*--- exit with error message --------------------------------------*/
void error_exit(int iErrno, const char* szFormat, ...) {
va_list va;
va_start(va, szFormat);
fprintf(stderr,"%s: ",gpszCmdname);
vfprintf(stderr, szFormat, va);
va_end(va);
exit(iErrno);
}
/*####################################################################
# Main
####################################################################*/
/*=== Initialization ===============================================*/
int main(int argc, char *argv[]) {
/*--- Variables ----------------------------------------------------*/
int iMode; /* 0:"-c" 1:"-e" 2:"-z",
4:"-cZ" 5:"-eZ" 6:"-zZ" */
int iPrio; /* -p option number (default 1) */
int iRet; /* return code */
int iGotOffset; /* 0:NotYet 1:GetZeroPoint 2:Done */
char szTime[33]; /* Buffer for the 1st field of lines */
struct timespec tsTime; /* Parsed time for the 1st field */
struct timespec tsOffset; /* Zero-point time to adjust the 1st field one */
char *pszPath; /* filepath on arguments */
char *pszFilename; /* filepath (for message) */
int iFileno; /* file# of filepath */
int iFd; /* file descriptor */
FILE *fp; /* file handle */
int i; /* all-purpose int */
/*--- Initialize ---------------------------------------------------*/
if (clock_gettime(CLOCK_REALTIME,>sZero) != 0) {
error_exit(errno,"clock_gettime() at initialize: %s\n",strerror(errno));
}
gpszCmdname = argv[0];
for (i=0; *(gpszCmdname+i)!='\0'; i++) {
if (*(gpszCmdname+i)=='/') {gpszCmdname=gpszCmdname+i+1;}
}
if (setenv("POSIXLY_CORRECT","1",1) < 0) {
error_exit(errno,"setenv() at initialization: \n", strerror(errno));
}
setlocale(LC_CTYPE, "");
/*=== Parse arguments ==============================================*/
/*--- Set default parameters of the arguments ----------------------*/
iMode = 0; /* 0:"-c"(default) 1:"-e" 2:"-z" 4:"-cZ" 5:"-eZ" 6:"-zZ" */
giTypingmode = 0;
iPrio = 1;
giVerbose = 0;
/*--- Parse options which start by "-" -----------------------------*/
while ((i=getopt(argc, argv, "cep:uyvhZz")) != -1) {
switch (i) {
case 'c': iMode&=4; iMode+=0; break;
case 'e': iMode&=4; iMode+=1; break;
case 'z': iMode&=4; iMode+=2; break;
case 'Z': iMode&=3; iMode+=4; break;
case 'u': (void)setenv("TZ", "UTC0", 1); break;
case 'y': giTypingmode=1; break;
#if defined(_POSIX_PRIORITY_SCHEDULING) && !defined(__OpenBSD__) && !defined(__APPLE__)
case 'p': if (sscanf(optarg,"%d",&iPrio) != 1) {print_usage_and_exit();}
break;
#endif
case 'v': giVerbose++; break;
case 'h': print_usage_and_exit();
default : print_usage_and_exit();
}
}
argc -= optind-1;
argv += optind ;
if (giVerbose>0) {warning("verbose mode (level %d)\n",giVerbose);}
/*=== Switch buffer mode ===========================================*/
if (setvbuf(stdout,NULL,(giTypingmode>0)?_IONBF:_IOLBF,0)!=0) {
error_exit(255,"Failed to switch to line-buffered mode\n");
}
/*=== Try to make me a realtime process ============================*/
if (change_to_rtprocess(iPrio)==-1) {print_usage_and_exit();}
/*=== Each file loop ===============================================*/
iRet = 0;
iGotOffset = 0;
iFileno = 0;
iFd = -1;
while ((pszPath = argv[iFileno]) != NULL || iFileno == 0) {
/*--- Open one of the input files --------------------------------*/
if (pszPath == NULL || strcmp(pszPath, "-") == 0) {
pszFilename = "stdin" ;
iFd = STDIN_FILENO ;
} else {
pszFilename = pszPath ;
while ((iFd=open(pszPath, O_RDONLY)) < 0) {
iRet = 1;
warning("%s: %s\n", pszFilename, strerror(errno));
iFileno++;
break;
}
if (iFd < 0) {continue;}
}
if (iFd == STDIN_FILENO) {
fp = stdin;
if (feof(stdin)) {clearerr(stdin);} /* Reset EOF condition when stdin */
} else {
fp = fdopen(iFd, "r");
}
/*--- Reading and writing loop -----------------------------------*/
switch (iMode) {
case 0: /* "-c" Calendar time mode */
while (1) {
switch (read_1st_field_as_a_timestamp(fp, szTime)) {
case 1: /* read successfully */
if (! parse_calendartime(szTime, &tsTime)) {
warning("%s: %s: Invalid calendar-time, "
"skip this line\n", pszFilename, szTime);
iRet = 1;
switch (skip_over_a_line(fp)) {
case 1: /* expected LF */
break;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
case -2: /* file access error */
warning("%s: File access error, "
"skip it\n", pszFilename);
goto CLOSE_THISFILE;
break;
default: /* bug of system error */
error_exit(1,"Unexpected error at %d\n",
__LINE__);
break;
}
break;
}
spend_my_spare_time(&tsTime, NULL);
switch (read_and_write_a_line(fp)) {
case 1: /* expected LF */
break;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
case -2: /* file access error */
warning("%s: File access error, "
"skip it\n", pszFilename);
iRet = 1;
goto CLOSE_THISFILE;
break;
default: /* bug of system error */
error_exit(1,"Unexpected error at %d\n",
__LINE__);
break;
}
break;
case 0: /* unexpected LF */
warning("%s: %s: Invalid timestamp field found, "
"skip this line.\n", pszFilename, szTime);
iRet = 1;
break;
case -2: /* unexpected EOF */
warning("%s: Came to EOF suddenly\n", pszFilename);
iRet = 1;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
break;
case -3: /* file access error */
warning("%s: File access error, skip it\n",
pszFilename);
iRet = 1;
goto CLOSE_THISFILE;
default: /* bug or system error */
error_exit(1,"Unexpected error at %d\n", __LINE__);
}
}
break;
case 1: /* "-e" UNIX epoch time mode */
while (1) {
switch (read_1st_field_as_a_timestamp(fp, szTime)) {
case 1: /* read successfully */
if (! parse_unixtime(szTime, &tsTime)) {
warning("%s: %s: Invalid UNIX-time, "
"skip this line\n", pszFilename, szTime);
iRet = 1;
switch (skip_over_a_line(fp)) {
case 1: /* expected LF */
break;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
case -2: /* file access error */
warning("%s: File access error, "
"skip it\n", pszFilename);
goto CLOSE_THISFILE;
break;
default: /* bug of system error */
error_exit(1,"Unexpected error at %d\n",
__LINE__);
break;
}
break;
}
spend_my_spare_time(&tsTime, NULL);
switch (read_and_write_a_line(fp)) {
case 1: /* expected LF */
break;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
case -2: /* file access error */
warning("%s: File access error, "
"skip it\n", pszFilename);
iRet = 1;
goto CLOSE_THISFILE;
break;
default: /* bug of system error */
error_exit(1,"Unexpected error at %d\n",
__LINE__);
break;
}
break;
case 0: /* unexpected LF */
warning("%s: %s: Invalid timestamp field found, "
"skip this line.\n", pszFilename, szTime);
iRet = 1;
break;
case -2: /* unexpected EOF */
warning("%s: Came to EOF suddenly\n", pszFilename);
iRet = 1;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
break;
case -3: /* file access error */
warning("%s: File access error, skip it\n",
pszFilename);
iRet = 1;
goto CLOSE_THISFILE;
default: /* bug or system error */
error_exit(1,"Unexpected error at %d\n", __LINE__);
}
}
break;
case 2: /* "-z" Zero time mode */
while (1) {
switch (read_1st_field_as_a_timestamp(fp, szTime)) {
case 1: /* read successfully */
if (! parse_unixtime(szTime, &tsTime)) {
warning("%s: %s: Invalid number of seconds, "
"skip this line\n", pszFilename, szTime);
iRet = 1;
switch (skip_over_a_line(fp)) {
case 1: /* expected LF */
break;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
case -2: /* file access error */
warning("%s: File access error, "
"skip it\n", pszFilename);
goto CLOSE_THISFILE;
break;
default: /* bug of system error */
error_exit(1,"Unexpected error at %d\n",
__LINE__);
break;
}
break;
}
if (iGotOffset<2) {
/* tsOffset = gtsZero - tsTime */
if ((gtsZero.tv_nsec - tsTime.tv_nsec) < 0) {
tsOffset.tv_sec = gtsZero.tv_sec
- tsTime.tv_sec - 1;
tsOffset.tv_nsec = gtsZero.tv_nsec
- tsTime.tv_nsec + 1000000000;
} else {
tsOffset.tv_sec = gtsZero.tv_sec -tsTime.tv_sec ;
tsOffset.tv_nsec = gtsZero.tv_nsec-tsTime.tv_nsec;
}
iGotOffset=2;
}
spend_my_spare_time(&tsTime, &tsOffset);
switch (read_and_write_a_line(fp)) {
case 1: /* expected LF */
break;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
case -2: /* file access error */
warning("%s: File access error, "
"skip it\n", pszFilename);
iRet = 1;
goto CLOSE_THISFILE;
break;
default: /* bug of system error */
error_exit(1,"Unexpected error at %d\n",
__LINE__);
break;
}
break;
case 0: /* unexpected LF */
warning("%s: %s: Invalid timestamp field found, "
"skip this line.\n", pszFilename, szTime);
iRet = 1;
break;
case -2: /* unexpected EOF */
warning("%s: Came to EOF suddenly\n", pszFilename);
iRet = 1;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
break;
case -3: /* file access error */
warning("%s: File access error, skip it\n",
pszFilename);
iRet = 1;
goto CLOSE_THISFILE;
default: /* bug or system error */
error_exit(1,"Unexpected error at %d\n", __LINE__);
}
}
break;
case 4: /* "-cZ" Calendar time with immediate outgoing mode */
if (iGotOffset==0) {
get_time_data_arrived(iFd, >sZero);
iGotOffset=1;
}
while (1) {
switch (read_1st_field_as_a_timestamp(fp, szTime)) {
case 1: /* read successfully */
if (! parse_calendartime(szTime, &tsTime)) {
warning("%s: %s: Invalid calendar-time, "
"skip this line\n", pszFilename, szTime);
iRet = 1;
switch (skip_over_a_line(fp)) {
case 1: /* expected LF */
break;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
case -2: /* file access error */
warning("%s: File access error, "
"skip it\n", pszFilename);
goto CLOSE_THISFILE;
break;
default: /* bug of system error */
error_exit(1,"Unexpected error at %d\n",
__LINE__);
break;
}
break;
}
if (iGotOffset==1) {
/* tsOffset = gtsZero - tsTime */
if ((gtsZero.tv_nsec - tsTime.tv_nsec) < 0) {
tsOffset.tv_sec = gtsZero.tv_sec
- tsTime.tv_sec - 1;
tsOffset.tv_nsec = gtsZero.tv_nsec
- tsTime.tv_nsec + 1000000000;
} else {
tsOffset.tv_sec = gtsZero.tv_sec -tsTime.tv_sec ;
tsOffset.tv_nsec = gtsZero.tv_nsec-tsTime.tv_nsec;
}
iGotOffset=2;
}
spend_my_spare_time(&tsTime, &tsOffset);
switch (read_and_write_a_line(fp)) {
case 1: /* expected LF */
break;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
case -2: /* file access error */
warning("%s: File access error, "
"skip it\n", pszFilename);
iRet = 1;
goto CLOSE_THISFILE;
break;
default: /* bug of system error */
error_exit(1,"Unexpected error at %d\n",
__LINE__);
break;
}
break;
case 0: /* unexpected LF */
warning("%s: %s: Invalid timestamp field found, "
"skip this line.\n", pszFilename, szTime);
iRet = 1;
break;
case -2: /* unexpected EOF */
warning("%s: Came to EOF suddenly\n", pszFilename);
iRet = 1;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
break;
case -3: /* file access error */
warning("%s: File access error, skip it\n",
pszFilename);
goto CLOSE_THISFILE;
default: /* bug or system error */
error_exit(1,"Unexpected error at %d\n", __LINE__);
}
}
break;
case 5: /* "-eZ" UNIX epoch time with immediate outgoing mode */
case 6: /* "-zZ" Zero time with immediate outgoing mode */
if (iGotOffset==0) {
get_time_data_arrived(iFd, >sZero);
iGotOffset=1;
}
while (1) {
switch (read_1st_field_as_a_timestamp(fp, szTime)) {
case 1: /* read successfully */
if (! parse_unixtime(szTime, &tsTime)) {
warning("%s: %s: Invalid timestamp, "
"skip this line\n", pszFilename, szTime);
iRet = 1;
switch (skip_over_a_line(fp)) {
case 1: /* expected LF */
break;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
case -2: /* file access error */
warning("%s: File access error, "
"skip it\n", pszFilename);
goto CLOSE_THISFILE;
break;
default: /* bug of system error */
error_exit(1,"Unexpected error at %d\n",
__LINE__);
break;
}
break;
}
if (iGotOffset==1) {
/* tsOffset = gtsZero - tsTime */
if ((gtsZero.tv_nsec - tsTime.tv_nsec) < 0) {
tsOffset.tv_sec = gtsZero.tv_sec
- tsTime.tv_sec - 1;
tsOffset.tv_nsec = gtsZero.tv_nsec
- tsTime.tv_nsec + 1000000000;
} else {
tsOffset.tv_sec = gtsZero.tv_sec -tsTime.tv_sec ;
tsOffset.tv_nsec = gtsZero.tv_nsec-tsTime.tv_nsec;
}
iGotOffset=2;
}
spend_my_spare_time(&tsTime, &tsOffset);
switch (read_and_write_a_line(fp)) {
case 1: /* expected LF */
break;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
case -2: /* file access error */
warning("%s: File access error, "
"skip it\n", pszFilename);
iRet = 1;
goto CLOSE_THISFILE;
break;
default: /* bug of system error */
error_exit(1,"Unexpected error at %d\n",
__LINE__);
break;
}
break;
case 0: /* unexpected LF */
warning("%s: %s: Invalid timestamp field found, "
"skip this file.\n", pszFilename, szTime);
iRet = 1;
break;
case -2: /* unexpected EOF */
warning("%s: Came to EOF suddenly\n", pszFilename);
iRet = 1;
case -1: /* expected EOF */
goto CLOSE_THISFILE;
break;
case -3: /* file access error */
warning("%s: File access error, skip it\n",
pszFilename);
iRet = 1;
goto CLOSE_THISFILE;
default: /* bug or system error */
error_exit(1,"Unexpected error at %d\n", __LINE__);
}
}
break;
default:
error_exit(255,"main() #L1: Invalid mode number\n");
}
CLOSE_THISFILE:
/*--- Close the input file ---------------------------------------*/
if (fp != stdin) {fclose(fp);}
/*--- End loop ---------------------------------------------------*/
if (pszPath == NULL) {break;}
iFileno++;
}
/*=== Finish normally ==============================================*/
return(iRet);}
/*####################################################################
# Functions
####################################################################*/
/*=== Read and write only one line having a timestamp ================
* [in] iFd : File descriptor number for read
* ptsTime : Pointer to return the time when data arrived
* [ret] (none) : This function alway calls error_exit() if any error
occured. */
void get_time_data_arrived(int iFd, struct timespec *ptsTime) {
/*--- Variables --------------------------------------------------*/
fd_set fdsRead;
/*--- Wait for data arriving -------------------------------------*/
FD_ZERO(&fdsRead);
FD_SET(iFd, &fdsRead);
if (select(iFd+1, &fdsRead, NULL, NULL, NULL) == -1) {
error_exit(errno,"select() in get_time_data_arrived(): %s\n",
strerror(errno));
}
/*--- Set the time -----------------------------------------------*/
if (clock_gettime(CLOCK_REALTIME,ptsTime) != 0) {
error_exit(errno,"clock_gettime() in get_time_data_arrived(): %s\n",
strerror(errno));
}
}
/*=== Read and write only one line having a timestamp ================
* [in] fp : Filehandle for read
* pszTime : Pointer for the string buffer to get the timestamp on
* the 1st field
* (Size of the buffer you give MUST BE 33 BYTES or more!)
* [ret] == 0 : Finished reading due to '\n'
* == 1 : Finished reading successfully, you may use the result in
* the buffer
* ==-1 : Finished reading because no more data in the "fp"
* ==-2 : Finished reading due to the end of file
* ==-3 : Finished reading due to a file reading error
* other: Finished reading due to a system error */
int read_1st_field_as_a_timestamp(FILE *fp, char *pszTime) {
/*--- Variables --------------------------------------------------*/
int iTslen = 0; /* length of the timestamp string */
int iChar;
/*--- Reading and writing a line ---------------------------------*/
while (1) {
iChar = getc(fp);
switch (iChar) {
case ' ' :
case '\t':
pszTime[iTslen]=0;
return 1;
case EOF :
if (feof( fp)) {
if (iTslen==0) {
return -1;
} else {
if (giVerbose>0) {
warning("EOF came while reading 1st field\n");
}
return -2;
}
} else if (ferror(fp)) {
if (giVerbose>0) {
warning("error while reading 1st field\n");
}
return -3;
} else {
return -4;
}
case '\n':
return 0;
default :
if (iTslen>31) { continue;}
else {pszTime[iTslen]=iChar; iTslen++; continue;}
}
}
}
/*=== Read and write only one line ===================================
* [in] fp : Filehandle for read
* [ret] == 1 : Finished reading/writing due to '\n', which is the last
* char of the file
* ==-1 : Finished reading due to the end of file
* ==-2 : Finished reading due to a file reading error
* ==-3 : Finished reading due to a system error */
int read_and_write_a_line(FILE *fp) {
/*--- Variables --------------------------------------------------*/
int iChar;
/*--- Reading and writing a line (normal mode) -------------------*/
if (! giTypingmode) {
while (1) {
iChar = getc(fp);
switch (iChar) {
case EOF :
if (feof( fp)) {return -1;}
if (ferror(fp)) {return -2;}
else {return -3;}
case '\n':
if (putchar('\n' )==EOF) {
error_exit(errno,"stdout write error #1: %s\n",
strerror(errno));
}
return 1;
default :
if (putchar(iChar)==EOF) {
error_exit(errno,"stdout write error #2: %s\n",
strerror(errno));
}
break;
}
}
return -3;
}
/*--- Reading and writing a line (typing mode) -------------------*/
iChar = getc(fp);
switch (iChar) {
case EOF :
if (feof( fp)) {return -1;}
if (ferror(fp)) {return -2;}
else {return -3;}
case '\n':
if (putchar('\n' )==EOF) {
error_exit(errno,"stdout write error #3: %s\n",
strerror(errno));
}
return 1;
default :
if (putchar(iChar)==EOF) {
error_exit(errno,"stdout write error #4: %s\n",
strerror(errno));
}
break;
}
while (1) {
iChar = getc(fp);
switch (iChar) {
case EOF :
if (feof( fp)) {return -1;}
if (ferror(fp)) {return -2;}
else {return -3;}
case '\n':
return 1;
default :
if (putchar(iChar)==EOF) {
error_exit(errno,"stdout write error #5: %s\n",
strerror(errno));
}
break;
}
}
}
/*=== Read and throw away one line ===================================
* [in] fp : Filehandle for read
* [ret] == 1 : Finished reading/writing due to '\n', which is the last
* char of the file
* ==-1 : Finished reading due to the end of file
* ==-2 : Finished reading due to a file reading error
* ==-3 : Finished reading due to a system error */
int skip_over_a_line(FILE *fp) {
/*--- Variables --------------------------------------------------*/
int iChar;
/*--- Reading and writing a line ---------------------------------*/
while (1) {
iChar = getc(fp);
switch (iChar) {
case EOF :
if (feof( fp)) {return -1;}
if (ferror(fp)) {return -2;}
else {return -3;}
case '\n':
return 1;
default :
break;
}
}
}
/*=== Parse a local calendar time ====================================
* [in] pszTime : calendar-time string in the localtime
* (/[0-9]{11,20}(\.[0-9]{1,9})?/)
* ptsTime : To be set the parsed time ("timespec" structure)
* [ret] > 0 : success
* ==0 : error (failure to parse) */
int parse_calendartime(char* pszTime, struct timespec *ptsTime) {
/*--- Variables --------------------------------------------------*/
char szDate[21], szNsec[10], szDate2[26];
int i, j, k; /* +-- 0:(reading integer part) */
char c; /* +-- 1:finish reading without_decimals */
int iStatus = 0; /* <--------- 2:to_be_started reading decimals */
struct tm tmDate;
/*--- Separate pszTime into date and nanoseconds -----------------*/
for (i=0; i<20; i++) {
c = pszTime[i];
if (('0'<=c) && (c<='9')) {szDate[i]=c; }
else if (c=='.' ) {szDate[i]=0; iStatus=2; i++; break;}
else if (c==0 ) {szDate[i]=0; iStatus=1; break;}
else {if (giVerbose>0) {
warning("%c: Unexpected chr. in "
"the integer part\n",c);
}
return 0;
}
}
if ((iStatus==0) && (i==20)) {
switch (pszTime[20]) {
case '.': szDate[20]=0; iStatus=2; i++; break;
case 0 : szDate[20]=0; iStatus=1; break;
default : warning("The integer part of the timestamp is too big "
"as a calendar-time\n",c);
return 0;
}
}
switch (iStatus) {
case 1 : strcpy(szNsec,"000000000");
break;
case 2 : j=i+9;
k=0;
for (; i<j; i++) {
c = pszTime[i];
if (('0'<=c) && (c<='9')) {szNsec[k]=c; k++;}
else if (c==0 ) {break; }
else {
if (giVerbose>0) {
warning("%c: Unexpected chr. in the decimal part\n",c);
}
return 0;
}
}
for (; k<9; k++) {szNsec[k]='0';}
szNsec[9]=0;
break;
default: warning("Unexpected error in parse_calendartime(), "
"maybe a bug?\n");
return 0;
}
/*--- Pack the time-string into the timespec structure -----------*/
i = strlen(szDate)-10;
if (i<=0) {return 0;}
k =0; for (j=0; j<i; j++) {szDate2[k]=szDate[j];k++;} /* Y */
szDate2[k]='-'; k++;
i+=2; for ( ; j<i; j++) {szDate2[k]=szDate[j];k++;} /* m */
szDate2[k]='-'; k++;
i+=2; for ( ; j<i; j++) {szDate2[k]=szDate[j];k++;} /* d */
szDate2[k]='T'; k++;
i+=2; for ( ; j<i; j++) {szDate2[k]=szDate[j];k++;} /* H */
szDate2[k]=':'; k++;
i+=2; for ( ; j<i; j++) {szDate2[k]=szDate[j];k++;} /* M */
szDate2[k]=':'; k++;
i+=2; for ( ; j<i; j++) {szDate2[k]=szDate[j];k++;} /* S */
szDate2[k]= 0;
memset(&tmDate, 0, sizeof(tmDate));
if(! strptime(szDate2, "%Y-%m-%dT%H:%M:%S", &tmDate)) {return 0;}
ptsTime->tv_sec = mktime(&tmDate);
ptsTime->tv_nsec = atol(szNsec);
return 1;
}
/*=== Parse a UNIX-time ==============================================
* [in] pszTime : UNIX-time string (/[0-9]{1,19}(\.[0-9]{1,9})?/)
* ptsTime : To be set the parsed time ("timespec" structure)
* [ret] > 0 : success
* ==0 : error (failure to parse) */
int parse_unixtime(char* pszTime, struct timespec *ptsTime) {
/*--- Variables --------------------------------------------------*/
char szSec[20], szNsec[10];
int i, j, k; /* +-- 0:(reading integer part) */
char c; /* +-- 1:finish reading without_decimals */
int iStatus = 0; /* <--------- 2:to_be_started reading decimals */
/*--- Separate pszTime into seconds and nanoseconds --------------*/
for (i=0; i<19; i++) {
c = pszTime[i];
if (('0'<=c) && (c<='9')) {szSec[i]=c; }
else if (c=='.' ) {szSec[i]=0; iStatus=2; i++; break;}
else if (c==0 ) {szSec[i]=0; iStatus=1; break;}
else {if (giVerbose>0) {
warning("%c: Unexpected chr. in "
"the integer part\n",c);
}
return 0;
}
}
if ((iStatus==0) && (i==19)) {
switch (pszTime[19]) {
case '.': szSec[19]=0; iStatus=2; i++; break;
case 0 : szSec[19]=0; iStatus=1; break;
default : warning("The integer part of the timestamp is too big "
"as a UNIX-time\n");
return 0;
}
}
switch (iStatus) {
case 1 : strcpy(szNsec,"000000000");
break;
case 2 : j=i+9;
k=0;
for (; i<j; i++) {
c = pszTime[i];
if (('0'<=c) && (c<='9')) {szNsec[k]=c; k++;}
else if (c==0 ) {break; }
else {
if (giVerbose>0) {
warning("%c: Unexpected chr. in the decimal part\n",c);
}
return 0;
}
}
for (; k<9; k++) {szNsec[k]='0';}
szNsec[9]=0;
break;
default: warning("Unexpected error in parse_unixtime(), maybe a bug?\n");
return 0;
}
/*--- Pack the time-string into the timespec structure -----------*/
ptsTime->tv_sec = (time_t)atoll(szSec);
if (ptsTime->tv_sec<0) {
ptsTime->tv_sec = (sizeof(time_t)>=8) ? LLONG_MAX : LONG_MAX;
}
ptsTime->tv_nsec = atol(szNsec);
return 1;
}
/*=== Sleep until the next interval period ===========================
* [in] ptsTo : Time until which this function wait
(given from the 1st field of a line, which not adjusted yet)
ptsOffset : Offset for ptsTo (set NULL if unnecessary) */
void spend_my_spare_time(struct timespec *ptsTo, struct timespec *ptsOffset) {
/*--- Variables --------------------------------------------------*/
struct timespec tsTo ;
struct timespec tsDiff;
struct timespec tsNow ;
/*--- Calculate how long I wait ----------------------------------*/
if (! ptsOffset) {
/* tsTo = ptsTo */
tsTo.tv_sec = ptsTo->tv_sec ;
tsTo.tv_nsec = ptsTo->tv_nsec;
} else {
/* tsTo = ptsTo + ptsOffset */
tsTo.tv_nsec = ptsTo->tv_nsec + ptsOffset->tv_nsec;
if (tsTo.tv_nsec > 999999999) {
tsTo.tv_nsec -= 1000000000;
tsTo.tv_sec = ptsTo->tv_sec + ptsOffset->tv_sec + 1;
} else {
tsTo.tv_sec = ptsTo->tv_sec + ptsOffset->tv_sec;
}
}
/* tsNow = (current_time) */
if (clock_gettime(CLOCK_REALTIME,&tsNow) != 0) {
error_exit(errno,"clock_gettime() in spend_my_spare_time(): %s\n",
strerror(errno));
}
/* tsDiff = tsTo - tsNow */
if ((tsTo.tv_nsec - tsNow.tv_nsec) < 0) {
tsDiff.tv_sec = tsTo.tv_sec - tsNow.tv_sec - 1;
tsDiff.tv_nsec = tsTo.tv_nsec - tsNow.tv_nsec + 1000000000;
} else {
tsDiff.tv_sec = tsTo.tv_sec - tsNow.tv_sec ;
tsDiff.tv_nsec = tsTo.tv_nsec - tsNow.tv_nsec;
}
/*--- Sleeping for tsDiff ----------------------------------------*/
while (nanosleep(&tsDiff,NULL) != 0) {
if (errno == EINVAL) { /* It means ptsNow is a past time, doesn't matter */
if (giVerbose>1) {warning("Waiting time is negative\n");}
break;
}
error_exit(errno,"nanosleep() in spend_my_spare_time(): %s\n",
strerror(errno));
}
}
/*=== Try to make me a realtime process ==============================
* [in] iPrio : 0:will not change (just return normally)
* 1:minimum priority
* 2:maximun priority for non-privileged users (only Linux)
* 3:maximun priority of this host
* [ret] = 0 : success, or errno
* =-1 : error (by this function)
* > 0 : error (by system call, and the value means "errno") */
int change_to_rtprocess(int iPrio) {
#if defined(_POSIX_PRIORITY_SCHEDULING) && !defined(__OpenBSD__) && !defined(__APPLE__)
/*--- Variables --------------------------------------------------*/
struct sched_param spPrio;
#ifdef RLIMIT_RTPRIO
struct rlimit rlInfo;
#endif
/*--- Initialize -------------------------------------------------*/
memset(&spPrio, 0, sizeof(spPrio));
/*--- Decide the priority number ---------------------------------*/
switch (iPrio) {
case 3 : if ((spPrio.sched_priority=sched_get_priority_max(SCHED_RR))==-1) {
return errno;
}
if (sched_setscheduler(0, SCHED_RR, &spPrio)==0) {
if (giVerbose>0) {warning("\"-p3\": succeeded\n" );}
return 0;
} else {
if (giVerbose>0) {warning("\"-p3\": %s\n",strerror(errno));}
}
case 2 :
#ifdef RLIMIT_RTPRIO
if ((getrlimit(RLIMIT_RTPRIO,&rlInfo))==-1) {
return errno;
}
if (rlInfo.rlim_cur > 0) {
spPrio.sched_priority=rlInfo.rlim_cur;
if (sched_setscheduler(0, SCHED_RR, &spPrio)==0) {
if (giVerbose>0){warning("\"-p2\" succeeded\n" );}
return 0;
} else {
if (giVerbose>0){warning("\"-p2\": %s\n",strerror(errno));}
}
if (giVerbose>0) {warning("\"-p2\": %s\n",strerror(errno));}
} else if (giVerbose>0) {
warning("RLIMIT_RTPRIO isn't set\n");
}
#endif
case 1 : if ((spPrio.sched_priority=sched_get_priority_min(SCHED_RR))==-1) {
return errno;
}
if (sched_setscheduler(0, SCHED_RR, &spPrio)==0) {
if (giVerbose>0) {warning("\"-p1\": succeeded\n" );}
return 0;
} else {
if (giVerbose>0) {warning("\"-p1\": %s\n",strerror(errno));}
}
return errno;
case 0 : if (giVerbose>0) {warning("\"-p0\": succeeded\n");}
return 0;
default: return -1;
}
#endif
/*--- Return successfully ----------------------------------------*/
return 0;
}
|
C
|
#include <stdio.h>
void copyString(char [], char [], int);
int main()
{
char str1[20], str2[20];
printf(" Input the string to copy : ");
scanf("%s", str1);
copyString(str1, str2, 0);
printf(" The first string is : %s\n", str1);
printf(" The copied string is : %s\n\n", str2);
return 0;
}
void copyString(char str1[], char str2[], int ctr)
{
str2[ctr] = str1[ctr];
if (str1[ctr] == '\0')
return;
copyString(str1, str2, ctr + 1);
}
|
C
|
/**
* --- bst.h -------------------------------------------------
* Header file with public interface for a Binary Search Tree.
* March 4, 2020
*/
#ifndef BST_H
#define BST_H
#include "item.h"
/**
* Tipo Node. Um struct que possui campos
* para a chave, para o valor, e ponteiros
* para o filho esquerdo e direito. */
struct Node;
/**
* Recebe um ponteiro para um no da arvore e retorna
* a chave contida neste no */
Tkey bst_getKey(Node *node);
/**
* Recebe um ponteiro para um no da arvore e retorna
* o valor contido neste no */
Tvalue bst_getValue(Node *node);
/**
* Recebe o ponteiro para a raiz da arvore e
* para a chave a ser pesquisada. Retorna o ponteiro
* para o no se a chave for encontrada; ou retorna nullptr
* caso contrário */
Node *bst_search(Node *node, Tkey key);
/**
* Recebe um ponteiro para a raiz da arvore, uma chave e um valor.
* Se a chave nao existir, insere um novo no com o par (chave,valor)
* Se a chave existir, nao insere nada.
* Retorna um ponteiro para a raiz da arvore modificada. */
Node *bst_insert(Node *node, Tkey key, Tvalue value);
/**
* Recebe um ponteiro para a raiz da arvore e
* Percorre os nos da arvore em pre-ordem e imprime na
* tela os pares (chave, valor) */
void bst_preorder(Node *node);
/**
* Recebe um ponteiro para a raiz da arvore e
* recebe um ponteiro f para uma funcao.
* Percorre os nos da arvore em pre-ordem fazendo o que
* a funcao f disser para fazer. */
void bst_preorder(Node *node, void f(Node*));
/**
* Recebe um ponteiro para a raiz da arvore e
* Percorre os nos da arvore em ordem simetrica (inorder) e imprime na
* tela os pares (chave, valor) */
void bst_inorder(Node *node);
/**
* Recebe um ponteiro para a raiz da arvore e
* Percorre os nos da arvore em pós-ordem e imprime na
* tela os pares (chave, valor) */
void bst_postorder(Node *node);
/**
* Recebe um ponteiro para a raiz da arvore e retorna a
* altura da arvore. */
int bst_height(Node *node);
/**
* Recebe um ponteiro para a raiz da arvore.
* Retorna true se a arvore estiver vazia e false, caso
* contrario. */
bool bst_empty(Node* node);
/**
* Recebe um ponteiro para a raiz da arvore e libera todos
* os nos, deixando a arvore vazia. Retorna nullptr. */
Node *bst_clear(Node *node);
/**
* Recebe um ponteiro para a raiz da arvore e uma chave.
* Se existir um no com essa chave, remove o no.
* Se nao existir, nada acontece.
* Retorna um ponteiro para a raiz da arvore modificada. */
Node *bst_remove(Node *node, Tkey key);
/**
* Recebe um ponteiro para a raiz da arvore e
* retorna um ponteiro para o no que contem a menor chave */
Node *bst_minimum(Node *node);
/**
* Recebe um ponteiro para a raiz da arvore e
* retorna um ponteiro para o no que contem a maior chave */
Node *bst_maximum(Node *node);
/**
* Recebe como parametro um ponteiro para a raiz da arvore
* e um ponteiro para um no x.
* Retorna o ponteiro para o no cuja chave eh sucessora
* da chave contida em x. */
Node* bst_successor(Node* root, Node *x);
/**
* Recebe como parametro um ponteiro para a raiz da arvore
* e um ponteiro para um no x.
* Retorna o ponteiro para o no cuja chave eh antecessora
* da chave contida em x. */
Node* bst_predecessor(Node* root, Node *x);
#endif
|
C
|
/* This program demonstrates formated scanf statement for floating-point input.
written by :
Date :
*/
#include<stdio.h>
main()
{
/* Local Definitions */
char name[9],name1[9],name2[9];
/*Statements*/
printf("Enter the name\n");
scanf("%4c",name);
printf("Enter the name\n");
scanf("%s",name1);
printf("Enter the name\n");
scanf("%4s",name2);
printf("\n%s",name);
printf("\n%s",name1);
printf("\n%s",name2);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include "format_validity.h"
#include "../misc/error_handler.h"
/* Serial format
* - min: 12 characters
* - max: 126 characters
* - type: 0-9, A-F
*/
__attribute__((pure))
int32_t check_serial_format(char *serial)
{
uint32_t i = 0;
size_t len = 0;
/* Check lenght validity */
len = strlen(serial);
if ((len < 12) || (len > 126))
{
return DEVIDD_ERR_OTHER;
}
for (i = 0; i < len; i++)
{
/* A character is valid if and only if its format is hexadecimal
and if it is not a lowercase */
if (!isxdigit(serial[i]) || islower(serial[i]))
{
return DEVIDD_ERR_OTHER;
}
}
return DEVIDD_SUCCESS;
}
/* Vendor/product format:
* - fixed size: 4
* - type: 0-9, A-F
*/
__attribute__((pure))
int32_t check_vendor_product_format(char *str)
{
int32_t i = 0;
if (strlen(str) != LEN_VENDOR_PRODUCT)
{
return DEVIDD_ERR_OTHER;
}
for (i = 0; i < LEN_VENDOR_PRODUCT; i++)
{
/* A character is valid if and only if its format is hexadecimal
and if it is not a lowercase */
if (!isxdigit(str[i]) || islower(str[i]))
{
return DEVIDD_ERR_OTHER;
}
}
return DEVIDD_SUCCESS;
}
/* Bcd_device format:
* - fixed size: 16
* - type: 0-1
*/
__attribute__((pure))
int32_t check_bcd_format(char *bcd)
{
int32_t i = 0;
if (strlen(bcd) != LEN_BCD)
{
return DEVIDD_ERR_OTHER;
}
for (i = 0; i < LEN_BCD; i++)
{
/* A character is valid if and only if its format is hexadecimal
and if it is not a lowercase */
if ((bcd[i] != '0') && (bcd[i] != '1'))
{
return DEVIDD_ERR_OTHER;
}
}
return DEVIDD_SUCCESS;
}
__attribute__((pure))
int32_t check_machine_format(char *machine)
{
if (strlen(machine) != LEN_FIELD)
return DEVIDD_ERR_OTHER;
return DEVIDD_SUCCESS;
}
__attribute__((pure))
int32_t check_bus_port_format(char *str)
{
int32_t i = 0;
if (strlen(str) > MAX_BUS_PORT)
{
return DEVIDD_ERR_OTHER;
}
for (i = 0; i < MAX_BUS_PORT; i++)
{
/* A character is valid if and only if its format is hexadecimal
and if it is not a lowercase */
if (!isdigit(str[i]))
{
return DEVIDD_ERR_OTHER;
}
}
return DEVIDD_SUCCESS;
}
__attribute__((pure))
int32_t check_horaries_format(char *field)
{
uint32_t i = 0;
size_t len = 0;
int32_t dash = DEVIDD_ERR_OTHER;
len = strlen(field);
if (len > LEN_FIELD)
{
return DEVIDD_ERR_OTHER;
}
for (i = 0; i < len; i++)
{
/* If not a digit, the character is unvalid */
if (isdigit(field[i]) == 0 && field[i] != '-')
{
return DEVIDD_ERR_OTHER;
}
if ((i != 0) && (i < len - 1) && field[i] == '-')
{
dash = DEVIDD_SUCCESS;
}
}
/* If no dash was found, dash is set to DEVIDD_ERR */
return dash;
}
__attribute__((pure))
int32_t check_field_format(char *field, int32_t i)
{
int32_t validity = DEVIDD_SUCCESS;
switch(i)
{
case FIELD_MACHINE:
if (check_machine_format(field) != DEVIDD_SUCCESS)
{
validity = DEVIDD_ERR_OTHER;
}
break;
case FIELD_BUS:
case FIELD_PORT:
if (check_bus_port_format(field) != DEVIDD_SUCCESS)
{
validity = DEVIDD_ERR_OTHER;
}
break;
case FIELD_SERIAL:
if (check_serial_format(field) != DEVIDD_SUCCESS)
{
validity = DEVIDD_ERR_OTHER;
}
break;
case FIELD_VENDOR:
case FIELD_PRODUCT:
if (check_vendor_product_format(field) != DEVIDD_SUCCESS)
{
validity = DEVIDD_ERR_OTHER;
}
break;
case FIELD_BCD:
if (check_bcd_format(field) != DEVIDD_SUCCESS)
{
validity = DEVIDD_ERR_OTHER;
}
break;
case FIELD_HORARY:
if (check_horaries_format(field) != DEVIDD_SUCCESS)
{
validity = DEVIDD_ERR_OTHER;
}
break;
default:
validity = DEVIDD_ERR_OTHER;
}
return validity;
}
/* Rule format:
(accept:user):machine:bus:port:serial:vendor:product:bcd:horary
- 8 fields
- length field: max 64
*/
int32_t check_rule_format(char * rule)
{
int32_t i = 0;
char *token = NULL;
int32_t valid = DEVIDD_SUCCESS;
token = calloc(1, DEVID_MAX_LEN);
if (token == NULL)
{
return DEVIDD_ERR_MEM;
}
for (i = 0; token != NULL; i++)
{
if (i == 0)
{
token = strtok(rule, ":");
}
else
{
token = strtok(NULL, ":");
}
valid = check_field_format(token, i);
if (valid != DEVIDD_SUCCESS)
break;
if (strlen(token) > LEN_FIELD)
{
syslog(LOG_ERR, "Rule %s invalid: field %s is too long",
rule, token);
valid = DEVIDD_ERR_OTHER;
break;
}
}
if (i != NB_FIELD_COMPLETE_ID)
{
syslog(LOG_ERR, "Rule %s invalid: %d fields found, 7 expected",
rule, (i + 1));
valid = DEVIDD_ERR_OTHER;
}
free(token);
return valid;
}
|
C
|
/*
* File: time.h
* Author: root
*
* Created on April 17, 2014, 10:40 PM
*/
#ifndef TIME_H
#define TIME_H
/*! \file
* \brief Time-related functions and macros
*/
#define HAVE_SYS_TIME_H 1
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <stdio.h>
#include <sys/types.h>
#include <stdint.h>
#include "inline_api.h"
/* We have to let the compiler learn what types to use for the elements of a
struct timeval since on linux, it's time_t and suseconds_t, but on *BSD,
they are just a long. */
extern struct timeval tv;
typedef typeof(tv.tv_sec) css_time_t;
typedef typeof(tv.tv_usec) css_suseconds_t;
/*!
* \brief Computes the difference (in seconds) between two \c struct \c timeval instances.
* \param end the end of the time period
* \param start the beginning of the time period
* \return the difference in seconds
*/
CSS_INLINE_API(
int64_t css_tvdiff_sec(struct timeval end, struct timeval start),
{
int64_t result = end.tv_sec - start.tv_sec;
if (result > 0 && end.tv_usec < start.tv_usec)
result--;
else if (result < 0 && end.tv_usec > start.tv_usec)
result++;
return result;
}
)
/*!
* \brief Computes the difference (in microseconds) between two \c struct \c timeval instances.
* \param end the end of the time period
* \param start the beginning of the time period
* \return the difference in microseconds
*/
CSS_INLINE_API(
int64_t css_tvdiff_us(struct timeval end, struct timeval start),
{
return (end.tv_sec - start.tv_sec) * (int64_t) 1000000 +
end.tv_usec - start.tv_usec;
}
)
/*!
* \brief Computes the difference (in milliseconds) between two \c struct \c timeval instances.
* \param end end of the time period
* \param start beginning of the time period
* \return the difference in milliseconds
*/
CSS_INLINE_API(
int64_t css_tvdiff_ms(struct timeval end, struct timeval start),
{
/* the offset by 1,000,000 below is intentional...
it avoids differences in the way that division
is handled for positive and negative numbers, by ensuring
that the divisor is always positive
*/
return ((end.tv_sec - start.tv_sec) * 1000) +
(((1000000 + end.tv_usec - start.tv_usec) / 1000) - 1000);
}
)
/*!
* \brief Returns true if the argument is 0,0
*/
CSS_INLINE_API(
int css_tvzero(const struct timeval t),
{
return (t.tv_sec == 0 && t.tv_usec == 0);
}
)
/*!
* \brief Compres two \c struct \c timeval instances returning
* -1, 0, 1 if the first arg is smaller, equal or greater to the second.
*/
CSS_INLINE_API(
int css_tvcmp(struct timeval _a, struct timeval _b),
{
if (_a.tv_sec < _b.tv_sec)
return -1;
if (_a.tv_sec > _b.tv_sec)
return 1;
/* now seconds are equal */
if (_a.tv_usec < _b.tv_usec)
return -1;
if (_a.tv_usec > _b.tv_usec)
return 1;
return 0;
}
)
/*!
* \brief Returns true if the two \c struct \c timeval arguments are equal.
*/
CSS_INLINE_API(
int css_tveq(struct timeval _a, struct timeval _b),
{
return (_a.tv_sec == _b.tv_sec && _a.tv_usec == _b.tv_usec);
}
)
/*!
* \brief Returns current timeval. Meant to replace calls to gettimeofday().
*/
CSS_INLINE_API(
struct timeval css_tvnow(void),
{
struct timeval t;
gettimeofday(&t, NULL);
return t;
}
)
/*!
* \brief Returns the sum of two timevals a + b
*/
struct timeval css_tvadd(struct timeval a, struct timeval b);
/*!
* \brief Returns the difference of two timevals a - b
*/
struct timeval css_tvsub(struct timeval a, struct timeval b);
/*!
* \brief Returns a timeval from sec, usec
*/
CSS_INLINE_API(
struct timeval css_tv(css_time_t sec, css_suseconds_t usec),
{
struct timeval t;
t.tv_sec = sec;
t.tv_usec = usec;
return t;
}
)
/*!
* \brief Returns a timeval corresponding to the duration of n samples at rate r.
* Useful to convert samples to timevals, or even milliseconds to timevals
* in the form css_samp2tv(milliseconds, 1000)
*/
CSS_INLINE_API(
struct timeval css_samp2tv(unsigned int _nsamp, unsigned int _rate),
{
return css_tv(_nsamp / _rate, ((_nsamp % _rate) * (4000000 / _rate)) / 4); /* this calculation is accurate up to 32000Hz. */
}
)
#endif /* TIME_H */
|
C
|
#include "../include/factory.h"
int simpleCommend(int socketFd, char *dirName, int command, void (*print)(char *Info))
{
linkMsg_t lmsg;
memset(&lmsg, 0, sizeof(lmsg));
lmsg.flag = command;
strcpy(lmsg.buf, dirName);
strcpy(lmsg.token, TOKEN);
lmsg.size = MSGHEADSIZE + strlen(lmsg.buf);
send(socketFd, &lmsg, lmsg.size, 0);
#ifdef ERROR_DEBUG
printf("\n\nsend information\n");
printf("lmsg.buf = %s##\n", lmsg.buf);
printf("send lsmg.size = %d\n", lmsg.size);
#endif
//接收返回信息
int ret;
bzero(lmsg.buf, strlen(lmsg.buf));
ret = recvCycle(socketFd, &lmsg, MSGHEADSIZE);
if (-1 == ret)
{
return -1;
}
ret = recvCycle(socketFd, lmsg.buf, lmsg.size - MSGHEADSIZE);
if (-1 == ret)
{
return -1;
}
if (SUCCESS == lmsg.flag)
{
print(lmsg.buf);
}
else
{
printf("error:%s\n", lmsg.buf);
}
return 0;
}
int upload(int socketFd, char *filename)
{
int ret;
int fd = open(filename, O_RDONLY);
ERROR_CHECK(fd, -1, "open");
struct stat fileStat;
fstat(fd, &fileStat);
char md5Str[40] = {0};
char fileType[4] = {0};
if (S_ISDIR(fileStat.st_mode))
{
fileType[0] = 'd';
}
else
{
fileType[0] = '-';
}
Compute_file_md5(filename, md5Str);
linkMsg_t lmsg;
bzero(&lmsg, sizeof(lmsg));
sprintf(lmsg.buf, "%s %s %s", fileType, filename, md5Str);
lmsg.flag = PUTSCOMMEND;
lmsg.size = strlen(lmsg.buf) + MSGHEADSIZE;
lmsg.fileSize = fileStat.st_size;
strcpy(lmsg.token, TOKEN);
send(socketFd,&lmsg, lmsg.size, 0);
#ifdef TEST_DOWNLOAD
printf("\n\n---------------upload.c line = %d------------\n", __LINE__);
printf("size = %d, flag = %d, fileSize = %ld\n", lmsg.size, lmsg.flag, lmsg.fileSize);
printf("token = %s\n", lmsg.token);
printf("filename = %s\n", lmsg.buf);
#endif
ret = recvCycle(socketFd, &lmsg, MSGHEADSIZE);
recvCycle(socketFd, lmsg.buf, lmsg.size - MSGHEADSIZE);
size_t offset;
sscanf(lmsg.buf, "%ld", &offset);
if (SUCCESS == lmsg.flag)
{
char *pMap = (char *)mmap(NULL, lmsg.fileSize, PROT_READ, MAP_SHARED, fd, 0);
send(socketFd, pMap + offset, lmsg.fileSize - offset, 0);
ret = munmap(pMap, lmsg.fileSize);
ERROR_CHECK(ret, -1, "munmap");
close(fd);
return 0;
}
else if (EXIST_FLAG == lmsg.flag)
{
printf("upload success!\n");
close(fd);
return 0;
}
else
{
recvCycle(socketFd, lmsg.buf, lmsg.size - MSGHEADSIZE); //接收错误信息
printf("upload refuse\n");
printf("%s\n", lmsg.buf);
close(fd);
return lmsg.flag;
}
}
int download(int socketFd, char* filename)
{
//打开文件
char pathName[100]={0};
sprintf(pathName,"../bin/%s",filename);
int newFileFd = open(pathName, O_CREAT| O_RDWR, 0666);
ERROR_CHECK(newFileFd, -1, "open");
/*获取当前文件大小,用做偏移量*/
struct stat fileStat;
fstat(newFileFd, &fileStat);
/*传送文件名,当前文件大小*/
linkMsg_t lmsg;
memset(&lmsg, 0, sizeof(lmsg));
sprintf(lmsg.buf, "%s %ld", filename, fileStat.st_size);
strcpy(lmsg.token, TOKEN);
lmsg.flag = GETSCOMMEND;
lmsg.size = MSGHEADSIZE + strlen(lmsg.buf);
send(socketFd, &lmsg, lmsg.size, 0);
#ifdef TEST_DOWNLOAD
printf("\n\n------------------------download.c 1------------\n");
printf("size = %d, flag = %d, fileSize = %ld\n", lmsg.size, lmsg.flag, lmsg.fileSize);
printf("filename = %s\n", lmsg.buf);
#endif
int ret;
//接收文件大小,和服务器确认信息
recvCycle(socketFd, &lmsg, MSGHEADSIZE);
#ifdef TEST_DOWNLOAD
printf("\n\n----------------download.c 1-----------------\n");
printf("size = %d, flag = %d, fileSize = %ld\n", lmsg.size, lmsg.flag, lmsg.fileSize);
printf("%s\n", lmsg.buf);
#endif
if(SUCCESS == lmsg.flag){
//设置偏移量
size_t offset = fileStat.st_size;
lseek(newFileFd, offset, SEEK_CUR);
//接收文件类型,Md5, 文件大小
char fileType[4] = {0};
char Md5Str[MD5SIZE] = {0};
size_t fileSize = 0;
recvCycle(socketFd, &lmsg.buf, lmsg.size - MSGHEADSIZE);
sscanf(lmsg.buf,"%s %s %ld", fileType, Md5Str, &fileSize);
/*
size_t totalNow = offset;
size_t prev = totalNow;
size_t limitSize = fileSize/10000;
*/
int fds[2];
pipe(fds);
while(1)
{
ret = splice(socketFd, NULL, fds[1], NULL, 20000, SPLICE_F_MORE | SPLICE_F_MOVE);
//printf("ret = %d\n", ret);
if(0 == ret)
{
printf("传输完毕\n");
break;
}
splice(fds[0], NULL, newFileFd, NULL, ret, SPLICE_F_MORE | SPLICE_F_MOVE);
/*
totalNow += ret;
if(totalNow - prev > limitSize)
{
printf("%50.2lf%%\r", (double)totalNow/fileSize*100);
fflush(stdout);
prev = totalNow;
}
*/
}
ret = close(fds[1]);
ret = close(fds[0]);
close(newFileFd);
printf("download success\n");
return 0;
}else if(FILE_EXIST_FLAG == lmsg.flag){
printf("文件已存在\n");
return 0;
}else{
printf("download refuse\n");
printf("%s\n", lmsg.buf); //服务器拒绝,并返回拒绝信息
close(newFileFd);
return -1;
}
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
int A, B, a, b;
scanf("%d %d", &a, &b);
A = (a % 10) * 100 + (a % 100 / 10) * 10 + (a / 100);
B = (b % 10) * 100 + (b % 100 / 10) * 10 + (b / 100);
if (A > B) printf("%d\n", A);
else printf("%d\n", B);
return 0;
}
|
C
|
/*
Problem Statement:Write a program which accept number from user and count frequency of such a
digits which are less than 6.
Input : 2395
Output : 3
Input : 1018
Output : 3
Input : 9440
Output : 3
Input : 96672
Output : 1
*/
#include"header.h"
int main()
{
int iValue=0;
int iRet=0;
printf("Enter the Number :");
scanf("%d",&iValue);
iRet=FeqSix(iValue);
printf("Frequency of Number which is less than 6 is : %d\n ",iRet);
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include "getnum.h"
#define TRUE 1
#define FALSE 0
int esCapicua(int num);
int
main()
{
int boleto, capicua;
do
{
boleto = getint("Ingrese un numero de boleto: ");
if(boleto < 0)
{
printf("Ingreso incorrecto de datos\n");
}
} while (boleto < 0);
capicua = esCapicua(boleto);
printf("El boleto %ses capicúa\n", (capicua) ? "" : "no ");
return capicua;
}
int
esCapicua(int num)
{
int aux = num;
int invertido = 0;
while(aux > 0)
{
invertido = 10 * invertido + (aux % 10);
aux /= 10;
}
return (invertido == num) ? TRUE : FALSE;
}
|
C
|
/*
* This file is in the Public Domain
*
* Based on code from Public Domain snprintf.c from mutt
* http://dev.mutt.org/hg/mutt/file/55cd4cb611d9/snprintf.c
* Tue Aug 08 22:49:12 2006 +0000
*
*/
#ifdef HAVE_CONFIG_H
#include <raptor_config.h>
#endif
#include "raptor.h"
#include "raptor_internal.h"
#include <float.h>
#define __USE_ISOC99 1
#include <math.h>
#ifndef HAVE_ROUND
/* round (C99): round x to the nearest integer, away from zero */
#define round(x) (((x) < 0) ? (long)((x)-0.5) : (long)((x)+0.5))
#endif
#ifndef HAVE_TRUNC
/* trunc (C99): round x to the nearest integer, towards zero */
#define trunc(x) (((x) < 0) ? ceil((x)) : floor((x)))
#endif
/* Convert a double to xsd:decimal representation.
* Returned is a pointer to the first character of the number
* in buffer (don't free it).
*/
char*
raptor_format_float(char *buffer, size_t *currlen, size_t maxlen,
double fvalue, unsigned int min, unsigned int max,
int flags)
{
/* DBL_EPSILON = 52 digits */
#define FRAC_MAX_LEN 52
double ufvalue;
double intpart;
double fracpart = 0;
double frac;
double frac_delta = 10;
double mod_10;
size_t exp_len;
size_t frac_len = 0;
size_t idx;
if (max < min)
max = min;
/* index to the last char */
idx = maxlen - 1;
buffer[idx--] = '\0';
ufvalue = fabs (fvalue);
intpart = round(ufvalue);
/* We "cheat" by converting the fractional part to integer by
* multiplying by a factor of 10
*/
frac = (ufvalue - intpart);
for (exp_len=0; exp_len <= max; ++exp_len) {
frac *= 10;
mod_10 = trunc(fmod(trunc(frac), 10));
if (fabs(frac_delta - (fracpart / pow(10, exp_len))) < (DBL_EPSILON * 2.0)) {
break;
}
frac_delta = fracpart / pow(10, exp_len);
/* Only "append" (numerically) if digit is not a zero */
if (mod_10 > 0 && mod_10 < 10) {
fracpart = round(frac);
frac_len = exp_len;
}
}
if (frac_len < min) {
buffer[idx--] = '0';
} else {
/* Convert/write fractional part (right to left) */
do {
mod_10 = fmod(trunc(fracpart), 10);
--frac_len;
buffer[idx--] = "0123456789"[(unsigned)mod_10];
fracpart /= 10;
} while(fracpart > 1 && (frac_len + 1) > 0);
}
buffer[idx--] = '.';
/* Convert/write integer part (right to left) */
do {
buffer[idx--] = "0123456789"[(int)fmod(intpart, 10)];
intpart /= 10;
} while(round(intpart));
/* Write a sign, if requested */
if(fvalue < 0)
buffer[idx--] = '-';
else if(flags)
buffer[idx--] = '+';
*currlen = maxlen - idx - 2;
return buffer + idx + 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(){
// Variables.
int array[3][4] = {{1,1,1,1}, {1,4,4,1}, {10, 10, 3, 3}};
int sum[3] = {0,0,0};
// Operations.
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
sum[i] += array[i][j];
}
}
// Outputs.
for (int i = 0; i < 3; i++)
{
printf("The value in %i position is: %i\n", i, sum[i]);
}
return 0;
}
|
C
|
/*****************************************************************************************************************/
/* Atomic Weight Calculator */
/*****************************************************************************************************************/
/*
* Author: Aly Khan Nuruddin
* Date: May 26, 2021
*
* Purpose: This program reads the atomic compositions of various amino acids from a data file, and then
* prints ther identification numbers and computed atomic weights on the screen, for the user.
*/
/*****************************************************************************************************************/
#define _CRT_SECURE_NO_WARNINGS // Prohibit the compiler from suggesting secure versions of library functions.
#include <stdio.h> // Include the standard input and output library in C.
#define OXYGEN_ATOMIC_MASS 15.99940 // Define the atomic mass of oxygen in a.m.u.
#define CARBON_ATOMIC_MASS 12.01100 // Define the atomic mass of carbon in a.m.u.
#define NITROGEN_ATOMIC_MASS 14.00674 // Define the atomic mass of nitrogen in a.m.u.
#define SULFUR_ATOMIC_MASS 32.06600 // Define the atomic mass of sulfur in a.m.u.
#define HYDROGEN_ATOMIC_MASS 1.00794 // Define the atomic mass of hydrogen in a.m.u.
int main(void) // Define the function "main".
{
FILE* inputFile; // Define the file pointer for the data file that is to be opened.
inputFile = fopen("amino_acids.txt", "r"); // Open the file that stores the identification numbers and number of moles of each element for each amino acid.
if (inputFile == NULL) // Define the condition when the file operation fails.
{
printf("Error: The file cannot be opened! "); // Notify the user that the file cannot be opened.
printf("Please check for a valid file. "); // Request the user to check for a valid file.
}
else // Define the condition when the file operation succeeds.
{
int identificationNumber; // Define the variable that stores the identification number of each amino acid.
int oxygenMoles; // Define the variable that stores the number of moles of oxygen.
int carbonMoles; // Define the variable that stores the number of moles of carbon.
int nitrogenMoles; // Define the variable that stores the number of moles of nitrogen.
int sulfurMoles; // Define the variable that stores the number of moles of sulfur.
int hydrogenMoles; // Define the variable that stores the number of moles of hydrogen.
float atomicWeight; // Define the variable that stores the atomic weight of each amino acid.
printf("For each amino acid, the first column indicates its identification number while the second column refers to its atomic weight, computed to six decimal places in g/mol.\n "); // Inform the user what the data value in each column represents.
while (fscanf(inputFile, "%d %d %d %d %d %d", &identificationNumber, &oxygenMoles, &carbonMoles, &nitrogenMoles, &sulfurMoles, &hydrogenMoles) != EOF) // Read the identification number and number of moles of each element for, row by row, from the data file.
{
atomicWeight = (oxygenMoles * OXYGEN_ATOMIC_MASS) + (carbonMoles * CARBON_ATOMIC_MASS) + (nitrogenMoles * NITROGEN_ATOMIC_MASS) + (sulfurMoles * SULFUR_ATOMIC_MASS) + (hydrogenMoles * HYDROGEN_ATOMIC_MASS); // Compute the atomic weight of each amino acid in grams per mol.
printf("\n%d %.6f\n\n", identificationNumber, atomicWeight); // Print the identification number and atomic weight of each amino acid upto six decimal places.
}
fclose(inputFile); // Close the file that stores the identification numbers and number of moles of each element for each amino acid.
}
system("PAUSE"); // Suspend the execution of the program.
return 0; // Terminate the execution of the program.
}
|
C
|
#include "../Inc/move.h"
// TODO: check borders.
// TODO: check consecutive moves
int findMove(int stackToPush)
{
STACK_TYPE newNode;
int children = 0;
newNode.finalMove = true;
if (((ballX - 1) > 0) && ((map[ballX][ballY] & 0x01) == 0))
{
newNode.move = 0x01;
newNode.finalMove = ((map[ballX - 1][ballY] == 0x00) ? true : false);
sPush(newNode, stackToPush);
children++;
}
if (((ballX - 1) > 0) && ((ballY + 1) < col) && ((map[ballX][ballY] & 0x02) == 0))
{
newNode.move = 0x02;
newNode.finalMove = ((map[ballX - 1][ballY + 1] == 0x00) ? true : false);
sPush(newNode, stackToPush);
children++;
}
if (((ballY + 1) < col) && ((map[ballX][ballY] & 0x04) == 0))
{
newNode.move = 0x04;
newNode.finalMove = ((map[ballX][ballY + 1] == 0x00) ? true : false);
sPush(newNode, stackToPush);
children++;
}
if (((ballX + 1) < row) && ((ballY + 1) < col) && ((map[ballX][ballY] & 0x08) == 0))
{
newNode.move = 0x08;
newNode.finalMove = ((map[ballX + 1][ballY + 1] == 0x00) ? true : false);
sPush(newNode, stackToPush);
children++;
}
if (((ballX + 1) < row) && ((map[ballX][ballY] & 0x10) == 0))
{
newNode.move = 0x10;
newNode.finalMove = ((map[ballX + 1][ballY] == 0x00) ? true : false);
sPush(newNode, stackToPush);
children++;
}
if (((ballX + 1) < row) && ((ballY - 1) > 0) && ((map[ballX][ballY] & 0x20) == 0))
{
newNode.move = 0x20;
newNode.finalMove = ((map[ballX + 1][ballY - 1] == 0x00) ? true : false);
sPush(newNode, stackToPush);
children++;
}
if (((ballY - 1) > 0) && ((map[ballX][ballY] & 0x40) == 0))
{
newNode.move = 0x40;
newNode.finalMove = ((map[ballX][ballY - 1] == 0x00) ? true : false);
sPush(newNode, stackToPush);
children++;
}
if (((ballX - 1) > 0) && ((ballY - 1) > 0) && ((map[ballX][ballY] & 0x80) == 0))
{
newNode.move = 0x80;
newNode.finalMove = ((map[ballX - 1][ballY - 1] == 0x00) ? true : false);
sPush(newNode, stackToPush);
children++;
}
return children;
}
void applyMove(STACK_TYPE moveNode)
{
map[ballX][ballY] = map[ballX][ballY] | moveNode.move;
if (moveNode.move & 0x01)
{
ballX -= 1;
map[ballX][ballY] |= 0x10;
}
else if (moveNode.move & 0x02)
{
ballX -= 1;
ballY += 1;
map[ballX][ballY] |= 0x20;
}
else if (moveNode.move & 0x04)
{
ballY += 1;
map[ballX][ballY] |= 0x40;
}
else if (moveNode.move & 0x08)
{
ballX += 1;
ballY += 1;
map[ballX][ballY] |= 0x80;
}
else if (moveNode.move & 0x10)
{
ballX += 1;
map[ballX][ballY] |= 0x01;
}
else if (moveNode.move & 0x20)
{
ballX += 1;
ballY -= 1;
map[ballX][ballY] |= 0x02;
}
else if (moveNode.move & 0x40)
{
ballY -= 1;
map[ballX][ballY] |= 0x04;
}
else if (moveNode.move & 0x80)
{
ballX -= 1;
ballY -= 1;
map[ballX][ballY] |= 0x08;
}
if (ballX <= 0 || ballY < 0)
int x = 5;
}
void reverseMove(STACK_TYPE moveNode)
{
if (moveNode.move & 0x01)
{
map[ballX][ballY] &= (0x10 ^ 0xFF);
ballX += 1;
}
else if (moveNode.move & 0x02)
{
map[ballX][ballY] &= (0x20 ^ 0xFF);
ballX += 1;
ballY -= 1;
}
else if (moveNode.move & 0x04)
{
map[ballX][ballY] &= (0x40 ^ 0xFF);
ballY -= 1;
}
else if (moveNode.move & 0x08)
{
map[ballX][ballY] &= (0x80 ^ 0xFF);
ballX -= 1;
ballY -= 1;
}
else if (moveNode.move & 0x10)
{
map[ballX][ballY] &= (0x01 ^ 0xFF);
ballX -= 1;
}
else if (moveNode.move & 0x20)
{
map[ballX][ballY] &= (0x02 ^ 0xFF);
ballX -= 1;
ballY += 1;
}
else if (moveNode.move & 0x40)
{
map[ballX][ballY] &= (0x04 ^ 0xFF);
ballY += 1;
}
else if (moveNode.move & 0x80)
{
map[ballX][ballY] &= (0x08 ^ 0xFF);
ballX += 1;
ballY += 1;
}
map[ballX][ballY] &= (moveNode.move ^ 0xFF);
}
|
C
|
/**
* \file
* \brief Tests for octopus publish/subscribe API
*/
/*
* Copyright (c) 2011, ETH Zurich.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <octopus/octopus.h>
#include <octopus/definitions.h>
#include <octopus/pubsub.h>
#include "common.h"
static const char* barrier_name = "d2pubsub_test";
static struct thread_sem ts;
static void message_handler(oct_mode_t mode, const char* record, void* st)
{
size_t* received = (size_t*) st;
if (mode & OCT_ON_PUBLISH) {
static const char* receive_order[] =
{ "msg_2", "msg_4", "msg_5", "msg_5", "msg_6", "msg_7" };
char* name = NULL;
debug_printf("Message: %s received: %zx\n", record, *received);
errval_t err = oct_read(record, "%s", &name);
ASSERT_ERR_OK(err);
ASSERT_STRING(receive_order[*received], name);
free(name);
}
else if (mode & OCT_REMOVED) {
debug_printf("OCT_REMOVED set...\n");
}
(*received)++;
}
static void subscriber(void)
{
errval_t err;
subscription_t id1 = 0;
subscription_t id2 = 0;
subscription_t id3 = 0;
subscription_t id4 = 0;
size_t received = 0;
char* barrier_record = NULL;
thread_sem_init(&ts, 0);
err = oct_subscribe(message_handler, &received, &id1, "111 [] attr: 10 }");
ASSERT_ERR(err, OCT_ERR_PARSER_FAIL);
err = oct_subscribe(message_handler, &received, &id1,
"_ { fl: 1.01, attr: 10 }");
ASSERT_ERR_OK(err);
debug_printf("id is: %"PRIu64"\n", id1);
char* str = "test.txt";
err = oct_subscribe(message_handler, &received, &id2, "_ { str: r'%s' }",
str);
ASSERT_ERR_OK(err);
debug_printf("id is: %"PRIu64"\n", id2);
err = oct_subscribe(message_handler, &received, &id3, "_ { age > %d }",
9);
ASSERT_ERR_OK(err);
debug_printf("id is: %"PRIu64"\n", id3);
err = oct_subscribe(message_handler, &received, &id4,
"r'^msg_(6|7)$'");
ASSERT_ERR_OK(err);
debug_printf("id is: %"PRIu64"\n", id4);
// Synchronize with publisher
err = oct_barrier_enter(barrier_name, &barrier_record, 2);
if (err_is_fail(err)) DEBUG_ERR(err, "barrier enter");
assert(err_is_ok(err));
// Wait until all messages received
while(received != 6) {
messages_wait_and_handle_next();
}
// Unsubscribe message handlers
err = oct_unsubscribe(id1);
ASSERT_ERR_OK(err);
err = oct_unsubscribe(id2);
ASSERT_ERR_OK(err);
err = oct_unsubscribe(id3);
ASSERT_ERR_OK(err);
err = oct_unsubscribe(id4);
ASSERT_ERR_OK(err);
while(received != 10) {
messages_wait_and_handle_next();
}
oct_barrier_leave(barrier_record);
free(barrier_record);
printf("Subscriber all done.\n");
}
static void publisher(void)
{
errval_t err;
char* barrier_record = NULL;
// Synchronize with subscriber
err = oct_barrier_enter(barrier_name, &barrier_record, 2);
if (err_is_fail(err)) DEBUG_ERR(err, "barrier enter");
assert(err_is_ok(err));
err = oct_publish("msg_1 { age: %d }", 9);
ASSERT_ERR_OK(err);
err = oct_publish("msg_2 { age: %d }", 10);
ASSERT_ERR_OK(err);
err = oct_publish("msg_3 { str: %d, age: '%d' }", 123, 8);
ASSERT_ERR_OK(err);
err = oct_publish("msg_4 { str: 'test.txt' }");
ASSERT_ERR_OK(err);
err = oct_publish("msg_5 { str: 'test.txt', attr: 10, fl: 1.01 }");
ASSERT_ERR_OK(err);
err = oct_publish("msg_6 { type: 'test', pattern: '123123' }");
ASSERT_ERR_OK(err);
err = oct_publish("msg_7 { type: 'test' }");
ASSERT_ERR_OK(err);
oct_barrier_leave(barrier_record);
free(barrier_record);
printf("Publisher all done.\n");
}
int main(int argc, char** argv)
{
oct_init();
assert(argc >= 2);
if (strcmp(argv[1], "subscriber") == 0) {
subscriber();
} else if (strcmp(argv[1], "publisher") == 0) {
publisher();
} else {
printf("Bad arguments (Valid choices are subscriber/publisher).");
}
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
int factorical (int n) {
int i, result = 1;
for (i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int perm (int n, int m) {
if (!n || !m) {
printf("illegal data\n");
return -1;
}
if (n < m) {
printf("inconsistent data\n");
return -1;
}
return factorical(n) / factorical(n - m);
}
int main () {
int n, m;
printf("Please enter two number with a space between these, n m: ");
scanf("%d%d", &n, &m);
printf("%d\n", perm(n, m));
}
|
C
|
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "c_utils.h"
#include "dbg.h"
#include "gfg.h"
static int loc[1010];
static int aux[1010];
static size_t aux_index[1010];
int cmp(const void* a, const void* b)
{
return *(int*)a - *(int*)b;
}
int rev_cmp(const void* a, const void* b)
{
return *(int*)b - *(int*)a;
}
int cus_cmp(const void* a, const void* b)
{
const int x = *((const int *)a);
const int y = *((const int *)b);
if (aux[x] == aux[y])
return x - y;
else
return aux[y] - aux[x];
}
int maximum_subarray(int A[], size_t n, int* res)
{
int maxSoFar = INT_MIN, maxAtIndex = 0, temp = 0;
for (size_t index = 0; index<n; index++)
{
//get max for subarray that ends at index
temp = maxAtIndex + A[index];
maxAtIndex = temp < A[index] ? A[index] : temp;
//update global max
if (maxSoFar < maxAtIndex) {
maxSoFar = maxAtIndex;
}
}
*res = maxSoFar;
return 0;
}
int find_missing_number(int A[], size_t n, int* res)
{
// Calculate X = XOR of first n+1 natural numbers
int X = 0;
for(size_t i = 1; i <= n+1; i++)
X ^= i;
// Calculate Y = XOR of all numbers in array
int Y = 0;
for(size_t i = 0;i < n; i++)
Y ^= A[i];
// return X^Y = missing number
*res = X^Y;
return 0;
}
int subarray_with_given_sum(int A[], size_t n, int s, size_t res[], size_t m)
{
size_t start = 0, end = 0;
int curr = 0;
// loop invariant : curr is sum of elements in [start,end)
while(start<n)
{
if(curr == s) break;
else if(curr < s)
{
if(end < n)
curr += A[end++];
else break;
}
else curr -= A[start++];
}
// put results in res if curr == s
if(curr == s)
{
check(m >= 2, "result array should be atleast 2 integer length");
res[0] = start+1;
res[1] = end;
return 0;
}
else return -1;
error:
return -1;
}
int sort_012(int A[], size_t n)
{
size_t b = 0, m = 0, e = n;
// loop invariant : 0s in [0,b), 1s in [b,m),
// [m,e) is unsorted & 2s in [e,n)
while (m < e)
{
if (A[m] == 0)
{
if (b != m) swap(A+b, A+m);
b++; m++;
}
else if (A[m] == 1)
{
m++;
}
else if (A[m] == 2)
{
e--;
swap(A+m, A+e);
}
}
return 0;
}
int equilibrium_point(int A[], size_t n, size_t *res)
{
//
if (n == 1)
*res = 1;
// find sum of all array elements
int sum = 0;
for (size_t i = 0; i < n; i++)
sum += A[i];
// loop invariant : sl = sum of elements in [0, i)
// sr = sum of elements in (i,n)
size_t i = 0;
int sl = 0, sr = sum - A[0];
for (i = 1; i < n; i++)
{
sl += A[i - 1];
sr -= A[i];
if (sl == sr)
{
*res = i + 1;
break;
}
}
if (i == n && n != 1) return -1;
return 0;
}
int maximum_sum_increasing_subsequence(int A[], size_t n, int* res)
{
// find MIS ending at index i
// loop invariant : aux[i] = sum of MIS starting in [0,i] and ending at i
for (size_t i = 0; i < n; i++)
{
aux[i] = A[i];
//loop invariant : aux[i] = sum of MIS for subarray [0,j] and ending at i
for (size_t j = 0; j < i; j++)
{
if (A[j] < A[i] && aux[i] < aux[j] + A[i])
{
aux[i] = aux[j] + A[i];
}
}
}
// find largest MIS ending at any index.
int max_sum = aux[0];
for (size_t i = 1; i < n; i++)
{
if (aux[i] > max_sum)
{
max_sum = aux[i];
}
}
*res = max_sum;
return 0;
}
int leaders_in_an_array(int A[], size_t n, int *res, size_t* res_size)
{
//loop invariant : A[aux_index[i]] is the largest element in [j,n)
size_t i = 0;
aux_index[i] = n - 1;
for (size_t j = n - 2; j < (size_t)-1; j--)
{
if (A[j] >= A[aux_index[i]])
{
i++;
aux_index[i] = j;
}
}
// copy leaders to result in reverse order
*res_size = 0;
while (i < (size_t)-1)
{
res[*res_size] = A[aux_index[i]];
(*res_size)++;
i--;
}
return 0;
}
int minimum_platforms(int A[], int B[], size_t n, int* res)
{
// sort arrival and departure of trains in ascending order.
qsort(A, n, sizeof(int), cmp);
qsort(B, n, sizeof(int), cmp);
// count = number of platforms
int count = 0;
*res = 1;
size_t i = 0, j = 0;
while (i < n && j < n)
{
if (A[i] < B[j])
{
count++; i++;
if (count > *res) *res = count;
}
else
{
count--; j++;
}
}
return 0;
}
int maximums_of_subarray_size_k(int A[], size_t n, size_t k, int* res,
size_t *res_size)
{
size_t maxpos = UINT_MAX;
*res_size = 0u;
// loop invariant : maxpos is the index of largest value in range (i, j)
for (size_t i = 0, j = k - 1; j < n; j++, i++)
{
if (maxpos < i || maxpos == UINT_MAX)
{
maxpos = i;
for (size_t l = i + 1; l <= j; l++)
if (A[l] > A[maxpos]) maxpos = l;
}
else
{
if (A[j] > A[maxpos])
maxpos = j;
}
res[(*res_size)++] = A[maxpos];
}
return 0;
}
int reverse_array_in_groups(int A[], size_t n, size_t k)
{
for (size_t i = 0; i < n; i += k)
{
// loop invariant : range i..l r..(i+k-1) is reversed
size_t l = i, r = (i + k - 1 < n) ? i + k - 1 : n - 1;
while (l < r)
{
int temp;
temp = A[l];
A[l] = A[r];
A[r] = temp;
l++; r--;
}
}
return 0;
}
int kth_smallest_element(int A[], size_t n, size_t k, int* res)
{
// loop invariant : [n-1-i,n) contains ith smallest to smallest
// elements in sorted in reverse order
for (size_t i = 0; i < k; i++)
{
// loop invariant : A[j+1] is smallest element in range (0, j+1)
for (size_t j = 0; j < n - i - 1; j++)
{
if (A[j] < A[j + 1])
{
int temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}
*res = A[n - k];
return 0;
}
int trapping_rainwater(int A[], size_t n, long long* res)
{
size_t l = 0, r = n - 1;
int maxl = 0, maxr = 0;
long long water = 0;
// loop invariant : water = amountof rain water trapped in ranges
// (0, l) and (r, n)
while (l < r)
{
if (A[l] < A[r])
{
if (maxl < A[l]) maxl = A[l];
else water += maxl - A[l];
l++;
}
else
{
if (maxr < A[r]) maxr = A[r];
else water += maxr - A[r];
r--;
}
}
*res = water;
return 0;
}
int pythagorean_triplet(int A[], size_t n)
{
for (size_t i = 0; i < n; i++)
{
A[i] *= A[i];
}
// reverse sort
qsort(A, n, sizeof(int), rev_cmp);
int flag = 0;
for (size_t i = 0; i < n - 2; i++)
{
size_t l = i + 1, r = n - 1;
while (l < r)
{
if (A[l] + A[r] == A[i])
{
flag = 1;
break;
}
else (A[l] + A[r] < A[i]) ? r-- : l++;
}
if (flag == 1) break;
}
if (flag != 1) return -1;
return 0;
}
int chocolate_distribution(int A[], size_t n, size_t m, int* res)
{
qsort(A, n, sizeof(int), cmp);
size_t l = 0, r = m - 1;
*res = INT_MAX;
// mindiff == smallest difference between A[l], A[l+m-1] in range (0,r)
while (r < n)
{
if (A[r] - A[l] < *res)
*res = A[r] - A[l];
l++; r++;
}
return 0;
}
struct iv {
size_t buy;
size_t sell;
};
int stock_buy_and_sell(int A[], size_t n, size_t* resu, size_t* res_size)
{
struct iv res[505];
// loop invariant : count = number of local minima followed by local maxima
size_t count = 0, i = 0;
while (i < n) {
// loop invariant : range A(i',i) consists of non-increasing integers
while (i < n - 1 && A[i + 1] <= A[i]) i++;
if (i == n - 1) break;
res[count].buy = i++;
// loop invariant : range (i', i-1) consistsof non-decreasing integers
while (i < n && A[i] >= A[i - 1]) i++;
res[count].sell = i - 1;
count++;
}
if (count == 0) return -1;
else {
*res_size = 0;
for (size_t i = 0; i < count; i++)
{
resu[*res_size] = res[i].buy;
resu[*res_size+1] = res[i].sell;
*res_size += 2;
}
}
return 0;
}
int elements_with_left_side_smaller_and_right_side_greater(int A[], size_t n,
int* res)
{
int min_right = INT_MAX;
// loop invariant : min_right is smallest element in range A[i, n)
for (size_t i = n - 1; i < UINT_MAX; i--)
{
if (A[i] < min_right)
min_right = A[i];
aux[i] = min_right;
}
// loop invariant : *res is largest in range A(0, i]
size_t i; *res = 0;
for (i = 0; i < n; i++)
{
if (A[i] > *res)
*res = A[i];
if (i != 0 && i != n - 1 && *res == A[i] && A[i] == aux[i])
{
break;
}
}
if (i == n) return -1;
return 0;
}
int convert_array_into_zigzag_fashion(int A[], size_t n)
{
int flag = 0; int temp;
// loop invariant : In range A(0, i) A[odd] < A[even]
for (size_t i = 0; i < n - 1; i++)
{
if (flag == 0)
{
if (A[i] > A[i + 1])
{
temp = A[i];
A[i] = A[i + 1];
A[i + 1] = temp;
}
}
else if (flag == 1)
{
if (A[i] < A[i + 1])
{
temp = A[i];
A[i] = A[i + 1];
A[i + 1] = temp;
}
}
flag = (flag == 0) ? 1 : 0;
}
return 0;
}
int find_the_element_that_appears_once_in_sorted_array(int A[], size_t n,
int* res)
{
size_t i;
// loop invariant : range A[0,i-1] has property A[k] == A[k+1], k is even
for (i = 0; i < n - 1; i += 2)
{
if (A[i] != A[i + 1])
{
*res = A[i];
return 0;
}
}
if (i == n - 1)
{
*res = A[i];
return 0;
}
return -1;
/*
int l= 0, mid = 0, r = n-1;
while(l<r)
{
mid = (l+r)/2;
if(A[mid] == A[mid-1])
{
if((mid-l+1) % 2 == 0 )
l = mid+1;
else
r = mid-2;
}
else if(A[mid] == A[mid+1])
{
if((r-mid+1) % 2 == 0 )
r = mid - 1;
else
l = mid + 2;
}
else break;
}
if(r<=l)
printf("%lld\n", A[l]);
else
printf("%lld\n",A[mid]);
*/
}
void heapify(size_t i, size_t k)
{
size_t l, r, min;
while (1)
{
l = 2 * i + 1; r = 2 * i + 2;
min = i;
if (l < k)
min = aux[l] < aux[min] ? l : min;
if (r < k)
min = aux[r] < aux[min] ? r : min;
if (min == i) break;
else
{
int temp = aux[i];
aux[i] = aux[min];
aux[min] = temp;
i = min;
}
}
//for(int i=0;i<k;i++)
//printf("%d ",A[i]);
//printf("\n");
}
int kth_largest_element_in_a_stream(int A[], size_t n, size_t k, int* res,
size_t *res_size)
{
int in = 0;
*res_size = 0;
// loop invariant : res[*res_size] is kth largest value in range A[0, i]
for (size_t i = 0; i < n; i++)
{
in = A[i];
if (i < k - 1) {
aux[i] = in;
res[*res_size] = -1;
}
else if (i == k - 1)
{
aux[i] = in;
size_t x = (k - 1) / 2;
while (x < UINT_MAX)
{
heapify(x, k);
--x;
}
res[*res_size] = aux[0];
}
else
{
if (in > aux[0])
{
aux[0] = in;
heapify(0, k);
}
res[*res_size] = aux[0];
}
++*res_size;
}
return 0;
}
size_t lb(int *A, size_t n, int val)
{
size_t l = 0, r = n - 1;
size_t mid;
while (l < r)
{
mid = (l + r) / 2;
if (A[mid] < val)
l = mid + 1;
else
r = mid;
}
return l;
}
int relative_sorting(int A[], size_t n, int B[], size_t m,
int* res, size_t* res_size)
{
// initialise auxiliury array
for(size_t i = 0; i < n; i++)
aux[i] = 0;
qsort(A, n, sizeof(int), cmp);
// loop invariant : range res(0, *res_size) contains all duplicates
// of elements in range B[0, i] in array A
int k;
*res_size = 0;
for (size_t i = 0; i < m; i++)
{
k = B[i];
size_t l = lb(A, n, k);
while (A[l] == k)
{
res[*res_size] = k;
aux[l] = 1;
l++; ++*res_size;
}
}
// loop invariant : res(*res_size', *res_size) contains elements in
// range A(0, i) except for elements already in res
for (size_t i = 0; i < n; i++)
{
if (aux[i] == 0)
{
res[*res_size] = A[i];
++*res_size;
}
}
return 0;
}
int spirally_traversing_a_matrix(int A[], size_t m, size_t n,
int* res, size_t* res_size)
{
size_t l = 0, t = 0;
size_t r = n - 1, b = m - 1;
*res_size = 0;
// loop invariant : *res_size increases
// if t == b by r - l
// if r == l by b - t
// else by 2*(r-l + b-t - 1)
while (l <= r && t <= b)
{
for (size_t i = l; i <= r; i++)
{
res[*res_size] = A[t*n + i];
++*res_size;
}
for (size_t i = t + 1; i <= b; i++)
{
res[*res_size] = A[i*n + r];
++*res_size;
}
if (t != b) {
for (size_t i = r - 1; i >= l && i < UINT_MAX; i--)
{
res[*res_size] = A[b*n + i];
++*res_size;
}
}
if (l != r) {
for (size_t i = b - 1; i > t; i--)
{
res[*res_size] = A[i*n + l];
++*res_size;
}
}
l++; r--; t++; b--;
}
return 0;
}
int sorting_array_elements_by_frequency(int A[], size_t n, int* res,
size_t* res_size)
{
// initialise auxiliury array
for(size_t i = 0; i < n; i++)
aux[i] = 0;
// loop invariant : i = sum(aux[loc[0]]..aux[loc[j]])
int k;
size_t j = 0;
for (size_t i = 0; i < n; i++)
{
k = A[i];
if (aux[k] == 0)
loc[j++] = k;
aux[k]++;
}
// sort loc by frequency of elements
qsort(loc, j, sizeof(int), cus_cmp);
// loop invariant : n - *res_size = sum(aux[loc[0]]..aux[loc[j]])
*res_size = 0;
for (size_t i = 0; i < j; i++)
while (aux[loc[i]]) {
res[*res_size] = loc[i];
aux[loc[i]]--;
++*res_size;
}
return 0;
}
int cus_cmp2(const void* a, const void* b)
{
char buf1[10], buf2[10];
const struct arr* ia = (const struct arr *)a;
const struct arr* ib = (const struct arr *)b;
strcpy(buf1, ia->a);
strcat(buf1, ib->a);
strcpy(buf2, ib->a);
strcat(buf2, ia->a);
return strcmp(buf2, buf1);
}
int largest_number_formed_by_array(struct arr As[], size_t n,
char *res, size_t *res_size)
{
qsort(As, n, sizeof(struct arr), cus_cmp2);
strcpy(res, As[0].a);
for(size_t i =1; i < n; i++)
strcat(res, As[i].a);
*res_size = strlen(res);
return 0;
}
int reverse_words_in_a_given_string(char *S, char* res)
{
int i = -1;
char* stack[50];
stack[++i] = strtok(S,".");
while(stack[i]){
stack[++i] = strtok(NULL, ".");
}
size_t skip = 0;
i--;
while(i > -1)
{
strcpy(res + skip, stack[i]);
size_t copy_length = strlen(stack[i]);
res[skip + copy_length] = '.';
skip+= copy_length + 1;
i--;
}
res[skip - 1] = '\0';
return 0;
}
int permutations_of_a_given_string(char* str)
{
size_t len = strlen(str);
if(len == 0 || len == 1) return -1;
char* i, *f, *b, *last;
i = str + len;
last = i - 1;
while(1)
{
f = i;
if(*--i < *f)
{
b = str + len;
while(!(*i < *--b));
swap_char(i, b);
reverse_string(f, last);
return 0;
}
if(*i == str[0])
{
reverse_string(i, last);
return -1;
}
}
}
|
C
|
#include <stdio.h>
#include <omp.h>
int main()
{
int ii;
#pragma omp parallel
{
for(ii=0;ii<10;ii++) {
printf("Iteration: %d\n",ii);
}
}
printf("\n");
return 0;
}
|
C
|
/*
* test-path.c
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include "glib.h"
#include "mono/utils/mono-path.c"
static char*
make_path (const char *a, int itrail, int slash, int upcase)
{
// Append 0, 1, or 2 trailing slashes to a.
g_assert (itrail >= 0 && itrail <= 2);
char trail [] = "//";
trail [itrail] = 0;
char *b = g_strdup_printf ("%s%s", a, trail);
#ifdef HOST_WIN32
if (slash)
g_strdelimit (b, '/', '\\');
if (upcase)
g_strdelimit (b, 'a', 'A');
#endif
return b;
}
int
main (void)
{
// Use letters not numbers in this data to exercise case insensitivity.
static const char * const bases [2] = {"/", "/a"};
static const char * const files [6] = {"/a", "/a/b", "/a/b/c", "/ab", "/b", "/b/b/"};
static const gboolean result [2][6] = {
{ TRUE, FALSE, FALSE, TRUE, TRUE, FALSE },
{ FALSE, TRUE, FALSE, FALSE, FALSE, FALSE }
};
int i = 0;
gboolean const verbose = !!getenv("V");
#ifdef HOST_WIN32
const int win32 = 1;
#else
const int win32 = 0;
#endif
// Iterate a cross product.
for (int upcase_file = 0; upcase_file <= win32; ++upcase_file) {
for (int upcase_base = 0; upcase_base <= win32; ++upcase_base) {
for (int itrail_base = 0; itrail_base <= 2; ++itrail_base) {
for (int itrail_file = 0; itrail_file <= 2; ++itrail_file) {
for (int ibase = 0; ibase < G_N_ELEMENTS (bases); ++ibase) {
for (int ifile = 0; ifile < G_N_ELEMENTS (files); ++ifile) {
for (int islash_base = 0; islash_base <= win32; ++islash_base) {
for (int islash_file = 0; islash_file <= win32; ++islash_file) {
char *base = make_path (bases [ibase], itrail_base, islash_base, upcase_base);
char *file = make_path (files [ifile], itrail_file, islash_file, upcase_file);
//verbose && printf ("mono_path_filename_in_basedir (%s, %s)\n", file, base);
gboolean r = mono_path_filename_in_basedir (file, base);
verbose && printf ("mono_path_filename_in_basedir (%s, %s):%d\n", file, base, r);
g_assertf (result [ibase][ifile] == r,
"mono_path_filename_in_basedir (%s, %s):%d\n", file, base, r);
if (strcmp (base, file) == 0)
g_assertf (!r,
"mono_path_filename_in_basedir (%s, %s):%d\n", file, base, r);
g_free (base);
g_free (file);
++i;
}
}
}
}
}
}
}
}
printf ("%d tests\n", i);
return 0;
}
|
C
|
#ifndef __BL__MODBUS_H__
#define __BL__MODBUS_H__
/******************************************************************************/
/* This is simple implementation of modbus RTU protocol over serial line. Only*/
/* two modbus functions in slave mode are supported: */
/* 0x03 Read Holding Registers */
/* 0x10 Preset Multiple Registers */
/* */
/* No exception support, timeout for reading data is based on 16b timer. */
/******************************************************************************/
#include <stdint.h>
#include "config.h"
typedef enum {
MODBUS_OK = 0, // The message were sucessfully received.
MODBUS_TIMEOUT, // Timeout, no or incomplete message were received.
MODBUS_WRONG_CRC, // Received message have wrong CRC.
MODBUS_SLAVE // Received message is for other slave on bus.
} modbus_status_e;
typedef struct {
uint8_t slave;
uint8_t function;
uint16_t address;
uint16_t wsize;
uint8_t data[252]; // Maximum payload in modbus RTU
//
// uint16_t crc;
} modbus_pdu_t;
/**
* Initialize modbus. Set slave address.
*/
void modbus_init(uint8_t slave);
/**
* Try to receive valid PDU for this slave.
* This function is blocking, it will block until valid data
* for this slave are received or until timeout. The timeout is
* triggered by timer overflow.
*
* `pdu` is pointer to data structure where valid data will be stored.
* `function` is number of function we are looking for.
*/
uint8_t modbus_recv_pdu(modbus_pdu_t *pdu);
/**
* Send modbus response to master. PDU will contain this slave address.
*/
uint8_t modbus_send_pdu(modbus_pdu_t *pdu);
#ifdef DEBUG_MODBUS
void modbus_print_pdu(modbus_pdu_t *pdu);
#endif
#endif
|
C
|
/******************BIBLIOTECA**********************/
#include "FBiblioteca.h"
MYSQL conex;
void menuExcluir(void){
int opc;
while(1){
printf("\n******************\n");
printf("***EXCLUIR***\n");
printf("******************\n");
printf("Digite uma opção:\n");
printf("[1]LIVRO\n");
printf("[2]LIVRARIA\n");
printf("[3]AUTOR\n");
printf("[4]AMIGO\n");
printf("[5]EMPRESTIMO\n");
printf("[6]COMPRA\n");
printf("[7]RETORNAR AO MENU PRINCIPAL\n\n\n");
scanf("%d", &opc);
switch (opc){
case 1: excluirLivro();
break;
case 2: excluirLivraria();
break;
case 3: excluirAutor();
break;
case 4: excluirAmigo();
break;
case 5: excluirEmprestimo();
break;
case 6: excluirCompra();
break;
case 7: menuPrincipal();
break;
default : printf("\n Opcao invalida! Tente novamente\n");
break;
}
}
}
/*--------------------------------------------------------------------------*/
void excluirLivro(void){
int res;
int codLivro;
printf("\n*****EXCLUIR LIVRO*****\n");
printf("\nDigite o código do Livro:\n");
scanf("%d",&codLivro);
char aux[301];
sprintf(aux,"DELETE FROM Livro WHERE Livro.CodLivro=%d",codLivro);
resultado(aux);
/***EXCLUI TAMBEM EM ESCREVE***/
sprintf(aux,"DELETE FROM Escreve WHERE Escreve.Livro_CodLivro=%d",codLivro);
resultado(aux);
/***EXCLUI TAMBEM EM COMPRA***/
sprintf(aux,"DELETE FROM Compra WHERE Compra.Livro_CodLivro=%d",codLivro);
resultado(aux);
/***EXCLUI TAMBEM EM EMPRESTA***/
sprintf(aux,"DELETE FROM Empresta WHERE Empresta.Livro_CodLivro=%d",codLivro);
resultado(aux);
}
/*--------------------------------------------------------------------------*/
void excluirLivraria(void){
int codLivraria;
printf("\n*****EXCLUIR LIVRARIA*****\n");
printf("\nDigite o código da Livraria:\n");
scanf("%d",&codLivraria);
char aux[301];
sprintf(aux,"DELETE FROM Livraria WHERE Livraria.CodLivraria=%d",codLivraria);
resultado(aux);
/***EXCLUI TAMBEM EM COMPRA***/
sprintf(aux,"DELETE FROM Compra WHERE Compra.Livraria_CodLivraria=%d",codLivraria);
resultado(aux);
}
/*--------------------------------------------------------------------------*/
void excluirAutor(void){
int codAutor;
printf("\n*****EXCLUIR AUTOR*****\n");
printf("\nDigite o código do Autor:\n");
scanf("%d",&codAutor);
char aux[301];
sprintf(aux,"DELETE FROM Autor WHERE Autor.CodAutor=%d",codAutor);
resultado(aux);
/***EXCLUI TAMBEM EM ESCREVE***/
sprintf(aux,"DELETE FROM Escreve WHERE Escreve.Autor_CodAutor=%d",codAutor);
resultado(aux);
}
/*--------------------------------------------------------------------------*/
void excluirAmigo(void){
int codAmigo;
char aux[301];
printf("\n*****EXCLUIR AMIGO*****\n");
printf("\nDigite o código do Amigo:\n");
scanf("%d",&codAmigo);
sprintf(aux,"DELETE FROM Amigo WHERE Amigo.CodAmigo=%d",codAmigo);
resultado(aux);
/***EXCLUI TAMBEM EM EMPRESTA***/
sprintf(aux,"DELETE FROM Empresta WHERE Empresta.Amigo_CodAmigo=%d",codAmigo);
resultado(aux);
}
/*--------------------------------------------------------------------------*/
void excluirEmprestimo(void){
int codEmprest;
char aux[201];
int opc;
printf("Código do emprestimo:\n");
scanf("%d",&codEmprest);
sprintf(aux,"DELETE FROM Empresta WHERE Empresta.CodEmprest= %d",codEmprest);
resultado(aux);
printf("Atualização do status. Digite os campos abaixo\n");
/*chama a funcao para alterar status*/
livroAlterarStatus();
}
/*--------------------------------------------------------------------------*/
void excluirCompra(void){
int codLivro, codLivraria, opc;
char aux[501];
printf("\n*****EXCLUIR COMPRA*****\n");
printf("Deseja consultar o código do livro(Tecle 1 para sim ou 0 para nao)?\n");
scanf("%d",&opc);
if(opc==1)
consultarTudoLivro();
printf("\n Código do Livro:\n");
scanf("%d",&codLivro);
printf("Deseja consultar o código da livraria(Tecle 1 para sim ou 0 para nao)?\n");
scanf("%d",&opc);
if(opc==1)
consultarTudoLivraria();
printf("\n Código da Livraria:\n");
scanf("%d",&codLivraria);
sprintf(aux,"DELETE FROM Compra WHERE Compra.Livro_CodLivro= %d AND Compra.Livraria_CodLivraria= %d",codLivro, codLivraria);
resultado(aux);
}
/*--------------------------------------------------------------------------*/
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_4__ TYPE_1__ ;
/* Type definitions */
struct TYPE_4__ {int /*<<< orphan*/ tag; } ;
typedef TYPE_1__ OSThread ;
/* Variables and functions */
int /*<<< orphan*/ OS_THREAD_TAG ;
TYPE_1__* alloc_zeroed (int,int) ;
__attribute__((used)) static OSThread *new_thread(void)
{
OSThread *t = alloc_zeroed(8, sizeof(OSThread));
if (!t)
return NULL;
t->tag = OS_THREAD_TAG;
return t;
}
|
C
|
//*********************************************************
//File name : 0704.c
//Author : gengbaoyuan
//Date : 4.21
//Student ID : 2018217691
//*********************************************************
#include <stdio.h>
#include <stdlib.h>
void myQuickSort(int *data, int start, int end)
{
if(start >= end)
{
return ;
}
int key = data[end];
int left = start - 1, right = start, temp;
while(right < end)
{
if(data[right] > key)
{
++left;
temp = data[left];
data[left] = data[right];
data[right] = temp;
}
++right;
}
temp = data[left + 1];
data[left + 1] = data[right];
data[right] = temp;
myQuickSort(data, start, left);
myQuickSort(data, left+2, end);
}
int main(void)
{
int data[20];
int size;
printf("How many number do you want to input (please under 20) ? ");
scanf("%d", &size);
if(size > 20)
{
size = 20;
}
printf("Please enter %d numbers : \n", size);
for(int i = 0; i < size; ++i)
{
scanf("%d", data + i);
}
myQuickSort(data, 0, size - 1);
printf("Sorted Result : \n");
for(int i = 0; i < size; ++i)
{
printf("%d ", data[i]);
}
printf("\n");
system("pause");
return 0;
}
|
C
|
#include "binary_trees.h"
/**
* binary_trees_ancestor - Finds lowest common ancestor of two nodes
* @first: pointer to first node
* @second: pointer to second node
* Return: pointer to lowest common ancestor
*/
binary_tree_t *binary_trees_ancestor(const binary_tree_t *first, const
binary_tree_t *second)
{
binary_tree_t *temp;
if (!first || !second)
return (0);
temp = (binary_tree_t *)second;
for (; first; second = temp)
{
for (; second; second = second->parent)
{
if (first == second)
return ((binary_tree_t *)first);
}
first = first->parent;
}
return (NULL);
}
|
C
|
/* See LICENSE for license details. */
/*
Module: meat_file.c
Description:
Abstraction of file access.
*/
#include "meat_os.h"
#include <stdio.h>
#include "meat_file.h"
#include "meat_ctxt.h"
#include "meat_heap.h"
/*
Structure: meat_file
Description:
*/
struct meat_file
{
FILE *
p_private;
}; /* struct meat_file */
struct meat_file *
meat_file_create(
struct meat_ctxt * const
p_ctxt,
enum meat_file_type const
e_type,
char const * const
p_name)
{
struct meat_file *
p_file;
p_file =
(struct meat_file *)(
meat_heap_alloc(
p_ctxt,
p_ctxt->p_heap,
sizeof(
struct meat_file)));
if (
p_file)
{
if (
meat_file_type_stdin
== e_type)
{
p_file->p_private =
stdin;
}
else if (
meat_file_type_stdout
== e_type)
{
p_file->p_private =
stdout;
}
else if (
meat_file_type_readonly
== e_type)
{
p_file->p_private =
fopen(
p_name,
"r");
}
else if (
meat_file_type_writeonly
== e_type)
{
p_file->p_private =
fopen(
p_name,
"w");
}
else if (
meat_file_type_append
== e_type)
{
p_file->p_private =
fopen(
p_name,
"a");
}
else
{
p_file->p_private =
NULL;
}
if (
p_file->p_private)
{
}
else
{
meat_heap_free(
p_ctxt,
p_ctxt->p_heap,
(void *)(
p_file));
p_file =
(struct meat_file *)(
0);
}
}
return
p_file;
} /* meat_file_create() */
void
meat_file_destroy(
struct meat_ctxt * const
p_ctxt,
struct meat_file * const
p_file)
{
if (
p_file->p_private)
{
if (
(
p_file->p_private != stdin)
&& (
p_file->p_private != stdout))
{
fclose(
p_file->p_private);
}
p_file->p_private = NULL;
}
meat_heap_free(
p_ctxt,
p_ctxt->p_heap,
(void *)(
p_file));
} /* meat_file_destroy() */
int
meat_file_read_char(
struct meat_ctxt * const
p_ctxt,
struct meat_file * const
p_file)
{
int
i_data;
(void)(
p_ctxt);
if (
p_file->p_private)
{
i_data =
fgetc(
p_file->p_private);
}
else
{
i_data =
-1;
}
return
i_data;
} /* meat_file_read_char() */
void
meat_file_write_char(
struct meat_ctxt * const
p_ctxt,
struct meat_file * const
p_file,
int const
c_data)
{
(void)(
p_ctxt);
if (
p_file->p_private)
{
fputc(
c_data,
p_file->p_private);
}
} /* meat_file_write_char() */
/* end-of-file: meat_file.c */
|
C
|
#include "holberton.h"
/**
* flip_bits - returns the number of bits
* @n: number
* @m: number
* Return: number of bits
*/
unsigned int flip_bits(unsigned long int n, unsigned long int m)
{
unsigned long int x, c;
unsigned int j = 0;
int i;
c = n ^ m;
for (i = 0; i <= 63; i++)
{
x = 1;
x = x << i;
if ((c & x) != 0)
{
j++;
}
}
return (j);
}
|
C
|
/*
* Copyright (c) 2011-16 Scott Vokes <vokes.s@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* For more information on skiplists, see William Pugh's paper,
* "Skip Lists: A Probabilistic Alternative to Balanced Trees".
*/
#ifndef SKIPLIST_H
#define SKIPLIST_H
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/* 0.9.0 */
#define SKIPLIST_VERSION_MAJOR 0
#define SKIPLIST_VERSION_MINOR 9
#define SKIPLIST_VERSION_PATCH 0
/* Opaque skiplist type. */
struct skiplist;
/* Memory allocation callback.
*
* When called as (NULL, 0, SIZE, udata), should be equivalent to
* `malloc(SIZE)`. When called as (P, OLD_SIZE, 0, udata), should be
* equivalent to `free(P)`, and return NULL. realloc-like behavior is
* not currently used. */
typedef void *skiplist_alloc_cb(void *p,
size_t osize, size_t nsize, void *udata);
/* Comparison callback, should return <0, 0, or >0 for less-than,
* equal, and greater-than, respectively. */
typedef int skiplist_cmp_cb(void *key_a, void *key_b);
/* Create a new skiplist, returns NULL on error.
* A comparison callback is required.
* A memory management callback is optional - if NULL,
* malloc & free will be used internally. */
struct skiplist *skiplist_new(skiplist_cmp_cb *cmp,
skiplist_alloc_cb *alloc, void *alloc_udata);
/* Set the random seed used when randomly constructing skiplists. */
void skiplist_set_seed(unsigned seed);
/* Randomly generate the height for the next level.
* Should return between 1 and SKIPLIST_MAX_HEIGHT, inclusive.
* Returning an illegal height is a checked error.
*
* For the skiplist's invariants to hold, the propability of
* >= level N should be a constant proportion of the probability
* of the level beneath it, e.g. prob(>=1) -> 1, prob(>=2) -> 1/2,
* prob(>=3) -> 1/4, prob(>=4) -> 1/8, etc.
*
* SKIPLIST_GEN_HEIGHT can be replaced at compile-time, but
* defaults to a probability of 0.5 per each additional level.
*/
uint8_t SKIPLIST_GEN_HEIGHT(void);
/* Add a key/value pair to the skiplist. Equal keys will be kept (bag
* functionality). KEY and/or VALUE are allowed to be NULL, provided the
* cmp callback can handle it. If you add multiple values under the same
* key, they will not necessarily be stored in any particular order.
*
* Returns whether the value was successfully added. */
bool skiplist_add(struct skiplist *sl, void *key, void *value);
/* Set a key/value pair in the skiplist, replacing an existing
* value if present. If OLD is non-NULL, then *old will be set
* to the previous value, or NULL if it was not present.
* Otherwise behaves the same as skiplist_add. */
bool skiplist_set(struct skiplist *sl,
void *key, void *value, void **old);
/* Get the value associated with KEY. If the key is found and VALUE is
* non-NULL, it will be written into *VALUE.
* Returns whether the key was found. */
bool skiplist_get(struct skiplist *sl, void *key, void **value);
/* Does the skiplist contain KEY? */
bool skiplist_member(struct skiplist *sl, void *key);
/* Delete an association for KEY in the skiplist.
* If found and VALUE is non-NULL, the old value will be
* written to *VALUE.
* Returns whether the key was found.
*
* Note: If there are multiple values for the key, only one
* (not necessarily the first) is deleted; see skiplist_delete_all. */
bool skiplist_delete(struct skiplist *sl, void *key, void **value);
/* Callback when freeing keys and/or values contained by the skiplist. */
typedef void skiplist_free_cb(void *key, void *value, void *udata);
/* Delete all associations for KEY in the skiplist. The callback is
* called for each key/value pair, and cannot be NULL. */
void skiplist_delete_all(struct skiplist *sl, void *key,
skiplist_free_cb *cb, void *udata);
/* Get the first or last pair from the skiplist.
* If key or value are non-NULL, the pair is returned in them.
* Passing in a NULL key is legal, it will be ignored.
* Passing in a NULL value is legal, but useless.
* Returns whether a pair was found (the skiplist is non-empty). */
bool skiplist_first(struct skiplist *sl, void **key, void **value);
bool skiplist_last(struct skiplist *sl, void **key, void **value);
/* Pop the key/value pair off the skiplist with the first/last key. Same
* return behavior as skiplist_first/last, but also deletes the pair. */
bool skiplist_pop_first(struct skiplist *sl, void **key, void **value);
bool skiplist_pop_last(struct skiplist *sl, void **key, void **value);
/* How many pairs are in the skiplist?
* Returns 0 on error. */
size_t skiplist_count(struct skiplist *sl);
/* Is the skiplist empty? */
bool skiplist_empty(struct skiplist *sl);
/* Callback when iterating over the contents of the skiplist.
* The return value determines whether to keep iterating.
* UDATA is an extra void * for the callback's closure/enironment. */
enum skiplist_iter_res {
SKIPLIST_ITER_HALT,
SKIPLIST_ITER_CONTINUE,
};
typedef enum skiplist_iter_res
skiplist_iter_cb(void *key, void *value, void *udata);
/* Iterate over the skiplist. See the typedef comment for
* skiplist_iter_cb for more information. */
void skiplist_iter(struct skiplist *sl,
skiplist_iter_cb *cb, void *udata);
/* Iterate over the skiplist, beginning at KEY. */
void skiplist_iter_from(struct skiplist *sl, void *key,
skiplist_iter_cb *cb, void *udata);
/* Clear the skiplist. Returns the number of pairs removed,
* or 0 on error. */
size_t skiplist_clear(struct skiplist *sl,
skiplist_free_cb *cb, void *udata);
/* Clear and free the skiplist. Returns the number of pairs removed,
* or 0 on error. */
size_t skiplist_free(struct skiplist *sl,
skiplist_free_cb *cb, void *udata);
#if SKIPLIST_DEBUG
#include <stdio.h>
/* Callback to print KEY and/or VALUE inside skiplist_debug
* to file F, if F is non-NULL. */
typedef void skiplist_fprintf_kv_cb(FILE *f, void *key,
void *value,void *udata);
/* Do an internal consistency check.
* Prints debugging info to F (if non-NULL). */
void skiplist_debug(struct skiplist *sl, FILE *f,
skiplist_fprintf_kv_cb *cb, void *udata);
#endif
#ifdef __cplusplus
}
#endif
#endif
|
C
|
#include <stdio.h>
#include <math.h>
int main() {
printf("Tutorijal 1, Zadatak \n");
int x1, y1, z1;
int x2, y2, z2;
float rastojanje=0;
printf("Unesi prvu tacku: ");
scanf("%d %d %d", &x1, &y1, &z1);
printf("Unesi drugu tacku: ");
scanf("%d %d %d", &x2, &y2, &z2);
rastojanje = sqrt(pow(x2-x1,2) + pow(y2-y1, 2) + pow(z2-z1,2));
printf("%.2f", rastojanje);
return 0;
}
|
C
|
#ifndef CHILD_H_
#define CHILD_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
typedef struct {
int id;
int age;
}Child;
void addChild(Child* child, FILE* f);
void printChild(Child* child);
void saveChild(Child* child, FILE* file);
Child* initChild();
#endif
|
C
|
#include"header.h"
int main()
{
char s[20];
int sfd,len,nsfd;
struct sockaddr_in v,v1;
sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)
{
perror("socket");
return;
}
printf("sfd=%d \n",sfd);
v.sin_family=AF_INET;
v.sin_port=htons(3000);
v.sin_addr.s_addr=inet_addr("0.0.0.0");
len=sizeof(v);
bind(sfd,(struct sockaddr *)&v,len);
perror("bind");
listen(sfd,5);
perror("listen");
printf("before....\n");
nsfd=accept(sfd,(struct sockaddr *)&v1,&len);
perror("accept");
read(nsfd,s,sizeof(s));
printf("Data=%s \n",s);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
const int LENGTH = 20;
char name[LENGTH];
int age;
printf("Enter your name: ");
fgets(name, LENGTH, stdin);
printf("Enter your age: ");
scanf("%d", &age);
printf("Your name is: %s\n", name);
printf("Your age is: %d\n", age);
printf("Goodbye \n");
return 0;
}
|
C
|
#include <stdio.h>
#define NMAX 2000001
int Stree[NMAX] = {0};
int SIZE;
void init(int a[], int s, int e)
{
SIZE = 2*(e-s+1);
for(int i = e-s+1; i < SIZE; i++)
Stree[i] = a[s+i-(e-s+1)];
for(int i = e-s; i > 0; i--)
Stree[i] = Stree[2*i]+Stree[2*i+1];
}
void update(int i, int n)
{
i += SIZE/2-1;
Stree[i] = n;
while(i)
{
i /= 2;
Stree[i] += n;
}
}
int sum(int l, int r)
{
l += SIZE/2-1;
r += SIZE/2;
int sum = 0;
while(l < r)
{
if(l % 2)
sum += Stree[l++];
if(r % 2)
sum += Stree[--r];
l /= 2;
r /= 2;
}
return sum;
}
void main()
{
int a[] = {2, 1, 1};
init(a, 0, 2);
printf("%d\n",sum(1,2));
update(2, 9);
printf("%d\n",sum(1,2));
}
|
C
|
/*************************************************************************
> File Name: forkShareFD.c
> Author: xyx
> Mail:719660015@qq.com
> Created Time: Wed 16 Sep 2020 01:53:33 AM PDT
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc, char* argv[]){
//open file
int fd = open(argv[1], O_RDWR | O_CREAT, 0755);
if(fd < 0){
perror("open error");
return -1;
}
//fork
pid_t pid = fork();
if(pid < 0){
perror("fork error");
return -1;
}else if(pid > 0){
//write shomething
printf("father: pid == [%d], fpid == [%d]\n", getpid(), getppid());
write(fd, "hello world", strlen("hello world"));
printf("write over\n");
close(fd);
int status;
while(1){
pid_t wpid = waitpid(-1, &status, WNOHANG);
//printf("wpid == [%d]\n", wpid);
if(wpid > 0){
if(WIFEXITED(status)){
printf("child normal exit, status == [%d]\n", WEXITSTATUS(status));
}else if(WIFSIGNALED(status)){
printf("child killed by signal, signo == [%d]\n", WTERMSIG(status));
}
}else if(wpid == 0){
//printf("child is living, wpid == [%d]\n", wpid);
}else if(wpid == -1){
printf("no child is living, wpid == [%d]\n", wpid);
break;
}
}
}else if(pid == 0){
printf("children: pid ==[%d], fpid == [%d]\n", getpid(), getppid());
char buf[1024];
memset(buf, 0x00, sizeof(buf));
int n;
sleep(1);
lseek(fd, 0, SEEK_SET);
n=read(fd, buf, sizeof(buf));
printf("read over, n == [%d],buf == [%s]\n", n, buf);
close(fd);
}
return 0;
}
|
C
|
/*
Gruppe:
Philipp-Marvin Quach
Camilo Andres Daza Barrios
Zum Bestehend der Tests:
srand48 gibt es auf Windows nicht, ich habe daher online nach einer
Variante gesucht die auf Windows läuft und Diese zu queuetest.c hinzu-
gefügt (inzwischen wieder entfernt):
https://gist.github.com/mortennobel/8665258
Die Ausgaben waren trotz konstantem Seed von 1000 immer unterschiedlich,
daher konnten wir nicht feststellen, ob die Tests bestanden werden, nur,
dass sich das Programm ausführen lässt und "ähnlich" aussehende
Ergebnisse liefert.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "queue.h"
typedef int Queueelement;
struct Queue {
Queueelement *queuespace;
unsigned long enqueueindex,
dequeueindex,
queuesize,
no_of_elements;
};
Queue *queue_new(unsigned long qsize)
{
Queue *q;
if(qsize <= 0)
{
fprintf(stderr, "Error: a queue must have a size of 1 or higher");
exit(EXIT_FAILURE);
}
q = (Queue*) malloc(sizeof (Queue));
q->queuespace = (Queueelement*) malloc(qsize * sizeof(Queueelement));
q->enqueueindex = 0;
q->dequeueindex = qsize - 1;
q->queuesize = qsize;
q->no_of_elements = q->dequeueindex - q->enqueueindex;
return q;
}
bool queue_is_empty(const Queue *q)
{
if(q->no_of_elements == 0)
{
return true;
}
else
{
return false;
}
}
void queue_double_size(Queue *q)
{
if(q->no_of_elements != q->queuesize)
{
fprintf(stderr, "Error: this can only be done if the queue is full");
exit(EXIT_FAILURE);
}
q->queuespace = realloc(q->queuespace,
sizeof(Queueelement) * q->queuesize * 2);
memcpy(q->queuespace + q->queuesize, q->queuespace,
q->dequeueindex * sizeof(Queueelement));
q->enqueueindex = q->queuesize + q->dequeueindex;
q->queuesize *= 2;
}
void queue_enqueue(Queue *q, Queueelement elem)
{
if(q->queuesize == q->no_of_elements) queue_double_size(q);
q->queuespace[q->enqueueindex] = elem;
q->no_of_elements++;
// wollte ich erst mit einer neuen modulo funktion machen,
// wegen unsigned longs aber wahrscheinlich schlecht?
// q->enqueueindex = mod((q->enqueueindex - 1), q->queuesize);
q->enqueueindex = q->enqueueindex > 0? q->enqueueindex-1 : q->queuesize-1;
}
Queueelement queue_dequeue(Queue *q)
{
Queueelement out;
if(q->no_of_elements <= 0)
{
fprintf(stderr, "Error: empty queues shall not return stuff");
exit(EXIT_FAILURE);
}
out = q->queuespace[q->dequeueindex];
q->dequeueindex = q->dequeueindex > 0? q->dequeueindex-1 : q->queuesize-1;
q->no_of_elements--;
return out;
}
void queue_print(const Queue *q)
{
unsigned long i;
unsigned long j = 1;
unsigned long index;
if(q->no_of_elements > 0)
{
for(i = 0; i < q->no_of_elements; i++)
{
if(q->dequeueindex-i >= 0)
{
index = q->dequeueindex-i;
}
else
{
index = q->queuesize-j;
j++;
}
printf("%d\n",q->queuespace[index]);
}
}
else
{
printf("empty\n");
}
}
void queue_delete(Queue *q)
{
free(q->queuespace);
free(q);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dteixeir <dteixeir@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/16 22:19:18 by dteixeir #+# #+# */
/* Updated: 2021/04/16 22:36:21 by dteixeir ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
void init_type(t_flags *flags)
{
flags->type = 0;
flags->zero = 0;
flags->minus = 0;
flags->padding = ' ';
flags->width = 0;
flags->precision = -1;
flags->number = 0;
flags->count = 0;
flags->len = 0;
flags->dot = 0;
flags->negative = 0;
flags->asterisk = 0;
}
int ft_printf(const char *input, ...)
{
const char *str;
t_flags flags;
va_list args;
va_start(args, input);
init_type(&flags);
if (!(str = ft_strdup(input)))
return (0);
while (str[flags.count])
{
if (str[flags.count] == '%')
{
flags.count++;
get_flags(str, &flags, args);
}
else
{
ft_putchar(&flags, str[flags.count]);
flags.count++;
}
}
free((char *)str);
va_end(args);
return (flags.len);
}
|
C
|
#include<stdio.h>
#include<math.h>
//Function we want to integrate
double f(double x){
double z=x+2; // we will change the operation we want here
return z;
}
void main(){
int s;
double a,b,y,x,sum=0,integral;
printf("Enter the no. of even sub-intervals: ");
scanf("%d",&s);
printf("\nEnter the initial limit: ");
scanf("%lf",&a);
printf("\nEnter the final limit: ");
scanf("%lf",&b);
y=fabs(b-a)/s;
/* This 'for' loop is used to divide the graph in the number of slabs as specified by the user */
for(int i=1;i<s;i++){
x=a+i*y;
if(i%2==0){
sum=sum+2*f(x);
}
else{
sum=sum+4*f(x);
}
}
integral=(y/3)*(f(a)+f(b)+sum);
printf("\nThe integral of the function is: %lf\n",integral);
}
|
C
|
#include <stdio.h>
#include "io_utils.h"
// vla C99; gcc; msvc x
void SumIntArrays(int rows, int columns, int array[][columns], int result[]) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
result[i] += array[i][j];
}
}
}
int main() {
int vehicle_limits[5][2] = {
0, 5, 1, [1][1] = 6, 2, 7, 3, 8, 4, 9
};
//int [2]
//vehicle_limits[0]
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 2; ++j) {
vehicle_limits[i][j] = i + j;
}
}
int scores[5][4] = {
{135, 135, 138, 277},
{105, 134, 108, 265},
{113, 107, 145, 232},
{123, 99, 140, 227},
{98, 118, 127, 242}
};
int result[5] = {0};
SumIntArrays(5, 4, scores, result);
PRINT_INT_ARRAY(result, 5);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <dirent.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include <netinet/in.h>
//#include <sys/ipc.h>
//#include <sys/sem.h>
#include <signal.h>
#include <semaphore.h>
/*
这个测试程序使用了POSIX标准的信号量接口,最开始使用了匿名信号量,但是并不能实现互斥。
sem_init初始化的匿名信号量只能在多线程中使用,多进程之间一定要使用共享的变量,比如,
使用共享内存,这里使用了sem_open创建了命名信号量。
多进程之间的互斥信号量,使用System V标准的接口最好。
*/
#define DEF_PORT 2018
#define MAX_EVENTS 1024 //接收的最大请求
#define BUFF_SIZE 1024
#define MAX_MSG_SIZE 4096 //单个消息最大字节数
/*
消息状态
*/
#define RECV_MSG_NONE 0
#define RECV_MSG_ERR 1
#define RECV_MSG_OK 2
#define RECV_MSG_CLOSE 3
#define RECV_MSG_OLMT 4
/* 标记父进程和子进程 */
#define PCS_CHILD 1
#define PCS_PARENT 2
#define CHILD_COUNT 2
#define ACCEPT_MAX_LIMIT MAX_EVENTS/CHILD_COUNT
pid_t _self_pid;
int _accpet_count; //accpet计数
int __child_count = 0;
sem_t *_accept_sem;
int try_accpet_lock(sem_t *sem) {
return sem_trywait(sem);
}
int release_accpet_lock(sem_t *sem) {
return sem_post(sem);
}
sem_t * init_accept_lock(char *name) {
return sem_open(name, O_CREAT|O_RDWR, 0664, 1);
}
int destroy_accpet_lock(sem_t *sem) {
return sem_close(sem);
}
struct msg_block {
int msg_end;
char msg[MAX_MSG_SIZE+1];
};
struct event_msg {
int inuse;
int fd;
struct msg_block data;
};
//全局信息存储
struct event_msg _evtmsg[ACCEPT_MAX_LIMIT];
void parent_handle_sig(int sig) {
if (sig == SIGINT || sig == SIGTERM) {
printf("remove semid\n");
destroy_accpet_lock(_accept_sem);
kill(0, SIGTERM);
usleep(50000);
exit(0);
} else if (sig == SIGCHLD) {
int st;
pid_t pid;
while((pid=waitpid(0, &st, WNOHANG)) > 0) {
if (WIFEXITED(st) || WIFSIGNALED(st)) {
printf("child %d exited\n", pid);
__child_count -= 1;
}
}
}
}
void child_handle_sig(int sig) {
if (sig == SIGTERM || sig == SIGINT || sig == SIGALRM) {
printf("child %u close connect before exit\n", _self_pid);
release_accpet_lock(_accept_sem);
exit(0);
}
}
//设置套接字的文件描述符为非阻塞模式
int set_nonblocking(int fd) {
int old_opt = fcntl(fd, F_GETFL);
int new_opt = old_opt | O_NONBLOCK;
fcntl(fd, F_SETFL, new_opt);
return old_opt;
}
//新创建的套接字连接加入到epoll列表中
void ep_addfd(int efd, int fd, int et){
struct epoll_event evt;
evt.data.fd = fd;
evt.events = EPOLLIN;
if (et)
evt.events |= EPOLLET;
epoll_ctl(efd, EPOLL_CTL_ADD, fd, &evt);
set_nonblocking(fd);
}
//从epoll连接列表中删除套接字
void ep_delfd(int efd, int fd) {
struct epoll_event evt;
epoll_ctl(efd, EPOLL_CTL_DEL, fd, &evt);
}
//设置套接字的触发模式
void ep_modfd(int efd, int fd, int opt, int et) {
struct epoll_event evt;
evt.data.fd = fd;
evt.events = opt;
if (et)
evt.events |= EPOLLET;
epoll_ctl(efd, EPOLL_CTL_MOD, fd, &evt);
}
void save_msg(int fd, struct msg_block * msg) {
int mi = fd % ACCEPT_MAX_LIMIT;
int fi = -1;
if ( (_evtmsg[mi].inuse && _evtmsg[mi].fd == fd)
||
_evtmsg[mi].inuse==0
) {
fi = mi;
} else {
for (int i=0; i<ACCEPT_MAX_LIMIT; i++) {
if (_evtmsg[i].inuse==0) {
fi = i;
break;
}
}
}
if (fi>=0 && fi<ACCEPT_MAX_LIMIT) {
_evtmsg[fi].inuse = 1;
_evtmsg[fi].fd = fd;
strcpy(_evtmsg[mi].data.msg, msg->msg);
}
}
struct event_msg * get_msg(int fd) {
for(int i=0;i<ACCEPT_MAX_LIMIT;i++) {
if (_evtmsg[i].fd == fd) {
return (_evtmsg+i);
}
}
return NULL;
}
void close_socket(int fd) {
close(fd);
_accpet_count -= 1;
}
int handle_recv_msg(int efd, int fd, struct msg_block *msg) {
int msg_count = 0;
int recv_count = 0;
char buf[BUFF_SIZE+1] = {'\0'};
msg->msg_end = 0;
msg->msg[0] = '\0';
int recv_flag = RECV_MSG_NONE;
while (1) {
recv_count = recv(fd, buf, BUFF_SIZE, 0);
if (recv_count < 0) {
if (errno==EAGAIN || errno==EWOULDBLOCK) {
if (recv_flag != RECV_MSG_OLMT)
recv_flag = RECV_MSG_OK;
break;
}
recv_flag = RECV_MSG_ERR;
close_socket(fd);
break;
} else if (recv_count == 0) { //connection closed
recv_flag = RECV_MSG_CLOSE;
ep_delfd(efd, fd);
close_socket(fd);
break;
} else {
msg_count += recv_count;
if (msg_count <= MAX_MSG_SIZE) {
recv_flag = RECV_MSG_OK;
strcat(msg->msg, buf);
} else {
recv_flag = RECV_MSG_OLMT;
}
}
}
return recv_flag;
}
void event_et(struct epoll_event *evt, int number, int efd, int lisd) {
int connfd = 0;
struct sockaddr_in conn;
socklen_t conn_size = sizeof(conn);
char buf[BUFF_SIZE+1] = {'\0'};
int recv_count = 0;
int recv_flag = RECV_MSG_NONE;
for (int i=0; i<number; i++) {
if (lisd == evt[i].data.fd) {
if (_accpet_count >= ACCEPT_MAX_LIMIT)
return;
if (try_accpet_lock(_accept_sem) < 0) {
printf("%u : failed to get lock\n", getpid());
return ;
}
connfd = accept(lisd, (struct sockaddr*)&conn, &conn_size);
release_accpet_lock(_accept_sem);
if (connfd < 0) {
//perror("accept");
return ;
}
_accpet_count += 1;
printf("%d : get connection -- sock: %d...\n", _self_pid, connfd);
ep_addfd(efd, connfd, 1);
} else if (evt[i].events & EPOLLIN){
printf("pid:%d get data from %d:\n", _self_pid, evt[i].data.fd);
struct msg_block msg;
msg.msg_end = 0;
msg.msg[0] = '\0';
recv_flag = RECV_MSG_NONE;
recv_flag = handle_recv_msg(efd, evt[i].data.fd, &msg);
if (recv_flag == RECV_MSG_OK) {
//printf("bytes:%ld recieved: %s\n", strlen(msg.msg),msg.msg);
if (strncmp(msg.msg, "//quit", 6)==0) {
ep_delfd(efd, evt[i].data.fd);
close_socket(evt[i].data.fd);
return ;
}
save_msg(evt[i].data.fd, &msg);
ep_modfd(efd, evt[i].data.fd, EPOLLOUT, 1);
} else if (recv_flag == RECV_MSG_CLOSE) {
printf("client closed\n");
} else if (recv_flag == RECV_MSG_OLMT) {
strcpy(msg.msg, "Error: out of limit\n");
save_msg(evt[i].data.fd, &msg);
ep_modfd(efd, evt[i].data.fd, EPOLLOUT, 1);
}
}else if (evt[i].events & EPOLLOUT){
struct event_msg * emsg = get_msg(evt[i].data.fd);
if (emsg == NULL)
return ;
printf("send msg: %s\n", emsg->data.msg);
send(evt[i].data.fd, (void*)emsg->data.msg, strlen(emsg->data.msg), 0);
ep_modfd(efd, evt[i].data.fd, EPOLLIN, 1);
}else {
}
}
}
int child_server(int lisd) {
_self_pid = getpid();
signal(SIGINT, SIG_IGN);
signal(SIGTERM, child_handle_sig);
signal(SIGCHLD, SIG_DFL);
_accpet_count = 0;
struct epoll_event events[ACCEPT_MAX_LIMIT];
int efd = epoll_create1(0);
if (efd < 0) {
perror("epoll_create1");
return 1;
}
ep_addfd(efd, lisd, 1);
int event_count = 0;
while(1) {
event_count = epoll_wait(efd, events, ACCEPT_MAX_LIMIT, -1);
if (event_count < 0) {
perror("epoll_wait");
break;
}
event_et(events, event_count, efd, lisd);
}
close(lisd);
close(efd);
return 0;
}
int main(int argc, char * argv[]) {
//start to daemon
pid_t dpid = fork();
if (dpid<0) {
perror("fork");
return 1;
}
if (dpid > 0) {
exit(0);
}
setsid();
//end daemon
int process_flag = PCS_PARENT;
//start to set semaphore
_accept_sem = init_accept_lock("accept-lock");
//end sem
struct sockaddr_in addr;
int lisd = socket(PF_INET, SOCK_STREAM, 0);
bzero((void*)&addr,sizeof(addr));
if(lisd<0)
{
perror("socket");
return -1;
}
int reuse = 1;
setsockopt(lisd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
int port = DEF_PORT;
if (argc > 1) {
if (strncmp(argv[1], "--port=", 7)==0) {
port = atoi(argv[1]+7);
if (port < 1024 || port > 50000) {
port = DEF_PORT;
}
}
}
addr.sin_port=htons(port);
addr.sin_addr.s_addr=inet_addr("127.0.0.1");
addr.sin_family=AF_INET;
if(bind(lisd,(struct sockaddr*)&addr,sizeof(addr)))
{
perror("bind");
return -1;
}
if(listen(lisd,13))
{
perror("listen");
return -1;
}
pid_t pid;
if (process_flag == PCS_PARENT) {
_self_pid = getpid();
printf("daemon running:%u at 127.0.0.1:%d\n", _self_pid, port);
signal(SIGINT, parent_handle_sig);
signal(SIGTERM, parent_handle_sig);
signal(SIGCHLD, parent_handle_sig);
while (1) {
/*
检测如果子进程数量小于设置默认值则创建子进程
*/
if (__child_count < CHILD_COUNT) {
int mis = CHILD_COUNT - __child_count;
for(int i=0; i<mis; i++) {
pid = fork();
if (pid < 0) {
continue;
}
if (pid > 0) {
__child_count += 1;
continue;
} else {
process_flag = PCS_CHILD;
goto child_run;
}
} //end for
} //end if
sleep(2);
}
}
child_run:;
if (process_flag == PCS_CHILD) {
child_server(lisd);
}
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int a, b, v;
int day;
scanf("%d %d %d", &a, &b, &v);
day = (v - b) / (a - b);
if ((v - b) % (a - b) == 0)
printf("%d", day);
else
printf("%d", day + 1);
return 0;
}
|
C
|
#include <setjmp.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
char f_stack[1024], g_stack[1024];
int f_size, g_size;
jmp_buf f_buf, g_buf;
char *top_stack;
void f(){
int n=0;
while(1){
printf(" f : %d \n", n++);
sleep(1);
if(setjmp(f_buf) ==0 ){
//sauvegarde de la pile dans f_stack
// 1 definir le nb d'octet a recopier
// memcpy(void *dest, const void *src, size_t n);
f_size = (void*)top_stack - (void*)&n;
printf(" char* %d , int * %d\n",sizeof(char*),sizeof(int*));
memcpy(f_stack, &n, f_size);
longjmp(g_buf,1);
}else{
//restaure la pile f_stack
memcpy(top_stack - f_size, f_stack, f_size);
}
}
}
void g(){
int m=1000;
while(1){
printf(" g : %d \n", m++);
sleep(1);
if(setjmp(g_buf) ==0 ){
//sauvegarde
g_size = (void*)top_stack - (void*)&m;
printf(" g_size %d \n",g_size);
memcpy(g_stack, &m, g_size );
longjmp(f_buf,1);
}else{
//restaure
memcpy(top_stack - g_size, g_stack, g_size);
}
}
}
int main(void){
char toto;
//placer @ du sommet de pile ds top_stack
top_stack = &toto;
if(setjmp(g_buf)==0){
f();
}else{
g();
}
return EXIT_SUCCESS;
}
|
C
|
#include "launch.h"
#include "str.h"
#include "userio.h"
#include "mproc.h"
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/resource.h>
struct mproc *procs = NULL;
int last = 0;
int ioflags = 0;
void sig_handler(int sig) {
switch (sig) {
case SIGCHLD:
handle();
break;
case SIGINT:
// nothing :)
break;
case SIGSEGV:
exit(0);
break;
default:
break;
}
}
int main(int argc, char *const argv[]) {
char **cmd;
int result;
signal(SIGCHLD, sig_handler);
signal(SIGINT, sig_handler);
signal(SIGSEGV, sig_handler);
ioflags = ADD(IOFL_IN, IOFL_OUT);
clear_prompt();
show_prompt();
for (;;) {
/* both IOFL_IN and IOFL_OUT required. */
if (!HAS(ioflags, IOFL_IN)) continue;
if (!HAS(ioflags, IOFL_OUT)) continue;
/* get tokenized strings from stdin. */
cmd = get_strings(stdin, 128, " \t\n");
result = launch(cmd);
if (NEED_TO_SHOW_PROMPT(result)) {
/*
In case like:
1) Returned just after spawning background process. (RET_BG)
2) Command is a builtin function. (RET_BUILTIN)
3) User typed nothing. (RET_NONE)
See launch() for more information.
*/
show_prompt();
free_strs(cmd);
}
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
int A[ 9 ] = { 4, 8, 3, 5, 6, 7, 2, 1, 0 };
#define N 1
int f( long long n, int x )
{
if( n < 2 )
return A[ x ];
else
{
return f( n - 1, x );
}
}
int main( int argc, char **argv )
{
long long m = ( argc > 1 ) ? (int)atol( argv[1] ) : N;
printf( "Here we go %lld\n", m );
int rv = f( ((long long)1) << ( m - 1 ), 1 );
return rv;
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
int main(void)
{
int fd = -1;
fd = open("test.c", O_WRONLY|O_CREAT|O_EXCL, 0644);
if (fd < 0) {
if (EEXIST == errno) { //file exist.
printf("file exist!\n");
fd = open("test.c", O_RDWR|O_APPEND);
} else {
perror("open failed!");
return -1;
}
}
// handle the file
//...
if (fd > 0 )
close(fd);
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include "helper.h"
int main(int argc, char *argv[]){
FILE *fp = fopen(argv[1], "rb");
if (fp == NULL) {
perror("fopen");
exit(1);
}
int total = get_file_size(argv[1]) / sizeof(struct rec);
int print_num;
if (total <= 100) {
print_num = total;
} else {
print_num = 100;
}
struct rec *t = malloc(sizeof(struct rec));
for (int i = 0; i < print_num; i ++) {
fread(t, sizeof(struct rec), 1, fp);
printf("%d, %s\n", t->freq, t->word);
}
if (fclose(fp) == -1) {
perror("fclose");
exit(1);
}
free(t);
}
|
C
|
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <pthread.h>
int fd;
void *read_func(void *arg)
{
char read_buff[128];
read( fd, &read_buff, sizeof(read_buff));
printf("Start Time from FIFO: %s\n",read_buff);
}
void *write_func(void *arg)
{
char write_buff[128];
time_t sec;
struct tm *timeinfo;
time (&sec);
timeinfo = localtime(&sec);
strftime(write_buff,128,"%H:%M:%S",timeinfo);
write( fd, write_buff, sizeof(write_buff));
printf("Start Time: %s\n", write_buff);
}
int main()
{
char path[256] = "FIFO";
int result, r_id, w_id;
pthread_t r_thread, w_thread;
if( mkfifo(path, 0777) ==0)
{
fd = open(path, O_RDWR);
w_id = 1;
result = pthread_create(&w_thread, NULL, write_func, &w_id);
if(result != 0 )
{
perror("Creating write thread");
return EXIT_FAILURE;
}
else
printf("Creating write thread - Success\n");
sleep(1);
r_id = 2;
result = pthread_create(&r_thread, NULL, read_func, &r_id);
if(result != 0 )
{
perror("Creating read thread");
return EXIT_FAILURE;
}
else
printf("Creating read thread - Success\n");
sleep(1);
}
else
perror("FIFO error:");
return 0;
}
|
C
|
// UCSD CSE237A - WI18
// All rights reserved
// Important! DO NOT MODIFY this file. You will not submit this file.
// This file is provided for your understanding of the program procedure.
// For more details, please see the instructions in the class website
#include <stdio.h>
#include <pthread.h>
#include <wiringPi.h>
#include "section1.h"
#include "shared_var.h"
int main(int argc, char* argv[]) {
SharedVariable v;
if (wiringPiSetup() == -1) {
printf("Failed to setup wiringPi.");
return 1;
}
program_init(&v);
while (v.bProgramExit != 1) {
program_body(&v);
delay(1);
}
program_exit(&v);
printf("Program finished.\n");
return 0;
}
|
C
|
//
// main.c
// Small mad-lib game
//
// Created by Dan Esrey on 2016/12/08.
// Copyright © 2016 Dan Esrey. All rights reserved.
//
#include <stdio.h>
#include "mad-lib enums.h"
int getUserName(char name[], char *prompt);
int main(int argc, const char * argv[]) {
char name[100] = "\0";
int numberOfItemsScanned = 0;
while (numberOfItemsScanned != 1) {
numberOfItemsScanned = getUserName(name, "Please enter your name:\n\n");
}
printf("Please choose an adjective:\n\n");
Adj adjChosen = AdjNull;
int firstNumberOfItemsScanned = 0;
while ((firstNumberOfItemsScanned != 1) ||
(adjChosen < AdjFirst) || (adjChosen > AdjLast)) {
fpurge(stdin);
printf("please enter:\n");
printf(" %d for scary\n", AdjScary);
printf(" %d for dangerous\n", AdjDangerous);
printf(" %d for flatulent\n", AdjFlatulent);
printf(" %d for tired\n", AdjTired);
firstNumberOfItemsScanned = scanf("%d", &adjChosen);
}
char *adjAsString = AdjGetStringName(adjChosen);
printf("Next, pease choose a noun:\n\n");
Nouns nounChosen = NounsNull;
int secondNumberOfItemsScanned = 0;
while ((secondNumberOfItemsScanned != 1) ||
(nounChosen < NounsFirst) || (nounChosen > NounsLast)) {
fpurge(stdin);
printf("please enter:\n");
printf(" %d for puppy\n", NounPuppy);
printf(" %d for pillow\n", NounPillow);
printf(" %d for notebook\n", NounNotebook);
printf(" %d for laptop\n", NounLaptop);
secondNumberOfItemsScanned = scanf("%d", &nounChosen);
}
char *nounAsString = NounsGetStringName(nounChosen);
printf("Lastly, pease choose a verb:\n\n");
Verbs verbChosen = VerbsNull;
int thirdNumberOfItemsScanned = 0;
while ((thirdNumberOfItemsScanned != 1) ||
(verbChosen < VerbsFirst) || (verbChosen > VerbsLast)) {
fpurge(stdin);
printf("please enter:\n");
printf(" %d for eat\n", VerbEat);
printf(" %d for run\n", VerbRun);
printf(" %d for destroy\n", VerbDestroy);
printf(" %d for investigate\n", VerbInvestigate);
printf(" %d for program\n", VerbProgram);
thirdNumberOfItemsScanned = scanf("%d", &verbChosen);
}
char *verbAsString = VerbsGetStringName(verbChosen);
printf("You chose the adjective '%s,' the noun '%s,' and the verb '%s.'\n\n", adjAsString, nounAsString, verbAsString);
printf("One day, %s was so excited because %s had just gotten a new %s.\n\n", name, name, nounAsString);
printf("%s looked at the %s and thought it looked a bit %s.\n\n", name, nounAsString, adjAsString);
printf("%s realized that with the new %s, %s would be able to %s the world!\n\n", name, nounAsString, name, verbAsString);
return 0;
}
int getUserName(char name[], char *prompt) {
int numberOfItemsScanned = 0;
while (numberOfItemsScanned != 1) {
fpurge(stdin);
printf("%s", prompt);
numberOfItemsScanned = scanf("%[^\n]s", name);
}
return numberOfItemsScanned;
}
|
C
|
/* alarm.c 4.1 83/06/10 */
/*
* Backwards compatible alarm.
*/
#include <sys/time.h>
alarm(secs)
int secs;
{
struct itimerval it, oitv;
register struct itimerval *itp = ⁢
timerclear(&itp->it_interval);
itp->it_value.tv_sec = secs;
itp->it_value.tv_usec = 0;
if (setitimer(ITIMER_REAL, itp, &oitv) < 0)
return (-1);
return (oitv.it_value.tv_sec);
}
|
C
|
//10ÿϢ2.75%ÿȡ10ȡꣿ
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
double money = 10.0; //ʹfloatЩ
double rate = 0.0275;
int year = 0;
printf("ʽΪ%fԪ%f%%\n", money, rate*100); //
do
{
money = money * (1 + rate) - 1; //ȡǮʣʽ
year ++;
if (money >= 0)
printf("%dʣʽΪ%fԪ\n", year, money); //
else //-1ʣʽС0ֻȡʣʽ
printf("%dȡʣʽ%fԪ\n", year, money + 1);
} while (money > 0);
//printf("%dȡʣʽ\n", year);
getch();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <time.h>
#include <ctype.h>
#include<string.h>
#include <windows.h>
int size;
//int magic_const;
int *cols_sum;
int row_sum=0;
//------------------------------
// Create a dinamically allocated array with capacity `n`
int *ints_new(int n)
{
// return (int *) calloc(n, sizeof (int));
return (int *) malloc (n * sizeof(int));
}
//-------------------------------
//obter o tamanho a ordem da matriz a partir do nome do ficheiro
void get_size(char *filename){
char *f = filename;
while(*f){
if (isdigit(*f)) size = strtol(f,&f,10);
else f++;
}
//magic_const= size * ( size * size + 1 ) / 2; //calcular o valor da constante magica
cols_sum = ints_new(size); //alocar memoria para a matriz que guarda a soma das colunas
}
char *check_magic_square(char *filename){
FILE *fp = fopen(filename,"r");
int n;
int row_temp=0;
int order=0;
int dlr_sum = 0;
int drl_sum = 0;
while ( fscanf(fp,"%d", &n) != EOF){
int row = (int)(order/size);
int col = (int)(order%size);
cols_sum[col] += n;
row_temp += n;
//printf("%d %d\n",row_sum,row_temp);
if(row == col) dlr_sum += n;
if(col == ( size - 1 ) - row ) drl_sum += n;
if(row == 0) row_sum += n;
if(col == size - 1){
if( row_sum == row_temp) row_temp = 0;
else return "Não é quadrado mágico\n";
}
order++;
}
if(dlr_sum != row_sum || drl_sum != row_sum) return "Quadrado imperfeito\n";
return "Quadrado mágico\n";
}
void magic_square( char *filename){
get_size(filename);
printf("%s",check_magic_square(filename));
}
int main(int argc, char *argv[])
{
char *filename= "inputs/p3.txt";
if (argc >= 2 )
filename = argv[1];
magic_square(filename);
return 0;
}
|
C
|
#include <stdio.h>
int main(int argc, char const *argv[])
{
int n;
scanf("%d", &n);
int i;
int bil1[n];
for(i=0; i<n; i++){
scanf("%d", &bil1[i]);
}
int bil2[n];
for(i=0; i<n; i++){
scanf("%d", &bil2[i]);
}
int x;
for(i=0; i<n; i+=2){
if((bil1[i] % 2 == 0) && (bil2[i] % 2 == 0)){
x=1;
}else{
x=0;
}
}
for(i=1; i<n; i+=2){
if((bil1[i] % 2 != 0) && (bil2[i] % 2!= 0)){
x=1;
}else{
x=0;
}
}
if(x==1){
printf("valid\n");
}else if(x==0){
printf("valid\n");
}else{
printf("tidak valid\n");
}
return 0;
}
|
C
|
//======================================================================================
// Auto Irrigation
// Water plants automatically based on the dryness of the soil
// or at regular intervals using the MSP430 microprocessor.
//
// Copyright 2012 Xavier Bick
//
// See README.md for usage and configuration instructions
//
// Licensed under the MIT license
//======================================================================================
//#include <msp430g2553.h>
//volatile unsigned int i;
//void main(void)
//{
//WDTCTL = WDT_ADLY_1000; // WDT 1s interval timer
//IE1 |= WDTIE; // Enable WDT interrupt
//P1DIR = 0xFF; // All P1.x outputs
//P1OUT = 0; // All P1.x reset
//P2DIR = 0xFF; // All P2.x outputs
//P2OUT = 0; // All P2.x reset
//BCSCTL3 = XCAP_3; //12.5pF cap- setting for 32768Hz crystal
//// An immediate Osc Fault will occur next
//IE1 |= OFIE; // Enable Osc Fault
//while(1)
//{
//P1OUT ^= 0x01; // Toggle P1.0 using exclusive-OR
//_BIS_SR(LPM3_bits + GIE); // Enter LPM3 w/interrupt
//}
//}
//#pragma vector=WDT_VECTOR
//__interrupt void watchdog_timer (void)
//{
//_BIC_SR_IRQ(LPM3_bits); // Clear LPM3 bits from 0(SR)
//}
//#pragma vector=NMI_VECTOR
//__interrupt void nmi_ (void)
//{
//do
//{
//IFG1 &= ~OFIFG; // Clear OSCFault flag
//for (i = 0xFFF; i > 0; i--); // Time for flag to set
//P1OUT ^= 0x01; // Toggle P1.0 using exclusive-OR
//}
//while (IFG1 & OFIFG); // OSCFault flag still set?
//IE1 |= OFIE; // Enable Osc Fault
//}
#include "msp430G2553.h"
// Pin Configuration (Defaults in parentheses):
#define WATER BIT6 // Output for water flow control (P1.6)
#define PROBE BIT5 // Input for dryness detection probe (P1.1 = A1)
#define MIN_DRY 0x0060 // ADC Input level at which to turn on water flow (0x220)
#define W_TIME 5 // How long to water the plany in seconds
#define DELAY 350 // Minimum time to wait between waterings in minutes
#define BTN BIT3 // Button for bypassing automatic watering
int flow = 0;
int bypass;
int i = 0;
int delay = (DELAY*60);
void main(void)
{
// ADC10CTL1 = CONSEQ_2;
WDTCTL = WDT_ADLY_1000; // WDT 1s interval timer
IE1 |= WDTIE; // Enable WDT interrupt
P1DIR = 0xFF; // All P1.x outputs
P1OUT = 0; // All P1.x reset
P2DIR = 0xFF; // All P2.x outputs
P2OUT = 0; // All P2.x reset
BCSCTL3 = XCAP_3; //12.5pF cap- setting for 32768Hz crystal
ADC10CTL0 = ADC10SHT_2 + ADC10ON; // ADC On
// An immedate Osc Fault will occur next
IE1 |= OFIE; // Enable Osc Fault
switch ( PROBE ) { // Sets ADC channel to match PROBE
case BIT0:
ADC10CTL1 |= INCH_0;
break;
case BIT1:
ADC10CTL1 |= INCH_1;
break;
case BIT2:
ADC10CTL1 |= INCH_2;
break;
case BIT3:
ADC10CTL1 |= INCH_3;
break;
case BIT4:
ADC10CTL1 |= INCH_4;
break;
case BIT5:
ADC10CTL1 |= INCH_5;
break;
case BIT6:
ADC10CTL1 |= INCH_6;
break;
case BIT7:
ADC10CTL1 |= INCH_7;
break;
case BIT8:
ADC10CTL1 |= INCH_8;
break;
case BIT9:
ADC10CTL1 |= INCH_9;
break;
case BITA:
ADC10CTL1 |= INCH_10;
break;
case BITB:
ADC10CTL1 |= INCH_11;
break;
case BITC:
ADC10CTL1 |= INCH_12;
break;
case BITD:
ADC10CTL1 |= INCH_13;
break;
case BITE:
ADC10CTL1 |= INCH_14;
break;
case BITF:
ADC10CTL1 |= INCH_15;
break;
/* Adjust the following for additional pins on devices with more than 16 channels
* case BIT0:
* ADC10CTL1 |= INCH_0;
break;
*/
}
ADC10AE0 |= PROBE; // Enables analog input on PROBE
ADC10CTL0 |= ENC;
P1DIR |= WATER;
P1DIR &= ~BTN;
P1IN |= BTN;
P1IE |= BTN;
P1OUT %= ~WATER; // Water flow initally off
__enable_interrupt();
for (;;) {
ADC10CTL0 |= ADC10SC; // Collects data
if (ADC10MEM > MIN_DRY && delay >= (DELAY*60)) { // When the dryness rises above MIN_DRY and Bypass is disabled,
P1OUT |= WATER; // Turns on water flow
flow = 1;
delay = 0;3
_BIS_SR(LPM3_bits + GIE); // Enter LPM3 w/interrupt
}
// else if (ADC10MEM < MIN_DRY - HYDR) { // When the dryness falls below MIN_DRY minus HYDR
// P1OUT &= ~WATER; // Turns off water flow
// }
}
}
#pragma vector=WDT_VECTOR
__interrupt void watchdog_timer (void)
{
if (flow == 1) {
if (i < W_TIME) {
i++;
}
else {
i = 0;
flow = 0;
P1OUT &= ~WATER;
delay = 0;
_BIC_SR_IRQ(LPM3_bits); // Clear LPM3 bits from 0(SR)
}
}
else if (flow == 0) {
if (delay < 40000) {
delay++;
}
}
}
#pragma vector=NMI_VECTOR
__interrupt void nmi_ (void)
{
do
{
IFG1 &= ~OFIFG; // Clear OSCFault flag
for (i = 0xFFF; i > 0; i--); // Time for flag to set
}
while (IFG1 & OFIFG); // OSCFault flag still set?
IE1 |= OFIE; // Enable Osc Fault
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct tree {
int data;
int altura;
struct tree *esq;
struct tree *dir;
} Tree;
int fator(Tree **root) { //Fator
if(*root == NULL) return 0;
if((*root)->esq == NULL && (*root)->dir == NULL) return 0;
if((*root)->esq == NULL) return (*root)->altura * -1;
if((*root)->dir == NULL) return (*root)->altura;
return (*root)->esq->altura - (*root)->dir->altura;
}
int maximo(Tree **esq, Tree **dir) {
if(*esq == NULL && *dir == NULL) return 0;
if(*esq == NULL) return (*dir)->altura + 1;
if(*dir == NULL) return (*esq)->altura + 1;
if((*esq)->altura > (*dir)->altura) return (*esq)->altura + 1;
else return (*dir)->altura + 1;
}
//Rotações em Arvore Binaria Balanceada/AVL.
void rse (Tree **root) { //Rotação Simples a Esquerda
if(*root == NULL) return;
Tree *aux = *root;
*root = (*root)->dir;
aux->dir = (*root)->esq;
(*root)->esq = aux;
aux->altura = maximo(&aux->esq, &aux->dir);
(*root)->altura = maximo(&(*root)->esq, &(*root)->dir);
}
void rsd (Tree **root) { //Rotação Simples a Direita
if(*root == NULL) return;
Tree *aux = *root;
*root = (*root)->esq;
aux->esq = (*root)->dir;
(*root)->dir = aux;
aux->altura = maximo(&aux->esq, &aux->dir);
(*root)->altura = maximo(&(*root)->esq, &(*root)->dir);
}
void rdd(Tree **root) { //Rotação Dupla a Direita
if(*root == NULL) return;
rse(&(*root)->esq);
rsd(&(*root));
}
void rde(Tree **root) { //Rotação Dupla a Esquerda
if(*root == NULL) return;
rsd(&(*root)->dir);
rse(&(*root));
}
void corrige(Tree **root) {
if(*root == NULL) return;
int fat = fator(&(*root));
if(fat < -1) {
if(fator(&(*root)->dir) <= 0)
rse(&(*root));
else
rde(&(*root));
} else if(fat > 1) {
if(fator(&(*root)->esq) >= 0)
rsd(&(*root));
else
rdd(&(*root));
}
}
Tree* maiorElemento(Tree *root) {
if(root == NULL) return NULL;
Tree *aux = root;
while (aux->dir != NULL) aux = aux->dir;
return aux;
}
Tree* menorElemento(Tree *root) {
if(root == NULL) return NULL;
Tree *aux = root;
while(aux->esq != NULL) aux = aux->esq;
return aux;
}
int qtdElementos(Tree **root) {
if(*root == NULL) return 0;
return 1 + qtdElementos(&(*root)->esq) + qtdElementos(&(*root)->dir);
}
Tree* removeMaior(Tree *root) {
if(root == NULL) return NULL;
if(root->dir == NULL) {
Tree *aux = root->esq;
free(root);
return aux;
}
root->dir = removeMaior(root->dir);
return root;
}
void mostraFolhas(Tree **root) {
if(*root == NULL) return;
if((*root)->esq == NULL && (*root)->dir == NULL)
printf("%d ", (*root)->data);
mostraFolhas(&(*root)->esq);
mostraFolhas(&(*root)->dir);
}
int comprimentoRaizToN(Tree **root, int data) {
if(*root == NULL) return -1;
if(data == (*root)->data) return 0;
if(data > (*root)->data) return 1 + comprimentoRaizToN(&(*root)->dir, data);
else if(data < (*root)->data) return 1 + comprimentoRaizToN(&(*root)->esq, data);
}
void N_to_Raiz(Tree **root, int data) {
if(*root == NULL) return;
if((*root)->data == data) {
printf("%d ", data);
return;
}
if(data > (*root)->data) N_to_Raiz(&(*root)->dir, data);
else N_to_Raiz(&(*root)->esq, data);
printf("%d ", (*root)->data);
}
void destruir(Tree *root) {
if(root == NULL) return;
destruir(root->esq);
destruir(root->dir);
free(root);
}
Tree* removeNo(Tree *root, int data) {
if(root == NULL) return 0;
if(data == root->data) {
if(root->esq == NULL) {
Tree *aux = root;
root = root->dir;
free(aux);
return root;
} else if(root->dir == NULL) {
Tree *aux = root;
root = root->esq;
free(aux);
return root;
} else if(root->esq != NULL && root->dir != NULL) {
Tree *aux = maiorElemento(root->esq);
root->data = aux->data;
root->esq = removeNo(root->esq, root->data);
return root;
}
}
if(data > root->data) {
root->dir = removeNo(root->dir, data);
root->altura = maximo(&root->esq, &root->dir);
return root;
}
else {
root->esq = removeNo(root->esq, data);
root->altura = maximo(&root->esq, &root->dir);
return root;
}
}
void addNode(Tree **root, int data) {
if(*root == NULL) {
*root = (Tree*) malloc (sizeof(Tree));
(*root)->altura = 0;
(*root)->data = data;
(*root)->esq = NULL;
(*root)->dir = NULL;
}
else if(data > (*root)->data) {
addNode(&(*root)->dir, data);
}
else {
addNode(&(*root)->esq, data);
}
(*root)->altura = maximo(&(*root)->esq, &(*root)->dir);
corrige(&(*root));
}
void preOrder(Tree *root) {
if(root == NULL) return;
printf("%d [%d] (%d) \n", root->data, root->altura, fator(&root));
preOrder(root->esq);
preOrder(root->dir);
}
void inOrder(Tree *root) {
if(root == NULL) return;
inOrder(root->esq);
printf("%d ", root->data);
inOrder(root->dir);
}
void posOrder(Tree *root) {
if(root == NULL) return;
posOrder(root->esq);
posOrder(root->dir);
printf("%d ", root->data);
}
int menu();
int main () {
Tree* root = NULL;
int i, op;
/*int input[12] = {50, 55, 40, 45, 12, 34, 22, 78, 10, 5, 1, 25};
for(i = 0; i < 12; ++i) {
addNode(&root, input[i]);
}*/
system("clear || cls");
do {
op = menu();
switch (op) {
case 0:
system("clear || cls");
printf("Falou :D\n");
break;
case 1: {
int valor;
system("clear || cls");
printf("Informe um valor para inserir: ");
scanf("%d", &valor);
addNode(&root, valor);
} break;
case 2:
system("clear || cls");
printf("Pre..: ");
preOrder(root);
printf("\n");
break;
case 3:
system("clear || cls");
printf("In.: ");
inOrder(root);
printf("\n");
break;
case 4:
system("clear || cls");
printf("Pos..:");
posOrder(root);
printf("\n");
break;
case 5:
system("clear || cls");
printf("Numero de elementos: %d", qtdElementos(&root));
printf("\n");
break;
case 6: {
root *maior;
system("clear || cls");
maior = maiorElemento(root);
if(maior != NULL) printf("Maior Elemento: %d\n", maior->data);
else printf("Arvore Vazia !!\n");
}
break;
case 7:{
root *menor;
system("clear || cls");
menor = menorElemento(root);
if(menor != NULL) printf("Menor Elemento: %d\n", menor->data);
else printf("Arvore Vazia !!\n");
}
break;
case 8:{
system("clear || cls");
if((root = removeMaior(root)) != NULL) printf("Maior elemento removido !!\n");
else printf("Arvore Vazia !!\n");
}
break;
case 9:
system("clear || cls");
printf("Folhas..: ");
mostraFolhas(&root);
printf("\n");
break;
case 10: {
system("clear || cls");
int n;
printf("Informe um no: ");
scanf("%d", &n);
printf("Comprimento da raiz ate %d: %d\n", n, comprimentoRaizToN(&root, n));
}
break;
case 11: {
int n;
system("clear || cls");
printf("Informe um no: ");
scanf("%d", &n);
N_to_Raiz(&root, n);
printf("\n");
}
break;
case 12:
system("clear || cls");
printf("Altura da arvore: %d\n", root->altura);
break;
case 13: {
system("clear || cls");
int n;
printf("Informe o no que deseja remover: ");
scanf("%d", &n);
if((root = removeNo(root, n)) != NULL) printf("No (%d) removido.\n", n);
else printf("Falha ao remover o no (%d).\n", n);
}
break;
case 14:
system("clear || cls");
destruir(root);
root = NULL;
break;
case 15:
system("clear || cls");
rse(&root);
break;
case 16:
system("clear || cls");
rsd(&root);
break;
case 17:
system("clear || cls");
rde(&root);
break;
case 18:
system("clear || cls");
rdd(&root);
break;
default:
printf("Opcao invalida");
break;
}
} while (op != 0);
return 0;
}
int menu() {
int op;
printf("0 - Sair\n");
printf("1 - Inserir\n");
printf("2 - Pre-Ordem\n");
printf("3 - Em-Ordem\n");
printf("4 - Pos-Ordem\n");
printf("5 - Quantidade de elementos\n");
printf("6 - Maior Elemento\n");
printf("7 - Menor Elemento\n");
printf("8 - Remove Maior Elemento\n");
printf("9 - Exibe folhas\n");
printf("10 - Comprimento da raiz ate qualquer no\n");
printf("11 - Caminho do no ate a raiz\n");
printf("12 - Altura da arvore\n");
printf("13 - Remove qualquer no\n");
printf("14 - Destroi\n");
printf("15 - Rotacao simples a esquerda\n");
printf("16 - Rotacao simples a direita\n");
printf("17 - Rotacao dupla a esquerda\n");
printf("18 - Rotacao dupla a direita\n");
printf("Escolha uma opcao: ");
scanf("%d", &op);
return op;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct employee{
int empNumber;
int score;
};
typedef struct employee employee;
int enterOption(){
int selection;
printf("1- Write to another file 2- update 3- add new record 4- delete record 5- traverse 6-exit\n");
scanf("%d", &selection);
return selection;
}
void textFile(FILE *ptr){
FILE *writePtr = fopen("newRecodFile.txt", "w");
employee mainEmp = {0,0};
if(writePtr == NULL){
printf("New record File cannot be created\n");
}else{
rewind(ptr);
fprintf(writePtr, "These are new infos");
while(!feof(ptr)){
fread(&mainEmp, sizeof(employee), 1, ptr);
if(mainEmp.empNumber != 0)
fprintf(writePtr, "%d-%d\n", mainEmp.empNumber, mainEmp.score);
fclose(writePtr);
}
}
}
void updateRecord(FILE *ptr){
int updatedRecordNo;
int newScore;
employee mainEmp = {0,0};
printf("Please enter the updated record no : ");
scanf("%d", &updatedRecordNo);
fseek(ptr , (updatedRecordNo-1)* sizeof(employee), SEEK_SET);
fread(&mainEmp, sizeof(employee), 1, ptr);
if(mainEmp.empNumber > 0 ){
printf("Old record : %d-%d \n", mainEmp.empNumber, mainEmp.score);
printf("Enter the new score : ");
scanf("%d", &newScore);
mainEmp.score = newScore;
fseek(ptr , (updatedRecordNo-1)* sizeof(employee), SEEK_SET);
fread(&mainEmp, sizeof(employee), 1, ptr);
}
}
void deleteRecord(FILE *ptr){
employee mainEmp;
employee emptyEmp = {0,0};
int empId;
printf("Enter the deleted record\n");
scanf("%d", &empId);
fseek(ptr, (empId-1)*sizeof(employee), SEEK_SET);
fread(&mainEmp, sizeof(employee), 1,ptr);
if(mainEmp.empNumber == 0)
printf("There is no account");
else{
fseek(ptr, (empId-1)*sizeof(employee), SEEK_SET);
fwrite(&emptyEmp, sizeof(employee), 1,ptr);
}
}
void traverse(FILE *ptr){
employee mainEmp = {0,0};
while(!feof(ptr)){
fread(&mainEmp, sizeof(employee), 1,ptr);
printf("%d-%d\n", mainEmp.empNumber, mainEmp.score);
}
fclose(ptr);
}
int main(){
FILE *ptr;
int selection;
ptr = fopen("employees.txt", "r+");
if(ptr == NULL){
printf("File cannot be opened \n");
}else{
while((selection = enterOption()) != 6){
switch (selection) {
case 1:textFile(ptr);break;
case 2:updateRecord(ptr);break;
case 3:deleteRecord(ptr);break;
case 4:traverse(ptr);break;
}
}
fclose(ptr);
}
}
|
C
|
#include <stdio.h>
void justPrint() {
printf("just print\n");
}
int returnTwo() {
printf("I return 2\n");
return 2;
}
int main() {
justPrint();
int a = returnTwo();
printf("a is %d\n", a);
}
|
C
|
/*
Ideally, you won't need to change this file. You may want to change
a few settings to speed debugging runs, but remember to change back
to the original settings during final testing.
The output format: "Size: %u\tmflop/s: %g\n"
These hands have touched the file:
David Bindel
David Garmire
Jason Riedy
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <math.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <unistd.h>
#include <time.h>
#include "timing.h"
#ifndef COMPILER
# define COMPILER "unknown"
#endif
#ifndef FLAGS
# define FLAGS "unknown"
#endif
/*
Your function _MUST_ have the following signature:
*/
extern const char* dgemm_desc;
extern void square_dgemm();
/*
We try to run enough iterations to get reasonable timings. The matrices
are multiplied at least MIN_RUNS times. If that doesn't take MIN_SECS
seconds, then we double the number of iterations and try again.
You may want to modify these to speed debugging...
*/
#define MIN_RUNS 4
/* #define MIN_SECS 1.0 */
#define MIN_SECS 0.25
/*
Note the strange sizes... You'll see some interesting effects
around some of the powers-of-two.
*/
const int test_sizes[] = {
31, 32, 96, 97, 127, 128, 129, 191, 192, 229,
#if defined(DEBUG_RUN)
# define MAX_SIZE 229u
#else
255, 256, 257, 319, 320, 321, 417, 479, 480, 511, 512, 639, 640,
767, 768, 769,
# define MAX_SIZE 769u
#endif
};
#define N_SIZES (sizeof (test_sizes) / sizeof (int))
/* --
* Initialize A to random numbers (A is MAX_SIZE * MAX_SIZE)
*/
void matrix_init(double *A)
{
int i;
for (i = 0; i < MAX_SIZE*MAX_SIZE; ++i)
A[i] = drand48();
}
/* --
* Zero out C (which is MAX_SIZE * MAX_SIZE)
*/
void matrix_clear(double *C)
{
memset(C, 0, MAX_SIZE * MAX_SIZE * sizeof(double));
}
/* --
* Check that C = A*B to within roundoff error.
*
* We use the fact that dot products satisfy the error bound
*
* float(sum a_i * b_i) = sum a_i * b_i * (1 + delta_i)
*
* where delta_i <= n * epsilon. In order to check your matrix
* multiply, we compute each element in turn and make sure that
* your product is within three times the given error bound.
* We make it three times because there are three sources of
* error:
*
* - the roundoff error in your multiply
* - the roundoff error in our multiply
* - the roundoff error in computing the error bound
*
* That last source of error is not so significant, but that's a
* story for another day.
*/
void validate_dgemm(const int M, const double *A, const double *B, double *C)
{
int i, j, k;
matrix_clear(C);
square_dgemm(M, A, B, C);
for (i = 0; i < M; ++i) {
for (j = 0; j < M; ++j) {
double dotprod = 0;
double errorbound = 0;
double err;
for (k = 0; k < M; ++k) {
double prod = A[k*M + i] * B[j*M + k];
dotprod += prod;
errorbound += fabs(prod);
}
errorbound *= (M * DBL_EPSILON);
err = fabs(C[j*M + i] - dotprod);
if (err > 3*errorbound) {
printf("Matrix multiply failed.\n");
printf("C(%d,%d) should be %lg, was %lg\n", i, j,
dotprod, C[j*M + i]);
printf("Error of %lg, acceptable limit %lg\n",
err, 3*errorbound);
exit(-1);
}
}
}
}
/* --
* Compute a MFlop/s rate for C += A*B.
*
* The code runs the multiplication repeatedly in a loop MIN_RUNS times,
* then doubles the loop time if it did not take MIN_SECS to perform the
* run. This helps us get around the limits of timer resolution.
*/
double time_dgemm(const int M, const double *A, const double *B, double *C)
{
timing_t start, finish;
double mflops, mflop_s;
double secs = -1.0;
int num_iterations = MIN_RUNS;
int i;
while (secs < MIN_SECS) {
matrix_clear(C);
get_time(&start);
for (i = 0; i < num_iterations; ++i) {
square_dgemm(M, A, B, C);
}
get_time(&finish);
secs = timespec_diff(start, finish);
mflops = 2.0 * num_iterations * M * M * M / 1.0e6;
mflop_s = mflops/secs;
num_iterations *= 2;
}
return mflop_s;
}
int main()
{
int i;
double mflop_s;
double* A __attribute__((aligned(16))) = (double*) malloc(MAX_SIZE * MAX_SIZE * sizeof(double));
double* B __attribute__((aligned(16))) = (double*) malloc(MAX_SIZE * MAX_SIZE * sizeof(double));
double* C __attribute__((aligned(16))) = (double*) malloc(MAX_SIZE * MAX_SIZE * sizeof(double));
matrix_init(A);
matrix_init(B);
printf("Compiler:\t%s\nOptions:\t%s\nDescription:\t%s\n\n",
COMPILER, FLAGS, dgemm_desc);
for (i = 0; i < N_SIZES; ++i) {
const int M = test_sizes[i];
validate_dgemm(M, A, B, C);
mflop_s = time_dgemm(M, A, B, C);
printf("Size: %u\tmflop/s: %lg\n", M, mflop_s);
}
free(C);
free(B);
free(A);
return 0;
}
|
C
|
#include <time.h>
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include "ip.h"
void get_rand_addr(
struct sockaddr * sin_net,
struct sockaddr * sin_smask,
struct sockaddr * sin_addr) {
struct sockaddr_in6 * sin_net_6 = sin_net;
struct sockaddr_in * sin_net_4 = sin_net;
struct sockaddr_in6 * sin_smask_6 = sin_smask;
struct sockaddr_in * sin_smask_4 = sin_smask;
struct sockaddr_in6 * sin_addr_6 = sin_addr;
struct sockaddr_in * sin_addr_4 = sin_addr;
uint32_t r;
int i;
sin_addr->sa_family = sin_net->sa_family;
if(sin_net->sa_family == AF_INET) {
r = rand();
sin_addr_4->sin_addr.s_addr = (r&(~sin_smask_4->sin_addr.s_addr)) |
(sin_net_4->sin_addr.s_addr & sin_smask_4->sin_addr.s_addr);
} else if(sin_net->sa_family == AF_INET6) {
for(i=0;i<4;i++) {
r = rand();
sin_addr_6->sin6_addr.s6_addr32[i] =
(r & (~sin_smask_6->sin6_addr.s6_addr32[i])) |
(sin_net_6->sin6_addr.s6_addr32[i] & sin_smask_6->sin6_addr.s6_addr32[i]);
}
}
}
void set_mask(struct sockaddr * sin,int family, int mask) {
uint32_t m[4] = {0,0,0,0};
int i;
struct sockaddr_in6 * sin_6 = sin;
struct sockaddr_in * sin_4 = sin;
srand(time(NULL));
sin->sa_family = family;
for(i=1;i<=mask;i++) {
if(i>96) {
m[3] = m[3] | (0x1 << (32 - i));
}else if(i>64) {
m[2] = m[2] | (0x1 << (32 - i));
} else if(i>32) {
m[1] = m[1] | (0x1 << (32 - i));
} else {
m[0] = m[0] | (0x1 << (32 - i));
}
}
for (i=0;i<4;i++) {
m[i] = htonl(m[i]);
}
if(family == AF_INET) {
memcpy(&(sin_4->sin_addr.s_addr),&(m[0]),32);
} else if(family == AF_INET6) {
memcpy(&(sin_6->sin6_addr.s6_addr32[0]),&(m[0]),128);
}
}
unsigned short int inet_cksum(unsigned short int *addr, size_t len, int init) {
register int nleft = (int) len;
register unsigned short int *w = addr;
unsigned short int answer = 0;
register int sum = init;
/*
* Our algorithm is simple, using a 32 bit accumulator (sum),
* we add sequential 16 bit words to it, and at the end, fold
* back all the carry bits from the top 16 bits into the lower
* 16 bits.
*/
while (nleft > 1) {
sum += *w++;
nleft -= 2;
}
/* mop up an odd byte, if necessary */
if (nleft == 1) {
*(u_char *) (&answer) = *(u_char *) w;
sum += answer;
}
/*
* add back carry outs from top 16 bits to low 16 bits
*/
sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
sum += (sum >> 16); /* add carry */
answer = ~sum; /* truncate to 16 bits */
return (answer);
}
int getipaddr(char * name, struct sockaddr * sin,int family) {
struct addrinfo * res;
struct addrinfo * info;
struct addrinfo hints = {0};
int error;
int found = 0;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_family = family;
error = getaddrinfo(name,NULL,&hints,&res);
if (error != 0)
{
if (error == EAI_SYSTEM)
{
perror("getaddrinfo");
}
else
{
fprintf(stderr, "error in getaddrinfo: %s\n", gai_strerror(error));
}
return -1;
}
else {
for(info = res;info != NULL && found == 0; info = info->ai_next) {
switch(info->ai_addr->sa_family) {
case AF_INET:
case AF_INET6:
memcpy(sin,info->ai_addr,info->ai_addrlen);
found = 1;
break;
}
}
freeaddrinfo(res);
}
if(found == 1){
return 0;
}
else {
return -2;
}
}
|
C
|
//use of semaphore for event notify instead of signal handlers
//in this we are implementing event notify using semaphores..
#include<signal.h>
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<string.h>
#include<errno.h>
sem_t sem;
void *threadFunc1(void *arg){
printf("thread1 has created\n");
sem_post(&sem); //we are unlocking it here(instead of p)
printf("deliverd a event notified to thread2 by unlocking the semphore\n");
pthread_exit(NULL);
}
void *threadFunc2(void *arg){
printf("thread2 has created\n");
sem_wait(&sem);//even if thread2 executes 1st it will block here untill thread1 unlocks it..(since we make semaphore initially in locked state by initialize it by 0(3rd arg) )..
sleep(1); //to print thread1 last printf first and the below printf last i've given a sleep here..
printf("event notify has recieved from thread1\n");
pthread_exit(NULL);
}
main(){
sem_init(&sem,0,0);//so we are lockin the semaphore initially..
//in previous semaphore examples we set semphore initially in unlock state by passing the 3rd argument as 1..
// but here in this case only it is mandatory to set initially in lock state by passing 3rd arg as 0..
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,threadFunc1,NULL);
// sleep(1);
pthread_create(&tid2,NULL,threadFunc2,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
}
|
C
|
/*
* varalloc.h -- variable allocation
*/
#ifndef _VARALLOC_H_
#define _VARALLOC_H_
#define REF_BYTE_SIZE 4 /* size of an address in bytes */
/**
* This class is used to calculate the memory needed for variables and stack frames
* of the currently compiled SPL program.
*
* Those values have to be stored in their corresponding fields in the ProcedureEntry, VariableEntry or
* ParameterTypes structs.
*
* @param program The program for which the variables have to be allocated.
* @param globalTable The symbol table for the current program.
* @param showVarAlloc A boolean value indicating, whether the progress of the allocation should be displayed to the user.
*/
void allocVars(Program *program, SymbolTable *globalTable, bool showVarAlloc);
void allocProcEntry(GlobalDeclaration *globalDeclaration, Entry* procEntry);
void allocParams(SymbolTable *localTable, int *inArgs, ParameterList *params, ParamTypes* paramTypes);
void allocVars_Proc(SymbolTable *localTable, int * varLengthCounter, VariableDeclarationList* vars );
void allocOutArgsProcEntry(SymbolTable *globalTable, StatementList *procBody, int * currentMaxInArgSize) ;
void allocOutArgsProcEntry_Stm(SymbolTable *globalTable, Statement * statement, int * currentMaxInArgSize) ;
#endif /* _VARALLOC_H_ */
|
C
|
#include "raylib.h"
int main(void) {
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight,
"raylib [shapes] example - basic shapes drawing");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
DrawText("some basic shapes available on raylib", 20, 20, 20, DARKGRAY);
DrawPoly((Vector2){screenWidth / 4 * 3, 320}, 6, 80, 0, BROWN);
// NOTE: We draw all LINES based shapes together to optimize internal
// drawing, this way, all LINES are rendered in a single draw pass
/*DrawLine(18, 42, screenWidth - 18, 42, BLACK);*/
/*DrawCircleLines(screenWidth / 4, 340, 80, DARKBLUE);*/
/*DrawTriangleLines((Vector2){screenWidth / 4 * 3, 160},*/
/*(Vector2){screenWidth / 4 * 3 - 20, 230},*/
/*(Vector2){screenWidth / 4 * 3 + 20, 230}, DARKBLUE);*/
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
|
C
|
#include "../../../test_common.h"
#include <math.h>
#include <errno.h>
//@ ensures \result < 1.0;
extern long double outrange();
//@ ensures \result >= 1.0;
extern long double inrange();
void runSuccess() {
acoshl(1.0L);
acoshl(0.0L);
acoshl(-1.0L);
acoshl(2.0L);
acoshl(-2.0L);
acoshl(inrange());
acoshl(outrange());
acoshl(anylongdouble());
}
void runFailure() {
}
int f;
void testValues() {
f = 2;
long double result;
//result = acoshl(0.5L);
// assert \coshl(result) == 0.5;
result = acoshl(2.0L);
//@ assert (math_errhandling & MATH_ERRNO) ==> (errno == EDOM);
errno = 0;
result = acoshl(outrange());
//@ assert (math_errhandling & MATH_ERRNO) ==> (errno == EDOM);
errno = 0;
result = acoshl(inrange());
//@ assert result >= 0;
//@ assert f == 2;
//@ assert vacuous: \false;
}
|
C
|
/* ----------------------------------------- *
| IPC homework #2 |
| iSum |
| Due date: 10/27 |
| 0016045 ymli @ cs104 |
* ----------------------------------------- */
#include <stdio.h>
#include <math.h> /* I need the powerful pow() ! */
void sum1 (int n) {
int sum = n, sign = 0; /* sign will tall you to plus or minus the next number */
while (n >= 10) {
printf("%d%c", n, (sign ? '+' : '-'));
n /= 10;
sum += ((sign ? 1: (-1)) * n);
sign = !sign; /* change the value of sign */
}
printf("%d = %d\n", n, sum);
}
int sum2 (int n) {
char foo[12];
int len = sprintf(foo, "%d", n); /* use sprintf() to get the length of n */
int i, div, temp, sum;
for (sum = 0, i = 1; i <= len; i++) {
div = (int) pow(10.0, (double)(len-i)); /* what to divide */
temp = n / div;
sum += temp;
printf("%d+", temp);
}
printf("\b = ");
return sum;
}
void sum3 (int n) {
char foo[12], fmt[10];
int len = sprintf(foo, "%d", n);
int i, div, temp, sum;
for (sum = 0, i = len-1; i >= 0; i--) {
div = (int) pow(10.0, (double)(len-i));
temp = n % div;
sum += temp;
sprintf(fmt, "%%0%dd+", len-i); /* make the format string for every term in the printf() bellow */
printf(fmt, temp);
}
printf("\b = %d\n", sum);
}
int main (void) {
int n;
printf("Enter an Integer >= 0:");
while (scanf("%d", &n) != EOF) {
sum1(n);
printf("%d\n", sum2(n)); /* catch the return value of sum2() */
sum3(n);
printf("\nEnter an Integer >= 0:");
}
return 0;
}
|
C
|
#include "ptuclib.h"
/* Program function_fun */
/* Type declaration: */
typedef int (*intfunc)(int n);
typedef char* string;
/* Variable declaration: */
/* Function declaration: */
int fibonacci(int n)
{
int result;
int f0, f1, temp;
f0 = 0;
f1 = 1;
while (n > 1)
{
temp = f1;
f1 = f1 + f0;
f0 = temp;
n = n - 1;
}
result = f1;
}
int factorial(int n)
{
int result;
int fac, i;
fac = 1;
for (i = n; i >= 1; i--) fac = i * fac;
result = fac;
return result;
}
void eval(string prompt, intfunc f, int val)
{
writeString(prompt);
writeString("(");
writeInteger(val);
writeString(")=");
writeInteger(f(val));
writeString("\n");
}
/* Main: */
int main() {
eval("Fibonacci",fibonacci,5);
eval("factorial",factorial,5);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <getopt.h> /* getopt_long() */
static void usage (FILE * fp, int argc, char ** argv);
static char * dev_name = NULL;
typedef enum {
IO_METHOD_READ,
IO_METHOD_MMAP,
IO_METHOD_USERPTR,
} io_method;
static io_method io= IO_METHOD_MMAP;
static const char short_options [] = "d:hmru";
static const struct option
long_options [] = {
{ "device", required_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{ "mmap", no_argument, NULL, 'm' },
{ "read", no_argument, NULL, 'r' },
{ "userp", no_argument, NULL, 'u' },
{ 0, 0, 0, 0 }
};
int main(int argc, char ** argv)
{
dev_name = "/dev/video";
for (;;) {
int index;
int c;
c = getopt_long (argc, argv,
short_options, long_options,
&index);
if (-1 == c) {
break;
}
switch (c) {
case 0: /* getopt_long() flag */
break;
case 'd':
dev_name = optarg;
break;
case 'h':
usage (stdout, argc, argv);
exit (EXIT_SUCCESS);
case 'm':
io = IO_METHOD_MMAP;
break;
case 'r':
io = IO_METHOD_READ;
break;
case 'u':
io = IO_METHOD_USERPTR;
break;
default:
usage (stderr, argc, argv);
exit (EXIT_FAILURE);
}
}
}
static void usage (FILE * fp, int argc, char ** argv)
{
fprintf (fp,
"Usage: %s [options]\n\n"
"Options:\n"
"-d | --device name Video device name [/dev/video]\n"
"-h | --help Print this message\n"
"-m | --mmap Use memory mapped buffers\n"
"-r | --read Use read() calls\n"
"-u | --userp Use application allocated buffers\n"
"",
argv[0]);
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct buffer {scalar_t__ offset; scalar_t__ len; scalar_t__ capacity; } ;
/* Variables and functions */
scalar_t__ buf_size_valid (int) ;
scalar_t__ buf_valid (struct buffer const*) ;
__attribute__((used)) static inline bool
buf_safe(const struct buffer *buf, int len)
{
return buf_valid(buf) && buf_size_valid(len)
&& buf->offset + buf->len + len <= buf->capacity;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** Created by Mackendy-Pierre Anselin on 25/02/2020.
** Email mackendy-pierre.anslin@epitech.eu.
** Copyright (c) 2020 TheExquisiteCrumpet. All rights reserved.
** strcspn.c description:
**
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int score1 = 0, score2 = 0, k = 0, sizen = 0, size = 0;
// initial Round1 strings
char player1[] = "geeks";
char play2[] = "";
printf("________________________________________\n\t[TEST STRCSPN]\n");
while (1) {
// generating random character
char randoml = 'a' + (random() % 26);
play2[k++] = randoml;
size = strcspn(play2, player1);
if (size == sizen) {
// if the character is present, break
score2 = size;
break;
}
else {
sizen = size;
}
}
// initial Round2 strings
const char player2[] = "geeks";
char play1[] = "";
k = 0, sizen = 0;
while (1) {
// generating random character
char randoml = 'a' + (random() % 26);
play1[k++] = randoml;
size = strcspn(play1, player2);
if (size == sizen) {
// if the character is present, break
score1 = size;
break;
}
else {
sizen = size;
}
}
if (score1 > score2)
printf("Player 1 won!! Score : %d", score1);
else if (score2 > score1)
printf("Player 2 won!! Score : %d", score2);
else
printf("Match Drawn!! Score : %d", score1);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
/* FizzBuzz VM: a VM for FizzBuzz
*
* Blame Nilium on #go-nuts for instigating this
*/
/* Each opcode is an unsigned short, which should correspond to at least 16 bits.
*
* Register machine version. The register machine has 8 registers and
* no main memory. Because we don't need main memory.
*
* Opcodes are decoded based on the instruction. The 3 LSBs indicate
* the opcode
* There are
* Opcodes are arranged as follows:
*
* LSB MSB
* Bit: 0123456789ABCDEF
* iiiaaaaaaaaaaaaa single argument, may be register or intermediate
* iiiaaabbbbbbbbbb two arguments, first is a register
* iiiaaabbbccccccc three arguments, first two are registers
*/
enum OPCODES {
OP_NOP = 0, /* NOP, remaining bits are unused (may be used for labels and such) */
OP_LOAD = 1, /* LOAD rD, imm rD = imm, imm must be between -512 and 511 */
OP_MOVE = 2, /* MOVE rD, rS rD = rS */
OP_ADD = 3, /* ADD rD, rA rD = rD + rS */
OP_MOD = 4, /* MOD rD, rA rD = rD % rA */
OP_CJMP = 5, /* CJMP rA, rel if rA == 0, jump relative by rel
nb: rel must be between -512 and 511 */
OP_PRINTCHAR = 6, /* PRINTCHAR imm if imm < 8, specifies register r1 - r16, and
the character in that register is printed.
Otherwise, the string constant at imm-16 is
printed */
OP_PRINTNUM = 7, /* PRINTNUM rA prints the numeric value in rA */
};
/* some convenience macros for encoding */
#define REG(rn) ((unsigned short)((rn-1) & 7))
#define OP(arg) ((unsigned short)(arg & 7))
#define IMM(arg) ((unsigned short)(arg & 0x1fff))
#define OP1(op,arg) ((unsigned short)(OP(op) | (IMM(arg) << 3)))
#define OP2(op,ra,arg) ((unsigned short)(OP(op) | (REG(ra) << 3) | (IMM(arg) << 6)))
#define OP3(op,ra,rb,arg) ((unsigned short)(OP(op) | (REG(ra) << 3) | (REG(rb) << 6) | (IMM(arg) << 9)))
#define LOAD(rdest, val) OP2(OP_LOAD, rdest, (val + 512))
#define MOVE(rdest, rsrc) OP2(OP_MOVE, rdest, REG(rsrc))
#define ADD(rdest, rsrc) OP2(OP_ADD, rdest, REG(rsrc))
#define MOD(rdest, rsrc) OP2(OP_MOD, rdest, REG(rsrc))
#define CJMP(rz,rel) OP2(OP_CJMP, rz, (rel+512))
#define PRINTSTR(s) OP1(OP_PRINTCHAR, (s+8))
#define PRINTCHAR(reg) OP1(OP_PRINTCHAR, REG(reg))
#define PRINTNUM(reg) OP1(OP_PRINTNUM, REG(reg))
static unsigned short fizzbuzz[] = {
/* start by loading constants */
LOAD(2, 1), /* 1 */
LOAD(3, 3), /* 2 */
LOAD(4, 5), /* 3 */
LOAD(5, 15), /* 4 */
LOAD(7, 0), /* 5 */
/* load counter */
LOAD(1,0), /* 6 */
/* lbl: loop0 */
ADD(1,2), /* 7 */
/* test for fizz+buzz */
MOVE(6,1), /* 8 */
MOD(6,5), /* 9 */
CJMP(6,9), /* 10 */
/* test for fizz */
MOVE(6,1), /* 11 */
MOD(6,3), /* 12 */
CJMP(6,8), /* 13 */
/* test for buzz */
MOVE(6,1), /* 14 */
MOD(6,4), /* 15 */
CJMP(6,7), /* 16 */
PRINTNUM(1), /* 17 */
CJMP(7, 6), /* 18 */
/* lbl: fizzbuzz */
PRINTSTR(0), /* 19 */
CJMP(7, 4), /* 20 */
/* lbl: fizz */
PRINTSTR(1), /* 21 */
CJMP(7, 2), /* 22 */
/* lbl: buzz */
PRINTSTR(2), /* 23 */
/* fall through */
/* lbl: loop1 */
LOAD(6, '\n'), /* 24 */
PRINTCHAR(6), /* 25 */
LOAD(6, -100), /* 26 */
ADD(6,1), /* 27 */
CJMP(6, 3), /* 28 */
LOAD(6, 0), /* 29 */
CJMP(6, -23), /* 30 */
LOAD(1, 0), /* 31 */
/* STOP */
};
const char *strings[] = {
"FizzBuzz",
"Fizz",
"Buzz"
};
int runvm(unsigned short *instr, size_t num_instr, const char *strings[], size_t num_strings)
{
size_t i;
int reg[8] = { 0 };
i = 0;
restart:
for(; i < num_instr; i++) {
int ci, op, r1, r2, arg;
ci = instr[i];
op = ci & 0x7;
/*
fprintf(stderr, "[%3zu] %2x 0x%4x\n", i, op, ci >> 3);
fprintf(stderr, "registers:\n");
for (int j=0; j < 8; j++) {
fprintf(stderr, " r%1d %d\n", j+1, reg[j]);
}
{
char buf[256];
fgets(buf, sizeof buf, stdin);
}
*/
switch (op)
{
case OP_NOP:
break;
case OP_LOAD:
r1 = (ci >> 3) & 0x7;
arg = (ci >> 6) - 512;
reg[r1] = arg;
break;
case OP_MOVE:
r1 = (ci >> 3) & 0x7;
r2 = (ci >> 6) & 0x7;
reg[r1] = reg[r2];
break;
case OP_ADD:
r1 = (ci >> 3) & 0x7;
r2 = (ci >> 6) & 0x7;
reg[r1] += reg[r2];
break;
case OP_MOD:
r1 = (ci >> 3) & 0x7;
r2 = (ci >> 6) & 0x7;
reg[r1] = reg[r1] % reg[r2];
break;
case OP_CJMP:
r1 = (ci >> 3) & 0x7;
arg = (ci >> 6) - 512;
if (reg[r1] == 0) {
i += arg;
goto restart;
}
break;
case OP_PRINTCHAR:
arg = ci >> 3;
if (arg < 8) {
putchar(reg[arg]);
} else {
arg -= 8;
assert(arg >= 0 && (size_t)arg < num_strings);
fputs(strings[arg],stdout);
}
break;
case OP_PRINTNUM:
arg = (ci >> 3) & 0x7;
printf("%d",reg[arg]);
break;
default:
fprintf(stderr, "unknown opcode, aborting.\n");
abort();
}
}
return reg[0];
}
int main(void)
{
return runvm(fizzbuzz, sizeof fizzbuzz / sizeof fizzbuzz[0], strings, sizeof strings / sizeof strings[0]);
}
|
C
|
/* routine to convert an string array to a int array */
#include <stdio.h>
void string_to_int(char *p_ichar2, int *p_ichar1, int max_position )
{
int iloop;
while ( *p_ichar2 != '\0' && iloop < max_position )
{
*p_ichar1= *p_ichar2;
p_ichar1++;
p_ichar2++;
iloop++;
}
return;
}
|
C
|
#ifndef NODES_H
#define NODES_H
#include "../utils/utils.h"
// calls exec with the needed arguments to execute Splitter/Merger node's job
void execSplitterMergerNodeJob(char* dataFileName, unsigned int searchRangeStart, unsigned int searchRangeEnd, char* searchPattern, unsigned int remainingTreeDepth,
char* childPipeName, char isFirstSplitterMerger, char skewFlag, unsigned int recordsNum, unsigned int leafsNum,
unsigned int leafIndexRangeStart, unsigned int leafIndexRangeEnd, int rootPid);
// calls exec with the needed arguments to execute Leaf node's job
void execLeafNodeJob(char* dataFileName, unsigned int searchRangeStart, unsigned int searchRangeEnd, char* searchPattern, char* childPipeName,
char skewFlag, unsigned int leafIndex, unsigned int recordsNum, unsigned int leafsNum, int rootPid);
// does Leaf node's job
// searchRangeStart and searchRangeEnd are used only if skewFlag = 0
// if skewFlag = 1: leafIndex, recordsNum and leafsNum are used to calculate the search range of the current Leaf node
void leafNodeJob(char* dataFileName, unsigned int searchRangeStart, unsigned int searchRangeEnd, char* searchPattern, char* parentPipeName,
char skewFlag, unsigned int leafIndex, unsigned int recordsNum, unsigned int leafsNum, int rootPid);
// does Splitter/Merger node's job
// searchRangeStart and searchRangeEnd are used only if skewFlag = 0
// if skewFlag = 1: leafIndexRangeStart and leafIndexRangeEnd are handled to be passed to children in order for the Leaf nodes to know which index they have in the tree
// rootPid: pid of Root node
char splitterMergerNodeJob(char* dataFileName, unsigned int searchRangeStart, unsigned int searchRangeEnd, char* searchPattern,
unsigned int remainingTreeDepth, char* parentPipeName, char isFirstSplitterMerger, char skewFlag,
unsigned int recordsNum, unsigned int leafsNum, unsigned int leafIndexRangeStart, unsigned int leafIndexRangeEnd, int rootPid);
// does Sort node's job
void sortNodeJob();
// does Root node's job
char rootNodeJob(unsigned int height, char* dataFileName, char* searchPattern, char skewFlag);
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.