language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#define IS_BUT1_PUSH (GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_14)) // 1 PC14
#define IS_BUT2_PUSH (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_10)) // 2 PB10
#define IS_BUT3_PUSH (!(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_14))) // 3 PB14
#define IS_BUT4_PUSH (!(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_7))) // 4 PB7
// "" - .0 (reset)
// " " - .1 (set)
#define SET_LED_ON (GPIO_ResetBits(GPIOC, GPIO_Pin_13))
#define SET_LED_OFF (GPIO_SetBits(GPIOC, GPIO_Pin_13))
//
#define IS_LED_OFF (GPIO_ReadOutputDataBit(GPIOC, GPIO_Pin_13))
// 1 = 50
#define MIN_TIME 100
//
#define BUT2_TIME_MS 1500
#define BUT3_TIME_MS 2500
#define BUT4_TIME_MS 3500
// ARR
#define DEF_ARR (1000-1) // = 500
#define BUT2_ARR (BUT2_TIME_MS/500*1000)
#define BUT3_ARR (BUT3_TIME_MS/500*1000)
#define BUT4_ARR (BUT4_TIME_MS/500*1000)
#include "stm32f10x.h"
int status = 0; // 1
unsigned int delay = DEF_ARR; //, 1
int light = DEF_ARR; //,
TIM_TimeBaseInitTypeDef tim;
int main(void)
{
//
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitTypeDef gpio_init;
gpio_init.GPIO_Pin = GPIO_Pin_13;
gpio_init.GPIO_Mode = GPIO_Mode_Out_PP;
gpio_init.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOC, &gpio_init);
gpio_init.GPIO_Pin = GPIO_Pin_14;
gpio_init.GPIO_Mode = GPIO_Mode_IPD;
GPIO_Init(GPIOC, &gpio_init);
gpio_init.GPIO_Pin = GPIO_Pin_10;
gpio_init.GPIO_Mode = GPIO_Mode_IPD;
gpio_init.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOB, &gpio_init);
gpio_init.GPIO_Pin = GPIO_Pin_14 | GPIO_Pin_7;
gpio_init.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOB, &gpio_init);
//
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
//
tim.TIM_ClockDivision = TIM_CKD_DIV1;
tim.TIM_CounterMode = TIM_CounterMode_Up;
tim.TIM_Period = DEF_ARR;
tim.TIM_Prescaler = 36000 - 1; //36000
TIM_TimeBaseInit(TIM3, &tim);
//
TIM_Cmd(TIM3, ENABLE);
//
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
//
NVIC_InitTypeDef nvicInit;
nvicInit.NVIC_IRQChannel = TIM3_IRQn;
nvicInit.NVIC_IRQChannelCmd = ENABLE;
nvicInit.NVIC_IRQChannelPreemptionPriority = 0;
nvicInit.NVIC_IRQChannelSubPriority = 0;
NVIC_Init(&nvicInit);
for(;;)
{
if (IS_BUT1_PUSH)
{
TIM_ITConfig(TIM3, TIM_IT_Update, DISABLE);
TIM_Cmd(TIM3, DISABLE);
SET_LED_OFF;
TIM_SetCounter(TIM3, 0);
tim.TIM_Period = UINT16_MAX;
TIM_TimeBaseInit(TIM3, &tim);
TIM_Cmd(TIM3, ENABLE);
while(IS_BUT1_PUSH)
{
if (TIM_GetCounter(TIM3) > MIN_TIME)
delay = TIM_GetCounter(TIM3);
}
status = 1;
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
SET_LED_ON;
}
if ((!IS_BUT1_PUSH) & status)
{
TIM_Cmd(TIM3, DISABLE);
TIM_SetCounter(TIM3, 0);
tim.TIM_Period = delay-1;
TIM_TimeBaseInit(TIM3, &tim);
TIM_Cmd(TIM3, ENABLE);
status = 0;
}
if (IS_BUT2_PUSH)
{
light = BUT2_ARR;
}
else if (IS_BUT3_PUSH)
{
light = BUT3_ARR;
}
else if (IS_BUT4_PUSH)
{
light = BUT4_ARR;
}
else
{
light = DEF_ARR;
}
}
}
void TIM3_IRQHandler(void) {
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) {
if (IS_LED_OFF) {
SET_LED_ON;
tim.TIM_Period = light - 1;
TIM_TimeBaseInit(TIM3, &tim);
TIM_ClearFlag(TIM3, TIM_IT_Update); //
return;
} else {
SET_LED_OFF;
tim.TIM_Period = delay - 1;
TIM_TimeBaseInit(TIM3, &tim);
TIM_ClearFlag(TIM3, TIM_IT_Update); //
return;
}
}
}
|
C
|
/**
* Checks that `idx_type` will correctly identify a structure containing a
* single double.
*/
#include "idx.h"
#include "idx_test.h"
int main(void) {
const uint8_t data[] = {
0x00, 0x00, 0x0e, 0x00,
0x40, 0x09, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18,
};
idx_assert(idx_type(data) == IDX_TYPE_DOUBLE);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <semaphore.h>
#include <stdbool.h>
#include <time.h>
#include <unistd.h>
#include "thread.h"
int main(void)
{
pthread_t cust0,cust1,cust2,chef;
sem_init (&kitchen, 0, 1);
printf("Customer 0 has infinite Hamburger\n");
printf("Customer 1 has infinite Fries\n");
printf("Customer 2 has infinite Soda\n");
printf("\n");
pthread_create(&chef,0,chefThread,0);
pthread_create(&cust0,0,customerThread,(void*)0);
pthread_create(&cust1,0,customerThread,(void*)1);
pthread_create(&cust2,0,customerThread,(void*)2);
while(1);
}
|
C
|
#include <stdio.h>
int main(int argc, const char *argv[])
{
int a = 0
, b = 0
, c = 0;
printf("please input two number:\n");
scanf("%d%d", &a, &b);
c = a%10 * 1000 + b%10 * 100 + b/10%10 * 10 + a/10%10 * 1;
printf("a = %d, b = %d,c = %d\n", a, b, c);
return 0;
}
|
C
|
#include "main.h"
/**
* leet - For printing letters into digits
*@s: Parameter used
*
*Return: Value of s
*/
char *leet(char *s)
{
int i;
char a[5] = {'A', 'E', 'O', 'T', 'L'};
char b[5] = {'4', '3', '0', '7', '1'};
int c;
for (i = 0; s[i] != '\0'; i++)
{
for (c = 0; c < 5; c++)
{
if (s[i] == a[c] || s[i] - 32 == a[c])
{
s[i] = b[c];
}
}
}
return (s);
}
|
C
|
/*
You are given a non-negative number less than or equal to 100000000 (1
followed by 8 zeroes). You have to divide the number into the
following components, and print them in the following order.
1. The part of the number which is less than a thousand.
2. The part of the number which is between a thousand and a lakh
3. The part of the number which is between a lakh and a crore
and so on. You should terminate printing when no higher power of 10 is
present to be printed.
For example, suppose the input number is
134847
Then the output should be
847
34
1
The question can be done with or without using arrays.
Hint: Using % (that is, the modulo operator) and / (the division
operator on integers) is helpful in solving this question.
*/
#include <stdio.h>
int main()
{
int n; /* the upper limit is lower than the max int value,
so no checks needed */
int divisor;
scanf("%d", &n);
divisor=1000;
printf("%d\n", n % divisor);
n = n/divisor;
divisor=100;
while ( n != 0 ){
printf ( "%d\n", n % divisor );
n = n/divisor;
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_move_ant.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tbleuse <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/26 13:06:44 by tbleuse #+# #+# */
/* Updated: 2018/07/20 13:17:26 by tbleuse ### ########.fr */
/* */
/* ************************************************************************** */
#include "../header/lem_in.h"
static void move_ant(t_room *start, t_room *end, char *name, int c)
{
if (start->ant > 0)
{
end->ant += 1;
if (c)
end->ant_name = start->ant_name;
else
end->ant_name = start->ant;
ft_printf("L%u-%s ", end->ant_name, name);
start->ant -= 1;
if (c)
start->ant_name = 0;
}
}
static void push_ant(t_stock *s)
{
t_room *tmp;
t_room *tmp2;
int i;
i = -1;
while (s->start->liaison[++i])
{
if (s->start->liaison[i]->way != 0)
{
tmp = s->start->liaison[i];
while (tmp->ant != 1 && findnext(tmp)->special != 2)
tmp = findnext(tmp);
if (tmp->ant == 1)
{
while (tmp->ant == 1)
{
tmp2 = tmp;
while (findnext(tmp2)->ant == 1 &&
findnext(tmp2)->special != 2)
tmp2 = findnext(tmp2);
move_ant(tmp2, findnext(tmp2), findnext(tmp2)->name, 1);
}
}
}
}
}
static void ft_move_ant_second(t_stock *s, int way)
{
int i;
ft_printf("\n");
push_ant(s);
way--;
if (way < 1)
way = 1;
i = -1;
while (s->start->liaison[++i])
{
if (s->start->liaison[i]->way <= way &&
s->start->liaison[i]->way != 0)
move_ant(s->start, s->start->liaison[i],
s->start->liaison[i]->name, 0);
}
}
int ft_move_ant(t_stock *s)
{
int way;
int i;
i = -1;
while (s->start->liaison[++i])
if (s->start->liaison[i]->special == 2)
{
while (s->ant_nbr > 0)
ft_printf("L%i-%s ", s->ant_nbr--, s->end->name);
}
s->start->ant = (int)s->ant_nbr;
way = how_much_way(s) + 1;
while (s->end->ant != s->ant_nbr)
ft_move_ant_second(s, way);
return (1);
}
|
C
|
#include <stdio.h>
int main(){
int a, b, c;
scanf(" %d %d %d", &a, &b, &c);
if(a+b<c || a+c<b || b+c<a){
printf("Isso não é um triângulo!");
}else if(a==b && b==c){
printf("Equilatero");
}else if(a!=b && b!=c && a!=c){
printf("Escaleno");
}else if((a==b)!=c || (a==c)!=b || (b==c)!=a){
printf("Isosceles");
}else{
printf("Easter Egg!");
}
return 0;
}
|
C
|
// Key.c
// This software configures the off-board piano keys
// Lab 6 requires a minimum of 3 keys, but you could have more
// Runs on TM4C123
// Program written by: Anuj Jain and George Koussa
// Date Created: 3/6/17
// Last Modified: 3/22/21
// Lab number: 6
// Hardware connections
// PE4-PE0 : piano keys
// Code files contain the actual implemenation for public functions
// this file also contains an private functions and private data
#include <stdint.h>
#include "../inc/tm4c123gh6pm.h"
// **************Key_Init*********************
// Initialize piano key inputs on PE4-0
// Input: none
// Output: none
void Key_Init(void){
SYSCTL_RCGCGPIO_R |= 0x10; // turn on port E clock
volatile int a = 4; // wait for clock to stabilize
a++;
GPIO_PORTE_DIR_R |= 0x00; // make PE0-PE4 inputs
GPIO_PORTE_DEN_R |= 0x0F; // enable PE0-PE4
GPIO_PORTE_PDR_R |= 0x0F; // enable Pull-down resistors on PE0-PE4
}
// **************Key_In*********************
// Input from piano key inputs on PE4-0
// Input: none
// Output: 0 to 15
// 0x01 is just Key0, 0x02 is just Key1, 0x04 is just Key2, 0x08 is just Key3
uint32_t Key_In(void){
return (GPIO_PORTE_DATA_R & 0x0F); //return data in PE0-PE4
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int uint32_t ;
typedef int /*<<< orphan*/ lua_State ;
/* Variables and functions */
int hsv2grb (int const,int const,int const) ;
int /*<<< orphan*/ luaL_argcheck (int /*<<< orphan*/ *,int,int,char*) ;
int luaL_checkint (int /*<<< orphan*/ *,int) ;
int /*<<< orphan*/ lua_pushnumber (int /*<<< orphan*/ *,int) ;
__attribute__((used)) static int cu_hsv2grb(lua_State *L) {
const int hue = luaL_checkint(L, 1);
const int sat = luaL_checkint(L, 2);
const int val = luaL_checkint(L, 3);
luaL_argcheck(L, hue >= 0 && hue <= 360, 1, "should be a 0-360");
luaL_argcheck(L, sat >= 0 && sat <= 255, 2, "should be 0-255");
luaL_argcheck(L, val >= 0 && val <= 255, 3, "should be 0-255");
// convert to grb
uint32_t tmp_color = hsv2grb(hue, sat, val);
// return
lua_pushnumber(L, (tmp_color & 0x00FF0000) >> 16);
lua_pushnumber(L, (tmp_color & 0x0000FF00) >> 8);
lua_pushnumber(L, (tmp_color & 0x000000FF));
return 3;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_sqrt.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ddenkin <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/02/24 18:50:50 by ddenkin #+# #+# */
/* Updated: 2018/02/24 19:01:03 by ddenkin ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static double f(double w, double g)
{
return (g * g - w);
}
static double fprime(double g)
{
return (2 * g);
}
static int closeenough(double a, double b)
{
return (ft_fabs(a - b) < ft_fabs(b * 0.0001));
}
static double findroot(double w, double g)
{
double newguess;
newguess = g - f(w, g) / fprime(g);
if (closeenough(newguess, g))
return (newguess);
else
return (findroot(w, newguess));
}
double ft_sqrt(double x)
{
return (findroot(x, 1));
}
|
C
|
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
pthread_key_t key;
void *tid1_func(void *arg)
{
int i=10;
printf("set key:%d in tid1\n",i);
pthread_setspecific(key,&i);
sleep(2);
printf("in tid1,after tid2 ends,key:%d\n",*(int *)pthread_getspecific(key));
}
void *tid2_func(void *arg)
{
int j=20;
printf("set key:%d in tid2\n",j);
pthread_setspecific(key,&j);
printf("in tid2,key:%d\n",*(int *)pthread_getspecific(key));
}
void destruct(void *t)
{
printf("key addr:%p\n",t);
}
int main(int argc,char *argv[])
{
pthread_t tid1,tid2;
pthread_key_create(&key,destruct);
pthread_create(&tid1,NULL,tid1_func,NULL);
pthread_create(&tid2,NULL,tid2_func,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_key_delete(key);
return 0;
}
|
C
|
#include "image.h"
#include <math.h>
#include <stdlib.h>
main(int ac,char *av[])
{
ImageData *img,*outimg;
int res;
double ang,dis;
int x,y,mx,my;
if(ac<3) {
printf("p[^܂");
return;
}
// t@C摜f[^̓ǂݍ
res=readBMPfile(av[1],&img);
if(res<0) {
printf("摜ǂ߂܂");
return;
}
hough(img,&outimg,&ang,&dis);
printf("%f %f\n",ang,dis);
writeBMPfile(av[2],outimg);
disposeImage(img);
disposeImage(outimg);
}
#define THETA_MAX 32
#define RO_MAX 50
#define MPI 3.14159
int addHough(int *himage,int x,int y,int hmx,int hmy)
{
if(x<0) return;
if(x>=hmx) return;
if(y<0) return;
if(y>=hmy) return;
himage[x+y*hmx]++;
}
int hough(ImageData *img,ImageData **oimg,double *ang,double *dis)
{
int i;
int x,y;
int te;
ImageData *outimg;
Pixel col,scol;
int ro,romax;
double teta,orgro;
int mx,my;
int hmx,hmy;
int maxVal,mmx,mmy;
int *himage; //ntϊ
mx=img->width-1;
my=img->height-1;
scol.r=0;
scol.g=0;
scol.b=0;
// Ίp̒߂
romax=(int)(sqrt(mx*mx+my*my)+1);
hmx=THETA_MAX;
hmy=RO_MAX*2;//romax*2;
himage=malloc(sizeof(int)*hmx*hmy);
for(i=0;i<hmx*hmy;i++) himage[i]=0;
for(y=0;y<my;y++) {
for(x=0;x<mx;x++) {
getPixel(img,x,y,&col); //摜̉f擾
if(col.r>0) {
for(te=0;te<THETA_MAX;te++) {
teta=MPI*(double)te/THETA_MAX;
orgro=x*cos(teta)+y*sin(teta);
ro=(int)(orgro*RO_MAX/romax + 0.5);
addHough(himage,te,ro+RO_MAX,hmx,hmy);
//setPixel(outimg,te,ro+romax,&scol);
}
}
}
}
*oimg=createImage(hmx,hmy,24);
outimg=(*oimg);
maxVal=-1;
for(y=0;y<hmy;y++) {
for(x=0;x<hmx;x++) {
int hval;
hval=himage[x+y*hmx];
if(hval>maxVal) {
maxVal=hval;
mmx=x;
mmy=y;
}
scol.r=hval;
scol.g=0;
scol.b=0;
setPixel(outimg,x,y,&scol);
}
}
*ang=180*(double)mmx/THETA_MAX;
*dis=(double)(mmy-RO_MAX)*romax/RO_MAX;
return TRUE;
}
|
C
|
#include "main.h"
int main(int argc, char **argv) {
/*
long long unsigned int N = 10;
array * workingArray = createArray(12, N);
readFile("chicago.txt", workingArray, N*10);
displayArray(workingArray);
*/
menu(initialization());
return 0;
}
array * initialization() {
printf("\tINITIALIZATION\n");
printf("Please enter a size for the table : ");
long long unsigned N = 0;
scanf(" %llu%*c", &N);
printf("Please enter a base for the table : ");
int base = 0;
scanf(" %d%*c", &base);
array * newArray = createArray(base, N);
return newArray;
}
void menu(array * workingArray) {
int stop = 0;
while (stop == 0) {
printf("\tMENU\nChoose an option by entering it's associated number\n0. Display the table\n1. Index calculation for a user\n2. Add a user in the table\n3. Load a number of users from the chicago.txt file\n4. Display a user's salary\n5. Display from an index to another\n6. Number of conflicts\n7. Average size of conflicts\n8. Remove a user\n9. Remove from an index to another\n10. Exit\nInput : ");
int input;
scanf(" %d%*c", &input); //switch needs an int, but if a non int is typed as input, the menu goes haywire, goes in a scary circle
switch (input) {
case 0:
displayArray(workingArray);
scanf("%*c");
break;
case 1:
ex1(workingArray);
break;
case 2:
ex2(workingArray);
break;
case 3:
ex3(workingArray);
break;
case 4:
ex4(workingArray);
break;
case 5:
ex5(workingArray);
break;
case 6:
ex6(workingArray);
break;
case 7:
ex7(workingArray);
break;
case 8:
ex8(workingArray);
break;
case 9:
ex9(workingArray);
break;
case 10:
printf("stop\n");
stop = 1;
break;
default:
break;
}
}
}
void ex1(array * workingArray) {
printf("\tINDEX CALCULATION FOR A USER\nPlease enter a lastname for the user : ");
char lastname[56], firstname[56];
scanf(" %s%*c", lastname);
printf("Please enter a firstname for the user : ");
scanf(" %s%*c", firstname);
printf("Index for \"%s %s\" : %llu\n", lastname, firstname, indexCalculator(lastname, firstname, workingArray->base, workingArray->N));
scanf("%*c");
}
void ex2(array * workingArray) {
printf("\tADD A USER TO THE TABLE\nPlease enter a lastname for the user : ");
char lastname[56], firstname[56];
int salary = 0;
scanf(" %s%*c", lastname);
printf("Please enter a firstname for the user : ");
scanf(" %s%*c", firstname);
printf("Please enter a salary for the user : ");
scanf(" %d%*c", &salary);
user * userToAdd = createUser(lastname, firstname, salary);
addSingleUserToArray(userToAdd, workingArray);
displayArray(workingArray);
scanf("%*c");
}
void ex3(array * workingArray) {
printf("\tLOAD A NUMBER OF USERS FROM THE CHICAGO.TXT FILE\nPlease enter the number of users to load : ");
long long unsigned int numberOfUsersToAdd = 0;
scanf(" %llu%*c", &numberOfUsersToAdd);
printf("working...\n");
readFile("../chicago.txt", workingArray, numberOfUsersToAdd);
displayArray(workingArray);
scanf("%*c");
}
void ex4(array * workingArray) {
printf("\tDISPLAY A USER\'S SALARY\nPlease enter the lastname of the user : ");
char lastname[56], firstname[56];
scanf(" %s%*c", lastname);
printf("Please enter the firstname of the user : ");
scanf(" %s%*c", firstname);
user * userToSearch = createUser(lastname, firstname, 0);
user * workingUser = searchUserInArray(userToSearch, workingArray);
if (workingUser == NULL) {
printf("Sorry, user \"%s %s\" was not found\n", lastname, firstname);
}
else {
displayUser(workingUser);
}
scanf("%*c");
}
void ex5(array * workingArray) {
printf("\tDISPLAY USERS FROM AN INDEX TO ANOTHER\nPlease enter an starting index : ");
long long unsigned int startingIndex = 0, finishingIndex = 0;
scanf(" %llu%*c", &startingIndex);
printf("Please enter a finishing index : ");
scanf(" %llu%*c", &finishingIndex);
if (startingIndex < workingArray->N && finishingIndex < workingArray->N) {
printf("array :\n");
for (long long unsigned int i = startingIndex; i <= finishingIndex; i++) {
printf("\tvector %llu:\n", i);
displayVector(workingArray->content + i);
}
}
else {
printf("Indexes out of range of the table, aborting.\n");
}
scanf("%*c");
}
void ex6(array * workingArray) {
printf("\tNUMBER OF CONFLICTS\n");
long long unsigned int numberOfConflicts = 0;
for (long long unsigned int i = 0; i < workingArray->N; i++) {
if ((workingArray->content + i)->currentNumberOfUsers > 1) {
numberOfConflicts++;
}
}
printf("There are %llu conflicts in the table\n", numberOfConflicts);
scanf("%*c");
}
void ex7(array * workingArray) {
printf("\tAVERAGE SIZE OF CONFLICTS\n");
long long unsigned int numberOfConflicts = 0, totalSizeOfConflicts = 0;
for (long long unsigned int i = 0; i < workingArray->N; i++) {
if ((workingArray->content + i)->currentNumberOfUsers > 1) {
numberOfConflicts++;
totalSizeOfConflicts+=(workingArray->content + i)->currentNumberOfUsers;
}
}
float averageSizeOfConflicts = totalSizeOfConflicts / numberOfConflicts + totalSizeOfConflicts % numberOfConflicts;
printf("Conflicts have an average size of %f\n", averageSizeOfConflicts);
scanf("%*c");
}
void ex8(array * workingArray) {
printf("\tREMOVE A USER\nPlease enter the lastname of the user : ");
char lastname[56], firstname[56];
scanf(" %s%*c", lastname);
printf("Please enter the firstname of the user : ");
scanf(" %s%*c", firstname);
user * userToRemove = createUser(lastname, firstname, 0);
removeUserFromVector(userToRemove, workingArray->content + indexCalculator(lastname, firstname, workingArray->base, workingArray->N));
printf("User was removed.\n");
scanf("%*c");
}
void ex9(array * workingArray) {
printf("\tREMOVE FROM AN INDEX TO ANOTHER\nPlease enter a starting index : ");
long long unsigned int startingIndex = 0, finishingIndex = 0;
scanf(" %llu%*c", &startingIndex);
printf("Please enter a finishing index : ");
scanf(" %llu%*c", &finishingIndex);
if (startingIndex < workingArray->N && finishingIndex < workingArray->N) {
printf("removing...\n");
for (long long unsigned int i = startingIndex; i <= finishingIndex; i++) {
//removeVector(workingArray->content + i);
*(workingArray->content + i) = *createVector();
}
printf("Users were removed\n");
}
else {
printf("Indexes out of range of the table, aborting.\n");
}
scanf("%*c");
}
|
C
|
//
// main.c
// Linked Lists
//
// Created by Jacob Cho on 2014-10-08.
// Copyright (c) 2014 Jacob Cho. All rights reserved.
//
#include <stdio.h>
struct Node {
int value;
struct Node * next;
};
typedef struct Node Node;
void printNodes(Node *head);
Node * nodeSearch(int value, Node *head);
void insertNode(int value, Node *head);
void removeNode(int value, Node *head);
Node * newNode(int value);
void deleteList(Node *head);
int main(int argc, const char * argv[]) {
Node firstNode = *newNode(1);
Node secNode = *newNode(2);
Node thirdNode = *newNode(3);
Node forthNode = *newNode(4);
Node fifthNode = *newNode(5);
Node sixthNode = *newNode(6);
firstNode.next = &secNode;
secNode.next = &thirdNode;
thirdNode.next = &forthNode;
forthNode.next = &fifthNode;
fifthNode.next = &sixthNode;
sixthNode.next = NULL;
printNodes(&firstNode);
Node *nodeToFind = nodeSearch(5, &firstNode);
printf("Value of node search: %d\n", nodeToFind->value);
insertNode(7, &firstNode);
printNodes(&firstNode);
removeNode(2, &firstNode);
printNodes(&firstNode);
deleteList(&firstNode);
printNodes(&firstNode);
return 0;
}
void printNodes(Node *head) {
Node *current = head;
printf("%d\n",current->value);
while (current->next != NULL) {
current = current->next;
int n = current->value;
printf("%d\n",n);
}
printf("%d\n",current->value);
}
Node * nodeSearch(int value, Node *head) {
Node *current = head;
while (current->next != NULL) {
if (current->value == value) {
return current;
}
current = current->next;
}
printf("Node not found\n");
return NULL;
}
void insertNode(int value, Node *head) {
Node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode(value);
}
void removeNode(int value, Node *head) {
Node *current = head;
Node *prev = head;
while (current->value != value) {
prev = current;
current = current->next;
}
prev->next = current->next;
current->next = NULL;
}
Node * newNode(int value) {
Node newNode;
newNode.value = value;
Node * result = &newNode;
return result;
}
void deleteList(Node *head) {
Node *current = head;
Node *next = head;
while (current->next != NULL) {
next = current->next;
current->next = NULL;
current->value = NULL;
current = next;
}
current->next = NULL;
current->value = NULL;
}
|
C
|
/*******************************
* Date Layer
*******************************/
#include "main.h"
#include "appinfo.h"
#include "date-layer.h"
static TextLayer *s_date_layer;
void date_update(struct tm *tick_time) {
static char date_buffer[] = "MON 00";
strftime(date_buffer, sizeof("MON 00"), "%a %e", tick_time);
text_layer_set_text(s_date_layer, date_buffer);
}
void date_window_load(Window *window) {
// Create and add the date layer
s_date_layer = text_layer_create(GRect(0, 110, 144, 20));
text_layer_set_background_color(s_date_layer, GColorClear);
text_layer_set_text_color(s_date_layer, GColorWhite);
text_layer_set_font(s_date_layer, g_medium_font);
text_layer_set_text_alignment(s_date_layer, GTextAlignmentCenter);
layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_date_layer));
}
void date_window_unload(Window *window) {
text_layer_destroy(s_date_layer);
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
bool solveMaze(char** maze, const int HT, const int WD, int x, int y); // draws a path to the exit on the maze string
void printMaze(char** maze, const int HT, const int WD); // prints the maze
int main(){
char mazeStr[] =
" ##############"
"# # ####"
"# ####* ### ####"
"# ###### ####"
"#### # #### ####"
"# # #### ####"
"#### # #### ####"
"#### ####"
"################";
const int HT = 9;
const int WD = 16;
char* maze[HT];
for (int i=0; i<HT ; i++) // filling the 2D char array
maze[i]=&mazeStr[i*WD];
solveMaze(maze, HT, WD, 0, 0);
printMaze(maze, HT, WD);
return 0;
}
bool solveMaze(char** maze, const int HT, const int WD, int x, int y)
{
if(x < 0 || y < 0 || x >= WD || y >= HT) return false;
if(maze[y][x] == '*') return true;
if(maze[y][x] == '#' || maze[y][x] == '.') return false;
maze[y][x] = '.';
if(solveMaze(maze, HT, WD, x, y - 1) == true) return true;
if(solveMaze(maze, HT, WD, x + 1, y) == true) return true;
if(solveMaze(maze, HT, WD, x, y + 1) == true) return true;
if(solveMaze(maze, HT, WD, x - 1, y) == true) return true;
maze[y][x] = ' ';
return false;
}
void printMaze(char** maze, const int HT, const int WD)
{
for (int i=0; i<HT ; i++){
for(int j=0; j<WD-1; j++)
printf("%c",maze[i][j]);
printf("%c\n",maze[i][WD-1]);
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h> //wtf
#include <sys/param.h> //wtf
#include <dirent.h> //wtf
#include <string.h>
static void countEntries(char *dirname, int *nFiles, int *nDirs)
{
char fullpath[MAXPATHLEN];
DIR * dirp;
struct dirent * dp;
dirp = opendir(dirname);
if (dirp == NULL)
{
perror("ERROR");
return;
}
while ((dp = deaddir(dirp)) != NULL)
{
struct stat stat_buffer;
struct stat *pointer = &stat_buffer;
if(strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0) continue;
sprintf(fullpath, "%s/%s", dirname, dp->d_name);
if(stat(fullpath, pointer) != 0)
{
perror("ERROR");
}
else if(S_ISDIR(pointer->st_mode))
{
(*nDirs)++;
countEntries(fullpath, nFiles, nDirs);
}
else if(S_ISREG(pointer->st_mode))
{
(*nFiles)++;
}
}
}
|
C
|
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BUF_SIZE 255
void error_macro(const char *error)
{
perror(error);
exit(1);
}
int main(void)
{
char *ptr = NULL;
int socket_fd = 0;
char buf[BUF_SIZE] = {0};
struct sockaddr_in client = {0};
socklen_t client_socket_fd_size = 0;
socket_fd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
if (socket_fd == -1)
{
error_macro("SOCKET CREATE");
}
client_socket_fd_size = sizeof(struct sockaddr_in);
do
{
if (recvfrom(socket_fd, buf, BUF_SIZE, 0, (struct sockaddr *)&client,
&client_socket_fd_size) == -1)
{
error_macro("RECVFROM ERROR");
}
ptr = buf;
ptr += 28;
printf("%s\n", ptr);
} while (strncmp(ptr, "exit", 255) != 0);
return 0;
}
|
C
|
#include "binary_trees.h"
/**
* recursive_height - height measure
* @tree: tree
* Return: height
*
*
**/
size_t recursive_height(const binary_tree_t *tree)
{
size_t x1 = 0;
size_t x2 = 0;
if (tree == NULL)
return (0);
x1 = recursive_height(tree->left);
x2 = recursive_height(tree->right);
if (x1 > x2)
return (x1 + 1);
return (x2 + 1);
}
/**
* binary_tree_height - recursive_height
* @tree: tree
* Return: height
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
if (tree == NULL)
return (0);
return (recursive_height(tree) - 1);
}
|
C
|
/**@file unity_log_helper.c
* @author Austin Glaser <austin@boulderes.com>
* @brief UnityLogHelper Source
*
* @addtogroup UNITY_LOG_HELPER
* @{
*/
/* --- PRIVATE DEPENDENCIES ------------------------------------------------- */
#include "unity_log_helper.h"
#include "log.h"
#include "unity.h"
#include "unity_util.h"
#include <inttypes.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
/* --- PRIVATE CONSTANTS ---------------------------------------------------- */
/* --- PRIVATE DATATYPES ---------------------------------------------------- */
/* --- PRIVATE MACROS ------------------------------------------------------- */
/* --- PRIVATE FUNCTION PROTOTYPES ------------------------------------------ */
/* --- PUBLIC VARIABLES ----------------------------------------------------- */
/* --- PRIVATE VARIABLES ---------------------------------------------------- */
/* --- PUBLIC FUNCTIONS ----------------------------------------------------- */
void AssertEqual_log_binary_data_t(log_binary_data_t expected,
log_binary_data_t actual,
unsigned short line,
const char * message)
{
char full_message[128];
strncat_if_nonempty(full_message, sizeof(full_message),
message, "Binary data type");
UNITY_TEST_ASSERT_EQUAL_HEX8(expected.type, actual.type,
line, full_message);
strncat_if_nonempty(full_message, sizeof(full_message),
message, "Binary data len");
UNITY_TEST_ASSERT_EQUAL_UINT32(expected.len, actual.len,
line, full_message);
strncat_if_nonempty(full_message, sizeof(full_message),
message, "Binary data pointer");
UNITY_TEST_ASSERT_EQUAL_PTR(expected.data, actual.data,
line, full_message);
}
void AssertEqual_log_entry_t(log_entry_t expected,
log_entry_t actual,
unsigned short line,
const char * message)
{
char full_message[128];
strncat_if_nonempty(full_message, sizeof(full_message),
message, "Log entry type");
UNITY_TEST_ASSERT_EQUAL_HEX8(expected.type, actual.type,
line, full_message);
strncat_if_nonempty(full_message, sizeof(full_message),
message, "Log entry subtype");
UNITY_TEST_ASSERT_EQUAL_HEX8(expected.subtype, actual.subtype,
line, full_message);
strncat_if_nonempty(full_message, sizeof(full_message),
message, "Log entry flags");
UNITY_TEST_ASSERT_EQUAL_HEX16(expected.flags, actual.flags,
line, full_message);
strncat_if_nonempty(full_message, sizeof(full_message),
message, "Log entry descriptor string");
UNITY_TEST_ASSERT_EQUAL_STRING(expected.descriptor_string,
actual.descriptor_string,
line, full_message);
strncat_if_nonempty(full_message, sizeof(full_message),
message, "Log entry binary data count");
UNITY_TEST_ASSERT_EQUAL_UINT32(expected.binary_data_count,
actual.binary_data_count,
line, full_message);
uint32_t i;
for (i = 0; i < LOG_MAX_BINARY_DATA; i++) {
strncat_if_nonempty(full_message, sizeof(full_message),
message, "Log entry binary data");
char number_string[16];
snprintf(number_string, sizeof(number_string), " %" PRIu32, i);
strncat(full_message, number_string,
sizeof(full_message) - strlen(full_message) - 1);
UNITY_TEST_ASSERT_EQUAL_log_binary_data_t(expected.binary_data[i],
actual.binary_data[i],
line, full_message);
}
}
/* --- PRIVATE FUNCTION DEFINITIONS ----------------------------------------- */
/** @} addtogroup UNITY_LOG_HELPER */
|
C
|
#include<stdio.h>
#include"Arthematic.h"
typedef struct complex_t{
int real;
int imaginary;
} complex_t;
int main(){
complex_t strr;
strr.real = 1;
strr.imaginary = 1;
int num3 = sum(strr.real , strr.imaginary);
printf("sum of 2 numbers are = %d\n",num3);
int num4 = Difference(strr.real , strr.imaginary);
printf("Difference of 2 numbers are = %d\n",num4);
int num5 = Product(strr.real , strr.imaginary);
printf("Product of 2 numbers are = %d\n",num5);
/* int num6 = Division(strr.real , strr.imaginary);
printf("Division of 2 numbers are = %d",num6);*/
return 0;
}
|
C
|
/*
* File Name: Chorros_Agua
* Author: Grupo 1
* description: Sistema show de luces y agua
* el usuario ingresa un archivo txt
**/
#include<stdio.h>
#include<conio.h>
#include<string.h>
char input[200]; // Almacena la cadena de entrada
char token[5]; // Almacena la cadena que forma el smbolo de la palabra
char ch; // Almacena los caracteres ledos actualmente
int p; // input [] subndice
int fg; // marca de cambio
int num; // Almacenar valores enteros
// Matriz de caracteres bidimensionales, almacenando palabras clave
char index[6][6]={"IF","WHILE","DO","ELSE","ELSI","PSI"};
// Declaracin del mtodo de anlisis lxico
void scaner();
int main()
{
//*****************************************************************************************************************************************************************
//Lector de archivos
//*****************************************************************************************************************************************************************
FILE *archivo;
char caracter;
archivo = fopen("Ingreso.txt","r");
if (archivo == NULL)
{
printf("\nError de apertura del archivo. \n\n");
}
else
{
printf("\nEl contenido del archivo es \n\n");
while((caracter = fgetc(archivo)) != EOF)
{
printf("%c",caracter);
}
}
fclose(archivo);
return 0;
// leer cclicamente en caracteres
p=0;
printf("please intput string(End with '#'):\n");
do {
ch=getchar();
input[p++] = ch;
} while( ch!='#' );
p=0;
do {
scaner();
switch( fg )
{
case 8:printf("( %d,%d ) ", fg,num);break;
case -1:printf("input error\n"); break;
default:printf("( %d,%s ) ", fg, token);
}
} while( fg != 0 );
return 0;
}
/*anlisis lxico*/
void scaner()
{
int m=0; // token [] subndice
int n;
// Filtrar espacios
ch=input[p++];
while(ch==' ') ch=input[p++];
// Flujo de procesamiento de palabras clave (identificador)
if(( ch<='z' && ch>='a' )||( ch<='Z' && ch>='A' ))
{
while(( ch<='z' && ch>='a' )||( ch<='Z' && ch>='A' )||( ch<='9' && ch>='0' ))
{
token[m++] = ch;
ch = input[p++];
}
p--;
token[m++] = '\0';
fg = 7;
for( n=0; n<6; n++ )
{
if(strcmp(token, index[n])==0)// strcmp () compara dos cadenas y devuelve 0 si son iguales
{
fg = n+1;
break;
}
}
}
// Flujo de procesamiento digital
else if(( ch<='9' && ch>='0' ))
{
num=0;
while(( ch<='9' && ch>='0' ))
{
num = num*10+ch-'0';
ch = input[p++];
}
p--;
fg = 8;
}
// Flujo de procesamiento del delimitador del operador
else
switch(ch)
{
case '<':
{
token[m++]=ch;
ch=input[p++];
if(ch=='>') // Generar <>
{
fg=14;
token[m++]=ch;
}
else if(ch=='=') // Generar <=
{
fg=15;
token[m++]=ch;
}
else
{
fg=13;
p--;
}
token[m++] = '\0';
break;
}
case '>':
{
token[m++]=ch;
ch=input[p++];
if(ch=='=') // Generar> =
{
fg=17;
token[m++]=ch;
}
else // Generar>
{
fg=16;
p--;
}
token[m++] = '\0';
break;
}
case '+': fg=9; token[0]=ch; token[1]='\0'; break;
case '-': fg=10; token[0]=ch; token[1]='\0'; break;
case '*': fg=11; token[0]=ch; token[1]='\0'; break;
case '/': fg=12; token[0]=ch; token[1]='\0'; break;
case '=': fg=18; token[0]=ch; token[1]='\0'; break;
case ';': fg=19; token[0]=ch; token[1]='\0'; break;
case '(': fg=20; token[0]=ch; token[1]='\0'; break;
case ')': fg=21; token[0]=ch; token[1]='\0'; break;
case '#': fg=0; token[0]=ch; token[1]='\0'; break;
default: fg=-1;
}
}
|
C
|
// C Programming - Project II
#include <stdio.h>
int main() {
// variable initializations
char firstName[256];
char lastName[256];
int courseNumber;
char courseTitle[] = "Introduction to Computing and Problem Solving";
int projectNumber, currentDay, currentYear;
// Input First Name
printf("Please Enter Your First Name:\n");
scanf("%s", firstName);
// Input Last Name
printf("Please Enter Your Last Name:\n");
scanf("%s", lastName);
// Input Course Number
printf("Please enter the Course Number:\n");
scanf("%i", &courseNumber);
// Input C Project Number
printf("Please enter the C Project Number (Integer):\n");
scanf("%i", &projectNumber);
// Input Current Day
printf("Enter the Current Day (Integer):\n");
scanf("%i", ¤tDay);
// Input Current Year
printf("Enter the Current Year (Integer):\n");
scanf("%i", ¤tYear);
// print statements
printf("\n\n%s %s\n\n", firstName, lastName);
printf("%i\n", courseNumber);
printf("%s\n", courseTitle);
printf("C Project %i\n\n", projectNumber);
printf("November %i, %i\n", currentDay, currentYear);
}
// Output:
// Theresa Thoraldson
//
// 1101
// Introduction to Computing and Problem Solving
// C Project 2
//
// November 13th 2017
|
C
|
//Given an array with n unique integers, produce a Reverse BST.Here,the left child is always larger and the right child is always smaller (opposite of a normal BST). Then, print the elements in prefix order (root, left child, right child).
#include <stdio.h>
#include <stdlib.h>
//defining a tree node
typedef struct NodeAddress
{
int val;
struct NodeAddress *left;
struct NodeAddress *right;
struct NodeAddress *parent;
} NodeAddress;
//creating a tree node
NodeAddress *createNode(int val)
{
NodeAddress *newNode = (NodeAddress *)malloc(sizeof(NodeAddress));
newNode->val = val;
newNode->left = NULL;
newNode->right = NULL;
newNode->parent = NULL;
return newNode;
}
//converting the array to a reverse tree (left child is always larger and right child is always smaller)
NodeAddress *arrayToReverseBST(int *a, int n)
{
NodeAddress *root = createNode(a[0]);
NodeAddress *current = root;
for (int i = 1; i < n; i++)
{
current = root;
while (current != NULL)
{
if (a[i] > current->val)
{
if (current->left == NULL)
{
//assigning the left child if it is larger than the parent
current->left = createNode(a[i]);
current->left->parent = current;
break;
}
else
{
current = current->left;
}
}
else if (a[i] < current->val)
{
//assigning the right child if it is smaller than the parent
if (current->right == NULL)
{
current->right = createNode(a[i]);
current->right->parent = current;
break;
}
else
{
current = current->right;
}
}
{
//assigning the right child if it is smaller than the parent
if (current->right == NULL)
{
current->right = createNode(a[i]);
current->right->parent = current;
break;
}
else
{
current = current->right;
}
}
}
}
return root;
}
//printing the tree in prefix order (root, left child, right child)
void prefixPrint(NodeAddress *root)
{
if (root != NULL)
{
printf("%d ", root->val);
prefixPrint(root->left);
prefixPrint(root->right);
}
}
void main()
{
//initiallizing a random array
int a[] = {398, 793, 748, 749, 38, 8929, 19};
int n = sizeof(a) / sizeof(a[0]);
NodeAddress *root = arrayToReverseBST(a, n);
prefixPrint(root);
}
//Given an integer k, print the next largest element (successor) in the Reverse BST. If k does not exist in this BST, print "Pudding" and if k’s successor does not exist in this BST, print "Hamburger".
#include <stdio.h>
#include <stdlib.h>
struct node
{
int val;
struct node *left;
struct node *right;
};
typedef struct node * NodeAddress;
NodeAddress insert(NodeAddress root, int val)
{
if (root == NULL)
{
root = (NodeAddress)malloc(sizeof(struct node));
root->val = val;
root->left = NULL;
root->right = NULL;
}
else
{
if (val < root->val)
{
root->right = insert(root->right, val);
}
else
{
root->left = insert(root->left, val);
}
}
return root;
}
NodeAddress arrayToBST(int *a, int n)
{
NodeAddress root = NULL;
for (int i = 0; i < n; i++)
{
root = insert(root, *a);
a+=1;
}
return root;
}
void prefixPrint(NodeAddress root)
{
if (root != NULL)
{
prefixPrint(root->left);
printf("%d ", root->val);
prefixPrint(root->right);
}
}
void successorReverseBST(NodeAddress root, int k)
{
NodeAddress temp = root;
NodeAddress successor = NULL;
int flag = -1;
while (temp != NULL)
{
if (temp->val == k)
{
flag = 1;
}
if (temp->val > k)
{
successor = temp;
temp = temp->right;
}
else
{
temp = temp->right;
}
}
if (flag == -1)
{
printf("Pudding\n");
}
else if (successor == NULL)
{
printf("Hamburger\n ");
}
else
{
printf("Successor element is: %d", successor->val);
}
}
int main()
{
//initiallizing a random array
int a[] = {398, 793, 748, 749, 38, 8929, 19};
int n = sizeof(a)/sizeof(a[0]);
NodeAddress head = arrayToBST(a, n);
prefixPrint(head);
printf("\n");
int k;
printf("Enter a number: ");
scanf("%d", &k);
successorReverseBST(head, k);
return 0;
}
//Given any two integers x and y in the Reverse BST, find the distance between the two in sorted order. That is, count how many numbers lie in between these two integers x and y. If x, y or both x and y don’t exist in the BST, return -1.
#include <stdio.h>
#include <stdlib.h>
//defining a tree node
typedef struct NodeAddress
{
int val;
struct NodeAddress *left;
struct NodeAddress *right;
struct NodeAddress *parent;
} NodeAddress;
//creating a tree node
NodeAddress *createNode(int val)
{
NodeAddress *newNode = (NodeAddress *)malloc(sizeof(NodeAddress));
newNode->val = val;
newNode->left = NULL;
newNode->right = NULL;
newNode->parent = NULL;
return newNode;
}
//converting the array to a reverse tree (left child is always larger and right child is always smaller)
NodeAddress *arrayToReverseBST(int *a, int n)
{
NodeAddress *root = createNode(a[0]);
NodeAddress *current = root;
for (int i = 1; i < n; i++)
{
current = root;
while (current != NULL)
{
if (a[i] > current->val)
{
if (current->left == NULL)
{
//assigning the left child if it is larger than the parent
current->left = createNode(a[i]);
current->left->parent = current;
break;
}
else
{
current = current->left;
}
}
else
{
//assigning the right child if it is smaller than the parent
if (current->right == NULL)
{
current->right = createNode(a[i]);
current->right->parent = current;
break;
}
else
{
current = current->right;
}
}
}
}
return root;
}
//sorting the reverse binary tree in ascending order
void sortReverseBST(NodeAddress *root)
{
if (root == NULL)
{
return;
}
sortReverseBST(root->right);
sortReverseBST(root->left);
}
//print values in the tree
void printTree(NodeAddress *root)
{
if (root == NULL)
{
return;
}
printTree(root->right);
printf("%d ", root->val);
printTree(root->left);
}
//finding number of elements in the tree
int NumberOfElements(NodeAddress *root)
{
if (root == NULL)
{
return 0;
}
return 1 + NumberOfElements(root->left) + NumberOfElements(root->right);
}
//converting the tree to an array
void treeToArray(NodeAddress *root, int *a, int *i)
{
if (root == NULL)
{
return;
}
treeToArray(root->right, a, i);
a[*i] = root->val;
*i = *i + 1;
treeToArray(root->left, a, i);
}
//print the array
void printArray(int *a, int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
//finding the distance between two integers in the reverse binary tree
int findDistance(NodeAddress *root, int x, int y)
{
int d = 0;
int m = NumberOfElements(root);
int b[m];
int i = 0;
treeToArray(root, b, &i);
//printArray(b, m);
int pc = -1;
int pc1 = -1;
//swapping x and y if x is larger than y
if (x > y)
{
int temp = x;
x = y;
y = temp;
}
for(int i=0; i<m; i++)
{
if(b[i] == x)
{
pc = i;
}
if(b[i] == y)
{
pc1 = i;
}
}
d = pc1 - pc;
return d;
}
void main()
{
//ititializing a random array
int a[] = {5,3,7,2,4,6,8,1};
int n = sizeof(a) / sizeof(a[0]);
NodeAddress *root = arrayToReverseBST(a, n);
sortReverseBST(root);
//printTree(root);
//user input
int x,y;
printf("Enter the element 1: ");
scanf("%d", &x);
printf("Enter the element 2: ");
scanf("%d", &y);
int d= findDistance(root, x, y);
printf("The distance between %d and %d is: %d\n", x, y, d);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "dominion.h"
#include "dominion_helpers.h"
#include "rngs.h"
//testing the adventurer card
int main(int argc, char** argv) {
printf("/*********************** Testing Adventurer Card **************************/\n");
//declare variables
struct gameState game;
int seed = rand() % 10;
int players = 2;
int bonus = 0;
int handPosition = 4;
int choice1, choice2, choice3 = 0;
int k[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//initialize game
initializeGame(players, k, seed, &game);
//grab numbers before calling the card
int handCount1 = numHandCards(&game);
if(cardEffect(adventurer, choice1, choice2, choice3, &game, handPosition, bonus) == 0){
int handCount2 = numHandCards(&game);
//check if deck has grown by more than 2 (number of treasure cards that can be taken with this card)
if(handCount2 == (handCount1 + 2)){
printf("ADVENTURER CARD TEST HAS PASSED\n");
}
else {
printf("ADVENTURER CARD TEST HAS FAILED\n");
}
}
else
{
printf("ADVENTURER CARD TEST HAS FAILED\n");
}
return 0;
}
|
C
|
/*
* Universidad Simón Bolívar
* Departamento de Computación y Tecnología de la Información
* CI-3825 -- Sistemas Operativos I
* Prof.: Yudith Cardinale
* Proyecto 2: Comunicación entre procesos
* Grupo 26
* Autores: Victor De Ponte, 05-38087
* Isaac Lopez, 07-41120
*
* Archivo: almacenamiento.h
* Descripción: Librería que define estructuras de almacenamiento de datos.
* (HEADER)
*/
#ifndef STD
#define STD
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#define TRUE 1
#define FALSE 0
#endif
#ifndef EDG
#define EDG
#include <limits.h>
#endif
/* Estructura para la comunicación entre procesos */
typedef struct ans Ans;
struct ans {
int numChild;
int numRegs;
int numDirects;
int tamBlks;
int tamStr;
int *lengths;
char * directories;
};
/*----------------------------------------------------------------------------*/
/* Definicion del tipo PilaString */
/**
* Estructura de pila convencional. Almacena Strings mediante apuntadores.
*/
typedef struct stack StackString;
struct stack {
char *palabra ;
StackString *sig;
};
typedef struct {
StackString *head;
int size;
} PilaString;
/* FIN tipo PilaString */
/* INICIO de operaciones referentes al tipo PilaString*/
/**
* Crea un nuevo stack de Strings, reservando la memoria para ello
*
* retorna: Un nuevo apuntador a StackString vacio.
*/
StackString *newStackString();
/**
* Crea una nueva pila vacia, reservando la memoria para ello
*
* retorna: Un nuevo apuntador a PilaString vacia.
*/
PilaString *newPilaString();
/**
* Inserta un nuevo elemento elem la PilaString pila.
*
* *pila: apuntador a la pila en donde se desea insertar el elemento.
*
* elem: String que se desea insertar en la pila.
*
* retorna: void.
*/
void pushPilaString(PilaString *pila, char* elem);
/**
* Elimina el primer elemento de la PilaString pila.
*
* *pila: apuntador a la pila de la cual se desea obtener el elemento.
*
* retorna: el string almacenado en stack obtenido.
*/
char* popPilaString(PilaString *pila);
/**
* Verifica si la PilaString pila esta vacia, es decir, no contiene elementos.
*
* *pila: apuntador a la pila en cuestion.
*
* retorna: 1 si la pila esta vacia 0 en caso contrario.
*/
int esVaciaPilaString(PilaString *pila);
/**
*Imprime la pila mostrando cada uno de sus elementos y si tamano total.
*
**pila: pila a imprimir
*/
void imprimePilaString(PilaString *pila);
/**
*Vacia la PilaString pila
*/
void cleanPila(PilaString *pila);
/*FIN de operaciones referentes al tipo PilaString */
/*Definición del tipo ListaInt.*/
/**
* Clasica lista de elementos. Es una lista de apuntadores que almacena int.
*/
typedef struct cajitaInt CajitaInt;
struct cajitaInt {
int data;
int pos;
CajitaInt *sig,*ant;
};
typedef struct {
CajitaInt *head,*tail;
int size;
} ListaInt;
/*FIN del tipo ListaInt.*/
/*INICIO Funciones y Procedimientos referentes al tipo ListaInt*/
/**
* Crea una nueva Cajita, reservando la memoria necesaria para ello.
*
* retorna: Un nuevo apuntador a Cajita vacía.
*/
CajitaInt *newCajitaInt();
/**
* Crea una nueva lista vacía, reservando la memoria necesaria para ello.
*
* retorna: un nuevo apuntador a una lista vacía.
*/
ListaInt *newListaInt();
/**
* Inserta el elemento 'elem' en la Lista '*list'
*
* *list: apuntador a la Lista donde se desea hacer la inserción.
*
* elem: elemento a insertar en la Lista.
*
* retorna: Un entero que indica el estado de la inserción; 0 si fue realizada
* con éxito, 1 en caso contrario.
*/
int add(ListaInt *list, int elem);
/**
* Elimina el elemento 'elem' en la Lista '*list'
*
* *list: apuntador a la Lista donde se desea hacer la eliminación.
*
* elem: elemento a eliminar de la Lista.
*/
void delete(ListaInt *list, int elem);
/**
* Devuelve el elemento en la posición pos.
* retorna en la variable 'ans' el elemento almacenado en la posición 'posi'.
* de no existir un elemento en esa posicion, asigna NULL a 'ans'.
* list: lista a consultar.
* posi: posición del elemento solicitado.
* ans: apuntador a la salida de esta funcion.
*/
void get_li(ListaInt *list, int posi, int *ans);
/**
* Devuelve un arreglo de enteros conteniendo los elementos de la lista 'list'
* en el mismo orden en que estaban almacenados.
* list: Lista a transformar en arreglo.
* retorna: un arreglo de enteros que contiene los elementos de 'lista' en el
* mismo orden en que estaban almacenados.
*/
int *liToArray(ListaInt *list);
/**
* Dice si un elemento 'elem' está actualmente o no en la Lista '*list'.
*
* *list: apuntador a la Lista donde se desea hacer la búsqueda.
*
* elem: elemento a buscar en la Lista.
*
* retorna: Un entero que indica el estado de la búsqueda; 1 si se encontró el
* elemento, 1 en caso contrario.
*/
int isIn(ListaInt *list, int elem);
/**
* Imprime en la salida estándar la ListaInt 'lista'.
*
* lista: ListaInt a imprimir.
*/
void li_print(ListaInt *lista);
/**
* Devuelve el primer elemento de la lista, y lo elimina de ésta.
* list: Lista a consultar.
* retorna: el primer elemento de la lista, o INT_MIN en caso de que sea
* una lista vacía.
*/
int getFirstLI(ListaInt *list);
/**
* Devuelve el último elemento de la lista, y lo elimina de ésta.
* list: Lista a consultar.
* retorna: el último elemento de la lista, o INT_MIN en caso de que sea
* una lista vacía.
*/
int getLastLI(ListaInt *list);
/**
* Se encarga de devolver una ListaInt a su estado original vacía, liberando la
* memoria consumida por ésta.
*
* lote: Un apuntador a la ListaInt que se desea liberar.
*
* retorna: 0 si se completó la limpieza con éxito, 1 en caso contrario.
*/
int li_liberar(ListaInt *lista);
/*FIN Funciones y Procedimientos referentes al tipo ListaInt*/
/*----------------------------------------------------------------------------*/
/*Definición del tipo ListaStr.*/
/**
* Clasica lista de elementos. Es una lista de apuntadores que almacena char *.
* (String)
*/
typedef struct cajaStr CajaStr;
struct cajaStr {
char *data;
int pos;
CajaStr *sig,*ant;
};
typedef struct {
CajaStr *head,*tail;
int size;
} ListaStr;
/*FIN del tipo ListaStr.*/
/*INICIO Funciones y Procedimientos referentes al tipo ListaStr*/
/**
* Crea una nueva CajaStr, reservando la memoria necesaria para ello.
*
* retorna: Un nuevo apuntador a CajaStr vacía.
*/
CajaStr *newCajaStr();
/**
* Crea una nueva lista vacía, reservando la memoria necesaria para ello.
*
* retorna: un nuevo apuntador a una lista vacía.
*/
ListaStr *newListaStr();
/**
* Inserta el elemento 'elem' en la Lista '*list'
*
* *list: apuntador a la Lista donde se desea hacer la inserción.
*
* elem: elemento a insertar en la Lista.
*
* retorna: Un entero que indica el estado de la inserción; 0 si fue realizada
* con éxito, 1 en caso contrario.
*/
int addLS(ListaStr *list, char *elem);
/**
* Elimina el elemento 'elem' en la Lista '*list'
*
* *list: apuntador a la Lista donde se desea hacer la eliminación.
*
* elem: elemento a eliminar de la Lista.
*/
void deleteLS(ListaStr *list, char *elem);
/**
* Devuelve el elemento en la posición pos.
* retorna en la variable 'ans' el elemento almacenado en la posición 'posi'.
* de no existir un elemento en esa posicion, asigna NULL a 'ans'.
* list: lista a consultar.
* posi: posición del elemento solicitado.
* ans: apuntador a la salida de esta funcion.
*/
void getLS(ListaStr *list, int posi, char *ans);
/**
* Devuelve un arreglo de String conteniendo los elementos de la lista 'list'
* en el mismo orden en que estaban almacenados.
* list: Lista a transformar en arreglo.
* retorna: un arreglo de String que contiene los elementos de 'lista' en el
* mismo orden en que estaban almacenados.
*/
char **LSToArray(ListaStr *list);
/**
* Dice si un elemento 'elem' está actualmente o no en la Lista '*list'.
*
* *list: apuntador a la Lista donde se desea hacer la búsqueda.
*
* elem: elemento a buscar en la Lista.
*
* retorna: Un entero que indica el estado de la búsqueda; 1 si se encontró el
* elemento, 1 en caso contrario.
*/
int isInLS(ListaStr *list, char *elem);
/**
* Imprime en la salida estándar la ListaInt 'lista'.
*
* lista: ListaInt a imprimir.
*/
void LSprint(ListaStr *lista);
/**
* Devuelve el primer elemento de la lista, y lo elimina de ésta.
* list: Lista a consultar.
* retorna: el primer elemento de la lista, o NULL en caso de que sea
* una lista vacía.
*/
char *getFirstLS(ListaStr *list);
/**
* Devuelve el último elemento de la lista, y lo elimina de ésta.
* list: Lista a consultar.
* retorna: el último elemento de la lista, o NULL en caso de que sea
* una lista vacía.
*/
char *getLastLS(ListaStr *list);
/**
* Se encarga de devolver una ListaInt a su estado original vacía, liberando la
* memoria consumida por ésta.
*
* lote: Un apuntador a la ListaInt que se desea liberar.
*
* retorna: 0 si se completó la limpieza con éxito, 1 en caso contrario.
*/
int LSLiberar(ListaStr *lista);
/*FIN Funciones y Procedimientos referentes al tipo ListaStr*/
/*----------------------------------------------------------------------------*/
/*FIN DEL ARCHIVO (EOF)*/
|
C
|
#include "./Lib/Grafo.h"
const int print_ele = 0;
void create_graph(int number_componentes, int per_connectivity, int number_vertices, Graph *graph){
per_connectivity = per_connectivity%101;
int newVert = (per_connectivity * (number_vertices - 1))/100;
if(newVert < 1)
return;
graph->number_vertices = number_vertices;
graph->adjList = (List *)malloc(sizeof(List) * number_vertices);
int vertices_per_components = number_vertices/number_componentes;
for(int i=0; i<number_componentes; ++i){
for(int j=i*vertices_per_components; j<vertices_per_components*(i+1); ++j){
if(j == ((vertices_per_components*(i+1))-1) )
push_list(i*vertices_per_components, &graph->adjList[j]);
else
push_list(j+1, &graph->adjList[j]);
}
}
newVert--;
if(newVert < 1)
return;
for(int i=0; i<number_vertices; i++){
int first_component = (i/number_componentes) * number_componentes;
for(int j=0, k=0, vert = first_component; j<number_vertices, k<newVert; j++, vert++){
vert = vert%number_vertices;
if(vert != i){
if(first_component+vertices_per_components-1 == i){
if(vert != first_component){
push_list(vert, &graph->adjList[i]);
k++;
}
}
else{
if(vert != i+1){
push_list(vert, &graph->adjList[i]);
k++;
}
}
}
}
}
}
void create_graph_connected(int per_connectivity, int number_vertices, Graph *graph){
per_connectivity = per_connectivity%101;
int newVert = (per_connectivity * (number_vertices - 1))/100;
graph->number_vertices = number_vertices;
graph->adjList = (List*)malloc(sizeof(List) * number_vertices);
if(newVert < 1)
return;
for(int i=0; i<number_vertices; i++){
int next_vertice = (i+1)%number_vertices;
push_list(next_vertice, &graph->adjList[i]);
}
newVert--;
if(newVert < 1)
return;
for(int i=0; i<number_vertices; i++){
for(int j=0, k=0; j<number_vertices, k<newVert; j++){
if(j != (i+1)%number_vertices && (j!= i)){
push_list(j, &graph->adjList[i]);
k++;
}
}
}
}
void create_graph_acyclic(int per_connectivity, int number_vertices, Graph *graph){
per_connectivity = per_connectivity%101;
int newVert = (per_connectivity * (number_vertices - 1))/100;
graph->number_vertices = number_vertices;
graph->adjList = (List*)malloc(sizeof(List) * number_vertices);
if(newVert < 1)
return;
for(int i=0; i<number_vertices; i++){
if(newVert < 1)
return;
for(int j=i+1; j<number_vertices; j++){
push_list(j, &graph->adjList[i]);
newVert--;
if(newVert < 1)
return;
}
}
}
void show_adjList_vertices(Graph graph){
int n = graph.number_vertices;
for(int i=0; i<n; i++){
printf("Vertice %d: \n", i);
show_list(graph.adjList[i]);
}
}
void DFS_Stack(Graph graph, int start){
int *vis = (int*)malloc(sizeof(int) * graph.number_vertices);
for(int i=0; i<graph.number_vertices; i++)
vis[i] = -1;
Stack stack;
new_stack(&stack);
push_stack(start, &stack);
vis[start] = 1;
while(!stack_empty(stack)){
int cur = top(stack);
if(print_ele)
printf("%d ", cur);
pop_stack(&stack);
for(Element* it = graph.adjList[cur].first; it != NULL; it = it->prox){
int act = it->data;
if(vis[act] == -1){
vis[act] = 1;
push_stack(act, &stack);
}
}
}
if(print_ele)
printf("\n");
}
void DFS_Recursive_Caller(Graph graph, int start){
int *vis = (int*)malloc(sizeof(int) * graph.number_vertices);
for(int i=0; i<graph.number_vertices; i++)
vis[i] = -1;
vis[start] = 1;
DFS_Recursive(start, &graph, vis);
if(print_ele)
printf("\n");
}
void DFS_Recursive(int cur, Graph *graph, int *vis){
if(print_ele)
printf("%d ", cur);
for(Element *it = graph->adjList[cur].first; it != NULL; it = it->prox){
int act = it->data;
if(vis[act] == -1){
vis[act] = 1;
DFS_Recursive(act, graph, vis);
}
}
}
void BFS(Graph graph, int start){
int *vis = (int*)malloc(sizeof(int) * graph.number_vertices);
for(int i=0; i<graph.number_vertices; i++)
vis[i] = -1;
Queue queue;
new_queue(&queue);
push_queue(start, &queue);
vis[start] = 1;
while(!queue_empty(queue)){
int cur = front_queue(queue);
if(print_ele)
printf("%d ", cur);
pop_queue(&queue);
for(Element *it = graph.adjList[cur].first; it != NULL; it = it->prox){
int act = it->data;
if(vis[act] == -1){
vis[act] = 1;
push_queue(act, &queue);
}
}
}
if(print_ele)
printf("\n");
}
int Dfs_Finding_Cycles(int cur, Graph *graph, int *color){
color[cur] = 1;
for(Element *it = graph->adjList[cur].first; it != NULL; it = it->prox){
int act = it->data;
if(color[act] == 0){
if(Dfs_Finding_Cycles(act, graph, color) == 1)
return 1;
}
else if(color[act] == 1)
return 1;
}
color[cur] = 2;
return 0;
}
int Finding_Cycles(Graph graph){
int *color = (int*)malloc(sizeof(int) * graph.number_vertices);
int *visited = (int*)malloc(sizeof(int) * graph.number_vertices);
for(int i=0; i < graph.number_vertices; i++)
visited[i] = color[i] = 0;
for(int i=0; i < graph.number_vertices; i++){
if(visited[i])
continue;
if(Dfs_Finding_Cycles(0,&graph,color))
return 1;
for(int i=0; i < graph.number_vertices; i++){
visited[i] += color[i];
color[i] = 0;
}
}
return 0;
}
void all_way_graph_caller(Graph graph){
Stack stack;
new_stack(&stack);
int *visited = (int*)malloc(sizeof(int) * graph.number_vertices);
for(int i=0; i<graph.number_vertices; i++){
for(int i=0; i<graph.number_vertices; i++)
visited[i] = 0;
visited[i] = 1;
push_stack(i, &stack);
all_way_graph(i, &graph, &stack, visited);
pop_stack(&stack);
}
}
void all_way_graph(int cur, Graph *graph, Stack *stack, int *visited){
if(stack->size == graph->number_vertices){
show_stack(*stack);
return;
}
for(Element *it = graph->adjList[cur].first; it != NULL; it = it->prox){
int act = it->data;
if(visited[act] == 0){
push_stack(act, stack);
visited[act] = 1;
all_way_graph(act, graph,stack, visited);
visited[act] = 0;
pop_stack(stack);
}
}
}
|
C
|
/*
* pFS API
*
* Copyright (C) 2008 Stanislas Polu <spolu@stanford.edu>.
* All Rights Reserved.
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/errno.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <sys/file.h>
#include "pfs.h"
#include "instance.h"
#include "entry.h"
#include "file.h"
#include "dir_cache.h"
#include "path.h"
#include "group.h"
/*---------------------------------------------------------------------
* Method: pfs_open
* Scope: Global Public
*
* Open a file after checking the flags. Creates it if necessary
* link (file_id) -> new_id used for read/write here.
* So that our file can get reclaimed while open and we still be able
* to use the new link to update the entry if the file get dirty.
*
*---------------------------------------------------------------------*/
int pfs_open (struct pfs_instance * pfs,
const char * path,
int flags, mode_t mode)
{
struct pfs_open_file * open_file = NULL;
struct pfs_path_info pi;
int retval, i;
struct pfs_entry * entry = NULL;
char * prt_path = NULL;
char * file_name;
if (strlen (path) == 1 && strncmp (path, "/", 1) == 0)
return -EISDIR;
open_file = (struct pfs_open_file *) malloc (sizeof (struct pfs_open_file));
open_file->ver = NULL;
open_file->fd = 0;
open_file->dirty = 0;
open_file->read_only = 0;
/* If the entry does not exist we create it along with the
underlying file. */
if ((retval = pfs_get_path_info (pfs, path, &pi)) != 0)
{
if (retval != -ENOENT)
goto error;
if (!(flags & O_CREAT)) {
retval = -ENOENT;
goto error;
}
prt_path = (char *) malloc (sizeof (char) * (strlen (path) + 1));
strncpy (prt_path, path, strlen (path) + 1);
for (i = strlen (prt_path) - 1; i > 0 && prt_path[i] != '/'; i--);
prt_path[i] = 0;
file_name = prt_path + (i + 1);
if (i == 0 ||
strstr (file_name, ":") != NULL) {
retval = -EACCES;
goto error;
}
if (strlen (file_name) > (PFS_NAME_LEN - 1)) {
retval = -ENAMETOOLONG;
goto error;
}
if (pfs_get_path_info (pfs, prt_path, &pi) != 0) {
retval = -ENOENT;
goto error;
}
/* We create the entry. */
open_file->ver = (struct pfs_ver *) malloc (sizeof (struct pfs_ver));
pfs_gen_vv (pfs, open_file->ver);
open_file->ver->type = PFS_FIL;
if ((open_file->fd = pfs_file_create (pfs, open_file->ver->dst_id, flags)) < 0) {
retval = -EIO;
goto error;
}
open_file->ver->st_mode = mode | S_IFREG;
strncpy (open_file->id, open_file->ver->dst_id, PFS_ID_LEN);
strncpy (open_file->grp_id, pi.grp_id, PFS_ID_LEN);
strncpy (open_file->dir_id, pi.dst_id, PFS_ID_LEN);
strncpy (open_file->file_name, file_name, PFS_NAME_LEN);
open_file->dirty = 3;
pi.is_main = 1;
pi.st_mode = open_file->ver->st_mode;
/* We call pfs_set_entry here to make the newly created file visible. */
if (pfs_set_entry (pfs, open_file->grp_id, open_file->dir_id,
open_file->file_name, 1, open_file->ver, 0) != 0) {
retval = -EIO;
goto error;
}
free (prt_path);
prt_path = NULL;
}
else if ((flags & O_CREAT) && (flags & O_EXCL)) {
retval = -EEXIST;
goto error;
}
/* The file exist we try to open it. */
else
{
if (pi.type == PFS_DIR) {
retval = -EISDIR;
goto error;
}
/* Check "Permissions". */
if ((pi.type != PFS_FIL) ||
((pi.is_main == 0 || (pi.st_mode & S_IWUSR) == 0) &&
((flags & O_WRONLY) || (flags & O_RDWR) || (flags & O_TRUNC)))) {
retval = -EACCES;
goto error;
}
if ((entry = pfs_get_entry (pfs, pi.dir_id, pi.name)) == NULL) {
retval = -ENOENT;
goto error;
}
for (i = 0; i < entry->ver_cnt; i ++) {
if (strncmp (entry->ver[i]->dst_id, pi.dst_id, PFS_ID_LEN) == 0) {
open_file->ver = pfs_cpy_ver (entry->ver[i]);
}
}
pfs_free_entry (entry);
entry = NULL;
if (open_file->ver == NULL) {
retval = -ENOENT;
goto error;
}
if (pi.is_main == 1 && ((flags & O_WRONLY) || (flags & O_RDWR)))
{
if (pfs_file_link_new_id (pfs, pi.dst_id, open_file->id) != 0 ||
(prt_path = pfs_mk_file_path (pfs, open_file->id)) == NULL ||
(open_file->fd = open (prt_path, flags)) < 0) {
if (open_file->fd < 0) {
retval = open_file->fd;
}
else {
retval = -EIO;
}
goto error;
}
open_file->dirty = 0;
}
else
{
strncpy (open_file->id, open_file->ver->dst_id, PFS_ID_LEN);
if((prt_path = pfs_mk_file_path (pfs, open_file->id)) == NULL ||
(open_file->fd = open (prt_path, flags)) < 0) {
if (open_file->fd < 0)
retval = open_file->fd;
else {
retval = -EIO;
}
goto error;
}
open_file->dirty = 2;
}
strncpy (open_file->ver->dst_id, open_file->id, PFS_ID_LEN);
strncpy (open_file->grp_id, pi.grp_id, PFS_ID_LEN);
strncpy (open_file->dir_id, pi.dir_id, PFS_ID_LEN);
strncpy (open_file->file_name, pi.name, PFS_NAME_LEN);
/* We don't need to call pfs_set_entry. File is already present. */
free (prt_path);
prt_path = NULL;
}
if (pi.is_main == 1 && ((flags & O_WRONLY) || (flags & O_RDWR)))
open_file->read_only = 0;
else
open_file->read_only = 1;
pfs_mutex_lock (&pfs->open_lock);
open_file->prev = NULL;
open_file->next = pfs->open_file;
if (pfs->open_file != NULL)
pfs->open_file->prev = open_file;
pfs->open_file = open_file;
pfs_mutex_unlock (&pfs->open_lock);
return open_file->fd;
error:
if (prt_path != NULL)
free (prt_path);
if (open_file != NULL) {
if (open_file->fd > 0)
close (open_file->fd);
if (open_file->ver != NULL)
pfs_free_ver (open_file->ver);
free (open_file);
}
printf ("PFS_LOG : PFS_OPEN\n");
printf ("ERROR : retval %d\n", retval);
return retval;
}
/*---------------------------------------------------------------------
* Method: pfs_pwrite
* Scope: Global Public
* FINAL
* write to file set dirty as 1
*
*---------------------------------------------------------------------*/
ssize_t pfs_pwrite (struct pfs_instance * pfs,
int pfs_fd,
const void * buf,
size_t len,
off_t offset)
{
struct pfs_open_file * open_file;
ssize_t lenw;
pfs_mutex_lock (&pfs->open_lock);
open_file = pfs->open_file;
while (open_file != NULL && open_file->fd != pfs_fd)
open_file = open_file->next;
pfs_mutex_unlock (&pfs->open_lock);
if (open_file == NULL)
return -EBADF;
if (open_file->read_only == 1)
return -EACCES;
if (open_file->dirty == 0)
open_file->dirty = 1;
if (lseek (open_file->fd, offset, SEEK_SET) != offset ||
(lenw = write (open_file->fd, buf, len)) < 0)
return -errno;
if (pfs->updt_cb != NULL)
pfs->updt_cb (pfs, NULL);
return lenw;
}
/*---------------------------------------------------------------------
* Method: pfs_pwrite
* Scope: Global Public
* FINAL
* read from file
*
*---------------------------------------------------------------------*/
ssize_t pfs_pread (struct pfs_instance * pfs,
int pfs_fd,
void * buf,
size_t len,
off_t offset)
{
struct pfs_open_file * open_file;
ssize_t lenr;
pfs_mutex_lock (&pfs->open_lock);
open_file = pfs->open_file;
while (open_file != NULL && open_file->fd != pfs_fd)
open_file = open_file->next;
pfs_mutex_unlock (&pfs->open_lock);
if (open_file == NULL)
return -EBADF;
if (lseek (open_file->fd, offset, SEEK_SET) != offset ||
(lenr = read (open_file->fd, buf, len)) < 0)
return -errno;
return lenr;
}
/*---------------------------------------------------------------------
* Method: pfs_fsync
* Scope: Global Public
* FINAL
* fsync file desc
*
*---------------------------------------------------------------------*/
int pfs_fsync (struct pfs_instance * pfs,
int pfs_fd)
{
int retval = 0;
struct pfs_open_file * open_file;
pfs_mutex_lock (&pfs->open_lock);
open_file = pfs->open_file;
while (open_file != NULL && open_file->fd != pfs_fd)
open_file = open_file->next;
pfs_mutex_unlock (&pfs->open_lock);
if (open_file == NULL)
return -EBADF;
if (fsync (open_file->fd) < 0)
return -errno;
if (open_file->dirty == 2)
retval = pfs_write_back_dir_cache (pfs, open_file->dir_id);
if (pfs->updt_cb != NULL)
pfs->updt_cb (pfs, NULL);
return retval;
}
/*---------------------------------------------------------------------
* Method: pfs_close
* Scope: Global Public
*
* Gets open_file in pfs->open_file DLL.
*
*---------------------------------------------------------------------*/
int pfs_close (struct pfs_instance * pfs,
int pfs_fd)
{
int retval;
struct pfs_open_file * open_file;
pfs_mutex_lock (&pfs->open_lock);
open_file = pfs->open_file;
while (open_file != NULL && open_file->fd != pfs_fd)
open_file = open_file->next;
if (open_file == NULL) {
pfs_mutex_unlock (&pfs->open_lock);
return -EBADF;
}
if (open_file->prev != NULL)
open_file->prev->next = open_file->next;
else
pfs->open_file = open_file->next;
if (open_file->next != NULL)
open_file->next->prev = open_file->prev;
pfs_mutex_unlock (&pfs->open_lock);
if ((retval = close (open_file->fd)) < 0) {
pfs_free_ver (open_file->ver);
free (open_file);
return -errno;
}
if (open_file->dirty == 2) {
}
else if (open_file->dirty == 3) {
pfs_reset_gen_vv (pfs, open_file->ver);
if (pfs_set_entry (pfs, open_file->grp_id, open_file->dir_id,
open_file->file_name, 0, open_file->ver, 1) != 0) {
pfs_free_ver (open_file->ver);
free (open_file);
return -EIO;
}
}
else if (open_file->dirty == 1) {
pfs_vv_incr (pfs, open_file->ver);
if (pfs_set_entry (pfs, open_file->grp_id, open_file->dir_id,
open_file->file_name, 1, open_file->ver, 1) != 0) {
pfs_free_ver (open_file->ver);
free (open_file);
return -EIO;
}
}
else {
if (pfs_file_unlink (pfs, open_file->id) < 0) {
pfs_free_ver (open_file->ver);
free (open_file);
return -errno;
}
}
pfs_free_ver (open_file->ver);
free (open_file);
return 0;
}
/*---------------------------------------------------------------------
* Method: pfs_stat
* Scope: Global Public
*
* For now using underlying storage stat except for permission.
*
*---------------------------------------------------------------------*/
int pfs_stat (struct pfs_instance * pfs,
const char * path,
struct stat * stbuf)
{
struct pfs_path_info pi;
int retval;
char * file_path = NULL;
memset (stbuf, 0, sizeof (struct stat));
if (strlen (path) == 1 && strncmp (path, "/", 1) == 0) {
stbuf->st_mode = S_IFDIR | 0555;
stbuf->st_nlink = 2;
return 0;
}
if ((retval = pfs_get_path_info (pfs, path, &pi)) != 0)
goto error;
/* We handle group directory separately. */
if (pi.type == PFS_GRP)
{
file_path = pfs_mk_dir_path (pfs, pi.dst_id);
if (file_path == NULL) {
retval = -EIO;
goto error;
}
if (stat (file_path, stbuf) < 0) {
retval = -errno;
goto error;
}
free (file_path);
file_path = NULL;
stbuf->st_mode = pi.st_mode;
return 0;
}
if (pi.type == PFS_FIL || pi.type == PFS_SML)
file_path = pfs_mk_file_path (pfs, pi.dst_id);
if (pi.type == PFS_DIR)
file_path = pfs_mk_dir_path (pfs, pi.dst_id);
if (file_path == NULL) {
retval = -EIO;
goto error;
}
if (stat (file_path, stbuf) < 0) {
retval = -errno;
goto error;
}
free (file_path);
file_path = NULL;
stbuf->st_mode = pi.st_mode;
if (!pi.is_main) {
stbuf->st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
}
return 0;
error:
if (file_path != NULL)
free (file_path);
if (retval != -ENOENT) {
printf ("PFS_LOG : PFS_STAT\n");
printf ("ERROR : retval %d\n", retval);
}
return retval;
}
/*---------------------------------------------------------------------
* Method: pfs_truncate
* Scope: Global Public
*
* Truncate a file denoted by its fd
*
*---------------------------------------------------------------------*/
int pfs_ftruncate (struct pfs_instance * pfs,
int pfs_fd,
off_t len)
{
struct pfs_open_file * open_file;
pfs_mutex_lock (&pfs->open_lock);
open_file = pfs->open_file;
while (open_file != NULL && open_file->fd != pfs_fd)
open_file = open_file->next;
pfs_mutex_unlock (&pfs->open_lock);
if (open_file == NULL)
return -EBADF;
if (open_file->read_only == 1)
return -EIO;
open_file->dirty = 1;
if (ftruncate (open_file->fd, (off_t) len) < 0)
return -errno;
if (pfs->updt_cb != NULL)
pfs->updt_cb (pfs, NULL);
return 0;
}
/*---------------------------------------------------------------------
* Method: pfs_truncate
* Scope: Global Public
*
* Truncate a file denoted by path
*
*---------------------------------------------------------------------*/
int pfs_truncate (struct pfs_instance * pfs,
const char * path,
off_t len)
{
struct pfs_path_info pi;
struct pfs_entry * entry = NULL;
struct pfs_ver * ver = NULL;
int retval;
char * file_path = NULL;
if (strlen (path) == 1 && strcmp (path, "/") == 0) {
retval = -EPERM;
goto error;
}
if ((retval = pfs_get_path_info (pfs, path, &pi)) != 0)
goto error;
if (pi.type == PFS_GRP ||
pi.is_main != 1 ||
(pi.st_mode & S_IWUSR) == 0) {
retval = -EACCES;
goto error;
}
if ((entry = pfs_get_entry (pfs, pi.dir_id, pi.name)) == NULL) {
retval = -ENOENT;
goto error;
}
if (entry->ver[entry->main_idx]->type != PFS_FIL) {
retval = -EISDIR;
goto error;
}
ver = pfs_cpy_ver (entry->ver[entry->main_idx]);
pfs_free_entry (entry);
entry = NULL;
if (pfs_file_link_new_id (pfs, pi.dst_id, ver->dst_id) != 0) {
retval = -EIO;
goto error;
}
pfs_vv_incr (pfs, ver);
file_path = pfs_mk_file_path (pfs, ver->dst_id);
if (truncate (file_path, len) < 0) {
retval = -errno;
goto error;
}
free (file_path);
if (pfs_set_entry (pfs, pi.grp_id, pi.dir_id,
pi.name, 1, ver, 1) != 0) {
retval = -EIO;
goto error;
}
pfs_free_ver (ver);
ver = NULL;
return 0;
error:
if (entry != NULL)
pfs_free_entry (entry);
if (ver != NULL)
pfs_free_ver (ver);
if (file_path != NULL)
free (file_path);
printf ("PFS_LOG : PFS_TRUNCATE\n");
printf ("ERROR : retval %d\n", retval);
return retval;
}
/*---------------------------------------------------------------------
* Method: pfs_readdir
* Scope: Global Public
*
* Return a null terminated array of null terminated string representing
* the directory entry.
* Assumes that no object is bigger than PFS_NAME_LEN - 1
* To be ensured in create_user/sd and file.
*
*---------------------------------------------------------------------*/
char ** pfs_readdir (struct pfs_instance * pfs,
const char * path)
{
struct pfs_dir * dir = NULL;
char ** entry_list = NULL;
int i, j, k, entry_cnt;
struct pfs_path_info pi;
char sd_owner [PFS_NAME_LEN];
char sd_name [PFS_NAME_LEN];
struct pfs_group * next_grp;
/* list the groups. */
if (strlen (path) == 1 && strcmp (path, "/") == 0)
{
pfs_mutex_lock (&pfs->group_lock);
entry_list = (char **) malloc (sizeof (char *) * (pfs->grp_cnt + 3));
for (i = 0; i < pfs->grp_cnt + 3; i ++)
entry_list[i] = NULL;
entry_list[0] = (char *) malloc (sizeof (char) * 2);
strncpy (entry_list[0], ".", 2);
entry_list[1] = (char *) malloc (sizeof (char) * 3);
strncpy (entry_list[1], "..", 3);
next_grp = pfs->group;
for (i = 2; i < pfs->grp_cnt + 2; i ++) {
entry_list[i] = (char *) malloc (sizeof (char) *
(strlen (next_grp->grp_name) + 1));
strncpy (entry_list[i], next_grp->grp_name, strlen (next_grp->grp_name) + 1);
next_grp = next_grp->next;
}
entry_list[i] = NULL;
pfs_mutex_unlock (&pfs->group_lock);
return entry_list;
}
/* list a directory. */
if (pfs_get_path_info (pfs, path, &pi) != 0)
return NULL;
dir = pfs_get_dir_cache (pfs, pi.dst_id);
if (dir == NULL)
return NULL;
entry_cnt = 0;
for (i = 0; i < dir->entry_cnt; i ++) {
for (j = 0; j < dir->entry[i]->ver_cnt; j ++) {
entry_cnt ++;
}
}
entry_list = (char **) malloc (sizeof (char *) * (entry_cnt + 3));
for (i = 0; i < entry_cnt + 3; i ++)
entry_list[i] = NULL;
entry_list[0] = (char *) malloc (2);
strncpy (entry_list[0], ".", 2);
entry_list[1] = (char *) malloc (3);
strncpy (entry_list[1], "..", 3);
k = 2;
for (i = 0; i < dir->entry_cnt; i ++) {
for (j = 0; j < dir->entry[i]->ver_cnt; j ++) {
if (pfs_get_sd_info (pfs, pi.grp_id,
dir->entry[i]->ver[j]->last_updt,
sd_owner, sd_name) != 0)
goto error;
if (j != dir->entry[i]->main_idx) {
entry_list[k] = (char *) malloc (sizeof (char) *
(strlen (dir->entry[i]->name) +
strlen (sd_owner) +
strlen (sd_name) +
3));
sprintf (entry_list[k], "%s.%s:%s",
sd_owner, sd_name, dir->entry[i]->name);
}
else {
entry_list[k] = (char *) malloc (sizeof (char) *
(strlen (dir->entry[i]->name) + 1));
strncpy (entry_list[k], dir->entry[i]->name,
strlen (dir->entry[i]->name) + 1);
}
k ++;
}
}
pfs_unlock_dir_cache (pfs, dir);
entry_list [k] = 0;
return entry_list;
error:
if (dir != NULL)
pfs_unlock_dir_cache (pfs, dir);
if (entry_list != NULL) {
for (i = 0; i < entry_cnt + 3; i ++) {
if (entry_list[i] != NULL)
free (entry_list[i]);
}
free (entry_list);
}
printf ("PFS_LOG : PFS_READDIR\n");
printf ("ERROR\n");
return NULL;
}
/*---------------------------------------------------------------------
* Method: pfs_mkdir
* Scope: Global Public
*
* Creates a directory.
*
*---------------------------------------------------------------------*/
int pfs_mkdir (struct pfs_instance * pfs,
const char * path,
mode_t mode)
{
struct pfs_path_info pi;
int i, retval;
char * prt_path = NULL;
char * name;
struct pfs_ver * ver = NULL;
struct pfs_entry * entry = NULL;
if (strlen (path) == 1 && strcmp (path, "/") == 0) {
retval = -EACCES;
goto error;
}
/* The entry already exists. */
if ((retval = pfs_get_path_info (pfs, path, &pi)) == 0)
{
retval = -EEXIST;
goto error;
}
/* No entry. We have to create it. */
else
{
if (retval != -ENOENT)
goto error;
prt_path = (char *) malloc (sizeof (char) * (strlen (path) + 1));
strncpy (prt_path, path, strlen (path) + 1);
for (i = strlen (prt_path) - 1; i > 0 && prt_path[i] != '/'; i--);
prt_path[i] = 0;
name = prt_path + (i + 1);
if (i == 0) {
retval = -EACCES;
}
if (strstr (name, ":") != NULL) {
retval = -EACCES;
goto error;
}
if (strlen (name) > (PFS_NAME_LEN - 1)) {
retval = -ENAMETOOLONG;
goto error;
}
if (pfs_get_path_info (pfs, prt_path, &pi) != 0) {
retval = -ENOENT;
goto error;
}
/* We create the entry. */
ver = (struct pfs_ver *) malloc (sizeof (struct pfs_ver));
ver->type = PFS_DIR;
ver->st_mode = S_IRUSR | S_IXUSR | S_IWUSR | S_IRGRP
| S_IXGRP | S_IROTH | S_IXGRP | S_IFDIR;
ver->mv = (struct pfs_vv *) malloc (sizeof (struct pfs_vv));
pfs_gen_vv (pfs, ver);
if (pfs_create_dir (pfs, ver->dst_id) != 0 ||
pfs_set_entry (pfs, pi.grp_id, pi.dst_id,
name, 1, ver, 1) != 0) {
pfs_dir_rmdir (pfs, ver->dst_id);
retval = -EIO;
goto error;
}
free (prt_path);
pfs_free_ver (ver);
prt_path = NULL;
ver = NULL;
}
return 0;
error:
if (entry != NULL)
pfs_free_entry (entry);
if (ver != NULL)
pfs_free_ver (ver);
if (prt_path != NULL)
free (prt_path);
printf ("PFS_LOG : PFS_MKDIR\n");
printf ("ERROR : retval %d\n", retval);
return retval;
}
/*---------------------------------------------------------------------
* Method: pfs_unlink
* Scope: Global Public
*
* Unlink a file denoted by path. Only main version acceptable.
*
*---------------------------------------------------------------------*/
int pfs_unlink (struct pfs_instance * pfs,
const char * path)
{
struct pfs_path_info pi;
struct pfs_entry * entry = NULL;
struct pfs_ver * ver = NULL;
int retval;
if (strlen (path) == 1 && strcmp (path, "/") == 0) {
retval = -EPERM;
goto error;
}
if ((retval = pfs_get_path_info (pfs, path, &pi)) != 0)
goto error;
if (pi.type == PFS_GRP || pi.is_main != 1) {
retval = -EACCES;
goto error;
}
if ((entry = pfs_get_entry (pfs, pi.dir_id, pi.name)) == NULL) {
retval = -ENOENT;
goto error;
}
if (entry->ver[entry->main_idx]->type == PFS_DIR) {
retval = -EPERM;
goto error;
}
ver = pfs_cpy_ver (entry->ver[entry->main_idx]);
pfs_free_entry (entry);
entry = NULL;
ver->type = PFS_DEL;
ver->st_mode = 0;
memset (ver->dst_id, 0, PFS_ID_LEN);
pfs_vv_incr (pfs, ver);
if (pfs_set_entry (pfs, pi.grp_id, pi.dir_id,
pi.name, 1, ver, 1) != 0) {
retval = -EIO;
goto error;
}
pfs_free_ver (ver);
ver = NULL;
return 0;
error:
if (entry != NULL)
pfs_free_entry (entry);
if (ver != NULL)
pfs_free_ver (ver);
printf ("PFS_LOG : PFS_UNLINK\n");
printf ("ERROR : retval %d\n", retval);
return retval;
}
/*---------------------------------------------------------------------
* Method: pfs_rmdir
* Scope: Global Public
*
* Checks atomically if dir empty and remove it
*
*---------------------------------------------------------------------*/
int pfs_rmdir (struct pfs_instance * pfs,
const char * path)
{
struct pfs_path_info pi;
int retval;
struct pfs_entry * entry = NULL;
struct pfs_ver * ver = NULL;
if (strlen (path) == 1 && strcmp (path, "/") == 0) {
retval = -EACCES;
goto error;
}
if ((retval = pfs_get_path_info (pfs, path, &pi)) != 0)
goto error;
if (pi.type != PFS_DIR || pi.is_main != 1) {
retval = -EACCES;
goto error;
}
if (pfs_dir_empty (pfs, pi.dst_id) == 0) {
retval = -ENOTEMPTY;
goto error;
}
if ((entry = pfs_get_entry (pfs, pi.dir_id, pi.name)) == NULL) {
retval = -ENOENT;
goto error;
}
if (entry->ver[entry->main_idx]->type != PFS_DIR) {
retval = -ENOTDIR;
goto error;
}
ver = pfs_cpy_ver (entry->ver[entry->main_idx]);
pfs_free_entry (entry);
entry = NULL;
ver->type = PFS_DEL;
ver->st_mode = 0;
memset (ver->dst_id, 0, PFS_ID_LEN);
pfs_vv_incr (pfs, ver);
if ((retval = pfs_set_entry (pfs, pi.grp_id, pi.dir_id,
pi.name, 1, ver, 1)) != 0) {
retval = -EIO;
goto error;
}
pfs_free_ver (ver);
ver = NULL;
//printf ("PFS_LOG : PFS_UNLINK DONE\n");
return 0;
error:
if (entry != NULL)
pfs_free_entry (entry);
if (ver != NULL)
pfs_free_ver (ver);
if (retval != -ENOTEMPTY) {
printf ("PFS_LOG : PFS_RMDIR\n");
printf ("ERROR : retval %d\n", retval);
}
return retval;
}
/*---------------------------------------------------------------------
* Method: pfs_rename
* Scope: Global Public
*
* Rename a file or directory.
*
*---------------------------------------------------------------------*/
int pfs_rename (struct pfs_instance * pfs,
const char * old,
const char * new)
{
struct pfs_path_info pi_old, pi_new;
struct pfs_entry * entry = NULL;
struct pfs_ver * ver_old = NULL;
struct pfs_ver * ver_new = NULL;
char * prt_path = NULL;
char * name;
int i, retval;
if ((strlen (old) == 1 && strcmp (old, "/") == 0) ||
(strlen (new) == 1 && strcmp (new, "/") == 0)) {
retval = -EACCES;
goto error;
}
if ((retval = pfs_get_path_info (pfs, old, &pi_old)) != 0)
goto error;
if (pi_old.type == PFS_GRP ||
pi_old.is_main != 1) {
retval = -EACCES;
goto error;
}
if ((entry = pfs_get_entry (pfs, pi_old.dir_id, pi_old.name)) == NULL) {
retval = -ENOENT;
goto error;
}
ver_old = pfs_cpy_ver (entry->ver[entry->main_idx]);
pfs_free_entry (entry);
entry = NULL;
if (pfs_get_path_info (pfs, new, &pi_new) == 0)
{
if (strncmp (pi_new.grp_id, pi_old.grp_id, PFS_ID_LEN) != 0) {
retval = -EXDEV;
goto error;
}
if (pi_new.type == PFS_GRP ||
pi_new.is_main != 1 ||
((pi_new.st_mode & S_IWUSR) == 0)) {
retval = -EACCES;
goto error;
}
if (pi_new.type == PFS_DIR && pfs_dir_empty (pfs, pi_new.dst_id) == 0) {
retval = -ENOTEMPTY;
goto error;
}
if ((entry = pfs_get_entry (pfs, pi_new.dir_id, pi_new.name)) == NULL) {
retval = -EIO;
goto error;
}
ver_new = pfs_cpy_ver (entry->ver[entry->main_idx]);
pfs_free_entry (entry);
entry = NULL;
pfs_vv_incr (pfs, ver_new);
}
else
{
if (strncmp (pi_new.grp_id, pi_old.grp_id, PFS_ID_LEN) != 0) {
retval = -EXDEV;
goto error;
}
prt_path = (char *) malloc (sizeof (char) * (strlen (new) + 1));
strncpy (prt_path, new, strlen (new) + 1);
for (i = strlen (prt_path) - 1; i > 0 && prt_path[i] != '/'; i--);
prt_path[i] = 0;
name = prt_path + (i + 1);
if (i == 0 ||
strstr (name, ":") != NULL) {
retval = -EACCES;
goto error;
}
if (strlen (name) > (PFS_NAME_LEN - 1)) {
retval = -ENAMETOOLONG;
goto error;
}
if (pfs_get_path_info (pfs, prt_path, &pi_new) != 0) {
retval = -ENOENT;
goto error;
}
ver_new = (struct pfs_ver *) malloc (sizeof (struct pfs_ver));
pfs_gen_vv (pfs, ver_new);
memset (ver_new->dst_id, 0, PFS_ID_LEN);
strncpy (pi_new.dir_id, pi_new.dst_id, PFS_ID_LEN);
strncpy (pi_new.name, name, PFS_NAME_LEN);
memset (pi_new.dst_id, 0, PFS_ID_LEN);
free (prt_path);
prt_path = NULL;
}
ver_new->type = ver_old->type;
memcpy (ver_new->dst_id, ver_old->dst_id, PFS_ID_LEN);
ver_new->st_mode = ver_old->st_mode;
ver_old->type = PFS_DEL;
memset (ver_old->dst_id, 0, PFS_ID_LEN);
ver_old->st_mode = 0;
pfs_vv_incr (pfs, ver_old);
if (pfs_set_entry (pfs, pi_new.grp_id, pi_new.dir_id,
pi_new.name, 1, ver_new, 1) != 0) {
retval = -EIO;
goto error;
}
if (pfs_set_entry (pfs, pi_old.grp_id, pi_old.dir_id,
pi_old.name, 0, ver_old, 1) != 0) {
retval = -EIO;
goto error;
}
pfs_free_ver (ver_old);
pfs_free_ver (ver_new);
return 0;
error:
if (entry != NULL)
pfs_free_entry (entry);
if (ver_old != NULL)
pfs_free_ver (ver_old);
if (ver_new != NULL)
pfs_free_ver (ver_new);
if (prt_path != NULL)
free (prt_path);
printf ("PFS_LOG : PFS_RENAME\n");
printf ("ERROR : retval %d\n", retval);
return retval;
}
/*---------------------------------------------------------------------
* Method: pfs_statfs
* Scope: Global Public
*
* Primarly used for now to pass the fs capacity
*
*---------------------------------------------------------------------*/
int pfs_statfs (struct pfs_instance * pfs,
struct statvfs * buf)
{
int retval;
char * info_path;
//printf ("PFS_LOG : PFS_STATFS\n");
/* we use info file to get underlying fs stat. */
info_path = (char *) malloc ((strlen (pfs->root_path) + strlen (PFS_INFO_PATH) + 1));
if (info_path == NULL)
return -EIO;
sprintf (info_path, "%s%s", pfs->root_path, PFS_INFO_PATH);
retval = statvfs (info_path, buf);
free (info_path);
buf->f_namemax = PFS_NAME_LEN - 1;
//buf->f_flag = ST_NOSUID;
//buf->f_fsid = 0;
//printf ("PFS_LOG : PFS_STATFS DONE\n");
return retval;
}
/*---------------------------------------------------------------------
* Method: pfs_readlink
* Scope: Global Public
*
*
*
*---------------------------------------------------------------------*/
int pfs_readlink (struct pfs_instance * pfs,
const char * path,
char * buf,
size_t bufsize)
{
struct pfs_path_info pi;
int retval;
int fd = 0;
char * ln_path = NULL;
size_t len = 0;
if (strlen (path) == 1 && strncmp (path, "/", 1) == 0)
return -EISDIR;
if ((retval = pfs_get_path_info (pfs, path, &pi)) != 0)
goto error;
/* The file exist we try to open it. */
if (pi.type != PFS_SML) {
retval = -ENOENT;
goto error;
}
/* Check "Permissions". */
if ((pi.st_mode & S_IRUSR) == 0) {
retval = -EACCES;
goto error;
}
if((ln_path = pfs_mk_file_path (pfs, pi.dst_id)) == NULL ||
(fd = open (ln_path, O_RDONLY)) < 0) {
if (fd < 0)
retval = fd;
else
retval = -EIO;
goto error;
}
free (ln_path);
ln_path = NULL;
read (fd, &len, sizeof (size_t));
if (len > bufsize)
len = bufsize - 1;
read (fd, buf, len);
buf[len] = 0;
close (fd);
return 0;
error:
if (ln_path != NULL)
free (ln_path);
if (fd > 0)
close (fd);
printf ("PFS_LOG : PFS_READLINK\n");
printf ("ERROR : retval %d\n", retval);
return retval;
}
/*---------------------------------------------------------------------
* Method: pfs_symlink
* Scope: Global Public
*
*
*
*---------------------------------------------------------------------*/
int pfs_symlink (struct pfs_instance * pfs,
const char * path,
const char * to)
{
int fd = 0;
size_t len;
struct pfs_path_info pi;
int retval, i;
struct pfs_ver * ver = NULL;
struct pfs_entry * entry = NULL;
char * prt_path = NULL;
char * file_name;
if (strlen (path) == 1 && strncmp (path, "/", 1) == 0)
return -EISDIR;
/* If the entry does not exist we create it along with the
underlying link file. */
if ((retval = pfs_get_path_info (pfs, path, &pi)) != 0)
{
if (retval != -ENOENT)
goto error;
prt_path = (char *) malloc (sizeof (char) * (strlen (path) + 1));
strncpy (prt_path, path, strlen (path) + 1);
for (i = strlen (prt_path) - 1; i > 0 && prt_path[i] != '/'; i--);
prt_path[i] = 0;
file_name = prt_path + (i + 1);
if (i == 0 ||
strstr (file_name, ":") != NULL) {
retval = -EACCES;
goto error;
}
if (strlen (file_name) > (PFS_NAME_LEN - 1)) {
retval = -ENAMETOOLONG;
goto error;
}
if (pfs_get_path_info (pfs, prt_path, &pi) != 0) {
retval = -ENOENT;
goto error;
}
/* We create the entry. */
ver = (struct pfs_ver *) malloc (sizeof (struct pfs_ver));
pfs_gen_vv (pfs, ver);
ver->type = PFS_SML;
if ((fd = pfs_file_create (pfs, ver->dst_id,
O_CREAT | O_WRONLY | O_TRUNC)) < 0) {
retval = -EIO;
goto error;
}
len = strlen (to);
write (fd, &len, sizeof (size_t));
write (fd, to, len);
close (fd);
ver->st_mode =
S_IRWXU |
S_IRGRP | S_IXGRP |
S_IROTH | S_IXOTH |
S_IFLNK;
if (pfs_set_entry (pfs, pi.grp_id, pi.dst_id,
file_name, 1, ver, 1) != 0) {
retval = -EIO;
goto error;
}
pfs_free_ver (ver);
ver = NULL;
free (prt_path);
prt_path = NULL;
}
else {
retval = -EEXIST;
goto error;
}
return 0;
error:
if (prt_path != NULL)
free (prt_path);
if (fd > 0)
close (fd);
if (ver != NULL)
pfs_free_ver (ver);
if (entry != NULL)
pfs_free_entry (entry);
printf ("PFS_LOG : PFS_SYMLINK\n");
printf ("ERROR : retval %d\n", retval);
return retval;
}
/*---------------------------------------------------------------------
* Method: pfs_link
* Scope: Global Public
*
* Create a link. Links have a strange semantic in pFS, it creates an
* entry a link to the same blob. That newly created id will be
* independently transmitted and modification made to the linked
* file won't be visible from the new file. Their versioning history
* diverges here.
*
*---------------------------------------------------------------------*/
int pfs_link (struct pfs_instance * pfs,
const char * path,
const char * to)
{
struct pfs_path_info pi;
int retval, i;
struct pfs_entry * entry = NULL;
struct pfs_ver * ver = NULL;
char * prt_path = NULL;
char * file_name;
struct pfs_path_info pi_to;
/* First we fetch the "to" dst_id. */
if (strlen (to) == 1 && strncmp (to, "/", 1) == 0)
return -EISDIR;
if ((retval = pfs_get_path_info (pfs, to, &pi_to)) != 0)
goto error;
/* The file exist we try to open it. */
if (pi_to.type != PFS_FIL) {
retval = -ENOENT;
goto error;
}
/* Check "Permissions". */
if ((pi_to.st_mode & S_IRUSR) == 0) {
retval = -EACCES;
goto error;
}
/* He we have all we need, let's work on path. */
if (strlen (path) == 1 && strncmp (path, "/", 1) == 0)
return -EISDIR;
if ((retval = pfs_get_path_info (pfs, path, &pi)) != 0)
{
if (retval != -ENOENT)
goto error;
prt_path = (char *) malloc (sizeof (char) * (strlen (path) + 1));
strncpy (prt_path, path, strlen (path) + 1);
for (i = strlen (prt_path) - 1; i > 0 && prt_path[i] != '/'; i--);
prt_path[i] = 0;
file_name = prt_path + (i + 1);
if (i == 0 ||
strstr (file_name, ":") != NULL) {
retval = -EACCES;
goto error;
}
if (strlen (file_name) > (PFS_NAME_LEN - 1)) {
retval = -ENAMETOOLONG;
goto error;
}
if (pfs_get_path_info (pfs, prt_path, &pi) != 0) {
retval = -ENOENT;
goto error;
}
/* We create the entry. */
ver = (struct pfs_ver *) malloc (sizeof (struct pfs_ver));
pfs_gen_vv (pfs, ver);
ver->type = PFS_FIL;
if (pfs_file_copy_id (pfs, pi_to.dst_id, ver->dst_id) != 0) {
retval = -EIO;
goto error;
}
ver->st_mode = pi_to.st_mode;
if (pfs_set_entry (pfs, pi.grp_id, pi.dst_id,
file_name, 1, ver, 1) != 0) {
retval = -EIO;
goto error;
}
pfs_free_ver (ver);
ver = NULL;
free (prt_path);
prt_path = NULL;
}
else {
retval = -EEXIST;
goto error;
}
return 0;
error:
if (prt_path != NULL)
free (prt_path);
if (ver != NULL)
pfs_free_ver (ver);
if (entry != NULL)
pfs_free_entry (entry);
printf ("PFS_LOG : PFS_LINK\n");
printf ("ERROR : retval %d\n", retval);
return retval;
}
/*---------------------------------------------------------------------
* Method: pfs_utime
* Scope: Global Public
*
* Set the tile access/modification time
*
*---------------------------------------------------------------------*/
int pfs_utimens (struct pfs_instance * pfs,
const char * path,
const struct timespec tv[2])
{
struct pfs_path_info pi;
int retval;
char * file_path = NULL;
struct timeval arg [2];
if (strlen (path) == 1 && strcmp (path, "/") == 0) {
retval = -EACCES;
goto error;
}
if (pfs_get_path_info (pfs, path, &pi) != 0) {
retval = -ENOENT;
goto error;
}
if (pi.type == PFS_GRP) {
retval = -EACCES;
goto error;
}
if (pi.type == PFS_FIL || pi.type == PFS_SML)
file_path = pfs_mk_file_path (pfs, pi.dst_id);
if (pi.type == PFS_DIR)
file_path = pfs_mk_dir_path (pfs, pi.dst_id);
if (file_path == NULL) {
retval = -EIO;
goto error;
}
arg[0].tv_sec = tv[0].tv_sec;
arg[0].tv_usec = tv[0].tv_nsec / 1000;
arg[1].tv_sec = tv[1].tv_sec;
arg[1].tv_usec = tv[1].tv_nsec / 1000;
if (utimes (file_path, arg) < 0) {
retval = -errno;
goto error;
}
free (file_path);
return 0;
error:
if (file_path != NULL)
free (file_path);
printf ("PFS_LOG : PFS_UTMIENS\n");
printf ("ERROR : retval %d\n", retval);
return retval;
}
/*---------------------------------------------------------------------
* Method: pfs_chmod
* Scope: Global Public
*
* Set the access mode
*
*---------------------------------------------------------------------*/
int pfs_chmod (struct pfs_instance * pfs,
const char * path,
mode_t mode)
{
struct pfs_path_info pi;
struct pfs_entry * entry = NULL;
struct pfs_ver * ver = NULL;
int retval;
if (strlen (path) == 1 && strcmp (path, "/") == 0) {
retval = -EPERM;
goto error;
}
if ((retval = pfs_get_path_info (pfs, path, &pi)) != 0)
goto error;
if (pi.type == PFS_GRP || pi.is_main != 1) {
retval = -EACCES;
goto error;
}
if ((entry = pfs_get_entry (pfs, pi.dir_id, pi.name)) == NULL) {
retval = -ENOENT;
goto error;
}
ver = pfs_cpy_ver (entry->ver[entry->main_idx]);
pfs_free_entry (entry);
entry = NULL;
ver->st_mode = mode;
if (pi.type == PFS_DIR)
ver->st_mode |= S_IFDIR;
if (pi.type == PFS_FIL)
ver->st_mode |= S_IFREG;
pfs_vv_incr (pfs, ver);
if (pfs_set_entry (pfs, pi.grp_id, pi.dir_id,
pi.name, 0, ver, 1) != 0) {
retval = -EIO;
goto error;
}
pfs_free_ver (ver);
ver = NULL;
return 0;
error:
if (entry != NULL)
pfs_free_entry (entry);
if (ver != NULL)
pfs_free_ver (ver);
printf ("PFS_LOG : PFS_UNLINK\n");
printf ("ERROR : retval %d\n", retval);
return retval;
}
/* SPECIAL OPERATIONS */
/*---------------------------------------------------------------------
* Method: pfs_group_create
* Scope: Global
*
* Create a group
*
*---------------------------------------------------------------------*/
int
pfs_group_create (struct pfs_instance * pfs,
char * grp_name)
{
char grp_id [PFS_ID_LEN];
if (strlen (grp_name) > PFS_NAME_LEN - 1)
return -1;
/* add the root dir. */
if (pfs_create_dir (pfs, grp_id) != 0)
return -1;
pfs_group_add (pfs, grp_name, grp_id);
#ifdef DEBUG
printf ("*** PFS_GRP_CREATE %.*s : %s\n", PFS_ID_LEN, grp_id, grp_name);
#endif
return 0;
}
int
pfs_bootstrap (const char * root_path,
const char * sd_owner,
const char * sd_name)
{
return pfs_bootstrap_inst (root_path,
sd_owner,
sd_name);
}
struct pfs_instance *
pfs_init (const char * root_path)
{
return pfs_init_instance (root_path);
}
int
pfs_destroy (struct pfs_instance * pfs)
{
printf ("PFS_LOG : PFS_DESTROY\n");
return pfs_destroy_instance (pfs);
}
int
pfs_sync (struct pfs_instance * pfs)
{
pfs_write_back_info (pfs);
pfs_write_back_group (pfs);
pfs_sync_dir_cache (pfs);
return 0;
}
int
pfs_set_updt_cb (struct pfs_instance * pfs,
int(*updt_cb)(struct pfs_instance *, struct pfs_updt *))
{
pfs_mutex_lock (&pfs->info_lock);
pfs->updt_cb = updt_cb;
pfs_mutex_unlock (&pfs->info_lock);
return 0;
}
|
C
|
#include <stdio.h>
#include "my_list.h"
list_t *my_params_in_list(int argc, char **argv);
int main(int nb_args, char** args)
{
list_t *params = NULL;
params = my_params_in_list(nb_args, args);
if (params != NULL) {
do {
printf("%s \n", ((char *)params->data));
params = params->next;
} while (params != NULL);
}
return 0;
}
|
C
|
int findMiddleIndex(int *nums, int numsSize) {
if (numsSize == 1)
return 0;
for (int i = 0; i < numsSize; i++) {
int sum_left = 0;
int sum_right = 0;
if (i == 0) {
for (int j = 1; j < numsSize; j++)
sum_right += nums[j];
}
else if (i == numsSize -1) {
for (int j = i-1; j >= 0; j--)
sum_left += nums[j];
}
else {
for (int j = 0; j < i; j++)
sum_left += nums[j];
for (int j = i+1; j < numsSize; j++)
sum_right += nums[j];
}
if (sum_left == sum_right)
return i;
}
return -1;
}
|
C
|
#include"stdio.h"
void RightShift( int arr[],int N, int k)
{
while(k--)
{
char t = arr[N-1];
for(int i = N-1; i > 0; i--)
arr[i] = arr[i-1];
arr[0] = t;
}
for(int i=0;i<N-1;i++)
{ printf("%d ",arr[i]);
}
printf("%d",arr[N-1]);
}
int main()
{
int N,M;
//输入
scanf("%d %d",&N,&M);
int table[N];
for(int i=0;i<N;i++)
{ scanf("%d",&table[i]);
}
//变换&输出
RightShift(table,N,M);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
// Deifning macro Q_MONTHS to be valued as 12
#define Q_MONTHS 12
// Creating a new type boolean_t to work with boolean values true and false
typedef enum{
false, true
}boolean_t;
// Creating a pointer to function type __function_compare__, that receies two addresses of memory and returns an integer
typedef int(*__function_compare__)(void*, void*);
// Creatinf a new type time_average_t to store info about time and month
typedef struct{
double time;
int month;
}time_average_t;
// Function definition
int compare_double(void*, void*);
time_average_t *set_bigger(time_average_t*);
// Main function
int main(void){
time_average_t *times = (time_average_t*)malloc(Q_MONTHS * sizeof(time_average_t)); // Allocates memory to store every time in the year
for(int i = 0; i < Q_MONTHS; i++){
scanf("%lf", ×[i].time);
times[i].month = i + 1;
}
time_average_t *bigger = set_bigger(times);
printf("%d %.2lf\n", bigger->month, bigger->time);
// Deallocates memory allocated for bigger and times
free(bigger);
free(times);
return 0;
}
// Sets the biggest time and stores it in the array as with its correspondent month
time_average_t *set_bigger(time_average_t *array){
time_average_t *time = (time_average_t*)malloc(sizeof(time_average_t));
time->month = array[0].month;
time->time = array[0].time;
for(int i = 0; i < Q_MONTHS; i++){
if(array[i].time > time->time){
time->time = array[i].time;
time->month = array[i].month;
}
}
return time;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print_list_sort_a.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: xinzhang <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/09/25 21:44:53 by xinzhang #+# #+# */
/* Updated: 2018/10/04 21:49:05 by xinzhang ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*int sort_mtime(time_t t1, time_t t2)
{
return (t1 - t2);
}
int re_sort_mtime(time_t t1, time_t t2)
{
return (t2 - t1);
}
*/
void sort_list_time(stat_dlist *dl, stat_node *sn, TIME_PTR t, int len)
{
stat_node *tmp;
stat_node *pre;
stat_node *head;
int flag;
int i;
head = sn;
i = len - 1;
if (len >= 2)
{
while (i > 0)
{
pre = NULL;
sn = head;
while (sn && sn->next)
{
// printf("-----------------------\n");
// display(head);
flag = 0;
if (t(sn->stat_info->st_mtimespec.tv_sec,
sn->next->stat_info->st_mtimespec.tv_sec) > 0)
{
flag = 1;
if (pre == NULL)
{
// printf("switch %ld %s, %ld %s,\n",
// sn->stat_info->st_mtimespec.tv_nsec,
// sn->sname,
// (sn->next->stat_info->st_mtimespec).tv_nsec,
// sn->next->next->sname);
tmp = sn->next;
sn->next = sn->next->next;
tmp->next = sn;
head = tmp;
pre = head;
}
else
{
// printf("switch %ld %s, %ld %s,\n",
// sn->stat_info->st_mtimespec.tv_nsec,
// sn->sname,
// (sn->next->stat_info->st_mtimespec).tv_nsec,
// sn->next->next->sname);
pre->next = sn->next;
tmp = sn->next;
sn->next = sn->next->next;
tmp->next = sn;
pre = pre->next;
}
}
if (!flag)
{
pre = sn;
sn = sn->next;
}
}
i--;
}
}
dl->head = head;
}
|
C
|
/*
ITS240-01
Lab 01
Ch3p119pe3
01/18/2017
Daniel Kuckuck
Heron's formula is based on a triangle with sides a, b, and c: area = sqrt(s*(s-a)*(s-b)*(s-c)), where s=(a+b+c)/2.
Using Heron’s formula, make a program that calculates and displays the area of a trianlge having sides of 3, 4, and 5.
*/
#include <stdio.h>
#include <math.h>
int main()
{
int side1, side2, side3, allSidesDiv2, area; /* initialize our integer variables */
side1=3; /* Define our variables */
side2=4;
side3=5;
printf("\nUsing Heron's formula we are going to find the area of a\ntriangle with the sides of %d, %d, and %d \n", side1, side2, side3);
printf("Heron\'s formula is area = sqrt(s*(s-a)*(s-b)*(s-c)),\nwhere s=(a+b+c)/2.\n\n"); /* I love how you escape the restricted characters */
allSidesDiv2=(side1+side2+side3)/2; /* define allSidesDiv2 or, s and perform our calculation for s */
printf("Our triangle calcuates s=(%d+%d+%d)/2 so s=%d.\n", side1, side2, side3, allSidesDiv2);
area=sqrt((allSidesDiv2-side1)*(allSidesDiv2-side2)*(allSidesDiv2-side3)); /*defining area and working our final calculation */
printf("The area then is, sqrt((%d-%d)*(%d-%d)*(%d-%d) \nwhich equals %d sqft.\n", allSidesDiv2, side1, allSidesDiv2, side2, allSidesDiv2, side3, area); /* I used the variables so that if I need to I can use the code again */
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <CL/cl.h>
#include "simple.h"
#define DATA_SIZE 1024
const char *KernelSource = "\n"
// FILL IN HERE!
"\n";
struct timespec start, stop;
void printTimeElapsed( char *text)
{
double elapsed = (stop.tv_sec -start.tv_sec)*1000.0
+ (double)(stop.tv_nsec -start.tv_nsec)/1000000.0;
printf( "%s: %f msec\n", text, elapsed);
}
void timeDirectImplementation( int count, float* in_a, float* in_b, float *out)
{
float sum;
clock_gettime( CLOCK_PROCESS_CPUTIME_ID, &start);
for (int i = 0; i < count; i++) {
for (int j = 0; j < count; j++) {
sum = 0.0;
for (int k = 0; k < count; k++) {
sum += in_a[i*count+k] * in_b[k*count+j];
}
out[i*count+j] =sum;
}
}
clock_gettime( CLOCK_PROCESS_CPUTIME_ID, &stop);
printTimeElapsed( "kernel equivalent on host");
}
int main (int argc, char * argv[])
{
cl_int err;
cl_kernel kernel;
// define and set work set here:
size_t global[?];
size_t local[?];
if( argc < ?) {
???
} else {
???
}
printf( "work group size: ???\n", ??? );
clock_gettime( CLOCK_PROCESS_CPUTIME_ID, &start);
/* Create data for the run. */
float *in_a = NULL; /* Original data set given to device. */
float *in_b = NULL; /* Original data set given to device. */
float *out = NULL; /* Results returned from device. */
int correct; /* Number of correct results returned. */
int count = DATA_SIZE;
float sum;
global[0] = count;
global[1] = count;
in_a = (float *) malloc (count * count * sizeof (float));
in_b = (float *) malloc (count * count * sizeof (float));
out = (float *) malloc (count * count * sizeof (float));
/* Fill the vector with random float values. */
for (int i = 0; i < count*count; i++) {
in_a[i] = rand () / (float) RAND_MAX;
in_b[i] = rand () / (float) RAND_MAX;
}
if( argc > 3) {
printf( "using openCL on host!\n");
err = initCPU();
} else {
printf( "using openCL on GPU!\n");
err = initGPU();
}
if( err == CL_SUCCESS) {
// Fill in here:
kernel = setupKernel( KernelSource, "matmul", ???);
// Fill in here:
runKernel( kernel, ???, global, local);
clock_gettime( CLOCK_PROCESS_CPUTIME_ID, &stop);
printKernelTime();
printTimeElapsed( "CPU time spent");
/* Validate our results. */
correct = 0;
for (int i = 0; i < count; i++) {
for (int j = 0; j < count; j++) {
sum = 0.0;
for (int k = 0; k < count; k++) {
sum += in_a[i*count+k] * in_b[k*count+j];
}
if ( abs(out[i*count+j] - sum) < 0.0001)
correct++;
}
}
/* Print a brief summary detailing the results. */
printf ("Computed %d/%d %2.0f%% correct values\n", correct, count*count,
(float)(count*count)/correct*100.f);
err = clReleaseKernel (kernel);
err = freeDevice();
timeDirectImplementation( count, in_a, in_b, out);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zmq.h>
// Receive 0MQ string from socket and convert into C string
// Caller must free returned string. Returns NULL if the context
// is being terminated.
char * s_recv (void *socket)
{
char buffer [256];
int size = zmq_recv (socket, buffer, 255, 0);
if (size == -1)
return NULL;
if (size > 255)
size = 255;
buffer [size] = 0;
return strdup (buffer);
}
// Convert C string to 0MQ string and send to socket
int s_send (void *socket, char *string)
{
int size = zmq_send (socket, string, strlen (string), 0);
return size;
}
|
C
|
#include <linux/kernel.h>
#include <linux/module.h>
struct met_api_tbl {
int (*met_tag_start) (unsigned int class_id, const char *name);
int (*met_tag_end) (unsigned int class_id, const char *name);
int (*met_tag_oneshot) (unsigned int class_id, const char *name, unsigned int value);
int (*met_tag_dump) (unsigned int class_id, const char *name, void *data, unsigned int length);
int (*met_tag_disable) (unsigned int class_id);
int (*met_tag_enable) (unsigned int class_id);
int (*met_set_dump_buffer) (int size);
int (*met_save_dump_buffer) (const char *pathname);
int (*met_save_log) (const char *pathname);
};
struct met_api_tbl met_ext_api;
EXPORT_SYMBOL(met_ext_api);
int met_tag_start(unsigned int class_id, const char *name)
{
if (met_ext_api.met_tag_start) {
return met_ext_api.met_tag_start(class_id, name);
}
return 0;
}
int met_tag_end(unsigned int class_id, const char *name)
{
if (met_ext_api.met_tag_end) {
return met_ext_api.met_tag_end(class_id, name);
}
return 0;
}
int met_tag_oneshot(unsigned int class_id, const char *name, unsigned int value)
{
//trace_printk("8181888\n");
if (met_ext_api.met_tag_oneshot) {
return met_ext_api.met_tag_oneshot(class_id, name, value);
}
//else {
// trace_printk("7171777\n");
//}
return 0;
}
int met_tag_dump(unsigned int class_id, const char *name, void *data, unsigned int length)
{
if (met_ext_api.met_tag_dump) {
return met_ext_api.met_tag_dump(class_id, name, data, length);
}
return 0;
}
int met_tag_disable(unsigned int class_id)
{
if (met_ext_api.met_tag_disable) {
return met_ext_api.met_tag_disable(class_id);
}
return 0;
}
int met_tag_enable(unsigned int class_id)
{
if (met_ext_api.met_tag_enable) {
return met_ext_api.met_tag_enable(class_id);
}
return 0;
}
int met_set_dump_buffer(int size)
{
if (met_ext_api.met_set_dump_buffer) {
return met_ext_api.met_set_dump_buffer(size);
}
return 0;
}
int met_save_dump_buffer(const char *pathname)
{
if (met_ext_api.met_save_dump_buffer) {
return met_ext_api.met_save_dump_buffer(pathname);
}
return 0;
}
int met_save_log(const char *pathname)
{
if (met_ext_api.met_save_log) {
return met_ext_api.met_save_log(pathname);
}
return 0;
}
EXPORT_SYMBOL(met_tag_start);
EXPORT_SYMBOL(met_tag_end);
EXPORT_SYMBOL(met_tag_oneshot);
EXPORT_SYMBOL(met_tag_dump);
EXPORT_SYMBOL(met_tag_disable);
EXPORT_SYMBOL(met_tag_enable);
EXPORT_SYMBOL(met_set_dump_buffer);
EXPORT_SYMBOL(met_save_dump_buffer);
EXPORT_SYMBOL(met_save_log);
|
C
|
/*************************************************************************
> File Name: 0707打印月份.c
> Author:
> Mail:
> Created Time: 2017年05月20日 星期六 13时06分56秒
************************************************************************/
//打入月份号,输出该月的英文月名
//例如输入“3”,则输出“March”
#include<stdio.h>
int main()
{
char p[12][10] = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
int num = 0;
printf("请输入月份:");
scanf("%d", &num);
if(num <= 12 && num >= 1)
{
printf("对应的英文名称为:%s", *(p+num-1));
}
else
{
printf("请输入0~12之间的数");
}
return 0;
}
|
C
|
/**
*project:父子进程给共享内存区的一个计数器加1
*author:Xigang Wang
*email:wangxigang2014@gmail.com
*/
#include "unpipc.h"
#define SEM_NAME "mysem"
int main(int argc, char *argv[])
{
int fd, i, nloop, zero = 0;
int *ptr;
sem_t *mutex;
if(argc != 3)
err_quit("usage: incr2 <pathname> <#loops>");
fd = Open(argv[1], O_RDWR | O_CREAT, FILE_MODE);/*打开文件用于读写,不存在则创建它*/
Write(fd, &zero, sizeof(int));/*写一个值为0的值保存到文件*/
/*调用mmap把刚打开的文件映射到本进程的内存空间中*/
ptr = Mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
Close(fd);
mutex = Sem_open(SEM_NAME, O_CREAT | O_EXCL, FILE_MODE, 1);
Sem_unlink(SEM_NAME);
setbuf(stdout, NULL);/*把标准输出设置为非缓冲区*/
if(Fork() == 0){
for(i = 0; i < nloop; ++i){
Sem_wait(mutex);
printf ("child:%d\n",(*ptr)++);
Sem_post(mutex);
}
exit(0);
}
for(i = 0; i < nloop; ++i){
Sem_wait(mutex);
printf ("parent:%d\n",(*ptr)++);
Sem_post(mutex);
}
return 0;
}
|
C
|
#include "graphics.h"
#include <SDL2/SDL.h>
#include <stdbool.h>
int mainLoop();
int initSDL();
int main(int argc, char *argv[])
{
initSDL();
mainLoop();
return 0;
}
int initSDL()
{
int status = SDL_Init(SDL_INIT_VIDEO);
return status;
}
int mainLoop()
{
// set up render
RenderTarget target;
initRenderTarget(&target);
for (int i = 0; i < 720000; ++i) {
if (i % 50 < 25)
target.framebuffer[i] = 0x0000FFFF;
else
target.framebuffer[i] = 0xFFFF0000;
}
while (1) {
displayRenderTarget(&target);
}
}
|
C
|
#define M61_DISABLE 1
#include "m61.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <inttypes.h>
// Constant for heavy hitters size
#define HEAVY_HITTERS_MAX_SIZE 6
struct m61_metadata {
unsigned long long size; // number of bytes in allocation
unsigned long long active_code; // if equal to 1234 if allocation is not 'active'
char* ptr_addr; // address of the pointer to the allocation
const char* file; // file in which allocation was called
int line; // line in which allocation was called
struct m61_metadata* prev; // pointer to previous node in doubly linked list
struct m61_metadata* next; // pointer to next node in doubly linked list
int padding; // padding to keep struct with 8-bit alignment
};
// Footer to check for boundary write errors
typedef struct m61_footer {
unsigned long long buffer_one; // 8-byte buffer for overflow
unsigned long long buffer_two; // 8-byte buffer for overflow
} m61_footer;
// Global struct to keep track of statistics
struct m61_statistics global_stats;
// Head doubly linked list of struct m61_metadata
struct m61_metadata* metadata_head = NULL;
// Global Array of Heavy Hitters
struct m61_metadata heavy_hitters[HEAVY_HITTERS_MAX_SIZE];
// Size of the Heavy Hitters array
int heavy_hitters_size = 0;
// Sample size for Heavy Hitters
unsigned long long sample_size = 0;
void bs(struct m61_metadata* array, int n) {
for(int i = 0; i < n - 1; i++) {
for(int j = 0; j < n - i - 1; j++) {
if(array[j].size < array[j+1].size) {
struct m61_metadata temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
void* m61_malloc(size_t sz, const char* file, int line) {
(void) file, (void) line; // avoid uninitialized variable warnings
// Your code here.
// Prevent integer overflow: check to make sure sz not greater than 2^32-1
if (sz > SIZE_MAX - sizeof(struct m61_statistics) - sizeof(m61_footer)) {
global_stats.nfail++;
global_stats.fail_size += sz;
return NULL;
}
// Initialize a footer to monitor boundary overwrite errors
m61_footer footer = {1111, 2222};
// Initialize struct to hold metadata (i.e. allocation size)
struct m61_metadata metadata = {sz, 0, NULL, file, line, NULL, NULL, 0};
struct m61_metadata* ptr = NULL;
// Allocate pointer w/ extra space to accommodate metadata
ptr = malloc(sizeof(struct m61_metadata) + sz + sizeof(m61_footer));
// Track failed allocations
if (!ptr) {
global_stats.nfail++;
global_stats.fail_size += sz;
return ptr;
}
// Track other statistics
global_stats.ntotal++;
global_stats.nactive++;
global_stats.total_size += sz;
global_stats.active_size += sz;
char* heap_min = (char*) ptr;
char* heap_max = (char*) ptr + sz + sizeof(struct m61_metadata) + sizeof(m61_footer);
if (!global_stats.heap_min || global_stats.heap_min >= heap_min) {
global_stats.heap_min = heap_min;
}
if (!global_stats.heap_max || global_stats.heap_max <= heap_max) {
global_stats.heap_max = heap_max;
}
// Update metadata with relevant information
metadata.ptr_addr = (char*) (ptr + 1);
// Store metadata at beginning of allocated pointer
*ptr = metadata;
// Randomly sample 1/20 allocations to identify heavy hitters
if (drand48() < .05) {
int flag = 0;
sample_size += metadata.size;
// Check if file/line number in array
for (int i = 0; i < HEAVY_HITTERS_MAX_SIZE; i++) {
if (heavy_hitters[i].file == metadata.file &&
heavy_hitters[i].line == metadata.line) {
heavy_hitters[i].size += metadata.size;
flag = 1;
}
}
// If file/line not present and array not full
if (!flag && heavy_hitters_size < HEAVY_HITTERS_MAX_SIZE) {
heavy_hitters[heavy_hitters_size] = metadata;
heavy_hitters_size++;
}
// If metadata.size is bigger than last element in array
else {
if (!flag && heavy_hitters[HEAVY_HITTERS_MAX_SIZE - 1].size < metadata.size)
heavy_hitters[HEAVY_HITTERS_MAX_SIZE - 1] = metadata;
}
bs(heavy_hitters, heavy_hitters_size);
}
if (metadata_head) {
ptr->next = metadata_head;
metadata_head->prev = ptr;
}
metadata_head = ptr;
// Store footer at the end of allocated pointer
m61_footer* footer_ptr = (m61_footer*) ((char*) (ptr + 1) + sz);
*footer_ptr = footer;
// Return pointer to requested memory
return ptr + 1;
}
void m61_free(void *ptr, const char *file, int line) {
(void) file, (void) line; // avoid uninitialized variable warnings
// Your code here.
if (ptr) {
struct m61_metadata* new_ptr = (struct m61_metadata*) ptr - 1;
if ((char*) new_ptr >= global_stats.heap_min && (char*) new_ptr <= global_stats.heap_max) {
if (new_ptr->active_code != 1234) {
if (new_ptr->ptr_addr != (char*) ptr) {
printf("MEMORY BUG: %s:%d: invalid free of pointer %p, not allocated\n", file, line, ptr);
for (struct m61_metadata* metadata = metadata_head; metadata != NULL; metadata = metadata->next) {
if ((char*) ptr >= (char*) metadata && (char*) ptr <= (char*) (metadata + 1) + metadata->size + sizeof(m61_footer))
printf(" %s:%d: %p is %zu bytes inside a %llu byte region allocated here\n",
metadata->file, metadata->line, ptr, (char*) ptr - metadata->ptr_addr, metadata->size);
}
abort();
}
// Ensure there are not multiple frees even with copy allocations
if (new_ptr->next) {
if (new_ptr->next->prev != new_ptr) {
printf("MEMORY BUG: %s%d: invalid free of pointer %p\n", file, line, ptr);
abort();
}
}
else if (new_ptr->prev) {
if (new_ptr->prev->next != new_ptr) {
printf("MEMEORY BUG: %s%d: invalid free of pointer %p\n", file, line, ptr);
abort();
}
}
else if ((new_ptr->prev && new_ptr->next) &&
(new_ptr->prev->next != new_ptr || new_ptr->next->prev != new_ptr)) {
printf("MEMORY BUG: %s%d: invalid free of pointer %p\n", file, line, ptr);
abort();
}
m61_footer* footer_ptr = (m61_footer*) ((char*) ptr + new_ptr->size);
if (footer_ptr->buffer_one != 1111 || footer_ptr->buffer_two != 2222) {
printf("MEMORY BUG: %s:%d: detected wild write during free of pointer %p\n", file, line, ptr);
abort();
}
// Remove node from doubly linked list
if (new_ptr->prev)
new_ptr->prev->next = new_ptr->next;
else
metadata_head = new_ptr->next;
if (new_ptr->next)
new_ptr->next->prev = new_ptr->prev;
new_ptr->next = NULL;
new_ptr->prev = NULL;
// Keep track of statistics
global_stats.nactive--;
global_stats.active_size -= new_ptr->size;
// Set code to indicate inactive allocation
new_ptr->active_code = 1234;
free(new_ptr);
}
else {
printf("MEMORY BUG: %s:%d: invalid free of pointer %p\n", file, line, ptr);
abort();
}
}
else {
printf("MEMORY BUG: %s:%d: invalid free of pointer %p, not in heap\n", file, line, ptr);
abort();
}
}
}
void* m61_realloc(void* ptr, size_t sz, const char* file, int line) {
void* new_ptr = NULL;
if (sz)
new_ptr = m61_malloc(sz, file, line);
if (ptr && new_ptr) {
// Copy the data from `ptr` into `new_ptr`.
// To do that, we must figure out the size of allocation `ptr`.
// Your code here (to fix test012).
struct m61_metadata* metadata = (struct m61_metadata*) ptr - 1;
size_t old_sz = metadata->size;
if (old_sz <= sz)
memcpy(new_ptr, ptr, old_sz);
else
memcpy(new_ptr, ptr, sz);
}
m61_free(ptr, file, line);
return new_ptr;
}
void* m61_calloc(size_t nmemb, size_t sz, const char* file, int line) {
// Your code here (to fix test014).
if (nmemb * sz < sz || nmemb * sz < nmemb) {
global_stats.nfail++;
return NULL;
}
void* ptr = m61_malloc(nmemb * sz, file, line);
if (ptr)
memset(ptr, 0, nmemb * sz);
return ptr;
}
void m61_getstatistics(struct m61_statistics* stats) {
// Your code here.
// Set all statistics to zero
bzero(stats, sizeof(struct m61_statistics));
// Set all statistics from global statistics variable
*stats = global_stats;
}
void m61_printstatistics(void) {
struct m61_statistics stats;
m61_getstatistics(&stats);
printf("malloc count: active %10llu total %10llu fail %10llu\n",
stats.nactive, stats.ntotal, stats.nfail);
printf("malloc size: active %10llu total %10llu fail %10llu\n",
stats.active_size, stats.total_size, stats.fail_size);
}
void m61_printleakreport(void) {
for (struct m61_metadata* metadata = metadata_head; metadata != NULL; metadata = metadata->next) {
printf("LEAK CHECK: %s:%d: allocated object %p with size %llu\n", metadata->file, metadata->line, metadata->ptr_addr, metadata->size);
}
}
// Function to print out Heavy Hitters
void m61_printheavyhitters(void) {
for(int i = 0; i < HEAVY_HITTERS_MAX_SIZE; i++)
printf("HEAVY HITTER: %s:%d: %llu bytes (%%~%.2f)\n", heavy_hitters[i].file, heavy_hitters[i].line, heavy_hitters[i].size, 100.0 * heavy_hitters[i].size / sample_size);
}
|
C
|
#include <stdio.h>
int factorial(int n)
{
printf("Entra a la función factorial, n vale: %i\n", n);
if (n > 1)
{
printf("La función se llamara a si misma otra vez \n");
return n * factorial(n - 1);
}
else
{
printf("n es igual a 1, termina la recursividad\n");
return 1;
}
}
int main()
{
printf("Recursividad!\n");
int result = factorial(5);
printf("\nEl resultado es: %i\n", result);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* global_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: wperu <wperu@student.42lyon.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/10 13:15:41 by amonteli #+# #+# */
/* Updated: 2021/06/08 14:42:18 by wperu ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../../includes/minishell.h"
void free_array(char **array)
{
int i;
i = 0;
while (array[i])
{
free(array[i]);
array[i] = NULL;
}
free(array);
array = NULL;
}
void free_lst(void)
{
t_env *index;
t_env *tmp;
index = g_ms->env;
tmp = index;
while (index != NULL)
{
tmp = index;
index = index->next;
free(tmp->var);
tmp->var = NULL;
free(tmp);
tmp = NULL;
}
}
char **ft_lst_to_array(void)
{
char **array;
t_env *tmp;
int i;
array = NULL;
tmp = g_ms->env;
i = 0;
while (tmp)
{
i++;
tmp = tmp->next;
}
array = (char **)ft_calloc(sizeof(char *), i + 1);
if (!array)
exit(-1);
tmp = g_ms->env;
i = 0;
while (tmp)
{
array[i] = tmp->var;
tmp = tmp->next;
i++;
}
return (array);
}
/*
char *ft_strndup(char *str, int n)
{
char *tab;
int i;
//printf("str = %s indice = %i\n",str,n);
tab = (char *)malloc((ft_strlen(str) + 1) * sizeof(char));
if (!tab)
return (NULL);
i = 0;
while (i < n)
{
tab[i] = str[i];
i++;
}
tab[i] = '\0';
printf("tab = %s\n", tab);
return (tab);
}*/
|
C
|
//UDP Server
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<error.h>
#include<netinet/in.h>
#include<unistd.h>
#include<arpa/inet.h>
#define PORT 7899
#define MAX_DATA 1024
void showError(const char* msg){
printf("Error: %s\n",msg);
exit(0);
}
void reverse(char s[],int len){
int n = len;
for(int i=0;i<n/2;i++){
char temp = s[i];
s[i] = s[n-i-1];
s[n-i-1] = temp;
}
}
int main(){
struct sockaddr_in server,client;
int createSocket,newSocket,length,len;
unsigned int client_len;
char data[MAX_DATA];
createSocket = socket(AF_INET,SOCK_DGRAM,0);
if(createSocket<0) showError("socket opening failed...");
length = sizeof(server);
bzero(&server,length);
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = INADDR_ANY;
if(bind(createSocket,(struct sockaddr*)&server,length)<0) showError("socket binding failed...");
printf("Server is running...\n");
client_len = sizeof(struct sockaddr_in);
while(1){
do{
bzero(data,MAX_DATA);
len= recvfrom(createSocket,data,MAX_DATA,0,(struct sockaddr*)&client,&client_len);
if(strcmp(data,"quit")==0){
break;
}
else{
if(len){
printf("Client: %s\n",data);
reverse(data,len);
sendto(createSocket,data,len,0,(struct sockaddr*)&client,client_len);
data[len] = '\0';
printf("Server: %s\n",data);
}
}
}while(len);
}
return 0;
}
|
C
|
#include <stdio.h>
void playground() {
static int x = 0;
x = x + 1;
printf("x = %i\n",x);
}
int main() {
playground();
playground();
playground();
printf("x = %i\n",x);
}
|
C
|
/*
* Group 08
* Shubham Lather 2016A7PS0006P
* Devyash Parihar 2016A7PS0066P
* Rahul Khandelwal 2016A7PS0128P
* Aniruddha Karve 2016A7PS0042P
*/
# include "parserDef.h"
#include "utils.h"
# include <stdlib.h>
# include <stdio.h>
void nodeCount(parseTree root,int* ans)
{
if(!root)
return ;
*ans=*ans+root->numChild;
for(int i=0;i<root->numChild;i++)
nodeCount(&(root->children[i]),ans);
}
void nodeCountAST(parseTree root,int* ans)
{
if(!root)
return ;
*ans=*ans+root->numChildAST;
for(int i=0;i<root->numChildAST;i++)
nodeCountAST(&(root->children[i]),ans);
}
int useful(int tokenClass) {
switch(tokenClass) {
case TK_MAIN:
case TK_END:
case TK_SEM:
case TK_INPUT:
case TK_PARAMETER:
case TK_LIST:
case TK_SQL:
case TK_SQR:
case TK_OUTPUT:
case TK_COMMA:
case TK_COLON:
case TK_DOT:
case TK_CALL:
case TK_WITH:
case TK_PARAMETERS:
case TK_ASSIGNOP:
case TK_WHILE:
case TK_ENDWHILE:
case TK_IF:
case TK_ENDIF:
case TK_OP:
case TK_CL:
case TK_RETURN:
case TK_TYPE:
case TK_ENDRECORD:
case eps:
return 0;
break;
default:
return 1;
}
}
void copy(parseTree dst,parseTree src)
{
dst->numChild = src->numChild;
dst->numChildAST = src->numChildAST;
dst->ruleNo = src->ruleNo;
dst->terminal = src->terminal;
dst->nonTerminal = src->nonTerminal;
dst->children = NULL;
dst->tp = NULL;
}
void createASTUtils(parseTree curr, parseTree par)
{
if(curr==NULL)
return ;
if(curr -> numChildAST == 0)
{
if(!useful(curr->terminal->tokenType))
par->numChildAST--;
return;
}
if(curr->numChildAST == 1 && curr->children[0].numChildAST == 0)
{
if(useful(curr->children[0].terminal->tokenType))
{
copy(curr,&(curr->children[0]));
return;
}
}
int count = curr->numChild;
for(int i = 0; i < count; i++)
createASTUtils(&(curr->children[i]),curr);
if(curr->numChildAST == 0)
par->numChildAST--;
if(curr->numChildAST == 1 && curr->children[0].numChildAST == 0)
{
for(int i = 0; i < curr->numChild ;i++)
{
if(curr->children[i].numChildAST==0 && curr->children[i].nonTerminal==-1)
{
if(useful(curr->children[i].terminal->tokenType))
copy(curr,&(curr->children[i]));
}
}
}
}
void buildAST(parseTree ast,parseTree root)
{
if(!root)
return;
ast->children = malloc((root->numChildAST)*sizeof(parsetree));
int m=0;
for(int i = 0;i < root->numChild;i++)
{
if(root->children[i].numChildAST!=0)
{
copy(&(ast->children[m]),&(root->children[i]));
buildAST(&(ast->children[m]),&(root->children[i]));
m++;
}
else
{
if(root->children[i].nonTerminal==-1 && useful(root->children[i].terminal->tokenType))
{
copy(&(ast->children[m]),&(root->children[i]));
m++;
}
}
}
}
parseTree createAST(parseTree root)
{
createASTUtils(root,NULL);
parseTree ast = malloc(sizeof(parsetree));
copy(ast,root);
buildAST(ast,root);
return ast;
}
void printAST(parseTree root)
{
parseTree current;
int class;
for(int i=0;i<root->numChildAST;i++)
{
current=&(root->children[i]);
if(!current)
printf("NULL\n");
if(current->numChildAST==0 && current->terminal->tokenType==eps)
continue;
if(current->numChildAST>0)
{
printf("-------\t\t");
printf("-------\t\t");
printf("-------\t\t");
printf("-------\t\t");
}
else{
printf("%s\t\t",current->terminal->lexeme);
printf("%lld\t\t",current->terminal->lineNum);
printf("%s\t\t",tokenRepr(current->terminal->tokenType));
if(current->terminal->tokenType==TK_NUM || current->terminal->tokenType==TK_RNUM)
printf("%s\t\t",current->terminal->lexeme);
else printf("-------\t\t");
}
printf("%s\t\t",idRepr(root->nonTerminal));
if(current->numChildAST==0)
{
printf("YES\t\t");
printf("-------\t\t");
}
else{
printf("NO\t\t");
printf("%s\t\t",idRepr(current->nonTerminal));
}
printf("\n");
printAST(current);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utils.h"
#include "parser.h"
#define strdup _strdup
static word_t* word_t_copy(word_t* word)
{
word_t* new_word;
if (word == NULL)
return NULL;
new_word = calloc(sizeof(word_t), 1);
if (word->string)
new_word->string = strdup(word->string);
new_word->expand = word->expand;
new_word->next_part = word_t_copy(word->next_part);
new_word->next_word = word_t_copy(word->next_word);
return new_word;
}
static simple_command_t* scmd_deep_copy(simple_command_t* scmd)
{
simple_command_t* new_scmd = calloc(sizeof(simple_command_t), 1);
new_scmd->verb = word_t_copy(scmd->verb);
new_scmd->params = word_t_copy(scmd->params);
new_scmd->in = word_t_copy(scmd->in);
new_scmd->out = word_t_copy(scmd->out);
new_scmd->err = word_t_copy(scmd->err);
new_scmd->io_flags = scmd->io_flags;
return new_scmd;
}
command_t* command_deep_copy(command_t* root)
{
command_t* new_root = calloc(sizeof(command_t), 1);
new_root->op = root->op;
if (root->op == OP_NONE)
new_root->scmd = scmd_deep_copy(root->scmd);
else {
new_root->cmd1 = command_deep_copy(root->cmd1);
new_root->cmd2 = command_deep_copy(root->cmd2);
}
return new_root;
}
static void free_word_t(word_t* word)
{
if (word == NULL)
return;
if (word->string)
free((char*)word->string);
if (word->next_part)
free_word_t(word->next_part);
if (word->next_word)
free_word_t(word->next_word);
free(word);
}
static void free_scmd(simple_command_t* scmd)
{
free_word_t(scmd->verb);
free_word_t(scmd->params);
free_word_t(scmd->in);
free_word_t(scmd->out);
free_word_t(scmd->err);
free(scmd);
}
void command_deep_free(command_t* root)
{
if (root->op == OP_NONE)
free_scmd(root->scmd);
else {
command_deep_free(root->cmd1);
command_deep_free(root->cmd2);
}
free(root);
}
|
C
|
#include "game.h"
bool gameTurn(User *start, User *other, int boardSize) {
system("clear");
char ch_x, ch_y;
int x, y = 0;
bool shotCan = false;
void *structureOther = USERSTRUCTURE(other);
bool gamePlayed = false;
printUsers(start, other, boardSize);
printBothBoard(start, other, boardSize);
printf("%s choose point to hit a ship of %s\n", USERNAME(start), USERNAME(other));
printf("x: ");
scanf(" %c", &ch_x);
printf("\ny: ");
scanf(" %c",&ch_y);
x = choiceChar(ch_x);
y = choiceChar(ch_y);
//x = randomShoot(boardSize);
//y = randomShoot(boardSize);
shotCan = canShot(other,x,y,boardSize);
if(shotCan) {
gamePlayed = shotPlayer(other, x,y);
modifyValuesStruct(other,x,y);
insertLittleCell(start,x,y);
if(gamePlayed) modifyShotsStruct(other,x,y,true);
else modifyShotsStruct(other,x,y,false);
}
else {
while(shotCan == false) {
printf("Try Again\n");
printf("%s choose point to hit a ship of %s\n", USERNAME(start), USERNAME(other));
printf("x: ");
scanf(" %c", &ch_x);
printf("\ny: ");
scanf(" %c",&ch_y);
x = choiceChar(ch_x);
y = choiceChar(ch_y);
//x = randomShoot(boardSize);
//y = randomShoot(boardSize);
if(shotCan) {
gamePlayed = shotPlayer(other, x,y);
modifyValuesStruct(other,x,y);
insertLittleCell(start,x,y);
}
else shotCan = canShot(start,x, y, boardSize);
}
}
if(sinkBoatStructure(structureOther, boardSize)) {
system("clear");
printUsers(start, other, boardSize);
printBothBoard(start, other, boardSize);
printf("You sank the ship!\n");
} else {
system("clear");
printUsers(start, other, boardSize);
printBothBoard(start, other,boardSize);
//printBoard(start, boardSize);
//printBoard(other, boardSize);
Point *p = newPoint(x,y);
void *aux = searchPoint(structureOther,p);
if(aux == NULL) printf("pois\n");
else {
Cell *cell = (Cell*)aux;
if(CELLVALUE(cell) == '*')
printf("You hit a ship!\n");
else if(CELLVALUE(cell) == '+')
printf("You hit a empty cell!\n");
}
}
sleep(2);
return gamePlayed;
}
// Play again after hit a ship
bool gamePlayed(User *start, User *other, int boardSize) {
bool gameTurnVar = gameTurn(start,other, boardSize);
bool broke = false;
while(gameTurnVar) {
gameTurnVar = gameTurn(start,other, boardSize);
if(allShipsSink(start) || allShipsSink(other)) {
broke = true;
break;
}
}
return broke;
}
//Game development to the condition allShipsSink(user) == true
void game(User *start, User *other, int boardSize) {
bool playAgainVar = false;
while(1) {
playAgainVar = gamePlayed(start, other, boardSize);
if(playAgainVar) {
printf("|| CONGRULATIONS! ||\n");
printf("The player %s win the game! \n", USERNAME(start));
break;
}
playAgainVar= gamePlayed(other,start, boardSize);
if(playAgainVar) {
printf("|| CONGRULATIONS! ||\n");
printf("The player %s win the game! \n", USERNAME(other));
break;
}
}
// Free all allocated memory used on the game
//freeUser(start);
//freeUser(other);
}
bool allShipsSink(User *usr) {
printf("Entrie no alShipsSink\n");
ListNode *node = usr -> shipList -> head;
int countShips = USERLIST(usr) -> size;
bool sink = false;
while(node != NULL) {
sink = sinkBoat((SHIP*)node -> data);
if(sink) countShips--;
node = node -> next;
}
if(countShips==0)
return true;
else
return false;
}
// random number between 0 and matrix size to hit a cell
int randomShoot(int matrixSize) {
int x = rand() % matrixSize;
return x;
}
bool canShot(User *usr, int x, int y, int boardSize) {
printf("x: %d y: %d\n ",x,y);
bool shot = true;
void *structure = USERSTRUCTURE(usr);
Point *p = newPoint(x,y);
if(y >= boardSize || x >= boardSize) {
shot = false;
return shot;
}
void *aux = searchPoint(structure,p);
if(aux == NULL) {
aux = initCell();
insertShip(structure, aux,p);
shot = true;
}
else {
Cell *cell = (Cell*)aux;
if(CELLVALUE(cell) == 'x' || CELLVALUE(cell) == '.') shot = true;
else if(CELLVALUE(cell) == '*' || CELLVALUE(cell) == '#') shot = false;
}
return shot;
}
bool shotPlayer(User *user, int x, int y) {
bool shot = false;
printf("x: %d y: %d\n",x,y);
Point *p = newPoint(x,y);
void *structure = USERSTRUCTURE(user);
void *aux = searchPoint(structure,p);
if(aux != NULL) {
Cell *cell = (Cell*)aux;
shot = hittedPiece(cell);
printf("SHOT: %d\n", shot);
}
else printf("NULA\n");
return shot;
}
bool sinkBoatStructure(void *structure, int boardSize) {
for(int i = 0; i < boardSize; i++) {
for(int j = 0; j < boardSize; j++) {
Point *p = newPoint(i,j);
void *aux = searchPoint(structure,p);
if(aux != NULL) {
Cell *cell = (Cell*)aux;
if(CELLVALUE(cell) == '*') {
SHIP *sh = SHIPCELL(cell);
if(sinkBoat(sh)==true) {
printf("Sink a boat with coordenates (%d,%d) \n", j,i);
return true;
}
}
}
free(p);
}
}
return false;
}
void modifyValuesStruct(User *user, int x, int y) {
printf("user : %s\n", user -> username);
void *structure = USERSTRUCTURE(user);
Point *p = newPoint(x,y);
void *aux = searchPoint(structure,p);
if(aux != NULL) {
Cell *cell = (Cell*)aux;
modifyValues(cell,x,y);
}
}
void modifyShotsStruct(User *user, int x, int y, bool b) {
void *structure = USERSTRUCTURE(user);
Point *p = newPoint(x,y);
void *aux = searchPoint(structure,p);
if(aux != NULL) {
modifyShot((Cell*)aux,b);
}
}
bool canInsert(User *user, SHIP *ship, int x, int y, int boardSize) {
bool insert = true;
int broke = 0;
//printf("user %s", user -> username);
void *structure = user -> dataStructs;
//printBoard(user, boardSize);
BitMap *bp = SHIPBITMAP(ship);
for(int i = 0; i < sizeBitMap; i++) {
for(int j = 0; j < sizeBitMap; j++) {
unsigned char data = CELLBP(bp,i,j);
if(data == '1') {
if((j+y) >= boardSize|| (i+x) >= boardSize) {
insert = false;
broke = 1;
break;
}
Point *p = newPoint(x+i,y+j);
void *aux = searchPoint(structure,p);
if(aux != NULL) {
insert = false;
broke = 1;
break;
}
else if(aux == NULL) {
insert = true;
}
free(p);
}
}
if(broke) {
break;
}
}
return insert;
}
bool insertShipInStructure(User *user, SHIP *ship, int x, int y, int boardSize) {
bool insert = canInsert(user,ship,x,y, boardSize);
printf("size: %d\n", boardSize);
printf("insert %d \n", insert);
//void *structure = getStructure(user);
BitMap *bp = SHIPBITMAP(ship);
printBitMap(bp);
void *structure = USERSTRUCTURE(user);
if(insert) {
for(int i = 0; i < sizeBitMap; i++) {
for(int j = 0; j < sizeBitMap; j++) {
unsigned char data = CELLBP(bp,i,j);
if (data == '1') {
SETBPX(bp,x);
SETBPY(bp,y);
Point *p = newPoint(BPX(bp) + i, BPY(bp) + j);
printf("ponto: x -> %d e y -> %d\n", p -> x, p -> y);
void *aux = searchPoint(structure,p);
if(aux == NULL) {
aux = initCell();
insertedShipCell(aux,ship);
insertShip(user -> dataStructs,aux,p);
}
free(p);
}
}
}
}
return insert;
}
void insertLittleCell(User *user, int x, int y) {
Point *p = newPoint(x,y);
void *aux = searchPoint(user -> dataStructs, p);
if(aux == NULL) {
aux = initCell();
insertShip(user -> dataStructs, aux, p);
}
free(p);
}
|
C
|
#include "cislo.h"
Cislo* VytvorCislo(void)
{
Cislo* pCislo = NULL;
pCislo = (Cislo*) malloc(sizeof(Cislo));
(*pCislo).mantisa = VytvorGumu(10);
VlozDoGumy((&(*pCislo).mantisa), 0, '0');
(*pCislo).exponent = VytvorGumu(10);
VlozDoGumy(&((*pCislo).exponent), 0, '0');
(*pCislo).znamenkoMan = '+';
(*pCislo).znamenkoExp = '+';
return pCislo;
};
Cislo* VratCislo(FILE* soubor)
{
Cislo* pCislo = VytvorCislo();
Cislo** ppCislo = &pCislo;
int stav = 0;
int index = 0;
char znak = '0';
char kam = '0';
if (soubor == NULL) //kontrola, ze soubor neni null
{
return NULL;
};
//printf("\%s", whiteSpace);
znak = fgetc(soubor);
while ((stav != 66) || (stav != 99)) // kontrola radneho konce cisla nebo chyby v nacteni cisla
{
if ((znak == '\n') || (feof(soubor) == 16))
{
switch (stav)
{
case 0: SmazCislo(ppCislo); return NULL;
case 1: SmazCislo(ppCislo); return NULL;
case 2: return pCislo;
case 3: SmazCislo(ppCislo); return NULL;
case 4: return pCislo;
case 5: SmazCislo(ppCislo); return NULL;
default: return NULL;
};
};
stav = Automat(stav,index,znak);
if ((stav == 1) && (strchr("+-",znak)))
// znamenko zapisuju jen, kdyz prijde + nebo -, stav 1 se muze vratit, i kdyz nacitam za znamenkem same nuly
{
kam = 'M';
ZapisZnamenko(ppCislo,kam,znak);
};
if ((stav == 2) || (stav == 5))
// vratila se cislice, kterou chci zapsat do mantisy
{
VlozDoGumy(&((*pCislo).mantisa),index,znak);
index = index + 1;
};
if (stav == 5)
// vratila se cislice v desetinne casti, tak musim zvysit zaporny exponent vysledneho cisla
{
Inkrement(&((*pCislo).exponent));
};
if (stav == 99) //CHYBA
{
SmazCislo(ppCislo);
return NULL;
};
if (stav == 66) //radny konec nacteni cisla
{
return pCislo;
};
znak = fgetc(soubor);
};
return pCislo;
};
void SmazCislo(Cislo** ppCislo)
{
if (ppCislo == NULL)
{
return;
};
SmazGumu(&((**ppCislo).mantisa));
SmazGumu(&((**ppCislo).exponent));
free(*ppCislo);
return;
};
void ZapisZnamenko(Cislo** ppCislo, char kam, char znak)
{
if (ppCislo == NULL)
{
*ppCislo = VytvorCislo();
};
if (kam == 'M')
{
(**ppCislo).znamenkoMan = znak;
};
if (kam == 'E')
{
(**ppCislo).znamenkoExp = znak;
};
return;
};
int Automat(int stav, int index, char znak)
{
switch (stav)
{
case 0: //Zacatek
if ((znak >= '1') && (znak <= '9'))
{
stav = 2;
return stav;
};
switch (znak)
{
case ',':
stav = 3;
return stav;
case '+':
stav = 1;
return stav;
case '-':
stav = 1;
return stav;
default:
return stav;
};
case 1: //Znamenko
if ((znak >= '1') && (znak <= '9'))
{
stav = 2;
return stav;
};
switch (znak)
{
case ',':
stav = 3;
return stav;
case '-':
stav = 1;
return stav;
case ' ':
stav = 66;
//KONEC
return stav;
default:
stav = 99;
//CHYBA
return stav;
};
case 2: //Cislice
if ((znak >= '0') && (znak <= '9'))
{
stav = 2;
return stav;
};
switch (znak)
{
case ',':
stav = 4;
return stav;
case ' ':
stav = 66; //KONEC
return stav;
default:
stav = 99; //CHYBA
return stav;
};
case 3: //Oddelovac na zacatku
if ((znak >= '1') && (znak <= '9'))
{
stav = 5;
return stav;
};
switch (znak)
{
case '0':
return stav;
case ' ':
stav = 66; //KONEC
return stav;
default:
stav = 99; //CHYBA
return stav;
};
case 4: // Oddelovac po nenulove cele casti
if ((znak >= '0') && (znak <= '9'))
{
stav = 5;
return stav;
};
switch (znak)
{
case ' ':
stav = 66; //KONEC
return stav;
default:
stav = 99; //CHYBA
return stav;
};
case 5: // Desetinna cislice
if ((znak >= '0') && (znak <= '9'))
{
stav = 5;
return stav;
};
switch (znak)
{
case ' ':
stav = 66; //KONEC
return stav;
default:
stav = 99; //CHYBA
return stav;
};
default:
return stav; // CHYBA procesu, nebyl rozpoznan stav
};
};
Cislo* OptimalizujCislo(Cislo** ppCislo)
{
// odstrani koncove nuly, pokud mantisa nekonci cislici 1-9
// pri odstranovani nepotrebnych nul upravuje exponent cisla
return *ppCislo;
};
void VypisCislo(Cislo** ppVysledek)
{
printf("%c", (**ppVysledek).znamenkoMan);
//podle exponentu celou cast cisla
//desetinna carka
//desetinna cast cisla
VypisGumu((**ppVysledek).mantisa);
return;
};
|
C
|
#include "stdio.h"
#include "stdlib.h"
#include "stdbool.h"
#include "windows.h"
void menu();
void print();
void ArrayInput();
void randArray();
void BubbleSort();
void InsertionSort();
void MergeSort();
void Merge();
void QuickSort();
void ShakerSort();
void main()
{
int t = 1, n = 0;
bool wasInput = false;
printf("Start\n");
int* A = NULL;
LARGE_INTEGER start, finish, freq;
double time;
QueryPerformanceFrequency(&freq);
while (t != 0)
{
menu();
scanf_s("%i", &t);
switch (t)
{
case 1:
{
printf("Enter the value of the array\n");
scanf_s("%d", &n);
A = (int*)malloc(n * sizeof(int));
if (NULL == A)
{
printf("OS didn't gave memory. Exit..");
exit(1);
}
else printf("Array successfully created!");
ArrayInput(A, n);
wasInput = true;
break;
}
case 2: {
printf("Enter the value of the array\n");
scanf_s("%d", &n);
A = (int*)malloc(n * sizeof(int));
if (NULL == A)
{
printf("OS didn't gave memory. Exit..");
exit(1);
}
else printf("Array successfully created!");
randArray(A, n);
wasInput = true;
break;
}
case 3: {
if (wasInput)
print(A, n);
else printf("Please, Create an array!\n");
break;
}
case 4: {
if (wasInput)
{
QueryPerformanceCounter(&start);
BubbleSort(A, n);
QueryPerformanceCounter(&finish);
time = (double)(finish.QuadPart - start.QuadPart) / (double)freq.QuadPart;
printf("time %lf\n", time);
}
else printf("Create an array!");
break;
}
case 5: {
if (wasInput)
{
int nc = 0, nsw = 0;
QueryPerformanceCounter(&start);
InsertionSort(A, n, &nc, &nsw);
QueryPerformanceCounter(&finish);
time = (double)(finish.QuadPart - start.QuadPart) / (double)freq.QuadPart;
printf("time %lf\n", time);
printf("Swaps: %d Comparisons: %d\n", nsw, nc);
}
else printf("Create an array!");
break;
}
case 6: {
if (wasInput)
{
int nc = 0, nsw = 0;
QueryPerformanceCounter(&start);
MergeSort(A, 0, n, &nc, &nsw);
QueryPerformanceCounter(&finish);
time = (double)(finish.QuadPart - start.QuadPart) / (double)freq.QuadPart;
printf("time %lf\n", time);
printf("Swaps: %d Comparisons: %d\n", nsw, nc);
}
else printf("Create an array!");
break;
}
case 7: {
if (wasInput)
{
QueryPerformanceCounter(&start);
QuickSort(A, 0, n - 1);
QueryPerformanceCounter(&finish);
time = (double)(finish.QuadPart - start.QuadPart) / (double)freq.QuadPart;
printf("time %lf\n", time);
}
else printf("Create an array!");
break;
}
case 8: {
if (wasInput)
{
int nc = 0, nsw = 0;
QueryPerformanceCounter(&start);
ShakerSort(A, 0, n-1, &nc, &nsw);
QueryPerformanceCounter(&finish);
time = (double)(finish.QuadPart - start.QuadPart) / (double)freq.QuadPart;
printf("time %lf\n", time);
printf("Swaps: %d Comparisons: %d\n", nsw, nc);
}
else printf("Create an array!");
break;
}
}
}
free(A);
}
void menu()
{
printf("\nMENU:\n");
printf("1. Create and fill the array yourself\n");
printf("2. Create and fill the array with random numbers\n");
printf("3. Output an array\n");
printf("4. BubbleSort\n");
printf("5. InsertionSort\n");
printf("6. MergeSort\n");
printf("7. QuickSort\n");
printf("8. ShakerSort\n");
printf("0. Exit\n");
}
void print(int A[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%i ", A[i]);
printf("\n");
}
void ArrayInput(int A[], int n)
{
printf("Start typing a sequence of numbers\n");
for (int i = 0; i < n; i++)
{
scanf_s("%d", &A[i]);
}
}
void randArray(int A[], int n)
{
int i;
int a, b;
printf("Enter the minimum and maximum number\n");
scanf_s("%d %d", &a, &b);
for (i = 0; i < n; i++)
{
A[i] = rand() % (b - a) + a;
}
}
void BubbleSort(int A[], int n)
{
int i, j;
int tmp;
for (i = 0; i < n; i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (A[j] > A[j + 1])
{
tmp = A[j];
A[j] = A[j + 1];
A[j + 1] = tmp;
}
}
}
}
void InsertionSort(int A[], int n, int* nc, int* nsw)
{
int i, t, j;
for (i = 0; i < n; i++)
{
t = A[i];
j = i - 1;
while ((j >= 0) && (A[j] > t))
{
A[j + 1] = A[j];
j--;
(*nsw)++;
}
A[j + 1] = t;
}
}
void MergeSort(int A[], int left, int right, int* nc, int* nsw)
{
int mid = (right + left) / 2;
(*nc)++;
if ((right - left) < 2)
{
return;
}
else
MergeSort(A, left, mid, &(*nc), &(*nsw));
MergeSort(A, mid, right, &(*nc), &(*nsw));
Merge(A, left, mid, right, &(*nc), &(*nsw));
}
void Merge(int A[], int left, int mid, int right, int* nc, int* nsw)
{
int it1 = 0;
int it2 = 0;
int* TMP = (int*)malloc((right - left) * sizeof(int));
while ((left + it1 < mid) && (mid + it2 < right))
{
if (A[left + it1] < A[mid + it2])
{
TMP[it1 + it2] = A[left + it1];
it1++;
(*nsw)++;
}
else
{
TMP[it1 + it2] = A[mid + it2];
it2++;
(*nsw)++;
}
}
while (left + it1 < mid)
{
TMP[it1 + it2] = A[left + it1];
it1++;
(*nsw)++;
}
while (mid + it2 < right)
{
TMP[it1 + it2] = A[mid + it2];
it2++;
(*nsw)++;
}
for (int i = 0; i < it1 + it2; i++)
A[left + i] = TMP[i];
(*nsw)++;
free(TMP);
}
void QuickSort(int A[], int left, int right)
{
int l = left, r = right, tmp = 0;
int opora = A[(l + r) / 2];
while (l <= r)
{
while (A[l] < opora)
{
l++;
}
while (A[r] > opora) {
r--;
}
if (l <= r)
{
tmp = A[l];
A[l] = A[r];
A[r] = tmp;
l++;
r--;
}
}
if (left < r)
QuickSort(A, left, r);
if (right > l)
QuickSort(A, l, right);
}
void ShakerSort(int A[], int left, int right, int* nc, int* nsw)
{
int tmp = 0;
while (left < right)
{
for (int i = left; i < right; i++)
{
if (A[i] > A[i + 1])
{
tmp = A[i];
A[i] = A[i + 1];
A[i + 1] = tmp;
(*nsw)++;
}
(*nc)++;
}
right--;
for (int j = right; j > left; j--)
{
if (A[j] < A[j - 1])
{
tmp = A[j];
A[j] = A[j - 1];
A[j - 1] = tmp;
(*nsw)++;
}
(*nc)++;
}
left++;
}
}
|
C
|
#include<stdio.h>
#include<windows.h>
void gotoxy(int x, int y)
{
COORD Cur;
Cur.X = x;
Cur.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Cur);
}
char answer;
void loby() //κ
{
int temp;
gotoxy(30,17);
printf("---------------------------------------------------");
gotoxy(30,7);
printf("---------------------------------------------------");
gotoxy(50,9);
printf(" ϱ ");
gotoxy(48,14);
printf(" : s : b");
for(temp=1;temp<10;temp++)
{
gotoxy(30,7+temp);
printf("|");
gotoxy(80,7+temp);
printf("|");
}
gotoxy(56,17);
do{
answer=getch();
}while(answer!='s'&&answer!='b'&&answer!='S'&&answer!='B');
system("cls");
}
void map() //
{
int x,y;
for(x=5;x<20;x++)
{
for(y=5;y<28;y++)
{
if((x==5)||(x==19)||(y==5)||(y==27))
{
gotoxy((x*2),y);
printf("");
}
Sleep(1);
}
}
Sleep(100);
gotoxy(22,3);
printf("STAGE 1");
gotoxy(25,28);
}
main()
{
int speed;
int score;
int stage;
int player_input, player_x=22,player_y=26;
loby();
for(stage=1;;stage++)
{
map();
while(1)
{
if(kbhit())
{
player_input=getch();
if(player_input==224)
{
player_input=getch();
switch(player_input)
{
case 75:
if(player_x!=12)
{
gotoxy(player_x,player_y);
printf(" ");
gotoxy(player_x=player_x-2,player_y);
printf("");
}
break;
case 77:
if(player_x!=36)
{
gotoxy(player_x,player_y);
printf(" ");
gotoxy(player_x=player_x+2,player_y);
printf("");
}
break;
}
}
}
}
}
}
|
C
|
#include <stdio.h>
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 1)
{
printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}
int main() {
int num;
char speg;
char fpeg;
printf("Enter the number of disks : ");
scanf("%d", &num);
printf("Enter the starting peg (A, B, or C): ");
scanf("%c", &speg);
printf("Enter the final peg (A, B, or C): ");
scanf("%c", &fpeg);
printf("The sequence of moves involved in the Tower of Hanoi are :\n");
if ((speg =='A' || speg =='C') && (fpeg =='A' || fpeg =='C')){
towers(num, speg, fpeg, 'B');
}
else if ((speg =='A' || speg =='B') && (fpeg =='A' || fpeg =='B')){
towers(num, speg, fpeg, 'C');
}
else{
towers(num, speg, fpeg, 'A');
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "tme3.h"
#define STACK_INIT_COUNT 32
#define TRUE 1
#define FALSE 0
#ifdef DEBUG
#define debug(i) fprintf(stderr, "%s\n", i);
#else
#define debug(i) ;
#endif
stack * make_stack(){
debug("make stack");
stack * res = malloc(sizeof(stack));
res->nodearr = malloc(STACK_INIT_COUNT * sizeof(node *));
res->nodecount = 0;
res->maxcount = STACK_INIT_COUNT;
}
void push_leaf(stack * st, node * leaf){
debug("push leaf");
if (st->nodecount >= st->maxcount) {
node ** newarr = malloc(st->maxcount * 2 * sizeof(node *));
for (int i=0; i<st->maxcount; i++)
newarr[i] = st->nodearr[i];
free(st->nodearr);
st->nodearr = newarr;
st->maxcount *= 2;
}
st->nodearr[st->nodecount++] = leaf;
}
node * get_leaf(stack * st, int i) {
debug("get leaf");
return st->nodearr[i];
}
void destroy_stack(stack * st){
debug("destroy stack");
free(st->nodearr);
free(st);
}
node * make_leaf() {
debug("make leaf");
node * res = malloc(sizeof(node));
res->left = NULL;
res->right = NULL;
res->isLeaf = TRUE;
res->value = -1;
return res;
}
node * make_tree(int size) {
debug("make tree");
srand(time(NULL));
stack * stack = make_stack();
node ** leaves = malloc(size * sizeof(node *));
node * root = make_leaf();
push_leaf(stack, root);
for (int i=1; i<size+1; i++) {
int random = rand() % (stack->nodecount); // TODO better random gen
node * leaf = get_leaf(stack, random);
leaf->isLeaf = FALSE;
node * l = make_leaf();
node * r = make_leaf();
leaf->left = l;
leaf->right = r;
push_leaf(stack, l);
push_leaf(stack, r);
}
destroy_stack(stack);
return root;
}
void destroy_tree(node * tree) {
debug("destroy tree");
if (!tree->isLeaf) {
destroy_tree(tree->left);
destroy_tree(tree->right);
}
free(tree);
}
void tag_tree_rec(node * tree, int * value) {
debug("tag tree rec");
if (!tree->isLeaf) {
tag_tree_rec(tree->left, value);
tree->value = *value++;
tag_tree_rec(tree->right, value);
}
}
void tag_tree(node * tree) {
debug("tag tree");
int i = 0;
tag_tree_rec(tree, &i);
}
void ald_rec(node * tree, float * count, float * acc, float depth) {
debug("ald rec");
if (tree->isLeaf) {
*count++;
*acc += depth;
}
else {
ald_rec(tree->left, count, acc, depth + 1);
ald_rec(tree->right, count, acc, depth + 1);
}
}
float ald (node * tree) {
debug("ald");
float count = 0;
float acc = 0;
ald_rec(tree, &count, &acc, 0);
return acc / count;
}
int main() {
float depth = 0;
for (int i=0; i<10000; i++) {
node * tree = make_tree(10000);
tag_tree(tree);
depth += ald(tree);
destroy_tree(tree);
fprintf(stdout, "%d / %d\n", i, 10000);
}
fprintf(stdout, "Average: %d\n", depth / 10000);
}
|
C
|
/* 51.
Scrivere un programma che carichi una matrice bidimensionale di caratteri e successivamente ricerchi al suo
interno un valore passato in ingresso dall’utente. Il programma restituisce quindi il numero di linea e di colonna relativo
all’elemento cercato se questo è presente nella matrice, il messaggio Elemento non presente altrimenti.
*/
#include <stdio.h>
#define LEN 1000
int main (int argc, char const *argv[])
{
char mat[LEN][LEN]; /* matrice */
char c; /* carattere da ricercare */
int cols; /* colonne di mat */
int rows; /* righe di mat */
int flag; /* flag */
int i, j; /* contatori */
/* assegnazione di cols */
printf ("Inserire il numero di colonne > ");
scanf ("%d", &cols);
/* assegnazione di rows */
printf ("Inserire il numero di righe > ");
scanf ("%d", &rows);
getchar();
/* costruzione di mat */
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
printf ("Colonna [%d] riga [%d] > ", j, i);
scanf ("%c", &mat[i][j]);
getchar();
}
printf ("\n");
}
/* assegnazione di c */
printf ("Carattere da cercare > ");
scanf ("%c", &c);
/* esito */
for (flag = i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
if (c == mat[i][j])
{
flag = 1;
printf ("Lettera \"%c\" a coordinate >> (%d; %d);\n", c, j, i);
}
if (!flag)
printf ("Elemento non presente\n");
printf ("\n");
return 0;
}
//
|
C
|
int main()
{
int i,j,k,m,n,sum=0;
int a[20][20],b[20];
for(i=0;;i++)
{
for(j=0;;j++)
{
scanf("%d",&a[i][j]);
if(a[i][j]==-1)
{
m=i;
break;
}
if(a[i][j]==0)
{
b[i]=j;
break;
}
}
if(a[i][j]==-1)
{
break;
}
}
for(i=0;i<m;i++)
{
sum=0;
for(j=0;j<b[i];j++)
{
for(k=0;k<=j;k++)
{
if(a[i][j]%a[i][k]==0&&a[i][j]/a[i][k]==2)
sum++;
else if(a[i][k]%a[i][j]==0&&a[i][k]/a[i][j]==2)
sum++;
}
}
printf("%d\n",sum);
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "Node.h"
#include "List.h"
int main()
{
Node *head = initializeList();
int answer;
int number;
do {
printf("1) Add back to list\n");
printf("2) Change min and max elements\n");
printf("3) Remove element with specified value\n");
printf("4) Sort\n");
printf("5) Print\n");
printf("6) Print reverse\n");
printf("7) Exit\n");
printf("Answer: ");
scanf("%i", &answer);
switch (answer) {
case 1:
printf("Number: ");
scanf("%d", &number);
pushBackToList(head, number);
printList(head);
break;
case 2:
changeMinMax(head);
printList(head);
break;
case 3:
printf("Value: ");
scanf("%d", &number);
removeFromList(head, number);
printList(head);
break;
case 4:
sort(head);
printList(head);
break;
case 5:
printList(head);
break;
case 6:
printListReverse(head);
break;
}
} while (answer != 7);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(void)
{
char buf[] = "asdf@gccfree@spelld";
char *p = strtok(buf, "@");
while(p)
{
printf("%s\n", p);
p = strtok(NULL, "@");
}
return(0);
}
|
C
|
/*
* spi.c
*
* Created: 12/22/2011 9:44:15 AM
* Author: Administrator
*/
#include "spi.h"
void spi_init()
{
// Initial the AVR ATMega328 SPI Peripheral
// Set MOSI (PORTB3),SCK (PORTB5) and PORTB2 (SS) as output, others as input
SPI_DDR = (1<<PORTB3)|(1<<PORTB5)|(1<<PORTB2);
// CS pin is not active
SPI_PORT |= (1<<SPI_CS);
// Enable SPI, Master Mode 0, set the clock rate fck/2
SPCR = (1<<SPE)|(1<<MSTR);
SPSR |= (1<<SPI2X);
}
void spi_write(uint8_t data)
{
// Activate the CS pin
SPI_PORT &= ~(1<<SPI_CS);
// Set SPDR to data
SPDR = data;
// Wait for transmission complete
while(!(SPSR & (1<<SPIF)));
// CS pin is not active
SPI_PORT |= (1<<SPI_CS);
}
uint8_t spi_read(void)
{
uint8_t data;
// Activate the CS pin
SPI_PORT &= ~(1<<SPI_CS);
// Set temp value for SPDR
SPDR = 0x00;
// Wait for transmission complete
while(!(SPSR & (1<<SPIF)));
data = SPDR;
// CS pin is not active
SPI_PORT |= (1<<SPI_CS);
return(data);
}
|
C
|
#include<stdio.h>
#define max 30
//typedef const int cint;
int main(){
int arr[max]={1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30};
int *ptr[max];
int i,j,*tmp;
for(i=0;i<max;i++){
ptr[i] = &arr[i];
}
for(i=0;i<max;i++){
for(j=i;j<max;j++){
if( *ptr[i] > *ptr[j]){
tmp =ptr[i];
ptr[i] = ptr[j];
ptr[j] =tmp;
}
}
}
for(i=0;i<max;i++){
printf("%d ",*ptr[i]);
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* lesderniersserontlespremiers.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: viduvern <viduvern@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/22 18:25:29 by viduvern #+# #+# */
/* Updated: 2019/03/31 15:02:44 by viduvern ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/minishell.h"
int ft_exec(char **envd, char **str)
{
pid_t father;
father = fork();
if (father == 0)
execve(str[0], str, envd);
else
wait(&father);
return (0);
}
int ft_find_env_2(char **tmp, char **str, char **envd)
{
char *lol;
char *bin;
int x;
x = 0;
lol = ft_strdup(str[0]);
bin = NULL;
while (tmp[x])
{
bin = ft_strjoin3(tmp[x], "/", lol);
free(str[0]);
str[0] = bin;
*str = str[0];
if (access(str[0], F_OK) == 0)
{
ft_exec(envd, str);
ft_free_db_tab(tmp);
free(lol);
return (1);
}
x++;
}
free(lol);
return (0);
}
int ft_find_env(char **envd, char **str)
{
char **tmp;
int i;
tmp = NULL;
i = 0;
while (envd[i])
{
if (ft_strnequ(envd[i], "PATH=", 5))
tmp = ft_strsplit(envd[i], ':');
if (tmp)
if (ft_find_env_2(tmp, str, envd))
return (1);
i++;
}
return (0);
}
int ft_bin(char **envd, char **str)
{
int i;
i = 0;
if (ft_check_str(*str, '/'))
{
if (access(str[0], F_OK) == 0)
ft_exec(envd, str);
else
ft_putendl("bash: command not found");
return (0);
}
else
{
if (ft_find_env(envd, str) == 0)
ft_putendl("bash: command not found");
}
return (0);
}
char **ft_checkpath(char *line, char **envd, char **str)
{
if (ft_strequ(str[0], "cd"))
ft_cd(line, envd, str);
else if (ft_strequ(str[0], "echo"))
ft_echo(line, envd, str);
else if (ft_strequ(str[0], "setenv"))
{
envd = ft_set_env(envd, str);
return (envd);
}
else if (ft_strequ(str[0], "unsetenv"))
{
envd = ft_unset_env(envd, str);
return (envd);
}
else
ft_bin(envd, str);
return (envd);
}
|
C
|
#include<stdio.h>
void main()
{
int a[20],min,max,i,n;
printf("\nHow many elements:");
scanf("%d",&n);
printf("\nEnter array elements:");
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
max=a[0]; //0th index element will get stored in max variable
min=a[0]; //0th index element will get stored in min variable
for(i=1; i<n; i++)
{
//comparision
if(a[i]>max)
{
max=a[i];
}
if(a[i]<min)
{
min=a[i];
}
}
printf("\nMaximum element of array is %d",max);
printf("\nMinimum element of array is %d",min);
}
|
C
|
/*************************************************
* Deitel - C Programming
* Chapter 3 -- Exercise 3.33
* "Hollow Square of Asterisks"
*************************************************/
/*
-------------------------------------------------------------------------------
:: Program Description ::
-------------------------------------------------------------------------------
The program should read in the side of a square and then prints a hollow sqaure
out of asterisks. Your program should work for squares of all side sizes between
1 and 20.
*/
#include <stdio.h>
int main(void)
{
int userInput;
puts("Please enter a number in the rage of 2 through 20.");
printf("Number: ");
if(scanf("%d", &userInput) != 1)
{
while (fgetc(stdin) != '\n');
puts("");
puts("You did not enter a valid number.");
}
else if (userInput >= 2 && userInput <= 20)
{
for (int n = 1; n <= userInput; n++)
{
for (int i = 1; i <= userInput; i++)
{
if (n == 1 || n == userInput)
{
printf("*");
}
else if (i == 1 || i == userInput)
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
}
return 0;
}
|
C
|
#include <stdio.h>
void slownie(int kwota){
printf("%d= ",kwota);
if(kwota>=1000){
int szescset = kwota /1000;
printf(" tysiąc");
kwota -= szescset *1000;
}
if(kwota>=900){
int szescset = kwota /900;
printf(" dziewięćset");
kwota -= szescset *900;
}
if(kwota>=800){
int szescset = kwota /800;
printf(" osiemset");
kwota -= szescset *800;
}
if(kwota>=700){
int szescset = kwota /700;
printf(" siedemset");
kwota -= szescset *700;
}
if(kwota>=600){
int szescset = kwota /600;
printf(" sześćset");
kwota -= szescset *600;
}
if(kwota>=500){
int piecset = kwota /500;
printf(" pięćset");
kwota -= piecset *500;
}
if(kwota>=400){
int czterysta = kwota /400;
printf(" czterysta");
kwota -= czterysta *400;
}
if(kwota>=300){
int trzysta = kwota /300;
printf(" trzysta");
kwota -= trzysta*300;
}
if(kwota>=200){
int dwiescie = kwota /200;
printf(" dwieście");
kwota -= dwiescie *200;
}
if(kwota>=100){
int sto = kwota /100;
printf(" sto");
kwota -= sto *100;
}
if(kwota>=90){
int piecdziesiat = kwota /90;
printf(" dziewiecdziesiat");
kwota -= piecdziesiat * 90;
}
if(kwota>=80){
int piecdziesiat = kwota /80;
printf(" osiemdziesiat");
kwota -= piecdziesiat * 80;
}
if(kwota>=70){
int piecdziesiat = kwota /70;
printf(" siedemdziesiat");
kwota -= piecdziesiat * 70;
}
if(kwota>=60){
int piecdziesiat = kwota /60;
printf(" szescdziesiat");
kwota -= piecdziesiat * 60;
}
if(kwota>=50){
int piecdziesiat = kwota /50;
printf(" piecdziesiat");
kwota -= piecdziesiat * 50;
}
if(kwota>=40){
int piecdziesiat = kwota /40;
printf(" czterdziesci");
kwota -= piecdziesiat * 40;
}if(kwota>=30){
int piecdziesiat = kwota /30;
printf(" trzydziesci");
kwota -= piecdziesiat * 30;
}
if(kwota>=20){
int dwadziescia = kwota /20;
printf(" dwadzieścia");
kwota -= dwadziescia * 20;
}
if(kwota>=19){
int dziesiec = kwota /19;
printf(" dziewiętnaście złotych");
kwota -= dziesiec * 10;
}
if(kwota>=18){
int dziesiec = kwota /18;
printf(" osiemnaście złotych");
kwota -= dziesiec * 18;
}
if(kwota>=17){
int dziesiec = kwota /17;
printf(" siedemnaście złotych");
kwota -= dziesiec * 17;
}
if(kwota>=16){
int dziesiec = kwota /16;
printf(" szesnacie złotych");
kwota -= dziesiec * 16;
}
if(kwota>=15){
int dziesiec = kwota /15;
printf(" piętnaście zlotych");
kwota -= dziesiec * 15;
}
if(kwota>=14){
int dziesiec = kwota /14;
printf(" czternaście złotych");
kwota -= dziesiec * 14;
}
if(kwota>=13){
int dziesiec = kwota /13;
printf(" trzynaście złotych");
kwota -= dziesiec * 13;
}if(kwota>=12){
int dziesiec = kwota /12;
printf(" dwanaście złotych");
kwota -= dziesiec * 12;
}if(kwota>=11){
int dziesiec = kwota /11;
printf(" jedenaście złotych");
kwota -= dziesiec * 11;
}
if(kwota>=10){
int dziesiec = kwota /10;
printf(" dziesięć złotych");
kwota -= dziesiec * 10;
}
if(kwota>=9){
int dziesiec = kwota /9;
printf(" dziewięć złotych");
kwota -= dziesiec * 9;
}
if(kwota>=8){
int dziesiec = kwota /8;
printf(" osiem złotych");
kwota -= dziesiec * 8;
}
if(kwota>=7){
int dziesiec = kwota /7;
printf(" siedem złotych");
kwota -= dziesiec * 7;
}
if(kwota>=6){
int dziesiec = kwota /6;
printf(" sześć złotych");
kwota -= dziesiec * 6;
}
if(kwota>=5){
int piec = kwota /5;
printf(" pięć złotych");
kwota -= piec * 5;
}
if(kwota>=4){
int dziesiec = kwota /4;
printf(" cztery złote ");
kwota -= dziesiec * 4;
}
if(kwota>=3){
int dziesiec = kwota /3;
printf(" trzy złote ");
kwota -= dziesiec * 3;
}
if(kwota>=2){
int dwa = kwota /2;
printf(" dwa złote ");
kwota -= dwa * 2;
}
if(kwota>=1){
int jeden = kwota /1;
printf(" jeden zlotych ");
kwota -= jeden * 1;
}
}
int main()
{
int kwota=0;
printf("Zadanie trzecie, czytanie słowne liczby\n");
printf("podaj kwotę\n");
scanf("%d", &kwota);
slownie(kwota);
return 0;
}
|
C
|
/* hmm_adjustb.c -- ECOZ System
*/
#include "utl.h"
#include "hmm.h"
#include <math.h>
#include <stdlib.h>
#include <assert.h>
// to verify stochastic requirement
//#define VERIFY
prob_t hmm_epsilon = 1.e-5;
void hmm_adjust_B_epsilon(Hmm *hmm, const char* logMsg) {
if (hmm_epsilon <= (prob_t) 0.) {
return; // no restriction
}
(void) logMsg; // avoid compile warning when VERIFY undefined.
const int N = hmm->N;
const int M = hmm->M;
prob_t **B = hmm->B;
#ifdef VERIFY
{
for (int j = 0; j < N; j++) {
prob_t *row = B[j];
prob_t sum = 0;
for (int k = 0; k < M; k++) {
if (row[k] < 0) {
printf(RED("hmm_adjust_B_epsilon: PRE ERROR: Σ B[%d][%d] = %Le < 0 %s\n\n"),
j, k, (long double) row[k], logMsg);
exit(1);
}
sum += row[k];
}
if (fabsl(sum - 1) > 1e-10) {
printf(RED("hmm_adjust_B_epsilon: PRE ERROR: Σ B[%d] = %Le != 1 %s\n\n"),
j, (long double) sum, logMsg);
//exit(1);
}
}
}
#endif
for (int j = 0; j < N; j++) {
prob_t *row = B[j];
prob_t total_added = 0, total_extra = 0;
for (int k = 0; k < M; k++) {
if (row[k] < hmm_epsilon) {
total_added += hmm_epsilon - row[k];
row[k] = hmm_epsilon;
}
else if (row[k] > hmm_epsilon) {
total_extra += row[k] - hmm_epsilon;
}
}
if (total_added) {
for (int k = 0; k < M; k++) {
if (row[k] > hmm_epsilon) {
prob_t extra = row[k] - hmm_epsilon;
prob_t fraction = extra / total_extra;
row[k] -= total_added * fraction;
}
}
#ifdef VERIFY
{
prob_t sum = 0;
for (int k = 0; k < M; k++) {
prob_t *row = B[j];
if (row[k] < hmm_epsilon) {
printf(RED("hmm_adjust_B_epsilon: POST ERROR: Σ B[%d][%d] = %Le < ε = %Le %s\n\n"),
j, k,
(long double) row[k], (long double) hmm_epsilon,
logMsg);
exit(1);
}
sum += row[k];
}
if (fabsl(sum - 1) > 1e-10) {
printf(RED("hmm_adjust_B_epsilon: POST ERROR: Σ B[%d] = %Le != 1 %s\n\n"),
j, (long double) sum, logMsg);
exit(1);
}
}
#endif
}
}
}
|
C
|
#include "client.h"
#include <unistd.h>
#include <string.h>
#include <malloc.h>
int main(int argc,char **argv) {
//variables we need
char *config = NULL, op;
ns_t *nameserver;
cmd_t *command;
char output[BUFFER];
//command line arguments
while( (op = getopt(argc,argv,"f:")) != -1) {
switch(op) {
case 'f':
config = malloc(sizeof(char)*strlen(optarg)+1);
strcpy(config,optarg);
}
}
//get config data (It will exit here on error)
nameserver = getNameserver(config);
//prompt on interactive mode
if(isatty(fileno(stdin))) {
printf("CSC 4200 Networking Program #1 Client\n");
printf(" Sumit Khanna -- (Interactive Mode)\n");
}
//user input loop
while(1) {
//read a command
if( (command = promptUser()) == NULL) {
if(isatty(fileno(stdin))) {printf("\nGoodbye\n"); }
exit(0); //user send EOF
}
//lookup service
switch(serviceLookup(command,nameserver)) {
case 0: //successful connect to name service
switch(runCommand(command,&output[BUFFER],BUFFER)) {
case 0: //successfuly response from service
break;
}
break;
case -1:
printf("Error: Invalid Nameserver\n");
break;
case -2:
printf("Error: Could Not Connect to Nameserver\n");
break;
case -3:
printf("Error: I/O Failure with Nameservice\n");
break;
case -4:
printf("Error: Invalid Response from Nameservice\n");
break;
case -5:
printf("Error: Unknown Service\n");
break;
}
//done with this command
freeCommand(command);
}
//clean up
freeNameserver(nameserver);
exit(0);
}
|
C
|
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, string argv[2])
{
//check for argument count
if (argc != 2)
{
printf("Usage: ./vigenere k\n");
return 1;
}
//this is a little redundant but works to check for letters only
if (isalpha(argv[1] == false))
{
printf("Key must be alphabetical character\n");
return 1;
}
char *key = argv[1];
for (int j = 0, h = strlen(key); j < h; j++)
{
if (!isalpha(key[j]))
{
printf("Key must be alphabetical character\n");
return 1;
}
}
//declare var, prompt user for inputs to ceasar
string plain = get_string("plaintext: ");
printf("ciphertext: ");
for (int i = 0, p = strlen(plain), k = 0; i < p; i++)
//checks that the plain text is alpha or skips
if (isalpha(plain[i]))
{
if (isupper(plain[i]))
{
//cipher iterates over the characters and shifts them
printf("%c", ((plain[i]) - 65 + (toupper(key[k])) - 65) % 26 + 65);
}
else if (islower(plain[i]))
{
printf("%c", ((plain[i]) - 97 + (toupper(key[k])) - 65) % 26 + 97);
}
//resets the array for the key shift
k = (k + 1) % strlen(key);
}
else
{
printf("%c", plain[i]);
}
printf("\n");
return 0;
}
|
C
|
#define NO_FREE_FRAME -1
#define ERR_INVALID_PAGE -2
// Definition for a page table entry. Each hold a frame number, a count for LRU, and a an int (used like a bool) for
// validity.
typedef struct pte {
unsigned long frame;
unsigned long count;
int valid;
} pte_t;
// Functions defined in pagetable.c
// Initialize a pagetable. This function malloc's memory, which needs to be freed using clear_table() after use.
// Arguments:
// unsigned long vm_size: A power of two specifying the size of the virtual memory
// unsigned long bytes_per_page: A power of two specifying the number of bytes addressed per page
// Return:
// A pte_t* that points to the first element of an array of pte_t elements. This array is malloc'd, and needs to be
// freed after use.
pte_t *initialize_table(unsigned long vm_size, unsigned long bytes_per_page);
// Calculate the mask needed to isolate offset bits
// Arguments:
// unsigned long bytes_per_page: A power of two specifying the size of each page/frame of memory
// Returns:
// A mask that can be used to isolate only the offset bits of a virtual address
unsigned long calc_d_mask(unsigned long bytes_per_page);
// Calculate the mask needed to isolate the page number
// Arguments:
// unsigned long vm_size: A power of two specifying the size of the virtual memory address space
// unsigned long d_mask: The mask for the offset bits
// Returns:
// A mask that can be used to isolate only the page bits of a virtual address
unsigned long calc_v_mask(unsigned long vm_size, unsigned long d_mask);
// Calculate the shift needed to translate page bits into a page number
// Arguments:
// unsigned long d_mask: The mask for offset bits
// Return:
// The number of shifts needed to translate page bits into a page number, or frame numbers into frame bits
unsigned long calc_shift(unsigned long d_mask);
// Perform address translation from virtual to physical addresses
// Arguments:
// unsigned long vaddr: The virtual address to be translated
// unsigned long v_mask: The mask used for isolating page bits
// unsigned long d_mask: The mask used for isolation offset bits
// unsigned long shift: The shift needed to translate page or frame bits into numbers or vice-versa
// pte_t *table: A pointer to a page table, which is just an array of pte_t initialized by initialize_table()
// Return:
// The physical address translation from the virtual address passed, or ERR_INVALID_PAGE if the vaddr passed is out of
// range
unsigned long vaddr_to_paddr(unsigned long vaddr, unsigned long v_mask, unsigned long d_mask, unsigned long shift,
pte_t *table);
// Free the memory used for the page table
// Arguments:
// None
// Return:
// None
void clear_table(pte_t *table);
// Get the number of page faults encountered
// Arguments:
// None
// Return:
// The number of page faults encountered so far
unsigned int get_page_faults();
// Functions defined in phypages.c
// Initialize the frames
// Arguments:
// unsigned long pm_size: Total size of the physical memory
// unsigned long bytes_per_page: The number of bytes in each page/frame
// Return:
// None
void initialize_frames(unsigned long pm_size, unsigned long bytes_per_page);
// Get the next free frame.
// Arguments:
// None
// Return:
// The next free frame if one is available, or NO_FREE_FRAME if no free frame is available
unsigned long get_free_frame();
|
C
|
#include<stdio.h>
#include<string.h>
void swap(char a[],int i,int j)
{
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
void permute(char a[], int l, int r)
{
if(l==r)
{
printf("\n%s",a);
}
else
{
for(int i=l;i<=r;i++)
{
swap(a,i,l);
permute(a,l+1,r);
swap(a,i,l);
}
}
}
int main()
{
char a[1000];
printf("\nenter the string : ");
scanf("%s",a);
int len = strlen(a);
permute(a,0,len-1);
return 0;
}
|
C
|
/*
*
*from 《数据结构》
*循环队列,顺序存储结构
* */
#include <stdio.h>
#include <stdlib.h>
// 预定义常量和类型
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef int QElemType;
// 循环队列,队列的顺序存储结构
#define MAXQSIZE 100 // 最大队列长度
typedef struct{
QElemType *base; // 初始化的动态分配存储空间
int front; // 头指针,若队列不空,指向队列头元素
int rear; // 尾指针,若队列不空,指向队列尾元素的下一各位值
}SqQueue;
Status InitQueue(SqQueue &Q){
// 构造一个空队列
Q.base = (QElemType*)malloc(MAXQSIZE * sizeof(QElemType));
if(!Q.base) exit(OVERFLOW); // 存储空间分配失败
Q.front = Q.rear = 0;
return OK;
}
int QueueLength(SqQueue Q){
// 返回Q的元素个数,及队列的长度
return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;
}
Status EnQueue(SqQueue &Q, QElemType e){
// 插入元素e为Q的新的队尾元素
if((Q.rear + 1) % MAXQSIZE == Q.front) return ERROR; // 队列满
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
return OK;
}
Status DeQueue(SqQueue &Q, QElemType &e){
// 若队列不空,则删除Q的队列元素,用e返回其值,并返回OK;否则返回ERROR
if(Q.front == Q.rear) return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
return OK;
}
int main(){
return 0;
}
|
C
|
/*
* C - Basics
* Fibonacci series up to a given number of elements
* (fibonacci_recursive.c) v20190727
*
* Gonzsou
*
*/
#include <stdio.h>
#include <stdlib.h>
void fib(int *previous, int *current, int n ){
/*swaps value stored on 'previous' by value stored in 'current', and calculates new 'current' value*/
int temp = *current;
*current += *previous;
*previous = temp;
/*controls the exit point of recursive function, every recursive function must have a condition in order to stop the recursion*/
if (n>3){
printf("%d, ", *current);
n--;
fib(previous, current, n); //recursion call to next element
} else if (n==3){
printf("%d\n", *current); //prints last element (last element without comma)
n--;
}
}
int main() {
/*base values */
int previous = 0;
int current = 1;
/*requests number fibonacci series elements to print*/
int n=0;
printf("Enter how many elements of fibonacci series you want to print: ");
scanf("%d", &n);
/*Controls what to print based on the number of elements 'n' entered by the user*/
if (n==1) {
printf("%d\n", previous);
} else if(n==2) {
printf("%d, %d\n", previous, current);
} else if (n>2) {
printf("%d, %d, ", previous, current);
fib(&previous, ¤t, n); //fib function call by reference
} else {
printf("%d, %d\n", previous, current);
}
}
|
C
|
/*
* Standard Dependable Vehicle Operating System
*
* Copyright (C) 2015 Ye Li (liye@sdvos.org)
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file src/include/osek/resource.h
* @author Ye Li (liye@sdvos.org)
* @brief OSEK Resource Management
*/
#ifndef _OSEK_RESOURCE_H_
#define _OSEK_RESOURCE_H_
#include <osek/types.h>
#include <osek/error.h>
/**
* @brief
* DeclareResource serves as an external declaration of a
* resource. The function and use of this service are
* similar to that of the external declaration of variables.
*
* Conformance:
* BCC1, BCC2, ECC1, ECC2
*
* @param[in] ResourceIdentifier
* Resource identifier (C-identifier)
*/
#define DeclareResource(ResourceIdentifier)
/**
* @brief
* This call serves to enter critical sections in the code
* that are assigned to the resource referenced by rid. A
* critical section shall always be left using
* ReleaseResource.
*
* The OSEK priority ceiling protocol for resource
* management is described in chapter 8.5.
*
* Nested resource occupation is only allowed if the inner
* critical sections are completely executed within the
* surrounding critical section (strictly stacked, see
* chapter 8.2, Restrictions when using resources). Nested
* occupation of one and the same resource is also
* forbidden! It is recommended that corresponding calls
* to GetResource and ReleaseResource appear within the
* same function. It is not allowed to use services which
* are points of rescheduling for non preemptable tasks
* (TerminateTask, ChainTask, Schedule and WaitEvent, see
* chapter 4.6.2) in critical sections. Additionally,
* critical sections are to be left before completion of
* an interrupt service routine. Generally speaking,
* critical sections should be short. The service may be
* called from an ISR and from task level.
*
* Conformance:
* BCC1, BCC2, ECC1, ECC2
*
* @param[in] rid
* Reference to resource
*
* @retval E_OK
* (Standard) No error
* @retval E_OS_ID
* (Extended) Resource rid is invalid
* @retval E_OS_ACCESS
* (Extended) Attempt to get a resource which is already
* occupied by any task or ISR, or the statically assigned
* priority of the calling task or interrupt routine is
* higher than the calculated ceiling priority
*/
StatusType GetResource (ResourceType rid);
/**
* @brief
* ReleaseResource is the counterpart of GetResource and
* serves to leave critical sections in the code that are
* assigned to the resource referenced by rid.
*
* For information on nesting conditions, see particularities
* of GetResource. The service may be called from an ISR and
* from task level.
*
* Conformance:
* BCC1, BCC2, ECC1, ECC2
*
* @param[in] rid
* Reference to resource
*
* @retval E_OK
* (Standard) No error
* @retval E_OS_ID
* (Extended) Resource rid is invalid
* @retval E_OS_NOFUNC
* (Extended) Attempt to release a resource which is not
* occupied by any task or ISR, or another resource shall
* be released before.
* @retval E_OS_ACCESS
* (Extended) Attempt to release a resource which has a
* lower ceiling priority than the statically assigned
* priority of the calling task or interrupt routine.
*/
StatusType ReleaseResource (ResourceType rid);
#endif
/* vi: set et ai sw=2 sts=2: */
|
C
|
#include <stdio.h>
#define IN 0
#define OUT 1
int main() {
int input, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while (EOF != (input = getchar())) {
if ('\n' == input) {
++nl;
state = OUT;
} else if (' ' == input || '\t' == input) {
state = OUT;
} else {
if (OUT == state) {
state = IN;
++nw;
}
}
++nc;
}
printf("line %d word %d chars %d\n", nl, nw, nc);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main() {
long nit, it, in;
double pi, x, y;
fprintf(stderr, "Please eneter number of MC steps = ");
scanf("%ld", &nit);
in = 0;
for (it = 0; it < nit; it++) {
x = (double)random()/RAND_MAX;
y = (double)random()/RAND_MAX;
if (x*x + y*y <= 1.0f) {
in++;
}
}
pi = in*4.0f/nit;
fprintf(stderr,"Pi = %.10f\n",pi);
return 0;
}
|
C
|
#include <stdio.h>
int main() {
int v[10],i,n;
scanf("%d", &n);
v[0] = n;
for(i=0; i<10; i++) {
printf("N[%d] = %d\n",i,v[i]);
v[i+1] = v[i]*2;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "struct_file.h"
int load_from_file(struct Chest *chest, char *file_name);
int main(int arc, char **argv)
{
printf("Enter name of file to load Chest struct from.\n");
char file_name[256];
scanf("%s", file_name);
printf("Loading %s\n", file_name);
struct Chest *chest = malloc(sizeof(struct Chest));
printf("Allocated %d bytes to chest. Sizeof chest: %d\n",
(int)sizeof(struct Chest), (int)sizeof(*chest));
if (load_from_file(chest, file_name) == 1)
{
printf("load_from_filed returned failuer code, exiting\n");
return 1;
}
return 0;
}
int load_from_file(struct Chest *chest, char *file_name)
{
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) == NULL)
{
return 1;
}
strcat(cwd, "/");
strcat(cwd, file_name);
printf("Opening file with path %s\n", cwd);
FILE *fp;
fp = fopen(cwd, "rb");
if (!fp)
{
printf("failure to open file, exiting\n");
return 1;
}
if (fread(chest, sizeof(struct Chest), 1, fp) == 0)
{
printf("fread read 0 objects, exiting\n");
return fclose(fp);
}
printf("Read name: %s, gp: %d\n", chest->name, chest->gp);
return fclose(fp);
}
|
C
|
#include"process.h"
#include"init.h"
#include"draw.h"
/*------生成地雷-------*/
void produceBom()
{
srand((unsigned)time(0)); //生成随机因子
int i,j,k;
for(k=0;k<iBoom_Num;k++)
{
i = rand() % iHigh;
j= rand() % iWidth ;
if(Mine[i][j].iBoom==1) //判断是否有雷,有雷则此次不算
k=k-1;
else
Mine[i][j].iBoom=1;
}
}
/*------统计格子周围的雷-------*/
int bomStatics(int i, int j)
{
int nNUM=0;
if((i==0)&&(j==0)) /*左上角*/
{
if(Mine[0][1].iBoom==1)
nNUM++;
if(Mine[1][0].iBoom==1)
nNUM++;
if(Mine[1][1].iBoom==1)
nNUM++;
}
else
if((i==0)&&(j==(iWidth-1))) /*右上角*/
{
if(Mine[0][iWidth-2].iBoom==1)
nNUM++;
if(Mine[1][iWidth-1].iBoom==1)
nNUM++;
if(Mine[1][iWidth-2].iBoom==1)
nNUM++;
}
else
if((i==(iHigh-1))&&(j==0)) /*左下角*/
{
if(Mine[iHigh-2][0].iBoom==1)
nNUM++;
if(Mine[iHigh-1][1].iBoom==1)
nNUM++;
if(Mine[iHigh-2][1].iBoom==1)
nNUM++;
}
else
if((i==(iHigh-1))&&(j==(iWidth-1))) /*右下角*/
{
if(Mine[iHigh-1][iWidth-2].iBoom==1)
nNUM++;
if(Mine[iHigh-2][iWidth-1].iBoom==1)
nNUM++;
if(Mine[iHigh-2][iWidth-2].iBoom==1)
nNUM++;
}
else if(j==0) /*第一列*/
{
if(Mine[i][j+1].iBoom==1)
nNUM++;
if(Mine[i+1][j].iBoom==1)
nNUM++;
if(Mine[i-1][j].iBoom==1)
nNUM++;
if(Mine[i-1][j+1].iBoom==1)
nNUM++;
if(Mine[i+1][j+1].iBoom==1)
nNUM++;
}
else if(j==(iWidth-1)) /*最右边一行*/
{
if(Mine[i][j-1].iBoom==1)
nNUM++;
if(Mine[i+1][j].iBoom==1)
nNUM++;
if(Mine[i-1][j].iBoom==1)
nNUM++;
if(Mine[i-1][j-1].iBoom==1)
nNUM++;
if(Mine[i+1][j-1].iBoom==1)
nNUM++;
}
else if(i==0) /*第一行*/
{
if(Mine[i+1][j].iBoom==1)
nNUM++;
if(Mine[i][j-1].iBoom==1)
nNUM++;
if(Mine[i][j+1].iBoom==1)
nNUM++;
if(Mine[i+1][j-1].iBoom==1)
nNUM++;
if(Mine[i+1][j+1].iBoom==1)
nNUM++;
}
else if(i==(iHigh-1)) /*最下面一行*/
{
if(Mine[i-1][j].iBoom==1)
nNUM++;
if(Mine[i][j-1].iBoom==1)
nNUM++;
if(Mine[i][j+1].iBoom==1)
nNUM++;
if(Mine[i-1][j-1].iBoom==1)
nNUM++;
if(Mine[i-1][j+1].iBoom==1)
nNUM++;
}
else /*普通格*/
{
if(Mine[i-1][j].iBoom==1)
nNUM++;
if(Mine[i-1][j+1].iBoom==1)
nNUM++;
if(Mine[i][j+1].iBoom==1)
nNUM++;
if(Mine[i+1][j+1].iBoom==1)
nNUM++;
if(Mine[i+1][j].iBoom==1)
nNUM++;
if(Mine[i+1][j-1].iBoom==1)
nNUM++;
if(Mine[i][j-1].iBoom==1)
nNUM++;
if(Mine[i-1][j-1].iBoom==1)
nNUM++;
}
return nNUM;
}
/*--------打开白格---------*/
void showWhite(int i,int j)
{
if((Mine[i][j].iFlag==1)||(Mine[i][j].iProcess==1))/*有旗或者已处理则退出*/
return;
Mine[i][j].iRound_Num=bomStatics(i,j); //统计周围雷数
if((Mine[i][j].iRound_Num==0)&&(Mine[i][j].iProcess!=1)) /*未处理,周围无雷*/
{
drawWhite(i,j); //画白格
iWin_Flag++;
Mine[i][j].iProcess=1;
}
else
if((Mine[i][j].iRound_Num!=0)&&(Mine[i][j].iProcess!=1))/*周围有雷*/
{
drawNum(i,j,Mine[i][j].iRound_Num);
Mine[i][j].iProcess=1;
iWin_Flag++;
return ;
}
/*8个方向递归*/
if((i!=0)&&(Mine[i-1][j].iProcess!=1))
showWhite(i-1,j);
if((i!=0)&&(j!=(iWidth-1))&&(Mine[i-1][j+1].iProcess!=1))
showWhite(i-1,j+1);
if((j!=(iWidth-1))&&(Mine[i][j+1].iProcess!=1))
showWhite(i,j+1);
if((j!=(iWidth-1))&&(i!=(iHigh-1))&&(Mine[i+1][j+1].iProcess!=1))
showWhite(i+1,j+1);
if((i!=(iHigh-1))&&(Mine[i+1][j].iProcess!=1))
showWhite(i+1,j);
if((i!=(iHigh-1))&&(j!=0)&&(Mine[i+1][j-1].iProcess!=1))
showWhite(i+1,j-1);
if((j!=0)&&(Mine[i][j-1].iProcess!=1))
showWhite(i,j-1);
if((i!=0)&&(j!=0)&&(Mine[i-1][j-1].iProcess!=1))
showWhite(i-1,j-1);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int c(const void *a, const void *b){
if(*(long long int*)a - *(long long int*)b > 0) return 1;
else if(*(long long int*)a - *(long long int*)b < 0) return -1;
else return 0;
}
int main(){
int N, M;
scanf("%d %d", &N, &M);
long long int a[N];
int i;
long A, B;
for(i = 0; i < N; i++){
scanf("%ld %ld", &A, &B);
a[i] = A * 1000000 + B;
}
qsort(a, N, sizeof(long long int), c);
i = 0;
long sum = 0;
long long int sum_m = 0;
int j;
while(sum < M){
for(j = 0; j < a[i] % 1000000; j++){
sum++;
sum_m += a[i] / 1000000;
if(sum == M) break;
}
i++;
}
printf("%lld\n", sum_m);
return 0;
}
|
C
|
/*
* Exercise_1-10.c
*
* Created on: 28 Jan 2021
* Author: Al
*/
#include <stdio.h>
typedef unsigned char bool;
#define TRUE (bool)1u
#define FALSE (bool)0u
int main()
{
int c;
for ( c = getchar(); c != EOF; c = getchar() ) {
bool flag = 0;
if ( c == '\t' ) {
flag = 1;
(void)putchar('\\');
(void)putchar('t');
}
if ( c == '\b' ) {
flag = 1;
(void)putchar('\\');
(void)putchar('b');
}
if ( c == '\\' ) {
flag = 1;
(void)putchar('\\');
(void)putchar('\\');
}
if ( flag == FALSE ) {
(void)putchar(c);
}
}
return 0;
}
|
C
|
#include "holberton.h"
#include <stdio.h>
/**
*binary_to_uint - converts a binary number to an unsigned int
*@b: poiter to a string
*Return: conv
**/
unsigned int binary_to_uint(const char *b)
{
unsigned int conv = 0;
int cont = 0, pow;
if (b == NULL)
{
return (0);
}
while (b[cont + 1] != '\0')
cont++;
pow = 1;
while (cont >= 0)
{
if (b[cont] != '0' && b[cont] != '1')
{
return (0);
}
conv += (b[cont] - '0') * pow;
pow *= 2;
cont--;
}
return (conv);
}
|
C
|
#include <stdio.h>
#include "list.h"
struct list
{
int info;
struct list *next;
};
/* init */
List *lst_init(void)
{
return NULL;
}
/* insert */
List *lst_insert(List *l, int i)
{
List *new = (List *)malloc(sizeof(List));
new->info = i;
new->next = l;
return new;
}
/* print */
void lst_print(List *l)
{
List *p;
for (p = l; p != NULL; p = p->next)
printf("info = %d\n", p->info);
}
/* empty */
int lst_empty(List *l)
{
if (l == NULL)
return 1;
else
return 0;
}
/* search */
List *lst_search(List *l, int v)
{
List *p;
for (p = l; p != NULL; p = p->next)
if (p->info == v)
return p;
return NULL;
}
/* out */
List *lst_out(List *l, int v)
{
List *prev = NULL; /* prev element */
List *p = l;
/* search element in list and save prev element */
while (p != NULL && p->info != v)
{
prev = p;
p = p->next;
}
// find ?
if (p == NULL)
return l;
if (prev == NULL)
{
/* remove element */
l = p->next;
}
else
{
/* remove element */
prev->next = p->next;
}
free(p);
return l;
}
void lst_libera(List *l)
{
List *p = l;
while (p != NULL)
{
List *t = p->next;
free(p);
p = t;
}
}
|
C
|
//
// LCBChapterSevenMachineExperimentOne.c
// DataStructurePractice
//
// Created by ly on 2018/6/18.
// Copyright © 2018年 LY. All rights reserved.
//
#include "LCBChapterSevenMachineExperimentOne.h"
int breadthOfBinaryTree(BinaryTree *tree) {
BinaryTreeCSqQueue *queue = initBinaryTreeCSqQueue() ;
int layerNodeCount = 1 ;
int layerNextNodeCount = 0;
int layerNodeCounter = 0;
int layerMaxCount = 1 ;
if (tree == NULL) {
return 0 ;
}
queue->rear = (queue->rear + 1)%MaxSize ;
queue->data[queue->rear] = tree ;
while (queue->rear != queue->front) {
queue->front = (queue->front + 1) %MaxSize ;
layerNodeCounter ++ ;
BinaryTree *treeCopy = queue->data[queue->front] ;
if (treeCopy->left != NULL) {
queue->rear = (queue->rear + 1) %MaxSize ;
queue->data[queue->rear] = treeCopy->left ;
layerNextNodeCount ++ ;
}
if (treeCopy->right != NULL) {
queue->rear = (queue->rear + 1) %MaxSize ;
queue->data[queue->rear] = treeCopy->right ;
layerNextNodeCount ++ ;
}
if (layerNodeCounter == layerNodeCount ) {
layerNodeCount = layerNextNodeCount;
layerNodeCounter = 0 ;
if (layerMaxCount < layerNextNodeCount) {
layerMaxCount = layerNextNodeCount ;
}
layerNextNodeCount = 0 ;
}
}
return layerMaxCount ;
}
int countNodeOfBinaryTree(BinaryTree *tree) {
if (tree == NULL) {
return 0 ;
}
int count = 1 ;
count += countNodeOfBinaryTree(tree->left) ;
count += countNodeOfBinaryTree(tree->right) ;
return count ;
}
int countLeafNodeOfBinaryTree(BinaryTree *tree) {
if (tree->left == NULL && tree->right == NULL) {
return 1 ;
}
int count = 0 ;
if (tree->left != NULL) {
count += countLeafNodeOfBinaryTree(tree->left) ;
}
if (tree->right != NULL) {
count += countLeafNodeOfBinaryTree(tree->right) ;
}
return count ;
}
|
C
|
#include<stdio.h>
#include<ctype.h>
void main()
{
char a[10];
int flag,i=1;
printf("\nEnter an Identifier");
scanf("%s",a);
if(isalpha(a[0]) || a[0]=='_')
flag=1;
else
{
flag=0;
}
while(a[i]!='\0')
{
if(!isdigit(a[i])&&!isalpha(a[i])&&a[i]!='_')
{
flag=0;
break;
}
i++;
}
if(flag==1)
printf("\nValid Identifier\n");
else
printf("\nNot a valid Identifier\n");
}
|
C
|
/*********************************
* Class: MAGSHIMIM C2 *
* openCV template *
**********************************/
#include <stdio.h>
#include <opencv2\highgui\highgui_c.h>
int main(void)
{
int i;
cvNamedWindow("Display window", CV_WINDOW_AUTOSIZE); //create a window
//create an image
IplImage* image = cvLoadImage("C:\\c1.png", 1);
if (!image)//The image is empty.
{
printf("could not open image\n");
}
else
{
cvShowImage("Display window", image);
cvWaitKey(0);
system("pause");
cvReleaseImage(&image);
}
return 0;
}
|
C
|
#include "addauthor.h"
void checkArgs(int argc)
{
if (argc == 1)
{
printf("Error: Please provide a author and a stream\n");
printf("</body>\n");
printf("</html>");
exit(1);
}
}
void getStreams(char * streams)
{
printf("list streams: ");
fgets(streams, 100, stdin);
if (strcmp(streams, "\n") == 0)
{
printf("Error: stream cannot be enter please run addauthor again!\n");
printf("</body>\n");
printf("</html>\n");
exit(1);
}
/* removes new line character */
streams[strlen(streams) - 1] = '\0';
}
int main(int argc, char const *argv[])
{
checkArgs(argc);
char streams[100];
char author[100];
int i;
strcpy(author, "");
if (strcmp(argv[1], "-r") == 0)
{
/* fetches the author then removes everything else */
for (i = 2; i < argc - 1; i++)
{
strcat(author, argv[i]);
if (i + 1 != argc - 1)
{
strcat(author, " ");
}
}
strcpy(streams, argv[argc- 1]);
/* removes the user */
removeUser(author, streams);
}
else
{
/* fetches the author then removes everything else */
for (i = 1; i < argc - 1; i++)
{
strcat(author, argv[i]);
if (i + 1 != argc - 1)
{
strcat(author, " ");
}
}
strcpy(streams, argv[argc- 1]);
/* adds the user */
addUser(author, streams);
}
printf("</body>\n");
printf("</html>\n");
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int t;
scanf("%d", &t);
getchar();
while(t--) {
int n, i, x = 0;
scanf("%d", &n);
int move[n+1];
getchar();
char ins[20];
for(i=0; i<n; i++) {
fgets(ins, 20, stdin);
if(ins[0]=='L') {
move[i] = -1;
x--;
}
else if(ins[0]=='R') {
move[i] = 1;
x++;
}
else{
int step;
char *a, *b;
sscanf(ins, "%*s %*s %d", &step);
x = x + move[step-1];
move[i] = move[step-1];
}
}
printf("%d\n", x);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<assert.h>
float calculateSeries(int);
int fact(int);
void main()
{
int n;
float res;
printf("Enter N value for the series: ");
scanf("%d",&n);
res = calculateSeries(n);
printf("\nSeries sum is : %f\n\n\n", res);
assert(calculateSeries(1) == 1.000000);
assert(calculateSeries(2) == 1.600000);
assert(calculateSeries(2) == 1.500000);
}
float calculateSeries( int n)
{
int i;
float result = 0;
for (i = 1; i<=n ; i++)
{
result = result + (float) 1/fact(i);
}
return result;
}
int fact(int n)
{
int factorial = 1,i;
for(i = 1; i<=n; i++)
factorial = factorial * i;
return factorial;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main(){
char name[7][20],temp[20];
int i,j;
for(i=0;i<7;i++){
printf("\nPlease enter name %d: ", i+1);
scanf("%s",&name[i]);
}
for(i=1;i<7;i++){
for(j=1;j<7;j++){
if(strcmp(name[j-1],name[j]) > 0){
strcpy(temp,name[j-1]);
strcpy(name[j-1],name[j]);
strcpy(name[j],temp);
}
}
}
printf("List name:");
for(i=0;i<7;i++){
printf("%s\t",name[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "way_finder.h"
/*
// List to take first
*/
typedef struct list list;
struct list {
list *next;
char c;
};
genom * take_first_solution(int max_size) {
list *l = NULL;
list *tail = NULL;
char c = (char)fgetc(stdin);
int size = 0;
while (c != EOF) {
if (c != '\n') {
list *new_el = malloc(sizeof(list));
new_el->c = c;
new_el->next = NULL;
if (l == NULL) {
l = new_el;
} else {
tail->next = new_el;
}
tail = new_el;
size++;
}
c = (char)fgetc(stdin);
}
genom *new_g;
if (size > max_size) {
new_g = NULL;
list *temp_last;
for (int i=0; i<size; i++) {
temp_last = l;
l = l->next;
free(temp_last);
}
} else {
new_g = malloc(sizeof(genom));
new_g->path = malloc(sizeof(char)*max_size);
new_g->size = size;
new_g->did_exit = true;
list *temp_last;
for (int i=0; i<size; i++) {
new_g->path[i] = l->c;
temp_last = l;
l = l->next;
free(temp_last);
}
}
return new_g;
}
int main() {
clock_t time_start = clock();
stdin_data *data = take_stdin();
genom *first_solution = take_first_solution((data->col-2)*(data->row-2));
generation *g = malloc(sizeof(generation));
if (first_solution != NULL) {
g->actual_size = 1;
g->max_genom_size = (data->col-2)*(data->row-2);
g->max_size = 100;
g->gen = malloc(sizeof(genom)*g->max_size);
*(g->gen) = *(first_solution);
free(first_solution);
for (int i=1; i<g->max_size; i++) {
(g->gen + i)->path = malloc(sizeof(char)*g->max_genom_size);
(g->gen + i)->size = 0;
(g->gen + i)->did_exit = false;
}
} else {
g->actual_size = 0;
g->max_genom_size = (data->col-2)*(data->row-2);
g->max_size = 100;
g->gen = malloc(sizeof(genom)*g->max_size);
for (int i=0; i<g->max_size; i++) {
(g->gen + i)->path = malloc(sizeof(char)*g->max_genom_size);
(g->gen + i)->size = 0;
(g->gen + i)->did_exit = false;
}
}
genom *best_genom = find_way(data, g, time_start);
printf("%d\n", best_genom->size);
for (int i=0; i<best_genom->size; i++) {
fprintf(stderr, "%c", best_genom->path[i]);
}
}
|
C
|
// INT STACK (HEADER FILE)
#include <stdbool.h>
#define MAX_SIZE 100
struct Stack{
int stk[MAX_SIZE];
int size;
int top;
};
typedef struct Stack Stack;
// Create Stack
Stack* createStack(int size){
Stack* stack = (Stack *)malloc(sizeof(Stack));
stack->size = size;
stack->top = -1;
return stack;
}
// FULL
bool isFull(Stack* stack){
if(stack->top == (stack->size-1)){
return true;
}
return false;
}
// EMPTY
bool isEmpty(Stack* stack){
if(stack->top < 0){
return true;
}
return false;
}
// DISPLAY
void display(Stack* stack){
if(isEmpty(stack)){
printf("\nStack is Empty !!");
}else{
printf("\nStack Elements (top to bottom) : ");
for(int index=stack->top ; index >=0 ; index-- ){
printf("%c ",stack->stk[index]);
}
}
}
// PUSH
void push(Stack* stack,int val){
if(! isFull(stack)){
stack->top += 1;
stack->stk[stack->top] = val;
return;
}
}
// POP
int pop(Stack* stack){
int val;
if(isEmpty(stack)){
return '\0';
}
else{
val = stack->stk[stack->top] ;
stack->top -= 1;
return val;
}
}
// PEEP
int peep(Stack* stack){
if(! isEmpty(stack)){
return stack->stk[stack->top];
}
}
|
C
|
/*
* Test program for color_conversion library
*
* Author: Dennis Koslowski <dennis.koslowski@gmx.de>
* Date: 2020-01-14
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "color_conversion.h"
/*
* Get the first character from stdin
*/
static char get_char() {
char ch = 0;
const size_t len = 64;
char buf[len];
printf("\nPlease make you choice: ");
fgets(buf, len, stdin);
if (2 == strlen(buf)) {
ch = buf[0];
}
return ch;
}
/*
* Get a double from stdin
*/
static double get_double(const char* name) {
double d = 0.0;
const size_t len = 64;
char buf[len];
int ok = 0;
do {
printf("%s: ", name);
fgets(buf, len, stdin);
if (sscanf(buf, "%lf", &d) == 1) {
ok = 1;
} else {
printf("Invalid input, please enter a decimal value\n");
}
} while (!ok);
return d;
}
/*
* Get a byte from stdin
*/
static double get_uint8(const char* name) {
unsigned int val = 0;
const size_t len = 64;
char buf[len];
int ok = 0;
do {
printf("%s: ", name);
fgets(buf, len, stdin);
if (sscanf(buf, "%d", &val) == 1 && val <= 0xff) {
ok = 1;
} else {
printf("Invalid input, please enter a value lower then 256\n");
}
} while (!ok);
return (uint8_t)val;
}
/*
* Print HSL data
*/
static void print_hsl_data(const hsl_data *hsl) {
printf("\nHSL data:\n");
printf("H: %lf\n", hsl->h);
printf("S: %lf\n", hsl->s);
printf("L: %lf\n", hsl->l);
}
/*
* Print HSV data
*/
static void print_hsv_data(const hsv_data *hsv) {
printf("\nHSV data:\n");
printf("H: %lf\n", hsv->h);
printf("S: %lf\n", hsv->s);
printf("V: %lf\n", hsv->v);
}
/*
* Print RGB data
*/
static void print_rgb_data(const rgb_data *rgb) {
printf("\nRGB data:\n");
printf("R: %f\n", rgb->r);
printf("G: %f\n", rgb->g);
printf("B: %f\n", rgb->b);
}
/*
* HSL -> RGB
*/
static void test_hsl2rgb() {
printf("\nTesting hsl2rgb()\n");
hsl_data hsl;
rgb_data rgb;
hsl.h = get_double("H");
hsl.s = get_double("S");
hsl.l = get_double("L");
print_hsl_data(&hsl);
if (hsl2rgb(&hsl, &rgb)) {
print_rgb_data(&rgb);
} else {
printf("\nError: invalid HSL data.\n");
}
}
/*
* RGB -> HSL
*/
static void test_rgb2hsl() {
printf("\nTesting rgb2hsl()\n");
hsl_data hsl;
rgb_data rgb;
rgb.r = get_double("R");
rgb.g = get_double("G");
rgb.b = get_double("B");
print_rgb_data(&rgb);
rgb2hsl(&rgb, &hsl);
print_hsl_data(&hsl);
}
/*
* HSV -> RGB
*/
static void test_hsv2rgb() {
printf("\nTesting hsv2rgb()\n");
hsv_data hsv;
rgb_data rgb;
hsv.h = get_double("H");
hsv.s = get_double("S");
hsv.v = get_double("V");
print_hsv_data(&hsv);
if (hsv2rgb(&hsv, &rgb)) {
print_rgb_data(&rgb);
} else {
printf("\nError: invalid HSV data.\n");
}
}
/*
* RGB -> HSV
*/
static void test_rgb2hsv() {
printf("\nTesting rgb2hsv()\n");
hsv_data hsv;
rgb_data rgb;
rgb.r = get_double("R");
rgb.g = get_double("G");
rgb.b = get_double("B");
print_rgb_data(&rgb);
rgb2hsv(&rgb, &hsv);
print_hsv_data(&hsv);
}
int main() {
printf("\nTesting the 'color_conversion' library\n");
int repeat = 1;
while (repeat) {
printf("\nPossible choices:\n");
printf(" [1] Function hsl2rgb()\n");
printf(" [2] Function rgb2hsl()\n");
printf(" [3] Function hsv2rgb()\n");
printf(" [4] Function rgb2hsv()\n");
printf(" [Q] Exit\n");
switch (get_char()) {
case '1':
test_hsl2rgb();
break;
case '2':
test_rgb2hsl();
break;
case '3':
test_hsv2rgb();
break;
case '4':
test_rgb2hsv();
break;
case 'q':
case 'Q':
repeat = 0;
printf("Exit\n");
break;
default:
// do nothing
break;
}
}
return EXIT_SUCCESS;
}
|
C
|
// client.c - Example of TCP/IP Client using sockets
// COEN 4840
// 05-Feb-2020 - terminate client on message “exit” from server
// 15-Apr-2023 - terminate client after receiving any message from server
//
// See: https://www.geeksforgeeks.org/tcp-server-client-implementation-in-c/
//
// To compile: gcc -Wall -o client client.c -lc
//
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#define MAX 256
#define PORT 8080 // This client connects on port 8080
#define SA struct sockaddr
// Send message to server and wait for response
void say_hello(int sockfd)
{
char buff[MAX*3];
char myHost[MAX];
char myMessage[MAX];
char *username;
int status;
// Get username and local host name
username = getenv("USER");
gethostname(myHost, MAX);
// Get message
printf("Enter message to send to server: ");
fgets(myMessage, sizeof(myMessage), stdin);
myMessage[strlen(myMessage)-1] = 0; // get rid of the '/n' character
// Send message to server
sprintf( buff, "%s from %s on %s\n", myMessage, username, myHost);
write(sockfd, buff, sizeof(buff));
// Read response from server, timeout configured with setsockopt()
bzero(buff, sizeof(buff));
status = read(sockfd, buff, sizeof(buff));
if (status > 0)
{
printf("From Server : %s\n", buff);
}
else
{
printf("No response from Server.\n");
}
}
int main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in servaddr;
struct addrinfo hints, *infoptr;
struct addrinfo *p;
struct timeval tv;
char host[256];
// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // use AF_INET6 to force IPv6
hints.ai_socktype = SOCK_STREAM;
int result = getaddrinfo(argv[1], NULL, &hints, &infoptr);
if (result)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(result));
exit(1);
}
for (p = infoptr; p != NULL; p = p->ai_next)
{
getnameinfo(p->ai_addr, p->ai_addrlen, host, sizeof (host), NULL, 0, NI_NUMERICHOST);
}
freeaddrinfo(infoptr);
// socket create and varification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
// Set timeout for socket read
tv.tv_sec = 5; // timeout in seconds
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
// assign IP, PORT
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(host);
servaddr.sin_port = htons(PORT);
// connect the client socket to server socket
if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) {
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
// send message to server & wait for response
say_hello(sockfd);
// close the socket
close(sockfd);
}
|
C
|
/*
** Silberschatz Figure 3.27, modified 9/2010 by MCM to implement a simple pipe read process
** Compile/execute using the Windows Command Line C Compiler (cl)
**
*/
#include <stdio.h>
#include <windows.h>
#define BUFFER_SIZE 25
int main(VOID)
{
HANDLE ReadHandle,WriteHandle;
CHAR buffer[BUFFER_SIZE];
DWORD read,write;
fprintf(stderr,"Child Process Two Executing\n");
ReadHandle = GetStdHandle(STD_INPUT_HANDLE);
fprintf(stderr,"Child ready to read from pipe\n");
if (ReadFile(ReadHandle, buffer, BUFFER_SIZE, &read, NULL))
fprintf(stderr,"\nchild two read from pipe: %s\n",buffer);
else
fprintf(stderr,"Error Reading from Pipe in Child 2\n");
fprintf(stderr,"Child 2 Process done reading from pipe\n");
WriteHandle = GetStdHandle(STD_OUTPUT_HANDLE);
if (WriteFile(WriteHandle, buffer, BUFFER_SIZE,&write,NULL))
fprintf(stderr,"\nchild two wrote to pipe: %s\n",buffer);
else
fprintf(stderr,"Error reading from pipe in child 2\n");
fprintf(stderr, "Child 2 is done\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/* lib */
#include <avl.h>
#include <debug.h>
#include <timer.h>
#define ULONG_MAX (~0UL)
static void
avl_dump(avl_node *n, FILE *fp)
{
if (n) {
if (n->link[0])
fprintf(fp, "\t%ld -> %ld\n", n->key, n->link[0]->key);
if (n->link[1])
fprintf(fp, "\t%ld -> %ld\n", n->key, n->link[1]->key);
avl_dump(n->link[0], fp);
avl_dump(n->link[1], fp);
}
}
static void
avl_dump_to_file(avl_node *n, const char *file)
{
FILE *fp;
fp = fopen(file, "w");
if (fp) {
fprintf(fp, "digraph G\n{\n");
fprintf(fp, "node [shape=\"circle\"];\n");
avl_dump(n, fp);
fprintf(fp, "}\n");
fclose(fp);
}
}
static void
test_1()
{
avl_node *root = NULL;
int i, rv;
int input[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
/* int input[] = { 100, 20, 150, 6, 26, 27 }; */
/* int input[] = { 100, 20, 150, 6, 26, 25 }; */
/* int input[] = { 3769, 4163, 3465, 4143, 4396, 4011 }; */
/* int input[] = { 3769, 4163, 3465, 4143, 4396, 4144 }; */
for (i = 0; i < ARRAY_SIZE(input); i++) {
struct avl_node *n;
n = avl_alloc();
n->key = input[i];
rv = avl_insert(&root, n);
if (rv == 0)
fprintf(stdout, "'avl_insert()' error, %ld\n", n->key);
}
for (i = 0; i < ARRAY_SIZE(input); i++) {
struct avl_node *n;
n = avl_lookup(root, input[i]);
if (n) {
struct avl_node *l = n->link[0];
struct avl_node *r = n->link[1];
fprintf(stdout, "-> %ld { %ld, %ld } %d\n",
n->key, l ? l->key:-99, r ? r->key:-99, n->bf);
}
}
avl_dump_to_file(root, __func__);
}
void sort_array(unsigned long *array, unsigned long n)
{
unsigned long c, d, swap;
for (c = 0 ; c < n - 1; c++) {
for (d = 0 ; d < n - c - 1; d++) {
if (array[d] > array[d+1]) {
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
}
#include <pthread.h>
pthread_mutex_t lock;
static void
test_2()
{
struct avl_node *root = NULL;
unsigned int tree_size = 1000000;
unsigned long max_nsec, d, diff;
struct avl_node *array;
struct timespec a, b;
int i, ret;
(void) pthread_mutex_init(&lock, NULL);
array = calloc(tree_size, sizeof(struct avl_node));
srand(time(NULL));
for (i = 0, max_nsec = 0, d = 0; i < tree_size; i++) {
do {
array[i].key = (rand() % ULONG_MAX);
pthread_mutex_lock(&lock);
time_now(&a);
ret = avl_insert(&root, &array[i]);
time_now(&b);
pthread_mutex_unlock(&lock);
} while (!ret);
diff = time_diff(&a, &b);
d += diff;
if (diff > max_nsec)
max_nsec = diff;
}
/* average */
d = d / i;
fprintf(stdout, "insertion: %lu nano/s, %f micro/s, max: %lu nsec\n",
d, (float) d / 1000, max_nsec);
/* lookup */
for (i = 0, d = 0, max_nsec = 0; i < tree_size; i++) {
time_now(&a);
(void) avl_lookup(root, array[i].key);
time_now(&b);
diff = time_diff(&a, &b);
d += diff;
if (diff > max_nsec)
max_nsec = diff;
}
/* average */
d = d / i;
fprintf(stdout, "lookup: %lu nano/s, %f micro/s, max: %lu nsec\n",
d, (float) d / 1000, max_nsec);
/* avl_dump_to_file(root, __func__); */
}
/* gcc avltest.c -I ../../include/ -I../avltree/ ../libavl_fpic.a -lrt */
/* dot test_1 -Tpng -o image.png */
int main(int argc, char **argv)
{
/* test_1(); */
test_2();
return 0;
}
|
C
|
#ifndef __SPACE_H__
#define __SPACE_H__
#include "gf2d_shape.h"
#include "gf2d_body.h"
typedef struct
{
List *dynamicBodyList; /**<list of bodies in the space*/
List *staticShapes; /**<list of shapes that will collide that do not move*/
int precision; /**<number of backoff attempts before giving up*/
Rect bounds; /**<absolute bounds of the space*/
float timeStep; /**<how much each iteration of the simulation progresses time by*/
Vector2D gravity; /**<global gravity pull direction*/
float dampening; /**<rate of movement degrade ambient frictions*/
float slop; /**<how much to correct for body overlap*/
Uint32 idpool;
}Space;
/**
* @brief create a new space
* @return NULL on error or a new empty space
*/
Space *gf2d_space_new();
/**
* @brief create a new space and set some defaults
* @param precision number of retry attempts when movement collides
* @param bounds the absolute bounds of the space
* @param timeStep this should be fraction that can add up to 1. ie: 0.1 or 0.01, etc
* @param gravity the direction that gravity pulls
* @param dampening the rate of all movemement decay
* @param slop how much to correct for body overlap
*/
Space *gf2d_space_new_full(
int precision,
Rect bounds,
float timeStep,
Vector2D gravity,
float dampening,
float slop);
/**
* @brief cleans up a space
*/
void gf2d_space_free(Space *space);
/**
* @brief visualize the space and its contents
* @param space the space to draw
* @param offset a positional offset applied when drawing.
*/
void gf2d_space_draw(Space *space,Vector2D offset);
/**
* @brief add a body to the space simulation
* @param space the space to add a body to
* @param body the body to add to the space
* @note the space will not free the body, but do not until it has been removed from the space
*/
void gf2d_space_add_body(Space *space,Body *body);
/**
* @brief removes a body from the space
* @note this should not be done DURING a space update
* @param space the space to remove the body from
* @param body the body to remove
*/
void gf2d_space_remove_body(Space *space,Body *body);
/**
* @brief add a statuc shape to the space
* @note the shape parameters need to be in absolute space, not relative to any body
* @param space the space to add to
* @param shape the shape to add.
*/
void gf2d_space_add_static_shape(Space *space,Shape shape);
/**
* @brief update the bodies in the physics space for one time slice
* @param space the space to be updated
*/
void gf2d_space_update(Space *space);
/**
* @brief attempt to fix any bodies that are overlapping static shapes or clipping the space bounds
* @param space the space to update
* @param tries the number of tries to get everything clear before giving up
*/
void gf2d_space_fix_overlaps(Space *space,Uint8 tries);
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* errors.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: csphilli <csphilli@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/02 11:46:01 by csphilli #+# #+# */
/* Updated: 2021/03/03 12:47:40 by csphilli ### ########.fr */
/* */
/* ************************************************************************** */
#include "asm.h"
void ft_error_line(char *error_msg, int line)
{
write(2, error_msg, ft_strlen(error_msg));
ft_putnbr_fd(line, 2);
write(2, ".\n", 2);
exit(1);
}
void label_not_found(char *error_msg, t_ins *node, char *label)
{
ft_putendl_fd(error_msg, 2);
ft_putstr_fd("Label '", 2);
ft_putstr_fd(label, 2);
ft_putstr_fd("' not found. Error on line ", 2);
ft_putnbr_fd(node->line, 2);
write(2, "\n", 1);
exit(1);
}
void error_arg_type(t_master *m, char *line)
{
ft_putstr_fd("ERROR: Invalid argument \'", 2);
ft_putstr_fd(line, 2);
ft_putstr_fd("\' found on line ", 2);
ft_putnbr_fd(m->line_cnt, 2);
ft_putendl_fd(".", 2);
exit(1);
}
|
C
|
/*
* json_tools.c
*
* Created on: Oct 19, 2018
* Author: zzz
*/
#include "cJSON.h"
#include "libov/ov_macros.h"
#include "libov/ov_ov.h"
#include "string.h"
#include "ovunity_helper.h"
OV_DLLFNCEXPORT cJSON* cJSON_ParseFromFile(OV_STRING path) {
OV_STRING jsonStr = ovunity_helper_data2str(path);
cJSON* tmp = cJSON_Parse(jsonStr);
Ov_HeapFree(jsonStr);
return tmp;
}
OV_DLLFNCEXPORT int cJSON_isSame(cJSON* file1, cJSON* file2) {
cJSON* child1 = NULL;
cJSON* child2 = NULL;
int same = 0;
int i = 0;
cJSON* jstmp = NULL;
for(child1 = (file1 != ((void*)0)) ? (file1)->child : ((void*)0);
child1 != ((void*)0);) {
same = 0;
if(child1->string)
child2 = cJSON_GetObjectItem(file2, child1->string);
else
child2 = cJSON_GetArrayItem(file2, i);
if(!child2 || child2->type != child1->type) {
// todo: error
child1 = child1->next;
continue;
}
switch(child1->type) {
case cJSON_Invalid:
if(cJSON_IsInvalid(child2)) same = 1;
break;
case cJSON_False:
if(cJSON_IsFalse(child2)) same = 1;
break;
case cJSON_True:
if(cJSON_IsTrue(child2)) same = 1;
break;
case cJSON_NULL:
if(cJSON_IsNull(child2)) same = 1;
break;
case cJSON_Number:
if(child1->valuedouble == child2->valuedouble) same = 1;
break;
case cJSON_String:
if(!strcmp(child1->valuestring, child2->valuestring)) same = 1;
break;
case cJSON_Array:
same = cJSON_isSame(child1, child2);
if(same == -1) { // todo info
};
break;
case cJSON_Object:
same = cJSON_isSame(child1, child2);
if(same == -1) { // todo info
};
break;
case cJSON_Raw:
if(cJSON_IsRaw(child2)) same = 1;
break;
default:
// todo: error
return -1;
}
if(same) {
if(child1->string) {
jstmp = child1->prev;
cJSON_DeleteItemFromObject(file1, child1->string);
child1 = jstmp ? jstmp : file1->child;
jstmp = child2->prev;
cJSON_DeleteItemFromObject(file2, child2->string);
child2 = jstmp ? jstmp : file2->child;
} else {
jstmp = child1->prev;
cJSON_DeleteItemFromArray(file1, i);
child1 = jstmp ? jstmp : file1->child;
jstmp = child2->prev;
cJSON_DeleteItemFromArray(file2, i);
child2 = jstmp ? jstmp : file2->child;
}
} else {
child1 = child1->next;
i++;
}
}
if(cJSON_GetArraySize(file1) || cJSON_GetArraySize(file2)) return 0;
return 1;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* tools.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tberthie <tberthie@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/02/21 00:51:09 by tberthie #+# #+# */
/* Updated: 2017/09/29 18:08:45 by tberthie ### ########.fr */
/* */
/* ************************************************************************** */
#include "tools.h"
#include <stdlib.h>
#include <unistd.h>
static void get_max(t_stack *a, t_stack *b, int *max)
{
int tmp;
int i;
max[0] = 1;
i = 0;
while (i < a->size)
if ((tmp = ft_intlen(a->stack[i++])) > max[0])
max[0] = tmp;
max[1] = 1;
i = 0;
while (i < b->size)
if ((tmp = ft_intlen(b->stack[i++])) > max[1])
max[1] = tmp;
}
static void fill(int len)
{
while (len-- > 0)
write(1, " ", 1);
}
void display(t_stack *a, t_stack *b)
{
int size;
int i;
int max[2];
get_max(a, b, max);
size = a->size > b->size ? a->size : b->size;
i = 0;
ft_putstr("\x1b[32mA");
fill(max[0]);
ft_putstr("B\x1b[0m\n");
while (i < size)
{
if (a->size > i)
{
ft_putnbr(a->stack[i]);
fill(max[0] - ft_intlen(a->stack[i]) + 1);
}
else
fill(max[0] + 1);
if (b->size > i)
ft_putnbr(b->stack[i]);
ft_putchar('\n');
i++;
}
ft_putstr("\x1b[33m\n");
}
char check_nbr(char *str, int *dst, t_stack *a)
{
char *tmp;
char neg;
int i;
*dst = 0;
neg = *str == '-' ? -1 : 1;
if (!str[(i = *str == '-')])
return (0);
while (str[i] <= '9' && str[i] >= '0')
*dst += *dst * 9 + str[i++] - '0';
*dst *= neg;
if (!i || ft_strcmp(str, (tmp = ft_itoa(*dst))))
return (0);
free(tmp);
i = 0;
while (i < a->size)
if (a->stack[i++] == *dst)
return (0);
return (1);
}
char check(t_stack *a, t_stack *b)
{
int size;
size = a->size;
if (b->size)
return (0);
while (size-- > 1)
if (a->stack[size] < a->stack[size - 1])
return (0);
return (1);
}
|
C
|
/* #include
*
* L.ECC - FEUP / PRO - L.EEC004
*
* Exemplo da utilização de apontadores com registos
*
* Compilar: clang ponto.c -o ponto
* Executar: ./ponto
*/
#include <stdio.h>
typedef struct {
float x, y;
} ponto;
void lerPonto( ponto *p);
void escreverPonto( ponto p);
main(){
ponto p;
while (1){
lerPonto(&p);
if(p.x==0 && p.y==0) break;
escreverPonto(p);
}
}
void lerPonto( ponto *p){
printf("x= "); scanf("%f", &p->x);
printf("y= "); scanf("%f", &p->y);
}
void escreverPonto( ponto p){
printf(" (%2.2f, %2.2f) \n", p.x, p.y);
}
|
C
|
#include "stm32f4xx.h"
static uint32_t fam_nus = 0;
static uint32_t fam_nms = 0;
/*******************************
ܣʱʼ
ֵ
*******************************/
void Delay_Init(void)
{
//رռʱжϡʱΪAHB/8
SysTick->CTRL = 0x0;
fam_nus = SystemCoreClock/8000000;
fam_nms = fam_nus * 1000;
SysTick->VAL = 0;
}
/*******************************
ܣʱ
ctr
ֵ
*******************************/
void Delay_Us(uint16_t ctr)
{
uint32_t Tick_Flag = 0;
SysTick->LOAD = ctr*fam_nus;
SysTick->VAL = 0;
SysTick->CTRL |= 0x01;
do
{
Tick_Flag = SysTick->CTRL;
}
while(!(Tick_Flag&(1<<16)) && (Tick_Flag&0x01));
SysTick->CTRL = 0x00;
}
/*******************************
ܣʱ
ctr
ֵ
*******************************/
void Delay_Ms(uint16_t ctr)
{
uint32_t Tick_Flag = 0;
SysTick->LOAD = ctr * fam_nms;
SysTick->VAL = 0;
SysTick->CTRL = 0x01;
do
{
Tick_Flag = SysTick->CTRL;
}
while(!(Tick_Flag & (1<<16)) && (Tick_Flag & 0x01));
SysTick->CTRL = 0x00;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.