language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | #include <types.h>
#include <lib.h>
#include <synchprobs.h>
#include <synch.h>
/*
* This simple default synchronization mechanism allows only creature at a time to
* eat. The globalCatMouseSem is used as a a lock. We use a semaphore
* rather than a lock so that this code will work even before locks are implemented.
*/
/*
* Replace this default synchronization mechanism with your own (better) mechanism
* needed for your solution. Your mechanism may use any of the available synchronzation
* primitives, e.g., semaphores, locks, condition variables. You are also free to
* declare other global variables if your solution requires them.
*/
/*
* replace this with declarations of any synchronization and other variables you need here
*/
//static struct semaphore *globalsem;
static struct lock *globallock;
static struct lock **bowllocks;
static struct cv *cat_cv;
static struct cv *mouse_cv;
static volatile int num_mice_eating;
static volatile int num_cats_eating;
static volatile int num_mice_waiting;
static volatile int num_cats_waiting;
volatile bool debug = false;
/*
* The CatMouse simulation will call this function once before any cat or
* mouse tries to each.
*
* You can use it to initialize synchronization and other variables.
*
* parameters: the number of bowls
*/
void
catmouse_sync_init(int bowls)
{
/* replace this default implementation with your own implementation of catmouse_sync_init */
globallock= lock_create("globalLock");
//globalsem = sem_create("globalCatMouseSem",1);
//malloc n* locks for bowllocks[]
bowllocks = kmalloc(bowls * sizeof(struct lock *));
for (int i=0; i<bowls; i++) {
bowllocks[i] = lock_create("bowl lock");
if (bowllocks[i] == NULL ){
for (int j =0; j<i; j++) {
lock_destroy(bowllocks[j]);
}
kfree(bowllocks);
lock_destroy(globallock);
kprintf("lock %d failed ", i);
KASSERT(false);
}
}
cat_cv = cv_create("cats_still_eating");
mouse_cv = cv_create("mice_still_eating");
num_cats_eating=0;
num_mice_eating=0;
num_mice_waiting=0;
num_cats_waiting=0;
return;
}
/*
* The CatMouse simulation will call this function once after all cat
* and mouse simulations are finished.
*
* You can use it to clean up any synchronization and other variables.
*
* parameters: the number of bowls
*/
void
catmouse_sync_cleanup(int bowls)
{
lock_destroy(globallock);
for (int i=0; i<bowls; i++) {
lock_destroy(bowllocks[i]);
}
kfree(bowllocks);
cv_destroy(cat_cv);
cv_destroy(mouse_cv);
//sem_destroy(globalsem);
}
/*
* The CatMouse simulation will call this function each time a cat wants
* to eat, before it eats.
* This function should cause the calling thread (a cat simulation thread)
* to block until it is OK for a cat to eat at the specified bowl.
*
* parameter: the number of the bowl at which the cat is trying to eat
* legal bowl numbers are 1..NumBowls
*
* return value: none
*/
void
cat_before_eating(unsigned int bowl)
{
if (debug) {kprintf("numcats: %d nummice: %d cat before tries lock_acq(g) \n", num_cats_eating, num_mice_eating);}
if (lock_do_i_hold(globallock)) {if (debug) {kprintf("cat before has its own glock-------------\n");}}
lock_acquire(globallock);
if (debug) {kprintf("cat before glock acquired\n");} //-------------------------------------
//check if there are mice eating || more mice waiting
while (num_mice_eating /*|| (num_mice_waiting> num_cats_eating)*/){
if (debug) {kprintf("cat before enters wait, mice waiting:%d cats eating%d\n", num_mice_waiting, num_cats_eating);}
num_cats_waiting++;
cv_wait(cat_cv,globallock);
num_cats_waiting--;
}
//go eat
num_cats_eating++;
lock_release(globallock);
lock_acquire(bowllocks[bowl-1]);
//V(globalsem);
if (debug) {kprintf("cat before: glock will be released\n");} //-------------------------------------
}
/*
* The CatMouse simulation will call this function each time a cat finishes
* eating.
*
* You can use this function to wake up other creatures that may have been
* waiting to eat until this cat finished.
*
* parameter: the number of the bowl at which the cat is finishing eating.
* legal bowl numbers are 1..NumBowls
*
* return value: none
*/
void
cat_after_eating(unsigned int bowl)
{
if (debug) {kprintf("numcats: %d nummice: %d cat after tries lock_acq(g) \n", num_cats_eating, num_mice_eating);}
if (lock_do_i_hold(globallock)) {if (debug) {kprintf("cat after has its own glock-------------\n");}}
lock_acquire(globallock);
if (debug) {kprintf("cat after glock acquired lk holder: \n");} //-------------------------------------
lock_release(bowllocks[bowl-1]);
num_cats_eating--;
if (!num_cats_eating) {
//let all mice eat
cv_broadcast(mouse_cv,globallock);
}
if (debug) {kprintf("cat after: glock will be released\n");} //-------------------------------------
lock_release(globallock);
}
/*
* The CatMouse simulation will call this function each time a mouse wants
* to eat, before it eats.
* This function should cause the calling thread (a mouse simulation thread)
* to block until it is OK for a mouse to eat at the specified bowl.
*
* parameter: the number of the bowl at which the mouse is trying to eat
* legal bowl numbers are 1..NumBowls
*
* return value: none
*/
void
mouse_before_eating(unsigned int bowl)
{
if (debug) {kprintf("numcats: %d nummice: %d mouse before tries lock_acq(g) \n", num_cats_eating, num_mice_eating);}
if (lock_do_i_hold(globallock)) {if (debug) {kprintf("mouse before has its own glock-------------\n");}}
lock_acquire(globallock);
if (debug) {kprintf("mouse before glock acquired\n");} //-------------------------------------
//check if there are cats eating
while (num_cats_eating /*|| (num_cats_waiting> num_mice_eating)*/){
if (debug) {kprintf("mouse before enters wait, cats waiting:%d mice eating%d\n", num_cats_waiting, num_mice_eating);}
num_mice_waiting++;
cv_wait(mouse_cv,globallock);
num_mice_waiting--;
}
//go eat
if (debug) {kprintf("numcats: %d nummice: %d mouse tries to acquired block after \n", num_cats_eating, num_mice_eating);}
//P(globalsem);
//if (debug){kprintf("semaphore entered \n");}
num_mice_eating++;
lock_release(globallock);
lock_acquire(bowllocks[bowl-1]);
//V(globalsem);
}
/*
* The CatMouse simulation will call this function each time a mouse finishes
* eating.
*
* You can use this function to wake up other creatures that may have been
* waiting to eat until this mouse finished.
*
* parameter: the number of the bowl at which the mouse is finishing eating.
* legal bowl numbers are 1..NumBowls
*
* return value: none
*/
void
mouse_after_eating(unsigned int bowl)
{
if (debug) {kprintf("numcats: %d nummice: %d mouse after tries lock_acq(g) \n", num_cats_eating, num_mice_eating);}
if (lock_do_i_hold(globallock)) {if (debug) {kprintf("mouse after has its own glock-------------\n");}}
lock_acquire(globallock);
if (debug) {kprintf("mouse after glock acquired\n");} //-------------------------------------
num_mice_eating--;
lock_release(bowllocks[bowl-1]);
if (!num_mice_eating ) {
//let all cats eat
cv_broadcast(cat_cv,globallock);
}
if (debug) {kprintf("mouse after: glock released\n");} //-------------------------------------
lock_release(globallock);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <stdbool.h>
#define BACKGROUND 39
#define BACKGROUNDRED 36
#define RED 4
#define WHITE 7
typedef enum months
{JANUARY = 0, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER};
char *rus (char *p)
{
static char txt[1024];
CharToOemA (p, txt);
return txt;
}
void gotoxy (int x, int y)
{
COORD position = {x, y}; //позиция x и y
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hConsole, position);
}
void setcolor (int i)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(handle, i);
}
void print_calendar (int month, int year, int horizontal, int vertical);
void pasha_p (int year, bool flag);
void clear_PashaWhitDay (int month1, int dayPasha, int month2, int dayWhitSunday);
char *name[] = {"Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"};
int days_month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool isDayCelebrate;
//1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
int *celebrateDays[12][31] = { {1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Январь
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Февраль
{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Март
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Апрель
{1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Май
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, // Июнь
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Июль
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0}, // Август
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Сентябрь
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Октябрь
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Ноябрь
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} // Декабрь
};
/******************************************************************/
int main()
{
int i, y, month, year, horizontal, vertical;
bool flag;
char str[1024];
// Размер окна
system ("mode 70, 50");
for (;;)
{
flag = false; // Флаг начала цикла
printf (rus ("Введите год: "));
year = gets(str);
year = atoi(str);
if (year < 1582 || year > 9999)
{
printf(rus ("Введите год от 1583 до 9999\n"));
system("pause");
system ("cls");
continue;
}
horizontal = 1;
vertical = 2;
month = FEBRUARY;
pasha_p (year, flag);
// Выводим на экран календарь с 3 месяцами в строке и 4 столбцами
for (i = 1; i <= 4; ++i)
{
// Выводим 3 месяца в строку
for (y = 1; y <= 3; ++y)
{
print_calendar (month, year, horizontal, vertical);
++month;
horizontal += 23;
}
// Переходим на новую строку печати 3 месяцев
horizontal = 1;
vertical += 9;
}
gotoxy (1, 38);
printf(rus("* 1 января - Новый год\n"));
printf(rus(" * 7 января - Рождество Христово\n"));
if (year >= 1975)
printf(rus(" * 8 марта - Международный женский день\n"));
if (year >= 1890)
printf(rus(" * 1 мая - День трудящихся\n"));
if (year > 1944)
printf(rus(" * 9 мая - День Победы\n"));
if (year > 1990)
{
printf(rus(" * 28 июня - День Конституции Украины\n"));
printf(rus(" * 24 августа - День независимости Украины\n"));
printf(rus(" * 14 октября - День защитника Украины\n"));
}
flag = true; // Флаг конца цикла
pasha_p(year, flag); // Передаем функции флаг конца цикла и сбрасываем дату Пасхи и Троицы
gotoxy (1, 48);
system ("pause");
system ("cls");
}
return 0;
}
/*****************************************************************************/
void print_calendar (int month, int year, int horizontal, int vertical)
{
int i, y, firstDayOfMonth, tempDay, temp1, day;
day = 1;
// Определяем високосный год ((year%4 == 0 and year%100 != 0) or (year%400 == 0))
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
days_month[FEBRUARY] = 29;
else
days_month[FEBRUARY] = 28;
if (month <= 2)
{
--year;
day += 3;
}
// В какой день начинается месяц
firstDayOfMonth = (day + year + year / 4 - year / 100 + year / 400 + (31 * month + 10) / 12) % 7;
// Печатаем "шапку" над каждым месяцем
gotoxy (horizontal, vertical);
++vertical;
printf (" ");
printf (rus (name[month - 1]));
gotoxy (horizontal, vertical);
++vertical;
printf (rus (" Пн Вт Ср Чт Пт Сб Вс\n"));
gotoxy (horizontal, vertical);
// Печатаем количество пробелов в зависимости от дня начала месяца
for (i = 1; i <= firstDayOfMonth; ++i)
printf(" ");
// Печатаем календарь на месяц
for (i = 1; i <= days_month[month - 1]; ++i)
{
temp1 = i;
if (month <= 2)
{
temp1 += 3;
tempDay = (temp1 + year + year / 4 - year / 100 + year / 400 + (31 * month + 10) / 12) % 7;
}
else
tempDay = (temp1 + year + year / 4 - year / 100 + year / 400 + (31 * month + 10) / 12) % 7;
// Если день праздничный в субботу или воскресенье, то подсвечиваем их
if (celebrateDays[month - 1][i - 1] == 1 && (tempDay == 5 || tempDay == 6))
{
setcolor(BACKGROUNDRED);
printf ("%3d", i);
}
// Если день суббота или воскресенье, то подсвечиваем под ними фон
else if (tempDay == 5 || tempDay == 6)
{
setcolor(BACKGROUND);
printf ("%3d", i);
}
// Если день праздничный, то выделяем его красным иначе белым
else if (celebrateDays[month - 1][i - 1] == 1)
{
setcolor(RED);
printf ("%3d", i);
}
else
{
setcolor(WHITE);
printf ("%3d", i);
}
//Переход на новую строку
if ((i + firstDayOfMonth) % 7 == 0)
gotoxy (horizontal, ++vertical);
}
setcolor(WHITE);
}
/*****************************************************************************/
void pasha_p (int year, bool flag)
{
int a, b, c, d, e;
int dayOfPasha, temp2;
// День Святой Троицы (англ. Whit Sunday)
int whitSundayDay;
int tempMonth;
// Определяем дату Пасхи
a = year % 19;
b = year % 4;
c = year % 7;
d = (19 * a + 15) % 30;
e = (2 * b + 4 * c + 6 * d + 6) % 7;
dayOfPasha = (d + e - 9) - 1;
/* ---- Записываем даты Пасхи и Троицы в массив ---- */
// Если Пасха в маю
if (dayOfPasha + 13 > 29)
{
if (flag == 0 && celebrateDays[MAY][dayOfPasha + 13 - 30] == 1)
isDayCelebrate = true;
else if (flag == 0 && celebrateDays[MAY][dayOfPasha + 13 - 30] == 0)
{
isDayCelebrate = false;
celebrateDays[MAY][dayOfPasha + 13 - 30] = 1;
}
// Определяем дату Троицы и зацисываем ее в массив
whitSundayDay = dayOfPasha + 13 - 30 + 50 - days_month[MAY];
celebrateDays[JUNE][whitSundayDay - 1] = 1;
}
// Если Пасха в апреле
else
{
if (flag == false && celebrateDays[APRIL][dayOfPasha + 13] == 1)
isDayCelebrate = true;
else if (flag == false && celebrateDays[APRIL][dayOfPasha + 13] == 0)
{
isDayCelebrate = false;
celebrateDays[APRIL][dayOfPasha + 13] = 1;
}
whitSundayDay = dayOfPasha + 13 + 50 - days_month[APRIL];
if (whitSundayDay > 31) // Если получили день троицы больше чем 31
{
tempMonth = JUNE; // Сохраним значения месяца чтобы потом сбросить его в 0
whitSundayDay = whitSundayDay - 31;
celebrateDays[JUNE][whitSundayDay - 1] = 1;
//if(flag == )
}
else
{
tempMonth = MAY;
celebrateDays[MAY][whitSundayDay - 1] = 1;
}
}
// Выводим даты празднования Пасхи и Троицы, затем сбрасываем даты в массиве
if (flag == true && dayOfPasha + 13 > 29) // Май
{
gotoxy(45, 38);
printf(rus(" * %d мая - Пасха\n"), dayOfPasha + 13 - 30 + 1);
gotoxy(45, 39);
printf(rus(" * %d июня - Троица"), whitSundayDay);
if (isDayCelebrate == false)
celebrateDays[MAY][dayOfPasha + 13 - 30] = 0;
celebrateDays[JUNE][whitSundayDay - 1] = 0;
}
else if (flag == true && dayOfPasha + 13 <= 29) // Апрель
{
gotoxy(45, 38);
printf(rus("* %d апреля - Пасха\n"), dayOfPasha + 13 + 1);
gotoxy(45, 39);
if (tempMonth == MAY)
{
if (dayOfPasha + 13 + 1 < 10)
printf(rus("* %2d мая - Троица"), whitSundayDay);
else
printf(rus("* %2d мая - Троица"), whitSundayDay);
}
if (tempMonth == JUNE)
printf(rus("* %2d июня - Троица"), whitSundayDay);
else
printf(rus("* %2d июня - Троица"), whitSundayDay);
if (!isDayCelebrate)
celebrateDays[APRIL][dayOfPasha + 13] = 0;
}
celebrateDays[tempMonth][whitSundayDay - 1] = 0;
}
/*****************************************************************************/
void clear_PashaWhitDay (int monthOfPasha, int _dayOfPasha, int monthOfWhitSunday, int _whitSundayDay)
{
if (monthOfPasha == MAY)
{
celebrateDays[MAY][_dayOfPasha + 13 - 30] = 0;
celebrateDays[JUNE][_whitSundayDay - 1] = 0;
}
else
celebrateDays[APRIL][_dayOfPasha + 13] = 0;
celebrateDays[monthOfWhitSunday][_whitSundayDay - 1] = 0;
}
|
C | /*
vector的删除和添加操作
*/
void moveZeroes(vector<int>& nums) {
if (nums.size() == 0)
{
return;
}
int i = 0;
int count=0;
while (true)
{
if (count == nums.size())
{
return;
}
if (nums[i] == 0)
{
nums.erase(nums.begin() + i);
nums.push_back(0);
i--;
}
i++;
count++;
}
} |
C | // compile with -std=c99
// reused code from 1-17 because i didn't feel like rewriting getline
// ignore the whitespace, it's there so you can simply "./a.out < kushblazingjudah.c"
#include <stdio.h>
#define MAXLINE 1000
int getline(char line[], int maxline);
int main() {
int len;
char line[MAXLINE];
while ((len = getline(line, MAXLINE)) > 0) {
// read backwards
for (int i = len; i >= 0; --i) {
if (line[i] == ' ' || line[i] == '\t' || (line[i] == '\n' && i == 0)) {
// i hate this so much
if (i > 0) {
line[i] = '\n';
line[i + 1] = 0;
} else
line[i] = 0;
} else if (line[i] == '\0' || line[i] == '\n')
continue;
else
break;
}
printf("%s", line);
}
return 0;
}
int getline(char s[], int lim) {
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = 0;
return i;
}
|
C | #include<stdio.h>
int main() {
float x1 = 23.4000;
float x2 = 43.2300;
float x3 = 32.2200;
float x4 = 68.2100;
float x5 = 9.8000;
float *ptr1 = &x1;
float *ptr2 = &x2;
float *ptr3 = &x3;
float *ptr4 = &x4;
float *ptr5 = &x5;
float* arr1[5] = {ptr1,ptr2,ptr3,ptr4,ptr5};
printf("Output=\n");
for(int itr=0; itr<5; itr++){
printf("Element %d = %f\n",itr,*(*(arr1 + itr)));
}
printf("\n");
float max = 0.0;
int index;
for(int itr=0; itr<5; itr++){
if(*(*(arr1 + itr)) > max){
max = *(*(arr1 + itr));
index = itr;
}
}
printf("Biggest value is %f and its index is %d\n",max,index);
printf("\n");
}
/*
Output=
Element 0 = 23.400000
Element 1 = 43.230000
Element 2 = 32.220001
Element 3 = 68.209999
Element 4 = 9.800000
Biggest value is 68.209999 and its index is 3
*/
|
C | #include <stdio.h>
inline int read ()
{
char c;
int n = 0;
while ((c = getchar_unlocked ()) < 48);
n += (c - '0');
while ((c = getchar_unlocked ()) >= 48)
n = n * 10 + (c - '0');
return n;
}
int main (void)
{
int t = read ();
while (t--)
{
int n = read (), i, count[8];
for (i = 0; i < 8; i++)
count[i] = 0;
char toss[50], l, pl;
scanf ("%s", toss);
pl = toss[0];
l = toss[1];
i = 2;
while (toss[i])
{
if (pl == 'T' && l == 'T' && toss[i] == 'T')
count[0]++;
else if (pl == 'T' && l == 'T' && toss[i] == 'H')
count[1]++;
else if (pl == 'T' && l == 'H' && toss[i] == 'T')
count[2]++;
else if (pl == 'T' && l == 'H' && toss[i] == 'H')
count[3]++;
else if (pl == 'H' && l == 'T' && toss[i] == 'T')
count[4]++;
else if (pl == 'H' && l == 'T' && toss[i] == 'H')
count[5]++;
else if (pl == 'H' && l == 'H' && toss[i] == 'T')
count[6]++;
else if (pl == 'H' && l == 'H' && toss[i] == 'H')
count[7]++;
pl = l;
l = toss[i];
i++;
}
printf ("%d ", n);
for (i = 0; i < 8; i++)
printf ("%d ", count[i]);
printf ("\n");
}
return 0;
} |
C | #include<stdio.h>
#include<ctype.h>
#include<string.h>
main()
{
int ncase,i,j,len;
float point,prob;
char temp[200];
//freopen("in.txt","r",stdin);
scanf("%d\n",&ncase);
while(ncase--)
{
scanf("\n");
gets(temp);
len=strlen(temp);
point=0;
for(i=0; i<len; i++)
{
if(isdigit(temp[i]))
point+=(temp[i]-'0');
else if(isalpha(temp[i]))
{
if(temp[i]=='A')
point+=1;
else
point+=0.5;
}
}
//printf("%.0f\n",point);
if(point>10.5)
prob=-1;
else if((10.5-point)>=0.5)
prob=100-(float)(((int)(10.5-point)+3))/13*100;
else
prob=100-(float)(((int)(10.5-point))/13*100);
printf("%.0f\n",prob);
}
}
|
C | #include <stdio.h>
#include <math.h>
int main(){
float a,b,c,d;
printf("enter the values of a,b,c for eqn a*x*x+b*x+c=0:");
scanf("%f %f %f",&a,&b,&c);
d=(b*b)-(4*a*c);
printf("\n value of d is %f",d);
if(d>0)
printf("\nroots of eqn are %f %f",(-b+sqrt(d))/(2*a),(-b-sqrt(d))/(2*a));
else if(d=0)
printf("\nroot of eqn is %f",-b/(2*a));
else{
printf("\nroots are imaginary");
printf("\n roots are %f+i%f %f+i%f",-b/2*a,-sqrt(-d)/(2*a),-b/2*a,sqrt(-d)/(2*a));
}
}
|
C | //Write a program to find the volume of a tromboloid using one function
#include<stdio.h>
Void main()
{
Int h,b,d,vol;
Printf(" enter hight,breadth,deapth of tromboloid");
Scanf("%d%d%d,&h,&b,&d);
Vol = *(h*d*b) + (d/b))/3;
Printf(%d*%d*%d+%d/%d)/3 = %d h,d,b,d,b,vol);
}
|
C | /*******************************************************************************
eex_timer.h - Real time executive Timer.
COPYRIGHT NOTICE: (c) ee-quipment.com
All Rights Reserved
******************************************************************************/
#ifndef _eex_timer_H_
#define _eex_timer_H_
#include <stdint.h>
#include "eex_os.h"
// Static allocator for timer.
// 'name' must not be in quotes. i.e. EEX_TIMER_NEW(myTimer) not EEX_TIMER_NEW("myTimer")
#define EEX_TIMER_NEW(name, fn_timer, argument, interval)
typedef void (*eex_timer_fn_t) (void * const argument);
typedef struct eex_timer_cb_t {
eex_timer_fn_t fn_timer; // start address of timer function
void *arg; // timer function argument
const char *name; // timer name
uint32_t control; // timer control and status bit field
uint32_t interval; // ms between periodic calls to fn_timer
uint32_t remaining; // ms remaining to expiry when timer stopped
uint32_t expiry; // kernel time when timer expires
struct eex_timer_cb_t *next; // next timer in linked list
} eex_timer_cb_t;
typedef enum {
eexTimerActive = 0x00000001, // timer has been added to list of active timers
eexTimerRunning = 0x00000002, // timer is running
} eex_timer_status_t;
/*
* On start, timer will fire the first timer after delay, then periodically at interval.
* If timer->interval = 0, timer is a one-shot. A one-shot timer is still active
* and may be rerun by calling eexTimerStart() again.
*
* To reset a timer, (e.g. a watchdog) call eexTimerStart() on an already running
* timer. It will be restarted using the new delay value.
*/
void eexTimerAdd(eex_timer_cb_t * timer);
void eexTimerRemove(eex_timer_cb_t * timer);
void eexTimerStart(eex_timer_cb_t* timer, uint32_t delay);
void eexTimerStop(eex_timer_cb_t * timer);
void eexTimerResume(eex_timer_cb_t * timer);
eex_timer_status_t eexTimerStatus(eex_timer_cb_t * timer);
#undef EEX_TIMER_NEW
#define EEX_TIMER_NEW(name, fn_timer, argument, interval) \
static eex_timer_cb_t name##_storage = { fn_timer, argument, #name, 0, interval, 0, 0, 0 }; \
static eex_timer_cb_t * const name = &name##_storage
#endif /* _eex_timer_H_ */
|
C | // CITS2002 Project 2 2020
// Name(s): Harry Carpenter, My Inner Conscience
// Student number(s): 22723303, ---
#include "mergetars.h"
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <stdbool.h>
#include "sysbin.h"
// I suppose we're assuming that the user IS passing through valid .tar files.
// The program will throw if it's not able to be unzipped via tar command, so that's the "safeguard"
// if you could call it that.
// ------------------------- in line defs ------------------------ //
// int create_output_tar(char * temp_directory, char * output_file);
// int compare_files(char *temp_directory, int tarc);
// -----------------------end in line defs ----------------------- //
/**
* Merge some TAR files
* @param argc
* @param argv
* @return
*/
int main(int argc, char *argv[]){
if(argc == 1){
printf("You have not provided any input criteria, aborting\n");
exit(0);
} else if( argc == 2) {
printf("You need to provide both input and output files\n");
exit(0);
}
char *tar_array[argc];
int tarc = 0;
for(int i = 1; i < argc-1; i++){
tar_array[i-1] = argv[i];
printf("->%s\n", tar_array[tarc]);
tarc++;
}
// construct the temporary directory
char template[] = "/tmp/tmpdir.XXXXXX";
char *temp_dir = mkdtemp((char *) &template);
// if the temp creation fails, drop everything and exit.
if(temp_dir == NULL){ perror("mkdtemp failed: "); exit( 0); }
//expand the tar files into the temp directory
expand_tars(tarc, tar_array, temp_dir);
// compare the extracted files for the merge
// this will copy and valid files into a working _out directory within the temp folder.
// this is so we can easily compartmentalise and work with duplicate files, because we
// don't want to override anything, yet.
if(comparefiles(tarc, temp_dir) != 0) {
perror("something went wrong!");
exit(121);
}
int create_result = create_output_tar(temp_dir, argv[argc-1]);
//create the defined output tar, throw error if failed
if(create_result != 0){
printf("ERROR: Failed to create output TAR file\n");
exit(122);
}
if(cleanup(temp_dir) != 0){
perror("core finished successfully, but temp cleanup failed");
return 0;
}
return 0;
}
|
C | #include <stdio.h>
int main () {
int sum = 0;
int start = 1;
int end = 10000;
int max = 555;
for( int i = start; i < end; i++)
{
sum = sum + i;
if (sum > max)
{
printf("with max. sum %d, the sum from %d to %d is equal to %d", max, start, i, sum );
break;
}
}
//printf("The sum from %d to %d is equal to %d\n", start, end, sum);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char* addBinary(char* a, char* b)
{
int len1 = strlen(a);
int len2 = strlen(b);
int len = len1 > len2 ? len1 + 1 : len2 + 1;
char *result = malloc(len + 1);
result[len] = '\0';
result[len - 1] = '\0';
int i, j, carry = 0;
len = 0;
for (i = len1 - 1, j = len2 - 1; carry || i >= 0 || j >= 0; i--, j--) {
int na = i >= 0 ? a[i] - '0' : 0;
int nb = j >= 0 ? b[j] - '0' : 0;
result[len++] = (na ^ nb ^ carry) + '0';
carry = carry + na + nb >= 2 ? 1 : 0;
}
for (i = 0, j = len - 1; i < j; i++, j--) {
char c = result[i];
result[i] = result[j];
result[j] = c;
}
return result;
}
int main(int argc, char **argv)
{
if (argc != 3) {
fprintf(stderr, "Usage: ./test s1 s2\n");
exit(-1);
}
printf("%s\n", addBinary(argv[1], argv[2]));
return 0;
}
|
C | extern void outc( char c );
void
main() {
for (char* p = "Hello world!\n"; *p;)
outc( *p++ );
} |
C | #include "PyGuiBindings.h"
#include "DataTypes.h"
#include "MidiDefinitions.h"
#include "USB.h"
#include "Target_Emulator.h"
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct _midiMap{
int pin;
int command;
int channel;
int value;
} midiMap;
void Sleep_ms(unsigned int milliSeconds)
{
struct timespec req = {0};
time_t seconds = (int) (milliSeconds / 1000);
milliSeconds = milliSeconds - (seconds * 1000);
req.tv_sec = seconds;
req.tv_nsec = milliSeconds * 1000000L;
while (nanosleep(&req, &req) == -1)
continue;
}
// Initial value for the analogue pins
int analogue_pin_definitions[NUM_ANALOGUE_PINS] = {ANALOGUE_1, ANALOGUE_2, ANALOGUE_3, ANALOGUE_4,
ANALOGUE_5, ANALOGUE_6, ANALOGUE_7, ANALOGUE_8};
int analogue_command_definitions = CC_CHANGE;
int analogue_channel_definitions[NUM_ANALOGUE_PINS] = {CC_CHANNEL_1, CC_CHANNEL_2, CC_CHANNEL_3, CC_CHANNEL_4,
CC_CHANNEL_5, CC_CHANNEL_6, CC_CHANNEL_7, CC_CHANNEL_8};
int analogue_value_definitions = 0;
// Initial value for the digital pins
int digital_pin_definitions[NUM_DIGITAL_PINS] = {DIGITAL_1, DIGITAL_2, DIGITAL_3, DIGITAL_4,
DIGITAL_5, DIGITAL_6, DIGITAL_7, DIGITAL_8};
int digital_on_command_definitions = CHAN_1_NOTE_ON;
int digital_off_command_definitions = CHAN_1_NOTE_OFF;
int digital_channel_definitions[NUM_DIGITAL_PINS] = {36, 37, 38, 39, 40, 41, 42, 43};
int digital_value_definitions = 0;
int main(void){
// create some pins
midiMap analogue_pins[NUM_ANALOGUE_PINS];
midiMap digital_pins[NUM_DIGITAL_PINS];
int value;
// init pins
int i;
for(i = 0; i < NUM_DIGITAL_PINS; i++){
digital_pins[i].pin = digital_pin_definitions[i];
digital_pins[i].command = 0;
digital_pins[i].channel = digital_channel_definitions[i];
digital_pins[i].value = digital_value_definitions;
}
for(i = 0; i < NUM_ANALOGUE_PINS; i++){
analogue_pins[i].pin = analogue_pin_definitions[i];
analogue_pins[i].command = analogue_command_definitions;
analogue_pins[i].channel = analogue_channel_definitions[i];
analogue_pins[i].value = analogue_value_definitions;
}
// Init the GUI and USB
PyGuiBindings_initConnection();
USB_init();
while(1){
// Update the values
PyGuiBindings_update();
for(i = 0; i < NUM_DIGITAL_PINS; i++){
value = PyGuiBindings_getDigital(digital_pins[i].pin);
// If the value doesnt match the current one
if (value != digital_pins[i].value){
printf("Digital %i changed to %i\n",(i+1), value );
// If the pin is not high send a midi on message
if (value > 0){
digital_pins[i].value = 1;
}
// Otherwise send a midi low message
else{
digital_pins[i].value = 0;
}
USB_sendMidiMessage(digital_on_command_definitions, digital_pins[i].channel, 127);
Sleep_ms(10);
USB_sendMidiMessage(digital_off_command_definitions, digital_pins[i].channel, 127);
}
}
for(i = 0; i < NUM_ANALOGUE_PINS; i++){
value = PyGuiBindings_getAnalogue(analogue_pins[i].pin);
// If the value doesnt match the current one
if (value != analogue_pins[i].value){
printf("Analogue %i changed to %i\n",(i+1), value);
// Save the new value and send a midi message
analogue_pins[i].value = value;
USB_sendMidiMessage(analogue_pins[i].command, analogue_pins[i].channel, analogue_pins[i].value);
}
}
// Sleep for 100ms
Sleep_ms(100);
}
return 0;
} |
C | #include<stdio.h>
int main()
{
int n;
printf("Please input an integer");
scanf("%d",&n);
printf("The result is:\n");
for(int i=1;i<=n;i++) //ӡϰ벿Ǻ
{
for(int j=1;j<=n-i;j++)
printf(" ");
for(int j=1;j<=2*i-1;j++)
printf("*");
printf("\n");
}
for(int i=n-1;i>=1;i--) //ӡ°벿Ǻ
{
for(int j=1;j<=n-i;j++)
printf(" ");
for(int j=1;j<=2*i-1;j++)
printf("*");
printf("\n");
}
return 0;
}
|
C | /*
** EPITECH PROJECT, 2019
** my_compute_factorial_it
** File description:
** factorial with iterative loop
*/
int my_compute_factorial_it(int nb)
{
int factorial = nb;
if (nb < 0)
return (0);
if (nb == 0)
return (1);
if (nb > 12)
return (0);
while (nb > 1) {
factorial = factorial * (nb - 1);
nb--;
}
return (factorial);
}
|
C | /*
输入一个整数,连续显示出该整数个 *(for)
*/
#include <stdio.h>
int main(void){
int a;
printf("请输入一个整数:");scanf("%d",&a);
for(int i=1;i<=a;i++){
printf("*");
}
printf("\n");
} |
C | /*
* mipscodegen.c - Functions to translate to Assem-instructions for
* the Jouette assembly language using Maximal Munch.
*/
#include <stdio.h>
#include <stdlib.h> /* for atoi */
#include <string.h> /* for strcpy */
#include "util.h"
#include "symbol.h"
#include "absyn.h"
#include "temp.h"
#include "tree.h"
#include "assem.h"
#include "frame.h"
#include "errormsg.h"
AS_targets AS_Targets(Temp_labelList labels) {
AS_targets p = checked_malloc(sizeof *p);
p->labels = labels;
return p;
}
AS_instr AS_Oper(string a, Temp_tempList d, Temp_tempList s, AS_targets j) {
AS_instr p = (AS_instr) checked_malloc(sizeof *p);
p->kind = I_OPER;
p->u.OPER.assem = a;
p->u.OPER.dst = d;
p->u.OPER.src = s;
p->u.OPER.jumps = j;
return p;
}
AS_instr AS_Label(string a, Temp_label label) {
AS_instr p = (AS_instr) checked_malloc(sizeof *p);
p->kind = I_LABEL;
p->u.LABEL.assem = a;
p->u.LABEL.label = label;
return p;
}
AS_instr AS_Move(string a, Temp_tempList d, Temp_tempList s) {
AS_instr p = (AS_instr) checked_malloc(sizeof *p);
p->kind = I_MOVE;
p->u.MOVE.assem = a;
p->u.MOVE.dst = d;
p->u.MOVE.src = s;
return p;
}
AS_instrList AS_InstrList(AS_instr head, AS_instrList tail) {
AS_instrList p = (AS_instrList) checked_malloc(sizeof *p);
p->head = head;
p->tail = tail;
return p;
}
/* put list b at the end of list a */
AS_instrList AS_splice(AS_instrList a, AS_instrList b) {
AS_instrList p;
if (a == NULL) return b;
for (p = a; p->tail != NULL; p = p->tail);
p->tail = b;
return a;
}
static Temp_temp nthTemp(Temp_tempList list, int i) {
assert(list);
if (i == 0) return list->head;
else return nthTemp(list->tail, i - 1);
}
static Temp_label nthLabel(Temp_labelList list, int i) {
assert(list);
if (i == 0) return list->head;
else return nthLabel(list->tail, i - 1);
}
/* first param is string created by this function by reading 'assem' string
* and replacing `d `s and `j stuff.
* Last param is function to use to determine what to do with each temp.
*/
static void format(char *result, string assem,
Temp_tempList dst, Temp_tempList src,
AS_targets jumps, Temp_map m) {
//fprintf(stdout, "a format: assem=%s, dst=%p, src=%p\n", assem, dst, src);
char *p;
int i = 0; /* offset to result string */
for (p = assem; p && *p != '\0'; p++) {
if (*p == '`') {
switch (*(++p)) {
case 's': {
int n = atoi(++p);
string s = Temp_look(m, nthTemp(src, n));
strcpy(result + i, s);
i += strlen(s);
}
break;
case 'd': {
int n = atoi(++p);
string s = Temp_look(m, nthTemp(dst, n));
strcpy(result + i, s);
i += strlen(s);
}
break;
case 'j':
assert(jumps);
{
int n = atoi(++p);
string s = Temp_labelstring(nthLabel(jumps->labels, n));
strcpy(result + i, s);
i += strlen(s);
}
break;
case '`':
result[i] = '`';
i++;
break;
default:
assert(0);
}
} else {
result[i] = *p;
i++;
}
}
result[i] = '\0';
}
void AS_print(FILE *out, AS_instr i, Temp_map m) {
char r[200]; /* result */
switch (i->kind) {
case I_OPER:
format(r, i->u.OPER.assem, i->u.OPER.dst, i->u.OPER.src, i->u.OPER.jumps, m);
fprintf(out, "%s\n", r);
break;
case I_LABEL:
format(r, i->u.LABEL.assem, NULL, NULL, NULL, m);
fprintf(out, "%s:\n", r);
/* i->u.LABEL->label); */
break;
case I_MOVE: {
if ((i->u.MOVE.dst == NULL) && (i->u.MOVE.src == NULL)) {
char *src = strchr(i->u.MOVE.assem, '%');
if (src != NULL) {
char *dst = strchr(src + 1, '%');
if (dst != NULL) {
//fprintf(out, "src: %s; dst: %s\n", src, dst);
if ((src[1] == dst[1]) && (src[2] == dst[2]) && (src[3] == dst[3])) break;
}
}
}
format(r, i->u.MOVE.assem, i->u.MOVE.dst, i->u.MOVE.src, NULL, m);
fprintf(out, "%s\n", r);
break;
}
}
}
/* c should be COL_color; temporarily it is not */
void AS_printInstrList(FILE *out, AS_instrList iList, Temp_map m) {
for (; iList; iList = iList->tail) {
AS_print(out, iList->head, m);
}
fprintf(out, "\n");
}
AS_proc AS_Proc(string p, AS_instrList b, string e) {
AS_proc proc = checked_malloc(sizeof(*proc));
proc->prolog = p;
proc->body = b;
proc->epilog = e;
return proc;
}
AS_instrList AS_rewrite(AS_instrList iList, Temp_map m) {
AS_instrList prev = NULL;
AS_instrList origin = iList;
for (AS_instrList i = iList; i; i = i->tail) {
AS_instr instr = i->head;
if (instr->kind == I_MOVE) {
Temp_temp src = instr->u.MOVE.src->head;
Temp_temp dst = instr->u.MOVE.dst->head;
if (Temp_look(m, src) == Temp_look(m, dst)) {
if (prev) {
prev->tail = i->tail;
continue;
} else {
origin = i->tail;
}
}
}
if (instr->kind == I_OPER && strncmp("\tjmp", instr->u.OPER.assem, 4) == 0) {
if (i->tail) {
AS_instr nInstr = i->tail->head;
if (nInstr->kind == I_LABEL && nInstr->u.LABEL.label == instr->u.OPER.jumps->labels->head) {
i = i->tail;
if (prev) {
prev->tail = i->tail;
continue;
} else {
origin = i->tail;
}
}
}
}
prev = i;
}
return origin;
}
void _replace(Temp_tempList l, Temp_temp origin, Temp_temp newTemp) {
for (; l; l = l->tail) {
if (l->head == origin) {
l->head = newTemp;
}
}
}
// TODO: rewriteProgram
AS_instrList AS_rewriteProgram(F_frame f, AS_instrList il, Temp_tempList spills) {
// allocate memory locations for each v in spilledNodes
for (; spills; spills = spills->tail) {
Temp_temp spillNode = spills->head;
F_access acc = F_allocLocal(f, TRUE);
for (AS_instrList cur = il; cur; cur = cur->tail) {
AS_instr instr = cur->head;
Temp_tempList dst=NULL, src=NULL;
switch (instr->kind) {
case I_LABEL:
continue;
case I_OPER:
dst = instr->u.OPER.dst;
src = instr->u.OPER.src;
break;
case I_MOVE:
dst = instr->u.MOVE.dst;
src = instr->u.MOVE.src;
break;
default: assert(0);
}
/* put all into a newTemp */
char buf[256];
Temp_temp newTemp = Temp_newtemp();
if (Temp_contain(src, spillNode)) {
sprintf(buf, "\tmovq %d(`s0), `d0", acc->u.offset);
AS_instr newInstr = AS_Oper(String(buf), Temp_TempList(newTemp, NULL), Temp_TempList(F_FP(), NULL), NULL);
_replace(src, spillNode, newTemp);
cur->tail = AS_InstrList(cur->head, cur->tail);
cur->head = newInstr;
cur = cur->tail;
}
if (Temp_contain(dst, spillNode)) {
sprintf(buf, "\tmovq `s0, %d(`s1)", acc->u.offset);
AS_instr newInstr = AS_Oper(String(buf), NULL, Temp_TempList(newTemp, Temp_TempList(F_FP(), NULL)), NULL);
_replace(dst, spillNode, newTemp);
cur->tail = AS_InstrList(newInstr, cur->tail);
cur = cur->tail;
}
}
}
return il;
} |
C | //michael silianov + evgeney golovachov
#include <stdio.h>
#include <stdlib.h>
#define N 5
// find and print beginning of siquences
// of same numbers 'size' length
void func(int mat[N][N], int size);
void main() {
int mat[N][N] = {
{1,2,3,4,5},
{2,1,1,1,1},
{2,1,5,6,7},
{2,1,6,7,8},
{2,8,7,8,9}
};
func(mat, 3);
}
void func(int mat[N][N], int size)
{
int i, j, c = 0, d = 0;
for (i = 0; i < N; i++) {
for (int j = 0; j < N-1; j++) {
if (mat[i][j] == mat[i][j+1] ) {
++c;
if (c >= size-1) {
printf("%11s [%d][%d]\n", "horizontal", i, j-size+2);
}
}else{
c = 0;
}
if (mat[j][i] == mat[j+1][i]) {
++d;
if (d >= size - 1) {
printf("%11s [%d][%d]\n","vertical", j-size+2, i);
}
}else{
d = 0;
}
}
}
}
|
C | #include<stdio.h>
int main()
{
int n,a[n],i,x;
printf("n");
scanf("%d",&n);
printf("array");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
x=n/2;
if(n%2==0)
{
for(i=x;i<n;i++)
{
printf("%d",a[i]);
}
for(i=0;i<x;i++)
{
printf("%d",a[i]);
}
}
else
{
for(i=x+1;i<n;i++)
{
printf("%d",a[i]);
}
printf("%d",a[x]);
for(i=0;i<x;i++)
{
printf("%d",a[i]);
}
}
}
|
C | #include <stdio.h>
int main(int __attribute__((unused)) argc, char __attribute__((unused)) *argv[])
{
int ascii;
float temp;
printf("Enter an ASCII codeint: ");
scanf("%d", &ascii);
printf("%d is the ASCII code for %c.\n", ascii, ascii);
printf("Enter an float value: ");
scanf("%f", &temp);
printf("The input is %f or %e.\n", temp, temp);
getchar();
return 0;
}
|
C | #include <stdio.h>
void callback1(void) __attribute__((noinline));
void callback2(void) __attribute__((noinline));
void functionPtrInt_test(void (*callback_ptr)()) __attribute__((noinline));
void callback1(void) { ; }
void callback2(void) { ; }
void functionPtrVoid_test(void (*callback_ptr)())
{
(*callback_ptr) (); // callback function
}
//Callback added in main()
int main(int argc, char *argv[])
{
if(argc%2 == 0)
functionPtrVoid_test(&callback1);
else
functionPtrVoid_test(&callback2);
return 0;
}
|
C | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE563_Unused_Variable__unused_value_int_22b.c
Label Definition File: CWE563_Unused_Variable__unused_value.label.xml
Template File: sources-sinks-22b.tmpl.c
*/
/*
* @description
* CWE: 563 Unused Variable
* BadSource: Initialize data
* GoodSource: Initialize and use data
* Sinks:
* GoodSink: Use data
* BadSink : Initialize and use data
* Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources.
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifndef OMITBAD
/* The global variable below is used to drive control flow in the sink function */
extern int CWE563_Unused_Variable__unused_value_int_22_badGlobal;
void CWE563_Unused_Variable__unused_value_int_22_badSink(int data)
{
if(CWE563_Unused_Variable__unused_value_int_22_badGlobal)
{
/* POTENTIAL FLAW: Possibly over-write the initial value of data before using it */
data = 10;
printIntLine(data);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* The global variables below are used to drive control flow in the sink functions. */
extern int CWE563_Unused_Variable__unused_value_int_22_goodB2G1Global;
extern int CWE563_Unused_Variable__unused_value_int_22_goodB2G2Global;
extern int CWE563_Unused_Variable__unused_value_int_22_goodG2BGlobal;
/* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */
void CWE563_Unused_Variable__unused_value_int_22_goodB2G1Sink(int data)
{
if(CWE563_Unused_Variable__unused_value_int_22_goodB2G1Global)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Use data without over-writing its value */
printIntLine(data);
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */
void CWE563_Unused_Variable__unused_value_int_22_goodB2G2Sink(int data)
{
if(CWE563_Unused_Variable__unused_value_int_22_goodB2G2Global)
{
/* FIX: Use data without over-writing its value */
printIntLine(data);
}
}
/* goodG2B() - use goodsource and badsink */
void CWE563_Unused_Variable__unused_value_int_22_goodG2BSink(int data)
{
if(CWE563_Unused_Variable__unused_value_int_22_goodG2BGlobal)
{
/* POTENTIAL FLAW: Possibly over-write the initial value of data before using it */
data = 10;
printIntLine(data);
}
}
#endif /* OMITGOOD */
|
C | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_5__ TYPE_2__ ;
typedef struct TYPE_4__ TYPE_1__ ;
/* Type definitions */
struct TYPE_5__ {int num_bufs; scalar_t__* refcnt; int num_tbufs; int /*<<< orphan*/ * tbufs; int /*<<< orphan*/ lock; TYPE_1__* queues; int /*<<< orphan*/ counter; int /*<<< orphan*/ * ts; } ;
struct TYPE_4__ {int head; int num; int tail; int* idx; int /*<<< orphan*/ cv; int /*<<< orphan*/ efd; int /*<<< orphan*/ lock; int /*<<< orphan*/ inited; } ;
typedef TYPE_1__ PoolQueue ;
typedef TYPE_2__ Pool ;
/* Variables and functions */
int POOL_MAX_QUEUES ;
int /*<<< orphan*/ assert (int) ;
int /*<<< orphan*/ efd_write (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ pthread_cond_signal (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ pthread_mutex_lock (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ pthread_mutex_unlock (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ tbuffer_dispatch (int /*<<< orphan*/ *,int) ;
void pool_push(Pool *s, int idx) {
pthread_mutex_lock(&s->lock);
// printf("push %d head %d tail %d\n", idx, s->head, s->tail);
assert(idx >= 0 && idx < s->num_bufs);
s->ts[idx] = s->counter;
s->counter++;
assert(s->refcnt[idx] > 0);
s->refcnt[idx]--; //push is a implcit release
int num_tbufs = s->num_tbufs;
s->refcnt[idx] += num_tbufs;
// dispatch pool queues
for (int i=0; i<POOL_MAX_QUEUES; i++) {
PoolQueue *c = &s->queues[i];
if (!c->inited) continue;
pthread_mutex_lock(&c->lock);
if (((c->head+1) % c->num) == c->tail) {
// queue is full. skip for now
pthread_mutex_unlock(&c->lock);
continue;
}
s->refcnt[idx]++;
c->idx[c->head] = idx;
c->head = (c->head+1) % c->num;
assert(c->head != c->tail);
pthread_mutex_unlock(&c->lock);
efd_write(c->efd);
pthread_cond_signal(&c->cv);
}
pthread_mutex_unlock(&s->lock);
for (int i=0; i<num_tbufs; i++) {
tbuffer_dispatch(&s->tbufs[i], idx);
}
} |
C | #include <stdio.h>
#include <math.h>
#include <time.h>
#include </usr/include/gsl/gsl_math.h>
#include </usr/include/gsl/gsl_linalg.h>
const double x0 = 2.0;
const double sigma = 4.0;
double g(double x)
{
double a0=-pow(x0,2)/(2*pow(sigma,2));
double a1=x0/(pow(sigma,2));
double a2=-1/(2*pow(sigma,2));
return exp(a0+a1*x+a2*pow(x,2));
}
double g2(double x, double alfa)
{
double U=rand()/(RAND_MAX+1.0);
return g(x)*(1.0+alfa*(U - 0.5));
}
double G(double x, gsl_vector *vector)
{
double b0=gsl_vector_get(vector,0);
double b1=gsl_vector_get(vector,1);
double b2=gsl_vector_get(vector,2);
double b3=gsl_vector_get(vector,3);
return exp(b0 + b1*x + b2*pow(x,2) + b3*pow(x,3));
}
double d(double N)
{
return ((3*sigma+x0)-(-3*sigma+x0))/(N-1);
}
void zapis(int N, gsl_vector *w, FILE *p)
{
for(int i = 0; i <= N; i++)
{
double x=(-3*sigma+x0)+0.1*i;
double lG=G(x, w);
fprintf(p, "%g %g \n",x, lG);
}
fprintf(p, "\n \n");
}
void zapisWezly(int N, gsl_vector *wezly, gsl_vector *wartosc, FILE *p)
{
for(int i = 0; i < N; i++)
{
fprintf(p, "%g %g \n",gsl_vector_get(wezly, i),gsl_vector_get(wartosc, i));
}
fprintf(p, "\n \n");
}
int main()
{
srand(time(NULL));
const int N1=11;
const int m=4;
const int N2=101;
FILE *p1=fopen("wezly.txt","w");
FILE *p2=fopen("G.txt","w");
gsl_vector *wezly=gsl_vector_calloc(N1);
for(int i=0;i<N1;i++)
{
gsl_vector_set(wezly,i,-3*sigma+x0+d(N1)*i);
}
gsl_vector *wezly2=gsl_vector_calloc(N2);
for(int i=0;i<N2;i++)
{
gsl_vector_set(wezly2,i,-3*sigma+x0+d(N2)*i);
}
gsl_vector *wartosc_g=gsl_vector_calloc(N1);
gsl_vector *wartosc_g2=gsl_vector_calloc(N1);
for(int i=0;i<N1;i++)
{
gsl_vector_set(wartosc_g,i,g(gsl_vector_get(wezly,i)));
gsl_vector_set(wartosc_g2,i,g2(gsl_vector_get(wezly,i),0.5));
}
gsl_vector *wartosc_g2_1=gsl_vector_calloc(N2);
for(int i=0;i<N2;i++)
{
gsl_vector_set(wartosc_g2_1,i,g2(gsl_vector_get(wezly2,i),0.5));
}
zapisWezly(N1,wezly,wartosc_g,p1);
zapisWezly(N1,wezly,wartosc_g2,p1);
zapisWezly(N2,wezly2,wartosc_g2_1,p1);
gsl_vector *wartosc_f=gsl_vector_calloc(N1);
gsl_vector *wartosc_f2=gsl_vector_calloc(N1);
for(int i=0;i<N1;i++)
{
gsl_vector_set(wartosc_f,i,log(gsl_vector_get(wartosc_g,i)));
gsl_vector_set(wartosc_f2,i,log(gsl_vector_get(wartosc_g2,i)));
}
gsl_vector *wartosc_f2_1=gsl_vector_calloc(N2);
for(int i=0;i<N2;i++)
{
gsl_vector_set(wartosc_f2_1,i,log(gsl_vector_get(wartosc_g2_1, i)));
}
gsl_vector *r=gsl_vector_calloc(m);
gsl_vector *r2=gsl_vector_calloc(m);
gsl_vector *r2_1=gsl_vector_calloc(m);
gsl_matrix *mG=gsl_matrix_calloc(m, m);
gsl_matrix *mG2=gsl_matrix_calloc(m, m);
gsl_matrix *mG2_1=gsl_matrix_calloc(m, m);
for(int i=0;i<m;i++)
{
double temp=0.0;
double temp2=0.0;
for(int j=0;j<N1;j++)
{
temp+=gsl_vector_get(wartosc_f,j)*pow(gsl_vector_get(wezly,j),i);
temp2+=gsl_vector_get(wartosc_f2, j)*pow(gsl_vector_get(wezly,j),i);
}
gsl_vector_set(r,i,temp);
gsl_vector_set(r2,i,temp2);
}
for(int i=0;i<m;i++)
{
double temp=0.0;
for(int j=0;j<N2;j++)
{
temp+=gsl_vector_get(wartosc_f2_1,j)*pow(gsl_vector_get(wezly2,j),i);
}
gsl_vector_set(r2_1,i,temp);
}
for(int i=0;i<m;i++)
{
for(int k=0;k<m;k++)
{
double temp=0;
for(int j=0;j<N1;j++)
{
temp+=pow(gsl_vector_get(wezly,j),i+k);
}
gsl_matrix_set(mG,i,k,temp);
gsl_matrix_set(mG2,i,k,temp);
}
}
for(int i=0;i<m;i++)
{
for(int k=0;k<m;k++)
{
double temp=0;
for(int j=0;j<N2;j++)
{
temp+=pow(gsl_vector_get(wezly2,j),i+k);
}
gsl_matrix_set(mG2_1,i,k,temp);
}
}
gsl_linalg_HH_svx(mG,r);
gsl_linalg_HH_svx(mG2,r2);
gsl_linalg_HH_svx(mG2_1,r2_1);
double a0 = -pow(x0, 2) / (2 * pow(sigma, 2));
double a1 = x0 / pow(sigma, 2);
double a2 = -1 / (2 * pow(sigma, 2));
printf("Analityczne(g1 oraz n = 11) \n");
printf("%g \n", a0);
printf("%g \n", a1);
printf("%g \n", a2);
printf("\n");
printf("Numeryczne(g1 oraz n = 11) \n");
for(int i = 0; i < m; i++){
printf("%g \n",gsl_vector_get(r, i));
}
printf("\n");
printf("Numeryczne(g2 oraz n = 11) \n");
for(int i = 0; i < m; i++){
printf("%g \n",gsl_vector_get(r2, i));
}
printf("\n");
printf("Numeryczne(g2 oraz n = 101) \n");
for(int i = 0; i < m; i++){
printf("%g \n",gsl_vector_get(r2_1, i));
}
printf("\n");
int k=((3*sigma+x0)-(-3*sigma+x0))/0.1;
zapis(k,r,p2);
zapis(k,r2,p2);
zapis(k,r2_1,p2);
gsl_vector_free(wezly);
gsl_vector_free(wezly2);
gsl_vector_free(wartosc_g);
gsl_vector_free(wartosc_g2);
gsl_vector_free(wartosc_g2_1);
gsl_vector_free(wartosc_f);
gsl_vector_free(wartosc_f2);
gsl_vector_free(wartosc_f2_1);
gsl_vector_free(r);
gsl_vector_free(r2);
gsl_vector_free(r2_1);
gsl_matrix_free(mG);
gsl_matrix_free(mG2);
gsl_matrix_free(mG2_1);
fclose(p1);
fclose(p2);
return 0;
} |
C | /**
* Realtime logging
* Multiple threads
*
* For greater applications you should use a mutex for curses operations
*/
#include <stdio.h>
#include <ncurses.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
static WINDOW *logWin, *cmdWin;
static int running;
static pthread_t thread;
static void *logThread();
static void killCmdWindow();
static void killAllWindows();
static void buildWindows();
static void rebuildWindows();
int main() {
initscr();
echo();
cbreak();
logWin = cmdWin = NULL;
buildWindows();
doupdate();
running = 1;
pthread_create(&thread, NULL, logThread, NULL);
while (1) {
char buf[500];
int r = wgetnstr(cmdWin, buf, sizeof(buf));
if (r == ERR) break;
else if (r == KEY_RESIZE) rebuildWindows();
else if (strlen(buf) == 0) break; // No text == exit
// Rebuild command window
killCmdWindow();
buildWindows();
// Post text
waddstr(logWin, buf);
waddstr(logWin, "\n");
wrefresh(logWin);
wrefresh(cmdWin);
}
running = 0;
pthread_join(thread, NULL);
killAllWindows();
endwin();
return 0;
}
static void *logThread() {
do {
waddstr(logWin, "Hello\n");
wrefresh(logWin);
wrefresh(cmdWin);
sleep(1);
} while (running);
return NULL;
}
static void killCmdWindow() {
delwin(cmdWin);
cmdWin = NULL;
}
static void killAllWindows() {
killCmdWindow();
}
static void buildWindows() {
if (!logWin) {
logWin = newwin(LINES-1, COLS, 1, 0);
scrollok(logWin, TRUE);
}
if (!cmdWin) cmdWin = newwin(1, COLS, 0, 0);
}
static void rebuildWindows() {
killAllWindows();
buildWindows();
}
|
C | #include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
int fd0[2], fd1[2];
pid_t pid;
char buf[255];
pipe(fd0);
pipe(fd1);
pid = fork();
if(pid == 0){
read(fd0[0],buf,255);
printf("This is child process 1.\n");
write(fd1[1],"hello",sizeof("hello"));
exit(0);
} else {
pid=fork();
if(pid == 0 ){
printf("This is child process 2.\n");
write(fd0[1],"hello",sizeof("hello"));
exit(0);
}
read(fd1[0],buf,255);
printf("This is parent process.\n");
}
}
|
C | #include "common.h"
void init_config(void)
{
//configure PORTB as output
TRISB = 0x00;
//configure PORTB as digital port
ADCON1 = 0x00;
//configure LATB with 0x55
LATB = 0x55;
//initially turn off all LED's
PORTB = 0x00;
}
unsigned short i;
void main(void)
{
init_config();
while(1)
{
//turn on all LED's
PORTB = ON;
//delay
for(i = 50000;i--;);
for(i = 50000;i--;);
for(i = 50000;i--;);
//turn off all LED's
PORTB = OFF;
//delay
for(i = 50000;i--;);
for(i = 50000;i--;);
for(i = 50000;i--;);
for(i = 50000;i--;);
for(i = 50000;i--;);
for(i = 50000;i--;);
}
} |
C | /*#include <stdio.h>
int main()
{
/*
Q1.ü ũ ˴ϴ. 32Ʈ ü ũ ΰ?
1. 2Ʈ 2.4Ʈ 3. 8Ʈ 4. 16Ʈ
---------------------------------------------
4Ʈ
*/
/*
Q2.int data 0x12345678 Ǿ ֽϴ. data
ʰ short * Ͽ data 0x12340412 ϴ ڵ带 ۼϼ.
hint:Ʋ ý ϹǷ short * ù ° ϸ 0x5678 0x0412 ִ.
--------------------------------------------------------------------------------------------------------------------
int data = 0x12345678;
short *p = (short *)&data;
*p = 0x0412;
printf("%x\n", data);
*/
/*
Q3. TestԼ mainԼ tips 5 ϴ ڵԴϴ. ĭ ä ڵ带 ϼϼ.
#include <stdio.h>
void Test(int *p)
{
ĭ
}
void main(void)
{
int tips = 0;
Test( ĭ);
}
------------------------------------------------------------------------------------------------------------
#include <stdio.h>
void Test(int *p)
{
*p = 5;
}
int main()
{
int tips = 0;
Test(&tips);
printf("%d\n", tips);
}
*/
/*
Q4.int * p 200 Ǿ ֽϴ. p++; ϰ p ּҴ ϱ?
------------------------------------
int 4Ʈ p++; p 204
*/
/*
Q5.int * pa pb ֽϴ.
pa 100 ְ pb 108 ֽϴ. ̷ Ȳ pb-pa ϱ?
*/
/*
Q6. Ͽ ϱ
a,b,c ֽϴ. 0x12, 0x34, 0x5678 Ǿ ֽϴ.
char a = 0x12
char b = 0x34;
short c = 0x5678;
̷ a,b,c Ͽ ο t 0x12345678 ϴ ڵ带 ۼ .
int t; //t 0x12345678 ǵ
hit1 : t 0x12345678 ϸ ȵ˴ϴ.
hit2 : Ʈ ڿ Ʈ ڸ ϸ ȵ˴ϴ.
hit3 : Ųٷ Ǵ Ʋ ý̶ .
ڵ忡 ߰ ϰ mainԼ printfԼ ؼ ڵ ۼ.
*/
/*
char a = 0x12;
char b = 0x34;
short c = 0x5678;
int t;
char *p = &t;
*(short *)p = (short *)c;
printf("%x\n", t);
*(p + 2) = (char *)b;
printf("%x\n", t);
*(p + 3) = (char *)a;
printf("%x\n", t);
}
*/ |
C | /*
********************************************************************************************************
ļbsp_GPIO.c
ܣҪͨIO
עðеIOã
*********************************************************************************************************
*/
#include "bsp_GPIO.h"
/*
********************************************************************************************************
ƣvoid LED_GPIO_Config(void)
ܣʼLED1GPIO
ӲӣLED1----PC13
*********************************************************************************************************
*/
void LED_GPIO_Config(void) //led gpio
{
/*һGPIO_InitTypeDef͵Ľṹ*/
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd( LED1_CLK, ENABLE); /*GPIOʱ*/
GPIO_InitStructure.GPIO_Pin = LED1_Pin; /*ѡҪƵGPIO*/
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; /*ģʽΪͨ*/
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; /*Ϊ50MHz */
GPIO_Init(LED1_PORT, &GPIO_InitStructure);/*ÿ⺯ʼGPIOC13*/
}
void USART1_GPIO_Config(void) //USART1 gpio
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); //ʹGPIOA
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE); //ʹUSART1
//GPIOģʽ-PA9 PA10Ϊ1
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_10MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA,&GPIO_InitStructure);
}
//------------------End of File----------------------------
|
C | #include <stdio.h>
#include <stdlib.h>
typedef struct jose{
int id;
struct jose *next;
}loop;
int count = 0,N=0,M=0;
/**
* @brief create a node of a linked list
*
* @param pro orignal address
* @param id people's id
*
* @return address of the newly built
*/
loop * create(loop *pro,int id)
{
loop *p = malloc(sizeof(loop));
p->id = id;
p->next = NULL;
if(pro)
pro->next = p;
return p;
}
/**
* @brief travel all points of the list and print the id of the out
*
* @param p original address
* @param m out when count to m
*
* @return success return 0
*/
int jose(loop *p,const int m)
{
loop *temp;
int i = m,t = 0;
while(--i)
{
temp = p;
p = p->next;
}
printf("%3d: %3d out%c",count,p->id,++count%5==0?'\n':'\t');
if(count == N)
return 0;
temp->next = p->next;
free(p);
jose(temp->next,m);
}
int main(int argc, const char *argv[])
{
loop *head = NULL,*p;
int i;
N = atoi(argv[1]);
M = atoi(argv[2]);
head = create(head,1);
for(i = 1;i < N;i++)
p = create((i-1)?p:head,i+1);
p->next = head;
jose(head,M);
return 0;
}
|
C | // 3. Program to calculate sum of an array
#include <stdio.h>
int main()
{
int sum=0,i;
int a[]={1,2,3,4,5};
int n=sizeof(a)/sizeof(a[0]);
for(i=0;i<n;i++)
{
sum+=a[i];
}
printf("%d\n",sum);
}
|
C | // Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
#include <RemoteProcess.h>
#include <BadHostException.h>
#include <TestUtil.h>
#define VERBOSE
#define N_TESTS 1
// Prototypes
bool Run_Test1(bool verbose, int *subtest, int *nsubtests);
// *******************************************************************
// Function: main
//
// Purpose:
// The main function for this test program. It executes the test
// cases.
//
// Programmer: Brad Whitlock
// Creation: Thu Aug 10 15:34:38 PST 2000
//
// Modifications:
//
// *******************************************************************
int
main(int argc, char *argv[])
{
int subtest, nsubtests;
bool test[N_TESTS];
TestUtil util(argc, argv, "Tests RemoteProcess class");
// Test the RemoteProcess class with a bad hostname.
test[0] = Run_Test1(util.verbose, &subtest, &nsubtests);
util.PrintTestResult(1, subtest, nsubtests, test[0]);
return util.PassFail(test, N_TESTS);
}
///////////////////////////////////////////////////////////////////////////
/// Test 1 - Test the RemoteProcess class.
///
/// Notes:
/// This test is designed to test the RemoteProcess class with a bad
/// host name to see if it throws a BadHostException.
///
///////////////////////////////////////////////////////////////////////////
// *******************************************************************
// Function: Run_Test1
//
// Purpose:
// Test the RemoteProcess class. Try giving it a bad machine name.
//
// Arguments:
// verbose : Whether or not to do lots of output.
// subtest : A return code to indicate the last subtest to be
// executed.
// nsubtests : The number of subtests.
//
// Notes:
//
// Programmer: Brad Whitlock
// Creation: Thu Aug 10 16:09:30 PST 2000
//
// Modifications:
//
// *******************************************************************
bool
Run_Test1(bool verbose, int *subtest, int *nsubtests)
{
// We have 1 subtests
*nsubtests = 1;
#ifdef VERBOSE
if(verbose)
{
cout << "=================================================" << endl;
cout << "Running Test 1" << endl;
cout << "=================================================" << endl;
}
#endif
bool retval = false;
// Create a RemoteProcess
*subtest = 1;
RemoteProcess remote("foo");
// Actually try to run the remote process on a machine that
// does not exist.
TRY
{
remote.Open("nonexistantmachine", 1, 1);
}
CATCH2(BadHostException, e)
{
cout << e.GetHostName() << "is an invalid host name." << endl;
retval = true;
}
ENDTRY
return retval;
}
|
C | /*
* invert.c - calculate the inverse of a large integer in an integer multiplation group
*
* 2016-11-01 Steven Wart created this file
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#include <stdarg.h>
#include <gmp.h>
void print_usage(char *name) {
printf("This program will compute the inverse of integer value, in the multiplication group for the modulus provided\n");
printf("Usage: %s <value> <prime>\n", name);
exit(0);
}
//
// Parse an integer value from the string and put it into result
// If the number cannot be parsed, exit the program
//
void parse_integer(mpz_t result, char *stringValue) {
// parse number using base=0 so we can accept 0x for hexadecimal numbers
int err = mpz_set_str(result, stringValue, 0);
if (err < 0) {
perror("invalid number");
exit(0);
}
}
int main(int argc, char **argv) {
mpz_t value, mod, pminus2, result;
char *resultString;
mpz_inits(value, mod, pminus2, result, NULL);
// if three numeric arguments aren't provided
// print usage and exit
if (argc != 3) {
print_usage(argv[0]);
}
// parse the inputs
parse_integer(value, argv[1]);
parse_integer(mod, argv[2]);
// 1. for prime p we have a^p = a mod p
// 2. and if a is not divisible by p, then a^(p-1) = 1 mod p
// 3. and a * (a^(p-2)) = a^(p-1) = 1
// 4. or 1 / a mod p = a^(p-2) mod p
// 5. therefore dividing by a is like multiplying by a^(p-2) mod p
mpz_sub_ui(pminus2, mod, 2L); // compute p-2
/* resultString = mpz_get_str(NULL, 10, pminus2); */
/* printf("p-2=%s\n", resultString); */
mpz_powm(result, value, pminus2, mod); // compute a^(p-2) mod p
// use the current allocation function for the result string (and in base 10)
resultString = mpz_get_str(NULL, 10, result);
printf("%s\n", resultString);
}
|
C | #include <stdio.h>
#include <stdlib.h>
typedef struct {
float x, y, z;
} vetor;
void sum(const vetor *v1, const vetor *v2, vetor *r) {
r->x = v1->x + v2->x, r->y = v1->y + v2->y, r->z = v1->z + v2->z;
}
float produto(const vetor *v1, const vetor *v2) {
return ((v1->x * v2->x) + (v1->y * v2->y) + (v1->z * v2->z));
}
int main(){
vetor a = {1.2, 2.5, 3.7}, b = {3.3, 4.7, 5.1}, r;
sum(&a, &b, &r);
printf("Soma vetorial = <%f, %f, %f>\n", r.x, r.y, r.z);
printf("Produto Escalar = %f\n", (produto(&a, &b)));
return 0;
}
|
C | /* Example code for how to call the routine "dspeig" for the dense
* symmetric eigenproblem with matrix A in packed storage.
* The routine uses LAPACK routines for the reduction and
* back-transformation and must therefore be linked to LAPACK.
* The number of threads for the LAPACK routines are set by
* OMP_NUM_THREADS or GOTO_NUM_THREADS or MKL_NUM_THREADS or ...
* depending on the BLAS used. For the tridiagonal stage with
* PMR_NUM_THREADS.
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <assert.h>
#include "global.h"
#include "mrrr.h"
int main(int argc, char **argv)
{
int n = 100;
int ldz = n;
int nz = n;
int size = (n*(n+1))/2;
double *AP, *W, *Z;
double vl, vu;
int il, iu;
int m, i;
AP = (double *) malloc((size_t) size*sizeof(double));
assert(AP != NULL);
W = (double *) malloc((size_t) n *sizeof(double));
assert(W != NULL);
Z = (double *) malloc((size_t) n*nz*sizeof(double));
assert(Z != NULL);
/* Initialize matrix in packed storage; since we use random value
* entries no distinction between upper or lower part stored */
srand( (unsigned) time( (time_t *) NULL) );
for (i=0; i<size; i++)
AP[i] = (double) rand() / RAND_MAX;
/* Calling "dspeig" to compute all or a subset of eigenvalues and
* optinally eigenvectors of a dense symmetric matrix in packed storage
* using LAPACK routines for reduction and backtransformation and
* the multi-threaded MRRR for the tridiagonal stage.
* The number of threads for the LAPACK routines are set by
* OMP_NUM_THREADS or GOTO_NUM_THREADS or MKL_NUM_THREADS or ...
* depending on the BLAS used. For the tridiagonal stage with
* PMR_NUM_THREADS.
* Since A is initialized randomly we can either assume it represents
* the upper or lower triangular part of A in packed storage */
il = 1;
iu = n/2 + 1;
dspeig("Vectors", "Index", "Lower", &n, AP, &vl, &vu, &il, &iu,
&m, W, Z, &ldz);
printf("Successfully computed eigenpairs!\n");
free(AP);
free(W);
free(Z);
return(0);
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define htlf 13
#define ecell "EMPTY_CELL"
typedef struct node
{
char key[50];
int pos;
}*HASH;
int c=0;
int close_hashfnc(char str[])
{
int i=0;
int sum=0;
while(str[i]!='\0')
{
sum+=(int)str[i];
i++;
}
return (sum%htlf);
}
void search_hash(HASH arr[],char str[],int k)
{
int i=k;
while((i+1)!=k)
{
if(strcmp(arr[i]->key,str)==0)
{
printf("FOUND AT POSITION: %d\n",arr[i]->pos);
c=1;
}
i=(i+1)%htlf;
}
if(strcmp(arr[i]->key,str)==0)
{
printf("FOUND AT POSITION: %d\n",arr[i]->pos);
c=1;
}
}
void delete(HASH arr[])
{
for(int i=0;i<htlf;i++)
{
arr[i]=(HASH)(malloc(sizeof(struct node)));
strcpy(arr[i]->key,ecell);
arr[i]->pos=-1;
}
}
void create_hash(HASH arr[],int key,char str[],char patt[],int p)
{
if(strcmp(arr[key]->key,ecell)==0)
{
strcpy(arr[key]->key,str);
arr[key]->pos=p;
return;
}
int i=key;
while(1)
{
key=(key+1)%htlf;
if(strcmp(arr[key]->key,ecell)==0)
{
strcpy(arr[key]->key,str);
arr[key]->pos=p;
return;
}
else if(i==key)
{
search_hash(arr,patt,close_hashfnc(patt));
delete(arr);
}
else
{
continue;
}
}
}
int main()
{
char str[50];
char patt[50];
int i;
printf("Input the String: ");
fgets(str,49,stdin);
printf("Input the Pattern: ");
fgets(patt,49,stdin);
str[strlen(str)-1]='\0';
patt[strlen(patt)-1]='\0';
printf("The String: %s\n",str);
printf("The Pattern: %s\n",patt);
HASH arr[htlf];
for(i=0;i<htlf;i++)
{
arr[i]=(HASH)(malloc(sizeof(struct node)));
strcpy(arr[i]->key,ecell);
arr[i]->pos=-1;
}
int m=strlen(str);
int n=strlen(patt);
for(i=0;i<=m-n;i++)
{
char temp[50];
int j=0;
while(j<n)
{
temp[j]=str[i+j];
j++;
}
temp[j]='\0';
int key=close_hashfnc(temp);
create_hash(arr,key,temp,patt,i);
}
int k=close_hashfnc(patt);
search_hash(arr,patt,k);
if(c==0)
{
printf("Not Found\n");
}
return 0;
} |
C | #include "ft_printf.h"
int ft_find_specifier(const char *format)
{
int i;
i = 0;
if (format[i] == '%' && format[i + 1] != '%')
return (1);
return (0);
}
int exeption(char const *format)
{
int i;
i = 0;
if ((format[i] == '%' && format[i + 1] == '%')
return (1);
else
return (0);
}
void ft_process_specifier(const char *format, int *ret, int *i)
{
while (format[*i])
{
(*i)++;
if (format[*i] == ('-' || '+' || ' ' || '#' || '0'))
flags();
if (format[*i] == ('*' || ))
width();
if (format[*i] == '.' && format[*i + 1] == ('*' || ))
accuracy();
if (format[*i] == 'l' || (format[*i] == 'h' && format[*i + 1] == 'h')
|| (format[*i] == 'l' && format[*i + 1] == 'l') || format[*i] == 'j'
|| format[*i] == 'z' || format[*i] == 't' || format[*i] == 'L')
size();
if (format[*i] == 'c' || format[*i] == 's' || format[*i] == 'p' ||
format[*i] == 'd' || format[*i] == 'i' || format[*i] == 'o' ||
format[*i] == 'u' || format[*i] == 'x' || format[*i] == 'X' ||)
type();
}
}
void ft_print_and_smth(const char *format, va_list *ap, int *ret) //23
{
int i;
i = 0;
while (format[i])
{
if (ft_find_specifier(format))
ft_process_specifier(format, ret, &i);
else
{
if (exeption(format))
{
write(1, '%', 1);
i += 2;
(*ret)++;
}
else
{
write(1, &format[i], 1);
i++;
(*ret)++;
}
}
}
}
int ft_printf(const char *format, ...)
{
va_list ap;
int *ret;
*ret = 0;
va_start(ap, format);
ft_print_and_smth(format, &ap, ret);
va_end(ap);
return (*ret);
}
|
C | /*
* Author: Vinicius Ferraco Arruda
* Email: [email protected]
* Professor: Eduardo Zambon
* Subject: Compilers
* Assignment: Implementation of an interpreter for the language C-Minus
*
*/
#ifndef ERROR_H
#define ERROR_H
#include <stdio.h>
#include <stdlib.h>
/* If this error occurs, let me know with which input the interpreter was tested */
#define IMPLEMENTATION_ERROR "Something very wrong happened !"
#define raise_error(msg) {printf("%s\n", msg);exit(EXIT_SUCCESS);}
#endif
|
C | #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
void* ThreadEntry1(void* arg){
(void)arg;
printf("Thread1\n");
return (void*)1;
}
void* ThreadEntry2(void* arg){
(void)arg;
printf("Thread2\n");
pthread_exit((void*)2);
return NULL;
}
void* ThreadEntry3(void* arg){
(void)arg;
printf("Thread3\n");
pthread_cancel(pthread_self());
return NULL;
}
//创建三个线程,分别使用不同的方式终止线程
//通过线程等待来观察线程返回的结果
int main(){
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, ThreadEntry1, NULL);
pthread_create(&tid2, NULL, ThreadEntry2, NULL);
pthread_create(&tid3, NULL, ThreadEntry3, NULL);
void* ret = NULL;
pthread_join(tid1, &ret);
printf("thread1 ret = %p\n", ret);
pthread_join(tid2, &ret);
printf("thread2 ret = %p\n", ret);
pthread_join(tid3, &ret);
printf("thread3 ret = %p\n", ret);
return 0;
}
|
C | //C Program to Find Solution of Ordinary Differential Equation of 1st Order by Euler's Modified Method
#include <stdio.h>
#include <math.h>
#define f(x,y) (x+y)
double error(int a)
{
return 5*pow(10,-a-1);
}
double mod(double x)
{
if(x<0)
return -x;
else
return x;
}
int main()
{
double x0,x,h,e,e1,y0,y1,y2,k0,k1;
printf("f(x,y)=x+y\nEnter Value of x::");
scanf("%lf",&x0);
printf("Enter Value of y for x=%4.2lf::",x);
scanf("%lf",&y0);
printf("Enter Step length h::");
scanf("%lf",&h);
printf("Enter value of x for which y is to be computed::");
scanf("%lf",&x);
printf("You need the answer correct upto how many decimal places? ::");
scanf("%lf",&e);
e=error(e);
printf("y(%4.2lf)=%.4lf\n",x0,y0);
while(x0<x)
{
k0=f(x0,y0);
y1=y0+h*k0;
e1=1;
while(e1>e)
{
k1=f(x0+h,y1);
y2=y0+h*(k0+k1)/2;
e1=mod(y2-y1);
y1=y2;
}
y0=y1;
x0=x0+h;
printf("y(%4.2lf)=%.4lf\n",x0,y0);
}
return 0;
}
|
C | /* tz_geo3d_circle.c
*
* 18-Mar-2008 Initial write: Ting Zhao
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <utilities.h>
#include "tz_error.h"
#include "tz_constant.h"
#include "tz_geo3d_utils.h"
#include "tz_geo3d_circle.h"
#include "tz_swc_cell.h"
#include "tz_math.h"
Geo3d_Circle* New_Geo3d_Circle()
{
Geo3d_Circle* circle = (Geo3d_Circle *) Guarded_Malloc(sizeof(Geo3d_Circle),
"New_Geo3d_Circle");
Geo3d_Circle_Default(circle);
return circle;
}
void Delete_Geo3d_Circle(Geo3d_Circle *circle)
{
free(circle);
}
void Kill_Geo3d_Circle(Geo3d_Circle *circle)
{
Delete_Geo3d_Circle(circle);
}
void Geo3d_Circle_Default(Geo3d_Circle *circle)
{
circle->radius = 1.0;
circle->center[0] = 0.0;
circle->center[1] = 0.0;
circle->center[2] = 0.0;
circle->orientation[0] = 0.0;
circle->orientation[1] = 0.0;
}
void Geo3d_Circle_Copy(Geo3d_Circle *dst, const Geo3d_Circle *src)
{
memcpy(dst, src, sizeof(Geo3d_Circle));
}
Geo3d_Circle* Copy_Geo3d_Circle(Geo3d_Circle *src)
{
Geo3d_Circle *circle = New_Geo3d_Circle();
Geo3d_Circle_Copy(circle, src);
return circle;
}
void Print_Geo3d_Circle(const Geo3d_Circle *circle)
{
printf("3D circle [ radius: %g; center: %g, %g, %g; orientation: %g, %g ]\n",
circle->radius, circle->center[0], circle->center[1],
circle->center[2], circle->orientation[0], circle->orientation[1]);
}
void Geo3d_Circle_Points(const Geo3d_Circle *circle, int npt,
const coordinate_3d_t start,
coordinate_3d_t coord[])
{
double step = TZ_2PI / npt;
double normal[3];
Geo3d_Orientation_Normal(circle->orientation[0], circle->orientation[1],
normal, normal + 1, normal + 2);
double tangent[3];
Geo3d_Cross_Product(normal[0], normal[1], normal[2],
start[0], start[1], start[2],
tangent, tangent + 1, tangent + 2);
int i, j;
double t = 0.0;
for (i = 0; i < npt; i++) {
double rcos = cos(t);
double rsin = sin(t);
for (j = 0; j < 3; j++) {
coord[i][j] = rcos * start[j] + rsin * tangent[j] + circle->center[j];
}
t += step;
}
}
void Geo3d_Circle_Rotate_Vector(const Geo3d_Circle *circle, double angle,
coordinate_3d_t coord)
{
double normal[3];
Geo3d_Orientation_Normal(circle->orientation[0], circle->orientation[1],
normal, normal + 1, normal + 2);
double tangent[3];
Geo3d_Cross_Product(normal[0], normal[1], normal[2],
coord[0], coord[1], coord[2],
tangent, tangent + 1, tangent + 2);
double rcos = cos(angle);
double rsin = sin(angle);
int j;
for (j = 0; j < 3; j++) {
coord[j] = rcos * coord[j] + rsin * tangent[j];
}
}
double Geo3d_Circle_Vector_Angle(const Geo3d_Circle *circle,
coordinate_3d_t v1, coordinate_3d_t v2)
{
double normal[3];
Geo3d_Orientation_Normal(circle->orientation[0], circle->orientation[1],
normal, normal + 1, normal + 2);
double tangent[3];
Geo3d_Cross_Product(normal[0], normal[1], normal[2],
v1[0], v1[1], v1[2],
tangent, tangent + 1, tangent + 2);
double angle = Geo3d_Angle2(v1[0], v1[1], v1[2], v2[0], v2[1], v2[2]);
if (Geo3d_Dot_Product(v2[0], v2[1], v2[2], tangent[0], tangent[1], tangent[2])
< 0.0) {
angle = TZ_2PI - angle;
}
return angle;
}
int Geo3d_Circle_Plane_Point(const Geo3d_Circle *circle,
const xz_orientation_t plane_ort,
int direction,
coordinate_3d_t coord)
{
if (direction == 1) {
Xz_Orientation_Cross(circle->orientation, plane_ort, coord);
} else if (direction == -1) {
Xz_Orientation_Cross(plane_ort, circle->orientation, coord);
} else {
TZ_WARN(ERROR_DATA_VALUE);
return 0;
}
double length = Coordinate_3d_Norm(coord);
/* the cross product is 0 if the two planes are parallel. Here we use
* 0.001 as the threshold for rounding error. */
if (length < 0.001) {
return 0;
} else {
Coordinate_3d_Scale(coord, circle->radius / length);
}
//Geo3d_Translate_Coordinate(coord, coord + 1, coord + 2, circle->center[0],
// circle->center[1], circle->center[2]);
return 1;
}
int Geo3d_Unit_Circle_Plane_Point(const xz_orientation_t circle_ort,
const xz_orientation_t plane_ort,
int direction,
coordinate_3d_t coord)
{
if (direction == 1) {
Xz_Orientation_Cross(circle_ort, plane_ort, coord);
} else if (direction == -1) {
Xz_Orientation_Cross(plane_ort, circle_ort, coord);
} else {
TZ_WARN(ERROR_DATA_VALUE);
return 0;
}
double length = Coordinate_3d_Norm(coord);
/* the cross product is 0 if the two planes are paralle. Here we use
* 0.001 as the threshold for rounding error. */
if (length < 0.001) {
return 0;
} else {
Coordinate_3d_Scale(coord, 1.0 / length);
}
return 1;
}
coordinate_3d_t*
Geo3d_Circle_Array_Points(const Geo3d_Circle *circle, int ncircle,
int npt_per_c, coordinate_3d_t *pts)
{
int nsample = npt_per_c;
if (pts == NULL) {
pts = (coordinate_3d_t *)
Guarded_Malloc(sizeof(coordinate_3d_t) * ncircle * npt_per_c,
"Geo3d_Circle_Array_Points");
}
coordinate_3d_t *pts_head = pts;
const Geo3d_Circle *bottom = &(circle[0]);
const Geo3d_Circle *top = &(circle[1]);
coordinate_3d_t plane_normal;
Xz_Orientation_Cross(bottom->orientation, top->orientation, plane_normal);
Coordinate_3d_Unitize(plane_normal);
xz_orientation_t plane_ort;
/* 0.001 is picked to test if two vectors are parallel */
if (Coordinate_3d_Norm(plane_normal) < 0.001) {
/* pick a plane that is not parallel to the circles */
plane_ort[0] = bottom->orientation[0] + TZ_PI_2;
plane_ort[1] = bottom->orientation[1];
} else {
Geo3d_Normal_Orientation(plane_normal[0], plane_normal[1],
plane_normal[2], plane_ort, plane_ort + 1);
}
coordinate_3d_t start1;
Geo3d_Circle_Plane_Point(bottom, plane_ort, 1, start1);
Geo3d_Circle_Points(bottom, nsample, start1, pts);
coordinate_3d_t start2;
Geo3d_Circle_Plane_Point(top, plane_ort, 1, start2);
pts += nsample;
Geo3d_Circle_Points(top, nsample, start2, pts);
int i;
for (i = 1; i < ncircle - 1; i++) {
bottom = &(circle[i]);
top = &(circle[i + 1]);
Xz_Orientation_Cross(bottom->orientation, top->orientation, plane_normal);
Coordinate_3d_Unitize(plane_normal);
if (Coordinate_3d_Norm(plane_normal) < 0.001) {
/* pick a plane that is not parallel to the circles */
plane_ort[0] = bottom->orientation[0] + TZ_PI_2;
plane_ort[1] = bottom->orientation[1];
} else {
Geo3d_Normal_Orientation(plane_normal[0], plane_normal[1],
plane_normal[2], plane_ort, plane_ort + 1);
}
Geo3d_Circle_Plane_Point(bottom, plane_ort, 1, start1);
double angle = Geo3d_Circle_Vector_Angle(bottom, start1, start2);
Geo3d_Circle_Plane_Point(top, plane_ort, 1, start2);
Geo3d_Circle_Rotate_Vector(top, angle, start2);
pts += nsample;
Geo3d_Circle_Points(top, nsample, start2, pts);
}
return pts_head;
}
Geo3d_Circle* Make_Geo3d_Circle_Array(int n)
{
Geo3d_Circle *circle = (Geo3d_Circle *)
Guarded_Malloc(sizeof(Geo3d_Circle) * n, "Make_Geo3d_Circle_Array");
int i;
for (i = 0; i < n; i++) {
Geo3d_Circle_Default(circle + i);
}
return circle;
}
void Geo3d_Circle_Swc_Fprint(FILE *fp, const Geo3d_Circle *circle,
int id, int parent_id)
{
Geo3d_Circle_Swc_Fprint_Z(fp, circle, id, parent_id, 1.0);
}
void Geo3d_Circle_Swc_Fprint_T(FILE *fp, const Geo3d_Circle *circle,
int id, int parent_id, int type, double z_scale)
{
Swc_Node cell;
cell.id = id;
cell.type = type;
cell.d = circle->radius;
cell.x = circle->center[0];
cell.y = circle->center[1];
cell.z = circle->center[2];
if (z_scale != 1.0) {
cell.z /= z_scale;
}
cell.parent_id = parent_id;
Swc_Node_Fprint(fp, &cell);
}
void Geo3d_Circle_Swc_Fprint_Z(FILE *fp, const Geo3d_Circle *circle, int id,
int parent_id, double z_scale)
{
Geo3d_Circle_Swc_Fprint_T(fp, circle, id, parent_id, 2, z_scale);
}
Swc_Node* Geo3d_Circle_To_Swc_Node(const Geo3d_Circle *circle,
int id, int parent_id, double z_scale,
int type, Swc_Node *node)
{
if (node == NULL) {
node = New_Swc_Node();
}
if (circle->radius <= 0.0) {
/* virtual node for a circle with invalid size */
node->id = -1;
} else {
node->id = id;
}
node->type = type;
node->d = circle->radius;
node->x = circle->center[0];
node->y = circle->center[1];
node->z = circle->center[2];
if (z_scale != 1.0) {
node->z /= z_scale;
}
node->parent_id = parent_id;
return node;
}
|
C | #ifndef BOARD_H
#define BOARD_H
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <math.h>
#include "chess_errors.h"
#include "position.h"
#include "../pieces/pieces.h"
#define True 1
#define False 0
#define DIMENSIONS 8
typedef uint8_t Bool;
typedef struct Board
{
uint32_t row[DIMENSIONS];
} Board;
Board *create_board();
Piece get_piece(Board *board, int8_t row, int8_t column);
Bool remove_piece(Board *board, int8_t row, int8_t column);
Bool move_piece(Board *board, Position *from, Position *to);
CellType get_cell_type(Piece piece);
Bool is_valid_move(Board *board, Piece piece, Position *from, Position *to);
Bool is_taking_piece(Piece piece, Piece next_piece);
void print_chess_piece(Piece piece);
void print_hex_board(Board *board);
void print_condenced_hex_board(Board *board);
void pretty_print_board(Board *board);
#endif
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
// ENUM é tipo de dado definido pelo usuário que define uma variável que vai receber apenas um conjunto restrito de valores.
// Representa um conjunto de valores inteiros representados por identificadores.
typedef enum boolean{false=0, true=1} Boolean;
// O comando typedef é usado para criar “sinônimo” ou um “alias” para tipos de dados existentes.
// TipoElemento e int são sinônimos a partir desta definição. Quando for necessário manipular outro tipo de dado, basta alterar essa definição.
typedef int TipoElemento;
typedef struct{
TipoElemento* array;
int tamVetor;
int qtdeElementos;
}Vetor;
/**
* Cria e inicializa a struct Vetor.
* RETORNO: endereço da struct Vetor criada e inicializada na memória HEAP
*/
Vetor* vet_criar(int tamVetor);
/**
* Insere o elemento na última posição do vetor.
* Parâmetro v: Ponteiro para a struct Vetor em que o elemento será inserido.
* Parâmetro elemento: Elemento a ser inserido.
* RETORNO: true se a inserção foi realizada com sucesso e false caso contrário
*/
Boolean vet_inserirFim(Vetor* v, TipoElemento elemento);
/**
* Insere um elemento em uma determinada posição.
* Parâmetro v: Ponteiro para a struct Vetor em que o elemento será inserido.
* Parâmetro elemento: Elemento a ser inserido.
* Parâmetro posicao: Posição em que o elemento deve ser inserido.
* RETORNO: true se a inserção foi realizada com sucesso e false caso contrário
*/
Boolean vet_inserir(Vetor* v, TipoElemento elemento, int posicao);
/**
* Substitui o valor de uma determinada posição do Vetor.
* Parâmetro v: Ponteiro para a struct Vetor.
* Parâmetro posicao: Posição a ser alterada.
* Parâmetro novoElemento: elemento a ser atribuido na posição.
* RETORNO: true se a alteração foi realizada com sucesso e false caso contrário
*/
Boolean vet_substituir(Vetor* v, int posicao, TipoElemento novoElemento);
/**
* USANDO A ESTRATÉGIA DO SCANF
* Remove o elemento de uma determinada posição do vetor .
* Parâmetro v: Ponteiro para a struct Vetor.
* Parâmetro posicao: posição a ser removida.
* Parâmetro endereco: endereço a ser utilizado para a copiar o valor do elemento removido.
* RETORNO: true se a inserção foi realizada com sucesso e false caso contrário
*/
Boolean vet_removerPosicao(Vetor* v, int posicao, TipoElemento* endereco);
/**
* Remove um determinado elemento do vetor .
* Parâmetro v: Ponteiro para a struct Vetor.
* Parâmetro elemento: elemento a ser removido.
* RETORNO: posição do elemento removido
*/
int vet_removerElemento(Vetor* v, TipoElemento elemento);
/**
* Devolve a quantidade de elementos do vetor.
* Parâmetro v: Ponteiro para a struct Vetor.
* RETORNO: quantidade de elementos do vetor
*/
int vet_tamanho(Vetor* v);
/**
* USANDO A ESTRATÉGIA DO SCANF
* Pesquisa o elemento armazenado em uma determinada posição do Vetor.
* Parâmetro v: Ponteiro para a struct Vetor.
* Parâmetro posicao: posicao a ser encontrada.
* Parâmetro saida: Endereço de memória onde a função deve armazenar o elemento encontrado.
* RETORNO: Se a posição for válida, realiza a cópia no endereço recebido por parâmetro SAIDA e devolve true.
* Caso contrário, devolve false
*/
Boolean vet_elemento(Vetor* v, int posicao, TipoElemento* saida);
/**
* Pesquisa a posição de um determinado elemento no Vetor.
* Parâmetro v: Ponteiro para a struct Vetor.
* Parâmetro elemento: elemento a ser procurado.
* RETORNO: Se encontrado, devolve a posição do elemento no vetor; caso contrário devolve -1
*/
int vet_posicao(Vetor* v, TipoElemento elemento);
/**
* Imprimir os elementos do vetor
* Parâmetro v: Ponteiro para a struct Vetor.
*/
void vet_imprimir(Vetor* v);
/**
* Destruir/Desalocar o vetor na memória HEAP
* Parâmetro v: Ponteiro para a struct Vetor.
*/
void vet_destruir(Vetor* v);
/**
* Escreve no endereço recebido por parâmetro uma versão string do vetor
* Parâmetro v: Ponteiro para a struct Vetor.
* Parâmetro endereco: endereço da região de memória onde a função deverá copiar os caracteres.
* RETORNO: true se a cópia foi realizada com sucesso e false caso contrário
*/
Boolean vet_toString(Vetor* v, char* enderecoString);
/**
* Verifica e aumenta a capacidade de armazenamento de acordo com a quantidade de elementos
*/
void verifica_aumenta(Vetor* v);
/**
* Verifica e diminui a capacidade de armazenamento de acordo com a quantidade de elementos
*/
void verifica_diminui(Vetor* v);
/**
* Cria um clone do vetor passado por parâmetro
* Parâmetro v: Endereço da struct Vetor a ser clonado.
* RETORNO: endereço da cópia da struct Vetor
*/
Vetor* vet_clone(Vetor* v);
/**
* Ordena o vetor com o algoritmos bubble sort.
* Parâmetro v: Ponteiro para a struct Vetor.
*/
void vet_ordenarBuble(Vetor* v);
/**
* Ordena o vetor com o algoritmos selection sort.
* Parâmetro v: Ponteiro para a struct Vetor.
*/
void vet_ordenarSelection(Vetor* v);
/**
* Ordena o vetor com o algoritmos selection sort de forma decrescente.
* Parâmetro v: Ponteiro para a struct Vetor.
*/
void vet_ordenarSelectionDesc(Vetor* v);
void vet_ordenarSelection_parcial(Vetor* v, int percentual);
/**
* Ordena o vetor com o algoritmos insertion sort.
* Parâmetro v: Ponteiro para a struct Vetor.
*/
void vet_ordenarInsertion(Vetor* v);
/**
* Pesquisa a posicao do elemento n no vetor usando a estratégia de busca binária.
* Parâmetro v: Ponteiro para a struct Vetor.
* Parâmetro elemento: elemento a ser procurado.
* RETORNO: Se encontrado, devolve a posição do elemento no vetor e -1 caso contrário
*/
int vet_buscaBinaria(Vetor* v, TipoElemento elemento);
/**
* Faz a leitura do arquivo, criando e preenchendo o TAD vetor com o conteúdo contido no arquivo.
* Parâmetro nomeArquivo: nome do arquivo
* RETORNO: endereço da struct Vetor criada, caso não seja possível realizar a importação, devolve NULL
*/
Vetor* vet_importar(char* nomeArquivo);
/**
* Faz a cópia dos elementos do vetor para um arquivo texto.
* Parâmetro v: Ponteiro para a struct Vetor.
* Parâmetro nomeArquivo: nome do arquivo a ser criado.
* RETORNO: Se encontrado, devolve a posição do elemento no vetor e -1 caso contrário
*/
Boolean vet_exportar(Vetor* v, char* nomeArquivo);
/**
* Cria o TAD com um tamanho específico e inicializa a estrutura preenchendo todas as posições com valores aleatórios.
* Parâmetro tam: Tamanho do vetor / quantidade de elementos.
* RETORNO: endereço da struct Vetor criada e inicializada
*/
Vetor* vet_criarAleatorio(int tam);
/**
* Cria o TAD com um tamanho específico e inicializa a estrutura preenchendo todas as posições com valores ordenados de forma ascendente.
* Parâmetro tam: Tamanho do vetor / quantidade de elementos.
* RETORNO: endereço da struct Vetor criada e inicializada
*/
Vetor* vet_criarAscendente(int tam);
/**
* Cria o TAD com um tamanho específico e inicializa a estrutura preenchendo todas as posições com valores ordenados de forma descendente.
* Parâmetro tam: Tamanho do vetor / quantidade de elementos.
* RETORNO: endereço da struct Vetor criada e inicializada
*/
Vetor* vet_criarDescendente(int tam);
/**
* Cria e inicializa a struct Vetor com valores parcialmente ordenados.
* Parâmetro tam: Tamanho do vetor / quantidade de elementos.
* Parâmetro percentual: Percentual do vetor que deve estar ordenado.
* RETORNO: endereço da struct Vetor criada e inicializada
*/
Vetor* vet_criarAscendenteParcial(int tam, int percentual);
//Converte a posicao negativa para uma inversa positiva
int negativeToPositive(Vetor* v, int posicao);
//Converte um numero inteiro para string ou char
char* itoa(int val, int base);
void shiftLeft(Vetor* v, int posicao);
|
C | #include <stdio.h>
#include <string.h>
int main() {
char c1[1024], c2[1024], temp[1024];
int pos;
scanf("%s %s %d", c1, c2, &pos);
for (int i = 1; i < pos; i++) {
strcpy(temp, c1);
strcpy(c1, c2);
strcpy(c2, temp);
strcat(c2, c1);
}
printf("%s", c1);
return 0;
}
|
C | #include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <fcntl.h>
#include "functions.h"
#include <sys/file.h>
void* reader(void *result){
int i, fd;
int aux = NUMBER_OF_LINES*POSITION_OF_NEWLINE;
int lineCounter=0;
char currentChar;
char* buf = (char*)malloc(sizeof(char)*(aux+1));
char* file = fileSelector();
if((fd = open(file, O_RDONLY)) < 0){
perror("Cannot open file");
exit(-1);
}
if(flock(fd, LOCK_SH) < 0){
perror("Failed to lock file");
exit(-1);
}
if((read(fd, buf, aux)) < 0){
perror("Failed to read file");
exit(-1);
}
if(validLetter(buf[0])){
for(i=0; lineCounter < NUMBER_OF_LINES; i++){
if(i%POSITION_OF_NEWLINE != NUMBER_OF_LETTERS){
if(buf[i]!=buf[0]) {
*((int*)result) = -1;
pthread_exit(result);
}
}else{
if(buf[i] != '\n') {
*((int*)result) = -1;
pthread_exit(result);
}
lineCounter++;
}
}
if(!read(fd, buf, aux)){
if(flock(fd, LOCK_UN) < 0){
perror("Failed to unlock file");
exit(-1);
}
if((close(fd))< 0){
perror("Failed to close file");
exit(-1);
}
*((int*)result) = 0;
pthread_exit(result);
}else{
*((int*)result) = -1;
pthread_exit(result);
}
}else{
*((int*)result) = -1;
pthread_exit(result);
}
}
int main(int argc, char *argv[]){
int i;
int result[NUMBER_OF_THREADS];
pthread_t tid[NUMBER_OF_THREADS];
void* status;
srand(time(NULL));
for(i = 0; i < NUMBER_OF_THREADS; i++){
if(pthread_create(&tid[i], NULL, reader, &result[i]) != 0){
perror("Failed to create thread");
exit(-1);
}else
printf("Foi criada a tarefa %d\n", (int)tid[i]);
}
for(i = 0; i < NUMBER_OF_THREADS; i++){
pthread_join(tid[i], &status);
printf("A tarefa %d terminou e devolveu:%d\n", (int)tid[i], result[i]);
}
exit(0);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf_countxX.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rvan-aud <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/28 15:08:49 by rvan-aud #+# #+# */
/* Updated: 2021/05/12 17:37:14 by rvan-aud ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
#include <stdio.h>
void ft_rev_int_tab(char *tab, int size)
{
int i;
char temp;
temp = 0;
i = 0;
while (size != 0 && i < size / 2)
{
temp = tab[i];
tab[i] = tab[(size - 1) - i];
tab[(size - 1) - i] = temp;
i++;
}
}
char convhex(int mod, int cap)
{
if (mod <= 9 && mod >= 0)
return (mod + '0');
else if (cap == 0)
return (mod - 10 + 'a');
else
return (mod - 10 + 'A');
}
static int convnwrite(unsigned int nb, char *result, int cap, t_flags *flags)
{
int i;
int mod;
i = 0;
while (nb > 0)
{
mod = nb % 16;
result[i++] = convhex(mod, cap);
nb = nb / 16;
}
result[i] = '\0';
i = ft_strlen(result);
ft_rev_int_tab(result, i);
i = 0;
while (i < 9)
{
flags->resultxX[i] = result[i];
i++;
}
return (ft_strlen(result));
}
void countnputnbrhex(va_list ap, int cap, int *count, t_flags *flags)
{
char result[9];
int nb;
nb = va_arg(ap, int);
flags->valuxX = (unsigned int)nb;
if (nb == 0)
{
flags->resultxX[0] = '0';
flags->resultxX[1] = '\0';
(*count)++;
return ;
}
*count += convnwrite((unsigned int)nb, result, cap, flags);
}
|
C | #include "helper.h"
#include <stdlib.h>
#include <string.h>
int rand_int(const int min, const int max)
{
int ret;
do {
ret = min + rand() / ((RAND_MAX + 1u) / (max - min + 1));
} while (ret > max);
return ret;
}
char *strip_newline(char *const restrict str)
{
str[strcspn(str, "\n")] = '\0';
return str;
}
|
C | #include "open_lock.h"
#include "send_data.h"
#include "rece_data.h"
#include "check_protocol.h"
static unsigned char check_data[5] = {0xFC,0x01,0x01,0xCC,0x01};
void check_data_init()
{
check_data[0] = CHECK_PROTOCOL_FIR;
check_data[1] = CHECK_BOARD_ADDR_INIT;
check_data[2] = CHECK_LOCK_ADDR_INIT;
check_data[3] = CHECK_PROTOCOL_SEC;
check_data[4] = check_data[0]^check_data[1]^check_data[2]^check_data[3];
}
int check_protocol(int addr, int data[])
{
int fd = 0;
int ret = 0;
fd = open_serial();
if(fd < 0)
{
printf("the serial is error!");
return -1;
}
check_data[1] = addr;
check_data[4] = check_data[0]^check_data[1]^check_data[2]^check_data[3];
//Ϳָ...
ret = send_data(fd, check_data);
if(ret != 0)
{
printf("Send_data is failure!!\n");
close_serial(fd);
return -1;
}
//շص
ret = rece_data(fd, data);
if(ret != RECE_DATA_LEN)
{
printf("Receive data is failure!!\n");
close_serial(fd);
return -1;
}
close_serial(fd);
return ret;
}
|
C | //B171381
//Implementation of queue using doublelinkedlist
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next,*prev;
};
struct node *top=NULL;
struct node* push(int ele);
struct node* pop();
void display();
void main()
{
int ele,ch;
printf("1.push\n2.pop\n3.display\n4.exit\n");
do
{
printf("enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
printf("enter the element to be inserted:");
scanf("%d",&ele);
push(ele);
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
break;
}
default:
{
printf("invalid choice\n");
break;
}
}
}
while(ch!=4);
}
struct node* push(int ele)
{
struct node *newnode;
newnode->data=ele;
newnode->next=NULL;
if(top==NULL)
{
top=newnode;
top->prev=NULL;
}
else
{
top->next=newnode;
newnode->prev=top;
top=newnode;
}
}
struct node* pop()
{
struct node *temp;
if(top==NULL)
{
printf("list is empty");
}
else
{
temp=top;
top=top->prev;
top->next=NULL;
printf("the deleted node is %p-%d-%p\n",temp->prev,temp->data,temp->next);
free(temp);
}
return top;
}
void display()
{
if(top==NULL)
{
printf("stack is empty\n");
}
else
{
while(top!=NULL)
{
printf("%p-%d-%p\n",top->prev,top->data,top->next);
top=top->prev;
}
}
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* support.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jmunoz <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/10/13 17:16:07 by jmunoz #+# #+# */
/* Updated: 2016/11/25 22:31:25 by jmunoz ### ########.fr */
/* */
/* ************************************************************************** */
#include "../Includes/ft_select.h"
/*
** Fonction qui ouvre un nouveau terminal le programme va ecrire.
*/
int open_fd(void)
{
int tty;
char *tmp;
tmp = ttyname(STDIN_FILENO);
if ((tty = open(tmp, O_WRONLY)) < 0)
{
free(tmp);
exit (-1);
}
free(tmp);
return (tty);
}
/*
** Fonction qui sauvegarde et restitue meta.
*/
t_meta *get_meta(t_meta *meta)
{
static t_meta *save = NULL;
if (meta)
save = meta;
return (save);
}
/*
** Fonction qui sauvegarde et restitue le fd du tty sur lequel le prog ecrit.
*/
int get_fd(int fd)
{
static int save = -1;
if (save < 0)
{
save = fd;
return (0);
}
else
return (save);
}
/*
** Fonction qui set la couleur appropriee (en fonction de la nature du fichier)
** et reset la couleur de base.
*/
void ft_set_color(size_t content_size)
{
static char set = 0;
if (!set)
{
if (S_ISDIR(content_size))
ft_putstr(ANSI_COLOR_CYAN);
else if (S_ISLNK(content_size))
ft_putstr(ANSI_COLOR_YELLOW);
else if (S_ISREG(content_size) && 00100 & content_size)
ft_putstr(ANSI_COLOR_GREEN);
else if (S_ISCHR(content_size))
ft_putstr(ANSI_COLOR_BLUE);
else if (S_ISBLK(content_size))
ft_putstr(ANSI_COLOR_RED);
else if (S_ISFIFO(content_size))
ft_putstr(ANSI_COLOR_MAGENTA);
else if (S_ISSOCK(content_size))
ft_putstr(ANSI_COLOR_MAGENTA);
}
else
ft_putstr(ANSI_COLOR_RESET);
set ^= 1;
}
/*
** Fonction permettant d'utiliser les termcaps.
*/
int fputchar(int c)
{
int fd;
fd = get_fd(0);
write(fd, &c, 1);
return (c);
}
|
C | #include<stdio.h>
int main(void)
{
long unsigned int *p = NULL;
printf("%d\n",sizeof(*p));
}
//(typedef int *ptr; ptr p =NULL;)
//(sizeof(all type *)=4,
|
C | #include <stdio.h>
#include <unistd.h>
#include <malloc.h>
#include <pthread.h>
#include <mqueue.h>
#include "peripherals_manager.h"
#include "common.h"
#define MAX_MSG_SIZE 256
// queue descriptor
mqd_t pm_queue;
// array for queue elements
pm_message rcvd_msgs[PANIC_TREAD_QUEUE_SIZE];
int last_msg_index = 0;
void *pm_thread(void* threadid)
{
char rcvd_msg[MAX_MSG_SIZE];
int msg_prio = 0;
results res = ERROR;
pm_message* msg;
printf("inside pm thread\r\n");
while (1)
{
res = mq_receive(pm_queue, rcvd_msg, MAX_MSG_SIZE, &msg_prio);
if (res == -1)
{
perror("mq rec error");
usleep(MSEC_TO_USEC(250));
continue;
}
if (rcvd_msg == NULL)
{
printf("rcved msg is null");
}
msg = (pm_message*)rcvd_msg;
printf("msg id: %u, data: %u\r\n", msg->data, msg->id);
}
}
results peripherals_manager_init(void)
{
results rc = ERROR;
pthread_t pm_thread_t;
struct mq_attr attr;
struct mq_attr mq_attr_ret;
printf("Creating pm thread\r\n");
rc = pthread_create(&pm_thread_t, NULL, pm_thread, NULL);
if (rc != 0)
{
printf("error creating pm thread rc:%u", rc);
return rc;
}
else
{
printf("success creating thread\r\n");
}
printf("create pm queue\r\n");
attr.mq_flags = 0;
attr.mq_maxmsg = 10;
attr.mq_msgsize = MAX_MSG_SIZE;
attr.mq_curmsgs = 0;
// queue name should be initialized with /
pm_queue = mq_open("/pm_queue", O_CREAT | O_RDWR, 0666, &attr);
if (pm_queue < 0)
{
printf("error creating queue %u\r\n", pm_queue);
return QUEUE_ERROR;
}
else
{
printf("queue create success\r\n");
}
mq_getattr(pm_queue, &mq_attr_ret);
printf("pm_queue attr %lu, %lu\r\n", mq_attr_ret.mq_msgsize, mq_attr_ret.mq_maxmsg);
return SUCCESS;
}
results peripherals_manager_push_to_queue(pm_message buffer)
{
// default prio of messages is 0
rcvd_msgs[last_msg_index].data = buffer.data;
rcvd_msgs[last_msg_index].id = buffer.id;
if (0 == mq_send(pm_queue, (const char*)&rcvd_msgs[last_msg_index], MAX_MSG_SIZE, 0))
{
last_msg_index++;
if (last_msg_index >= PANIC_TREAD_QUEUE_SIZE)
{
last_msg_index = 0;
}
//return SUCCESS;
}
else
{
perror("push to pm queue failed");
return ERROR;
}
} |
C | //
// Created by william on 2018/12/4.
//
#include "select.h"
#include "sort_check.h"
#include "sort_tool.h"
void extremum(ElementType const arr[], int lo, int hi, int *max, int *min) {
*max = *min = lo;
ElementType v = arr[hi];
while (lo <= hi) {
if (compare(v, arr[*min]) <= 0) *min = hi;
if (compare(arr[*max], v) <= 0) *max = hi;
v = arr[--hi];
}
}
void select_sort(ElementType arr[], unsigned int len) {
int j = len;
int max = 0, min = 0;
while (len / 2 < j--) {
int i = len - j - 1;
extremum(arr, i, j, &max, &min);
swap(arr[i], arr[min]);
//处理最大值为i的情况
if (max == i) max = min;
swap(arr[j], arr[max]);
}
}
int main() {
ElementType a[] = {1118, 7, 17, 9, 6, 1, 32, 3, 5, 6, 43, 2, 13, 23, 8, 1, 44, 55, 22, 43, 66, 123, 456, 42};
select_sort(a, sizeof(a) / sizeof(ElementType));
printf("%d\n", check_sorted(a, sizeof(a) / sizeof(ElementType)));
print_arr(a, sizeof(a) / sizeof(int));
}
|
C | #include <stdlib.h>
#include "hw1.h"
#include "debug.h"
#include "pcipher.h"
#include "fcipher.h"
#ifdef _STRING_H
#error "Do not #include <string.h>. You will get a ZERO."
#endif
#ifdef _STRINGS_H
#error "Do not #include <strings.h>. You will get a ZERO."
#endif
#ifdef _CTYPE_H
#error "Do not #include <ctype.h>. You will get a ZERO."
#endif
int main(int argc, char **argv)
{
unsigned short mode;
mode = validargs(argc, argv);
debug("Mode: 0x%X", mode);
if(mode == 0x8000) {
USAGE(*argv, EXIT_SUCCESS);
return EXIT_SUCCESS;
}
if(mode == 0x0000){
USAGE(*argv, EXIT_FAILURE);
return EXIT_FAILURE;
}
else{ //EITHER A POLYBIUS CIPHER OR A FRACTIONATED CIPHER
if((mode & 0x4000) == 0x4000){ //CHECK IF SECOND MSB IS SET. IF SET, IT IS AN -f CIPHER
//CALL -f CIPHER HELPER METHOD IN SEPARATE C FILE.
if((mode & 0x2000) == 0x2000){ //CHECK IF THIRD MSB IS SET. IF SET, THEN IT IS A -d DECODE.
//IT IS A DECODE.
int result = fDecode(mode);
if(result == 1){
return EXIT_FAILURE;
}
else{
return EXIT_SUCCESS;
}
}
else{
//IT IS AN ENCODE.
int result = fEncode(mode);
if(result == 1){
return EXIT_FAILURE;
}
else{
return EXIT_SUCCESS;
}
}
}
else{ //OTHERWISE IT HAS TO BE A -p CIPHER
//CALL -p CIPHER HELPER METHOD IN SEPARATE C FILE.
createPTable(mode);
if((mode & 0x2000) == 0x2000){ //CHECK IF THIRD MSB IS SET. IF SET, THEN IT IS A -d DECODE.
//IT IS A DECODE.
pDecode(mode);
}
else{
//IT IS AN ENCODE.
int result = pEncode(mode);
if(result == 1){
return EXIT_FAILURE;
}
else{
return EXIT_SUCCESS;
}
}
}
// printf("%d\n", mode);
// printf("%s\n", key);
}
}
/*
* Just a reminder: All non-main functions should
* be in another file not named main.c
*/ |
C | #include<stdio.h>
#include<stdlib.h>
void display(int a1[],int n)
{ int i;
for(i=0;i<n;i++)
printf("%d ",a1[i]);
printf("\n");
}
int* getRecord(int s_size, int* s, int *result_size)
{
int i,c=0,d=0,size=2;
int *a1,*a2;
a1=(int *)malloc(sizeof(int)*s_size);
a2=(int *)malloc(sizeof(int)*s_size);
a1[0]=a2[0]=s[0];
for(i=1; i<s_size; i++)
{
if(a1[i-1]<s[i])
{ a1[i]=s[i];
c++;
}
else
a1[i]=a1[i-1];
if(a2[i-1]>s[i])
{ a2[i]=s[i];
d++;
}
else
a2[i]=a2[i-1];
}
*result_size=&size;
int *cur=(int *)malloc(sizeof(int)*2);
cur[0]=c;
cur[1]=d;
display(a1,s_size);
display(a2,s_size);
return cur;
}
int main() {
int n;
scanf("%d",&n);
int *s = malloc(sizeof(int) * n);
for(int s_i = 0; s_i < n; s_i++){
scanf("%d",&s[s_i]);
}
int result_size;
int* result = getRecord(n, s, &result_size);
printf("--------------");
for(int i = 0; i < result_size; i++) {
if (i) {
printf(" ");
}
printf("%d", result[i]);
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ncurses.h>
#include <sys/stat.h>
#include "ftlsg.h"
int main(int argc, char **argv)
{
// variables required to read file
FILE *file;
char *buffer;
char argbuffer[256];
unsigned long fileLen;
SAVEGAME save;
//
// VERIFY THAT FILE EXISTS
//
// note! this code allows for buffer overflow!
struct stat sb;
if (argc > 1)
{
strcpy(argbuffer, argv[1]);
if (stat(argbuffer, &sb) != 0)
{
fprintf(stderr, "ERROR! File not found!\n");
return 1;
}
}
else
{
strcpy(argbuffer, argv[0]);
usage(argbuffer);
return 1;
}
//
// READ FILE
//
file = fopen(argbuffer, "rb");
if (!file) // verify that we can open the file
{
fprintf(stderr, "ERROR! Unable to open file!");
fclose(file);
return 1;
}
// get file length
fseek(file, 0, SEEK_END);
fileLen=ftell(file);
fseek(file, 0, SEEK_SET);
buffer=(char *)malloc(fileLen+1);
if (!buffer)
{
fprintf(stderr, "ERROR! Out of memory!\n");
return 1;
}
fread(buffer, fileLen, 1, file);
if (read_4_le_bytes_as_int(buffer, 0) != 2) // simple file format verification
{
fprintf(stderr, "ERROR! Not an FTL savegame!\n");
return 1;
}
parse_data(&save, buffer, fileLen);
//print_data(&save);
user_input(&save);
save_data(&save);
fclose(file);
// garbage collection
free(buffer);
free(save.ss_name);
free(save.ss_type);
free(save.ss_type2);
free(save.ss_name2);
free(save.ss_class);
free(save.remaining);
free(save.events);
return 0;
}
void parse_data(SAVEGAME *save, char *buffer, unsigned long fileLen)
{
int adrp = 0;
(*save).unkn1 = read_4_le_bytes_as_int(buffer, (adrp));
(*save).unkn2 = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).unkn3 = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).unkn4 = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).unkn5 = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).max_crew = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).ss_name_len = read_4_le_bytes_as_int(buffer, (adrp+=4));
// allocate memory for ship name and parse
(*save).ss_name=(char *)malloc((*save).ss_name_len+1);
adrp+=4;
for (int i=0; i<(*save).ss_name_len+1;i++)
{
(*save).ss_name[i] = (char)buffer[adrp+i];
}
(*save).ss_name[(*save).ss_name_len] = '\0';
(*save).ss_type_len = read_4_le_bytes_as_int(buffer, (adrp+=(*save).ss_name_len));
// allocate memory for ship type and parse
(*save).ss_type=(char *)malloc((*save).ss_type_len+1);
adrp+=4;
for (int i=0; i<(*save).ss_type_len+1;i++)
{
(*save).ss_type[i] = (char)buffer[adrp+i];
}
(*save).ss_type[(*save).ss_type_len] = '\0';
(*save).unkn6 = read_4_le_bytes_as_int(buffer, (adrp+=(*save).ss_type_len));
(*save).unkn7 = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).max_events = read_4_le_bytes_as_int(buffer, (adrp+=4));
// parse all events
(*save).events = (EVENT *)malloc(sizeof(EVENT)*(*save).max_events);
for (int i=0; i<(*save).max_events; i++)
{
(*save).events[i].name_len = read_4_le_bytes_as_int(buffer, (adrp+=4));
adrp+=4;
for (int j=0; j<((*save).events[i].name_len);j++)
{
(*save).events[i].name[j] = (char)buffer[adrp+j];
}
(*save).events[i].name[(*save).events[i].name_len] = '\0';
adrp+=(*save).events[i].name_len;
(*save).events[i].value = read_4_le_bytes_as_int(buffer, (adrp));
}
(*save).ss_type2_len = read_4_le_bytes_as_int(buffer, (adrp+=4));
// allocate memory for ship type (again) and parse
(*save).ss_type2=(char *)malloc((*save).ss_type2_len+1);
adrp+=4;
for (int i=0; i<(*save).ss_type_len+1;i++)
{
(*save).ss_type2[i] = (char)buffer[adrp+i];
}
(*save).ss_type2[(*save).ss_type_len] = '\0';
(*save).ss_name2_len = read_4_le_bytes_as_int(buffer, (adrp+=(*save).ss_type2_len));
// allocate memory for ship type (again) and parse
(*save).ss_name2=(char *)malloc((*save).ss_name2_len+1);
adrp+=4;
for (int i=0; i<(*save).ss_name2_len+1;i++)
{
(*save).ss_name2[i] = (char)buffer[adrp+i];
}
(*save).ss_name2[(*save).ss_name2_len] = '\0';
(*save).ss_class_len = read_4_le_bytes_as_int(buffer, (adrp+=(*save).ss_name2_len));
(*save).ss_class=(char *)malloc((*save).ss_class_len+1);
adrp+=4;
for (int i=0; i<(*save).ss_class_len+1;i++)
{
(*save).ss_class[i] = (char)buffer[adrp+i];
}
(*save).ss_class[(*save).ss_class_len] = '\0';
(*save).start_crew_len = read_4_le_bytes_as_int(buffer, (adrp+=(*save).ss_class_len));
adrp+=4;
// parse all starting crew
(*save).start_crew = (CREW *)malloc(sizeof(CREW)*(*save).start_crew_len);
for (int i=0; i<(*save).start_crew_len; i++)
{
(*save).start_crew[i].race_len = read_4_le_bytes_as_int(buffer, (adrp));
adrp+=4;
for (int j=0; j<((*save).start_crew[i].race_len);j++)
{
(*save).start_crew[i].race[j] = (char)buffer[adrp+j];
}
(*save).start_crew[i].race[(*save).start_crew[i].race_len] = '\0';
adrp+=(*save).start_crew[i].race_len;
(*save).start_crew[i].name_len = read_4_le_bytes_as_int(buffer, (adrp));
adrp+=4;
for (int j=0; j<((*save).start_crew[i].name_len);j++)
{
(*save).start_crew[i].name[j] = (char)buffer[adrp+j];
}
(*save).start_crew[i].name[(*save).start_crew[i].name_len] = '\0';
adrp+=(*save).start_crew[i].name_len;
}
(*save).ss_integrity = read_4_le_bytes_as_int(buffer, (adrp));
(*save).ss_fuel = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).ss_missiles = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).ss_droids = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).scrap = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew_len = read_4_le_bytes_as_int(buffer, (adrp+=4));
// parse all current crew
(*save).current_crew = (CREW *)malloc(sizeof(CREW)*(*save).current_crew_len);
for (int i=0; i<(*save).current_crew_len; i++)
{
(*save).current_crew[i].name_len = read_4_le_bytes_as_int(buffer, (adrp+=4));
adrp+=4;
for (int j=0;j<(*save).current_crew[i].name_len;j++)
{
(*save).current_crew[i].name[j] = (char)buffer[adrp+j];
}
(*save).current_crew[i].name[(*save).current_crew[i].name_len] = '\0';
adrp+=(*save).current_crew[i].name_len;
(*save).current_crew[i].race_len = read_4_le_bytes_as_int(buffer, (adrp));
adrp+=4;
for (int j=0; j<((*save).current_crew[i].race_len);j++)
{
(*save).current_crew[i].race[j] = (char)buffer[adrp+j];
}
(*save).current_crew[i].race[(*save).current_crew[i].race_len] = '\0';
adrp+=(*save).current_crew[i].race_len;
(*save).current_crew[i].unkn1 = read_4_le_bytes_as_int(buffer, (adrp));
(*save).current_crew[i].health = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].x_coord = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].y_coord = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].room = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].room_tile = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].unkn7 = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].skill_pilot = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].skill_engines = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].skill_shields = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].skill_weapons = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].skill_repair = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].skill_combat = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].gender = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].stat_repairs = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].stat_combat_kills = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].stat_piloted_evasions = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].stat_skill_masteries = read_4_le_bytes_as_int(buffer, (adrp+=4));
(*save).current_crew[i].unkn19 = read_4_le_bytes_as_int(buffer, (adrp+=4));
}
// parse remaining data as a byte stream (not modifyable)
adrp+=4;
unsigned long remaining = fileLen-adrp;
(*save).remaining_len = remaining;
(*save).remaining = (char *)malloc(sizeof(char)*remaining+1);
for (int i=0; i<remaining;i++)
{
(*save).remaining[i] = buffer[adrp+i];
}
}
int read_4_le_bytes_as_int(char *buffer, int offset)
{
return (unsigned char) buffer[offset+0] | (buffer[offset+1]<<8) | (buffer[offset+2]<<16) | (buffer[offset+3]<<24);
}
void user_input_crew(SAVEGAME *save, int crewid)
{
int crewattr;
clear();
printw("FTL SAVEGAME EDITOR > CREW\n");
printw("==========================\n");
printw("\n [N]ame: %s\n\n", (*save).current_crew[crewid].name);
printw("\n [M]aximize Stats\n\n");
printw(" - Skill - [P]iloting: %d\n", (*save).current_crew[crewid].skill_pilot);
printw(" - Skill - [E]ngines: %d\n", (*save).current_crew[crewid].skill_engines);
printw(" - Skill - [S]hields: %d\n", (*save).current_crew[crewid].skill_shields);
printw(" - Skill - [W]eapons: %d\n", (*save).current_crew[crewid].skill_weapons);
printw(" - Skill - [R]epair: %d\n", (*save).current_crew[crewid].skill_repair);
printw(" - Skill - [C]ombat: %d\n", (*save).current_crew[crewid].skill_combat);
printw(" - Other - [G]ender: %d\n", (*save).current_crew[crewid].gender);
printw(" - Other - r[A]ce: %s\n", (*save).current_crew[crewid].race);
printw(" - Other - [X] coordinate: %d\n", (*save).current_crew[crewid].x_coord);
printw(" - Other - [Y] coordinate: %d\n", (*save).current_crew[crewid].y_coord);
attron(A_BOLD);
printw("\nWhat do you want to change? [M, P, E, S, W, R, C, G, A, X, Y] [return=exit] ");
attroff(A_BOLD);
crewattr = getch();
switch(crewattr)
{
case 109: // m
// maximizing stats
(*save).current_crew[crewid].skill_pilot = 30;
(*save).current_crew[crewid].skill_engines = 30;
(*save).current_crew[crewid].skill_shields = 110;
(*save).current_crew[crewid].skill_weapons = 130;
(*save).current_crew[crewid].skill_repair = 36;
(*save).current_crew[crewid].skill_combat = 16;
break;
case 112: // p
printw("\nSet pilot skill value [0-30]: ");
scanw("%d", &(*save).current_crew[crewid].skill_pilot);
break;
case 101: // e
printw("\nSet engine skill value [0-30]: ");
scanw("%d", &(*save).current_crew[crewid].skill_engines);
break;
case 115: // s
printw("\nSet shield skill value [0-110]: ");
scanw("%d", &(*save).current_crew[crewid].skill_shields);
break;
case 119: // w
printw("\nSet weapon skill value [0-130]: ");
scanw("%d", &(*save).current_crew[crewid].skill_weapons);
break;
case 114: // r
printw("\nSet repair skill value [0-36]: ");
scanw("%d", &(*save).current_crew[crewid].skill_repair);
break;
case 99: // c
printw("\nSet combat skill value [0-16]: ");
scanw("%d", &(*save).current_crew[crewid].skill_combat);
break;
case 103: // g
printw("\nSet gender [0=female, 1=male]: ");
scanw("%d", &(*save).current_crew[crewid].gender);
break;
case 97: // a
printw("\nSet race [energy, engi, human, mantis, rock, slug]: ");
scanw("%s", &(*save).current_crew[crewid].race);
// ensure room enough for race name
(*save).current_crew[crewid].race_len = 6;
break;
case 120: // x
printw("\nSet X coordinate: ");
scanw("%d", &(*save).current_crew[crewid].x_coord);
break;
case 121: // y
printw("\nSet Y coordinate: ");
scanw("%d", &(*save).current_crew[crewid].y_coord);
break;
case 10: // return
return;
default:
break;
}
}
void user_input(SAVEGAME *save)
{
initscr();
int quit = 0;
int ch;
while (1)
{
printw("FTL SAVEGAME EDITOR\n");
printw("===================\n\n");
printw(" Spaceship: %s\n", (*save).ss_name);
printw(" Crew size: %d\n\n", (*save).current_crew_len);
printw(" [M]aximize resources\n\n");
printw(" - [C]rew\n");
printw(" - i[N]tegrity: %d\n", (*save).ss_integrity);
printw(" - [F]uel: %d\n", (*save).ss_fuel);
printw(" - m[I]ssiles: %d\n", (*save).ss_missiles);
printw(" - [D]roids: %d\n", (*save).ss_droids);
printw(" - [S]crap: %d\n\n", (*save).scrap);
attron(A_BOLD);
printw("What do you want to change? [M,C,N,F,I,D,S] [return=exit] ");
attroff(A_BOLD);
refresh();
ch = getch();
printw("\n");
refresh();
int crewid;
int temp = 0;
switch(ch)
{
case 109: // m
(*save).scrap = 9999;
(*save).ss_droids = 999;
(*save).ss_fuel = 999;
(*save).ss_integrity = 30;
(*save).ss_missiles = 999;
break;
case 99: // c
for (int i=0;i<(*save).current_crew_len;i++)
{
printw(" #%d. %s\n", i+1, (*save).current_crew[i].name);
}
attron(A_BOLD);
printw("\nChoose crew member: ");
attroff(A_BOLD);
crewid = getch();
crewid-=49;
user_input_crew(save, crewid);
break;
case 110: // n
printw("\nSet current integrity value: ");
scanw("%d", &temp);
// should validate all input, but the example below is a lot of
// work to program (for all variables) not to mention a lot of
// work to maintain. need to think this one through...
if (temp <= 30 && temp > 0)
{
(*save).ss_integrity = temp;
}
else
{
printw("Invalid integrity value. Enter value in range [1-30]\n");
getch();
}
break;
case 102: // f
printw("\nSet current fuel value: ");
scanw("%d", &(*save).ss_fuel);
break;
case 100: // d
printw("\nSet current droid value: ");
scanw("%d", &(*save).ss_droids);
break;
case 105: // i
printw("\nSet current missile value: ");
scanw("%d", &(*save).ss_missiles);
break;
case 115: // s
printw("\nSet current scrap value: ");
scanw("%d", &(*save).scrap);
break;
case 10: // return
quit=1;
break;
}
clear();
if (quit == 1) break;
}
endwin();
}
void print_data(SAVEGAME *save)
{
printf("Unknown #1: %d\n", (*save).unkn1);
printf("Unknown #2: %d\n", (*save).unkn2);
printf("Unknown #3: %d\n", (*save).unkn3);
printf("Unknown #4: %d\n", (*save).unkn4);
printf("Unknown #5: %d\n", (*save).unkn5);
printf("Max crew: %d\n", (*save).max_crew);
printf("Ship name: %s\n", (*save).ss_name);
printf("Ship type: %s\n", (*save).ss_type);
printf("Unknown #6: %d\n", (*save).unkn6);
printf("Unknown #7: %d\n", (*save).unkn7);
printf("Max events: %d\n", (*save).max_events);
printf("Event #1: %s", (*save).events[0].name);
printf(" (%d)\n", (*save).events[0].value);
for (int i=0;i<(*save).max_events;i++)
{
printf("Event #%d: %s", i+1, (*save).events[i].name);
printf(" (%d)\n", (*save).events[i].value);
}
printf("Ship name (again): %s\n", (*save).ss_name);
printf("Ship type (again): %s\n", (*save).ss_type2);
printf("Ship class: %s\n", (*save).ss_class);
printf("Starting crew size: %d\n", (*save).start_crew_len);
for (int i=0;i<(*save).start_crew_len;i++)
{
printf("Start Crew #%d: %s (%s)\n", i+1, (*save).start_crew[i].name, (*save).start_crew[i].race);
}
printf("Spaceship integrity: %d\n", (*save).ss_integrity);
printf("Spaceship fuel: %d\n", (*save).ss_fuel);
printf("Spaceship missiles: %d\n", (*save).ss_missiles);
printf("Spaceship droids: %d\n", (*save).ss_droids);
printf("Scrap: %d\n", (*save).scrap);
printf("Current Crew Size: %d\n", (*save).current_crew_len);
for (int i=0;i<(*save).current_crew_len;i++)
{
printf("Current Crew #%d: %s (%s)\n", i+1, (*save).current_crew[i].name, (*save).current_crew[i].race);
printf(" - Unknown 1: (%d)\n", (*save).current_crew[i].unkn1);
printf(" - Health: %d\n", (*save).current_crew[i].health);
printf(" - X coordinate: (%d)\n", (*save).current_crew[i].x_coord);
printf(" - Y coordinate: (%d)\n", (*save).current_crew[i].y_coord);
printf(" - Room: (%d)\n", (*save).current_crew[i].room);
printf(" - Room Tile: (%d)\n", (*save).current_crew[i].room_tile);
printf(" - Unknown 7: (%d)\n", (*save).current_crew[i].unkn7);
printf(" - Skill - Piloting: (%d)\n", (*save).current_crew[i].skill_pilot);
printf(" - Skill - Engines: (%d)\n", (*save).current_crew[i].skill_engines);
printf(" - Skill - Shields: (%d)\n", (*save).current_crew[i].skill_shields);
printf(" - Skill - Weapons: (%d)\n", (*save).current_crew[i].skill_weapons);
printf(" - Skill - Repair: (%d)\n", (*save).current_crew[i].skill_repair);
printf(" - Skill - Combat: (%d)\n", (*save).current_crew[i].skill_combat);
printf(" - Gender: (%d)\n", (*save).current_crew[i].gender);
printf(" - Stat - Repairs: (%d)\n", (*save).current_crew[i].stat_repairs);
printf(" - Stat - Combat kills: (%d)\n", (*save).current_crew[i].stat_combat_kills);
printf(" - Stat - Piloted evasions: (%d)\n", (*save).current_crew[i].stat_piloted_evasions);
printf(" - Stat - Skill masteries: (%d)\n", (*save).current_crew[i].stat_skill_masteries);
printf(" - Unknown 19: (%d)\n", (*save).current_crew[i].unkn19);
}
}
void save_data(SAVEGAME *save)
{
FILE *fp;
fp = fopen("output.sav", "wb");
fwrite(&(*save).unkn1, sizeof(int),1,fp);
fwrite(&(*save).unkn2, sizeof(int),1,fp);
fwrite(&(*save).unkn3, sizeof(int),1,fp);
fwrite(&(*save).unkn4, sizeof(int),1,fp);
fwrite(&(*save).unkn5, sizeof(int),1,fp);
fwrite(&(*save).max_crew, sizeof(int),1,fp);
fwrite(&(*save).ss_name_len, sizeof(int),1,fp);
fwrite((*save).ss_name, sizeof(char),(*save).ss_name_len,fp);
fwrite(&(*save).ss_type_len, sizeof(int),1,fp);
fwrite((*save).ss_type, sizeof(char),(*save).ss_type_len,fp);
fwrite(&(*save).unkn6, sizeof(int),1,fp);
fwrite(&(*save).unkn7, sizeof(int),1,fp);
fwrite(&(*save).max_events, sizeof(int),1,fp);
for(int i=0;i<(*save).max_events;i++)
{
fwrite(&(*save).events[i].name_len, sizeof(int),1,fp);
fwrite((*save).events[i].name, sizeof(char),(*save).events[i].name_len,fp);
fwrite(&(*save).events[i].value, sizeof(int),1,fp);
}
fwrite(&(*save).ss_type2_len, sizeof(int),1,fp);
fwrite((*save).ss_type2, sizeof(char),(*save).ss_type2_len,fp);
fwrite(&(*save).ss_name2_len, sizeof(int),1,fp);
fwrite((*save).ss_name2, sizeof(char),(*save).ss_name2_len,fp);
fwrite(&(*save).ss_class_len, sizeof(int),1,fp);
fwrite((*save).ss_class, sizeof(char),(*save).ss_class_len,fp);
fwrite(&(*save).start_crew_len, sizeof(int),1,fp);
for(int i=0;i<(*save).start_crew_len;i++)
{
fwrite(&(*save).start_crew[i].race_len, sizeof(int),1,fp);
fwrite((*save).start_crew[i].race, sizeof(char),(*save).start_crew[i].race_len,fp);
fwrite(&(*save).start_crew[i].name_len, sizeof(int),1,fp);
fwrite((*save).start_crew[i].name, sizeof(char),(*save).start_crew[i].name_len,fp);
}
fwrite(&(*save).ss_integrity, sizeof(int),1,fp);
fwrite(&(*save).ss_fuel, sizeof(int),1,fp);
fwrite(&(*save).ss_missiles, sizeof(int),1,fp);
fwrite(&(*save).ss_droids, sizeof(int),1,fp);
fwrite(&(*save).scrap, sizeof(int),1,fp);
fwrite(&(*save).current_crew_len, sizeof(int),1,fp);
for(int i=0;i<(*save).current_crew_len;i++)
{
fwrite(&(*save).current_crew[i].name_len, sizeof(int),1,fp);
fwrite((*save).current_crew[i].name, sizeof(char),(*save).current_crew[i].name_len,fp);
fwrite(&(*save).current_crew[i].race_len, sizeof(int),1,fp);
fwrite((*save).current_crew[i].race, sizeof(char),(*save).current_crew[i].race_len,fp);
fwrite(&(*save).current_crew[i].unkn1, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].health, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].x_coord, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].y_coord, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].room, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].room_tile, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].unkn7, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].skill_pilot, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].skill_engines, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].skill_shields, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].skill_weapons, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].skill_repair, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].skill_combat, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].gender, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].stat_repairs, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].stat_combat_kills, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].stat_piloted_evasions, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].stat_skill_masteries, sizeof(int),1,fp);
fwrite(&(*save).current_crew[i].unkn19, sizeof(int),1,fp);
}
fwrite((*save).remaining, sizeof(char),(*save).remaining_len,fp);
fclose(fp);
}
void usage(char *argbuffer)
{
fprintf(stderr, "Usage:\n");
fprintf(stderr, "%s <savegame file>\n", argbuffer);
fprintf(stderr, "Example: %s continue.sav\n", argbuffer);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
struct point {
int x;
int y;
};
struct line {
struct point p1;
struct point p2;
};
char *read_input(char *filename, size_t *out_size) {
char *output;
FILE *f;
size_t size;
if (!filename) return NULL;
f = fopen(filename, "rb");
fseek(f, 0, SEEK_END);
size = (size_t) ftell(f);
fseek(f, 0, SEEK_SET);
output = malloc(size);
if (!output) return NULL;
fread(output, 1, size, f);
fclose(f);
*out_size = size;
return output;
}
size_t get_n_inputs(char *input) {
size_t n_inputs;
n_inputs = 1;
while (*input) {
if (*input == ',') ++n_inputs;
++input;
}
return n_inputs;
}
void split_string(char *input, char **inputs) {
char *tok;
tok = strtok(input, ",");
do {
*inputs++ = tok;
} while ((tok = strtok(NULL, ",")));
}
int get_input_list(char *input, size_t *out_count, char ***out_inputs) {
*out_count = get_n_inputs(input);
*out_inputs = malloc(*out_count * sizeof(char *));
if (!*out_inputs) return -1;
split_string(input, *out_inputs);
return 0;
}
int calc_line_segs(
size_t n_inputs,
char **inputs,
size_t *out_linecount,
struct line **out_lines
) {
struct point p = { 0 };
struct line prev_line = { 0 }, next_line, *out_line;
*out_linecount = n_inputs - 1;
*out_lines = malloc(*out_linecount * sizeof(struct line));
if (!*out_lines) return -1;
out_line = *out_lines;
while (--n_inputs) {
int run;
/* Add 1 to inputs to ignore the leading direction character (R, U, D, L) */
if (sscanf((*inputs) + 1, "%d", &run) == EOF) return -1;
next_line = prev_line;
switch ((*inputs)[0]) {
case 'R': p.x += run; break;
case 'U': p.y += run; break;
case 'L': p.x -= run; break;
case 'D': p.y -= run; break;
}
next_line.p1 = prev_line.p2;
next_line.p2 = p;
prev_line = next_line;
*out_line++ = next_line;
++inputs;
}
return 0;
}
void set_limits(int a, int b, int *out_min, int *out_max) {
if (!out_max) return;
if (!out_min) return;
if (a < b) {
*out_min = a;
*out_max = b;
} else {
*out_min = b;
*out_max = a;
}
}
int intersection(struct line *a, struct line *b, struct point *out_p) {
int xmax, xmin, ymax, ymin;
if (!a) return 0;
if (!b) return 0;
/* Check if line a is horizontal or vertical */
if ((a->p1.y - a->p2.y) == 0) {
/* Here, a is horizontal */
if ((b->p1.y - b->p2.y) == 0) return 0;
set_limits(a->p1.x, a->p2.x, &xmin, &xmax);
set_limits(b->p1.y, b->p2.y, &ymin, &ymax);
if (a->p1.y >= ymin && a->p1.y <= ymax) {
if (b->p1.x >= xmin && b->p2.x <= xmax) {
if (!out_p) return 1;
out_p->x = b->p1.x;
out_p->y = a->p1.y;
return 1;
}
}
} else {
/* Here, a is vertical */
if ((b->p1.x - b->p2.x) == 0) return 0;
set_limits(a->p1.y, a->p2.y, &ymin, &ymax);
set_limits(b->p1.x, b->p2.x, &xmin, &xmax);
if (a->p1.x >= xmin && a->p1.x <= xmax) {
if (b->p1.y >= ymin && b->p1.y <= ymax) {
if (!out_p) return 1;
out_p->x = a->p1.x;
out_p->y = b->p1.y;
return 1;
}
}
}
return 0;
}
int calc_intersections(
size_t n_first,
struct line *first_lines,
size_t n_second,
struct line *second_lines,
size_t *out_count,
struct point **out_intersections
) {
size_t i, j;
struct point p, *out_intersection;
*out_intersections = malloc(n_first * n_second * sizeof(struct point));
if (!*out_intersections) return -1;
out_intersection = *out_intersections;
for (i = 0; i < n_first; ++i) {
for (j = 0; j < n_second; ++j) {
if (intersection(first_lines + i, second_lines + j, &p)) {
*out_intersection++ = p;
++(*out_count);
}
}
}
return 0;
}
void print_closest_intersection(
size_t n_intersections,
struct point *intersections
) {
struct point min = { INT_MAX / 2, INT_MAX / 2 };
if (!n_intersections) return;
if (!intersections) return;
while (--n_intersections) {
struct point cur;
cur = *intersections++;
if ((abs(cur.x) + abs(cur.y)) < (abs(min.x) + abs(min.y))) {
if (abs(cur.x) + abs(cur.y) > 0) min = cur;
}
}
printf("( % 4d % 4d ) -> %u\n", min.x, min.y, abs(min.x) + abs(min.y));
}
int main(int arg, char **argv) {
char **first_inputs = NULL, **second_inputs = NULL;
char *first, *second;
size_t first_size, second_size, n_first, n_second;
size_t n_first_lines, n_second_lines, n_intersections = 0;
struct line *first_lines = NULL, *second_lines = NULL;
struct point *intersections;
first = read_input("../3/first.txt", &first_size);
second = read_input("../3/second.txt", &second_size);
if (!first) return -1;
if (!second) return -1;
if (get_input_list(first, &n_first, &first_inputs)) return -1;
if (get_input_list(second, &n_second, &second_inputs)) return -1;
/* Remove \n at the end */
first_size -= 1;
second_size -= 1;
if (calc_line_segs(
n_first,
first_inputs,
&n_first_lines,
&first_lines
)) {
return -1;
}
if (calc_line_segs(
n_second,
second_inputs,
&n_second_lines,
&second_lines
)) {
return -1;
}
if (calc_intersections(
n_first_lines,
first_lines,
n_second_lines,
second_lines,
&n_intersections,
&intersections
)) {
return -1;
}
print_closest_intersection(n_intersections, intersections);
free(intersections);
free(first_lines);
free(second_lines);
free(first_inputs);
free(second_inputs);
free(first);
free(second);
return 0;
}
|
C | #include "std.h"
#include "table.h"
#include "get_word.h"
#include "lexicon.h"
#include "network.h"
// max_states is the maximum number of states allowed in the network.
const int max_states = 50;
const char *network_file = "network";
// The network is stored in a table of states. Each is referenced by
// its name.
table *network;
istream *network_in;
// state::insert() associates an arc with it's tail.
void state::insert( arc *a )
{
arc_list *al = new arc_list( a );
al->next = branches;
branches = al;
}
// get_state() gets a state from the network. If the input name (s)
// does not refer to a state, then a new one is created and put in the
// table.
state *get_state( char *s )
{
state *x = (state *) network->lookup(s);
if (x == NULL)
{
network->insert( s, new state );
x = (state *) network->lookup(s);
}
return (x);
}
// build_arc() reads the network file and gets the parts of an arc.
// An arc has a tail (the state that it comes from), a head (the state
// that it goes to), and a category (what type of morpheme licenses
// the transition). The order in which the things are defined is not
// important as long as all the pieces are specified. When the
// semi-colon is found (marking the end of the definition) the head
// and category are associated with the tail by inserting an arc
// structure in the tail state.
void build_arc()
{
char *w;
state *to_state = NULL;
state *from_state = NULL;
category *by_category = NULL;
while ( (w=get_word(network_in)) != NULL )
{
if (strcmp("to", w)==0)
to_state = get_state(get_word(network_in));
else if (strcmp("from", w)==0)
from_state = get_state(get_word(network_in));
else if (strcmp("by", w)==0)
by_category = get_category(get_word(network_in));
else if (strcmp(";", w)==0)
{
if ( to_state == NULL || from_state == NULL || by_category == NULL )
cerr << "incomplete arc definition\n";
else
from_state->insert( new arc( by_category, to_state ));
return;
}
else
cerr << "network input error. need to,from, or by. found "<<w<<"\n";
}
cerr << "unexpected end of network file\n";
}
// set_final_states() simply gets states and sets the final flag in
// them until a semi-colon is found to mark the end of the definition.
void set_final_states()
{
char *w;
while ( (w=get_word(network_in)) != NULL )
{
if (strcmp(";", w)==0)
return;
get_state(w)->final = 1;
}
cerr << "unexpected end of network file\n";
}
// read_network() reads the network file. It should find either an
// arc definition or a final state definition. One is signaled by the
// word "arc" and the other by the word "final".
void read_network()
{
filebuf network_in_buf;
if (network_in_buf.open( network_file, input ) == 0)
{
cerr << "cannot open network file: "<<network_file<<"\n";
exit(1);
}
network_in = new istream( &network_in_buf );
char *w;
while ( (w=get_word(network_in)) != NULL )
{
if (strcmp("arc", w)==0)
build_arc();
else if (strcmp("final", w)==0)
set_final_states();
else
cerr << "unknown network word: "<<w<<"\n";
}
}
// init_network() initializes the network table and reads the network
// file.
void init_network()
{
network = new table(max_states);
read_network();
}
|
C | #include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data; //node will store an integer
struct node *right,*left;
}node;
node* root=NULL;
node* add_node(node* temp,int value)
{
if(temp==NULL)
{
temp=(node*)malloc(sizeof(node));
temp->data=value;
temp->left=temp->right=NULL;
}
else if(value<temp->data)
{
temp->left=add_node(temp->left,value);
}
else
{
temp->right=add_node(temp->right,value);
}
return temp;
}
void inorder(node *temp) {
if (temp != NULL) {
inorder(temp->left);
printf("%d ", temp->data);
inorder(temp->right);
}
}
void preorder(node *temp) {
if (temp != NULL) {
printf("%d ", temp->data);
preorder(temp->left);
preorder(temp->right);
}
}
void postorder(node *temp) {
if (temp != NULL) {
postorder(temp->left);
postorder(temp->right);
printf("%d ", temp->data);
}
}
main()
{
int value,flag=1;
printf("\nCREATING TREE\n");
while(flag)
{
printf("enter value to insert/create Tree\n");
scanf("%d",&value);
root=add_node(root,value);
printf("enter 1 to add more else enter 0\n");
scanf("%d",&flag);
}
printf("\nTRAVERSING\n");
if (root == NULL)
printf("Tree Is Not Created");
else {
printf("\nThe Inorder display : ");
inorder(root);
printf("\nThe Preorder display : ");
preorder(root);
printf("\nThe Postorder display : ");
postorder(root);
}
}
|
C | #include <stdio.h>
void reverse(/*unsigned char *input*/)
{
//int v4 = 1337;
int v1;
unsigned char *v5;
unsigned char v3;
unsigned char input[255];
while (1)
{
scanf("%s", input);
v5 = input;
v3 = *v5;
int v4 = 1337;
do
{
v1 = 32 * v4 + v3;
v3 = (v5++)[1];
v4 += v1;
} while (v3);
printf("%08X\r\n", (unsigned int)v4);
if (v4 == 0xEF2E3558)
{
printf("Got it\r\n");
break;
}
}
}
int main()
{
reverse();
return 0;
}; |
C | /*
#include <stdio.h>
int main(void) {
FILE * ms = fopen("C:/Users/tkskd/Desktop/mystroy.txt", "wt");
if (ms == NULL) {
puts(" !");
return -1;
}
fputs("#̸: \n", ms);
fputs("#ֹιȣ: 900112-1234567\n", ms);
fputs("#ȭȣ: 010-4322-8956\n", ms);
fclose(ms);
return 0;
}
*/ |
C | #include <stdio.h>
int main()
{
printf("simple.c\n");
printf("To compile and run simply type: \"gcc simple.c -o simple.exe && ./simple.exe\"\n");
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* last_sort.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lwourms <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/23 17:43:26 by lwourms #+# #+# */
/* Updated: 2021/06/29 19:06:26 by lwourms ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
void last_sort_pile_4_nb(t_list *pile)
{
if (pile->next && (int)pile->content > (int)pile->next->content)
sa(&pile);
}
void last_sort_pile_2_nb(t_list *pile)
{
if (pile->next && (int)pile->content > (int)pile->next->content)
sa(&pile);
}
void last_sort_pile_nb(t_datas *datas, int size)
{
while (datas->a_pile)
{
if (size < 4)
{
last_sort_pile_3_nb(datas->a_pile);
return ;
}
else if (size < 6)
{
datas->chunk = set_array_nb(*datas, datas->a_pile, size);
ft_sort_array_ascending(&(datas->chunk), size);
if (is_pile_sorted(datas->a_pile, datas->chunk))
return ;
last_sort_pile_5_nb(datas, size);
return ;
}
else if (is_smaller_in_pile(datas->a_pile, (int)datas->a_pile->content))
{
pb(&(datas->a_pile), &(datas->b_pile), datas->str);
size--;
}
else
ra(&(datas->a_pile));
}
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lnorcros <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/08 18:45:56 by lnorcros #+# #+# */
/* Updated: 2021/02/08 18:45:58 by lnorcros ### ########.fr */
/* */
/* ************************************************************************** */
#include "libftprintf.h"
void set_line(t_line *line, int *r_l, const char **format)
{
(*line).precision = 1;
(*line).precision_p = 'n';
(*line).precision_d = 'n';
(*line).minus = 0;
(*line).width = 0;
(*line).null_flag = 0;
while (**format != '%' && **format)
{
*r_l += write(1, &(**format), 1);
(*format)++;
}
}
int ft_printf(const char *format, ...)
{
va_list ap;
t_line line;
int return_length;
va_start(ap, format);
return_length = 0;
while (*format)
{
set_line(&line, &return_length, &format);
if (*format == '%')
{
parse_perc(&format, &return_length);
if (*format == '%')
{
rep_perc(&format, &line, &return_length, &ap);
if (!(*format))
va_end(ap);
if (!(*format))
return (return_length);
format++;
}
}
}
va_end(ap);
return (return_length);
}
|
C | #include "holberton.h"
/**
*cap_string - capitalizes the first letter in a world
*@s: string
*Return: a string
*/
char *cap_string(char *s)
{
int counter = 0;
if ((s[counter] >= 'a' || (s[counter] <= 'z' && !(s[counter] < 'a'))))
s[counter] -= 32;
while (s[counter] != '\0')
{
if ((s[counter - 1]) && (s[counter - 1] == ' ' ||
s[counter - 1] == '\n' || s[counter - 1] == '\t' || s[counter - 1] == '.'))
if (s[counter] >= 'a' || (s[counter] <= 'z' && !(s[counter] < 'a')))
{
s[counter] -= 32;
}
counter++;
}
return (s);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mapping.h"
DWORD reverseBits(DWORD x){
x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));
return((x >> 16) | (x << 16));
}
void writeValue(DWORD addr, DWORD value){
//printf("Write to %08x, data: %08x\n", addr, value);
// BOOL bPass = PCIE_Write32( hPCIe, PCIE_BAR0, addr, reverseBits(value));
BOOL bPass = PCIE_Write32( hPCIe, PCIE_BAR0, addr, value);
if (!bPass){
printf("ERROR: PCIe Read Failed.\n");
exit(1);
}
}
DWORD readValue(DWORD addr){
DWORD value = 0x00000000;
BOOL bPass = PCIE_Read32( hPCIe, PCIE_BAR0, addr, &value);
if (!bPass){
printf("ERROR: PCIe Read Failed.\n");
exit(1);
}
//printf("Read from %08x, data: %08x\n", addr, value);
return value;
}
void writeDifficultyMessage(DWORD * difficulty){
int i;
for(i = 0; i < TARGET_WORDS; i++){
writeValue(TARGET_ADDRESS + (i*FACTOR), difficulty[TARGET_WORDS - i - 1]);
}
}
void pauseForTarget(){
DWORD state = 0;
writeValue(CONTROL_ADDRESS, state);
writeValue(STATUS_ADDRESS, 0x00000000);
}
void resumeFromTarget(){
DWORD state = 0x00000001;
writeValue(CONTROL_ADDRESS, state);
}
void pauseMining(){
DWORD state = 0;
writeValue(CONTROL_ADDRESS, state);
writeValue(STATUS_ADDRESS, 0x00000000);
}
void resumeMining(){
DWORD state = 0x00000002;
writeValue(CONTROL_ADDRESS, state);
}
state_t getState(){
DWORD state = readFromStatusRegister();
printf("Read from Status Register, data: %08x\n", state);
if(SUCCESS_BIT_SET(state)){
if(STOPPED_BIT_SET(state)){
return SUCCESSFUL;
}else{
return SUCCESSFUL;
}
}else{
if(STOPPED_BIT_SET(state)){
return WAITING;
}else{
return MINING;
}
}
}
void writeToControlRegister(DWORD value){
writeValue(CONTROL_ADDRESS, value);
}
DWORD readFromStatusRegister(){
return readValue(STATUS_ADDRESS);
}
void writeBitcoinMessage(DWORD * data){
int i;
for(i = 0; i < BITCOIN_WORDS; i++){
writeValue(BITCOIN_ADDRESS + (i*FACTOR), reverseBits(data[BITCOIN_WORDS - i - 1]));
}
}
void readBitcoin(DWORD * data){
int i;
for(i = 0; i < BITCOIN_WORDS; i++){
data[BITCOIN_WORDS - i - 1] = reverseBits(readValue(BITCOIN_ADDRESS + (i*FACTOR)));
}
data[BITCOIN_WORDS] = readValue(NONCE_ADDRESS);
}
void readDifficulty(DWORD * data){
int i;
for(i = 0; i < TARGET_WORDS; i++){
data[TARGET_WORDS - i - 1] = readValue(TARGET_ADDRESS + (i*FACTOR));
}
}
|
C | #include<stdio.h>
#include<stdlib.h>
void main()
{
char filename[20];
printf("Enter file name to be read:");
scanf("%s",filename);
print_fivechar(filename);
}
void print_fivechar(char *f)
{
FILE *fp;
char ch;
int no=0;
fp=fopen(f,"r");
printf("Last five character are ===> ");
fseek(fp,-20,SEEK_END);
/*if(fseek(fp,-5,SEEK_END) == -1)
{
printf("No enough charcters");
exit(-1);
}*/
while((ch=fgetc(fp))!=EOF)
{
printf("%c",ch);
}
printf("\n");
fclose(fp);
}
|
C | /* Esercizio 15
Scrivere un programma in C che legga da tastiera 12 interi e inserisca i primi
6 nell’array a e gli altri nell’array b. Dichiarare inoltre un terzo array c di 3
elementi.
Scrivere poi una procedura che calcoli il prodotti tra gli elementi pari dell’array
a e gli elementi dispari dell’array b e li inserisca in ordine nell’array c (ovvero,
c[0] = a[0] ∗ b[1], c[1] = a[2] ∗ b[3], c[2] = a[4] ∗ b[5], ecc se gli array fossero più
lunghi).
Scrivere un’altra funzione che calcoli il minimo di un array.
Stampare il minimo dell’array c. */
#include <stdio.h>
void prodotto(int a[], int b[], int c[], int dim_ab, int dim_c);
int min(int c[], int dim_c);
int main()
{
int i;
int a[6];
int b[6];
int c[3];
for(i=0; i<6; i++)
scanf("%d", &a[i]);
for(i=0; i<6; i++)
scanf("%d", &b[i]);
prodotto(a, b, c, 6, 3);
//for(i=0; i<3; i++)
// printf("%d\n", c[i]);
printf("%d\n", min(c, 3));
return 0;
}
void prodotto(int a[], int b[], int c[], int dim_ab, int dim_c)
{
int i; // indice c[]
int j=0; // indice a[] e b[]
for(i=0; i<dim_c; i++)
{
c[i]=a[j]*b[j+1];
j=j+2;
}
//altro metodo per non scrivere j:
//int i;
// for(i=0; i<dim_c; i++)
// {
// c[i]=a[i*2]*b[i*2+1];
// }
}
int min(int c[], int dim_c)
{
int min=c[0]; //variabile minimo
int i;
for(i=0; i<dim_c; i++)
{
if(min>c[i])
min=c[i];
}
return min;
}
|
C | #include "common.h"
// simple write-ahead logging for atomic file replacement
#define DATABUF_SIZE 4096
struct wal_checksum {
unsigned char digest[20];
};
static int calc_file_checksum(FILE *fp, struct wal_checksum *csum)
{
int success = 1;
unsigned char databuf[DATABUF_SIZE];
size_t datalen;
SHA1_CTX ctx;
SHA1Init(&ctx);
while (!feof(fp)) {
datalen = fread(databuf, 1, sizeof(databuf), fp);
if (ferror(fp)) {
success = 0;
break;
}
if (datalen > 0) {
SHA1Update(&ctx, databuf, datalen);
}
}
SHA1Final(csum->digest, &ctx);
return success;
}
static int copy_file_contents(FILE *dstfp, FILE *srcfp)
{
int success = 1;
char databuf[DATABUF_SIZE];
size_t datalen;
while (!feof(srcfp)) {
datalen = fread(databuf, 1, sizeof(databuf), srcfp);
if (ferror(srcfp)) {
success = 0;
break;
}
if (datalen > 0) {
if (fwrite(databuf, 1, datalen, dstfp) != datalen) {
success = 0;
break;
}
}
}
return success;
}
// internal: overwrite dst with src, then destory checksum
static int do_overwrite(const char *dst[], const char *src[], int n, const char *sum)
{
int i;
FILE *srcfp = NULL;
FILE *dstfp = NULL;
FILE *sumfp = NULL;
for (i = 0; i < n; i++) {
srcfp = robust_fopen(src[i], "rb");
if (!srcfp) goto fail;
dstfp = robust_fopen(dst[i], "wbc");
if (!dstfp) goto fail;
if (!copy_file_contents(dstfp, srcfp)) goto fail;
if (fflush(dstfp) != 0) goto fail;
safe_fclose(&dstfp);
safe_fclose(&srcfp);
}
sumfp = robust_fopen(sum, "wbc");
if (!sumfp) goto fail;
if (fflush(sumfp) != 0) goto fail;
safe_fclose(&sumfp);
return 1;
fail:
safe_fclose(&srcfp);
safe_fclose(&dstfp);
safe_fclose(&sumfp);
return 0;
}
// internal: delete checksum and src
static int do_cleanup(const char *src[], int n, const char *sum)
{
int success = 1;
int i;
if (robust_unlink(sum) != 0 && errno != ENOENT) success = 0;
for (i = 0; i < n; i++) {
if (robust_unlink(src[i]) != 0 && errno != ENOENT) success = 0;
}
return success;
}
// internal: commit changes
static int do_commit(const char *dst[], const char *src[], int n, const char *sum)
{
return do_overwrite(dst, src, n, sum) && do_cleanup(src, n, sum);
}
// replace dst[] with src[], with temporary checksum(s) stored in sum
static int wal_replaceN(const char *dst[], const char *src[], int n, const char *sum)
{
FILE *sumfp = NULL;
FILE *srcfp = NULL;
int i;
// step 1: write checksum
sumfp = robust_fopen(sum, "wbc");
if (!sumfp) goto fail;
for (i = 0; i < n; i++) {
srcfp = robust_fopen(src[i], "r+bc");
if (!srcfp) goto fail;
struct wal_checksum csum;
if (!calc_file_checksum(srcfp, &csum)) goto fail;
if (fwrite(&csum, sizeof(csum), 1, sumfp) != 1) goto fail;
if (fflush(srcfp) != 0) goto fail;
safe_fclose(&srcfp);
}
if (fflush(sumfp) != 0) goto fail;
safe_fclose(&sumfp);
// step 2: commit changes
return do_commit(dst, src, n, sum);
fail:
safe_fclose(&srcfp);
safe_fclose(&sumfp);
return 0;
}
// check consistency, run undo or redo if necessary
static int wal_checkN(const char *dst[], const char *src[], int n, const char *sum)
{
FILE *sumfp = NULL;
FILE *srcfp = NULL;
int i;
// step 1: verify checksum
sumfp = robust_fopen(sum, "rb");
if (!sumfp) goto undo;
for (i = 0; i < n; i++) {
struct wal_checksum csum1, csum2;
if (fread(&csum1, sizeof(csum1), 1, sumfp) != 1) goto undo;
srcfp = robust_fopen(src[i], "rb");
if (!srcfp) goto undo;
if (!calc_file_checksum(srcfp, &csum2)) goto undo;
safe_fclose(&srcfp);
if (memcmp(&csum1, &csum2, sizeof(struct wal_checksum)) != 0) goto undo;
}
safe_fclose(&sumfp);
// step 2a: redo commit
return do_commit(dst, src, n, sum);
undo:
// step 2b: rollback
safe_fclose(&srcfp);
safe_fclose(&sumfp);
return do_cleanup(src, n, sum);
}
int wal_replace(char *dst[], char *src[], int n, const char *sum)
{
return wal_replaceN((const char **) dst, (const char **) src, n, sum);
}
int wal_check(char *dst[], char *src[], int n, const char *sum)
{
return wal_checkN((const char **) dst, (const char **) src, n, sum);
}
int wal_replace1(const char *dst, const char *src, const char *sum)
{
return wal_replaceN(&dst, &src, 1, sum);
}
int wal_check1(const char *dst, const char *src, const char *sum)
{
return wal_checkN(&dst, &src, 1, sum);
}
|
C | #include "thread_qsort.h"
void swap(int *a, int *b) {
int c = *a;
*a = *b;
*b = c;
}
int cmp(const void *a, const void *b) {
return *((int*) a) - *((int*) b);
}
void thqsort_real_sort(void *_arg) {
struct TaskArg *arg = _arg;
if (arg->sz <= 1) return;
if (arg->depth == 0) {
qsort(arg->a, arg->sz, sizeof(int), cmp);
return;
}
//Partition
int x = arg->a[(rand() % arg->sz)];
int i = 0, j = arg->sz - 1;
while (i <= j) {
while (arg->a[i] < x) i++;
while (arg->a[j] > x) j--;
if (i <= j) swap(&(arg->a[i++]), &(arg->a[j--]));
}
//Create new tasks
struct Task *taskl = malloc(sizeof(struct Task));
taskl->f = thqsort_real_sort;
struct TaskArg *argl = malloc(sizeof(struct TaskArg));
argl->a = arg->a;
argl->sz = j + 1;
argl->depth = arg->depth - 1;
argl->pool = arg->pool;
argl->left = NULL;
argl->right = NULL;
taskl->arg = argl;
((struct TaskArg*)(_arg))->left = taskl;
struct Task *taskr = malloc(sizeof(struct Task));
taskr->f = thqsort_real_sort;
struct TaskArg *argr = malloc(sizeof(struct TaskArg));
argr->a = arg->a + i;
argr->sz = arg->sz - i;
argr->depth = arg->depth - 1;
argr->pool = arg->pool;
argr->left = NULL;
argr->right = NULL;
taskr->arg = argr;
((struct TaskArg*)(_arg))->right = taskr;
thpool_submit(arg->pool, taskl);
thpool_submit(arg->pool, taskr);
}
void wait_for_all_tasks(struct Task *task) {
if (!task) return;
if (!task->done) thpool_wait(task);
wait_for_all_tasks(((struct TaskArg*)(task->arg))->left);
wait_for_all_tasks(((struct TaskArg*)(task->arg))->right);
free(task->arg);
free(task);
}
void thqsort(int *a, int sz, int nTh, int depth) {
struct ThreadPool pool;
thpool_init(&pool, nTh);
struct Task *task = malloc(sizeof(struct Task));
task->f = thqsort_real_sort;
struct TaskArg *arg = malloc(sizeof(struct TaskArg));
arg->a = a;
arg->sz = sz;
arg->depth = depth;
arg->pool = &pool;
task->arg = (void *)arg;
thpool_submit(&pool, task);
wait_for_all_tasks(task);
thpool_finit(&pool);
} |
C | #include <stdio.h>
#include <locale.h>
#include <math.h>
// LEIA UM NUMERO REAL E IMPRIMA O RESULTADO DO QUADRADO DESSE NUMERO
int main(){
float num;
scanf("%f", &num);
printf("%f", pow(num, 2));
}
|
C | /*
óʾʹnoneblock дԱƶ˻߱ƵĵӦá
ʵֿõƾ߶ʱ ԼʱЧ
nbеĶʱʵ ԵƾߵĿƣЧҲöʱʵ֡
ʾ:
1nbܽ
2ͨnbܵinvoke һ()
3nbĶʱӦã
4pwm
5jsonίнӿڵʹ(jsonίнӿhttpdotdĬϵⲿӿ)
*/
#include "include.h"
/*
ģ:
ʽ:
{
"method":"dollcatch.steer",
"params":"U"\"D" \"L"\"R" \"F"\"B"
}
*/
#define NB_NAME "dollcatch"
//ﶨҪʹЩ ԼһЩΪĺ궨
#define IO1 WIFIIO_GPIO_17
#define IO2 WIFIIO_GPIO_18
#define IO3 WIFIIO_GPIO_19
#define IO4 WIFIIO_GPIO_20
#define IO5 WIFIIO_GPIO_21
#define IO6 WIFIIO_GPIO_22
#define STEER_Y_UP() {api_io.low(IO1);api_io.high(IO2);}
#define STEER_Y_DOWN() {api_io.high(IO1);api_io.low(IO2);}
#define STEER_Y_MID() {api_io.low(IO1);api_io.low(IO2);}
#define STEER_X_RIGHT() {api_io.low(IO3);api_io.high(IO4);}
#define STEER_X_LEFT() {api_io.high(IO3);api_io.low(IO4);}
#define STEER_X_MID() {api_io.low(IO3);api_io.low(IO4);}
#define STEER_Z_BACK() {api_io.low(IO5);api_io.high(IO6);}
#define STEER_Z_FRONT() {api_io.high(IO5);api_io.low(IO6);}
#define STEER_Z_MID() {api_io.low(IO5);api_io.low(IO6);}
#define STEER_OP_TIME_LAST_MAX 1000
typedef struct{
char steer;
}invoke_msg_opt_dollcatch_t;
///////////////////////////////////////////
// úΪʱԤʱ䱻dollcatch
// ̵á
///////////////////////////////////////////
int dollcatch_timer(nb_info_t* pnb, nb_timer_t* ptmr, void *ctx)
{
if((void*)'R' == ctx || (void*)'L' == ctx)
STEER_X_MID()
if((void*)'U' == ctx || (void*)'D' == ctx)
STEER_Y_MID()
if((void*)'F' == ctx || (void*)'B' == ctx)
STEER_Z_MID()
else{
STEER_X_MID();
STEER_Y_MID();
STEER_Z_MID();
}
return NB_TIMER_RELEASE;
}
////////////////////////////////////////
//údollcatchУʵ timer
////////////////////////////////////////
int timer_adjest_safe(nb_info_t*pnb, nb_invoke_msg_t* msg)
{
//ȡߵͼ
invoke_msg_opt_dollcatch_t* opt = api_nb.invoke_msg_opt(msg);
nb_timer_t* ptmr;
if('U' == opt->steer){
STEER_Y_UP();
}
else if('D' == opt->steer){
STEER_Y_DOWN();
}
else if('R' == opt->steer){
STEER_X_RIGHT();
}
else if('L' == opt->steer){
STEER_X_LEFT();
}
else if('F' == opt->steer){
STEER_Z_FRONT();
}
else if('B' == opt->steer){
STEER_Z_BACK();
}
else {
return STATE_OK;
}
//ѾţtimerڵȴУλtimer
ptmr = api_nb.timer_by_ctx(pnb, (void*)((u32_t)opt->steer));
if(NULL == ptmr){ //ûоµ
LOG_INFO("dollcatch:tmr alloced.\r\n");
ptmr = api_nb.timer_attach(pnb, STEER_OP_TIME_LAST_MAX, dollcatch_timer, (void*)((u32_t)opt->steer), 0); //alloc
}
else{ // ¶
LOG_INFO("dollcatch:tmr restarted.\r\n");
api_nb.timer_restart(pnb, STEER_OP_TIME_LAST_MAX, dollcatch_timer);
}
return STATE_OK;
}
////////////////////////////////////////
//úIJ dollcatch
//֤ʹnbṩ
//invokeƣdollcatch"ע"к
////////////////////////////////////////
int dollcatch_steer_arrange(nb_info_t* pnb, char steer)
{
LOG_INFO("DELEGATE:%c.\r\n",steer);
//һinvokeҪ(Ϣ)
nb_invoke_msg_t* msg = api_nb.invoke_msg_alloc(timer_adjest_safe, sizeof(invoke_msg_opt_dollcatch_t), NB_MSG_DELETE_ONCE_USED);
invoke_msg_opt_dollcatch_t* opt = api_nb.invoke_msg_opt(msg);
opt->steer = steer;
api_nb.invoke_start(pnb , msg);
return STATE_OK;
}
////////////////////////////////////////
//ίнӿڵĶ:
// JSON_DELEGATE() ΪӺ
// __ADDON_EXPORT__ 꽫÷ŶΪ¶
// ʽ һjsonһ
// ִɺĻص 丽
//
// ú ǵøίнӿڵĽ
// httpdotd Եøýӿ
// ӿΪ dollcatch.steer
////////////////////////////////////////
int __ADDON_EXPORT__ JSON_DELEGATE(steer)(jsmn_node_t* pjn, fp_json_delegate_ack ack, void* ctx) //̳fp_json_delegate_start
{
int ret = STATE_OK;
char* err_msg = NULL;
nb_info_t* pnb;
if(NULL == (pnb = api_nb.find(NB_NAME))){ //жϷǷѾ
ret = STATE_ERROR;
err_msg = "Service unavailable.";
LOG_WARN("dollcatch:%s.\r\n", err_msg);
goto exit_err;
}
LOG_INFO("DELEGATE dollcatch.steer.\r\n");
char steer[4];
if(JSMN_STRING != pjn->tkn->type ||
STATE_OK != jsmn.tkn2val_str(pjn->js, pjn->tkn, steer, sizeof(steer), NULL)){
ret = STATE_ERROR;
err_msg = "Params error.";
LOG_WARN("dollcatch:%s.\r\n", err_msg);
goto exit_err;
}
if('U' == steer[0] || 'D' == steer[0] || 'R' == steer[0] || 'L' == steer[0] || 'F' == steer[0] || 'B' == steer[0]){
dollcatch_steer_arrange(pnb, steer[0]);
}
else {
ret = STATE_ERROR;
err_msg = "Params invalid.";
LOG_WARN("dollcatch:%s.\r\n", err_msg);
goto exit_err;
}
//exit_safe:
if(ack)
jsmn.delegate_ack_result(ack, ctx, ret);
return ret;
exit_err:
if(ack)
jsmn.delegate_ack_err(ack, ctx, ret, err_msg);
return ret;
}
////////////////////
//nbܵûص
////////////////////
///////////////////////////
//nbϢѭ֮ǰ
///////////////////////////
int enter(nb_info_t* pnb)
{
api_io.init(WIFIIO_GPIO_17, OUT_PUSH_PULL);
api_io.init(WIFIIO_GPIO_18, OUT_PUSH_PULL);
api_io.init(WIFIIO_GPIO_19, OUT_PUSH_PULL);
api_io.init(WIFIIO_GPIO_20, OUT_PUSH_PULL);
api_io.init(WIFIIO_GPIO_21, OUT_PUSH_PULL);
api_io.init(WIFIIO_GPIO_22, OUT_PUSH_PULL);
api_io.low(WIFIIO_GPIO_17);
api_io.low(WIFIIO_GPIO_18);
api_io.low(WIFIIO_GPIO_19);
api_io.low(WIFIIO_GPIO_20);
api_io.low(WIFIIO_GPIO_21);
api_io.low(WIFIIO_GPIO_22);
LOG_INFO("dollcatch:IO initialized.\r\n");
//////////////////////////////////////////////////////
//STATE_OKֵ֮Ϣѭֱ˳
//////////////////////////////////////////////////////
return STATE_OK;
}
///////////////////////////
//nbյ˳Ϣʱ
///////////////////////////
int before_exit(nb_info_t* pnb)
{
return STATE_OK;
}
///////////////////////////
//˳nbϢѭ֮
///////////////////////////
int exit(nb_info_t* pnb)
{
return STATE_OK;
}
////////////////////
//صϳɽṹ
////////////////////
static const nb_if_t nb_dollcatch_if = {enter, before_exit, exit};
////////////////////////////////////////
//ÿһaddonmainúڼغ
// ʺ:
// addonл飻
// ʼݣ
// ADDON_LOADER_GRANTED ºغ
//ж
//ú wifiIO
////////////////////////////////////////
int main(int argc, char* argv[])
{
nb_info_t* pnb;
if(NULL != api_nb.find(NB_NAME)){ //жϷǷѾ
LOG_WARN("main:Service exist,booting abort.\r\n");
goto err_exit;
}
////////////////////////////////////////
//ǽһnbܳḶ̌
//ΪNB_NAME
////////////////////////////////////////
if(NULL == (pnb = api_nb.info_alloc(0))) //nbṹ
goto err_exit;
api_nb.info_preset(pnb, NB_NAME, &nb_dollcatch_if); //ṹ
if(STATE_OK != api_nb.start(pnb)){
LOG_WARN("main:Start error.\r\n");
api_nb.info_free(pnb);
goto err_exit;
}
LOG_INFO("main:Service starting...\r\n");
return ADDON_LOADER_GRANTED;
err_exit:
return ADDON_LOADER_ABORT;
}
|
C | #include<stdio.h>
#include<conio.h>
void main()
{
int large, slarge, a,b,c;
clrscr();
printf("================================\n\n");
printf("Finding Largest and Second largest Among 3 Nos\n\n");
printf("================================\n\n");
printf("Enter 3 Numbers");
scanf("%d%d%d",&a,&b,&c);
if((a>b)&&(a>c))
{
large=a;
if(b>c)
slarge=b;
else
slarge=c;
}
else if((b>c)&&(b>a))
{
large=b;
if(a>c)
slarge=a;
else
slarge=c;
}
else
{
large=c;
if(b>c)
slarge=b;
else
slarge=c;
}
printf("Large = %d, Second Large =%d", large,slarge);
getch();
}
|
C | /// III.SINGLY LINKED LIST ///
// 14.ADDING NEW NODE BEFORE A GIVEN NODE //
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *next;
};
typedef struct node NODE;
NODE *Create_Node(int data){
NODE *ptr = (NODE *)malloc(sizeof(struct node));
ptr->data = data;
ptr->next = NULL;
return ptr;
}
NODE *Add_At_End(NODE *head, int data){
NODE *temp = Create_Node(data);
NODE *ptr = head;
if(head==NULL){
head = temp;
}
else{
while(ptr->next!=NULL){
ptr = ptr->next;
}
ptr->next = temp;
}
return head;
}
NODE *Insert_Before_Node(NODE *head, int newdata, int data){
NODE *temp = Create_Node(newdata);
NODE *ptr = head;
if(head == NULL || head->data > data){
temp->next = head;
head = temp;
}
else{
ptr = head;
while(ptr->next!=NULL && ptr->next->data != data){
ptr = ptr->next;
}
temp->next = ptr->next;
ptr->next = temp;
}
return head;
}
void Print_Data(NODE *head){
NODE *ptr = head;
if(ptr==NULL){
printf("Linked List is Empty!\n");
}
else{
while(ptr != NULL){
printf("%d ",ptr->data);
ptr = ptr->next;
}
printf("\n");
}
}
int main()
{
NODE *head = NULL;
head = Add_At_End(head,10);
head = Add_At_End(head,20);
head = Add_At_End(head,30);
head = Add_At_End(head,40);
head = Insert_Before_Node(head,100,20);
Print_Data(head);
return 0;
}
|
C | #include<stdio.h>
int main()
{
int a,b;
FILE *fp;
fp=fopen("f1.txt","w");
printf("Enter two numbers\n");
scanf("%d %d",&a,&b);
fprintf(fp,"Sum of %d & %d is %d",a,b,a+b);
fclose(fp);
}
|
C |
#include "arena.h"
void push_free_stack( struct slab_struct *slab ){
// add necessary code
struct slab_struct *rover=free_stack;
struct slab_struct *dover=slab;
struct slab_struct *end;
if(slab==NULL)
return;
while(dover->next!=NULL){
dover=dover->next;
}
end=dover;
while(rover!=NULL && rover->next!=NULL){
rover=rover->next;
}
dover=free_stack;
if (free_stack==NULL){
free_stack=slab;
}
else{
rover->next=slab;
}
rover=free_stack;
while(rover != end){
rover=rover->next;
}
rover->next=NULL;
}
struct slab_struct *pop_free_stack( int arena_id ){
struct slab_struct *return_value = free_stack;
struct slab_struct *rover = free_stack;
// add necessary code
if(return_value->next==NULL){
free_stack=NULL;
return return_value;
}
if(return_value->next!=NULL){
return_value=return_value->next;
}
while(return_value->next!=NULL){
return_value=return_value->next;
rover=rover->next;
}
return_value->arena_id=arena_id;
rover->next=NULL;
return_value->next=NULL;
return return_value;
}
void arena_init(){
int i;
for( i = 0; i < N_SLABS; i++ ){
slab[i].next = NULL;
slab[i].ptr = &(slab[i].bytes[0]);
slab[i].arena_id = -1;
}
for( i = 0; i < N_ARENAS; i++ ){
arena[i] = &slab[i];
slab[i].arena_id = i;
arena_ref_cnt[i] = 0;
}
free_stack = NULL;
for( i = N_ARENAS; i < N_SLABS; i++ ){
push_free_stack( &slab[i] );
}
}
int release_arena( int arena_id ){
struct slab_struct *current;
if( (arena_id < 0) || (arena_id >= N_ARENAS) ){
printf( "release: bad arena_id\n" );
return 1;
}
if( arena[arena_id] == NULL ){
printf( "release: null arena ptr\n" );
return 2;
}
if( arena_ref_cnt[arena_id] > 0 ){
printf( "warning: releasing a region with %d references\n",
arena_ref_cnt[arena_id] );
}
// add code to reset all slabs and return all but first to the free list
// (traverse singly-linked slab list and push slabs in that order)
current = arena[arena_id]->next;
while( current != NULL ){
current->arena_id=-1;
current->ptr=¤t->bytes[0];
current = current->next;
}
current=arena[arena_id]->next;
push_free_stack(current);
// remember to set the arena_id fields of freed slabs to -1
current=arena[arena_id];
current->ptr=¤t->bytes[0];
arena_ref_cnt[arena_id]=0;
current->next=NULL;
return 0;
}
unsigned char *alloc_from_arena( int arena_id, int size ){
struct slab_struct *current;
unsigned char *return_ptr;
if( (arena_id < 0) || (arena_id >= N_ARENAS) ){
printf( "alloc: bad arena_id\n" );
return NULL;
}
if( size > N_BYTES ){
printf( "alloc: requested size too large\n" );
return NULL;
}
current = arena[arena_id];
if(current->next==NULL){
if(size <= ¤t->bytes[N_BYTES] - current->ptr){
return_ptr= current->ptr+size;
current->ptr=return_ptr;
arena_ref_cnt[arena_id]++;
return return_ptr;
}
}
else{
while(current->next!=NULL){
if(size <= ¤t->bytes[N_BYTES] - current->ptr){
return_ptr= current->ptr+size;
current->ptr=return_ptr;
arena_ref_cnt[arena_id]++;
return return_ptr;
}
current=current->next;
}
}
if(size <= ¤t->bytes[N_BYTES] - current->ptr){
return_ptr= current->ptr+size;
current->ptr=return_ptr;
arena_ref_cnt[arena_id]++;
return return_ptr;
}
// add code to return a pointer if space is available, otherwise
// return NULL
if(free_stack!=NULL){
current->next=pop_free_stack(arena_id);
current=current->next;
current->next=NULL;
current->arena_id=arena_id;
if(size <= ¤t->bytes[N_BYTES] - current->ptr){
return_ptr= current->ptr+size;
current->ptr=return_ptr;
arena_ref_cnt[arena_id]++;
return return_ptr;
}
}
current = arena[arena_id];
while(current!=NULL){
current=current->next;
}
current =arena[arena_id];
return NULL;
// remember to set the arena_id field of an added slabs to the value
// of the arena specified by the input parameter
}
// return input argument so usage can be p2 = copy_ptr( p1 );
unsigned char* copy_ptr( unsigned char *ptr ){
int i, arena_id;
for( i = 0; i < N_SLABS; i++ ){
if(ptr >= &slab[i].bytes[0] && ptr <= &slab[i].bytes[N_BYTES]){
// add code to determine if the pointer falls into
// an allocated area within this slab
arena_id = slab[i].arena_id;
if( (arena_id < 0) || (arena_id >= N_ARENAS) ){
printf( "copy ptr: bad arena_id\n" );
return NULL;
}
arena_ref_cnt[arena_id]++;
return ptr;
}
}
printf( "copy ptr: ptr was not within an allocated area in a slab\n" );
return NULL;
}
void delete_ptr( unsigned char *ptr ){
int i, arena_id;
for( i = 0; i < N_SLABS; i++ ){
if(ptr >= &slab[i].bytes[0] && ptr <= &slab[i].bytes[N_BYTES]){
// add code to determine if the pointer falls into
// an allocated area within this slab
arena_id = slab[i].arena_id;
if( arena_ref_cnt[arena_id] <= 0 ){
printf( "delete ptr: bad ref count\n" );
}else{
arena_ref_cnt[arena_id]--;
}
if( arena_ref_cnt[arena_id] == 0 ) release_arena( arena_id );
return;
}
}
printf( "delete ptr: ptr was not within an allocated area in a slab\n" );
}
void print_arena( int arena_id ){
struct slab_struct *current;
if( (arena_id < 0) || (arena_id >= N_ARENAS) ){
printf( "print arena: bad arena_id\n" );
exit(-1);
}
printf( "a%d: allocated spaces", arena_id );
current = arena[arena_id];
while( current != NULL ){
printf( " %d,", (int)(current->ptr - ¤t->bytes[0]) );
current = current->next;
}
printf( " refs=%d\n", arena_ref_cnt[arena_id] );
}
void print_arena_ids(){
int i;
printf( "slab arena_id values:" );
for( i = 0; i < N_SLABS; i++ ){
printf( " %d", slab[i].arena_id );
}
printf( "\n" );
}
|
C | #include "rbtree.h"
/* -------------------------------------------- */
/* Private interface : */
/* binary search tree with red-black coloring */
/* -------------------------------------------- */
/* -------------------------------------------- */
/* Type definition : */
/* -------------------------------------------- */
#define RED 'r'
#define BLACK 'b'
struct _rbtree {
RedBlackTree parent;
RedBlackTree left;
RedBlackTree right;
int root;
unsigned char color;
};
/* -------------------------------------------- */
/* Visitors */
/* -------------------------------------------- */
#define MAXFILE 4096
typedef struct s_queue {
RedBlackTree queue[MAXFILE];
int head;
int tail;
} *QueueOfBinaryTrees;
QueueOfBinaryTrees queue_create() {
QueueOfBinaryTrees f = (QueueOfBinaryTrees) malloc(sizeof(struct s_queue));
f->head = 0;
f->tail = 0;
return f;
}
void queue_push(QueueOfBinaryTrees f, RedBlackTree a) {
f->queue[f->head] = a;
f->head = (f->head + 1) % MAXFILE;
}
RedBlackTree queue_pop(QueueOfBinaryTrees f) {
RedBlackTree a = f->queue[f->tail];
f->tail = (f->tail + 1) % MAXFILE;
return (a);
}
int queue_empty(QueueOfBinaryTrees f) {
return (f->tail == f->head);
}
void queue_delete(QueueOfBinaryTrees f) {
free(f);
}
/* -------------------------------------------- */
/* Export the tree as a dot file */
/* -------------------------------------------- */
void printNode(RedBlackTree n, FILE *file){
if (n->color == RED) {
fprintf(file, "\tn%d [style=filled, fillcolor=red, label=\"{{<parent>}|%d|{<left>|<right>}}\"];\n",
n->root, n->root);
} else {
fprintf(file, "\tn%d [style=filled, fillcolor=grey, label=\"{{<parent>}|%d|{<left>|<right>}}\"];\n",
n->root, n->root);
}
if (n->left){
fprintf(file, "\tn%d:left:c -> n%d:parent:c [headclip=false, tailclip=false]\n",
n->root, n->left->root);
} else {
fprintf(file, "\tlnil%d [style=filled, fillcolor=black, label=\"NIL\"];\n", n->root);
fprintf(file, "\tn%d:left:c -> lnil%d:c [headclip=false, tailclip=false]\n",
n->root, n->root);
}
if (n->right){
fprintf(file, "\tn%d:right:c -> n%d:parent:c [headclip=false, tailclip=false]\n",
n->root, n->right->root);
} else {
fprintf(file, "\trnil%d [style=filled, fillcolor=black, label=\"NIL\"];\n", n->root);
fprintf(file, "\tn%d:right:c -> rnil%d:c [headclip=false, tailclip=false]\n",
n->root, n->root);
}
}
void rbtree_export_dot(RedBlackTree t, FILE *file) {
QueueOfBinaryTrees q = queue_create();
fprintf(file, "digraph RedBlackTree {\n\tgraph [ranksep=0.5];\n\tnode [shape = record];\n\n");
queue_push(q, t);
while (!queue_empty(q)) {
t = queue_pop(q);
printNode(t, file);
if (!rbtree_empty(rbtree_left(t)))
queue_push(q, rbtree_left(t));
if (!rbtree_empty(rbtree_right(t)))
queue_push(q, rbtree_right(t));
}
fprintf(file, "\n}\n");
}
/*---------------------------------------------------*/
/* Implementation of RedBlackTree */
/*---------------------------------------------------*/
RedBlackTree rbtree_create(){
return NULL;
}
RedBlackTree rbtree_construct(RedBlackTree left,RedBlackTree right, int root){
RedBlackTree t = (RedBlackTree)malloc(sizeof(struct _rbtree));
//initialisation de t qui devient la racine de l'arbre
t->parent = NULL;
t->left = left;
t->right = right;
t->root = root;
//initialisation du parent de l'arbre de gauche
if(left)
left->parent = t;
//initialisation du parent de l'arbre de droite
if(right)
right->parent = t;
return t;
}
bool rbtree_empty(RedBlackTree t){
return (t == NULL);
}
RedBlackTree rbtree_left(RedBlackTree t){
return t->left;
}
RedBlackTree rbtree_right(RedBlackTree t){
return t->right;
}
void leftrotate(RedBlackTree *t){
RedBlackTree x = *t;
RedBlackTree y = x->right;
x->right = y->left;
if(y->left != NULL)
y->left->parent = x;
y->parent = x->parent;
if(y->parent!=NULL){
if(x == x->parent->left)
x->parent->left = y;
else
x->parent->right = y;
}
y->left = x;
x->parent = y;
*t = y;
}
void rightrotate(RedBlackTree *t){
RedBlackTree y = *t;
RedBlackTree x = y->left;
y->left = x->right;
if (x->right != NULL)
x->right->parent = y;
x->parent = y->parent;
if (x->parent != NULL) {
if (y == y->parent->right)
y->parent->right = x;
else
y->parent->left = x;
}
x->right = y;
y->parent = x;
*t = x;
}
void rbtree_add(RedBlackTree *t,int root) {
RedBlackTree new=rbtree_construct(NULL,NULL,root);
new->color=RED;
RedBlackTree itr=*t;
RedBlackTree tmpNode;
if(itr){
do{
tmpNode=itr;
if(root > itr->root){
itr=itr->right;
if(!itr){
tmpNode->right=new;
new->parent=tmpNode;
}
}
else{
itr=itr->left;
if(!itr){
tmpNode->left=new;
new->parent=tmpNode;
}
}
}while(itr);
}
else
*t=new;
fixredblackproperties_insert(&new);
}
RedBlackTree grandparent(RedBlackTree x){
if((x != NULL) && (x->parent != NULL))
return x->parent->parent;
else
return NULL;
}
RedBlackTree uncle(RedBlackTree x){
RedBlackTree y = grandparent(x);
if(y == NULL)
return NULL;
if(x->parent == y->left)
return y->right;
else
return y->left;
}
void fixredblackproperties_insert(RedBlackTree *x){
if ((*x)->color == RED)
fix_insert_case0(x);
}
void fix_insert_case0(RedBlackTree *x){
if((*x)->parent == NULL)
(*x)->color = BLACK;
else if ((*x)->parent->color == RED)
fix_insert_case1(x);
}
void fix_insert_case1(RedBlackTree *x){
RedBlackTree f = uncle((*x));
if(f != NULL && f->color == RED){
RedBlackTree pp = grandparent((*x));
(*x)->parent->color = BLACK;
f->color = BLACK;
pp->color = RED;
fix_insert_case0(&pp);
}
else
fix_insert_case2(x);
}
void fix_insert_case2(RedBlackTree *x) {
if (grandparent((*x)) == (*x)->parent) {
fix_insert_case2_left(x);
} else{
fix_insert_case2_right(x);
}
}
void fix_insert_case2_left(RedBlackTree *x) {
RedBlackTree p = ((*x)->parent);
RedBlackTree pp = grandparent((*x));
if ((*x) == (p)->right) {
leftrotate(&p);
(*x) = ((*x)->left);
}
(*x)->parent->color = BLACK;
(pp)->color = RED;
rightrotate(&pp);
}
void fix_insert_case2_right(RedBlackTree *x) {
RedBlackTree p = ((*x)->parent);
RedBlackTree pp = grandparent((*x));
if ((*x) == (p)->right) {
rightrotate(&p);
(*x) = ((*x)->left);
}
(*x)->parent->color = BLACK;
(pp)->color = RED;
leftrotate(&pp);
}
|
C | #include<stdio.h>
#include<stdlib.h>
struct Emp {
int eid;
char ename[20];
float esal;
};
int main(){
struct Emp *ptr;
ptr=(struct Emp *)malloc(sizeof(struct Emp));
if(ptr==NULL){
printf("memory allocation fails");
}
else{
printf("Enter employee details");
scanf("%d%s%f",&ptr->eid,ptr->ename,&ptr->esal);
printf("Ename:%s\nEid:%d\nEsal:%f",ptr->ename,ptr->eid,ptr->esal);
}
}
|
C | #include<iostream>
#include<memory>
#include<stack>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
};
Node *allocateNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
void printSpiral(Node *root)
{
if(root == NULL)
return;
stack<Node *> s1;
stack<Node *> s2;
s1.push(root);
while(!s1.empty() || !s2.empty())
{
while(!s1.empty())
{
Node *temp = s1.top();
s1.pop();
cout << temp->data << " ";
if(temp->right != NULL)
s2.push(temp->right);
if(temp->left != NULL)
s2.push(temp->left);
}
while(!s2.empty())
{
Node *temp = s2.top();
s2.pop();
cout << temp->data << " ";
if(temp->left != NULL)
s1.push(temp->left);
if(temp->right != NULL)
s1.push(temp->right);
}
}
}
int main()
{
Node *root = allocateNode(1);
root->left = allocateNode(2);
root->right = allocateNode(3);
root->left->left = allocateNode(7);
root->left->right = allocateNode(6);
root->right->left = allocateNode(5);
root->right->right = allocateNode(4);
cout << "Spiral Order traversal of binary tree is: \n";
printSpiral(root);
return 0;
}
|
C | typedef struct DuLNode {
ElemType data;
struct DuLNode *prior;
struct DuLNode *next;
} DuLNode, *DuLinkList;
// 空的双向循环链表
L->next == L->prior == L;
// 在带表头结点的双向循环链表 L 中 P 结点之前插入结点 S
void ListInsert_DuL(DuLinkList &L, DuLNode *p, DuLNode *s) {
s->prior = p->prior;
s->next = p;
p->prior->next = s;
p->prior = s;
}
// 删除带头结点的双向循环链表 L 中的 P 结点,以 e 返回他的数据元素
void ListDel_DuL(DuLinkList &L, DuLNode *p, ElemType &e) {
e = p->data;
p->prior->next = p->next;
p->next->prior = p->prior;
delete p;
} |
C | #include <stdio.h>
#include <string.h>
int sort_word(char *word1, char *word2);
void insertion_sort(char *word1,char *word2,int n);
void verify_anagram(char *word1,char *word2,int n);
int main()
{
char word1[20],word2[20];
printf("Enter first word in uppercase letters= ");
fgets(word1,20,stdin);
printf("Enter second word in uppercase letters = ");
fgets(word2,20,stdin);
sort_word(word1,word2);
}
/* The following funtion converts the letters in the word
to their ASCII format for easier sorting before passing them
as arguements to the insertion_sort function */
int sort_word(char *word1, char *word2)
{
int n = strlen(word1);
char n_word1[20],n_word2[20];
for(int i=0;i<n-1;i++)
{
n_word1[i] = word1[i]-'A';
}
for(int i=0;i<n-1;i++)
{
n_word2[i] = word2[i]-'A';
}
insertion_sort(n_word1,n_word2,n);
}
/*The following function performs insertion sort algorithm to
sort the letters in the words before passing them as arguments
to the verify_anagram function*/
void insertion_sort(char *word1,char *word2,int n)
{
//sorting first word using insertion sort algorithm
int i=1, key;
for (i=1;i<n-1;i++)
{
key = word1[i];
int j = i-1;
while(j>=0 && word1[j]>key)
{
word1[j+1] = word1[j];
j = j-1;
}
word1[j+1] = key;
}
//sorting second word using insertion sort algorithm
for (i=1;i<n-1;i++)
{
key = word2[i];
int j = i-1;
while(j>=0 && word2[j]>key)
{
word2[j+1] = word2[j];
j = j-1;
}
word2[j+1] = key;
}
verify_anagram(word1,word2,n);
}
/*The following function verifies if the two words are anagram
by comparing their sorted counterparts*/
void verify_anagram(char *word1,char *word2,int n)
{
int x = 0;
int count=0;
while(word1[x]==word2[x] && x<n-1)
{
count = count+1;
x=x+1;
}
if(count==n-1)
printf("The words are anagrams");
else
printf("The words are not anagrams");
}
|
C | #include <lpc214x.h> / if in local folder use "lpc214x.h"
#include <stdint.h>
//Sin = 512 + (511*sin((360*n)/42))
void delay_ms(uint16_t j)
{
uint16_t x,i;
for(i=0;i<j;i++)
{
for(x=0; x<6000; x++); /* loop to generate 1 ms
delay with Cclk = 60MHz */
}
}
int main (void)
{
uint16_t value;
uint8_t i;
i = 0;
PINSEL1 = 0x00080000; /* P0.25 as DAC output */
IO0DIR = 0xFFFFFFFF;
uint16_t sin_wave[] = { 512,591,665,742,808,873,926,968,998,1017,1023,1017,998,968,926,873,808,742,665,591,512,436,359,282,216,211,151,97,55,25,6,0,6,25,55,97,151,211,216,282,359,436 };
while(1)
{
while(i !=42) /* number of points*/
{
value = sin_wave[i]*50;
DACR = value; delay_ms(1);
i++;
}
i = 0;
}
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jjauzion <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/07 17:20:27 by jjauzion #+# #+# */
/* Updated: 2018/01/29 19:22:03 by jjauzion ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char *ft_obase(unsigned int base)
{
unsigned int i;
char *obase;
obase = ft_strnew(base);
i = -1;
while (++i < base)
{
if (i < 10)
obase[i] = '0' + i;
else
obase[i] = 'a' + i - 10;
}
return (obase);
}
char *ft_uitoa_base(uintmax_t value, uintmax_t base)
{
char *obase;
char *res;
int i;
if (base < 2 || base > 16)
return (NULL);
obase = ft_obase(base);
if (!(res = ft_strnew((sizeof(uintmax_t) * 8))))
return (NULL);
i = 0;
while (value >= base)
{
res[i] = obase[value % base];
value = value / base;
i++;
}
res[i] = obase[value % base];
res[i + 1] = '\0';
res = ft_strrev(res);
ft_strdel(&obase);
return (res);
}
|
C | #include<stdio.h>
int isleap(int year)
{
if(year%400==0)
{
return 0;
}
else if(year%100==0)
{
return 1;
}
else if(year%4==0)
{ return 2;
}
else
{
return -1;
}
}
int main()
{
int year,r;
printf("enter the year \n");
scanf("%d",&year);
r=isleap(year);
switch(r)
{
case 0:
printf("%d is a qudrenil leap year \n",year);
break;
case -1:
printf("%d is not a leap year\n",year);
break;
case 1:
printf("%d is a centuary year\n",year);
break;
case 2:
printf("%d is a leap year\n",year);
break ;
}
return 0;
}
|
C | #ifndef _PAGE_FAULT_HANDLER_H
#define _PAGE_FAULT_HANDLER_H
#include <defs.h>
/**
* When page fault occurs:
* (1) Check address that caused fault
* (2) Check if memory area exists for the address
* (3) If yes, add a physical page for the location with required protection
* (4) In case of file backed vma, load file contents into page
* @param err_code page-fault error code
* @return OK or ERROR
*/
int page_fault_handler(uint64_t err_code);
/*----------------------------------------------------------------------------*/
/* Page fault error code */
/* Bit 0: 0 - Page not present 1 - Page protection violation */
#define PF_ERROR_CODE_P 0x1UL
/* Bit 1: 0 - Memory read 1 - Memory write */
#define PF_ERROR_CODE_W 0x2UL
/* Bit 2: 0 - Supervisor mode 1 - User mode */
#define PF_ERROR_CODE_U 0x4UL
/*-------- Kinda not used --------*/
/* Bit 3: RSV */
#define PF_ERROR_CODE_RSV 0x8UL
/* Bit 4: ID */
#define PF_ERROR_CODE_ID 0x16UL
/*--------------------------------*/
/*----------------------------------------------------------------------------*/
#endif
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jfrancis <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/20 18:22:20 by jfrancis #+# #+# */
/* Updated: 2021/05/15 23:57:32 by jfrancis ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_words(char const *s, char c)
{
size_t wc;
unsigned int i;
int temp;
wc = 0;
i = 0;
temp = 0;
if (!s)
return (wc);
while (s[i] != '\0')
{
if (s[i] == c)
temp = 1;
if (s[i] != c && temp == 0)
{
wc++;
temp = 1;
}
else if (s[i] == c && temp == 1)
{
temp = 0;
}
i++;
}
return (wc);
}
int ln(char *s, int i, char c)
{
int count;
count = 0;
while (s[i] != c && s[i])
{
count++;
i++;
}
return (count);
}
static void cut_str(char const *s, char **s_array, int i, char c)
{
int j;
int k;
j = 0;
k = 0;
while (s[i] != c && s[i])
s_array[j][k++] = s[i++];
s_array[j++][k] = '\0';
}
char **ft_split(char const *s, char c)
{
char **s_array;
int i;
int j;
i = 0;
j = 0;
s_array = malloc(sizeof(char *) * (count_words(s, c) + 1));
if (!s || !s_array)
return (NULL);
while (s[i])
{
while (s[i] == c && s[i])
i++;
if (s[i])
{
s_array[j] = malloc(sizeof(char) * ln((char *)s, i, c) + 1);
if (!s_array[j])
return (NULL);
cut_str(s, s_array, i, c);
}
}
s_array[j] = NULL;
return (s_array);
}
|
C | /*
** create_tab.c for 42sh.h in /u/epitech_2012/sellie_a/cu/42sh/mysh
**
** Made by arnaud sellier
** Login <[email protected]>
**
** Started on Wed Jun 11 15:27:14 2008 arnaud sellier
** Last update Thu Jun 12 16:38:24 2008 arnaud sellier
*/
#include "42sh.h"
void free_completion_tab(t_vector *target)
{
int i;
i = 0;
while (vector_size(target))
xsfree(vector_pop(target));
vector_free(target);
}
void create_local_tab(t_param *param)
{
DIR *dir;
struct dirent *dp;
struct stat s;
char buf[1024];
param->local_tab = vector_init();
if ((dir = opendir(".")) == NULL)
return;
while ((dp = readdir(dir)) != NULL)
{
strcpy(buf, dp->d_name);
stat(buf, &s);
if (S_ISDIR(s.st_mode))
strcat(buf, "/");
vector_push(param->local_tab, my_strdup(buf));
}
closedir(dir);
}
int create_files_tab(t_param *param, t_vector *filehist,
char *begin)
{
DIR *dir;
read_tild(param, begin);
if ((dir = opendir(begin)) == NULL)
{
if (access(begin, F_OK))
{
my_printf("\n%s: no such file or directory.\n\n", begin);
return (1);
}
else if (access(begin, R_OK) || access(begin, X_OK))
{
my_printf("\n%s unreadable.\n\n", begin);
return (1);
}
}
read_this_folder(filehist, dir, begin);
closedir(dir);
return (0);
}
void create_cmd_tab(t_param *param)
{
char *path;
DIR *dir;
param->cmd_tab = vector_init();
while ((path = get_next_path(param->env)))
{
if ((dir = opendir(path)) == NULL)
continue;
read_this_path(param->cmd_tab, dir, path);
closedir(dir);
}
if ((dir = opendir(".")) == NULL)
return;
read_local_cmd(param->cmd_tab, dir);
closedir(dir);
}
|
C | #include <gumo/renderer/shader.h>
#include <gl/glew.h>
#include <glfw/glfw3.h>
#include <stdio.h>
const color_t COLOR_BLUE = {0.2f, 0.3f, 0.8f, 1.0f};
const color_t COLOR_RED = {0.8f, 0.3f, 0.2f, 1.0f};
const color_t COLOR_GREEN = {0.2f, 0.8f, 0.3f, 1.0f};
const color_t COLOR_WHITE = {1.0f, 1.0f, 1.0f, 1.0f};
const color_t COLOR_BLACK = {0.0f, 0.0f, 0.0f, 1.0f};
void compile_shader(const char* vertex_source, const char* fragment_source, shader_t* shader)
{
// Create an empty vertex shader handle
unsigned int vertex_shader = glCreateShader(GL_VERTEX_SHADER);
// Send the vertex shader source code to GL
glShaderSource(vertex_shader, 1, &vertex_source, NULL);
// Compile the vertex shader
glCompileShader(vertex_shader);
int success = 0;
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
if(success == false)
{
// The maxLength includes the NULL character
char info_log[512];
glGetShaderInfoLog(vertex_shader, 512, NULL, info_log);
// We don't need the shader anymore.
glDeleteShader(vertex_shader);
// Use the infoLog as you see fit.
GM_LOG_ERROR("Vertex shader compilation failure!");
GM_LOG_ERROR(info_log);
// In this simple program, we'll just leave
return;
}
// Create an empty fragment shader handle
unsigned int fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
// Send the fragment shader source code to GL
glShaderSource(fragment_shader, 1, &fragment_source, NULL);
// Compile the fragment shader
glCompileShader(fragment_shader);
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
if (success == false)
{
// The max_length includes the NULL character
char info_log[512];
glGetShaderInfoLog(fragment_shader, 512, NULL, &info_log[0]);
// We don't need the shader anymore.
glDeleteShader(fragment_shader);
// Either of them. Don't leak shaders.
glDeleteShader(vertex_shader);
// Use the infoLog as you see fit.
GM_LOG_ERROR("Fragment shader compilation failure!");
GM_LOG_ERROR(info_log);
// In this simple program, we'll just leave
return;
}
// Vertex and fragment shaders are successfully compiled.
// Now time to link them together into a program.
// Get a program object.
unsigned int program = glCreateProgram();
// Attach our shaders to our program
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
// Link our program
glLinkProgram(program);
// Note the different functions here: glGetProgram* instead of glGetShader*.
glGetProgramiv(program, GL_LINK_STATUS, &success);
if (success == false)
{
// The maxLength includes the NULL character
char info_log[512];
glGetProgramInfoLog(program, 512, NULL, &info_log[0]);
// We don't need the program anymore.
glDeleteProgram(program);
// Don't leak shaders either.
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
// Use the infoLog as you see fit.
GM_LOG_ERROR("Shader link failure!");
GM_LOG_ERROR(info_log);
// In this simple program, we'll just leave
return;
}
// Always detach shaders after a successful link.
glDetachShader(program, vertex_shader);
glDetachShader(program, fragment_shader);
shader->id = program;
//shader->vertex = vertex_shader;
//shader->fragment = fragment_shader;
}
inline void delete_shader(shader_t* shader)
{
glDeleteProgram(shader->id);
}
inline void bind_shader(shader_t* shader)
{
glUseProgram(shader->id);
}
void shader_set_int(shader_t* shader, const char* name, int value)
{
int location = glGetUniformLocation(shader->id, name);
glUniform1i(location, value);
}
void shader_set_int_array(shader_t* shader, const char* name, int* values, unsigned int length)
{
int location = glGetUniformLocation(shader->id, name);
glUniform1iv(location, length, values);
}
void shader_set_float(shader_t* shader, const char* name, float value)
{
int location = glGetUniformLocation(shader->id, name);
glUniform1f(location, value);
}
void shader_set_float2(shader_t* shader, const char* name, struct vec2 value)
{
int location = glGetUniformLocation(shader->id, name);
glUniform2f(location, value.x, value.y);
}
void shader_set_float3(shader_t* shader, const char* name, struct vec3 value)
{
int location = glGetUniformLocation(shader->id, name);
glUniform3f(location, value.x, value.y, value.z);
}
void shader_set_float4(shader_t* shader, const char* name, struct vec4 value)
{
int location = glGetUniformLocation(shader->id, name);
glUniform4f(location, value.x, value.y, value.z, value.w);
}
void shader_set_color(shader_t* shader, const char* name, color_t value)
{
int location = glGetUniformLocation(shader->id, name);
glUniform4f(location, value.r, value.g, value.b, value.a);
}
void shader_set_matrix4(shader_t* shader, const char* name, const matrix4_t* matrix4)
{
int location = glGetUniformLocation(shader->id, name);
glUniformMatrix4fv(location, 1, GL_FALSE, (float* )matrix4);
} |
C | /**
* sigLib, simple Signals Library
*
* Copyright (C) 2013 Charles-Henri Mousset
*
* This file is part of sigLib.
*
* sigLib is free software: you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* sigLib 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 Lesser General Public License for more details. You should have received a copy of the GNU
* General Public License along with sigLib. If not, see <http://www.gnu.org/licenses/>.
*
* Authors: Charles-Henri Mousset
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "csv.h"
int csv_load(char *path, int *size, float ***data)
{
FILE *fd;
char *cell, line[CSV_BUFF_LEN], *ret;
int i, ncols = 0, nlines = 0, curr_line = 0;
float **output;
fd = fopen(path, "r");
if(fd == NULL)
{
printf("can't open file %s\n", path);
return -1;
}
rewind(fd);
// get first line to get the header
ret = fgets(line, CSV_BUFF_LEN, fd);
if(ferror(fd))
{
printf("can't read file\n");
return -2;
}
cell = strtok(line, ",;\t");
while (cell)
{
++ncols;
cell = strtok(NULL,",;\t");
}
// create a table containing pointers to the data tables
output = calloc(ncols + 1, sizeof(float *));
*data = output;
// count the lines in our file
do
{
++nlines;
ret = fgets(line, CSV_BUFF_LEN, fd);
} while (ret);
// get memory for that
for(i=0; i<ncols; i++)
{
output[i] = malloc(nlines * sizeof(float));
if(output[i] == NULL)
{
printf("cannot allocate memory for the data of colum %d (%d lines)\n", i, nlines);
return -3;
}
}
// got to the start of the file, and ignore first line
rewind(fd);
ret = fgets(line, CSV_BUFF_LEN, fd);
// read the first line of data
ret = fgets(line, CSV_BUFF_LEN, fd);
while (feof(fd) == 0)
{
if(ferror(fd))
{
printf("can't read file at line %d (data index %d)\n", curr_line+1, curr_line);
return -2;
}
i = 0;
cell = strtok(line, ",;\t");
while(cell)
{
if(i >= ncols)
{
printf("line %d has %d columns, expecting %d\n", curr_line+1, i, ncols);
return -3;
}
output[i][curr_line] = strtof(cell, NULL);
cell = strtok(NULL, ",;\t");
i++;
}
if(i < ncols)
{
printf("line %d has %d columns, expecting %d\n", curr_line+1, i, ncols);
return -4;
}
curr_line++;
// get a line of values
ret = fgets(line, CSV_BUFF_LEN, fd);
}
*size = nlines-1;
return 0;
}
int csv_display(float **csv, int csv_l)
{
int csv_cols=0, i, j;
if (csv == NULL)
return -1;
while (csv[csv_cols])
++csv_cols;
printf("size of CSV is %d columns, %d lines of data\n", csv_cols, csv_l);
for(i=0; i < csv_l; i++)
{
for(j=0; j < csv_cols; j++)
{
printf("%f", csv[j][i]);
if(j < csv_cols-1)
printf(", ");
else
printf("\n");
}
}
return 0;
}
void csv_free(float **csv)
{
int i=0;
if(csv == NULL)
return;
while(csv[i])
free(csv[i++]);
free(csv);
}
|
C |
//这是一个简单的udpk客户端
//
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
int main()
{
int sockfd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if(sockfd<0)
perror("create error");
//client need not bind;
struct sockaddr_in severaddr;
severaddr.sin_family=AF_INET;
severaddr.sin_port=htons(9000);
severaddr.sin_addr.s_addr=inet_addr("10.10.31.119");
socklen_t len=sizeof(severaddr);
while(1)
{
//after sendto,you can recvfrom
char buff[1024]={};
scanf("%s",buff);
sendto(sockfd,buff,strlen(buff),0,(struct sockaddr *)&severaddr,len);
memset(buff,0x00,1024);
//怎么复制粘贴?指定行内容
//怎么打开多个文件窗口?
//取消防火墙的命令?
// makefile 的编写?
ssize_t rlen=recvfrom(sockfd,buff,1023,0,(struct sockaddr*)&severaddr,&len);
if(rlen<=0)
{
perror("recv error");
return -1;
}
printf("sever say [%s]",buff);
}
close(sockfd);
return 0;
}
|
C | #include "globalv.h"
//Puts in random data in a non-life cell
void randomSpawner(int numOfOrganismsToSpawn, int length, int width) {
srand(time(NULL));
int i,j,count;
extern TableType table;
count = 0;
while(count < numOfOrganismsToSpawn){
i=rand()%length;
j=rand()%width;
if(table[i][j] != LIFE_YES){
table[i][j] = LIFE_YES;
count++;
}
}
}
|
C |
/// Taken from Posix Tutorial -- https://computing.llnl.gov/tutorials/pthreads/
// Example demonstrates Mutex control over Pies. Now add a Pie Producer
// And then a conditional ?
// R. Trenary, 1/26/12
//
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5
int Done [NUM_THREADS]; // A flag for each thread. AND them
// and one unfinished means we still have work
pthread_mutex_t MyMutex= PTHREAD_MUTEX_INITIALIZER; // A mutex and a cond (itional)
pthread_cond_t PiesToEat= PTHREAD_COND_INITIALIZER; // Initialized
int PieceOfPies; // Important shared variable
//==================================
// BAKER THREAD
//==================================
void *PieBaking(void *threadid) // THE BAKER
{int i, AllDone;
int rc ; // Return Code
while (1)
{ AllDone=1;
for (i=0;i<NUM_THREADS;i++) AllDone= ( Done[i] && AllDone);
if (AllDone) {printf("All Eaters are done \n"); break;}
do {rc = pthread_mutex_trylock(&MyMutex); // does this lock if successful ?
} while (rc !=0);
if (PieceOfPies == 0) {PieceOfPies +=2;
printf("Baked a couple of of pies\n");
}
// make a couple of pies if needed
pthread_cond_broadcast(&PiesToEat);
pthread_mutex_unlock(&MyMutex);
}
printf("Done Baking\n");
pthread_exit(NULL);
}
// ==================================
// EATER THREAD
// ==================================
void *PieEating(void *threadid)
{
long tid;
int rc = -1; // Initialize to not acquired
tid = * ((long *) threadid);
int PiecesEaten = 0; // Control Pieces Eaten by Thread
Done[tid] = 0; // Not Done
while (PiecesEaten < 2)
{
while ( rc !=0 )
{ rc = pthread_mutex_trylock(&MyMutex); // will return non zero if not acquired
usleep(100); // sleep and try again
}
printf(" Thread %lu acquired lock \n", tid);
// pthread_mutex_lock(&MyMutex);
if (PieceOfPies == 0) (pthread_cond_wait(&PiesToEat, &MyMutex));
printf("Eating pie for Dennis. It's me, thread #%ld!\n", tid);
PieceOfPies--; // critical section
pthread_mutex_unlock(&MyMutex);
// and sleep some of it off
usleep(100);
rc = -1;
printf("%d available piece of pies \n",PieceOfPies);
PiecesEaten++; // Ate a piece of pie
}
Done[tid] = 1; // All done
printf("Thread %lu is done and said so \n",tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
pthread_t PieBaker;
int rc;
long t;
long *Tptr[NUM_THREADS];
PieceOfPies = 0;
for(t=0; t<NUM_THREADS; t++)
{ Tptr[t] = (long *) malloc(sizeof(long));
(*Tptr[t]) = (long) t;
printf("In main: creating thread %lu\n", t);
rc = pthread_create(&threads[t], NULL, PieEating, (void *)Tptr[t]);
if (rc){
printf("ERROR; return code from pthread_create() for eaters is %d\n", rc);
exit(-1); }
}
rc = pthread_create(&PieBaker, NULL, PieBaking, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() for baker is %d\n", rc);
exit(-1);}
printf("looks like pies are done cooking\n");
/* Last thing that main() should do */
pthread_mutex_destroy(&MyMutex);
pthread_cond_destroy(&PiesToEat);
pthread_exit(NULL);
printf("Done in main\n");
exit(0);
}
|
C | #include <stdio.h>
#include <ctype.h>
int main()
{
int ch;
while((ch=getchar())!=EOF) {
if(islower(ch))
ch=toupper(ch);
else if(isupper(ch))
ch=tolower(ch);
putchar(ch);
}
putchar('\n');
}
|
C | /***********************************************************************
* Copyright (C) 2018 [email protected] All rights reserved.
* * File Name: main.c
* Brief: 本程序模拟简单的音乐播放器的控制流程
* Author: frank
* Email: [email protected]
* Version: 1.0
* Created Time:2018-08-23 22:48:22
* Blog: http://www.cnblogs.com/black-mamba
* Github: https://github.com/suonikeyinsuxiao
*
***********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "xmg_mutex.h"
#include "xmg_thread.h"
static int s_playstate = 0;//0,stop;1,start;2,pause;
xmg_mutex_s test_mutex1;
XMG_THREAD_PID app_uipc_tx_thread_struct;
static void app_uipc_tx_thread(void)
{
int status;
printf("starting app_uipc_tx_thread\n");
while(1)
{
while (s_playstate != 1)//!start
{
status = xmg_lock_mutex(&test_mutex1);
if (status < 0)
{
printf("xmg_lock_mutex failed\n");
break;
}
}
printf("playing...\n");
//sleep(1);
}
printf("thread exit\n");
pthread_exit(NULL);
}
int main(int argc, char** argv)
{
//int te =1;
int status;
xmg_init_mutex(&test_mutex1);
//printf("app_uipc_tx_thread=%x\n", app_uipc_tx_thread);
status = xmg_create_thread(app_uipc_tx_thread, 0, 0, &app_uipc_tx_thread_struct);
printf("main thread sleep 1s...\n");
sleep(1);
//play start
s_playstate = 1;
status = xmg_unlock_mutex(&test_mutex1);
if (status < 0)
{
printf("xmg_unlock_mutex failed\n");
}
printf("main thread play 5s...\n");
sleep(15);
//play pause
s_playstate = 2;
printf("main thread pause 5s...\n");
sleep(5);
//play start
s_playstate = 1;
status = xmg_unlock_mutex(&test_mutex1);
if (status < 0)
{
printf("xmg_unlock_mutex failed\n");
}
printf("main thread play 5s...\n");
sleep(5);
//play stop
s_playstate = 0;
xmg_stop_thread(app_uipc_tx_thread_struct);
printf("main thread stop 5s...\n");
sleep(5);
//(void)te;
return 0;
}
|
C | // Example C program for bit-banging synchronous communication.
//
// This program sends an array of curr_bytes. For each curr_byte, bits are sent from least
// significant to most significant by setting the data pin to 0/1 after each
// positive clock edge.
// gpo(0): clock pin, with period PERIOD and ~50% duty cycle
// gpo(1): data pin, 0/1 depending on current bit
//
// Michael Zimmer ([email protected])
#include "flexpret_timing.h"
#include "flexpret_io.h"
#define PERIOD 1200
void sync_comm(uint32_t* data, uint32_t length)
{
uint32_t i, j; // loop counters
uint32_t current; // current word of data
uint32_t time = get_time()+1000; // start time after initialization
for(i = 0; i < length; i++) { // iterate through input data
current = data[i]; // read next word
for(j = 0; j < 32; j++) { // iterate through each bit in word
time = time + PERIOD/2;
set_compare(time);
delay_until(); // wait half period
gpo_set_0(1); // posedge clk on pin
if(current & 1) { // if bit == 1...
gpo_set_0(2); // output bit goes high
} else { // if bit == 0...
gpo_clear_0(2); // output bit goes high
}
current = current >> 1; // setup next bit
time = time + PERIOD/2;
set_compare(time);
delay_until(); // wait half period
gpo_clear_0(1); // negedge clk on pin
}
}
}
int main(void)
{
uint32_t data[2] = {0x01234567, 0x89ABCDEF};
sync_comm(data,2);
return 1;
}
|
C | //
// sudokuStrategies.c
// projetofinal
//
// Created by Faculdade on 28/12/2019.
// Copyright © 2019 Patricia. All rights reserved.
//
#include "sudokuStrategies.h"
MATRIX * create_Vetor_Strategies(MATRIX *pM){
CELL * c= pM->pfirst, *aux=c;
int size =pM->size;
for(int i=0;i<size;i++){
(c->p)[i]=0;
}
for(int i=0;i< size;i++){// linhas
for(int j=0;j<size;j++){ //colunas
if(c->v ==0){
int k=0; // andar dentro do m
for(int num =1;num <=size;num++){
if(ifSafe(pM, i, j, num)==1){
(c->p)[k] = num;
k++;
}
}
if( k<size )// garante que o último é mesmo o último
(c->p)[k]= 0;
}
c=c->E;
}
aux=aux->S;
c=aux;
}
return pM;
}
void cliente_Strategies(void){
MATRIX * m = (MATRIX*)malloc(sizeof(MATRIX));
int size = 9;
init_matrix(m, size);
m=readMatrixtxt("/Users/faculdade/Documents/LP/projetofinal/data/matrizApont5.txt");
printMatrixF2(*m);
create_Vetor_Strategies(m);
print_Vetor_Strategies(*m);
/*hiddenSingles(m);
printMatrixF2(*m);
print_Vetor_Strategies(*m);
nakedSingles(m);
printMatrixF2(*m);
print_Vetor_Strategies(*m);
//testar com outro sudoku
nakedPairs(m);
printMatrixF2(*m);
print_Vetor_Strategies(*m);
boxLineReduction(m);
printMatrixF2(*m);
print_Vetor_Strategies(*m);*/
pointingPairs(m);
printMatrixF2(*m);
print_Vetor_Strategies(*m);
free_matrix(m);
free(m);
}
void print_Vetor_Strategies(MATRIX pM){
int size = pM.size;
CELL * c= pM.pfirst, *aux=c;
for(int i=0;i< size;i++){
for(int j=0;j<size;j++){
printf("(%d,%d):",i,j);
for(int k =0;k <=size;k++){
int num =(c->p)[k];
if(num == 0){
break;
}
else
printf("%d ",num);
}
c=c->E;
printf("\n");
}
aux=aux->S;
c=aux;
}
}
MATRIX * nakedSingles (MATRIX * pM){
CELL * c= pM->pfirst, *aux=c;
int size = pM->size;
for(int i=0;i< size;i++){
for(int j=0;j<size;j++){
if((c->p)[0]!=0 && (c->p)[1]==0) {// Se só existir uma possibilidade
c->v= (c->p)[0];
(c->p)[0]=0;// Esvazia o vetor de probabilidades
}
c=c->E;
}
aux=aux->S;
c=aux;
}
create_Vetor_Strategies(pM);// atualiza o vetor de probabilidades
return pM;
}
MATRIX * hiddenSingles (MATRIX * pM){
CELL * c= pM->pfirst, *aux=c;
int size = pM->size;
int count[size];
for(int i=0;i<size;i++){// inicialização da variável local count
count[i]=0;
}
for(int i=0;i< size;i++){
for(int j=0;j<size;j++){
for(int k=0; k<size;k++){
if((c->p)[k]==0)
break;
// guarda o número de vezes que um valor aparece no valor-1
count[(c->p)[k]-1]= (count[(c->p)[k]-1] )+ 1;
}
c=c->E;
}
for(int z=0; z<size;z++){
if(count[z]==1)// se só aparecer uma vez nessa linha
placeHiddenSingles(pM, aux, z+1);
}
for(int k=0;k<size;k++){// zera se a variável local count
count[k]=0;
}
aux=aux->S;
c=aux;
}
return pM;
}
MATRIX * placeHiddenSingles (MATRIX * pM, CELL * cLine, int num){
for(int i=0;i<pM->size && cLine!=NULL;i++){
for(int k=0;k<pM->size && (cLine->p)[k]<=num;k++){
if((cLine->p)[k]==num){
cLine->v = num;
create_Vetor_Strategies(pM);// atualiza o vetor de probabilidades
return pM;
}
}
cLine=cLine->E;
}
return pM;
}
MATRIX * nakedPairs(MATRIX * pM){
CELL * c= pM->pfirst, *aux=c;
int size = pM->size;
int pair[2]={0,0}, flag[3]={0,0,0};
for(int i=0;i< size;i++){
for(int j=0;j<size;j++){
// se existir só dois digitos guarda-se esses digitos
if( (c->p)[0]!=0 && (c->p)[1]!=0 && (c->p)[2]==0){
// Encontra-se um possivel par
if(pair[0]==0 && pair[1]==0){
pair[0]=(c->p)[0];
pair[1]=(c->p)[1];
flag[1]=j; // coluna do primeiro par
}
//Encontra-se outro par
else if(pair[0]== (c->p)[0] && pair[1]== (c->p)[1]){
flag[0]=1;
flag[2]=j;// coluna do segundo par
break;
}
}
c=c->E;
}
if(flag[0] == 1){
c=aux;
for(int j=0;j<size;j++){
if(j!=flag[1] && j!=flag[2]){// colunas dos pares
removeFromVector(c, pair[0], size);
removeFromVector(c, pair[1], size);
}
c=c->E;
}
}
aux=aux->S;
c=aux;
// zera se as variáveis
pair[0]=0;pair[1]=0;
flag[0]=0; flag[1]=0;flag[2]=0;
}
return pM;
}
CELL* removeFromVector(CELL * c, int num, int size){
for (int k=0;k<size || (c->p)[k]!=0;k++) {
if ( (c->p)[k]== num) {
for(int z=k;z<size-1;z++) //Elimina até ao penultimo
(c->p)[z] = (c->p)[z+1];
if((c->p)[size-2]==(c->p)[size-1])// se for o último
(c->p)[size-1]=0;
k--;// para confirmar o valor novo dessa possição
}
}
return c;
}
MATRIX * pointingPairs(MATRIX * pM){
CELL * c= pM->pfirst, *aux=c, *current =c, *box =NULL;;
int size = pM->size, num=0;
int square =(int)sqrt(pM->size);
int startCol = 0, flag =0,startRow=0;
for(int i=0;i< size;i++){
for(int j=0;j<size;j++){
for(int k=0;k<size;k++){
num= (c->p)[k];
if(num == 0)// se não ouver nada no vetor de possibilidades
break;
else{// fixas num valor e vê se se aparece dentro da caixa
startCol=(c->c) - (c->c)%(square);
startRow = (c->l) - (c->l)%(square);
current =c; // guarda a célula que estamos fixados
for (int col=0; col<size;col++){
if(col!=c->c){
c=c->W;
}
else{
for(int line=0;line<(startRow+square);line++){
if(line != startRow)
c=c->N;
else{
for(int w=startRow;w<startRow+square;w++){
if(w==current->l)
c=c->S;
box=c;
for(int z=startCol;z<startRow+square;z++){
for(int q=0;q<size && (c->p)[q]!=0;q++){
if( (c->p)[q]== num){
flag=1;
break;
}
}
c=c->E;
}
box=box->S;
c=box;
}
}
}
}
c=current;// volta se para a célula onde estavamos fixados
if(flag==0)
isInBoxPointingPairs(pM, num,startCol, c->l);
flag=0;
}
}
}
c=c->E;
for(int r=0;r<2;r++)
if(r==1) return NULL;
}
aux=aux->S;
c=aux;
}
return pM;
}
void isInBoxPointingPairs(MATRIX * pM, int num,int startCol,int line){
CELL * c= pM->pfirst;
int size = pM->size;
for(int i=0;i<size;i++){
if(i==line){
for(int j=0;j<size;j++){
if(j!=startCol && j!=(startCol+sqrt(size)) ){
for(int k=0;k<size;k++){
if((c->p)[k]==num)
removeFromVector(c, num, size);
}
}
c=c->E;
}
return;
}
else
c=c->S;
}
}
MATRIX * boxLineReduction(MATRIX * pM){
// vou verificar em cada linha e célula por célula se o valor aparece fora da caixa
// se aparecer remove se o valor do resto das células da caixa sem ser a linha que estavamos
CELL * c= pM->pfirst, *aux=c, *current =c;
int size = pM->size, num=0;
int square =(int)sqrt(pM->size);
int startCol = 0, flagIs =0;
for(int i=0;i< size;i++){
for(int j=0;j<size;j++){
for(int k=0;k<size;k++){
num= (c->p)[k];
if(num == 0)// se não ouver nada no vetor de possibilidades
break;
else{// fixas num valor e vê se se aparece fora da caixa
current =c; // guarda a célula que estamos fixados
startCol = (c->c) - (c->c)%(square);
c = aux; // volta ao inicio da linha
for (int col=0; col<size;col++){
if(col < startCol || col >= (startCol + square)){
if ((c->p)[0]==0)
break;
else{
for(int z=0;(c->p)[z] !=0;z++){
if((c->p)[z] == num && flagIs!=1){
flagIs =1;
break;
}
}
}
}
c=c->E;
}
c=current;// volta se para a célula onde estamos fixados
}
if(flagIs == 0){ // se o valor não aparecer na linha fora da caixa
// remove se dentro da caixa
boxLineReduction_BoxRemoval(pM, num, (c->l) - (c->l)%(square), (c->c) - (c->c)%(square), c->l);
//return pM;// Feito para poder testar
}
flagIs=0;
}
c=c->E;
}
aux=aux->S;
c=aux;
}
return pM;
}
MATRIX * boxLineReduction_BoxRemoval(MATRIX * pM, int num, int startL, int startCol, int notL){
int square =(int)sqrt(pM->size);
int size = pM->size;
CELL * cell= pM->pfirst, *aux=cell;
for(int l=0;l<(startL +square);l++){
if(l==startL){
for(int c=0;c<(startCol +square);c++){
if(c==startCol){// chegamos á primeira célula da caixa
aux =cell;
for(int line =l;line<(startL +square);line++){
if(line!=notL){
for(int col=c;col<(startCol +square);col++){
if(cell->v==0)
removeFromVector(cell, num, size);
cell=cell->E;
}
}
aux = aux->S;
cell=aux;
}
return pM;
}
cell=cell->E;
}
}
cell = cell->S;
}
return pM;
}
void solveSudokuStrategies(MATRIX * pM){
pM=nakedSingles(pM);
pM=hiddenSingles(pM);
pM=nakedSingles(pM);
solveSudokuRec(pM);
}
|
C | #include"header.h"
int validate(char* num)
{
int i;
int n=0;
int flag=0;
if(num[0]=='+') {
flag=0;
}
else if(num[0]=='-') {
flag=1;
}
else if((num[0] >= '0') && (num[0] <= '9')){
n = n * 10 + num[0] - '0';
}
for(i = 1; i < str_len(num)-1; i++) {
if ((num[i] >= '0') && (num[i] <= '9'))
{
n = n * 10 + (num[i] - '0');
}
else {
printf("\nInvalid input!\nTry again\n");
exit(0);
}
}
if(n >= 2147483647 || n <= -2147483648)
{
printf("Outof Range!!\n Try again\n");
} else {
if (flag) {
return (~(n) + 1);
}
else {
return n;
}
}
return 0;
}
|
C | #include<stdio.h>
double pi(unsigned int n);
int main(void){
double pivar;
unsigned int i;
for(i=1; i<=1000000000; i*=10){
pivar = pi(i);
printf(" %10d = %lf \n",i,pivar);
}
return 0;
}
double pi(unsigned int n){
int pm=0;
unsigned int i;
double pivar=0;
for (i=1;i<=n;i+=2){
if(pm==0){
pivar+=1.0/i;
pm=1;
}else{
pivar-=1.0/i;
pm=0;
}
}
pivar*=4;
return pivar;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.