language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/*
Dynamic Queue
*/
#pragma once
//#define kDefaultDataBufferSize (100*1024)
//#define kDefaultSizeBufferSize (100*8)
typedef void * queuePtr;
/********************************************
to create a new queue
returns a pointer to an allocated queue
or NULL if can't allocate memory
*/
queuePtr
queueCreate ();
/********************************************
to create a new queue
returns a pointer to an allocated queue
or NULL if can't allocate memory
this version allows creation of a queue at a specific size. the
size of the buffer that will be created is numElements * elementSize.
The size of the size buffer will be numElements * sizeof(SizeType)
*/
queuePtr
queueCreateWithSize ( unsigned int numElements, unsigned int elementSize );
/********************************************
to destroy a queue that you have previously created
given a previously allocated queue
returns a 1 if good, 0 if failed
*/
int
queueDestroy (queuePtr queue);
/********************************************
to place an event onto the end of the queue
given a queue, a pointer to memory and a length
returns a 1 if added, 0 if failed
if you get a 0 then the current data in the queue
is still good
*/
int
queuePush (queuePtr queue, char * pointer, unsigned int length, unsigned int type);
/********************************************
pops an event from the queue, last in first out
give a queue, a pointer to a block, a pointer to a length, and a pointer to a type
returns a 1 if was able to pop, 0 if failed
pointer is pointed at beginning of block to send, or NULL if error
*/
int
queuePopLIFO (queuePtr queue, char ** pointer, unsigned int * length, unsigned int * type);
/********************************************
pops an event from the queue, first in first out
give a queue, a pointer to a block, a pointer to a length, and a pointer to a type
returns a 1 if was able to pop, 0 if failed
pointer is pointed at beginning of block to send, or NULL if error
*/
int
queuePopFIFO (queuePtr queue, char ** pointer, unsigned int * length, unsigned int * type);
/********************************************
undo the previous pop
to do a peek you must first Pop and then PopUndo
given a queue
return 0 if we can't undo the last pop
return 1 if we were able to undo the last pop
Only backs up 1 event.
Not valid after a Push.
*/
int
queuePopUndo (queuePtr queue);
/********************************************
to clear the queue
given a queue, reset all internal pointers to empty state
return a 0 if a NULL object
return a 1 if succeeded
*/
int
queueClear (queuePtr queue);
/********************************************
to get the number of entries in a Q
given a queue
return current number of entries.
*/
unsigned int
queueCountEntries (queuePtr queue);
/********************************************
to get the size of a queue
given a queue
return current allocated size
*/
unsigned int
queueGetSize (queuePtr queue);
/********************************************
to get the count of the times that we have pushed into the queue
given a queue
return the count
*/
unsigned int
queueCountPushes (queuePtr queue);
/********************************************
to get the count of the times popLIFO was successfully called.
given a queue
return the count
*/
unsigned int
queueCountPopLIFO (queuePtr queue);
/********************************************
to get the count of the times PopFIFO was successfully called.
given a queue
return the count
*/
unsigned int
queueCountPopFIFO (queuePtr queue);
/********************************************
to resize the internal data sizes to the given amount
given a queue, a pointer to memory and a length
returns a 1 if succeed, 0 if failed
*/
int
queueResize (queuePtr queue, unsigned int entryLength, unsigned int bufferLength);
int
queueMark(queuePtr queue);
int
queueRewindToMark(queuePtr queue);
|
C
|
#include<stdio.h>
struct info
{
int id_no;
char name[20];
char addr[20];
int age;
};
struct info std[50];
void main()
{
int i,n;
printf("Enter the Number of Student:");
scanf("%d", &n);
//printf("Enter ID,NAME,ADDRESS and AGE:");
for(i=0;i<n;i++)
{
printf("Now Enter student ID:");
scanf("%d", &std[i].id_no);
printf("Enter name of Student:");
scanf("%s", &std[i].name);
printf("Enter Address of Student:");
scanf("%s", &std[i].addr);
printf("Enter age of Student:");
scanf("%d", &std[i].age);
//scanf("%d%s%s%d", &std[i].id_no,std[i].name,std[i].addr,std[i].age);
}
printf("Student Information:\n");
for(i=0;i<n;i++)
{
printf("%d\t%s\t%s\t%d\n", &std[i].id_no,std[i].name,std[i].addr,std[i].age);
}
}
|
C
|
#include <stdio.h>
extern void writescr(int ,int, char *);
extern void pmWriteScr(int,int,char *);
void clearscreen(int);
void writeln(char *);
extern void gdt_flush(int,int ,int ,int ,int,int);
extern void schedule();
void enqueue();
void pmWriteln(int,int);
void createProcess(unsigned int ,unsigned int, unsigned int, unsigned int ,unsigned int);
unsigned int *allocStack();
struct PCB {
unsigned int esp;
unsigned int ss;
};
extern void go(struct PCB *);
//Queue Functions
void p1();
void p2();
void p3();
void p4();
void p5();
void p6();
void p7();
void p8();
void p9();
void p10();
int size=10;
int rear=0;
int front=0;
struct PCB *q[11];
int ch;
/* The En-Queue Function */
void enqueue(struct PCB *pcb)
{
rear = (rear + 1) % 11;
q[rear] = pcb;
}
/* The D-Queue Function */
struct PCB *dequeue()
{
struct PCB* ret;
front = (front + 1) % 11;
ret = q[front];
return ret;
}
/* Define GDT entry */
struct gdt_entry
{
unsigned short limit_low;
unsigned short base_low; /* Base value goes to three different direction */
unsigned char base_middle;
unsigned char access;
unsigned char attributes;
unsigned char base_high;
} __attribute__((packed));
struct gdt_ptr
{
unsigned short limit;
unsigned int base;
}__attribute__((packed));
extern void _linker(struct gdt_ptr *);
struct gdt_entry gdt[5]; /*GDT with 5 entry*/
struct gdt_ptr gp; /* GDT pointer */
/* Descriptor in the Global Descriptor Table */
void initGDTEntry(int index, unsigned long base , unsigned long limit, unsigned char access,
unsigned char attributes)
{
/*descriptor base address */
gdt[index].base_low =(base& 0xFFFF);
gdt[index].base_middle=(base>>16) & 0xFF;
gdt[index].base_high=(base>>24) & 0xFF;
/* Descriptor Limits */
gdt[index].limit_low =(limit & 0xFFFF);
gdt[index].attributes=((limit >>16)& 0x0F);
gdt[index].attributes |=(attributes & 0xF0);
gdt[index].access = access;
}
void gdt_install()
{
/* setup the GDT pointer and limit */
gp.limit=(sizeof(struct gdt_entry)*5)-1;
gp.base= (unsigned int)gdt;
/* NULL descriptor */
initGDTEntry(0,0,0,0,0);
/* Code Segment Descriptor , limit 4GB,granularity 4Kb,
32bit opcode*/
/*gdt_set_gate(num,base,limit,access,gran)*/
initGDTEntry(1,0,640*1024-1,0x9A,0x40);
/* Data Segment */
initGDTEntry(2,0,640*1024-1,0x92,0x40);
/* stack segment*/
initGDTEntry(3,0,640*1024-1,0x92,0x40);
/* video segment */
initGDTEntry(4,0xb8000,0xF9F,0x92,0x40); /* F9F hex value of 80*25*2-1*/
/* Flush old GDT*/
_linker(&gp);
gdt_flush(8,16,24,16,16,32); /* 1x8 for CS
(2x8) for DS
(3x8) for SS
4x8 for es */
}
void p1()
{
int i=0;
char *msg;
msg="Process P1: 0";
while(1)
{
i=(i+1)%10;
msg[12] = '0' + i;
writescr(5,0,msg);
schedule();
}
}
void p2()
{
int i=0;
char *msg;
msg="Process P2: 0";
while(1)
{
i=(i+1)%10;
msg[12] = '0' + i;
writescr(6,0,msg);
schedule();
}
}
void p3()
{
int i=0;
char *msg;
msg="Process P3: 0";
while(1)
{
i=(i+1)%10;
msg[12] = '0' + i;
writescr(7,0,msg);
schedule();
}
}
void p4()
{
int i=0;
char *msg;
msg="Process P4: 0";
while(1)
{
i=(i+1)%10;
msg[12] = '0' + i;
writescr(8,0,msg);
schedule();
}
}
void p5()
{
int i=0;
char *msg;
msg="Process P5: 0";
while(1)
{
i=(i+1)%10;
msg[12] = '0' + i;
writescr(9,0,msg);
schedule();
}
}
void p6()
{
int i=0;
char *msg;
msg="Process P6: 0";
while(1)
{
i=(i+1)%10;
msg[12] = '0' + i;
writescr(10,0,msg);
schedule();
}
}
void p7()
{
int i=0;
char *msg;
msg="Process P7: 0";
while(1)
{
i=(i+1)%10;
msg[12] = '0' + i;
writescr(11,0,msg);
schedule();
}
}
void p8()
{
int i=0;
char *msg;
msg="Process P8: 0";
while(1)
{
i=(i+1)%10;
msg[12] = '0' + i;
writescr(12,0,msg);
schedule();
}
}
void p9()
{
int i=0;
char *msg;
msg="Process P9: 0";
while(1)
{
i=(i+1)%10;
msg[12] = '0' + i;
writescr(13,0,msg);
schedule();
}
}
void p10()
{
int i=0;
char *msg;
msg="Process P10:0";
while(1)
{
i=(i+1)%10;
msg[12] = '0' + i;
writescr(14,0,msg);
schedule();
}
}
int row=0;
int nextstack =0;
unsigned int mystacks [10][1024];
unsigned int *allocStack()
{
return mystacks[nextstack++];
}
struct PCB PCBs[10];
struct PCB *current;
struct PCB *pcb;
//struct pcb *dequeue();
int next_pcb = 0;
struct PCB *allocatePCB()
{
return &(PCBs[next_pcb++]);
};
void createProcess (unsigned int ds,unsigned int ss, unsigned int stackTop, unsigned int cs ,
unsigned int processEntry)
{
unsigned int *st;
st= (unsigned int *) stackTop;
st=st-1;
*st=0x0000;
st=st-1;
*st=cs;
st=st-1;
*st=processEntry;
st = st - 1;
*st = 0; //ebp
st=st-1;
*st=0; //esp
st=st-1;
*st=0; //edi
st=st-1;
*st=0; //esi
st=st-1;
*st=0; //edx
st=st-1;
*st=0; //ecx
st=st-1;
*st=0; // ebx
st=st-1;
*st=0; // eax
st=st-1;
*st=ds; //ds
st=st-1;
*st=ds; //es
st=st-1;
*st=ds; //fs
st=st-1;
*st=ds; //gs
pcb=allocatePCB();
pcb->ss=ss;
pcb->esp= (unsigned int) st;
enqueue(pcb);
}
void writeln (char *s)
{
int col=1;
writescr(row,col,s);
col++;
row++;
}
/* Clear the Screen */
void clearscreen(int line)
{
int i=line;
while(i >= 0)
{
writescr(i,0," ");
i++;
if(i>25)
return;
}
}
/* This one used to fill the screen with * in protected mood */
void pmWriteln(int row,int seg)
{
int j=row;
while (j>0)
{
pmWriteScr(j,seg,"********************************************************************************");
j++;
if(j>25)
return;
}
}
int main(void)
{
int line =0;
unsigned int *s;
int wCol=5;
clearscreen(line);
writeln("Initializing OS");
writeln("Setting up OS descriptor...");
gdt_install();
pmWriteScr(wCol,32," done");
wCol++;
pmWriteln(wCol,32);
/*while(1);*/
//program3 starts here
clearscreen(0);
writeln("Running Ten processes");
front = rear = 0;
next_pcb = 0;
nextstack = 0;
s=allocStack(); // Allocating stack
createProcess((unsigned int)16,(unsigned int) 24,(unsigned int) (s+1024),(unsigned int ) 8,(unsigned int) p1);
s=allocStack();
createProcess((unsigned int)16,(unsigned int) 24,(unsigned int) (s+1024),(unsigned int ) 8,(unsigned int) p2);
/*
s=allocStack();
createProcess((unsigned int)16,(unsigned int) 24,(unsigned int) (s+1024),(unsigned int ) 8,(unsigned int) p3);
s=allocStack();
createProcess((unsigned int)16,(unsigned int) 24,(unsigned int) (s+1024),(unsigned int ) 8,(unsigned int) p4);
s=allocStack();
createProcess((unsigned int)16,(unsigned int) 24,(unsigned int) (s+1024),(unsigned int ) 8,(unsigned int) p5);
s=allocStack();
createProcess((unsigned int)16,(unsigned int) 24,(unsigned int) (s+1024),(unsigned int ) 8,(unsigned int) p6);
s=allocStack();
createProcess((unsigned int)16,(unsigned int) 24,(unsigned int) (s+1024),(unsigned int ) 8,(unsigned int) p7);
s=allocStack();
createProcess((unsigned int)16,(unsigned int) 24,(unsigned int) (s+1024),(unsigned int ) 8,(unsigned int) p8);
s=allocStack();
createProcess((unsigned int)16,(unsigned int) 24,(unsigned int) (s+1024),(unsigned int ) 8,(unsigned int) p9);
s=allocStack();
createProcess((unsigned int)16,(unsigned int) 24,(unsigned int) (s+1024),(unsigned int ) 8,(unsigned int) p10);
*/
current = dequeue();
go(current);
while(1);
return 0;
} /*Main ends Here */
|
C
|
#include <stdio.h>
main(argc, argv)
int argc;
char *argv[];
{
char c;
while ((c = getchar()) != EOF) {
if (c == '`') {
processParam(argc, argv);
} else {
if (c == '\\') {
c = getchar();
if (c != '`')
putchar('\\');
}
putchar(c);
}
}
}
processParam(argc, argv)
int argc;
char *argv[];
{
int offset;
offset = scanNumber();
if (argc <= offset)
fprintf(stderr, "param: offset %d out of range\n", offset);
else if (offset == 0)
printf("`");
else
printf("%s", argv[offset]);
}
int
scanNumber()
{
char c;
int result;
c = getchar();
if (c == 'w' || c == 'W')
return(1);
else if (c == 'n' || c == 'N')
return(2);
else if (c == 'e' || c == 'E')
return(3);
else if (c == 's' || c == 'S')
return(4);
else if (c == 'r' || c == 'R')
return(5);
result = 0;
while ('0' <= c && c <= '9') {
result = result * 10 + c - '0';
c = getchar();
}
ungetc(c, stdin);
if (result == 0)
return(0);
else
return(result + 5);
}
|
C
|
//Nick Vilimek
#include <stdio.h>
#include <string.h>
int main ( int argc, char* argv[] ){
char* cmd;
char buffer[200];
char* strippedNewline;
fgets(buffer,200,stdin);
strippedNewline = strtok(buffer,"\n");
while(cmd != NULL){
printf("%s\n", cmd);
cmd = strtok(NULL,",");
}
/*
int max_args = 15;
int max_argv_size = max_args + 2;
char* cmd;
char* my_argv[max_argv_size];
char* remainingArgv;
cmd = strtok(strippedNewline," ");
my_argv[0] = cmd;
int i;
for(i=1;i<max_argv_size;i++){
remainingArgv = strtok(NULL," ");
if(remainingArgv == NULL){
my_argv[i] = '\0';
break;
}
my_argv[i] = remainingArgv;
}
execvp( cmd, my_argv );
*/
return 0;
}
|
C
|
#include "chat_client.h"
int setUpUDPServer(int *socketd,struct sockaddr_in *address_info, int port) {
if ( (*socketd = socket(AF_INET, SOCK_DGRAM, 0))==-1 ) {//socket client gia epikoinonia me ton allo client
printf("\nSocket creation failure %d\n",errno); //
perror("Socket");
return 1;
}
/*
Apofasisame oti to port gia epikoinonia metaksi 2 clients that ine to epomeno aftou pou xrisimopoiithike
gia epikoinonia me ton TCP server
*/
memset( address_info,0,sizeof(*address_info) );
address_info->sin_family = AF_INET;
address_info->sin_addr.s_addr = htonl(INADDR_ANY);
INC_PORT:
++port;
address_info->sin_port = htons(port);
if ( bind(*socketd,(struct sockaddr*)address_info,sizeof(*address_info))==-1 ) {
if ( errno != EADDRINUSE ) {
printf("\nServer bind failure %d\n",errno);
perror("Server:");
return -1;
}
else {
printf("\nServer bind failure %d\n",errno);
perror("Server:");
printf("Increasing Port Number");
goto INC_PORT;
}
}
return 0;
}
|
C
|
#include "ocilib.h"
/* requires script demo/number.sql */
void err_handler(OCI_Error *err)
{
printf("%s\n", OCI_ErrorGetString(err));
}
int main(void)
{
OCI_Connection *cn = NULL;
OCI_Statement *st = NULL;
OCI_Resultset *rs = NULL;
OCI_TypeInfo *tc = NULL;
OCI_TypeInfo *to = NULL;
OCI_Number *nm = NULL;
OCI_Coll *cl = NULL;
OCI_Elem *el = NULL;
OCI_Object *ob = NULL;
OCI_Number *no = NULL;
OCI_Number *nt = NULL;
OCI_Number **ar = NULL;
unsigned int i, n;
otext buf[128] = "";
if (!OCI_Initialize(err_handler, NULL, OCI_ENV_DEFAULT))
{
return EXIT_FAILURE;
}
cn = OCI_ConnectionCreate("db", "usr", "pwd", OCI_SESSION_DEFAULT);
st = OCI_StatementCreate(cn);
tc = OCI_TypeInfoGet(cn, "test_num_coll_t", OCI_TIF_TYPE);
to = OCI_TypeInfoGet(cn, "test_num_t", OCI_TIF_TYPE);
cl = OCI_CollCreate(tc);
ob = OCI_ObjectCreate(cn, to);
el = OCI_ElemCreate(tc);
nm = OCI_NumberCreate(cn);
ar = OCI_NumberArrayCreate(cn, 5);
// Testing fetching numbers (as number and using implicit conversion number to string)
OCI_Prepare(st, "select value from test_number");
OCI_Execute(st);
rs = OCI_GetResultset(st);
while (OCI_FetchNext(rs))
{
OCI_Number *n = OCI_GetNumber(rs, 1);
const otext *s = OCI_GetString(rs, 1);
OCI_NumberToText(n, NULL, sizeof(buf), buf);
printf("%s - %s\n", buf, s);
}
// Testing binding external single number
OCI_Prepare(st, "begin :1 := :1 *2 ; end;");
OCI_BindNumber(st, ":1", nm);
OCI_NumberFromText(nm, "1234.4321", NULL);
OCI_Execute(st);
OCI_NumberToText(nm, NULL, sizeof(buf), buf);
printf("%s\n", buf);
// Testing binding internal single number
OCI_Prepare(st, "begin :1 := :1 *2 ; end;");
OCI_SetBindAllocation(st, OCI_BAM_INTERNAL);
OCI_BindNumber(st, ":1", NULL);
nt = OCI_BindGetData(OCI_GetBind(st, 1));
OCI_NumberFromText(nt, "1234.4321", NULL);
OCI_Execute(st);
OCI_NumberToText(nt, NULL, sizeof(buf), buf);
printf("%s\n", buf);
OCI_SetBindAllocation(st, OCI_BAM_EXTERNAL);
// Testing registering number for a returning into statement
OCI_Prepare(st, "update test_number set value = value *2 returning value into :1");
OCI_RegisterNumber(st, ":1");
OCI_Execute(st);
rs = OCI_GetResultset(st);
while (OCI_FetchNext(rs))
{
printf("%s\n", OCI_GetString(rs, 1));
}
// testing Collections
OCI_NumberFromText(nm, "1111.2222", NULL);
OCI_ElemSetNumber(el, nm);
OCI_CollAppend(cl, el);
OCI_NumberFromText(nm, "3333.4444", NULL);
OCI_ElemSetNumber(el, nm);
OCI_CollAppend(cl, el);
printf("%d\n", OCI_CollGetCount(cl));
for (i = 1, n = OCI_CollGetCount(cl); i <= n; i++)
{
OCI_Elem *e = OCI_CollGetElem(cl, i);
OCI_Number *n = OCI_ElemGetNumber(e);
OCI_NumberToText(n, NULL, sizeof(buf), buf);
printf("%s\n", buf);
}
// Testing objects
OCI_NumberFromText(nm, "5555.6666", NULL);
OCI_NumberToText(nm, NULL, sizeof(buf), buf);
printf("%s\n", buf);
OCI_ObjectSetNumber(ob, "value", nm);
no = OCI_ObjectGetNumber(ob, "value");
OCI_NumberToText(no, NULL, sizeof(buf), buf);
printf("%s\n", buf);
// Testing fetching infinite values to string
OCI_Prepare(st, "SELECT utl_raw.cast_to_number('FF65'), utl_raw.cast_to_number('00') from dual");
OCI_Execute(st);
rs = OCI_GetResultset(st);
while (OCI_FetchNext(rs))
{
printf("pos infinite = [%s]\n", OCI_GetString(rs, 1));
printf("neg infinite = [%s]\n", OCI_GetString(rs, 2));
}
// Testing array of numbers
OCI_NumberFromText(ar[0], "1.2", NULL);
OCI_NumberFromText(ar[1], "~", NULL);
OCI_NumberFromText(ar[2], "5.6", NULL);
OCI_NumberFromText(ar[3], "-~", NULL);
OCI_NumberFromText(ar[4], "9.2", NULL);
OCI_NumberToText(ar[0], NULL, sizeof(buf), buf);
printf("%s\n", buf);
OCI_NumberToText(ar[1], NULL, sizeof(buf), buf);
printf("%s\n", buf);
OCI_NumberToText(ar[2], NULL, sizeof(buf), buf);
printf("%s\n", buf);
OCI_NumberToText(ar[3], NULL, sizeof(buf), buf);
printf("%s\n", buf);
OCI_NumberToText(ar[4], NULL, sizeof(buf), buf);
printf("%s\n", buf);
OCI_NumberArrayFree(ar);
OCI_NumberFree(nm);
OCI_ElemFree(el);
OCI_CollFree(cl);
OCI_ObjectFree(ob);
OCI_StatementFree(st);
OCI_ConnectionFree(cn);
OCI_Cleanup();
return EXIT_SUCCESS;
}
|
C
|
#include "a4.h"
#include <stdio.h>
#include <stdlib.h>
PPM_IMAGE *read_ppm(const char *file_name){
FILE *read_file;
read_file = fopen(file_name, "r");
unsigned char a,b;
int w, h, m_color;
int red, green, blue;
fscanf(read_file, "%c%c", &a, &b);
fscanf(read_file, "%d", &w);
fscanf(read_file, "%d", &h);
fscanf(read_file, "%d", &m_color);
PPM_IMAGE *copy_img;
copy_img = (PPM_IMAGE *)malloc(sizeof(PPM_IMAGE));
copy_img->width = w;
copy_img->height = h;
copy_img->max_color = m_color;
copy_img->data = (PIXEL *)malloc((w*h)*(sizeof(PIXEL)));
for(int i = 0; i < w*h; i++){
fscanf(read_file, "%d", &red);
fscanf(read_file, "%d", &green);
fscanf(read_file, "%d", &blue);
copy_img->data[i].r = red;
copy_img->data[i].g = green;
copy_img->data[i].b = blue;
}
fclose(read_file);
return copy_img;
}
void write_ppm(const char *file_name , const PPM_IMAGE *image){
FILE *write_file;
int increment = 0;
write_file = fopen(file_name, "w");
fprintf(write_file, "P3\n");
fprintf(write_file, "%d %d\n", image->width, image->height);
fprintf(write_file, "%d\n", image->max_color);
for(int i = 0; i < image->height; i++){
for(int j = 0; j < image->width; j++){
fprintf(write_file, "%d ", image->data[increment].r);
fprintf(write_file, "%d ", image->data[increment].g);
fprintf(write_file, "%d ", image->data[increment].b);
increment++;
}
fprintf(write_file, "\n");
}
fclose(write_file);
}
|
C
|
#include<stdio.h>
int main()
{
int n,i,f,s,d;
printf("Enter howmany rows:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d %d",&f,&s);
printf("%d\t%d\n",f,s);
d=f-s;
printf("difference is %d",d);
}
return 0;
}
|
C
|
/********************************************************************************
* File: misc.c
* Date: 2002-09-24
* Author: Alain Girardet/Dominik Blunk
* Last Modified: 2002-10-24
*
* Description: Misc functions
*
*
* 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 2 of the License, or (at your option) any later
* version. See http://www.fsf.org/copyleft/gpl.txt.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
********************************************************************************/
#include <sys/time.h>
#include <stdio.h>
#include "wepattack.h"
#include "config.h"
#include "misc.h"
double difftime_us(struct timeval *time_start, struct timeval *time_end) {
double ret_time;
ret_time = ((double)(time_end->tv_usec) / 1000000);
ret_time += ((double)time_end->tv_sec);
ret_time -= ((double)(time_start->tv_usec) / 1000000);
ret_time -= (double)(time_start->tv_sec);
return ret_time;
}
void show_help() {
fprintf(stdout,"WEPATTACK by Dominik Blunk and Alain ");
fprintf(stdout,"Girardet - Version %s\n", VERSION);
fprintf(stdout,"\nusage: wepattack -f dumpfile [-w wordfile]");
fprintf(stdout, " [-m mode] [-n network]\n");
fprintf(stdout,"-f dumpfile \tnetwork dumpfile to read\n");
fprintf(stdout,"\t\t(in PCAP format as TCPDUMP or ETHEREAL uses)\n");
fprintf(stdout,"-w wordlist \twordlist to use (default: stdin)\n");
fprintf(stdout,"-m mode \trun wepattack in diffente modes (default: all)\n");
fprintf(stdout,"\t\tvalues: 64, 128, n64, n128\n");
fprintf(stdout,"-n network \tnetwork number to attack\n");
fprintf(stdout,"-? \t\tShows this help\n\n");
}
void wlan_key_cracked() {
// write result to logfile
log_bssid(current_packet);
// display information on screen
printf("\n++++++++++ Packet decrypted! ++++++++++\n");
// display bssid and key
printf("BSSID: ");
print_hex_array(stdout, current_packet->frame.bssid,6);
printf("/ Key %d", current_packet->frame.key);
// display wepkey
printf("\tWepKey: ");
print_hex_array(stdout, current_packet->secret,
current_packet->encryption&0x0F);
if ((current_packet->encryption&0x60) == MODE_WEP)
printf("(%s)", current_packet->secret);
else if ((current_packet->encryption&0x60) == MODE_KEYGEN)
printf("(%s)", current_packet->nwep_secret);
// display encryption
printf("\nEncryption: %d Bit", ((current_packet->encryption&0x0F)+3)*8);
if ((current_packet->encryption&0x60) == MODE_KEYGEN)
printf(" (KEYGEN)");
printf("\n");
}
int
d_fprintf (FILE *__restrict __stream,
__const char *__restrict __format,...) {
if (DEBUG) {
fprintf(__stream, __format);
}
}
void print_hex_array(FILE* out, unsigned char* data, int length) {
int start = 0;
while(start < length) {
fprintf(out,"%.2X ",data[start]);
start++;
}
}
|
C
|
//
// stringFuncs.c
// pdbParse
//
// Created by mkaya on 26/07/2017.
// Copyright © 2017 mkaya. All rights reserved.
//
#include "stringFuncs.h"
char *getString(char *string,int baslangic, int bitis){
char *parca = (char*)malloc(bitis+1-baslangic*sizeof(char));
int i;
int a = 0;
for(i = baslangic-1; i < bitis; i++){
parca[a] = string[i];
a++;
}
parca[a] = '\0';
return parca;
}
double getDouble(char *string,int baslangic, int bitis){
char parca[bitis-baslangic+1];
int i;
int a = 0;
for(i = baslangic-1; i < bitis; i++){
parca[a] = string[i];
a++;
}
parca[a] = '\0';
return atof(parca);
}
int getInt(char *string,int baslangic, int bitis){
char parca[bitis-baslangic+1];
int i;
int a = 0;
for(i = baslangic-1; i < bitis; i++){
parca[a] = string[i];
a++;
}
parca[a] = '\0';
return atoi(parca);
}
char getChar(char *string,int sira){
return string[sira-1];
}
|
C
|
#include <stdio.h>
main()
{
int c;
int l=0;
int cl=0;
int ln=0;
int cln=0;
while (EOF != (c=getchar()))
{
if ('\n' == c)
{
cln++;
if (cl > l) {l=cl; ln=cln;}
cl=0;
}
cl++;
}
printf("%d\n", l);
printf("%d\n", ln);
}
|
C
|
/*
*Hector Jesus De La Garza Ponce 619971
*Oziel Alonzo Garza Lopez 805074
*Libreria pila.c
*/
#include <stdio.h>
#include <stdlib.h>
#include "pilas.h"
/*
* Función: push
* Parámetros: pila *x, void* dato
* Descripción: Funcion encargada de agregar un valor desconocido a una pila, el valor desconocido solo sera un pointer a este
* Salida: ninguna
*/
void push(pila *x, void* dato){
//Si la pila tiene elementos, crear un nuevo nodo y ponerlo como la cabeza
//El nodo siguiente del nuevo nodo es la cabeza actual de la pila.
if(pilaVacia(x)==1){
nodo *nuevo = malloc(sizeof(nodo));
nuevo->dato = dato;
nuevo->siguiente=x->primero;
x->primero = nuevo;
x->tamanio+=1;
}else{
//Si la pila no tiene elementos, ingresar el nodo nuevo y ponerlo como la cabeza
nodo *nuevo = malloc(sizeof(nodo));
nuevo->dato = dato;
nuevo->siguiente = NULL;
x->primero = nuevo;
x->tamanio+=1;
}
}
/*
* Función: pop
* Parámetros: pila *x
* Descripción: Saca de la pila el nodo con el apuntador al dato desconocido, al realizar esto el nodo ya se le hizo free
* Salida: Regresa un apuntador a una variable tipo nodo donde se encuentra un apuntador al dato
*/
nodo* pop(pila *x){
//Si la pila no esta vacia
if(pilaVacia(x)==1){
//Obtener el nodo cabeza
nodo *cabeza;
cabeza = malloc(sizeof(nodo));
cabeza = x->primero;
//Crear un nodo auxiliar
nodo *nuevaCabeza;
nuevaCabeza = malloc(sizeof(nodo));
nuevaCabeza = cabeza->siguiente;
// Regresar el dato de la cabeza
nodo* temporal;
temporal = malloc(sizeof(nodo));
temporal->dato = cabeza->dato;
//Liberar memoria de la cabeza
free(x->primero);
//Poner como cabeza al nodo auxiliar
x->primero = nuevaCabeza;
x->tamanio = x->tamanio - 1;
return temporal;
} else {
x->primero = NULL;
return NULL;
}
}
/*
* Función: pilaVacia
* Parámetros: pila *x
* Descripción: Verifica que la pila no este vacia, regresa un 1 si tiene uno o mas elementos, 0 de lo contrario
* Salida: Regresa un entero con valor 0 o 1
*/
int pilaVacia(pila *x){
if(x->tamanio == 0)
return 0;
else
return 1;
}
|
C
|
inherit SKILL;
void setup() {
set("name","廨");
set("type","herb");
set("effective_level",200);
set("usage/herb",1);
set("difficulty",200);
set("skill_class","knight");
}
int valid_learn(object me)
{
if( me->query_skill("herb", 1) < me->query_skill("dream-herb",1)) {
return notify_fail("ҩķ㣬廨\n");
}
return 1;
}
int help(object me)
{
write(@HELP
ѧϰ廨ҪͬȼҩΪ
L50лkaixiehua
ҩæ2-3֣ʧæ2
L100ľxiumugong
ɣ100廨Ѫ˺ĵֿ+5%
ɣɣ150廨Ѫ˺ĵֿ+10%
ɣɣɣ200廨Ѫ˺ĵֿ+15%
ͬʱʹʱæҡ
L100Ʊ̡canyunbi
öж֣ɹæ֣
ȫʧæ֡
ÿַһΣ֣
ÿ˺Чҩrandom(Чҩ/4)
L120ɢbeisusan
Զ֣кȡתƸͶѣ
ÿ20ʹһΣæ
ȡ廨ȼ*2
L140䡻huanmengluo
ԯʹãٻ鸨ˣ
ʱ90սÿ15ʹһΡ
ؼĶӶ
L170ȥҲchunquye
ҩ֮˵սеֵС20%ʱ
ÿܵ˺20%ļ˲ָֻЧһΡȼ
СL100ָ3000ȼL100L120֮䣬ɻָ4500
ȼL120ʱԻָ6000
ؼÿ1СʱʹһΣÿγСʱЧΪֹ
L180ʧ(shihunyin)
ҩ֮˵ʬƳҩˣ൱ڵȵĹ
ҩ˴ʱΪ5ӣֵΪԭ110%ÿ5ʹһΡ
L200Գ֡(buzichi)
240ҩ
ͶֵIJǡ
ͶֶѪ˺ĵֿ10%
10غϣBOSSʱ
ÿ10غʹһΡ
L200(yujiliang)
280ҩö֣æ
˶ЧΪƱ̡һ룬ʸ
ÿַһΣ
˺һ뷵ΪѪָ
HELP
);
return 1;
}
|
C
|
/* DO NOT MODIFY | NE MODIFIEZ PAS */
#ifndef STUDENT_H_
#define STUDENT_H_
#include "support.h"
#define PI 3.14159265
#define WIDTH 3
#define GREYSCALE " .:-=+*#%@";
#define IMG_SIZE 42
// Question 1
float calculator(int choice, float a, float b);
// Question 2
double deg_to_rad(double deg);
double power(double x, double y);
double factorial(int x);
double sinus(double x, int n);
// Question 3
int *row_adder(int matrix[][WIDTH], int height);
// Question 4
void convert_to_ascii(int image[][IMG_SIZE], char ascii[][IMG_SIZE]);
void display_image(char ascii[][IMG_SIZE]);
#endif /* STUDENT_H_ */
|
C
|
//Ray Allan Foote
//footer@onid.orst.edu
//CS311_400
//Assignment 6 (pthreads)
#define _BSD_SOURCE
#include <limits.h>
#include <sys/types.h>
#include <fcntl.h>
#include <getopt.h>
#include <pthread.h>
#include <stdio.h>
#include <sys/times.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
struct arg_struct {
unsigned int *array;
int numthred;
unsigned int thredin;
unsigned int total;
};
void setBit(unsigned int a[], int k){
int i= k/32;
int pos = k%32;
int flag = 1;
flag = flag << pos;
a[i] = a[i] | flag;
}
void clearBit(unsigned int a[], int k){
int i = k/32;
int pos = k%32;
int flag = 1;
flag = flag << pos;
flag = ~flag;
a[i] = a[i] & flag;
}
int testBit(unsigned int a[], int k){
int i= k/32;
int pos = k%32;
int flag = 1;
flag = flag << pos;
if (a[i] & flag)
return 1;
return 0;
}
void multiples(unsigned int *array, unsigned int base, unsigned int total){
if ((base == 0) || (base == 1)){
return;
} else {
for (int i = base + 1; i < total; i++){
if (testBit(array, i) == 0){
if (i % base == 0){
setBit(array, i);
}
}
}
}
}
void * threadFunc(void *arguments){
struct arg_struct *args = arguments;
int i, s;
for (i = 2; i < args->total; i++){
if (i % args->numthred == args->thredin){
s = pthread_mutex_lock(&mtx);
if (s != 0){
perror("mutex not locked");
exit(EXIT_FAILURE);
}
multiples(args->array, i, args->total);
s = pthread_mutex_unlock(&mtx);
if (s != 0){
perror("mutex not unlocked");
exit(EXIT_FAILURE);
}
}
}
return NULL;
}
int main(int argc, char **argv){
int c;
int print = 1;
int status;
extern char *optarg;
extern int optind, optopt;
unsigned int totbits = 1000;
int numthred = 2;
unsigned int *bitArray;
unsigned int size = ((totbits / 32)) + 1;
int i;
bitArray = malloc((sizeof(unsigned int)) * size);
//getopts for numthred/totbits/quiet
while ((c = getopt(argc, argv, "m:c:q")) != -1) {
switch (c){
case 'm':
totbits = atol(optarg);
break;
case 'c':
numthred =atoi(optarg);
break;
case 'q':
print = 0;
break;
}
}
//intitialize bit array
for (i = 0; i < size; i++){
bitArray[i] = 0;
}
//make and initialize threads
pthread_t thread[numthred];
struct arg_struct args[numthred];
for(i = 0; i < numthred; i++){
int s;
args[i].array = bitArray;
args[i].numthred = numthred;
args[i].thredin = i;
args[i].total = totbits;
s = pthread_create(&thread[i], NULL, threadFunc, (void *)&args[i]);
if (s != 0){
perror("thread create error");
exit(EXIT_FAILURE);
}
}
for (i = 0; i < numthred; i++)
pthread_join(thread[i], (void*)&status);
if (print > 0){
for (i = 4; i < totbits; i++){
if ((testBit(bitArray, i - 2) == 0) && (testBit(bitArray, i) == 0)){
printf("%d, %d\n", i-2, i);
}
}
}
exit(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include "ece454rpc_types.h"
int ret_int;
return_type r;
return_type add( const int nparams, arg_type* a )
{
printf("Entered the add function.\n");
if( nparams != 2 )
{
/* Error! */
r.return_val = NULL;
r.return_size = 0;
return r;
}
if( a->arg_size != sizeof( int ) || a->next->arg_size != sizeof( int ) )
{
/* Error! */
r.return_val = NULL;
r.return_size = 0;
return r;
}
int i = *( int * )( a->arg_val );
int j = *( int * )( a->next->arg_val );
printf("i = %d, j = %d\n", i, j);
ret_int = i + j;
r.return_val = ( void * )( &ret_int );
r.return_size = sizeof( int );
return r;
}
return_type multiply(const int nparams, arg_type* a)
{
printf("Entered the multiply function.\n");
if (nparams != 2)
{
/* Error! */
r.return_val = NULL;
r.return_size = 0;
return r;
}
if (a->arg_size != sizeof(int) || a->next->arg_size != sizeof(int))
{
/* Error! */
r.return_val = NULL;
r.return_size = 0;
return r;
}
int i = *(int *)(a->arg_val);
int j = *(int *)(a->next->arg_val);
printf("i = %d, j = %d\n", i, j);
ret_int = i * j;
r.return_val = (void *)(&ret_int);
r.return_size = sizeof(int);
return r;
}
return_type multiplyFive(const int nparams, arg_type* a)
{
printf("Entered the multiplyFive function.\n");
if (nparams != 5)
{
/* Error! */
r.return_val = NULL;
r.return_size = 0;
return r;
}
if (a->arg_size != sizeof(int) || a->next->arg_size != sizeof(int))
{
/* Error! */
r.return_val = NULL;
r.return_size = 0;
return r;
}
int i = *(int *)(a->arg_val);
int j = *(int *)(a->next->arg_val);
int k = *(int *)(a->next->next->arg_val);
int l = *(int *)(a->next->next->next->arg_val);
int m = *(int *)(a->next->next->next->next->arg_val);
printf("i=%d j=%d k=%d l=%d m=%d\n", i, j, k, l, m);
ret_int = i * j * k * l * m;
r.return_val = (void *)(&ret_int);
r.return_size = sizeof(int);
return r;
}
int main()
{
bool procedure_registered = register_procedure( "addtwo", 2, add );
bool procedure_registered_again_again = register_procedure("multfive", 5, multiplyFive);
bool procedure_registered_again = register_procedure( "multtwo", 2, multiply);
if (!procedure_registered)
{
printf("Could not register procedure!\n");
}
launch_server();
/* should never get here, because
launch_server(); runs forever. */
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node
{
int coef;
int exp;
struct node *link;
};
void input_LL(struct node **,int,int);
void display(struct node *);
void addition(struct node **,struct node **,struct node **);
void product(struct node **,struct node **,struct node **);
void main()
{
struct node *start_p=NULL,*start_q=NULL,*start_r=NULL;
int i,n,c,e;
printf("Enter first polynomial?\n");
printf("Enter no of terms?\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter %d term\n",i+1);
printf("Enter coefficient\n");
scanf("%d",&c);
printf("Enter exponent\n");
scanf("%d",&e);
input_LL(&start_p,c,e);
}
printf("Enter second polynomial\n");
printf("Enter no of terms?\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter %d term\n",i+1);
printf("Enter coefficient\n");
scanf("%d",&c);
printf("Enter exponent\n");
scanf("%d",&e);
input_LL(&start_q,c,e);
}
printf("First polynomial:\n");
display(start_p);
printf("second polynomial:\n");
display(start_q);
addition(&start_p,&start_q,&start_r);
printf("sum of two polynomial:\n");
display(start_r);
start_r=NULL;
product(&start_p,&start_q,&start_r);
printf("Product of the two polynomial:\n");
display(start_r);
}
void input_LL(struct node **start,int c,int e)
{
struct node *temp,*temp1,*prev;
if (*start==NULL)
{
temp=(struct node*)malloc(sizeof(struct node));
if (temp==NULL)
printf("Node is not created.Term cannot be inserted\n");
else
{
temp->coef=c;
temp->exp=e;
temp->link=NULL;
*start=temp;
}
}
else
{
temp1=*start;
while (temp1!=NULL && temp1->exp>e)
{
prev=temp1;
temp1=temp1->link;
}
if(temp1==NULL)
{
temp=(struct node *)malloc(sizeof(struct node));
if (temp==NULL)
printf("Node is not created\n");
else
{
temp->coef=c;
temp->exp=e;
temp->link=NULL;
prev->link=temp;
}
}
else
{
if(temp1->exp==e)
temp1->coef=temp1->coef+c;
else
{
if(temp1==*start)
{
temp=(struct node *)malloc (sizeof (struct node));
if(temp==NULL)
printf("Node is not created\n");
else
{
temp->coef=c;
temp->exp=e;
temp->link=*start;
*start=temp;
}
}
else
{
temp=(struct node *)malloc(sizeof(struct node));
if (temp==NULL)
printf("node is not created\n");
else
{
temp->coef=c;
temp->exp=e;
temp->link=temp1;
prev->link=temp;
}
}
}
}
}
}
void display(struct node *start)
{
struct node *temp;
temp=start;
if (temp==NULL)
printf("Empty polynomial\n");
else
{
while(temp!=NULL)
{
printf("+ %d X ^%d ",temp->coef,temp->exp);
temp=temp->link;
}
printf("\n");
}
}
void addition(struct node** start_p,struct node **start_q,struct node** start_r)
{
int c,e;
struct node *pptr,*qptr;
*start_r=NULL;
pptr=*start_p;
qptr=*start_q;
while(pptr!=NULL && qptr!=NULL)
{
if (pptr->exp==qptr->exp)
{
c=pptr->coef+qptr->coef;
e=pptr->exp;
input_LL(start_r,c,e);
pptr=pptr->link;
qptr=qptr->link;
}
else
{
if (pptr->exp>qptr->exp)
{
c=pptr->coef;
e=pptr->exp;
input_LL(start_r,c,e);
pptr=pptr->link;
}
else
{
c=qptr->coef;
e=qptr->exp;
input_LL(start_r,c,e);
qptr=qptr->link;
}
}
}
while(pptr!=NULL)
{
c=pptr->coef;
e=pptr->exp;
input_LL(start_r,c,e);
pptr=pptr->link;
}
while (qptr!=NULL)
{
c=qptr->coef;
e=qptr->exp;
input_LL(start_r,c,e);
qptr=qptr->link;
}
}
void product(struct node ** start_p,struct node **start_q,struct node** start_r)
{
int c,e;
struct node *pptr,*qptr;
*start_r=NULL;
pptr=*start_p;
qptr=*start_q;
if (*start_p==NULL && *start_q==NULL)
printf("\n Multiplication of polynomial is not possible\n");
else
{
while(pptr!=NULL)
{
qptr=*start_q;
while(qptr!=NULL)
{
c=pptr->coef*qptr->coef;
e=pptr->exp+qptr->exp;
input_LL(start_r,c,e);
qptr=qptr->link;
}
pptr=pptr->link;
}
}
}
|
C
|
#include "pool.h"
#include "functions.h"
#include "iterators.h"
int data[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int fibonacci(int n){
if(n == 0 || n == 1){
return 1;
}
else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
Value fib(Value* val){
int n = val[0].asInt;
return asInt(fibonacci(n));
}
void print(Value* val){
printf("%d\n", val[0].asInt);
}
int main() {
initPool();
Function* printFunction = makeFunction(1, print);
Function* fibFunction = makeFunction(1, fib);
foreach_int(printFunction, data, 10);
localSafeSync();
printf("Desired output: Should iterate through numbers 1-10 in any order. \n");
waitFor(fibFunction, printFunction, 0);
foreach_int(fibFunction, data, 10);
localSafeSync();
printf("Desired output: Should iterate through first 10 fibonacci numbers in any order. \n");
return 0;
}
|
C
|
#ifndef LIST_H
#define LIST_H
#include <stdlib.h>
struct node {
int val;
struct node *next;
}typedef node;
struct list {
struct node *head;
struct node *tail;
}typedef list;
void init(struct list *); //initialize empty list
int size(struct list *); //return number of nodes in list
void print(struct list *); //print the values in list
void push_front(struct list *, int);//push to front of list
void push_back(struct list *, int); //push to end of list
int front(struct list *); //returns value at the front of the list
int back(struct list *); //returns value at the back of the list
int pop_back(struct list *); //remove node from back and return value
int empty(struct list *); //returns true if list is empty
int remove_front(struct list *);//remove node from front and return value int empty(struct list); //returns true if list is empty
void delete(struct list *); //remove all nodes from list
#endif
|
C
|
#include "holberton.h"
#include <stdio.h>
#include <stdlib.h>
/**
* alloc_grid - allocates memory for a simulation of a 2D array
* @width: The amount of columns in the grid
* @height: The amount of rows
* Return: The double array pointing to the grid
*/
int **alloc_grid(int width, int height)
{
int **array;
int row, column, i;
if (width == 0 || height == 0)
return (NULL);
array = malloc(sizeof(int *) * height); /*make an array of pointers*/
if (array == NULL) /*This allows for array[i]*/
{
free(array);
return (NULL);
}
for (i = 0; i < height; i++) /*create the "second" part of 2D array*/
{
array[i] = malloc(sizeof(int) * width); /*allows array[i][j]*/
if (array[i] == NULL)
{
for (; i >= 0; i--)
free(array[i]);
free(array);
return (NULL);
}
}
for (row = 0; row < height; row++)
{
for (column = 0; column < width; column++)
array[row][column] = 0;
}
return (array);
}
|
C
|
#include<stdio.h>
#include<string.h>
void main()
{
int i,j,m,n,item,loc=0,loc1=0,f=0;
int a[20][20];
printf("\nEnter size of the array\n");
scanf("%d%d",&m,&n);
printf("\n\tEnter The Value Of Array:");
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\n\tEnter The Value To Be Serched:");
scanf("%d",&item);
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
if(item==a[i][j])
{
loc=i;
loc1=j;
f=1;
//break;
}
}
}
if(f==1)
printf("\n\tThe Item is at Row:%d And Coloumn:%d",loc,loc1);
else
printf("Element not found");
printf("\n\n\t\tSearch Completed.");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "math.h"
#include <stdbool.h>
static void spaceToStr(int num) {
if (num > 0) {
for (int i = 1; i <= num; i++) {
printf(" ");
}
}
}
static void starToStr(int num) {
if (num > 0) {
for (int i = 1; i <= num; i++) {
printf("*");
}
printf("\n");
}
}
static void makeTriangle(int answer) {
int mainRow = 0;
int spacing = 0;
int counter = 0;
char star = '*';
if (answer == 1) {
printf("*\n");
answer = 0;
}
else {
mainRow = answer + (answer - 1);
spacing = mainRow/2;
spaceToStr(spacing);
printf("%c\n", star);
answer--;
counter++;
}
while (answer != 0) {
if (answer == 1) {
starToStr(mainRow);
answer--;
}
else {
spacing--;
spaceToStr(spacing);
printf("%c", star);
spaceToStr(counter);
printf("%c\n", star);
counter = counter + 2;
answer--;
}
}
}
// Main function
int main() {
bool ask = true;
while (ask == true) {
int answer;
printf("Enter number of rows (from 1 to 20):\n");
scanf("%d", &answer);
if (answer >= 1 && answer <= 20) {
ask = false;
makeTriangle(answer);
}
}
return 0;
}
|
C
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head) {
if (head == NULL || head->next == NULL) return head;
struct ListNode* listNode = head->next;
head->next = swapPairs(listNode->next);
listNode->next = head;
return listNode;
}
|
C
|
/* ************************************ */
/* */
/* vc_stock.c */
/* */
/* By: Emre E, Javier, Minami */
/* */
/* ************************************ */
#include <stdlib.h>
#include <stdio.h>
#define SPC 32
#define TAB 9
#define NL 10
#define SIZE_CHAR_POINTER 4
typedef struct s_stock
{
int size_param;
char *str;
char *copy;
char **words;
} t_stock;
int vc_strlen(char *str) {
int i = 0;
while(*(str + i))
{
i++;
}
return i;
}
char *vc_strcpy(char *dest, char *src) {
int src_len;
int dest_len;
int i;
int j;
i = 0;
j = 0;
src_len = vc_strlen(src);
dest_len = vc_strlen(dest);
while (*(src + i) != '\0')
{
*(dest + i) = *(src + i);
i++;
}
while (*(dest + j + src_len) != '\0')
{
*(dest + j + src_len) = '\0';
j++;
}
return dest;
}
char *vc_strdup(char *src) {
char *newstr;
int size;
size = vc_strlen(src) + 1;
if (src != NULL)
{
newstr = (char *)malloc(size);
newstr[size - 1] = '\0';
newstr = vc_strcpy(newstr, src);
}
return newstr;
}
int num_of_row(char *str, int len) {
int i;
int row;
row = 0;
for (i = 0; i <= len; i++)
{
if (i > 0)
{
if (*(str + i) == SPC || *(str + i) == TAB || *(str + i) == NL || *(str + i) == '\0')
{
if (*(str + i - 1) != SPC && *(str + i - 1) != TAB && *(str + i - 1) != NL && *(str + i - 1) != '\0')
{
row++;
}
}
}
}
row++;
return row;
}
char **creat_container(char *str, int len) {
char **container;
container = (char **)malloc(num_of_row(str, len) * SIZE_CHAR_POINTER);
if (container == NULL) printf("ALLOCATE ERROR!\n");
else
{
int i;
int letter;
int row;
letter = 0;
row = 0;
for (i = 0; i <= len; i++)
{
letter++;
if (*(str + i) == SPC || *(str + i) == TAB
|| *(str + i) == NL || *(str + i) == '\0')
{
if (letter > 1)
{
char *word;
word = (char *)malloc(letter);
if (word == NULL) printf("ALLOCATE ERROR!\n");
else container[row] = word;
row++;
}
letter = 0;
}
}
container[num_of_row(str, len) - 1] = 0;
}
return container;
}
char **vc_split_whitespaces(char *str){
char **newargv;
int i;
int row;
int col;
row = 0;
col = 0;
newargv = creat_container(str, vc_strlen(str));
for (i = 0; i <= vc_strlen(str); i++)
{
if (*(str + i) == SPC || *(str + i) == TAB
|| *(str + i) == NL || *(str + i) == '\0')
{
newargv[row][col] = '\0';
if (vc_strlen(newargv[row]) > 0) row++;
col = 0;
}
else
{
newargv[row][col] = str[i];
col++;
}
}
return newargv;
}
|
C
|
#ifndef FILE_OPERATIONS_H
#define FILE_OPERATIONS_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include "../include/global.h"
char* buildFullPath(char* pathToFile, char* fileName); // Returns a string like this: pathToFile\fileName
int copyBytes(FILE* scrFile, FILE* destFile, int howManyBytes);
void copyFile(char* srcFileName, char* cpyFileName);
void copyFileTo(char* srcFileName, char* cpyFileName, char* src_folder,char* dest_folder); // Copies an entire file, byte per byte, from a folder, to another
MemFile* copyFileToMemory(FILE* fp);
MemFileInt* copyFileToMemoryAsInt(FILE* fp);
int deleteFile(char* fileName);
char* concatenate (char* str1, char*str2); // Merges 2 strings into 1
int countAllFiles(char* startingPath, char* extFilter);
int countFilesSingleFolder(char* pathToFolder, char* extFilter);
MemFile* copyFileToMemory(FILE* fp);
int fileExists(char* fileName); // Returns 1 if the file with the given name exist in the same folder as this exe and 0 otherwise
char** getAllFiles(char* pathToFiles, char* extFilter, long* filesToPatchCount);
char** getFilesSingleFolder(char* pathToFiles, char* extFilter, int totalFiles);
long getBytesEndingPos(const char* bytesToLocate, FILE* file); // Locates any given array of bytes in a given file, returns the byte offset of the last byte that matched or -1 if it couldn't find it
char* getCurrentPath();
char* getFileExt(char* fileName);
long getFileSize(FILE* fp);
void goInside(char* startingPath, char*** fileNames, char* extFilter, long* currentFile);
int isDirectory(const char *completePath);
long locateInt(int intToLocate, FILE* fp);
int matchingBytes(FILE* file1, FILE* file2);
void moveFile(char* fileName, char* src_folder,char* dest_folder); // Moves a file from one folder to another
char* oneLevelDown(char* path); // Returns a string with the path stripped one level down
FILE* openFile(char* fileName,const char* mode); // Open a file and checks if the file was opened successfully
size_t readLine(char* line, FILE* fp);
void systemCopyAndRename(char* srcFileName, char* destFileName,char* src_folder,char* dest_folder);
void systemCopy(char* srcFileName,char* src_folder,char* dest_folder);
void systemMove(char* fileTypeFilter, char* src_folder,char* dest_folder);
void systemMkDir(char* folderPath);
#endif // FILE_OPERATIONS_H
|
C
|
#include<stdio.h>
int main()
{
int feet,inch;
printf("enter the value of feet");
scanf("%d",&feet);
inch=feet*12;
printf("total inches will be:%d\n", inch);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/random.h>
#include "define_macro_functions.h"
#include "define_macros.h"
#include "structures.h"
#include "convert.h"
#include "vrf.h"
#include "crypto_vrf.h"
#include "VRF_functions.h"
/*
-----------------------------------------------------------------------------------------------------------
Functions
-----------------------------------------------------------------------------------------------------------
*/
/*
-----------------------------------------------------------------------------------------------------------
Name: create_random_VRF_keys
Description: Creates a random seed, and uses the seed to generate random VRF public key and a random VRF secret key
Parameters:
public_key - The VRF public key
secret_key - The VRF secret key
Return: 0 if an error has occured, 1 if successfull
-----------------------------------------------------------------------------------------------------------
*/
int create_random_VRF_keys(unsigned char *VRF_public_key, unsigned char *VRF_secret_key)
{
// Variables
unsigned char data[crypto_vrf_SEEDBYTES+1];
if (getrandom(data,crypto_vrf_SEEDBYTES,0) != crypto_vrf_SEEDBYTES)
{
return 0;
}
// create the VRF private and secret key
crypto_vrf_keypair_from_seed(VRF_public_key, VRF_secret_key, data);
return 1;
}
/*
-----------------------------------------------------------------------------------------------------------
Name: generate_key
Description: Generates a random public and private key, to be used for the signing and verifying of messages between the block verifiers
-----------------------------------------------------------------------------------------------------------
*/
void generate_key()
{
// Variables
unsigned char vrf_secret_key_data[crypto_vrf_SECRETKEYBYTES+1];
unsigned char vrf_public_key_data[crypto_vrf_PUBLICKEYBYTES+1];
char vrf_secret_key[VRF_SECRET_KEY_LENGTH+SMALL_BUFFER_SIZE];
char vrf_public_key[VRF_PUBLIC_KEY_LENGTH+SMALL_BUFFER_SIZE];
int count;
int count2;
memset(vrf_secret_key,0,sizeof(vrf_secret_key));
memset(vrf_public_key,0,sizeof(vrf_public_key));
memset(vrf_secret_key_data,0,sizeof(vrf_secret_key_data));
memset(vrf_public_key_data,0,sizeof(vrf_public_key_data));
if (create_random_VRF_keys((unsigned char*)vrf_public_key_data,(unsigned char*)vrf_secret_key_data) != 1 || crypto_vrf_is_valid_key((const unsigned char*)vrf_public_key_data) != 1)
{
color_print("Could not generate keys","red");
return;
}
// convert the VRF data to a string
for (count2 = 0, count = 0; count2 < (int)crypto_vrf_SECRETKEYBYTES; count2++, count += 2)
{
snprintf(vrf_secret_key+count,VRF_SECRET_KEY_LENGTH-1,"%02x",vrf_secret_key_data[count2] & 0xFF);
}
for (count2 = 0, count = 0; count2 < (int)crypto_vrf_PUBLICKEYBYTES; count2++, count += 2)
{
snprintf(vrf_public_key+count,VRF_PUBLIC_KEY_LENGTH-1,"%02x",vrf_public_key_data[count2] & 0xFF);
}
color_print("\nPublic Key:","green");
color_print(vrf_public_key,"green");
color_print("\nSecret Key:","green");
color_print(vrf_secret_key,"green");
return;
}
/*
-----------------------------------------------------------------------------------------------------------
Name: sign_network_block_string
Description: Signs the network block string
Parameters:
data - The signed data
MESSAGE - The sign_data
MESSAGE_SETTINGS - 1 to print the messages, otherwise 0. This is used for the testing flag to not print any success or error messages
Return: 0 if an error has occured, 1 if successfull
-----------------------------------------------------------------------------------------------------------
*/
int sign_network_block_string(char *data, const char* MESSAGE)
{
// Variables
char beta_string[SMALL_BUFFER_SIZE];
char proof[SMALL_BUFFER_SIZE];
// define macros
#define SIGN_NETWORK_BLOCK_STRING_ERROR(settings) \
memcpy(error_message.function[error_message.total],"sign_network_block_string",25); \
memcpy(error_message.data[error_message.total],settings,sizeof(settings)-1); \
error_message.total++; \
return 0;
memset(beta_string,0,sizeof(beta_string));
memset(proof,0,sizeof(proof));
// sign data
if (VRF_sign_data(beta_string,proof,MESSAGE) == 0)
{
SIGN_NETWORK_BLOCK_STRING_ERROR("Could not sign the network block string");
}
memset(data,0,strlen(data));
memcpy(data,proof,VRF_PROOF_LENGTH);
memcpy(data+VRF_PROOF_LENGTH,beta_string,VRF_BETA_LENGTH);
return 1;
#undef SIGN_NETWORK_BLOCK_STRING_ERROR
}
/*
-----------------------------------------------------------------------------------------------------------
Name: VRF_sign_data
Description: Sign data using the block verifiers ECDSA key
Parameters:
beta - The beta string
proof - The proof
data - The data
Return: 0 if an error has occured, 1 if successfull
-----------------------------------------------------------------------------------------------------------
*/
int VRF_sign_data(char *beta_string, char *proof, const char* data)
{
// Variables
unsigned char proof_data[crypto_vrf_PROOFBYTES+1];
unsigned char beta_string_data[crypto_vrf_OUTPUTBYTES+1];
int count;
int count2;
memset(beta_string,0,strlen(beta_string));
memset(proof,0,strlen(proof));
memset(proof_data,0,sizeof(proof_data));
memset(beta_string_data,0,sizeof(beta_string_data));
// sign data
if (crypto_vrf_prove((unsigned char*)proof_data,(const unsigned char*)secret_key_data,(const unsigned char*)data,(unsigned long long)strlen(data)) != 0 || crypto_vrf_proof_to_hash((unsigned char*)beta_string_data,(const unsigned char*)proof_data) != 0)
{
return 0;
}
// convert the data to a string
for (count2 = 0, count = 0; count2 < (int)crypto_vrf_PROOFBYTES; count2++, count += 2)
{
snprintf(proof+count,VRF_PROOF_LENGTH,"%02x",proof_data[count2] & 0xFF);
}
for (count2 = 0, count = 0; count2 < (int)crypto_vrf_OUTPUTBYTES; count2++, count += 2)
{
snprintf(beta_string+count,VRF_BETA_LENGTH,"%02x",beta_string_data[count2] & 0xFF);
}
return 1;
}
/*
-----------------------------------------------------------------------------------------------------------
Name: VRF_data_verify
Description: Verifies data
Parameters:
PUBLIC_ADDRESS - The public address
DATA_SIGNATURE - The data signature
DATA - The data
Return: 0 if an error has occured, 1 if successfull
-----------------------------------------------------------------------------------------------------------
*/
int VRF_data_verify(const char* BLOCK_VERIFIERS_PUBLIC_KEY, const char* BLOCK_VERIFIERS_DATA_SIGNATURE, const char* DATA)
{
// Variables
char data[3];
unsigned char public_key_data[crypto_vrf_PUBLICKEYBYTES+1];
unsigned char proof_data[crypto_vrf_PROOFBYTES+1];
unsigned char beta_string_data[crypto_vrf_OUTPUTBYTES+1];
int count;
int count2;
memset(public_key_data,0,sizeof(public_key_data));
memset(proof_data,0,sizeof(proof_data));
memset(beta_string_data,0,sizeof(beta_string_data));
// convert the public key, proof and beta string to a string
for (count = 0, count2 = 0; count < VRF_PUBLIC_KEY_LENGTH; count2++, count += 2)
{
memset(data,0,sizeof(data));
memcpy(data,&BLOCK_VERIFIERS_PUBLIC_KEY[count],2);
public_key_data[count2] = (unsigned char)strtol(data, NULL, 16);
}
for (count = 0, count2 = 0; count < VRF_PROOF_LENGTH; count2++, count += 2)
{
memset(data,0,sizeof(data));
memcpy(data,&BLOCK_VERIFIERS_DATA_SIGNATURE[count],2);
proof_data[count2] = (unsigned char)strtol(data, NULL, 16);
}
for (count = VRF_PROOF_LENGTH, count2 = 0; count < VRF_BETA_LENGTH; count2++, count += 2)
{
memset(data,0,sizeof(data));
memcpy(data,&BLOCK_VERIFIERS_DATA_SIGNATURE[count],2);
beta_string_data[count2] = (unsigned char)strtol(data, NULL, 16);
}
return crypto_vrf_verify((unsigned char*)beta_string_data,(const unsigned char*)public_key_data,(const unsigned char*)proof_data,(const unsigned char*)DATA,(unsigned long long)strlen(DATA)) != 0 ? 0 : 1;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_btree_repare.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mdufaud <mdufaud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/16 17:48:54 by mdufaud #+# #+# */
/* Updated: 2017/11/21 12:47:12 by mdufaud ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void btree_repare_case_1(t_btree *node)
{
node->color = b_black;
}
static void btree_repare_case_3(t_btree **root, t_btree *node)
{
t_btree *gp;
t_btree *uncle;
uncle = ft_btree_uncle(node);
gp = node->parent ? node->parent->parent : NULL;
if (node->parent)
node->parent->color = b_black;
if (uncle)
uncle->color = b_black;
if (gp)
{
gp->color = b_red;
ft_btree_repare(root, gp);
}
}
static void btree_repare_case_4(t_btree **root, t_btree *node)
{
t_btree *gp;
gp = node->parent ? node->parent->parent : NULL;
if (gp && gp->left && node == gp->left->right)
{
ft_btree_rotate_left(root, node->parent);
node = node->left;
}
else if (gp && gp->right && node == gp->right->left)
{
ft_btree_rotate_right(root, node->parent);
node = node->right;
}
gp = node->parent ? node->parent->parent : NULL;
if (node->parent && node == node->parent->left)
ft_btree_rotate_right(root, gp);
else
ft_btree_rotate_left(root, gp);
if (gp)
gp->color = b_red;
if (node->parent)
node->parent->color = b_black;
}
void ft_btree_repare(t_btree **root, t_btree *node)
{
t_btree *uncle;
uncle = ft_btree_uncle(node);
if (!node->parent)
btree_repare_case_1(node);
else if (node->parent->color == b_black)
return ;
else if (uncle && uncle->color == b_red)
btree_repare_case_3(root, node);
else
btree_repare_case_4(root, node);
}
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "graph_utils.h"
#include "fifo.h" /* for taboo list */
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <fcntl.h>
#include "connect.h"
#define MAXSIZE (541)
#define TABOOSIZE (500)
#define BIGCOUNT (9999999)
/***
*** example of very simple search for R(7,7) counter examples
***
*** starts with a small randomized graph and works its way up to successively
*** larger graphs one at a time
***
*** uses a taboo list of size #TABOOSIZE# to hold and encoding of and edge
*** (i,j)+clique_count
***/
/*
* PrintGraph
*
* prints in the right format for the read routine
*/
void PrintGraph(int *g, int gsize)
{
int i;
int j;
fprintf(stdout,"%d\n",gsize);
for(i=0; i < gsize; i++)
{
for(j=0; j < gsize; j++)
{
fprintf(stdout,"%d ",g[i*gsize+j]);
}
fprintf(stdout,"\n");
}
return;
}
/*
* CopyGraph
*
* copys the contents of old_g to corresponding locations in new_g
* leaving other locations in new_g alone
* that is
* new_g[i,j] = old_g[i,j]
*/
void CopyGraph(int *old_g, int o_gsize, int *new_g, int n_gsize)
{
int i;
int j;
/*
* new g must be bigger
*/
if(n_gsize < o_gsize)
return;
for(i=0; i < o_gsize; i++)
{
for(j=0; j < o_gsize; j++)
{
new_g[i*n_gsize+j] = old_g[i*o_gsize+j];
}
}
return;
}
/*
***
*** returns the number of monochromatic cliques in the graph presented to
*** it
***
*** graph is stored in row-major order
*** only checks values above diagonal
*/
int CliqueCount(int *g,
int gsize)
{
int i;
int j;
int k;
int l;
int m;
int n;
int o;
int count=0;
int sgsize = 7;
for(i=0;i < gsize-sgsize+1; i++)
{
for(j=i+1;j < gsize-sgsize+2; j++)
{
for(k=j+1;k < gsize-sgsize+3; k++)
{
if((g[i*gsize+j] == g[i*gsize+k]) &&
(g[i*gsize+j] == g[j*gsize+k]))
{
for(l=k+1;l < gsize-sgsize+4; l++)
{
if((g[i*gsize+j] == g[i*gsize+l]) &&
(g[i*gsize+j] == g[j*gsize+l]) &&
(g[i*gsize+j] == g[k*gsize+l]))
{
for(m=l+1;m < gsize-sgsize+5; m++)
{
if((g[i*gsize+j] == g[i*gsize+m]) &&
(g[i*gsize+j] == g[j*gsize+m]) &&
(g[i*gsize+j] == g[k*gsize+m]) &&
(g[i*gsize+j] == g[l*gsize+m])) {
for(n=m+1; n < gsize-sgsize+6; n++)
{
if((g[i*gsize+j]
== g[i*gsize+n]) &&
(g[i*gsize+j]
== g[j*gsize+n]) &&
(g[i*gsize+j]
== g[k*gsize+n]) &&
(g[i*gsize+j]
== g[l*gsize+n]) &&
(g[i*gsize+j]
== g[m*gsize+n])) {
for(o=n+1; o < gsize-sgsize+7; o++) {
if((g[i*gsize+j]
== g[i*gsize+o]) &&
(g[i*gsize+j]
== g[j*gsize+o]) &&
(g[i*gsize+j]
== g[k*gsize+o]) &&
(g[i*gsize+j]
== g[l*gsize+o]) &&
(g[i*gsize+j]
== g[m*gsize+o]) &&
(g[i*gsize+j] ==
g[n*gsize+o])) {
count++;
}
}
}
}
}
}
}
}
}
}
}
}
return(count);
}
#if 0
int open_socket(){
int sock;
struct sockaddr_in server;
char message[1000] , server_reply[2000];
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");
server.sin_addr.s_addr = inet_addr("169.231.19.110");
server.sin_family = AF_INET;
server.sin_port = htons( 8888 );
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
return sock;
}
void socket_upload(int sock, int *g,int gsize)
{
if( write(sock, &gsize, sizeof(gsize) ) < 0 )
error("ERROR writing to socket");
/*int *gCopy = (int*)malloc(gsize*gsize*sizeof(int));
memcpy(gCopy,g,gsize*gsize*sizeof(int));
struct sockaddr_in sockInfo;
char *toSend = (char*)malloc(255+(gsize*gsize+3)*sizeof(char));
int i,j;
toSend[0] = gsize;
for(i=1;i<gsize*gsize+1;i++)
{
toSend[i] = '0' + gCopy[i];
}
toSend[i] = '\n';
toSend[i+1] = '\0';
while(1)
{
for(j=0;j<(gsize*gsize+2)/255+1;j++)
{
if(send(sock,toSend+j*255,255,0)<0)
{
printf("fail, retrying at package %d...\n",j);
j--;
continue;
}
}
printf("wait.\n");
char buf[256];
buf[0] = 0;
int received = recv(sock,buf,1,0);
if(received==1)
break;
}
printf("sent.\n");
free(gCopy);
free(toSend);*/
}
#endif
int main(int argc,char *argv[])
{
int *g;
int *new_g;
int gsize;
int count;
int i;
int j;
int best_count;
int best_i;
int best_j;
void *taboo_list;
int val,iter,jter;
//int sock = open_socket();
/*
* start with graph of size 40
*/
gsize = 40;
g = (int *)malloc(gsize*gsize*sizeof(int));
if(g == NULL) {
exit(1);
}
/*
* make a fifo to use as the taboo list
*/
taboo_list = FIFOInitEdge(TABOOSIZE);
if(taboo_list == NULL) {
exit(1);
}
/*
* start out with all zeros
*/
memset(g,0,gsize*gsize*sizeof(int));
val = 0, iter = 0, jter=0;
for( iter=0; iter<gsize; iter++){
for( jter = 0; jter< gsize; jter++){
g[iter*gsize + jter] = val;
val = 1 - val;
}
}
if( atoi(argv[2]) ){
for(i=0; i<gsize; i++){
for(j=0; j<gsize; j++)
g[i*gsize +j] = 1 - g[i*gsize +j];
}
}
PrintGraph(g, gsize);
int flag = 0;
int term = atoi(argv[1]);
/*
* while we do not have a publishable result
*/
while(gsize < 204)
{
/*
* find out how we are doing
*/
count = CliqueCount(g,gsize);
/*
* if we have a counter example
*/
if(count == 0)
{
printf("Eureka! Counter-example found!\n");
PrintGraph(g,gsize);
if(gsize == term)
{
FILE *fp;
char buf[100];
bzero(buf, 100);
sprintf(buf, "graph%d_3.state", gsize);
printf("Filename: %s", buf);
fp = fopen(buf, "w+");
PrintGraphToFile(g, gsize, fp);
fclose(fp);
}
//socket_upload(sock, g, gsize);
/*
* make a new graph one size bigger
*/
new_g = (int *)malloc((gsize+1)*(gsize+1)*sizeof(int));
if(new_g == NULL)
exit(1);
/*
* copy the old graph into the new graph leaving the
* last row and last column alone
*/
//CopyGraph(g,gsize,new_g,gsize+1);
new_g = RandomGraphGenerator(gsize+1);
/*
* zero out the last column and last row
*/
/*for(i=0; i < (gsize+1); i++)
{
if(drand48() > 0.5) {
new_g[i*(gsize+1) + gsize] = 0; // last column
new_g[gsize*(gsize+1) + i] = 0; // last row
}
else
{
new_g[i*(gsize+1) + gsize] = 1; // last column
new_g[gsize*(gsize+1) + i] = 1; // last row
}
}*/
/*
* throw away the old graph and make new one the
* graph
*/
free(g);
g = new_g;
gsize = gsize+1;
/*
* reset the taboo list for the new graph
*/
taboo_list = FIFOResetEdge(taboo_list);
/*
* keep going
*/
continue;
}
/*
* otherwise, we need to consider flipping an edge
*
* let's speculative flip each edge, record the new count,
* and unflip the edge. We'll then remember the best flip and
* keep it next time around
*
* only need to work with upper triangle of matrix =>
* notice the indices
*/
for(i=0; i < gsize; i++)
{
for(j=i+1; j < gsize; j++)
{
/*
* flip it
*/
g[i*gsize+j] = 1 - g[i*gsize+j];
count = CliqueCount(g,gsize);
/*
* is it better and the i,j,count not taboo?
*/
if((count < best_count) &&
!FIFOFindEdge(taboo_list,i,j))
// !FIFOFindEdgeCount(taboo_list,i,j,count))
{
best_count = count;
best_i = i;
best_j = j;
}
/*
* flip it back
*/
g[i*gsize+j] = 1 - g[i*gsize+j];
}
}
if(best_count == BIGCOUNT) {
printf("no best edge found, terminating\n");
exit(1);
}
/*
* keep the best flip we saw
*/
g[best_i*gsize+best_j] = 1 - g[best_i*gsize+best_j];
/*
* taboo this graph configuration so that we don't visit
* it again
*/
count = CliqueCount(g,gsize);
FIFOInsertEdge(taboo_list,best_i,best_j);
// FIFOInsertEdgeCount(taboo_list,best_i,best_j,count);
printf("ce size: %d, best_count: %d, best edge: (%d,%d), new color: %d\n",
gsize,
best_count,
best_i,
best_j,
g[best_i*gsize+best_j]);
/*
* rinse and repeat
*/
}
FIFODeleteGraph(taboo_list);
return(0);
}
int *RandomGraphGenerator(int n)
{
int *g = (int*)malloc(n*n*sizeof(int));
int i=0,j=0;
srand(time(0));
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
g[i*n+j] = rand()%2;
}
return g;
}
|
C
|
#include <stdio.h>
int main(void){
int num;
printf("10 ԷϽÿ \n");
scanf("%d",&num);
printf("10 : %d | 16 %x \n", num,num);
return 0;
}
|
C
|
/*Programa: Torres de Hanoi
Autor: Sergi Planes
Data: 16/06/201
Funcionalitat: Estructura de dades del programa */
//llibrerias
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
//Constants utilitzades.
#define NUMDISCOS 3 //Especifica el nombre de discs
#define NUMTORRES 3 //Indica el nombre de torres
#define SIZERES 20 //Indica el nombre de caracters del fitxer
#define MODE 2 //Emmagatzema ap o w segons el mode escollit
#define RES 2 //Emmagatzema una resposta (Si/No)
#define ESPAIS 14 //Linia de guionets al final de cada dibuix de torres
//Estructures de dades
typedef int torres[NUMTORRES]; //Vector que emmagatzema els discs de cada torre
typedef torres *joc[NUMTORRES]; //Matriu de vectors de discs
//Funcions utilitzades.
void imprimir_hora(FILE *f);
void imprimir_capcalera_ini(FILE *f, int nd, char mode[MODE]);
void imprimir_capcalera_fin(FILE *f, int nd, char mode[MODE]);
void visualitzacio_mov(FILE *f, int nd, char mode[MODE]);
void visualitzar_mov(int n);
int buscar_mode(char **argv);
int buscar_fitxer(char **argv);
int buscar_discos(char **argv);
void dibuixar_config_ini(FILE *f, int nd);
void dibuixar(FILE *f, int nd, int v[NUMTORRES][nd]);
void move(int nd, int towerorg, int towerdest, int depth, FILE *f);
void hanoi(int nd, int towerorg, int towerdest, int toweraux, int depth, FILE *f);
void swap(int *v, int i, int j);
void ordena_major_menor(int *v);
void alliberar_matriu(int *mat[NUMTORRES]);
//void inicialitzar_matriu((int *v)**v);
void moure_disc(int *v[NUMTORRES], int towerorg, int towerdest, int nd);
|
C
|
#include "memory.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
Memory* memCreate() {
int i;
Memory* mem = (Memory*)malloc(sizeof(Memory));
memset(mem->ramFlag, 0x00, 0x400000);
memset(mem->romFlag, 0x00, 0x80000);
mem->romMask = 0x03;
for (i = 0; i < 32; i++) {
mem->rom[i].type = MEM_ROM;
mem->rom[i].num = i & 0xff;
mem->rom[i].dptr = mem->romData + (i << 14);
mem->rom[i].fptr = mem->romFlag + (i << 14);
}
for (i = 0; i < 256; i++) {
mem->ram[i].type = MEM_RAM;
mem->ram[i].num = i & 0xff;
mem->ram[i].dptr = mem->ramData + (i << 14);
mem->ram[i].fptr = mem->ramFlag + (i << 14);
}
memSetSize(mem,48);
mem->pt[0] = &mem->rom[0];
mem->pt[1] = &mem->ram[5];
mem->pt[2] = &mem->ram[2];
mem->pt[3] = &mem->ram[0];
return mem;
}
void memDestroy(Memory* mem) {
free(mem->ramData);
free(mem->ramFlag);
free(mem->romData);
free(mem->romFlag);
free(mem);
}
MemPage* memGetBankPtr(Memory* mem, unsigned short adr) {
return mem->pt[adr >> 14];
}
MemPage* ptr;
unsigned char memRd(Memory* mem, unsigned short adr) {
ptr = mem->pt[adr >> 14];
mem->flag |= (ptr->fptr[adr & 0x3fff] & MEM_BRK_RD);
return ptr->dptr[adr & 0x3fff];
}
void memWr(Memory* mem, unsigned short adr, unsigned char val) {
ptr = mem->pt[adr >> 14];
mem->flag |= (ptr->fptr[adr & 0x3fff] & MEM_BRK_WR);
if (ptr->type == MEM_RAM) ptr->dptr[adr & 0x3fff] = val;
}
unsigned char* memGetFptr(Memory* mem, unsigned short adr) {
return mem->pt[adr >> 14]->fptr + (adr & 0x3fff);
}
void memSetSize(Memory* mem, int val) {
if (mem->memSize == val) return;
mem->memSize = val;
switch (val) {
case 48:
mem->memMask = 0x07; // need 7, cuz it uses pages 2,5,0
break;
case 128:
mem->memMask = 0x07;
break;
case 256:
mem->memMask = 0x0f;
break;
case 512:
mem->memMask = 0x1f;
break;
case 1024:
mem->memMask = 0x3f;
break;
case 2048:
mem->memMask = 0x7f;
break;
case 4096:
mem->memMask = 0xff;
break;
default:
mem->memMask = 0x07;
mem->memSize = 48;
break;
}
}
void memSetBank(Memory* mem, int bank, int wut, unsigned char nr) {
if (wut == MEM_ROM) nr &= mem->romMask;
if (wut == MEM_RAM) nr &= mem->memMask;
switch (bank) {
case MEM_BANK0:
switch (wut) {
case MEM_ROM: mem->pt[0] = (nr == 0xff) ? &mem->ram[0] : &mem->rom[nr]; break;
case MEM_RAM: mem->pt[0] = &mem->ram[nr]; break;
}
break;
case MEM_BANK1:
switch (wut) {
case MEM_ROM: mem->pt[1] = &mem->rom[nr]; break;
case MEM_RAM: mem->pt[1] = &mem->ram[nr]; break;
}
break;
case MEM_BANK2:
switch (wut) {
case MEM_ROM: mem->pt[2] = &mem->rom[nr]; break;
case MEM_RAM: mem->pt[2] = &mem->ram[nr]; break;
}
break;
case MEM_BANK3:
switch (wut) {
case MEM_ROM: mem->pt[3] = &mem->rom[nr]; break;
case MEM_RAM: mem->pt[3] = &mem->ram[nr]; break;
}
break;
}
}
void memSetPage(Memory* mem, int type, int page, char* src) {
switch(type) {
case MEM_ROM:
memcpy(mem->rom[page & 31].dptr,src,0x4000);
break;
case MEM_RAM:
memcpy(mem->ram[page & 255].dptr,src,0x4000);
break;
}
}
void memGetPage(Memory* mem, int type, int page, char* dst) {
switch(type) {
case MEM_ROM:
memcpy(dst,mem->rom[page & 31].dptr,0x4000);
break;
case MEM_RAM:
memcpy(dst,mem->ram[page & 255].dptr,0x4000);
break;
}
}
unsigned char* memGetPagePtr(Memory* mem, int type, int page) {
unsigned char* res = NULL;
switch (type) {
case MEM_ROM:
res = mem->rom[page & 31].dptr;
break;
case MEM_RAM:
res = mem->ram[page & 255].dptr;
break;
}
return res;
}
|
C
|
/* Author: Lauren Sampaio
* File: matrix_product.c
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <sys/wait.h>
#include <pthread.h>
#include "matrix_product.h"
int step = 0;
/* Essayer de faire avec fork, et comparer avec le multithread */
double * alloc_matrix( int rows, int cols )
{
double * matrix;
matrix = (double*) malloc(rows * cols * sizeof(double));
fprintf(stderr, "Malloc successful\n");
return matrix;
}
int random_matrix( double * matrix, int rows, int cols, int seed )
{
srand(seed);
double range = (MAX - MIN);
double div = RAND_MAX / range;
for(int row = 0; row < rows; row++) {
for(int col = 0; col < cols; col++) {
double current_value = MIN + (rand() / div);
matrix[row * cols + col] = current_value;
}
}
return 0;
}
int ordered_matrix( double * matrix, int rows, int cols )
{
for(int row = 0; row < rows; row++) {
for(int col = 0; col < cols; col++) {
matrix[row * cols + col] = row * cols + col;
}
}
return 0;
}
double * product_matrix( double * matrix1, int rows1, int cols1, double * matrix2, int rows2, int cols2 )
{
double * result;
result = alloc_matrix( rows1, cols2);
for( int row = 0; row < rows1; row++ ){
for(int col = 0; col < cols2; col++)
{
double cell = 0;
for( int c = 0; c < cols1; c++ ) {
cell += matrix1[row * cols1 + c] * matrix2[c * cols2 + col];
}
result[row * cols2 + col] = cell;
}
}
return result;
}
double * product_matrix_thread( double * matrix1, int rows1, int cols1, double * matrix2, int rows2, int cols2 )
{
double * result;
result = alloc_matrix( rows1, cols2);
thread_struct current;
current.matrix1 = matrix1;
current.rows1 = rows1;
current.cols1 = cols1;
current.matrix2 = matrix2;
current.rows2 = rows2;
current.cols2 = cols2;
current.result = result;
pthread_t threads[MAX_THREAD];
for (int i = 0; i < MAX_THREAD; i++) {
pthread_create(&threads[i], NULL, product_thread, (void*)(¤t));
}
for (int i = 0; i < MAX_THREAD; i++) {
pthread_join(threads[i], NULL);
}
return current.result;
}
double * product_matrix_fork( double * matrix1, int rows1, int cols1, double * matrix2, int rows2, int cols2 )
{
pid_t pid1, pid2, pid3;
int sector = 0;
double * result;
result = alloc_matrix( rows1, cols2 );
thread_struct current;
current.matrix1 = matrix1;
current.rows1 = rows1;
current.cols1 = cols1;
current.matrix2 = matrix2;
current.rows2 = rows2;
current.cols2 = cols2;
current.result = result;
pid1 = fork( );
if(pid1 < 0 ) {
fprintf(stderr, "Erreur: échec du fork()\n");
exit(EXIT_FAILURE);
} else if( pid1 == 0 ) {
//Fils 1
sector++;
pid2 = fork();
if(pid2 < 0) {
fprintf(stderr, "Erreur: échec du fork()\n");
exit(EXIT_FAILURE);
} else if(pid2 == 0) {
//Fils 2
sector++;
pid3 = fork();
if(pid3 < 0) {
fprintf(stderr, "Erreur: échec du fork()\n");
exit(EXIT_FAILURE);
} else if(pid3 == 0) {
//Fils 3
sector++;
fprintf(stderr, "Fils 3\n");
product_calcul( ¤t, sector );
} else {
//Fils 2
fprintf(stderr, "Fils 2\n");
product_calcul( ¤t, sector );
wait(NULL);
}
} else {
//Fils 1
fprintf(stderr, "Fils 1\n");
product_calcul( ¤t, sector );
wait(NULL);
}
} else {
//Pere
fprintf(stderr, "Pere\n");
product_calcul( ¤t, sector );
wait(NULL);
}
return current.result;
}
void print_matrix( double * matrix, int rows, int cols)
{
for( int row = 0; row < rows; row++ ){
printf("[ ");
for(int col = 0; col < cols; col++) {
printf("%3.3f ", matrix[row * cols + col]);
}
printf("]\n");
}
}
void * product_thread(void* arg)
{
int sector = step++;
thread_struct * current = ( thread_struct * ) arg;
product_calcul( current, sector );
}
int product_calcul(thread_struct * current, int sector)
{
int max_i, min_i, max_j, min_j;
if(sector == 0 || sector == 1) {
max_i = current->rows1 / 2;
min_i = 0;
} else {
max_i = current->rows1;
min_i = current->rows1 / 2;
}
if(sector % 2 == 0) {
max_j = current->cols2 / 2;
min_j = 0;
} else {
max_j = current->cols2;
min_j = current->cols2 / 2;
}
for (int i = min_i; i < max_i; i++) {
for(int j = min_j; j < max_j; j++) {
for( int c = 0; c < current->cols1; c++ ) {
current->result[i * current->cols1 + j] += current->matrix1[i * current->cols1 + c] * current->matrix2[c * current->cols2 + j];
}
}
}
return 0;
}
|
C
|
#include <stdio.h>
int main(){
int nbtetes,coup;
nbtetes=8542;
coup = 0 ;
while ( nbtetes > 1 ) {
nbtetes=nbtetes/2;
coup++ ;
printf("%d -> %d \n", coup, nbtetes ) ;
if(((nbtetes%2)!=0)&&(nbtetes!=1)) {
nbtetes=(nbtetes*3)+1;
}
}
/* for(coup=0;nbtetes>1;coup++){
printf("%d -%d \n",coup, nbtetes);
nbtetes=nbtetes/2;
if (nbtetes == 1)
break ;
if((nbtetes%2)!=0){
nbtetes=(nbtetes*3)+1;
//printf("%d \n",nbtetes);
}
}
coup++;
printf("%d \n",coup);
*/
if ( nbtetes == 1 )
coup++ ;
printf("coups : %d\n", coup ) ;
return 0;
}
|
C
|
#include "header.h"
#include <stdio.h>
char *AnotherString = "Hello Everyone";
main()
{
printf("Running...\n");
/*
* Call WriteMyString() - defined in another file
*/
WriteMyString(MY_STRING);
printf("Finished.\n");
}
|
C
|
#include "line.h"
#include <math.h>
//draw_line
//draw_line <channel>,<x1>,<y1>,<x2>,<y2>,<width>,<color>
void draw_line(thread_context* context, char* args) {
int channel = 0, color = COLOR_TRANSPARENT, height = 0;
double x1 = 0, y1 = 0, x2 = 0, y2 = 0, width = 0;
bool color_empty = true;
args = read_channel(args, &channel);
if (is_valid_2D_channel_number(channel)) {
args = read_double(args, &x1);
args = read_double(args, &y1);
args = read_double(args, &x2);
args = read_double(args, &y2);
args = read_double(args, &width);
args = read_color_arg_empty(args, &color, 4, &color_empty);
//cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_NEAREST);
if (debug) printf("draw_line %d,%f,%f,%f,%f,%f,%d\n", channel, x1, y1, x2, y2, width, color);
channel_info * led_channel = get_channel(channel);
cairo_t* cr = led_channel->cr;
if (!color_empty) {
set_cairo_color_rgba(cr, color);
}
cairo_new_path(cr);
cairo_set_line_width(cr, width);
cairo_move_to(cr, x1, y1);
cairo_line_to(cr, x2, y2);
cairo_stroke(cr);
} else {
fprintf(stderr, ERROR_INVALID_2D_CHANNEL);
}
}
//draw a sharp 1 pixel line without anti aliasing
//draw_sharp_line <channel>,<x1>,<y1>,<x2>,<y2>,<width>,<color>
//width argument must always be 1, not implemented
void draw_sharp_line(thread_context* context, char* args) {
int x, y, dx, dy, dx1, dy1, px, py, xe, ye, i;
int x1, y1, x2, y2, channel, line_width=1;
unsigned int color = 255;
args = read_channel(args, &channel);
if (is_valid_2D_channel_number(channel)) {
args = read_int(args, &x1);
args = read_int(args, &y1);
args = read_int(args, &x2);
args = read_int(args, &y2);
args = read_int(args, &line_width);
args = read_color_arg(args, &color, 3);
} else {
fprintf(stderr, ERROR_INVALID_2D_CHANNEL);
return;
}
if (debug) printf("draw_sharp_line %d,%d,%d,%d,%d,%d\n", channel, x1, y1, x2, y2, color);
channel_info * led_channel = get_channel(channel);
cairo_surface_flush(led_channel->surface);
unsigned int* pixels = (unsigned int*)cairo_image_surface_get_data(led_channel->surface); //get pointer to pixel data
unsigned int pixel_stride = led_channel->pixel_stride;
int width = led_channel->width;
int height = led_channel->height;
color = convert_cairo_color(color);
dx = x2 - x1;
dy = y2 - y1;
dx1 = fabs(dx);
dy1 = fabs(dy);
px = 2 * dy1 - dx1;
py = 2 * dx1 - dy1;
if (dy1 <= dx1)
{
if (dx >= 0)
{
x = x1;
y = y1;
xe = x2;
}
else
{
x = x2;
y = y2;
xe = x1;
}
if (y < height && x < width) pixels[y * pixel_stride + x] = color;
for (i = 0;x < xe;i++)
{
x = x + 1;
if (px < 0)
{
px = px + 2 * dy1;
}
else
{
if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0))
{
y = y + 1;
}
else
{
y = y - 1;
}
px = px + 2 * (dy1 - dx1);
}
if (y < height && x < width) pixels[y * pixel_stride + x] = color;
}
}
else
{
if (dy >= 0)
{
x = x1;
y = y1;
ye = y2;
}
else
{
x = x2;
y = y2;
ye = y1;
}
if (y < height && x < width) pixels[y * pixel_stride + x] = color;
for (i = 0;y < ye;i++)
{
y = y + 1;
if (py <= 0)
{
py = py + 2 * dx1;
}
else
{
if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0))
{
x = x + 1;
}
else
{
x = x - 1;
}
py = py + 2 * (dx1 - dy1);
}
if (y < height && x < width) pixels[y * pixel_stride + x] = color;
}
}
cairo_surface_mark_dirty_rectangle(led_channel->surface, (x1 > x2) ? x2 : x1, (y1 > y2) ? y2 : y1, dx, dy);
}
|
C
|
/**
* File contains a example test program for the generic Hash map implemented
*
* The Output of the program looks like:
* Inserting : ONE
* 0 ---> size = 0 ||
* 1 ---> size = 1 || ONE |
*
* Inserting : TWO
* 0 ---> size = 0 ||
* 1 ---> size = 2 || ONE | TWO |
*
* Inserting : THREE
* 0 ---> size = 0 ||
* 1 ---> size = 3 || ONE | TWO | THREE |
*
* Inserting : FOUR
* 0 ---> size = 1 || FOUR |
* 1 ---> size = 0 ||
* 2 ---> size = 1 || ONE |
* 3 ---> size = 2 || TWO | THREE |
*
* Inserting : FIVE
* 0 ---> size = 2 || FOUR | FIVE |
* 1 ---> size = 0 ||
* 2 ---> size = 1 || ONE |
* 3 ---> size = 2 || TWO | THREE |
*
* Inserting : SIX
* 0 ---> size = 1 || FOUR |
* 1 ---> size = 1 || FIVE |
* 2 ---> size = 1 || SIX |
* 3 ---> size = 0 ||
* 4 ---> size = 1 || ONE |
* 5 ---> size = 0 ||
* 6 ---> size = 1 || TWO |
* 7 ---> size = 1 || THREE |
*
* Inserting : SEVEN
* 0 ---> size = 1 || FOUR |
* 1 ---> size = 1 || FIVE |
* 2 ---> size = 1 || SIX |
* 3 ---> size = 0 ||
* 4 ---> size = 2 || ONE | SEVEN |
* 5 ---> size = 0 ||
* 6 ---> size = 1 || TWO |
* 7 ---> size = 1 || THREE |
*
* Inserting : EIGTH
* 0 ---> size = 1 || FOUR |
* 1 ---> size = 1 || FIVE |
* 2 ---> size = 1 || SIX |
* 3 ---> size = 0 ||
* 4 ---> size = 3 || ONE | SEVEN | EIGTH |
* 5 ---> size = 0 ||
* 6 ---> size = 1 || TWO |
* 7 ---> size = 1 || THREE |
*
* Finding: FOUND TWO
* MAP SIZE : Before deletion -- 6
* Erased 1
* Erased 2
* MAP SIZE : After deletion -- 5
* 0 ---> size = 1 || FOUR |
* 1 ---> size = 1 || FIVE |
* 2 ---> size = 1 || SIX |
* 3 ---> size = 0 ||
* 4 ---> size = 3 || ONE | SEVEN | EIGTH |
* 5 ---> size = 0 ||
* 6 ---> size = 0 ||
* 7 ---> size = 1 || THREE |
*
* MAP SIZE : After reinsertion -- 7
* 0 ---> size = 0 ||
* 1 ---> size = 1 || FOUR |
* 2 ---> size = 1 || FIVE |
* 3 ---> size = 0 ||
* 4 ---> size = 0 ||
* 5 ---> size = 1 || SIX |
* 6 ---> size = 0 ||
* 7 ---> size = 0 ||
* 8 ---> size = 2 || SEVEN | EIGTH |
* 9 ---> size = 1 || ONE |
* 10 ---> size = 0 ||
* 11 ---> size = 0 ||
* 12 ---> size = 0 ||
* 13 ---> size = 1 || TWO |
* 14 ---> size = 0 ||
* 15 ---> size = 1 || THREE |
*
**/
#include "../hashmap.h"
#include <stdio.h>
#include <string.h>
typedef struct a_st {
int b;
char a[10];
} att;
int compare(att *a, att *b) {
if (a->b == b->b){
return 0;
}
return 1;
}
void print_obj(att *entry) {
printf("%s", entry->a);
}
int get_hash(att *entry) {
return entry->b;
}
DECLARE_HASHMAP(att)
DEFINE_HASHMAP(att, compare, get_hash, free, realloc)
HASH_MAP_PRINT_FUNC(att, print_obj)
int main() {
HASH_MAP(att) *map = HASH_MAP_CREATE(att)();
att *x = (att *)malloc(sizeof(att));
x->b = 1;
strcpy(x->a, "ONE");
att *y = (att *)malloc(sizeof(att));
y->b = 3;
strcpy(y->a, "TWO");
att *z = (att *)malloc(sizeof(att));
z->b = 8;
strcpy(z->a, "THREE");
att *a = (att *)malloc(sizeof(att));
a->b = 5;
strcpy(a->a, "FOUR");
att *b = (att *)malloc(sizeof(att));
b->b = 10;
strcpy(b->a, "FIVE");
att *c = (att *)malloc(sizeof(att));
c->b = 7;
strcpy(c->a, "SIX");
att *d = (att *)malloc(sizeof(att));
d->b = 9;
strcpy(d->a, "SEVEN");
att *e = (att *)malloc(sizeof(att));
e->b = 17;
strcpy(e->a, "EIGTH");
HASH_MAP_INSERT(att)(map, &x, HMDR_FIND);
printf("Inserting : ");
print_obj(x);
printf("\n");
HASH_MAP_PRINT(att)(map);
HASH_MAP_INSERT(att)(map, &y, HMDR_FIND);
printf("Inserting : ");
print_obj(y);
printf("\n");
HASH_MAP_PRINT(att)(map);
HASH_MAP_INSERT(att)(map, &z, HMDR_FIND);
printf("Inserting : ");
print_obj(z);
printf("\n");
HASH_MAP_PRINT(att)(map);
HASH_MAP_INSERT(att)(map, &a, HMDR_FIND);
printf("Inserting : ");
print_obj(a);
printf("\n");
HASH_MAP_PRINT(att)(map);
HASH_MAP_INSERT(att)(map, &b, HMDR_FIND);
printf("Inserting : ");
print_obj(b);
printf("\n");
HASH_MAP_PRINT(att)(map);
HASH_MAP_INSERT(att)(map, &c, HMDR_FIND);
printf("Inserting : ");
print_obj(c);
printf("\n");
HASH_MAP_PRINT(att)(map);
HASH_MAP_INSERT(att)(map, &d, HMDR_FIND);
printf("Inserting : ");
print_obj(d);
printf("\n");
HASH_MAP_PRINT(att)(map);
HASH_MAP_INSERT(att)(map, &e, HMDR_FIND);
printf("Inserting : ");
print_obj(e);
printf("\n");
HASH_MAP_PRINT(att)(map);
att *x1 = (att *)malloc(sizeof(att));
x1->b = 3;
strcpy(x1->a, "TWO");
if(HASH_MAP_FIND(att)(map, &x1)){
printf("Finding: FOUND %s\n", x1->a);
}
printf("\nMAP SIZE : Before deletion -- %ld\n", map->size);
att *x2 = (att *)malloc(sizeof(att));
x2->b = 3;
strcpy(x2->a, "TWO");
if(HASH_MAP_ERASE(att)(map, x2)){
if(HASH_MAP_FIND(att)(map, &x2)){
printf("Finding %s\n", x2->a);
} else {
printf("Erased 1\n");
}
}
x = (att *)malloc(sizeof(att));
x->b = 3;
strcpy(x->a, "TWO");
if(HASH_MAP_ERASE(att)(map, x)){
if(HASH_MAP_FIND(att)(map, &x)){
printf("Finding %s\n", x->a);
} else {
printf("Erased 1\n");
}
} else {
printf("Erased 2\n");
}
printf("MAP SIZE : After deletion -- %ld\n", map->size);
HASH_MAP_PRINT(att)(map);
y = (att *)malloc(sizeof(att));
y->b = 3;
strcpy(y->a, "TWO");
HASH_MAP_INSERT(att)(map, &y, HMDR_FIND);
printf("MAP SIZE : After reinsertion -- %ld\n", map->size);
HASH_MAP_PRINT(att)(map);
HASH_MAP_DESTROY(att)(map);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int fibo(int n){
if((n==0) ||(n==1)){
return n;
}else{
return fibo(n-1)+fibo(n-2);
}
}
main(void){
setlocale(LC_ALL, "portuguese");
int a,i;
printf("Digite ate quantos numeros voc quer:");
scanf("%d",&a);
for(i = 0; i <= a; i++){
printf(" %d ", fibo(i));
}
printf("\n");
system("pause");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "circular_double_linked_list.h"
int main()
{
struct Node *list1 = NULL;
while (1)
{
char *command;
int i1, i2, i3, i4;
scanf("%s", command);
scanf("%d", &i1);
scanf("%d", &i2);
printf("%s %d", command, i2);
if (strcmp(command, "add") == 0)
{
while(1) {
int i;
scanf("%d", &i2);
printf("%d\n", i2);
fflush(stdout);
break;
return 0;
if(i == '\n') break;
list1 = add(list1, i);
printList(list1,1);
}
}
break;
}
}
/*else if (strcmp(command, "delete")==0)
{
while(1) {
int i;
scanf("%d",&i);
if(i == '\n') break;
list1 = delete(list1, i);
printList(list1,1);
}
}
else if (strcmp(command, "sort")==0)
{
list1 = sort(list1);
printList(list1,1);
}
else if (strcmp(command, "print")==0)
{
char *p;
scanf("%s",p);
if (strcmp(p, "true"))
printList(list1, 1);
else
printList(list1, 0);
}
else
printf("Wrong");*/
/*
struct Node *list1 = NULL;
list1 = add(list1, 10);
list1 = add(list1, 8);
list1 = add(list1, 7);
list1 = add(list1, 2);
list1 = add(list1, 19);
list1 = add(list1, 1);
list1 = add(list1, 20);
list1 = add(list1, 15);
list1 = add(list1, 20);
list1 = add(list1, 2);
printList(list1,1);
list1 = delete(list1,3);
list1 = delete(list1,4);
printList(list1,1);
list1 = delete(list1,2);
printList(list1,1);
list1 = add(list1, 100);
printList(list1,1);
list1 = add(list1, 20);
list1 = add(list1, 18);
list1 = add(list1, 55);
printList(list1,1);
list1 = delete(list1,55);
printList(list1,1);
list1 = sort(list1);
printList(list1,1);
list1 = sort(list1);
printList(list1,1);
list1 = delete(list1,100);
printList(list1,1);
list1 = sort(list1);
printList(list1,1);
printList(list1,0);*/
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main() {
char s[100];
gets(s);
int i=0, j=0, k=0, dom=0, flag=0;
int l = strlen(s);
while(s[i]!='@' && i<l) {
if(s[i]>=97 && s[i]<=122 || s[i]>=48 && s[i]<=57 || s[i]=='_') {
if(k>10){
printf("Id too long!");
flag=1;
exit(1);
} else {
k++;
i++;
}
} else {
printf("Invalid Id!");
flag=1;
exit(1);
}
}
i++;
while(s[i]!='.' && i<l) {
if(s[i]>=97 && s[i]<=122 || s[i]>=48 && s[i]<=57) {
if(j>10){
printf("Domain name too long!");
flag=1;
exit(1);
} else {
k++;
i++;
}
} else {
printf("Invalid Id!");
flag=1;
exit(1);
}
}
i++;
while(s[i]!='\0' && i<l){
if(s[i]>=97 && s[i]<=122 || s[i]>=48 && s[i]<=57 ) {
if(dom>3){
printf("Domain name too long!");
flag=1;
exit(1);
} else {
k++;
i++;
}
} else {
printf("Invalid Id!");
flag=1;
exit(1);
}
}
if(flag==0)
printf("Valid email id!");
return 0;
}
|
C
|
#include "bstitr.h"
#include "../bstitrpreord.h"
#include "../bstitrinord.h"
#include "../bstitrpostord.h"
#include "../bstitrbreadth.h"
#include "adt/adt.h"
#include "adt/ptr/adtptr.h"
/* ************************************************************************** */
BSTType* ConstructBSTIterative()
{
BSTType* type = (BSTType*)malloc(sizeof(BSTType));
type->bst_Destruct = &bstDestructItr;
type->bst_Equal = &bstEqualItr;
type->bst_Insert = &bstInsertItr;
type->bst_Clone = &bstCloneItr;
type->bst_Exists = &bstExistsItr;
type->bst_Remove = &bstRemoveItr;
type->bst_GetNRemoveMin = &GetNRemoveMinItr;
type->bst_GetMin = &bstGetMinItr;
type->bst_RemoveMin = &bstRemoveMinItr;
type->bst_GetMax = &bstGetMaxItr;
type->bst_GetNRemoveMax = &GetNRemoveMaxItr;
type->bst_RemoveMax = &bstRemoveMaxItr;
type->bst_GetPredecessor = &bstGetPredecessorItr;
type->bst_GetNRemovePredecessor = &bstGetNRemovePredecessorItr;
type->bst_RemovePredecessor = &bstRemovePredecessorItr;
type->bst_GetSuccessor = &bstGetSuccessorItr;
type->bst_GetNRemoveSuccessor = &bstGetNRemoveSuccessorItr;
type->bst_RemoveSuccessor = &bstRemoveSuccessorItr;
type->bst_PreOrderMap = &bstPreOrderMapItr;
type->bst_PostOrderMap = &bstPostOrderMapItr;
type->bst_InOrderMap = &bstInOrderMapItr;
type->bst_BreadthMap = &bstBreadthMapItr;
type->bst_PreOrderFold = &bstPreOrderFoldItr;
type->bst_PostOrderFold = &bstPostOrderFoldItr;
type->bst_InOrderFold = &bstInOrderFoldItr;
type->bst_BreadthFold = &bstBreadthFoldItr;
type->bst_GetData = &bstGetDataItr;
return type;
}
/* ************************************************************************** */
void DestructBSTIterative(BSTType* type)
{
free(type);
}
/* ************************************************************************** */
bool bstEqualItr(void* treeroot, void* treerootx)
{
BSTNode* root = (BSTNode*)treeroot;
BSTNode* rootx = (BSTNode*)treerootx;
BSTNode* node = NULL;
BSTNode* nodex = NULL;
ITRType* itrType = ConstructBSTPreOrderIterator();
ITRObject* iter = itrConstruct(itrType, root);
ITRObject* iterx = itrConstruct(itrType, rootx);
while(!itrTerminated(iter) && !itrTerminated(iterx)){
node = (BSTNode*)itrElement(iter);
nodex = (BSTNode*)itrElement(iterx);
if(adtCompare(node->data, nodex->data) != 0){
return false;
}
itrSuccessor(iter);
itrSuccessor(iterx);
}
if(!itrTerminated(iter) || !itrTerminated(iterx)){
return false;
}
return true;
}
/* ************************************************************************** */
void bstDestructItr(void* treeroot)
{
BSTNode* root = (BSTNode*)treeroot;
ITRType* itrType = ConstructBSTPostOrderIterator();
ITRObject* iter = itrConstruct(itrType, root);
DataType* ptrType = ConstructPtrDataType();
DataObject* ptr = adtConstruct(ptrType);
BSTNode* node;
while(!itrTerminated(iter)){
ptr->value = (BSTNode*)itrElement(iter);
node = ptr->value;
free(node);
itrSuccessor(iter);
}
itrDestruct(iter);
DestructBSTPostOrderIterator(itrType);
}
/* ************************************************************************** */
bool bstExistsItr(void* treeroot, DataObject* elem)
{
BSTNode* root = (BSTNode*)treeroot;
BSTNode* curr = root;
while(curr != NULL){
if(adtCompare(curr->data, elem) > 0){
curr = curr->LeftPtr;
} else if (adtCompare(curr->data, elem) < 0){
curr = curr->RightPtr;
} else if (adtCompare(curr->data, elem) == 0){
return true;
}
}
return false;
}
/* ************************************************************************** */
void * bstRemoveItr(void* treeroot, DataObject* elem )
{
BSTNode* root = (BSTNode*)treeroot;
BSTNode *pred = NULL, *curr = root;
while (curr) {
if (adtCompare(curr->data, elem) > 0) {
pred = curr;
curr = curr->LeftPtr;
} else if (adtCompare(curr->data, elem) < 0) {
pred = curr;
curr = curr->RightPtr;
} else {
// *isRemoved = true;
if (pred) {
if (pred->LeftPtr == curr) {
pred->LeftPtr = RemoveRoot(pred->LeftPtr);
} else {
pred->RightPtr = RemoveRoot(pred->RightPtr);
}
curr = NULL;
} else {
return RemoveRoot(curr);
}
}
}
return root;
}
/* ************************************************************************** */
void * RemoveRoot(void* treeroot)
{
BSTNode* root = (BSTNode*) treeroot;
if (root) {
if (root->LeftPtr && root->RightPtr) {
DataObject* tmpData;
root->RightPtr = GetNRemoveMinItr(root->RightPtr, &tmpData);
adtDestruct(root->data);
root->data = tmpData;
}
else {
BSTNode* tmp = root;
adtDestruct(root->data);
root = !(root->LeftPtr) ? root->RightPtr : root->LeftPtr;
free(tmp);
}
}
return root;
}
/* ************************************************************************** */
void * bstGetMinItr(void* treeroot)
{
BSTNode * root = (BSTNode*)treeroot;
BSTNode* curr = root;
DataObject* ret = NULL;
if(root == NULL){
return NULL;
}
while(curr->LeftPtr != NULL) {
curr = curr->LeftPtr;
}
if(curr != NULL){
ret = adtClone(curr->data);
return ret;
}
printf("il minimo e': ");
adtWriteToMonitor(ret);
return NULL;
}
/* ************************************************************************** */
void * GetNRemoveMinItr(void * treeroot , void * treefather){
BSTNode* root = (BSTNode*)treeroot;
BSTNode* previous = (BSTNode*)treefather;
BSTNode* curr = root;
BSTNode* ancestor = previous;
while(curr->LeftPtr !=NULL){
ancestor=curr;
curr= curr->LeftPtr;
}
if (curr == ancestor->LeftPtr) {
ancestor->LeftPtr = curr->RightPtr;
} else ancestor->RightPtr = curr->RightPtr;
return curr;
}
/* ************************************************************************** */
void * bstRemoveMinItr(void* treeroot, void * treefather)
{
BSTNode* root = (BSTNode*)treeroot;
BSTNode* previous = (BSTNode*)treefather;
BSTNode* curr=NULL;
BSTNode* ancestor=NULL;
ancestor=previous;
curr=root;
while(curr->LeftPtr != NULL){
ancestor=curr;
curr= curr->LeftPtr;
}
if(curr == ancestor->LeftPtr){
ancestor->LeftPtr = curr->RightPtr;
} else ancestor->RightPtr = curr->RightPtr;
return root;
}
/* ************************************************************************** */
void * bstGetMaxItr(void* treeroot)
{
BSTNode* root = (BSTNode*)treeroot;
BSTNode* curr = root;
while(curr->RightPtr !=NULL){
curr= curr->RightPtr;
}
if (curr != NULL) {
DataObject* ret = adtClone(curr->data);
return ret;
}
return NULL;
}
/* ************************************************************************** */
void * GetNRemoveMaxItr(void * treeroot , void * treefather){
BSTNode* root = (BSTNode*)treeroot;
BSTNode* previous = (BSTNode*)treefather;
BSTNode* curr=NULL;
BSTNode* ancestor=NULL;
ancestor=previous;
curr=root;
while(curr->RightPtr !=NULL){
ancestor=curr;
curr= curr->RightPtr;
}
if(curr == ancestor->RightPtr){
ancestor->RightPtr = curr->LeftPtr;
} else ancestor->LeftPtr = curr->LeftPtr;
return curr;
}
/* ************************************************************************** */
void * bstRemoveMaxItr(void* treeroot, void* prenode)
{
BSTNode* root = (BSTNode*)treeroot;
BSTNode* previous = (BSTNode*)prenode;
BSTNode* curr=NULL;
BSTNode* ancestor=NULL;
ancestor=previous;
curr=root;
while(curr->RightPtr !=NULL){
ancestor=curr;
curr= curr->RightPtr;
}
if(curr == ancestor->RightPtr){
ancestor->RightPtr = curr->LeftPtr;
} else ancestor->LeftPtr = curr->LeftPtr;
return curr;
}
/* ************************************************************************** */
void * bstGetSuccessorItr(void* treeroot, DataObject* elem)
{
BSTNode* root = (BSTNode*)treeroot;
BSTNode* curr = root;
BSTNode* node = NULL;
while(curr != NULL && adtCompare(curr->data, elem) != 0){
if(adtCompare(curr->data, elem) < 0){
curr = curr->RightPtr;
} else if(adtCompare(curr->data, elem) > 0) {
node = curr;
curr = curr->LeftPtr;
}
}
if(curr != NULL && curr->RightPtr != NULL){
node = bstGetMinItr(curr->RightPtr);
}
if(node != NULL) {
return node->data;
}
else return NULL;
}
/* ************************************************************************** */
void * bstGetPredecessorItr(void* treeroot, DataObject* elem)
{
BSTNode* root = (BSTNode*)treeroot;
BSTNode* curr = root;
BSTNode* pred = NULL;
BSTNode* ancestor = NULL;
while(curr != NULL) {
if (adtCompare(curr->data, elem) > 0) {
curr = curr->LeftPtr;
} else if (adtCompare(curr->data, elem) < 0) {
ancestor = curr;
curr = curr->RightPtr;
} else if (adtCompare(curr->data, elem) == 0) {
if(curr->LeftPtr != NULL) {
pred = bstGetMaxItr(curr->LeftPtr);
if(pred) {
return adtClone(pred->data);
}
else return NULL;
} else if(curr->LeftPtr == NULL && curr->RightPtr != NULL){
pred = ancestor;
}
if(curr->LeftPtr == NULL && curr->RightPtr == NULL){
pred = ancestor;
}
if(pred) {
return adtClone(pred->data);
}
}
}
if(ancestor != NULL) {
return ancestor->data;
}
else return NULL;
}
/* ************************************************************************** */
void * bstGetNRemovePredecessorItr(void* treeroot, DataObject* elem, void* prenode)
{
BSTNode* root = (BSTNode*)treeroot;
BSTNode* ancestor = (BSTNode*)prenode;
BSTNode *curr = root;
BSTNode *pred = NULL;
BSTNode *ret = NULL;
while(curr != NULL && adtCompare(curr->data, elem) != 0){
if(adtCompare(curr->data, elem) < 0){
if(pred != NULL) {
ancestor = pred;
}
pred = curr;
curr = curr->RightPtr;
}else{
ancestor = curr;
curr = curr->LeftPtr;
}
}
if(curr == NULL || curr->LeftPtr == NULL){
ret = pred;
BSTNode *elemToRemove = pred;
if(pred == NULL){
return NULL;
}
if(pred->RightPtr == NULL && pred->LeftPtr == NULL){
BSTNode *retnode = (BSTNode*)malloc(sizeof(BSTNode));
retnode->data= adtConstruct(pred->data->type);
retnode->data->value = adtGetValue(pred->data);
adtSetValue(pred->data, elemToRemove->data->value);
if(ancestor->RightPtr == pred){
ancestor->RightPtr = elemToRemove->RightPtr;
}else{
ancestor->LeftPtr = elemToRemove->RightPtr;
}
return retnode;
}
if(pred->RightPtr!=NULL){
BSTNode *retnode = (BSTNode*)malloc(sizeof(BSTNode));
retnode->data = adtConstruct(pred->data->type);
elemToRemove = GetNRemoveMinItr(pred->RightPtr, pred);
retnode->data->value = adtGetValue(pred->data);
adtSetValue(pred->data, elemToRemove->data->value);
return retnode;
}else if(pred->LeftPtr!=NULL){
BSTNode *retnode = (BSTNode*)malloc(sizeof(BSTNode));
retnode->data= adtConstruct(pred->data->type);
elemToRemove= GetNRemoveMaxItr(pred->LeftPtr, pred);
retnode->data->value= adtGetValue(pred->data);
adtSetValue(pred->data, elemToRemove->data->value);
}
}else{
ret = GetNRemoveMaxItr(curr->LeftPtr, curr);
}
return ret;
}
/* ************************************************************************** */
void * bstRemovePredecessorItr(void* treeroot, DataObject* elem, void* prenode)
{
BSTNode* root = (BSTNode*)treeroot;
BSTNode* ancestor = (BSTNode*)prenode;
BSTNode *curr = root;
BSTNode *pred = NULL;
BSTNode *ret = NULL;
while(curr != NULL && adtCompare(curr->data, elem) != 0){
if(adtCompare(curr->data, elem) < 0){
if(pred != NULL) {
ancestor = pred;
}
pred = curr;
curr = curr->RightPtr;
}else{
ancestor = curr;
curr = curr->LeftPtr;
}
}
if(curr == NULL || curr->LeftPtr == NULL){
ret = pred;
BSTNode* elemToRemove = pred;
if(pred == NULL){
return NULL;
}
if(pred->RightPtr == NULL && pred->LeftPtr == NULL){
BSTNode *retnode = (BSTNode*)malloc(sizeof(BSTNode));
retnode->data= adtConstruct(pred->data->type);
retnode->data->value = adtGetValue(pred->data);
adtSetValue(pred->data, elemToRemove->data->value);
if(ancestor->RightPtr == pred){
ancestor->RightPtr = elemToRemove->RightPtr;
}else{
ancestor->LeftPtr = elemToRemove->RightPtr;
}
return retnode;
}
if(pred->RightPtr!=NULL){
BSTNode* retnode = (BSTNode*)malloc(sizeof(BSTNode));
retnode->data = adtConstruct(pred->data->type);
elemToRemove = GetNRemoveMinItr(pred->RightPtr, pred);
retnode->data->value = adtGetValue(pred->data);
adtSetValue(pred->data, elemToRemove->data->value);
return retnode;
}else if(pred->LeftPtr!=NULL){
BSTNode* retnode = (BSTNode*)malloc(sizeof(BSTNode));
retnode->data= adtConstruct(pred->data->type);
elemToRemove= GetNRemoveMaxItr(pred->LeftPtr, pred);
retnode->data->value= adtGetValue(pred->data);
adtSetValue(pred->data, elemToRemove->data->value);
}
}else{
ret = GetNRemoveMaxItr(curr->LeftPtr, curr);
}
return ret;
}
/* ************************************************************************** */
void * bstInsertItr(void* treeroot, DataObject* elem, int* size)
{
BSTNode* root = (BSTNode*)treeroot;
BSTNode *ancestor= NULL;
BSTNode *curr= root;
while(curr != NULL){
if(adtCompare(curr->data, elem)>0){
ancestor= curr;
curr= curr->LeftPtr;
}else if(adtCompare(curr->data, elem)<0){
ancestor= curr;
curr= curr->RightPtr;
}else{
return root;
}
}
curr = (BSTNode*)malloc(sizeof(BSTNode));
curr->data= adtClone(elem);
*((int*)size) = *((int*)size)+1;
if(ancestor == NULL){
curr->LeftPtr = curr->RightPtr = NULL;
root= curr;
}else if(adtCompare(ancestor->data, elem)>0){
curr->LeftPtr = curr->RightPtr = NULL;
ancestor->LeftPtr= curr;
}else{
curr->LeftPtr = curr->RightPtr = NULL;
ancestor->RightPtr= curr;
}
return root;
}
/* ************************************************************************** */
void * bstGetNRemoveSuccessorItr(void* treeroot, DataObject* elem, void* prenode)
{
BSTNode* root = (BSTNode*)treeroot;
BSTNode* ancestor = (BSTNode*)prenode;
BSTNode *curr= root;
BSTNode *succ= NULL;
BSTNode *ret= NULL;
while(curr!=NULL && adtCompare(curr->data, elem)!=0){
if(adtCompare(curr->data, elem)<0){
ancestor = curr;
curr= curr->RightPtr;
}else{
if(succ != NULL) {
ancestor = succ;
}
succ= curr;
curr= curr->LeftPtr;
}
}
if(curr== NULL || curr->RightPtr==NULL){
ret= succ;
BSTNode *del= succ;
if(succ==NULL){
return NULL;
}
if(succ->RightPtr==NULL && succ->LeftPtr==NULL){
BSTNode *retnode= (BSTNode*)malloc(sizeof(BSTNode));
retnode->data= adtConstruct(succ->data->type);
retnode->data->value= adtGetValue(succ->data);
adtSetValue(succ->data, del->data->value);
if(ancestor->RightPtr==succ){
ancestor->RightPtr= del->RightPtr;
}else{
ancestor->LeftPtr= del->LeftPtr;
}
return retnode;
}
if(ancestor == NULL){
BSTNode *retnode= (BSTNode*)malloc(sizeof(BSTNode));
retnode->data= adtConstruct(succ->data->type);
del= GetNRemoveMinItr(succ->RightPtr, succ);
retnode->data->value= adtGetValue(succ->data);
adtSetValue(succ->data, del->data->value);
return retnode;
}else{
if(succ->RightPtr == NULL){
if(ancestor->RightPtr==succ){
ancestor->RightPtr= del->RightPtr;
}else{
ancestor->LeftPtr= del->LeftPtr;
}
}else if(succ->LeftPtr == NULL){
if(ancestor->RightPtr == succ){
ancestor->RightPtr= del->RightPtr;
}else{
ancestor->LeftPtr= del->RightPtr;
}
}else{
BSTNode *retnode = (BSTNode*)malloc(sizeof(BSTNode));
retnode->data= adtConstruct(succ->data->type);
del= GetNRemoveMaxItr(succ->LeftPtr, succ);
retnode->data->value= adtGetValue(succ->data);
adtSetValue(succ->data, del->data->value);
return retnode;
}
}
}else{
ret = GetNRemoveMinItr(curr->RightPtr, curr);
}
return ret;
}
/* ************************************************************************** */
void * bstRemoveSuccessorItr(void* treeroot, DataObject* elem, void* prenode)
{
BSTNode* root = (BSTNode*)treeroot;
BSTNode* ancestor = (BSTNode*)prenode;
BSTNode *curr= root;
BSTNode *succ= NULL;
BSTNode *ret= NULL;
while(curr!=NULL && adtCompare(curr->data, elem)!=0){
if(adtCompare(curr->data, elem)<0){
ancestor = curr;
curr= curr->RightPtr;
}else{
if(succ != NULL) {
ancestor = succ;
}
succ= curr;
curr= curr->LeftPtr;
}
}
if(curr== NULL || curr->RightPtr==NULL){
ret= succ;
BSTNode *del= succ;
if(succ==NULL){
return NULL;
}
if(succ->RightPtr==NULL && succ->LeftPtr==NULL){
BSTNode *retnode= (BSTNode*)malloc(sizeof(BSTNode));
retnode->data= adtConstruct(succ->data->type);
retnode->data->value= adtGetValue(succ->data);
adtSetValue(succ->data, del->data->value);
if(ancestor->RightPtr==succ){
ancestor->RightPtr= del->RightPtr;
}else{
ancestor->LeftPtr= del->LeftPtr;
}
return retnode;
}
if(ancestor == NULL){
BSTNode *retnode= (BSTNode*)malloc(sizeof(BSTNode));
retnode->data= adtConstruct(succ->data->type);
del= GetNRemoveMinItr(succ->RightPtr, succ);
retnode->data->value= adtGetValue(succ->data);
adtSetValue(succ->data, del->data->value);
return retnode;
}else{
if(succ->RightPtr == NULL){
if(ancestor->RightPtr==succ){
ancestor->RightPtr= del->RightPtr;
}else{
ancestor->LeftPtr= del->LeftPtr;
}
}else if(succ->LeftPtr == NULL){
if(ancestor->RightPtr == succ){
ancestor->RightPtr= del->RightPtr;
}else{
ancestor->LeftPtr= del->RightPtr;
}
}else{
BSTNode *retnode = (BSTNode*)malloc(sizeof(BSTNode));
retnode->data= adtConstruct(succ->data->type);
del= GetNRemoveMaxItr(succ->LeftPtr, succ);
retnode->data->value= adtGetValue(succ->data);
adtSetValue(succ->data, del->data->value);
return retnode;
}
}
}else{
ret = GetNRemoveMinItr(curr->RightPtr, curr);
}
return ret;
}
/* ************************************************************************** */
void * bstCloneItr(void* treeroot)
{
BSTNode* root=(BSTNode*)treeroot;
if(root==NULL)
{
return NULL;
}
StackType* stkType = ConstructStackVecType();
StackObject* stack = stkConstruct(stkType);
DataType* ptrType = ConstructPtrDataType();
DataObject* ptr = adtConstruct(ptrType);
DataObject* data;
BSTNode* clone;
BSTNode* newClone;
clone = (BSTNode*)malloc(sizeof(BSTNode));
clone->data = adtClone(root->data);
clone->LeftPtr = NULL;
clone->RightPtr = NULL;
BSTNode* newRoot = clone;
while(root != NULL) {
if(root->LeftPtr != NULL && clone->LeftPtr == NULL) {
newClone=(BSTNode*)malloc(sizeof(BSTNode));
newClone->data=adtClone(root->LeftPtr->data);
newClone->LeftPtr = newClone->RightPtr = NULL;
clone->LeftPtr=newClone;
adtSetValue(ptr,clone);
stkPush(stack,ptr);
adtSetValue(ptr,root);
stkPush(stack,ptr);
root=root->LeftPtr;
clone=clone->LeftPtr;
} else if(root->RightPtr != NULL && clone->RightPtr == NULL) {
newClone=(BSTNode*)malloc(sizeof(BSTNode));
newClone->data=adtClone(root->RightPtr->data);
newClone->LeftPtr = newClone->RightPtr = NULL;
clone->RightPtr = newClone;
adtSetValue(ptr,clone);
stkPush(stack,ptr);
adtSetValue(ptr,root);
stkPush(stack,ptr);
root = root->RightPtr;
clone = clone->RightPtr;
} else {
if(!stkEmpty(stack)) {
data=stkTopNPop(stack);
root=(BSTNode*)adtGetValue(data);
adtDestruct(data);
data=stkTopNPop(stack);
clone=(BSTNode*)adtGetValue(data);
adtDestruct(data);
} else {
root=NULL;
clone=NULL;
}
}
}
return newRoot;
}
/* ************************************************************************** */
void bstPreOrderMapItr(void* treeroot, MapFun fun, void* par)
{
BSTNode* root = (BSTNode*)treeroot;
ITRType* itrType = ConstructBSTPreOrderIterator();
ITRObject* iter = itrConstruct(itrType, root);
BSTNode* node;
while(!itrTerminated(iter)){
node = (BSTNode*)itrElement(iter);
fun(node->data, par);
itrSuccessor(iter);
}
}
/* ************************************************************************** */
void bstPostOrderMapItr(void* treeroot, MapFun fun, void* par)
{
BSTNode* root = (BSTNode*)treeroot;
ITRType* itrType = ConstructBSTPostOrderIterator();
ITRObject* iter = itrConstruct(itrType, root);
BSTNode* node;
while(!itrTerminated(iter)){
node = (BSTNode*)itrElement(iter);
fun(node->data, par);
itrSuccessor(iter);
}
}
/* ************************************************************************** */
void bstInOrderMapItr(void* treeroot, MapFun fun, void* par)
{
BSTNode* root = (BSTNode*)treeroot;
ITRType* itrType = ConstructBSTInOrderIterator();
ITRObject* iter = itrConstruct(itrType, root);
BSTNode* node;
while(!itrTerminated(iter)){
node = (BSTNode*)itrElement(iter);
fun(node->data, par);
itrSuccessor(iter);
}
}
/* ************************************************************************** */
void bstBreadthMapItr(void* treeroot, MapFun fun, void* par)
{
BSTNode* root = (BSTNode*)treeroot;
ITRType* itrType = ConstructBSTBreadthIterator();
ITRObject* iter = itrConstruct(itrType, root);
BSTNode* node;
while(!itrTerminated(iter)){
node = (BSTNode*)itrElement(iter);
fun(node->data, par);
itrSuccessor(iter);
}
}
/* ************************************************************************** */
void bstPreOrderFoldItr(void* treeroot, FoldFun fun, void* accum, void* par)
{
BSTNode* root = (BSTNode*)treeroot;
ITRType* itrType = ConstructBSTPreOrderIterator();
ITRObject* iter = itrConstruct(itrType, root);
BSTNode* node;
while(!itrTerminated(iter)){
node = (BSTNode*)itrElement(iter);
fun(node->data, accum, par);
itrSuccessor(iter);
}
}
/* ************************************************************************** */
void bstInOrderFoldItr(void* treeroot, FoldFun fun, void* accum, void* par)
{
BSTNode* root = (BSTNode*)treeroot;
ITRType* itrType = ConstructBSTInOrderIterator();
ITRObject* iter = itrConstruct(itrType, root);
BSTNode* node;
while(!itrTerminated(iter)){
node = (BSTNode*)itrElement(iter);
fun(node->data, accum, par);
itrSuccessor(iter);
}
}
/* ************************************************************************** */
void bstPostOrderFoldItr(void* treeroot, FoldFun fun, void* accum, void* par)
{
BSTNode* root = (BSTNode*)treeroot;
ITRType* itrType = ConstructBSTPostOrderIterator();
ITRObject* iter = itrConstruct(itrType, root);
StackType* stkType = stkConstructVecType();
StackObject* stack = stkConstruct(stkType);
BSTNode* node;
while(!itrTerminated(iter)){
node = (BSTNode*)itrElement(iter);
fun(node->data, accum, par);
itrSuccessor(iter);
}
}
/* ************************************************************************** */
void bstBreadthFoldItr(void* treeroot, FoldFun fun, void* accum, void* par)
{
BSTNode* root = (BSTNode*)treeroot;
ITRType* itrType = ConstructBSTBreadthIterator();
ITRObject* iter = itrConstruct(itrType, root);
BSTNode* node;
while(!itrTerminated(iter)){
node = (BSTNode*)itrElement(iter);
fun(node->data, accum, par);
itrSuccessor(iter);
}
}
/* ************************************************************************** */
void* bstGetDataItr(void* roott, DataObject* elemToFind)
{
BSTNode* root = (BSTNode*)roott;
if(root==NULL){
return NULL;
}
if(adtCompare(root->data, elemToFind)==0){
return root->data;
}
if(adtCompare(root->data, elemToFind) > 0){
return bstGetDataItr(root->LeftPtr, elemToFind);
}
return bstGetDataItr(root->RightPtr, elemToFind);
}
|
C
|
// MT, 2016mar01
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>
#include "Obj.h"
#include "Str.h"
char* Str_from_long_create(long const inVal)
{
char* retVal = NULL;
char const * const formatStr = "%ld";
char dummy[] = { '\0' };
int const strLen = snprintf(dummy, sizeof(dummy)*sizeof(char), formatStr, inVal); // Without terminating '\0'.
if(strLen>0)
{
retVal = malloc((((size_t)strLen)+1)*(sizeof *retVal));
assert(retVal!=NULL);
if(sprintf(retVal, formatStr, inVal)!=strLen)
{
free(retVal);
retVal = NULL;
}
}
return retVal;
}
char* Str_from_double_create(double const inVal)
{
char* retVal = NULL;
char const * const formatStr = "%f"; // Add some formatting?
char dummy[] = { '\0' };
int const strLen = snprintf(dummy, sizeof(dummy)*sizeof(char), formatStr, inVal); // Without terminating '\0'.
if(strLen>0)
{
retVal = malloc((((size_t)strLen)+1)*(sizeof *retVal));
assert(retVal!=NULL);
if(sprintf(retVal, formatStr, inVal)!=strLen)
{
free(retVal);
retVal = NULL;
}
}
return retVal;
}
char* Str_append_create(char * const inStrA, char const * const inStrB)
{
char* retVal = NULL;
assert((inStrA!=NULL)&&(inStrB!=NULL));
if((inStrA!=NULL)&&(inStrB!=NULL))
{
size_t const aLen = strlen(inStrA),
bLen = strlen(inStrB),
valLen = aLen+bLen+1;
retVal = realloc(inStrA, valLen*(sizeof *retVal));
assert(retVal!=NULL);
if(valLen==1)
{
retVal[0] = '\0';
}
else
{
size_t pos = aLen;
strncpy(retVal+pos, inStrB, bLen);
pos += bLen;
retVal[pos] = '\0';
assert(pos==(valLen-1));
}
}
return retVal;
}
char* Str_concat_create(char const * const inStrA, char const * const inStrB)
{
char* retVal = NULL;
assert((inStrA!=NULL)&&(inStrB!=NULL));
if((inStrA!=NULL)&&(inStrB!=NULL))
{
size_t const aLen = strlen(inStrA),
bLen = strlen(inStrB),
valLen = aLen+bLen+1;
retVal = malloc(valLen*(sizeof *retVal));
assert(retVal!=NULL);
if(valLen==1)
{
retVal[0] = '\0';
}
else
{
size_t pos = 0;
strncpy(retVal+pos, inStrA, aLen);
pos += aLen;
strncpy(retVal+pos, inStrB, bLen);
pos += bLen;
retVal[pos] = '\0';
assert(pos==(valLen-1));
}
}
return retVal;
}
char* Str_copy_create(char const * const inStr)
{
char* retVal = NULL;
assert(inStr!=NULL);
if(inStr!=NULL)
{
size_t const strLen = strlen(inStr)+1;
retVal = malloc(strLen*(sizeof *retVal));
assert(retVal!=NULL);
strncpy(retVal, inStr, strLen);
}
return retVal;
}
double* Str_double_create(char const * const inStr, size_t const inLen, size_t * const inOutIndex)
{
double *retVal = NULL,
buf = 0.0;
char * endPtr = NULL;
assert(inStr!=NULL);
assert(inOutIndex!=NULL);
if((*inOutIndex)<inLen)
{
buf = strtod(inStr+(*inOutIndex), &endPtr);
}
size_t const consumeLen = (size_t)(endPtr-(inStr+(*inOutIndex)));
if(consumeLen>0)
{
retVal = Obj_double_create(buf);
*inOutIndex = (*inOutIndex)+consumeLen;
}
return retVal;
}
char* Str_string_create(char const * const inStr, size_t const inLen, char const inTag, size_t * const inOutIndex)
{
char *retVal = NULL,
*buf = NULL;
do
{
size_t terminatorPos = 0,
escapedCount = 0,
bufPos = 0;
if(((*inOutIndex)+2)>=inLen)
{
break;
}
if(inStr[*inOutIndex]!=inTag)
{
break;
}
++(*inOutIndex);
size_t const firstCharPos = *inOutIndex;
while((*inOutIndex)<inLen)
{
if(inStr[*inOutIndex]==inTag)
{
if(inStr[(*inOutIndex)-1]!='\\')
{
terminatorPos = *inOutIndex;
++(*inOutIndex); // (consumes closing ")
break;
}
++escapedCount;
}
++(*inOutIndex);
}
if(terminatorPos==0)
{
break;
}
size_t const len = terminatorPos-firstCharPos, // (without terminator)
bufLen = len-escapedCount+1,
lastBufPos = bufLen-1;
buf = malloc(bufLen*(sizeof *buf));
assert(buf!=NULL);
size_t const firstCharPosPlusLen = firstCharPos+len,
lastCharPos = firstCharPosPlusLen-1;
for(size_t i = firstCharPos;i<firstCharPosPlusLen;++i)
{
if(!((inStr[i]=='\\')&&(i<lastCharPos)&&(inStr[i+1]==inTag)))
{
buf[bufPos++] = inStr[i];
}
}
assert(bufPos==lastBufPos);
buf[lastBufPos] = '\0';
retVal = buf;
buf = NULL;
}while(false);
free(buf);
return retVal;
}
|
C
|
#include <stdio.h>
void add(int * array)
{
array[3]=array[0]+array[1]+array[2];
printf("\nthe sum is %d",array[3]);
}
int main(void)
{
int array[4],i;
void add(int *);
printf("enter the three numbers");
for(i=0;i<3;i++)
{
scanf("%d",&array[i]);
}
add(array);
return 0;
}
|
C
|
/*
* Copyright 2021 The CFU-Playground Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdint.h>
#include "cfu.h"
//
// In this function, place C code to emulate your CFU. You can switch between
// hardware and emulated CFU by setting the CFU_SOFTWARE_DEFINED DEFINE in
// the Makefile.
uint32_t software_cfu(int funct3, int funct7, uint32_t rs1, uint32_t rs2)
{
uint32_t retval = 0;
if (funct3 & 0x2)
{
// bitreverse (rs1)
for (int i = 0; i < 32; ++i)
{
retval |= (((rs1 >> i) & 0x1) << (31 - i));
}
}
else if (funct3 & 0x1)
{
// byte swap (rs1)
for (int i = 0; i < 32; i += 8)
{
retval |= (((rs1 >> i) & 0xff) << (24 - i));
}
}
else
{
// byte sum
retval += (rs1 & 0xff) + (rs2 & 0xff);
rs1 >>= 8;
rs2 >>= 8;
retval += (rs1 & 0xff) + (rs2 & 0xff);
rs1 >>= 8;
rs2 >>= 8;
retval += (rs1 & 0xff) + (rs2 & 0xff);
rs1 >>= 8;
rs2 >>= 8;
retval += (rs1 & 0xff) + (rs2 & 0xff);
}
return retval;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = malloc(sizeof(int) * 5);
volatile int i;
int sum = 0;
for (i = 0; i < 5; i++) {
arr[i] = i;
}
for (i = 0; i < 5; i++) {
sum += arr[i];
}
free(arr);
return sum;
}
|
C
|
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <sys/unistd.h>
#include <sys/signal.h>
#include <string.h>
#include <pwd.h>
#include <time.h>
#include <sys/types.h>
int usr1_caught = 0;
int sigs_to_send;
pid_t catcher_pid;
typedef enum sig_mode {
KILL, QUEUE, RT, UNDEFINED
} sig_mode;
sig_mode get_mode(char* name){
if(!strcmp(name, "kill"))
return KILL;
if(!strcmp(name, "sigqueue"))
return QUEUE;
if(!strcmp(name, "sigrt"))
return RT;
return UNDEFINED;
}
void kill_sending(){
for(int i = 0; i < sigs_to_send; ++i){
kill(catcher_pid, SIGUSR1);
}
kill(catcher_pid, SIGUSR2);
}
void queue_sending(){
union sigval sv;
sv.sival_int = SIGEV_NONE;
for(int i = 0; i < sigs_to_send; ++i){
sigqueue(catcher_pid, SIGUSR1, sv);
}
sigqueue(catcher_pid, SIGUSR2, sv);
}
void rt_sending(){
for(int i = 0; i < sigs_to_send; ++i){
kill(catcher_pid, SIGRTMIN);
}
kill(catcher_pid, SIGRTMAX);
}
void usr1_reaction(){
++usr1_caught;
}
void usr2_reaction(){
printf("Sender caught %d/%d signals\n", usr1_caught, sigs_to_send);
exit(0);
}
int main(int argc, char** argv){
if(argc < 4){
printf("Too few arguments\n");
exit(-1);
}
catcher_pid = atoi(argv[1]);
sigs_to_send = atoi(argv[2]);
char* mode = argv[3];
struct sigaction sa_usr1;
struct sigaction sa_usr2;
sigfillset(&sa_usr1.sa_mask);
sigfillset(&sa_usr2.sa_mask);
sa_usr1.sa_flags = 0;
sa_usr2.sa_flags = 0;
sa_usr1.sa_handler = &usr1_reaction;
sa_usr2.sa_handler = &usr2_reaction;
sig_mode send_mode = get_mode(mode);
switch(send_mode) {
case KILL:
case QUEUE:
sigaction(SIGUSR1, &sa_usr1, NULL);
sigaction(SIGUSR2, &sa_usr2, NULL);
break;
case RT:
sigaction(SIGRTMIN, &sa_usr1, NULL);
sigaction(SIGRTMAX, &sa_usr2, NULL);
break;
default:
printf("Mode is incorrect\n");
exit(-1);
}
switch(send_mode) {
case KILL: kill_sending(); break;
case QUEUE: queue_sending(); break;
case RT: rt_sending(); break;
default: printf("Mode is incorrect\n"); exit(-1);
}
while(1){
pause();
}
return 0;
}
|
C
|
/* A simple server in the internet domain using TCP
The port number is passed as an argument */
#include "sls_detector_defs.h"
#include "slsDetectorServer_defs.h"
#include "communication_funcs.h"
#include "slsDetectorServer_funcs.h"
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
extern int sockfd;
void error(char *msg){
perror(msg);
}
int main(int argc, char *argv[]){
int portno, b;
int retval=OK;
int sd, fd;
int debugflag = 0;
// if socket crash, ignores SISPIPE, prevents global signal handler
// subsequent read/write to socket gives error - must handle locally
signal(SIGPIPE, SIG_IGN);
// circumvent the basic tests
if(argc > 1) {
if(!strcasecmp(argv[1],"-debug")){
debugflag = 1;
argc=1;
}
}
#ifdef STOP_SERVER
char cmd[100];
#endif
if (argc==1) {
portno = DEFAULT_PORTNO;
cprintf(BLUE,
"********************************************************\n"
"********* opening control server on port %d **********\n"
"********************************************************\n\n"
, portno);
b=1;
basictests(debugflag);
#ifdef STOP_SERVER
sprintf(cmd,"%s %d &",argv[0],DEFAULT_PORTNO+1);
//cprintf(BLUE,"cmd:%s\n", cmd);
system(cmd);
#endif
} else {
portno = DEFAULT_PORTNO+1;
if ( sscanf(argv[1],"%d",&portno) == 0) {
printf("could not open stop server: unknown port\n");
return 1;
}
cprintf(BLUE,
"********************************************************\n"
"*********** opening stop server on port %d ***********\n"
"********************************************************\n\n"
, portno);
b=0;
}
init_detector(b); //defined in slsDetectorServer_funcs
sd=bindSocket(portno); //defined in communication_funcs
sockfd=sd;
if (getServerError(sd)) { //defined in communication_funcs
printf("server error!\n");
return -1;
}
/* assign function table */
function_table(); //defined in slsDetectorServer_funcs
#ifdef VERBOSE
printf("function table assigned \n");
#endif
if (b)
printf("\nControl Server Ready...\n\n");
else
printf("\nStop Server Ready...\n\n");
/* waits for connection */
while(retval!=GOODBYE) {
#ifdef VERBOSE
printf("\n");
#endif
#ifdef VERY_VERBOSE
printf("Waiting for client call\n");
#endif
fd=acceptConnection(sockfd); //defined in communication_funcs
#ifdef VERY_VERBOSE
printf("Conenction accepted\n");
#endif
if (fd>0) {
retval=decode_function(fd); //defined in slsDetectorServer_funcs
#ifdef VERY_VERBOSE
printf("function executed\n");
#endif
closeConnection(fd); //defined in communication_funcs
#ifdef VERY_VERBOSE
printf("connection closed\n");
#endif
}
}
exitServer(sockfd); //defined in communication_funcs
printf("Goodbye!\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <pwd.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
void print_lstat(const char* );
void if_dir(DIR* );
void display_file_type(int );
void display_permisions(int );
char* formatdate(char*, time_t );
int is_dir(const char* );
int main(int argc, char **argv)
{
if (argc == 1) {
DIR *dir = opendir(".");
if_dir(dir);
closedir(dir);
} else {
int i;
for (i = 1; i < argc; ++i) {
if (is_dir(argv[i]) == 0) continue;
print_lstat(argv[i]);
}
}
return 0;
}
void if_dir(DIR *dir) {
char *file_name;
struct dirent *curr_file_in_dir; //struct with info about directory
while ((curr_file_in_dir = readdir(dir)) != NULL) {
file_name = curr_file_in_dir->d_name;
print_lstat(file_name);
}
}
void print_lstat(const char* file_name)
{
struct stat buf;
if (lstat(file_name, &buf) == -1 ) {
perror("file not exist");
return;
}
if (is_dir(file_name) == 0) return;
display_file_type(buf.st_mode);
display_permisions(buf.st_mode);
printf(" %lu ", buf.st_nlink); // hard link counter
struct passwd *pw_d;
pw_d = getpwuid(buf.st_uid); //Get user name(from UID) into struct passwf.pw_name
printf("%s ",pw_d->pw_name); // User Name
pw_d = getpwuid(buf.st_gid); // Make for GID same as for UID
printf("%s ",pw_d->pw_name); // Group Name
printf("%ld ",buf.st_size); //file size
char date_buf[36];
printf("%s ", formatdate(date_buf, buf.st_mtime));
printf("%s\n",file_name);
}
void display_file_type ( int st_mode )
{
switch ( st_mode & S_IFMT )
{
case S_IFDIR: putchar ( 'd' ); return;
case S_IFCHR: putchar ( 'c' ); return;
case S_IFBLK: putchar ( 'b' ); return;
case S_IFREG: putchar ( '-' ); return;
case S_IFLNK: putchar ( 'l' ); return;
case S_IFSOCK: putchar ( 's' ); return;
}
}
// Display permissions by format: rwxrwxrwx
void display_permisions(int st_mode)
{
printf( (st_mode & S_IRUSR) ? "r" : "-");
printf( (st_mode & S_IWUSR) ? "w" : "-");
printf( (st_mode & S_IXUSR) ? "x" : "-");
printf( (st_mode & S_IRGRP) ? "r" : "-");
printf( (st_mode & S_IWGRP) ? "w" : "-");
printf( (st_mode & S_IXGRP) ? "x" : "-");
printf( (st_mode & S_IROTH) ? "r" : "-");
printf( (st_mode & S_IWOTH) ? "w" : "-");
printf( (st_mode & S_IXOTH) ? "x" : "-");
}
char* formatdate(char* str, time_t val)
{
strftime(str, 36, "%b %d %H:%M", localtime(&val));
return str;
}
// Check that file is a directory
int is_dir(const char* name)
{
DIR *dir = opendir(name);
if (dir) {
closedir(dir);
return 1;
} else {
return 0;
}
}
|
C
|
#include <stdio.h>
void print_array(int array[], int num)
{
int i;
for (i = 0; i < num; i++)
{
printf("%d ", array[i]);
}
printf("\n");
return;
}
void express(int a[][2], int express_node[], int num)
{
int i, k;
for (i = 0; i < num; i++)
{
k = a[i][1];
express_node[k] = a[i][0];
}
return;
}
int main(void)
{
int a[][2] ={{2,4}, {4,1}, {1,0}, {0,3}};
int express_node[] = {-1,-1,-1,-1};
int num;
num = sizeof(a)/sizeof(a[0]);
express(a, express_node, num);
print_array(express_node, num+1);
return 0;
}
|
C
|
//
// binary.c
//
//
// Created by Adenike Adeyemi on 5/18/17.
//
//
#include <stdio.h>
int main(){
FILE *fp;
fp = fopen("test4.bin", "wb");
if(!fp){
printf("Unable to open\n");
return 1;
}
// char x[10]="ABCDEFGHIJ";
//void function1()
//int function2()
//int function3(int x, int y)
char x[88] =
{
0xA2, 0x58, //200 set I to end of instructions
0x60, 0x06, //202 V0 = 3
0xF0, 0x18, //204 set timer
0xC1, 0xFF, //206 rand values
0xC2, 0xFF, //208
0xC3, 0xFF, //20A
0xC4, 0xFF, //20C
0xC5, 0xFF, //20E
0xC6, 0xFF, //210
0xC7, 0xFF, //212
0xC8, 0xFF, //214
0xC9, 0xFF, //216
0xCA, 0xFF, //218
0xCB, 0xFF, //21A
0xCC, 0xFF, //21C
0xCD, 0xFF, //21E
0xCE, 0xFF, //220
0xFE, 0x55, //222 dump registers in memory
0xF0, 0x15, //224 set delay
0xF0, 0x18, //226 set timer
0x60, 0x03, //228 V0 = 3
0x61, 0x47, //22A V1 = 71
0x62, 0xFC, //22C v2 = 252
0x63, 0x00, //22E 0 everything
0x64, 0x00, //230
0x65, 0x00, //232
0x66, 0x00, //234
0x67, 0x00, //236
0x68, 0x00, //238
0x69, 0x00, //23A
0x6A, 0x00, //23C
0x6B, 0x00, //23E
0x6C, 0x00, //240
0x6D, 0x00, //242
0x6E, 0x00, //244
0xA2, 0x68, //246
0xF0, 0x33, //248
0xA2, 0x78, //24A
0xF1, 0x33, //24C
0xA2, 0x88, //24E
0xF2, 0x33, //250
0xA2, 0x58, //252
0xFE, 0x65, //254
0x00, 0x00 //256
};
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
fclose(fp);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_free_utility.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mgras <mgras@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/02/21 19:15:37 by mgras #+# #+# */
/* Updated: 2016/02/21 19:17:27 by mgras ### ########.fr */
/* */
/* ************************************************************************** */
#include "rtv1.h"
#include "mlx.h"
#include "key_define.h"
/*
** Quick uitlity for freeing shit
** Could be so wrong btw so watch out
*/
char **ft_free_char_tab(char **del)
{
int ss;
ss = 0;
if (del == NULL)
return (NULL);
while (del[ss])
{
if (del[ss])
ft_strdel(&(del[ss]));
ss++;
}
free(del);
del = NULL;
return (del);
}
int **ft_free_int_tab(int **del, int len)
{
int ss;
ss = 0;
if (del == NULL)
return (NULL);
while (ss != len)
{
if (del[ss])
free(del[ss]);
ss++;
}
free(del);
del = NULL;
return (del);
}
void ft_free_obj_lst(t_object *start)
{
t_object *swp;
while (start)
{
swp = start->next;
free(start);
start = NULL;
start = swp;
}
}
void ft_free_light_lst(t_light *start)
{
t_light *swp;
while (start)
{
swp = start->next;
free(start);
start = NULL;
start = swp;
}
}
|
C
|
//
// LSUtils.h
// LockScreen
//
// Copyright (c) 2014 SquareCodeCamp. All rights reserved.
//
#ifndef LockScreen_LSUtils_h
#define LockScreen_LSUtils_h
typedef enum {
LSDirectionUndefined = -1,
LSDirectionUp = 0,
LSDirectionDown,
}LSDirection;
LSDirection directionBetweenPoints(CGPoint pointA, CGPoint pointB) {
return pointB.y > pointA.y;
}
CGFloat angleBetweenPoints(CGPoint pointA, CGPoint pointB) {
CGFloat deltaY = pointB.y - pointA.y;
CGFloat deltaX = pointB.x - pointA.x;
return atan(deltaY / deltaX) * (180 / M_PI);
}
CGFloat distanceBetweenPoints(CGPoint pointA, CGPoint pointB) {
CGFloat xDist = (pointB.x - pointA.x);
CGFloat yDist = (pointB.y - pointA.y);
CGFloat distance = sqrt((xDist * xDist) + (yDist * yDist));
return distance;
}
CGFloat angleAmongPoints(CGPoint pointA, CGPoint pointB, CGPoint pointC)
{
CGFloat c = distanceBetweenPoints(pointA, pointB);
CGFloat a = distanceBetweenPoints(pointB, pointC);
CGFloat b = distanceBetweenPoints(pointA, pointC);
return (180 / M_PI) * acos(((a * a) + (c * c) - (b * b))/((2.0 * (a) * (c))));
}
#endif
|
C
|
#ifndef TB_ARRAY_H
#define TB_ARRAY_H
#include <stdlib.h>
#define TB_ARRAY_HDR_ELEM size_t
#define TB_ARRAY_HDR_SIZE 2 * sizeof(TB_ARRAY_HDR_ELEM)
#define tb_array__hdr(b) ((size_t*)(void*)(b) - 2)
#define tb_array__cap(b) tb_array__hdr(b)[0]
#define tb_array__len(b) tb_array__hdr(b)[1]
#define tb_array_len(b) ((b) ? tb_array__len(b) : 0)
#define tb_array_cap(b) ((b) ? tb_array__cap(b) : 0)
#define tb_array_resize(b, n) (*((void**)&(b)) = tb_array__resize((b), (n), sizeof(*(b))))
#define tb_array_reserve(b, n) (*((void**)&(b)) = tb_array__reserve((b), (n), sizeof(*(b))))
#define tb_array_grow(b, n) (*((void**)&(b)) = tb_array__grow((b), (n), sizeof(*(b))))
#define tb_array_push(b, v) (tb_array_grow((b), 1), (b)[tb_array__len(b)++] = (v))
#define tb_array_free(b) (tb_array_resize(b, 0))
#define tb_array_pack(b) (tb_array_resize((b), tb_array_len(b)))
#define tb_array_clear(b) ((b) ? tb_array__len(b) = 0 : 0)
#define tb_array_last(b) ((b) + tb_array_len(b))
#define tb_array_sizeof(b) (tb_array_len(b) * sizeof(*(b)))
void* tb_array__resize(void* buf, size_t new_cap, size_t elem_size);
void* tb_array__reserve(void* buf, size_t reserve, size_t elem_size);
void* tb_array__grow(void* buf, size_t increment, size_t elem_size);
#endif /* !TB_ARRAY_H */
|
C
|
#include "queue.h"
#include "queueTest.h"
#include <stdlib.h>
#include <stdio.h>
bool queueTest(void)
{
bool result = true;
Queue* queue = initQueue();
enqueue(queue, 5);
if (empty(queue))
{
result = false;
printf(" 1 \n");
}
if (dequeue(queue) != 5)
{
printf(" 2 \n");
}
if (!empty(queue))
{
result = false;
printf(" 3 \n");
}
enqueue(queue, 6);
enqueue(queue, 7);
if (dequeue(queue) != 6)
{
result = false;
printf(" 4 \n");
}
deleteQueue(&queue);
if (queue != NULL)
{
result = false;
}
return result;
}
|
C
|
#include "environment.h"
#include <stdio.h>
#include <errno.h>
#define DETECT_DEVICE_ERROR(dev_fd, DEVICE) \
if (dev_fd < 0) { \
printf("Device open error : %s\n", DEVICE); \
exit(1); \
}
// construct_environment must be called by main function
// when program begins
void
construct_environment(struct environment** env)
{
struct environment *new_env = calloc(1, sizeof(struct environment));
/* Open Device and Check whether an error occurs */
/* devices for reading data */
new_env->ev_fd = open(EVENT_DEVICE, O_RDWR | O_NONBLOCK);
DETECT_DEVICE_ERROR(new_env->ev_fd, EVENT_DEVICE);
new_env->push_switch_fd = open(PUSH_SWITCH_DEVICE, O_RDWR | O_NONBLOCK);
DETECT_DEVICE_ERROR(new_env->push_switch_fd, PUSH_SWITCH_DEVICE);
/* devices for writing data */
new_env->fnd_fd = open(FND_DEVICE, O_RDWR);
DETECT_DEVICE_ERROR(new_env->fnd_fd, FND_DEVICE);
new_env->led_fd = open(LED_DEVICE, O_RDWR);
DETECT_DEVICE_ERROR(new_env->led_fd, LED_DEVICE);
new_env->dot_fd = open(FPGA_DOT_DEVICE, O_WRONLY);
DETECT_DEVICE_ERROR(new_env->dot_fd, FPGA_DOT_DEVICE);
new_env->lcd_fd = open(FPGA_TEXT_LCD_DEVICE, O_WRONLY);
DETECT_DEVICE_ERROR(new_env->lcd_fd, FPGA_TEXT_LCD_DEVICE);
/* Setting the key of message queue */
new_env->msg_key = 1234;
new_env->mode = 0;
*env = new_env;
printf("Construct Environment\n");
}
// destruct_environment must be called by main process
// when input and output process are terminated
void
destruct_environment(struct environment* env)
{
#define CLOSE_ERROR_CHECK(fd) \
if (close(fd) == -1) { \
printf("Errno: %d\n", errno); \
perror("close"); \
}
CLOSE_ERROR_CHECK(env->ev_fd);
CLOSE_ERROR_CHECK(env->push_switch_fd);
CLOSE_ERROR_CHECK(env->fnd_fd);
CLOSE_ERROR_CHECK(env->led_fd);
CLOSE_ERROR_CHECK(env->lcd_fd);
CLOSE_ERROR_CHECK(env->dot_fd);
#undef CLOSE_ERROR_CHECK
free(env);
printf("Destruct Envrionment\n");
}
|
C
|
/*
** my_str_to_wordtab_double.c for mysh in /home/sachs_a/delivery/system_unix/
**
** Made by Alexandre Sachs
** Login <sachs_a@epitech.net>
**
** Started on Wed Mar 15 10:59:39 2017 Alexandre Sachs
** Last update Mon Apr 3 20:45:16 2017 Alexandre Sachs
*/
#include <stdlib.h>
#include "basics.h"
int separators_double(char *str, char sep, char sep2)
{
int i;
int c;
i = 0;
c = 0;
if (!str)
return (-1);
while ((str[i] == sep && str[i]) || (str[i] == sep2 && str[i]))
i++;
while (str[i])
{
while ((str[i] != sep && str[i]) && (str[i] != sep2 && str[i]))
i++;
c++;
while ((str[i] == sep && str[i]) || (str[i] == sep2 && str[i]))
i++;
}
return (c);
}
int word_size_double(char *str, int c, char sep, char sep2)
{
int i;
i = 0;
if (!str)
return (-1);
while ((str[i] == sep && str[i]) || (str[i] == sep2 && str[i]))
i++;
while (c != 1)
{
while ((str[i] != sep && str[i]) && (str[i] != sep2 && str[i]))
i++;
while ((str[i] == sep && str[i]) || (str[i] == sep2 && str[i]))
i++;
c--;
}
c = 0;
while ((str[i] != sep && str[i] != sep2) && str[i++] != '\0')
c++;
return (c + 1);
}
char **my_str_to_wordtab_double(char *str, char sep, char sep2)
{
char **tab;
int i;
int j;
int k;
k = 0;
i = 0;
if (!str || (tab = malloc(sizeof(char *) *
(separators_double(str, sep, sep2) + 1))) == NULL)
return (NULL);
while (i != (separators_double(str, sep, sep2)))
{
j = 0;
if ((tab[i] = malloc(sizeof(char) * (word_size_double(str, (i + 1), sep,
sep2)))) == NULL)
return (NULL);
while ((str[k] != sep && str[k]) && (str[k] != sep2 && str[k]))
tab[i][j++] = str[k++];
tab[i][j] = '\0';
while ((str[k] == sep && str[k]) || (str[k] == sep2 && str[k]))
k++;
i++;
}
tab[i] = NULL;
return (tab);
}
|
C
|
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <stdlib.h>
static void sighandler(int signo){
if (signo == SIGUSR1){
printf("My Parent PID: %d \n", getppid());
}
if (signo == SIGINT){
int crash = open("status.txt", O_CREAT|O_RDWR, 0777);
if (crash < 0){
perror("ERROR with status.txt");
return;
}
lseek(crash,0,SEEK_END);
int stats = write(crash,"SIGINT Program Terminated.\n",27);
close(crash);
exit(0);
}
}
int main(){
signal(SIGUSR1,sighandler);
signal(SIGINT,sighandler);
while(1){
printf("I am currently running: %d \n", getpid());
kill(getpid(),SIGUSR1);
sleep(1);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
int notIn(float x,float y,int r)
{
if((x+2)*(x+2)+(y-2)*(y-2)<=r*r)return 0;
if((x-2)*(x-2)+(y-2)*(y-2)<=r*r)return 0;
if((x+2)*(x+2)+(y+2)*(y+2)<=r*r)return 0;
if((x-2)*(x-2)+(y+2)*(y+2)<=r*r)return 0;
return 1;
}
int main(int argc,char **argv)
{
printf("%s\n",argv[0]);
printf("输入坐标, 以空格分开: ");
float x,y;
scanf("%f %f",&x,&y);
if(!notIn(x,y,1)) printf("10m\n");
else printf("0m\n");
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_extra_functions_3.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rgarcia- <rgarcia-@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/09/15 17:53:25 by rgarcia- #+# #+# */
/* Updated: 2020/09/15 18:11:08 by rgarcia- ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static int ft_countdigits_hexa(unsigned int c)
{
int i;
i = 1;
while (c / 16 > 0)
{
i++;
c /= 16;
}
return (i);
}
char *ft_to_hexa(t_struct *t)
{
int i;
char *s;
char *str;
i = ft_countdigits_hexa(t->aux_u);
if (!(s = malloc(sizeof(char) * 17)))
return (0);
if (!(str = malloc(sizeof(char) * (i + 1))))
return (0);
if (t->flag_mayus)
s = "0123456789ABCDEF";
else
s = "0123456789abcdef";
i--;
while (t->aux_u > 0)
{
str[i] = s[t->aux_u % 16];
t->aux_u /= 16;
i--;
}
return (str);
}
static int ft_countdigits_hexa_l(unsigned long long int c)
{
int i;
i = 1;
while (c / 16 > 0)
{
i++;
c /= 16;
}
return (i);
}
char *ft_to_hexa_l(t_struct *t)
{
int i;
char *s;
char *str;
i = ft_countdigits_hexa_l(t->aux_u_l);
if (!(s = malloc(sizeof(char) * 17)))
return (0);
if (!(str = malloc(sizeof(char) * (i + 1))))
return (0);
if (t->flag_mayus)
s = "0123456789ABCDEF";
else
s = "0123456789abcdef";
i--;
while (t->aux_u_l > 0)
{
str[i] = s[t->aux_u_l % 16];
t->aux_u_l /= 16;
i--;
}
return (str);
}
char *ft_strjoin(char const *s1, char const *s2)
{
int i;
int j;
char *str;
if (s1 != 0 && s2 != 0)
{
i = ft_strlen(s1) + ft_strlen(s2) + 1;
if (!(str = (char *)malloc(i)))
return (0);
i = 0;
while (s1[i] != '\0')
{
str[i] = (char)s1[i];
i++;
}
j = 0;
while (s2[j] != '\0')
{
str[i + j] = (char)s2[j];
j++;
}
str[i + j] = '\0';
return (str);
}
return (0);
}
|
C
|
#include"book.h"
Book *head = NULL;
int nbook = 0;
int choice(){
while(1){
system("clear");
int m;
printf("\n*************************欢迎使用图书管理系统*************************\n\n");
printf("请输入项目前编号执行相关操作:\n\n");
printf("[1] 查看图书\n[2] 添加新图书\n[3] 修改图书信息\n[4] 删除图书\n");
printf("[0] 退出系统\n");
scanf("%d",&m);
switch(m){
case 1:
viewbook();
break;
case 2:
addbook();
break;
case 3:
modbook();
break;
case 4:
delbook();
break;
case 0:
return 0;
default:
printf("采集项目参数失败");
break;
}}
return 1;
}
int viewbook(){
system("clear");
Book *bp;
printf("图书编号 图书名 图书存数 图书状态\n");
for(bp =head; bp != NULL; bp = bp->next){
printf("%d \t%s\t%d\t%s\n", bp->id, bp->name,bp->count,bp->status ? "不可借" : "可借");
}sleep(2);
if(nbook){
return nbook;
}else{
printf("图书馆还没有图书哦\n");
return 0;
}
sleep(2);
return -1;
}
void printbook(Book *bp){
printf("图书编号 图书名图书存数图书状态\n");
printf("%d \t%s\t%d\t%s\n", bp->id, bp->name,bp->count,bp->status ? "不可借" : "可借");
}
int addbook(){
system("clear");
char sname[MAXNAME];
int id, count;
char *namep;
while(1){
id = 0;
count = 0;
namep = NULL;
printf("请输入图书名:\n");
scanf("%s", sname);
getchar();
printf("请输入图书编号:\n");
scanf("%d", &id);
getchar();
if(!(id > 0 && id < 1000)){
printf("输入编号不符合要求");
fflush(stdin);
continue;
}
printf("请输入图书数量:\n");
scanf("%d", &count);
getchar();
if(!(count > 0 && count < 50)){
printf("输入数目不符合要求");
fflush(stdin);
continue;
}
Book *bp;
if((bp = lookup(namep = strdup(sname), id)) == NULL){
bp = (Book *)malloc(sizeof (Book));
if(bp == NULL || (bp->name = namep) == NULL){
printf("注册图书失败");
fflush(stdin);
continue;
}
bp->id = id;
bp->count = count;
bp->status = AVAILABLE;
++nbook;
/* Book *p = head;
while(p->next != NULL)
{
p = p->next;
}
p->next = bp; */
bp->next = head;
head = bp;
printf("图书 %s 注册成功\n", sname);
return id;
}else{
fflush(stdin);
printf("图书名或编号已经被占用");
}
}
sleep(2);
return -1;
}
Book *lookup(char *s, int id){
Book *bp;
for(bp = head; bp != NULL; bp = bp->next){
if(id == bp->id || strcmp(s, bp->name) == 0){
return bp;
}
}
return NULL;
}
int modbook(){
system("clear");
Book *bp = NULL;
while(1){
int id = 0;
printf("请输入要修改信息的图书编号:\n");
scanf("%d", &id);
getchar();
if(!(id > 0 && id < 1000)){
fflush(stdin);
printf("图书编号不符合要求");
continue;
}
if((bp = lookup("", id)) != NULL){
printf("以下为要修改的图书的现有信息:\n");
printbook(bp);
printf("[1] 修改图书名\n[2] 修改图书数量\n[3] 修改图书状态\n[0] 放弃修改\n");
while(1){
int i;
scanf("%d", &i);
getchar();
if(!(i == 1 || i == 2 || i == 3 || i == 0)){
fflush(stdin);
printf("输入项目前编号选择相关项目");
continue;
}
switch(i){
case 1:
while(1){
char newname[MAXNAME], *namep;
printf("图书名:\n");
scanf("%s", newname);
getchar();
if((lookup(namep = strdup(newname), 0)) != NULL){
fflush(stdin);
printf("图书名已存在");
continue;
}
if((bp->name = namep) != NULL){
printf("修改成功\n");
sleep(2);
return id;
}
}
break;
case 2:
while(1){
int bnum;
printf("输入图书数量:\n");
scanf("%d", &bnum);
getchar();
if(!(bnum > 0 || bnum < 1000)){
fflush(stdin);
printf("数目不符合要求");
continue;
}
bp->count = bnum;
printf("修改成功\n");
sleep(2);
return id;
}
break;
case 3:
while(1){
char c;
int status;
status = bp->status;
status == AVAILABLE ? printf("修改状态为[不可借]: Y N\n") : printf("修改状态为[可借]: Y N\n");
scanf("%c", &c);
getchar();
if(!( c == 'Y' || c == 'y' || c == 'N' || c == 'n')){
fflush(stdin);
printf("指令无效");
continue;
}
if(c == 'Y' || c == 'y'){
status == AVAILABLE ? bp->status = UNAVAILABLE : (bp->status = AVAILABLE);
printf("修改成功\n");
sleep(2);
return id;
}else{
printf("放弃修改\n");
return 0;
}
}
break;
case 0:
return 0;
default:
printf("获取参数失败");
break;
}
}
}else{
printf("没有此图书\n");
return 0;
}
}
return -1;
}
int delbook(){
system("clear"); ///////////////////////////////////////////
Book *bp, *fbp;
int id = 0;
printf("请输入要注销的图书编号:\n");
scanf("%d", &id);
getchar();
if(!(id > 0 && id < 1000)){
fflush(stdin);
printf("图书编号不符合要求");
return -1;
}
for(fbp = bp = head; bp != NULL; fbp = bp, bp = bp->next){
if(bp->id == id){
printbook(bp);
break;
}
}
if(bp != NULL){
while(1){
printf("确定要注销此图书:Y N\n");
char YN;
scanf("%c", &YN);
getchar();
if(!((YN == 'Y' || YN == 'y') || (YN == 'N' || YN == 'n'))){
fflush(stdin);
printf("指令无效\n");
continue;
}
if(YN == 'Y' || YN == 'y'){
bp == head ? head = bp->next : (fbp->next = bp->next);
free(bp->name); //2018-05-26修改:添加释放name这块内存//bp内存的只是指向name的指针
free(bp);
bp = NULL;
printf("图书注销成功\n");
break;
}else{
printf("放弃注销\n");
return 0;
}
}
return id;
}else{
printf("要注销的图书编号不存在\n");
return -1;
}
sleep(2);
return -1;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include"stack.h"
void StackInit(Stack* pstack)
{
pstack->topIndex = -1;
}
int SIsEmpty(Stack* pstack)
{
if(pstack->topIndex==-1)
return TRUE;
else return FALSE;
}
void SPush(Stack* pstack , Data data)
{
pstack->topIndex += 1;
pstack->stack[pstack->topIndex] = data;
}
Data SPop(Stack* pstack)
{
int rIdx;
if(SIsEmpty(pstack))
{
printf("Stack Memory Error!");
exit(-1);
}
rIdx = pstack->topIndex;
return pstack->stack[rIdx];
}
Data SPeek(Stack* pstack)
{
if(SIsEmpty(pstack))
{
printf("Stack Meomory Error!");
exit(-1);
}
return pstack->stack[pstack->topIndex];
}
void QueueInit(Queue *pq)
{
pq->front = 0;
pq->rear = 0;
}
int QIsEmpty(Queue* pq)
{
if(pq->front == pq->rear)
return TRUE;
else return FALSE;
}
int NextPosIdx(int pos)
{
if(pos == QUE_LEN-1) return 0;
else return pos+1;
}
void Enqueue(Queue* pq, Data data)
{
if(NextPosIdx(pq->rear) == pq->front)
{
printf("Queue Memory Error!");
exit(-1);
}
pq->rear = NextPosIdx(pq->rear);
pq->queArr[pq->front] = data;
}
Data Dequeue(Queue* pq)
{
if(QIsEmpty(pq))
{
printf("Queue Memory Error!");
exit(-1);
}
pq->front = NextPosIdx(pq->front);
return pq->queArr[pq->front];
}
Data QPeek(Queue* pq)
{
if(QIsEmpty(pq))
{
printf("Queue Memory Error!");
exit(-1);
}
return pq->queArr[NextPosIdx(pq->front)];
}
|
C
|
/* Copyright 2013-2015 Drew Thoreson
*
* This file is part of Telos.
*
* Telos is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, version 2 of the License.
*
* Telos 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 Telos. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#define TIMESPEC_INIT(s, ns) \
{ \
.tv_sec = s, \
.tv_nsec = ns \
}
#define TIMESPEC(name, s, ns) \
struct timespec name = TIMESPEC_INIT(s, ns)
#define ITIMERSPEC(name, s, ns) \
struct itimerspec name = { \
.it_interval = {0}, \
.it_value = TIMESPEC_INIT(s, ns) \
}
#define HALFSEC_NSEC 500000000
static const int one = 1;
static const int two = 2;
static const TIMESPEC(less_than_one, 0, HALFSEC_NSEC);
static const TIMESPEC(less_than_two, 1, HALFSEC_NSEC);
static const TIMESPEC(less_than_three, 2, HALFSEC_NSEC);
static _Noreturn void nanosleep_proc(const struct timespec *how_long, char c)
{
nanosleep(how_long, NULL);
printf("%c", c);
exit(0);
}
static void sleep_test(void)
{
printf("Testing sleep... abc ?= ");
fflush(stdout);
if (!fork())
nanosleep_proc(&less_than_two, 'b');
if (!fork())
nanosleep_proc(&less_than_one, 'a');
nanosleep(&less_than_three, NULL);
puts("c");
fflush(stdout);
}
static void alarm_handler(int signo)
{
puts("rm");
}
static void alarm_test(void)
{
sigset_t set;
signal(SIGALRM, alarm_handler);
printf("Testing alarm... alrm ?= ");
fflush(stdout);
alarm(1);
if (alarm(1) <= 0)
printf("error");
printf("al");
fflush(stdout);
sigfillset(&set);
sigdelset(&set, SIGALRM);
sigsuspend(&set);
printf("Testing alarm(0)... ");
fflush(stdout);
alarm(2);
if (alarm(0) > 0)
puts("okay");
else
puts("error");
fflush(stdout);
}
static void timer_action(int signo, siginfo_t *info, void *context)
{
printf("1 ");
fflush(stdout);
}
static void timer_test(void)
{
timer_t tid;
sigset_t mask;
struct sigaction act;
ITIMERSPEC(time, 0, HALFSEC_NSEC);
sigprocmask(SIG_BLOCK, NULL, &mask);
act.sa_mask = mask;
act.sa_flags = SA_SIGINFO;
act.sa_sigaction = timer_action;
if (sigaction(SIGALRM, &act, NULL) == -1) {
printf("sigaction() failed\n");
}
if (timer_create(CLOCK_MONOTONIC, NULL, &tid) < 0) {
printf("timer_create() failed\n");
}
printf("Testing timers...\nVerify ascending: ");
fflush(stdout);
if (timer_settime(tid, 0, &time, NULL) < 0) {
printf("timer_settime() failed\n");
}
sleep(200); /* should be interrupted */
puts("2");
fflush(stdout);
}
static void clock_test(void)
{
struct timespec t;
if (clock_gettime(CLOCK_MONOTONIC, &t) < 0) {
printf("clock_gettime() failed\n");
return;
}
printf("CLOCK_MONOTONIC: %lu\n", t.tv_sec);
if (clock_gettime(CLOCK_REALTIME, &t) < 0) {
printf("clock_gettime() failed\n");
return;
}
printf("CLOCK_REALTIME: %lx\n", t.tv_sec);
}
#include <stdlib.h>
int main(int argc, char *argv[])
{
sleep_test();
alarm_test();
timer_test();
clock_test();
return 0;
}
|
C
|
/*
*******************************************************************************
\file ww.h
\brief Arbitrary length words
\project bee2 [cryptographic library]
\created 2012.04.18
\version 2023.02.02
\copyright The Bee2 authors
\license Licensed under the Apache License, Version 2.0 (see LICENSE.txt).
*******************************************************************************
*/
/*!
*******************************************************************************
\file ww.h
\brief Слова конечной длины
*******************************************************************************
*/
#ifndef __WW_H
#define __WW_H
#include "bee2/defs.h"
#include "bee2/core/safe.h"
#ifdef __cplusplus
extern "C" {
#endif
/*!
*******************************************************************************
\file ww.h
Реализованы операции с двоичными словами произвольной конечной длины, т.е.
элементами {0,1}*.
Двоичное слово задается массивом машинных слов: word w[n].
Разряды слова w[0] нумеруются от 0 (младший) до B_PER_W - 1 (старший),
разряды w[1] -- от B_PER_W (младший) до 2 * B_PER_W - 1 (старший) и т.д.
Запись [n]w означает, что слово w состоит из n машинных слов.
\pre Все входные указатели действительны.
\pre В функциях работы со словами по адресам памяти для слов
зарезервировано ясное из конекста либо уточняемое в описаниях функций
число машинных слов.
*******************************************************************************
*/
/*
*******************************************************************************
Псевдонимы
*******************************************************************************
*/
#if (B_PER_W == 16)
#include "bee2/core/u16.h"
#define wwRev2 u16Rev2
#define wwTo u16To
#define wwFrom u16From
#elif (B_PER_W == 32)
#include "bee2/core/u32.h"
#define wwRev2 u32Rev2
#define wwTo u32To
#define wwFrom u32From
#elif (B_PER_W == 64)
#include "bee2/core/u64.h"
#define wwRev2 u64Rev2
#define wwTo u64To
#define wwFrom u64From
#else
#error "Unsupported word size"
#endif /* B_PER_W */
/*! Корректное слово [n]a? */
#define wwIsValid(a, n) memIsValid((a), O_OF_W(n))
/*! Буферы слов [n]a и [n]b не пересекаются? */
#define wwIsDisjoint(a, b, n) memIsDisjoint(a, b, O_OF_W(n))
/*! Буферы слов [n]a и [n]b совпадают или не пересекаются? */
#define wwIsSameOrDisjoint(a, b, n) memIsSameOrDisjoint(a, b, O_OF_W(n))
/*! Буферы слов [n]a и [m]b не пересекаются? */
#define wwIsDisjoint2(a, n, b, m) memIsDisjoint2(a, O_OF_W(n), b, O_OF_W(m))
/*! Буферы слов [n]a, [m]b и [k]c не пересекаются? */
#define wwIsDisjoint3(a, n, b, m, c, k)\
memIsDisjoint3(a, O_OF_W(n), b, O_OF_W(m), c, O_OF_W(k))
/*
*******************************************************************************
Копирование, логические операции
*******************************************************************************
*/
/*! \brief Копирование слов
Cлово [n]a переписывается в [n]b:
\code
b <- a.
\endcode
\pre Буфер b либо не пересекается, либо совпадает с буфером a.
*/
void wwCopy(
word b[], /*!< [out] приемник */
const word a[], /*!< [in] источник */
size_t n /*!< [in] длина a в машинных словах */
);
/*! \brief Перестановка слов
Cлова [n]a и [n]b меняются местами:
\code
a <-> b.
\endcode
\pre Буфер b не пересекается с буфером a.
*/
void wwSwap(
word a[], /*!< [in,out] первое слово */
word b[], /*!< [in,out] второе слово */
size_t n /*!< [in] длина a и b в машинных словах */
);
/*! \brief Проверка совпадения слов
Проверяется совпадение слов [n]a и [n]b.
\return Признак сопадения.
\safe Имеется ускоренная нерегулярная редакция.
*/
bool_t wwEq(
const word a[], /*!< [in] первое слово */
const word b[], /*!< [in] второе слово */
size_t n /*!< [in] длина a и b в машинных словах */
);
bool_t SAFE(wwEq)(const word a[], const word b[], size_t n);
bool_t FAST(wwEq)(const word a[], const word b[], size_t n);
/*! \brief Сравнение слов
Cлова [n]a и [n]b сравниваются обратно-лексикографически.
\remark a > b, если a[n - 1] == b[n - 1],..., a[i] == b[i], a[i] > b[i].
\return 1, если a > b, или -1, если a < b, или 0, если a == b.
\safe Имеется ускоренная нерегулярная редакция.
*/
int wwCmp(
const word a[], /*!< [in] первое слово */
const word b[], /*!< [in] второе слово */
size_t n /*!< [in] длина a и b в машинных словах */
);
int SAFE(wwCmp)(const word a[], const word b[], size_t n);
int FAST(wwCmp)(const word a[], const word b[], size_t n);
/*! \brief Сравнение слов разной длины
Cлова [n]a и [m]b сравниваются обратно-лексикографически (см. wwCmp())
после дополнения нулями до слов одинаковой длины.
\return 1, если a > b, или -1, если a < b, или 0, если a == b.
\safe Имеется ускоренная нерегулярная редакция.
*/
int wwCmp2(
const word a[], /*!< [in] первое слово */
size_t n, /*!< [in] длина a в машинных словах */
const word b[], /*!< [in] второе слово */
size_t m /*!< [in] длина b в машинных словах */
);
int SAFE(wwCmp2)(const word a[], size_t n, const word b[], size_t m);
int FAST(wwCmp2)(const word a[], size_t n, const word b[], size_t m);
/*! \brief Сравнение слова c машинным словом
Слово [n]a сравнивается с машинным словом w.
\return 1, если a > w, или -1, если a < w, или 0, если a == w.
\safe Имеется ускоренная нерегулярная редакция.
*/
int wwCmpW(
const word a[], /*!< [in] сравниваемое слово */
size_t n, /*!< [in] длина a в машинных словах */
register word w /*!< [in] машинное слово */
);
int SAFE(wwCmpW)(const word a[], size_t n, register word w);
int FAST(wwCmpW)(const word a[], size_t n, register word w);
/*! \brief Cложение слов по модулю 2
Определяется поразрядная по модулю 2 сумма [n]с слов [n]a и [n]b:
\code
c <- a ^ b.
\endcode
\pre Буфер c либо не пересекается, либо совпадает с каждым из буферов a, b.
*/
void wwXor(
word c[], /*!< [out] сумма */
const word a[], /*!< [in] первое слагаемое */
const word b[], /*!< [in] второе слагаемое */
size_t n /*!< [in] длина a и b в машинных словах */
);
/*! \brief Добавление слова по модулю 2
К слову [n]b добавляется слово [n]a. Сложение выполняется поразрядно
по модулю 2:
\code
b <- a ^ b.
\endcode
\pre Буфер b либо не пересекается, либо совпадает с буфером a.
*/
void wwXor2(
word b[], /*!< [in,out] второе слагаемое / сумма */
const word a[], /*!< [in] первое слагаемое */
size_t n /*!< [in] длина a в машинных словах */
);
/*! \brief Обнуление слова
Слово [n]a обнуляется:
\code
a <- 0.
\endcode
*/
void wwSetZero(
word a[], /*!< [out] слово */
size_t n /*!< [in] длина a в машинных словах */
);
/*! \brief Присвоение слову значения -- машинного слова
Слову [n]a присваивается значение w, которое является машинным словом:
\code
a[0] <- w, a[1] <- 0, ..., a[n - 1] <- 0.
\endcode
\pre n > 0 или w == 0.
*/
void wwSetW(
word a[], /*!< [out] слово */
size_t n, /*!< [in] длина a в машинных словах */
register word w /*!< [in] значение */
);
/*! \brief Заполнение слова машинным словом
Всем машинным словам [n]a присваивается значение w:
\code
a[0] <- w, a[1] <- w, ..., a[n - 1] <- w.
\endcode
\pre n > 0 или w == 0.
*/
void wwRepW(
word a[], /*!< [out] слово */
size_t n, /*!< [in] длина a в машинных словах */
register word w /*!< [in] значение */
);
/*! \brief Нулевое слово?
Проверяется, что слово [n]a нулевое.
\return TRUE, если a - нулевое, и FALSE в противном случае.
\safe Имеется ускоренная нерегулярная редакция.
*/
bool_t wwIsZero(
const word a[], /*!< [in] проверяемое слово */
size_t n /*!< [in] длина a в машинных словах */
);
bool_t SAFE(wwIsZero)(const word a[], size_t n);
bool_t FAST(wwIsZero)(const word a[], size_t n);
/*! \brief Принимает значение -- машинное слово?
Проверяется, что слово [n]a принимает значение w, которое
является машинным словом:
\code
a[0] == w && a[1] == ... == a[n - 1] == 0?
\endcode
\remark Пустое слово (n == 0) принимает значение 0.
\return TRUE, если a = w, и FALSE в противном случае.
\safe Имеется ускоренная нерегулярная редакция.
*/
bool_t wwIsW(
const word a[], /*!< [in] проверяемое слово */
size_t n, /*!< [in] длина a в машинных словах */
register word w /*!< [in] значение */
);
bool_t SAFE(wwIsW)(const word a[], size_t n, register word w);
bool_t FAST(wwIsW)(const word a[], size_t n, register word w);
/*! \brief Повтор машинного слова?
Проверяется, что все машинные слова [n]a принимают значение w:
\code
a[0] == w && a[1] == w && ... && a[n - 1] == w?
\endcode
\remark В пустом слове (n == 0) повторяется значение 0.
\return TRUE, если a составлено из w, и FALSE в противном случае.
\safe Имеется ускоренная нерегулярная редакция.
*/
bool_t wwIsRepW(
const word a[], /*!< [in] проверяемое слово */
size_t n, /*!< [in] длина a в машинных словах */
register word w /*!< [in] значение */
);
bool_t SAFE(wwIsRepW)(const word a[], size_t n, register word w);
bool_t FAST(wwIsRepW)(const word a[], size_t n, register word w);
/*! \brief Размер значащей части слова в машинных словах
Определяется размер значащей части слова [n]a. Размер полагается равным
индексу последнего ненулевого машинного слова, увеличенному на единицу.
\remark Размер пустого (n == 0) или нулевого слов равняется 0.
\safe Функция нерегулярна.
*/
size_t wwWordSize(
const word a[], /*!< [in] слово */
size_t n /*!< [in] длина a в машинных словах */
);
/*! \brief Размер значащей части слова в октетах
Определяется размер значащей части слова [n]a. Размер полагается равным
индексу последнего ненулевого октета, увеличенному на единицу.
\remark Размер пустого (n == 0) или нулевого слов равняется 0.
\safe Функция нерегулярна.
*/
size_t wwOctetSize(
const word a[], /*!< [in] слово */
size_t n /*!< [in] длина a в машинных словах */
);
/*
*******************************************************************************
Операции с битами, кодирование
*******************************************************************************
*/
/*! \brief Проверить разряд слова
В слове a определяется разряд с номером pos.
\pre По адресу a зарезервировано W_OF_B(pos + 1) машинных слов.
\return TRUE, если бит ненулевой, и FALSE в противном случае.
*/
bool_t wwTestBit(
const word a[], /*!< [in] слово */
size_t pos /*!< [in] номер разряда */
);
/*! \brief Получить разряды слова
В слове a определяется разряды с номерами pos,..., pos + width - 1.
\pre По адресу a зарезервировано W_OF_B(pos + width) машинных слов.
\pre width <= B_PER_W.
\return Машинное слово, составленное из разрядов a с номерами
pos (младший), pos + 1,..., pos + width -1 (старший).
*/
word wwGetBits(
const word a[], /*!< [in] слово */
size_t pos, /*!< [in] номер первого разряда */
size_t width /*!< [in] число разрядов */
);
/*! \brief Установить разряд слова
В слове a разряду с номером pos присваивается значение val.
\pre По адресу a зарезервировано W_OF_B(pos + 1) машинных слов.
\pre val == FALSE || val == TRUE.
*/
void wwSetBit(
word a[], /*!< [in,out] обрабатываемое слово */
size_t pos, /*!< [in] номер разряда */
register bool_t val /*!< [in] устанавливаемое значение */
);
/*! \brief Установить разряды слова
В слове a определяется разряды с номерами pos,..., pos + width - 1
устанавливаются равными последовательным разрядам val
(от младшего к старшему).
\pre По адресу a зарезервировано W_OF_B(pos + width) машинных слов.
\pre width <= B_PER_W.
*/
void wwSetBits(
word a[], /*!< [out] слово */
size_t pos, /*!< [in] номер первого разряда */
size_t width, /*!< [in] число разрядов */
register word val /*!< [in] значение разрядов */
);
/*! \brief Инвертировать разряд слова
В слове a инвертируется разряд с номером pos.
\pre По адресу a зарезервировано W_OF_B(pos + 1) машинных слов.
*/
void wwFlipBit(
word a[], /*!< [out] слово */
size_t pos /*!< [in] номер разряда */
);
/*! \brief Количество первых (младших) нулевых битов
Определяется длина серии из нулевых битов в начале слова [n]a.
\return Длина серии.
\safe Функция нерегулярна.
*/
size_t wwLoZeroBits(
const word a[], /*!< [in] слово */
size_t n /*!< [in] длина a в машинных словах */
);
/*! \brief Количество последних (старших) нулевых битов
Определяется длина серии из нулевых битов в конце слова [n]a.
\return Длина серии.
\safe Функция нерегулярна.
*/
size_t wwHiZeroBits(
const word a[], /*!< [in] слово */
size_t n /*!< [in] длина a в машинных словах */
);
/*! \brief Размер значащей части слова в битах
Определяется размер значащей части слова [n]a. Размер полагается
равным индексу последнего ненулевого разряда, увеличенному на единицу.
\remark Размер пустого (n == 0) или нулевого слов равняется 0.
\remark Если wwBitSize(a, n) == m > 0, то для a как числа выполняется
2^{m - 1} < a <= 2^m - 1.
\return Размер значащей части.
\safe Функция нерегулярна.
*/
size_t wwBitSize(
const word a[], /*!< [in] слово */
size_t n /*!< [in] длина a в машинных словах */
);
/*! \brief Расчет NAF
В [2n + 1]naf помещается кодированное представление оптимальной знаковой
формы (NAF) слова [n]a. Рассчитывается оконная NAF с размером окна w.
\remark NAF(a, w) представляет собой последовательность символов
(a_0, a_1,..., a_{l-1}) такую, что
- a_i \in {0, \pm 1, \pm 3, ..., \pm 2^{w-1} - 1};
- если a != 0, то a_{l-1} != 0;
- a как число равняется \sum {i=0}^{l-1} a_i 2^i;
- среди любых w последовательных символов a_i только один ненулевой.
.
\remark Известно, что l - длина NAF - не превосходит wwBitSize(a) + 1.
\remark Кодирование символов состоит в следующем
(\<b> -- двоичная запись числа b):
- нулевые a_i представляются одним двоичным символом 0;
- положительные a_i представляются w двоичными символами 0\<a_i>;
- отрицательные a_i представляются w двоичными символами 1\<|a_i|>;
- кодированное представление - это конкатенация кода a_{l-1}
(первые символы), ...., кода a_1, кода a_0 (последние символы).
.
\remark Для кодирования w последовательных элементов a_i потребуется
не более (w - 1) * 1 + 1 * w = 2 * w - 1 битов. Поэтому при w < B_PER_W
для хранения всего кодового представления потребуется
не более 2 * n + 1 слов.
\remark Если при расчете NAF получен суффикс \alpha, 0,..., 0, 1,
в котором w - 1 нулей и \alpha < 0, то этот суффикс заменяется на
\beta, 0,..., 0, 1, в котором w - 2 нулей и
\beta = 2^{w - 1} + \alpha > 0.
Суффиксы описывают одинаковые числа:
2^w + \alpha = 2^{w - 1} + \beta.
Длина второго суффикса и соответствующей NAF на единицу меньше.
\pre 2 <= w < B_PER_W.
\pre Буфер naf не пересекается с буфером a.
\return Размер naf (число символов l).
\safe Функция нерегулярна.
*/
size_t wwNAF(
word naf[], /*!< [out] знаковая форма */
const word a[], /*!< [in] слово */
size_t n, /*!< [in] длина a в машинных словах */
size_t w /*!< [in] длина окна */
);
/*
*******************************************************************************
Сдвиги и очистка
*******************************************************************************
*/
/*! \brief Сдвиг в сторону первых (младших) разрядов
Слово [n]a сдвигается на shift позиций в сторону первых разрядов.
Освободившиеся разряды заполняются нулями.
\remark При интерпретации слов как чисел сдвиг означает деление на
число 2^shift с приведением результата mod 2^{n * B_PER_W}.
*/
void wwShLo(
word a[], /*!< [in,out] сдвигаемое слово */
size_t n, /*!< [in] длина a в машинных словах */
size_t shift /*!< [in] величина сдвига */
);
/*! \brief Сдвиг в сторону первых (младших) разрядов с заемом
Слово [n]a сдвигается на shift позиций в сторону первых разрядов.
Освободившиеся разряды заполняются разрядами carry.
\return Машинное слово, составленное из вытесненных последними разрядов.
*/
word wwShLoCarry(
word a[], /*!< [in,out] сдвигаемое слово */
size_t n, /*!< [in] длина a в машинных словах */
size_t shift, /*!< [in] величина сдвига */
word carry /*!< [in] машинное слово заема */
);
/*! \brief Сдвиг в сторону последних (старших) разрядов
Слово [n]a сдвигается на shift позиций в сторону последних разрядов.
Освободившиеся разряды заполняются нулями.
\remark При интерпретации слов как чисел сдвиг означает умножение на
число 2^shift с приведением результата mod 2^{n * B_PER_W}.
*/
void wwShHi(
word a[], /*!< [in] сдвигаемое слово */
size_t n, /*!< [in] длина a в машинных словах */
size_t shift /*!< [in] величина сдвига */
);
/*! \brief Сдвиг в сторону последних (старших) разрядов с заемом
Слово [n]a сдвигается на shift позиций в сторону последних разрядов.
Освободившиеся разряды заполняются разрядами carry.
\return Машинное слово, составленное из вытесненных последними разрядов.
*/
word wwShHiCarry(
word a[], /*!< [in,out] сдвигаемое слово */
size_t n, /*!< [in] длина a в машинных словах */
size_t shift, /*!< [in] величина сдвига */
word carry /*!< [in] машинное слово заема */
);
/*! \brief Отбросить первые (младшие) разряды слова
В слове [n]a обнуляются разряды с номерами
0, 1,..., min(pos, n * B_PER_W) - 1.
*/
void wwTrimLo(
word a[], /*!< [in,out] обрабатываемое слово */
size_t n, /*!< [in] длина a в машинных словах */
size_t pos /*!< [in] граница обнуляемых разрядов */
);
/*! \brief Отбросить последние (старшие) разряды слова
В слове [n]a обнуляются разряды с номерами
pos, pos + 1,...., n * B_PER_W - 1.
\remark При pos >= n * B_PER_W никаких действий не выполняется.
\remark При интерпретации слов как чисел отбрасывание разрядов означает
приведение mod 2^pos.
*/
void wwTrimHi(
word a[], /*!< [in,out] обрабатываемое слово */
size_t n, /*!< [in] длина a в машинных словах */
size_t pos /*!< [in] номер первого обнуляемого разряда */
);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* __WW_H */
|
C
|
#include <stdio.h>
#include <string.h>
/**
*/
int main()
{
char str1[50];
char str2[20];
printf("Ŀַ");
gets(str1);
printf("Դַ");
gets(str2);
strcpy(str1,str2);
printf("***ƺ***\n");
printf("Ŀַ%s\n",str1);
printf("Դַ%s\n",str2);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#define QTY_EMPLEADOS 10
#define QTY_NOMBRES 5
#define QTY_CARACTERES 50
#define STATUS_EMPTY 0
#define STATUS_NOT_EMPTY 1
struct sEmpleado
{
//********* OBLIGATORIOS
int idEmpleado;
int status;
//********* DATOS
char nombre[50];
char apellido[50];
};
int getString( char *pResultado,
char *pMensaje,
char *pMensajeError,
int minimo,
int maximo,
int reintentos);
int imprimirArrayString(char nombres[][QTY_CARACTERES],char dni[][500],int cantidad);
int ordenarArrayString(char nombres[][QTY_CARACTERES],char dni[][500],int cantidad);
int imprimirArrayEmpleados(struct sEmpleado *aEmpleados,int cantidad);
int ordenarArrayEmpleados(struct sEmpleado *aEmpleados,int cantidad,int orden);
int main(void)
{
struct sEmpleado aEmpleados[1000];
struct sEmpleado bEmpleado;
int i;
int idEmpleado = 0;
for(i=0;i<3;i++){
getString(bEmpleado.nombre,"Ingrese el nombre",
"ERROR", 1, 49, 2);
getString(bEmpleado.apellido,"Ingrese el apellido",
"ERROR", 1, 49, 2);
bEmpleado.idEmpleado = idEmpleado;
idEmpleado++;
bEmpleado.status = STATUS_NOT_EMPTY;
aEmpleados[i] = bEmpleado;
}
ordenarArrayEmpleados(aEmpleados,3,1);
imprimirArrayEmpleados(aEmpleados,3);
return EXIT_SUCCESS;
}
int getString( char *pResultado,
char *pMensaje,
char *pMensajeError,
int minimo,
int maximo,
int reintentos)
{
int retorno = -1;
char buffer[4096];
if (pResultado != NULL &&
pMensaje != NULL &&
pMensajeError != NULL &&
minimo<=maximo &&
reintentos >= 0)
{
do
{
printf("%s",pMensaje);
__fpurge(stdin);
fgets(buffer,sizeof(buffer),stdin);
buffer[strlen(buffer)-1] = '\0';
if(strlen(buffer)<=maximo && strlen(buffer)>=minimo)
{
strncpy(pResultado,buffer,maximo+1);
retorno = 0;
break;
}
printf("%s",pMensajeError);
reintentos--;
}while(reintentos >= 0);
}else {
printf("%s",pMensajeError);
}
return retorno;
}
int imprimirArrayString(char nombres[][QTY_CARACTERES],char dni[][500],int cantidad){
int retorno = -1;
int i;
if(nombres != NULL && cantidad>0){
retorno = 0;
for(i=0;i<cantidad;i++){
printf("%s %s\n",nombres[i],dni[i]);
}
}
return retorno;
}
int ordenarArrayString(char nombres[][QTY_CARACTERES],char dni[][500],int cantidad){
int retorno = -1;
int i;
int fSwap;
char buffer[500];
char bufferDni[500];
do{
fSwap = 0;
for(i = 0;i<cantidad-1;i++){
if(strcmp(nombres[i],nombres[i+1])>0){
fSwap = 1;
strcpy(buffer,nombres[i+1]);
strcpy(bufferDni,dni[i+1]);
strcpy(nombres[i+1],nombres[i]);
strcpy(dni[i+1],dni[i]);
strcpy(nombres[i],buffer);
strcpy(dni[i],bufferDni);
}
}
}while(fSwap);
return retorno;
}
int imprimirArrayEmpleados(struct sEmpleado *aEmpleados,int cantidad){
int retorno = -1;
int i;
if(aEmpleados != NULL && cantidad>0){
retorno = 0;
for(i=0;i<cantidad;i++){
printf("Id: %d -Nombre: %s -Apellido %s \n",aEmpleados[i].idEmpleado,aEmpleados[i].nombre,aEmpleados[i].apellido);
}
}
return retorno;
}
int ordenarArrayEmpleados(struct sEmpleado *aEmpleados,int cantidad,int orden){
int retorno = -1;
int i;
int fSwap;
struct sEmpleado bBuffer;
if (orden == 0){
do{
fSwap = 0;
for(i = 0;i<cantidad-1;i++){
if(strncmp(aEmpleados[i].nombre,aEmpleados[i+1].nombre,50)==0){
if(strncmp(aEmpleados[i].apellido,aEmpleados[i+1].apellido,50)>0){
fSwap = 1;
bBuffer= aEmpleados[i+1];
aEmpleados[i+1] = aEmpleados[i];
aEmpleados[i]= bBuffer;}
}else if(strncmp(aEmpleados[i].nombre,aEmpleados[i+1].nombre,50)>0){
fSwap = 1;
bBuffer= aEmpleados[i+1];
aEmpleados[i+1] = aEmpleados[i];
aEmpleados[i]= bBuffer;
}
}
}while(fSwap);
} else if (orden == 1){
do{
fSwap = 0;
for(i = 0;i<cantidad-1;i++){
if(strncmp(aEmpleados[i].nombre,aEmpleados[i+1].nombre,50)==0){
if(strncmp(aEmpleados[i].apellido,aEmpleados[i+1].apellido,50)<0){
fSwap = 1;
bBuffer= aEmpleados[i+1];
aEmpleados[i+1] = aEmpleados[i];
aEmpleados[i]= bBuffer;}
}else if(strncmp(aEmpleados[i].nombre,aEmpleados[i+1].nombre,50)<0){
fSwap = 1;
bBuffer= aEmpleados[i+1];
aEmpleados[i+1] = aEmpleados[i];
aEmpleados[i]= bBuffer;
}
}
}while(fSwap);
}
return retorno;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include <sys/time.h>
#include <assert.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>
#include <assert.h>
#include <sys/wait.h>
void demo();
struct test{
char name[32];
void (*fun_ptr)();
} tests_arr[] = {
{"Demo", demo}
};
void demo(){
char* user_buffer = (char*)__cosmix_address_sanitizer_annotation(malloc(sizeof(char)*8));
printf("Welcome to ASan's demo, please enter an input to my 8 byte array!\n");
scanf("%s",user_buffer);
printf("You entered: %s\n", user_buffer);
printf("Have a nice day!\n");
}
/** Change debug flag to 1 in address sanitizer runtime and check prints **/
int main(){
while(1){
demo();
}
}
|
C
|
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#include <string.h>
#include <immintrin.h>
#include <stdint.h>
#include <stdbool.h>
#define ITERATIONS 1000000000
#define EXEC_TIME 100
#define BILLION 1000000000L
#define INSTR 9
#define FILE_SIZE 10737418240 //10GB
#define EXP_DURATION 10 //20s
int *thread_op_array; //array holding total operations completed by each thread
char *target_mem_ptr;
char *source_mem_ptr;
bool isThroughPut_op = false;
FILE *fp;
struct thread_data_t
{
FILE *thread_fp;
long block_size;
int from;
int to;
} *thread_data;
long get_total_op(int no_threads)
{
long total_op = 0;
int j;
for(j = 0; j < no_threads; j++)
{
total_op += thread_op_array[j];
}
return total_op;
}
void
exec_threads (void *method, int no_threads, long block_size);
void*
read_write_op(void * param);
void*
seq_read_op(void* param);
void*
rand_read_op(void* param);
void*
read_write_op(void * param)
{
int thread_id = (int )(intptr_t)param;
struct timespec start;
long start_address;
long end_address;
FILE *fp_start_addr;
long block_size;
long thread_total_op = 0;
long end_time;
char *buff;
FILE *src_fp;
src_fp = fopen("read_write_test_src.txt","r+");
clock_gettime(CLOCK_REALTIME, &start);
end_time = start.tv_sec + EXP_DURATION;
block_size = thread_data[thread_id].block_size;
buff = (char *) malloc(block_size);
start_address = thread_data[thread_id].from * block_size;
end_address = thread_data[thread_id].to * block_size + block_size - 1;
fp_start_addr = thread_data[thread_id].thread_fp;
lseek(fp_start_addr, start_address, SEEK_SET);//Initial seek to the thread file boundary
// fp_end_addr = thread_data[thread_id].thread_fp + end_address;
//inital seek of the src file pointer
lseek(src_fp, start_address, SEEK_SET);
int thread_block_complete = 0;
while(thread_block_complete == 0)
{
lseek(fp_start_addr,start_address , SEEK_SET);
lseek(src_fp,start_address , SEEK_SET);
start_address += block_size;
if(start_address >= end_address)
{
start_address = thread_data[thread_id].from * block_size;
thread_block_complete = 1;
}
//copying from source file
fread(buff, block_size, 1, src_fp);
//writing contents to target file
fwrite(buff, block_size, 1, fp_start_addr);
clock_gettime(CLOCK_REALTIME,&start);
thread_total_op++;
// printf("start_address %ld \n",start_address);
}
thread_op_array[thread_id] = thread_total_op;
// printf("thread %d total op %ld\n",thread_id,thread_op_array[thread_id]);
}
void*
seq_read_op(void* param)
{
int thread_id = (int )(intptr_t)param;
struct timespec start;
long start_address;
long end_address;
FILE *fp_start_addr;
long block_size;
long thread_total_op = 0;
long end_time;
char *buff;
clock_gettime(CLOCK_REALTIME, &start);
end_time = start.tv_sec + EXP_DURATION;
block_size = thread_data[thread_id].block_size;
buff = (char *) malloc(block_size);
start_address = thread_data[thread_id].from * block_size;
end_address = thread_data[thread_id].to * block_size + block_size - 1;
fp_start_addr = thread_data[thread_id].thread_fp;
// fp_end_addr = thread_data[thread_id].thread_fp + end_address;
//inital seek of the src file pointer
int thread_block_complete = 0;
while(thread_block_complete == 0)
{
lseek(fp_start_addr,start_address , SEEK_SET);
fread(buff, block_size, 1, fp_start_addr);
start_address += block_size;
if(start_address >= end_address)
{
start_address = thread_data[thread_id].from * block_size;
thread_block_complete = 1;
}
//copying from source file
clock_gettime(CLOCK_REALTIME,&start);
thread_total_op++;
// printf("start_address %ld \n",start_address);
}
thread_op_array[thread_id] = thread_total_op;
// printf("thread %d total op %ld\n",thread_id,thread_op_array[thread_id]);
}
void*
rand_read_op(void* param)
{
int thread_id = (int )(intptr_t)param;
struct timespec start;
long start_address;
long end_address;
FILE *fp_start_addr;
long block_size;
long thread_total_op = 0;
long end_time;
char *buff;
long from;
long no_blocks = 0;
srand(time(NULL));
clock_gettime(CLOCK_REALTIME, &start);
end_time = start.tv_sec + EXP_DURATION;
block_size = thread_data[thread_id].block_size;
buff = (char *) malloc(block_size);
start_address = thread_data[thread_id].from * block_size;
end_address = thread_data[thread_id].to * block_size + block_size - 1;
from = thread_data[thread_id].from;
no_blocks = thread_data[thread_id].to - thread_data[thread_id].from;
fp_start_addr = thread_data[thread_id].thread_fp;
// fp_end_addr = thread_data[thread_id].thread_fp + end_address;
//inital seek of the src file pointer
int i = no_blocks;
while(i>0)
{
lseek(fp_start_addr,start_address , SEEK_SET);
fread(buff, block_size, 1, fp_start_addr);
start_address = (from + (rand()% no_blocks)) * block_size;
if(start_address >= end_address)
{
start_address = thread_data[thread_id].from * block_size;
}
//copying from source file
clock_gettime(CLOCK_REALTIME,&start);
thread_total_op++;
// printf("start_address %ld \n",start_address);
i--;
}
thread_op_array[thread_id] = thread_total_op;
// printf("thread %d total op %ld\n",thread_id,thread_op_array[thread_id]);
}
void calculate_mem_perf(void* (*method)(void *),int no_threads, long block_size)
{
double latency, throughput;
struct timespec start,end;
clock_gettime(CLOCK_REALTIME,&start);
exec_threads(method, no_threads, block_size);
clock_gettime(CLOCK_REALTIME,&end);
double total_op = get_total_op(no_threads);
printf("%lf\n",total_op);
double total_sec = (double)((end.tv_nsec-start.tv_nsec)/1000000000)+(double)end.tv_sec-start.tv_sec;
if(isThroughPut_op)
{
throughput = ((total_op * (double) block_size) / 1048576) / (double) total_sec;
fprintf(fp,"%d %lf\n", no_threads, throughput);
}
else
{
//mesure in ms
latency = (total_sec / (double) total_op) * 1000;
fprintf(fp,"%d %lf\n", no_threads, latency);
}
printf("total sec %lf\n",(double)end.tv_sec-start.tv_sec);
}
void exec_threads (void *method, int no_threads, long block_size)
{
pthread_t thread[8];
int i;
for (i = 0; i < no_threads; i++)
{
pthread_create (&thread[i], NULL, method, (void *)(intptr_t)i);
}
for (i = 0; i < no_threads; i++)
{
pthread_join(thread[i],NULL);
}
}
void release_thread_data()
{
free(target_mem_ptr);
free(source_mem_ptr);
free(thread_data);
free(thread_op_array);
}
void init_thread_data(int no_threads, long block_size)
{
int i=0;
int block_count;
//target_mem_ptr = (char *) malloc(MEMORY_CHUNK_SIZE);//initialize memory
//source_mem_ptr = (char *) malloc(MEMORY_CHUNK_SIZE);
thread_data = (struct thread_data_t *)malloc(sizeof(struct thread_data_t) * no_threads);
//FILE *fp = fopen("disk_file.txt","r+");
block_count = FILE_SIZE / block_size;
for(i=0;i<no_threads;i++)
{
thread_data[i].block_size = block_size;
thread_data[i].thread_fp = fopen("disk_file.txt","r+");
thread_data[i].from = i * (block_count / no_threads);
thread_data[i].to = ((block_count / no_threads) * (i+1))-1;
}
thread_op_array= (int*) calloc(no_threads, sizeof(int));
}
//arg list param_space no_threada block_size
int main(int argc, char *argv[])
{
int no_threads = 1;// 1,2,4,8
int param_space = 1; // 1 read/write , 2 sequential write, 3 random write
long block_size = 1; //1 8B,2 8KB, 3 8MB, 4 80MB
long byte_val[4] = {8,8192,8388608,83886080};
volatile char *memory_dummy;
char filename[3]={'\0','\0','\0'};
memory_dummy = (char *) malloc(sizeof(char)*BILLION*3);
no_threads = atoi (argv[2]);
param_space = atoi (argv[1]);
block_size = atoi (argv[3]);
sprintf(filename,"%d%d",param_space,block_size);
fp = fopen(filename,"a+");
if(block_size == 2 || block_size == 3 || block_size == 4) // compute throughput only if block_size == 2,3,4
{
isThroughPut_op = true;
}
if(block_size == 1)
{
block_size = byte_val[block_size-1];
}
else if(block_size == 2)
{
block_size = byte_val[block_size-1];
}
else if(block_size == 3)
{
block_size = byte_val[block_size-1];
}
else if(block_size == 4)
{
block_size = byte_val[block_size-1];
}
// printf("paramspace = %d, no_threads %d block_size %ld\n",param_space,no_threads,block_size);
init_thread_data(no_threads,block_size);
if(param_space ==1)//read/write operation
{
calculate_mem_perf( read_write_op,no_threads, block_size);
}
else if(param_space == 2)//sequential write operation
{
calculate_mem_perf( seq_read_op,no_threads, block_size);
}
else//randome write
{
calculate_mem_perf( rand_read_op,no_threads, block_size);
}
fclose(fp);
free((void *)memory_dummy);
release_thread_data();
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
int score;
int star[5] = { 0 };
printf(" Է : ");
int max = 0;
int min = 100; //0~100 Էϴ ̱
while (1)
{
scanf("%d", &score);
if (score < 0) break;
switch (score/10)
{
case 10:case 9: star[0]++; break;
case 8: star[1]++; break;
case 7: star[2]++; break;
case 6: star[3]++; break;
default: star[4]++;
}
if (score > max) max = score;
if (min > score)min = score;
}
char *label[] = { "90 ̻","80 ","70 ","60 ","60 ̸" };
for (int i = 0; i < sizeof(star); i++)
{
printf("%s : ", label[i]);
for (int j = 0; j < star[i]; j++)
{
printf("*");
}
printf("\n");
}
printf("ְ : %d", max);
printf(" : %d", min);
return 0;
}
|
C
|
/*!
* MPT solver module helper function
* set IVP equotation count and grid size/data
*/
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/uio.h>
#include "meta.h"
#include "../solver.h"
extern int mpt_solver_module_value_ivp(MPT_STRUCT(value) *val, const MPT_IVP_STRUCT(parameters) *par)
{
static const uint8_t fmt[] = "iu";
val->fmt = fmt;
val->ptr = par;
return par && (par->neqs != 1 || par->pint) ? 1 : 0;
}
extern int mpt_solver_module_ivpset(MPT_IVP_STRUCT(parameters) *ivp, MPT_INTERFACE(convertable) *src)
{
MPT_INTERFACE(iterator) *it;
struct iovec grid;
int32_t neqs;
uint32_t pint;
int ret, len;
/* default values */
neqs = 1;
pint = 0;
if (!src) {
ivp->neqs = neqs;
ivp->pint = pint;
if (ivp->grid) {
free(ivp->grid);
ivp->grid = 0;
}
return 0;
}
/* direct distinct conversions */
len = 0;
if ((ret = src->_vptr->convert(src, 'i', &neqs)) > 0) {
if (neqs < 1) {
return MPT_ERROR(BadValue);
}
if ((len = src->_vptr->convert(src, MPT_type_vector('d'), &grid)) > 0) {
size_t part = grid.iov_len / sizeof(double);
if (part < 2 || part >= UINT32_MAX) {
return MPT_ERROR(BadValue);
}
pint = part - 1;
}
if (!len) {
ivp->neqs = neqs;
ivp->pint = pint;
if (ivp->grid) {
free(ivp->grid);
}
return 0;
}
else if (len > 0) {
double *tmp;
size_t size = (pint + 1) * sizeof(*tmp);
if (!(tmp = malloc(size))) {
return MPT_ERROR(BadOperation);
}
if (ivp->grid) {
free(ivp->grid);
}
if (grid.iov_base) {
ivp->grid = memcpy(tmp, grid.iov_base, size);
} else {
ivp->grid = memset(tmp, 0, size);
}
return 0;
}
len = 0;
}
/* get values from iterator */
if ((ret = src->_vptr->convert(src, MPT_type_pointer(MPT_ENUM(TypeIterator)), &it)) >= 0) {
if (!ret || !it) {
ivp->neqs = neqs;
ivp->pint = pint;
return 0;
}
if ((ret = it->_vptr->get(it, 'i', &neqs)) < 0) {
return ret;
}
else if (!ret) {
ivp->neqs = neqs;
ivp->pint = pint;
return 0;
}
if (neqs < 1) {
return MPT_ERROR(BadValue);
}
if ((ret = it->_vptr->advance(it)) < 0) {
return ret;
}
len = 1;
/* PDE without grid data */
if ((ret = it->_vptr->get(it, MPT_type_vector('d'), &grid)) < 0) {
if ((ret = it->_vptr->get(it, 'u', &pint)) < 0) {
int32_t tmp;
if ((ret = it->_vptr->get(it, 'i', &tmp)) < 0) {
return ret;
}
if (ret > 0) {
if (tmp < 0) {
return MPT_ERROR(BadValue);
}
pint = tmp;
}
}
if (!ret) {
pint = 0;
}
else if ((ret = it->_vptr->advance(it)) < 0) {
return ret;
}
else {
len = 2;
}
if (ivp->grid) {
free(ivp->grid);
ivp->grid = 0;
}
}
/* copy grid data for PDE */
else if (ret) {
double *ptr;
size_t part = grid.iov_len / sizeof(double);
if (part < 2 || part > UINT32_MAX) {
return MPT_ERROR(BadValue);
}
if ((ret = it->_vptr->advance(it)) < 0) {
return ret;
}
pint = part - 1;
part *= sizeof(double);
if (!(ptr = malloc(part))) {
return MPT_ERROR(BadOperation);
}
if (grid.iov_base) {
memcpy(ptr, grid.iov_base, part);
} else {
memset(ptr, 0, part);
}
if (ivp->grid) {
free(ivp->grid);
}
ivp->grid = ptr;
len = 2;
}
/* no grid data equals ODE/DAE mode */
else if (ivp->grid) {
free(ivp->grid);
ivp->grid = 0;
}
}
ivp->neqs = neqs;
ivp->pint = pint;
return len;
}
|
C
|
#include<stdio.h>
int main()
{
int x,y,sum=0,i,j;
scanf("%d %d",&x,&y);
j=(x*(x+1))/2;
//if(j<=y){
for(i=1;;i++)
{
sum+=i;
if(sum==y)
{
printf("0");
return 0;
}
else if(sum>y)
{
printf("%d",y-(sum-i));
return 0;
}
if(sum%j==0)
{
i=0;
}
}
}
|
C
|
/**************************************************************************
Module: rms_rec_arch_command.c
Description: This module is to setup an RDA control command
to start or stop archive II recording.
Assumptions:
**************************************************************************/
/*
* RCS info
* $Author: garyg $
* $Locker: $
* $Date: 2003/06/26 14:50:54 $
* $Id: rms_arch.c,v 1.10 2003/06/26 14:50:54 garyg Exp $
* $Revision: 1.10 $
* $State: Exp $
*/
/*
* System Include Files/Local Include Files
*/
#include <rms_message.h>
#include <orpgedlock.h>
/*
* Constant Definitions/Macro Definitions/Type Definitions
*/
/*
* Static Globals
*/
/*
* Static Function Prototypes
*/
/**************************************************************************
Description: This routine reads the message and send the command to
start or stop Archive II recording.
Input: rda_arch_buf - Pointer to message buffer.
Output: RDA command for Archive II.
Returns: Message sent = 1, Not sent = -1
Notes:
**************************************************************************/
int rms_rec_arch_command (UNSIGNED_BYTE *rda_arch_buf) {
/* Buffer pointer for RMS message */
UNSIGNED_BYTE *rda_arch_buf_ptr;
int ret;
int rda_arch_flag;
int vol_scans;
/* Set pointer to start of buffer */
rda_arch_buf_ptr = rda_arch_buf;
/* Place pointer past message header */
rda_arch_buf_ptr += MESSAGE_START;
/* Convert archive flag */
rda_arch_flag = conv_shrt(rda_arch_buf_ptr);
rda_arch_buf_ptr += PLUS_SHORT;
/* Convert number of volume scans */
vol_scans = conv_shrt(rda_arch_buf_ptr);
rda_arch_buf_ptr += PLUS_SHORT;
/* Get lock status of RDA command buffer */
ret = ORPGEDLOCK_get_edit_status(ORPGDAT_RDA_COMMAND, 0);
/* If RDA command buffer locked return error */
if ( ret == ORPGEDLOCK_EDIT_LOCKED){
LE_send_msg(RMS_LE_ERROR,"RMS: Unable to access archive RDA commands are locked");
return (24);
}
/* Validation check for number of volume scans */
if (vol_scans < 0){
LE_send_msg(RMS_LE_ERROR,"RMS: Number of volume scans less than 0 (#scans %d)", vol_scans);
return (24);
}
if ( vol_scans > 255){
LE_send_msg(RMS_LE_ERROR,"RMS: Number of volume scans greater than 255 (#scans %d)", vol_scans);
return (24);
}
/* FAA/RMMS command to start Archive II recording */
if (rda_arch_flag == 4){
/* If vol_scans equal zero
Archive II will do continuous recording */
ret = ORPGRDA_send_cmd (COM4_RDACOM, RMS_INITIATED_RDA_CTRL_CMD, CRDA_ARCH_COLLECT,
vol_scans, 0, 0, 0, NULL);
if (ret < 0)
return (ret);
return (0);
} /* start archive II */
/* FAA/RMMS command to stop Archive II recording */
if (rda_arch_flag == 6){
ret = ORPGRDA_send_cmd(COM4_RDACOM, RMS_INITIATED_RDA_CTRL_CMD, CRDA_ARCH_STOP, 0,
0, 0, 0, NULL);
if (ret < 0)
return (ret);
return (0);
} /* stop archive II */
/* If FAA/RMMS command not valid return error code */
return (24);
} /* End rms rec arch command */
|
C
|
#include <stddef.h>
#include <stdbool.h>
#include "set.h"
Set set_singleton(size_t i) {
return 1lu<<i;
}
bool set_has(Set S, size_t i) {
return (S & (1lu<<i)) != 0;
}
Set set_include(Set S, size_t i) {
return S | (1lu<<i);
}
Set set_exclude(Set S, size_t i) {
return S & ~(1lu<<i);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <term.h>
#include <ncurses.h>
/*
Compile this with -lncurses
*/
int main(void){
char *bold, *offbold;
setupterm(NULL, fileno(stdout), (int *)0);
bold = tigetstr("smso");
offbold = tigetstr("rmso");
putp(bold);
printf("This should be highlighted\n");
putp(offbold);
beep();
exit(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define _CRT_SECURE_NO_WARNINGS
void main()
{
int Weight, Height;
float BMI;
printf("Please enter weight (in kg) and height (in cm), respectively: ");
scanf("%d%d", &Weight, &Height);
BMI = (double)Weight/powf((double)Height/100,2);
if(BMI < 18.5)
{
printf("Underweight");
}
else if (BMI >= 18.5 && BMI < 25 )
{
printf("Normal weight");
}
else if (BMI >= 25 && BMI < 30 )
{
printf("Increased weight");
}
else if (BMI >= 30 && BMI < 40 )
{
printf("Obese");
}
else if (BMI >= 40)
{
printf("Very high obese");
}
}
|
C
|
/**
* This class currently computes the axis on which consecutive acceleration vectors are turning.
*/
#include "rotation_axis.h"
void initialise_rotation_axis(RotationAxis *axis_and_angle_buffer) {
axis_and_angle_buffer->is_current_axis_valid = false;
axis_and_angle_buffer->is_previous_accel_data_valid = false;
}
void update_rotation_axis(float *new_accel_data, RotationAxis *rotation_axis_buffer) {
// If there is no previous acceleration data, store the current data and return
if (rotation_axis_buffer->is_previous_accel_data_valid == false) {
copy_accel_vector(rotation_axis_buffer->previous_accel_data, new_accel_data);
rotation_axis_buffer->is_previous_accel_data_valid = true;
rotation_axis_buffer->is_current_axis_valid = false;
return;
}
// Store the cross product of the previous and new accel data as the "current axis".
float cross_product_out[3];
cross_product(cross_product_out, rotation_axis_buffer->previous_accel_data, new_accel_data);
copy_accel_vector(rotation_axis_buffer->current_axis, cross_product_out);
copy_accel_vector(rotation_axis_buffer->previous_accel_data, new_accel_data);
rotation_axis_buffer->is_current_axis_valid = true;
}
|
C
|
#include "trap.h"
void
pic_eoi(uint8_t irq)
{
if (irq >= 8)
{
outb(PIC2_CMD, PIC_EOI);
}
outb(PIC1_CMD, PIC_EOI);
}
Interrupt_gate idt[256];
extern uint32_t vectors_array[];
void
init_interrupt_gate_entry(Interrupt_gate *entry, uint32_t offset, uint16_t selector)
{
entry->offset_0_15 = 0xffff & offset;
entry->offset_16_31 = 0xffff & (offset >> 16);
entry->selector = selector;
entry->zero = 0;
entry->type = 0x8e;
}
void
trap_init(void)
{
// NOTE(max): We initialize IDT
for (int i = 0; i < 256; i++)
{
init_interrupt_gate_entry(&idt[i], vectors_array[i], 0x08);
}
load_idt(idt, sizeof(idt));
// NOTE(max): ICW1
outb(PIC1_CMD, ICW1_INIT | ICW1_ICW4);
outb(PIC2_CMD, ICW1_INIT | ICW1_ICW4);
// NOTE(max): ICW2
outb(PIC1_DATA, PIC1_NEW_OFFSET);
outb(PIC2_DATA, PIC2_NEW_OFFSET);
// NOTE(max): ICW3
outb(PIC1_DATA, 0x4);
outb(PIC2_DATA, 0x2);
// NOTE(max): ICW4
outb(PIC1_DATA, ICW4_8086);
outb(PIC2_DATA, ICW4_8086);
// NOTE(max): mask ALL hw interrupts
outb(PIC1_DATA, 0xff);
outb(PIC2_DATA, 0xff);
}
void
test_trap_handler(uint32_t param)
{
printf("Syscall param = %x\n", param);
}
void
syscall_meaning_of_life(void)
{
printf("The meaning of life is 42\n");
}
void
syscall_print_str(char *str)
{
put_str(str);
}
void
trap(Trap_frame *frame)
{
switch (frame->trap_num)
{
case 0x80:
{
if (frame->eax == 42)
syscall_meaning_of_life();
else if (frame->eax == 7)
syscall_print_str((char *)frame->ebx);
} break;
case IRQ_1: // keyboard
{
pic_eoi(1);
kbd_handler();
} break;
default:
{
vga_clear_screen();
put_str("I can't handle this interrupt\n");
} break;
}
}
|
C
|
#include<stdio.h>
/*
Study of Division Operators
C provides 2 division operators
1) / (Divide)
It gives the quotient of division
2) % (Modulus)
It gives the remainder of division.
It works on whole numbers only.
*/
int main()
{
int q, r;
q = 15/7;
r = 15%7;
printf("15 divided by 7");
printf("\n quotient : %d ", q);
printf("\n remainder : %d ", r);
return 0;
}
|
C
|
#ifndef _QUEUE_H_
#define _QUEUE_H_
#define QueueMax 10
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef int QUDataType;
typedef struct Queue
{
QUDataType _data[QueueMax];
QUDataType* _front; // ͷ
QUDataType* _rear; // β
size_t size;
}Queue;
void QueueInit(Queue* pq);
void QueueDestory(Queue* pq);
Queue* BuyQueueNode(QUDataType x);
void QueuePush(Queue* pq, QUDataType x);
void QueuePop(Queue* pq);
QUDataType QueueFront(Queue* pq);
QUDataType QueueBack(Queue* pq);
int QueueEmpty(Queue* pq);
int QueueSize(Queue* pq);
void TestQueue();
#endif /*_QUEUE_H_*/
|
C
|
//memlayout.c
#include <stdio.h>
#include <stdlib.h>
// Stored in data segment
int initialized_global = 0x1234;
// Stored in bss segment
int uninitialized_global;
void main()
{
// Stored on stack
int stack_variable = 0x5678;
// Stored on heap
int* heap_variable = (int*) malloc(sizeof(int));
*heap_variable = 0x9ABC;
free(heap_variable);
}
|
C
|
#include<stdio.h>
int fpb(int d,int e){
if(d==0)return e;
else{return fpb(e%d,d);}
}
int main(){
int a,b;
printf("Program Mencari Faktor Persekutuan Terbesar\n"
"Silahkan masukkan Angka Pertama> ");
scanf("%d",&a);
printf("Silahkan masukkan Angka Kedua> ");
scanf("%d",&b);
printf("FPB/GCD dari %d dan %d> %d\n",a,b,fpb(a,b));
}
|
C
|
/*
Given an array of characters print the characters that have ‘n’ number of occurrences.
If a character appears consecutively it is counted as 1 occurrence
*/
// Below version code different from zoho question
// code question : https://practice.geeksforgeeks.org/problems/remaining-string/0
#include <stdio.h>
int main()
{
// char string[] = "geeksforgeeks";
// char ch = 'e';
// int occurences = 2;
char string[10000];
scanf("%s",string);
getchar();
char ch;
scanf("%c",&ch);
int occurences;
scanf("%d",&occurences);
int flag = 0;
if(occurences > 0)
{
int i = 0,count = 0;
while (string[i] != '\0')
{
if(count == occurences) {
flag = (string[i+1] != '\0') ? 1 : 0;
break;
} else if(string[i] == ch) {
count++;
i = (count == occurences) ? i : i+1;
} else {
i++;
}
}
if(flag)
{
for (int j = i+1; string[j] != '\0'; j++)
{
printf("%c",string[j]);
}
printf("\n");
} else {
printf("\n");
}
}
else {
printf("%s\n",string);
}
return 0;
}
|
C
|
#include <stdlib.h>
struct s_node {
void *content;
struct s_node *next;
};
void *intersection(struct s_node *lst1, struct s_node *lst2)
{
while (lst1 != NULL)
{
struct s_node *tmp = lst2;
while (tmp != NULL)
{
if (tmp == lst1)
return tmp;
tmp = tmp->next;
}
lst1 = lst1->next;
}
return NULL;
}
|
C
|
/* ------- file: -------------------------- molzeeman.c -------------
Version: rh2.0
Author: Han Uitenbroek (huitenbroek@nso.edu)
Last modified: Thu Jun 30 15:35:10 2011 --
-------------------------- ----------RH-- */
/* --- Routines to calculate Zeeman splitting patterns and relative
strengths of Zeeman components in molecular transitions.
-- -------------- */
#include <stdlib.h>
#include <math.h>
#include "rh.h"
#include "atom.h"
#include "spectrum.h"
#include "error.h"
/* --- Function prototypes -- -------------- */
double MolZeemanStr(double Ju, double Mu, double Jl, double Ml);
double MolLande_a(double Lambda, double Sigma, double Omega, double J);
double MolLande_b(double Lambda, double S, double N, double J);
/* --- Global variables -- -------------- */
extern char messageStr[];
/* ------- begin -------------------------- MolZeemanStr.c ---------- */
double MolZeemanStr(double Ju, double Mu, double Jl, double Ml)
{
const char routineName[] = "MolZeemanStr";
int q, dJ;
double s;
/* --- Return the strength of Zeeman component (Ju, Mu) -> (Jl, Ml),
where J and M are the total angular momentum and magnetic
quantum numbers of the upper and lower level of a Zeeman split
molecular transition.
See: - G. Herzberg 1950, in "Spectra of Diatomic Molecules", p.301-3
- S.V. Berdyugina and S.K. Solanki 2002, A&A 385, 701-715
- A. Schadee 1978, JQSRT 19, 517-531
Note: Berdyugina & Solanki adhere to the definition that dJ = Jl - Ju
-- -------------- */
q = (int) (Ml - Mu);
dJ = (int) (Jl - Ju);
switch (dJ) {
case 1:
switch (q) {
case 1: s = (Ju + 1.0 + Mu) * (Ju + 2.0 + Mu) /
(2*(Ju + 1.0) * (2*Ju + 1.0) * (2*Ju + 3.0)); break;
case 0: s = (Ju + 1.0 + Mu) * (Ju + 1.0 - Mu) /
((Ju + 1.0) * (2*Ju + 1.0) * (2*Ju + 3.0)); break;
case -1: s = (Ju + 1.0 - Mu) * (Ju + 2.0 - Mu) /
(2*(Ju + 1.0) * (2*Ju + 1.0) * (2*Ju + 3.0)); break;
}
break;
case 0:
switch (q) {
case 1: s = (Ju - Mu) * (Ju + 1.0 + Mu) /
(2*Ju * (Ju + 1.0) * (2*Ju + 1.0)); break;
case 0: s = Mu*Mu /
(Ju * (Ju + 1.0) * (2*Ju + 1.0)); break;
case -1: s = (Ju + Mu) * (Ju + 1.0 - Mu) /
(2*Ju * (Ju + 1.0) * (2*Ju + 1.0)); break;
}
break;
case -1:
switch (q) {
case 1: s = (Ju - Mu) * (Ju - 1.0 - Mu) /
(2*Ju * (2*Ju - 1.0) * (2*Ju + 1.0)); break;
case 0: s = (Ju + Mu) * (Ju - Mu) /
(Ju * (2*Ju - 1.0) * (2*Ju + 1.0)); break;
case -1: s = (Ju + Mu) * (Ju - 1.0 + Mu) /
(2*Ju * (2*Ju - 1.0) * (2*Ju + 1.0)); break;
}
break;
default:
sprintf(messageStr, "Invalid dJ: %d", dJ);
Error(ERROR_LEVEL_2, routineName, messageStr);
}
/* --- The strengths are normalized already. -- -------------- */
return s;
}
/* ------- end ---------------------------- MolZeemanStr_b.c -------- */
/* ------- begin -------------------------- MolLande_a.c ------------ */
double MolLande_a(double Lambda, double Sigma, double Omega, double J)
{
/* --- Lande factor for level in Hund's case a
See: S.V. Berdyugina and S.K. Solanki 2002, A&A 385, 701-715, Eq. 2
-- -------------- */
return (Lambda + 2.0*Sigma) * Omega / (J * (J + 1.0));
}
/* ------- end ---------------------------- MolLande_a.c ------------ */
/* ------- begin -------------------------- MolLande_b.c ------------ */
double MolLande_b(double Lambda, double S, double N, double J)
{
/* --- Lande factor for level in Hund's case b
See: S.V. Berdyugina and S.K. Solanki 2002, A&A 385, 701-715, Eq. 10
-- -------------- */
if (Lambda == 0) {
return 1.0 / (J*(J + 1.0)) *
(J*(J + 1.0) - N*(N + 1.0) + S*(S + 1.0));
} else {
return 1.0 / (J*(J + 1.0)) *
(Lambda*Lambda / (2*N*(N + 1.0)) *
(J*(J + 1.0) + N*(N + 1.0) - S*(S + 1.0)) +
J*(J + 1.0) - N*(N + 1.0) + S*(S + 1.0));
}
}
/* ------- end ---------------------------- MolLande_b.c ------------ */
/* ------- begin -------------------------- MolLande_eff.c ---------- */
double MolLande_eff(MolecularLine *mrt)
{
const char routineName[] = "MolLande_eff";
register double Ml, Mu;
double g_eff, Ju, Jl, norm, Nl, Nu, shift, strength, gLu, gLl;
norm = 0.0;
g_eff = 0.0;
Jl = (mrt->gi - 1.0) / 2.0;
Ju = (mrt->gj - 1.0) / 2.0;
switch (mrt->Hundi) {
case CASE_A:
gLl = MolLande_a(mrt->Lambdai, mrt->Si, mrt->Omegai, Jl);
break;
case CASE_B:
Nl = Jl - mrt->Si + (mrt->subi - 1);
gLl = MolLande_b(mrt->Lambdai, mrt->Si, Nl, Jl);
break;
default:
sprintf(messageStr, "Unsupported Hund's case: %d", mrt->Hundi);
Error(ERROR_LEVEL_2, routineName, messageStr);
}
switch (mrt->Hundj) {
case CASE_A:
gLu = MolLande_a(mrt->Lambdaj, mrt->Sj, mrt->Omegaj, Ju);
break;
case CASE_B:
Nu = Ju - mrt->Sj + (mrt->subj - 1);
gLu = MolLande_b(mrt->Lambdaj, mrt->Sj, Nu, Ju);
break;
default:
sprintf(messageStr, "Unsupported Hund's case: %d", mrt->Hundj);
Error(ERROR_LEVEL_2, routineName, messageStr);
}
for (Ml = -Jl; Ml <= Jl; Ml++) {
for (Mu = -Ju; Mu <= Ju; Mu++) {
if ((Ml - Mu) == 1.0) {
shift = gLl*Ml - gLu*Mu;
strength = MolZeemanStr(Ju, Mu, Jl, Ml);
g_eff += shift * strength;
norm += strength;
}
}
}
return g_eff / norm;
}
/* ------- end ---------------------------- MolLande_eff.c ---------- */
/* ------- begin -------------------------- MolZeeman.c ------------- */
void* MolZeeman(MolecularLine *mrt)
{
const char routineName[] = "MolZeeman";
register int n;
double Jl, Ju, Mu, Ml, norm[3], g_eff, Nl, Nu, gLl, gLu, lambda_air;
ZeemanMultiplet *zm;
/* --- Return a pointer to a ZeemanMultiplet structure with all the
components of a Zeeman split line. The strengths in the line
are normalized to unity for each of the three possible values
of q = [-1, 0, 1].
Convention:
-- q = +1 corresponds to a redshifted \sigma profile
(zm->shift > 0). This redshifted profile has
right-handed circular polarization when the
magnetic field parallel to the line of sight and
points towards the observer.
-- q = 0 corresponds to an unpolarized \pi profile
-- -------------- */
mrt->zm = (ZeemanMultiplet *) malloc(sizeof(ZeemanMultiplet));
initZeeman(mrt->zm);
zm = mrt->zm;
if (mrt->g_Lande_eff != 0.0) {
/* --- In case an effective Landee factor has been specified, or
the the inputs.use_effective_Lande parameter has been set
in the input -- -------------- */
zm->Ncomponent = 3;
zm->q = (int *) malloc(3 * sizeof(int));
zm->strength = (double *) malloc(3 * sizeof(double));
zm->shift = (double *) malloc(3 * sizeof(double));
/* --- Normal Zeeman triplet -- -------------- */
for (n = 0; n < 3; n++) {
zm->q[n] = -1 + n;
zm->strength[n] = 1.0;
zm->shift[n] = zm->q[n] * mrt->g_Lande_eff;
}
} else {
/* --- Anomalous Zeeman splitting. First, count the number of
components -- -------------- */
Jl = (mrt->gi - 1.0) / 2.0;
Ju = (mrt->gj - 1.0) / 2.0;
switch (mrt->Hundi) {
case CASE_A:
gLl = MolLande_a(mrt->Lambdai, mrt->Si, mrt->Omegai, Jl);
break;
case CASE_B:
Nl = Jl - mrt->Si + (mrt->subi - 1);
gLl = MolLande_b(mrt->Lambdai, mrt->Si, Nl, Jl);
break;
default:
sprintf(messageStr, "Unsupported Hund's case: %d", mrt->Hundi);
Error(ERROR_LEVEL_2, routineName, messageStr);
}
switch (mrt->Hundj) {
case CASE_A:
gLu = MolLande_a(mrt->Lambdaj, mrt->Sj, mrt->Omegaj, Ju);
break;
case CASE_B:
Nu = Ju - mrt->Sj + (mrt->subj - 1);
gLu = MolLande_b(mrt->Lambdaj, mrt->Sj, Nu, Ju);
break;
default:
sprintf(messageStr, "Unsupported Hund's case: %d", mrt->Hundj);
Error(ERROR_LEVEL_2, routineName, messageStr);
}
/* --- Determine the number of components -- -------------- */
zm->Ncomponent = 0;
for (Ml = -Jl; Ml <= Jl; Ml++) {
for (Mu = -Ju; Mu <= Ju; Mu++)
if (fabs(Mu - Ml) <= 1.0) zm->Ncomponent++;
}
zm->q = (int *) malloc(zm->Ncomponent * sizeof(int));
zm->strength = (double *) malloc(zm->Ncomponent * sizeof(double));
zm->shift = (double *) malloc(zm->Ncomponent * sizeof(double));
/* --- Fill the structure and normalize the strengths -- -------- */
for (n = 0; n < 3; n++) norm[n] = 0.0;
n = 0;
g_eff = 0.0;
for (Ml = -Jl; Ml <= Jl; Ml++) {
for (Mu = -Ju; Mu <= Ju; Mu++) {
if (fabs(Ml - Mu) <= 1.0) {
zm->q[n] = (int) (Ml - Mu);
zm->shift[n] = gLl*Ml - gLu*Mu;
zm->strength[n] = MolZeemanStr(Ju, Mu, Jl, Ml);
if ((Ml - Mu) == 1)
g_eff += zm->strength[n] * zm->shift[n];
norm[zm->q[n]+1] += zm->strength[n];
n++;
}
}
}
for (n = 0; n < zm->Ncomponent; n++)
zm->strength[n] /= norm[zm->q[n]+1];
mrt->g_Lande_eff = g_eff / norm[2];
}
vacuum_to_air(1, &(mrt->lambda0), &lambda_air);
sprintf(messageStr, " -- %2s line at %9.4f nm has %3d "
"Zeeman components, gL_eff = %7.4f\n", mrt->molecule->ID,
lambda_air, zm->Ncomponent, mrt->g_Lande_eff);
Error(MESSAGE, routineName, messageStr);
}
/* ------- end ------------------------- MolZeeman.c ---------------- */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define CANT 5
int main()
{
int i,edad[CANT],legajo[CANT],isEmpty[CANT];
float sueldo[CANT];
for (i=0;i<CANT;i++){
isEmpty[i]=1
}
for(i=0; i<CANT; i++)
{
edad[i]=0;
sueldo[i]=0;
}
do
{
for(i=0;i<CANT;i++){
if(isEmpty[i]==1){
printf("Ingrese Edad");
scanf("%d",&edad[leg-1]);
printf("Ingrese el sueldo");
scanf("%f",&aux);
sueldo[cont]=aux;
isEmpty[i]=0;
break;
}
printf("Desea ingresar otro dato S/N?");
fflush(stdin);
scanf("%c",&seguir);
cont++;
}
while(seguir=='s');
for(i=0; i<MAX; i++){
suma=suma+sueldo[i];}
prom=suma/MAX;
printf("El sueldo promedio es %.2f",prom);
}
}
|
C
|
/*
* 読み込んだ整数値を3で割った剰余を表示
*/
#include <stdio.h>
int main(void)
{
int num;
printf("整数を入力してください:");
scanf("%d", &num);
if (num % 3 == 0)
puts("その数は3で割り切れます。");
else if (num % 3 == 1)
puts("その数を3で割った余りは1です。");
else
puts("その数を3で割った余りは2です。");
return(0);
}
|
C
|
/*practica 4-1
saine coronado gozain
*/
#include<stdio.h>
int main()
{
int n,i;
printf("inserta un numero\t");
scanf("\n%d",&n);//guarda un entero
for (i=0;i<=n;i++){ //for desde 0 hasta n
printf("%d\n",i);}
}
|
C
|
#include<stdio.h>
#include<time.h>
int notPrime(int a)
{
int b=sqrt(a),i;
if(a==1)
return 1;
for(i=2;i<=b;i++)
if(!(a%i))
return 1;
return 0;
}
int power(int a)
{
int b=1,i;
for(i=0;i<a;i++)
b*=10;
return b;
}
int isTruncatable(int a)
{
int i=0;
while(a/power(i))
if(notPrime(a/power(i++)))
return 0;
while(i)
if(notPrime(a%power(--i)))
return 0;
return 1;
}
int main()
{
double time=(double)clock()/CLOCKS_PER_SEC;
int i=10,sum=0,count=0;
while(count<11)
if(isTruncatable(++i))
{
sum+=i;
count++;
}
printf("%d\n",sum);
printf("%.3f sec\n",(double)clock()/CLOCKS_PER_SEC-time);
getch();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* 6.5
Crea un programa llamado
ex_6_5
,
en el que el usuario introduzca números enteros hasta
adivinar el número aleatorio entre 0 y 100 generado al azar por el ordenador. El programa debe
avisar si el número introducido por el usuario es más grande o más pequeño que el número
generado aleatoriamente.
La instrucción de C que te permite generar un número aleatorio entre 0 i
n
-1, ambos incluidos,
es
rand()%n
, y la instrucción de C que nos permite que los números aleatorios sean
diferentes en cada nueva ejecución del programa es
srand(time(NULL))
o bien
srand(getpid()) */
int main (void) {
srand(time(NULL));
int num, numal = rand() % 101;
printf("Hola dime un número del 0 al 100: ");
scanf("%d",&num);
while ( num != numal ){
if ( num > numal ){
printf("Tiene que ser mas pequeño ");
scanf("%d", &num);
}
else {
printf("El numero tiene que ser mayor ");
scanf("%d", &num);
}
}
printf("----------------------------------\n");
printf("|Muy bien! Tienes mucha suerte!|\n");
printf("----------------------------------");
}
|
C
|
#include<stdio.h>
//c program to check whether a triangle is valid or not if angles are given.
int main()
{
int angle1, angle2, angle3, sum;
printf("Entert the angles of traiangle\n");
scanf("%d%d%d", &angle1, &angle2, &angle3);
sum = angle1+angle2+angle3;
if (sum == 180 && angle1 > 0 && angle2 > 0 && angle3 > 0)
{
printf(" Triangle is valid\n");
}
else
{
printf("Triangle is not valid\n");
}
return 0;
}
|
C
|
#include <stdio.h>
int main(){
int a,b;
scanf("%d %d",&a, &b);
for(int i=a; i<=b; i++){
if(i%2!=0){
printf("%d ",i);
}
}
}
|
C
|
#include<stdio.h>
typedef int integer; /*TYPE DEFINATION*/
void main()
{
printf("******typedef******\n");
/*Inputs*/
integer a;
/*Output*/
printf("The Program has run without error than \n:- typedef int integer; -:\n has successfully performed\n");
}
|
C
|
// SyncStates.h
// Created by Chris LeCroy on Thu, Dec 4, 1997 @ 10:48 PM.
#ifndef __SyncStates__
#define __SyncStates__
// State = status of record
// Actions = Action to take
// Remote = Handheld
// Local = Macintosh or PC
// Description of states
// No Change = no changes since last HotSync
// Modify = Record modified since last HotSync
// ArchiveNoModify = Record to be archived - not modified since last HotSync
// ArchiveModify = Record to be archived - has been modified since last HotSync
// Delete = Record to be deleted
// Add = Record has been added since last HotSync
// NoRecord = Status indicating there is no existing record
// ReadOnly = Record is a ReadOnly Record - can not be modified (Local Only)
// Description of Actions
// None = Do nothing
// Archive = Record is archived then deleted from database
// Delete = Record is deleted from database
// RemoteReplaceLocal = Record on the Mac/PC is replaced with the HH record
// LocalReplaceRemote = Record on the HH is replaced with the Mac/PC record
// SyncError = Indicates a condition which should not logically occur (also logs error)
// Log = Send message to log
/*
The following are the atomic states that a pair of records might be in.
combination of "states". Each record pair is examined and and the appropriate
state bits are set.
*/
enum
{
kRemoteNoChange = 0x00000001,
kRemoteModify = 0x00000002,
// kRemoteAdd = 0x00000004,
kRemoteDelete = 0x00000008,
kRemoteArchiveModify = 0x00000010,
kRemoteArchiveNoModify = 0x00000020,
kRemoteNoRecord = 0x00000040,
kLocalNoChange = 0x00000100,
kLocalModify = 0x00000200,
// kLocalAdd = 0x00000400,
kLocalDelete = 0x00000800,
kLocalArchiveModify = 0x00001000,
kLocalArchiveNoModify = 0x00002000,
kLocalNoRecord = 0x00004000,
kLocalReadOnly = 0x00008000,
kRecordDataUnequal = 0x00010000,
kRecordDataEqual = 0x00020000
};
const UInt32 kStatesCount = 32;
/*
The following are the atomic actions that may be taken in response to a particular
combination of "states". More than one atomic action may be taken for some
state oombination. For example a full record deletion would be represented as:
kActionLocalDelete | kActionRemoteDelete
IMPORTANT:
Atomic actions are performed in right-to-left-bitwise order (ie, the actions with smaller
numbers happen first).
*/
enum
{
kSyncError = 0x00000000,
kActionLocalAddToRemote = 0x00000001,
kActionRemoteAddToLocal = 0x00000002,
kActionRemoteArchive = 0x00000010, //really means archive *and* delete
kActionRemoteReplaceLocal = 0x00000020,
kActionRemoteDelete = 0x00000040,
kActionLocalArchive = 0x00000100, //really means archive *and* delete
kActionLocalReplaceRemote = 0x00000200,
kActionLocalDelete = 0x00000400,
kActionNone = 0x01000000,
kActionLog = 0x02000000
};
const UInt32 kActionsCount = 32;
struct StateAndAction
{
UInt32 state;
UInt32 actions;
};
const StateAndAction kStateToActionMap[] =
{ // State Actions
// ----- -------
{ kRemoteNoChange | kLocalModify | kRecordDataEqual , kActionNone },
{ kRemoteNoChange | kLocalArchiveNoModify | kRecordDataEqual , kActionLocalArchive | kActionRemoteDelete },
{ kRemoteNoChange | kLocalArchiveModify | kRecordDataEqual , kActionLocalArchive | kActionRemoteDelete },
{ kRemoteNoChange | kLocalDelete | kRecordDataEqual , kActionLocalDelete | kActionRemoteDelete },
// { kRemoteNoChange | kLocalAdd | kRecordDataEqual , kSyncError },
{ kRemoteNoChange | kLocalNoRecord | kRecordDataEqual , kSyncError },
{ kRemoteNoChange | kLocalNoChange | kRecordDataEqual , kActionNone },
{ kRemoteModify | kLocalModify | kRecordDataEqual , kActionNone },
{ kRemoteModify | kLocalArchiveNoModify | kRecordDataEqual , kActionRemoteReplaceLocal | kActionLog },
{ kRemoteModify | kLocalArchiveModify | kRecordDataEqual , kActionRemoteDelete | kActionLocalArchive },
{ kRemoteModify | kLocalDelete | kRecordDataEqual , kActionRemoteReplaceLocal | kActionLog },
// { kRemoteModify | kLocalAdd | kRecordDataEqual , kSyncError },
{ kRemoteModify | kLocalNoRecord | kRecordDataEqual , kSyncError },
{ kRemoteModify | kLocalNoChange | kRecordDataEqual , kActionNone },
{ kRemoteArchiveNoModify | kLocalModify | kRecordDataEqual , kActionLocalReplaceRemote | kActionLog },
{ kRemoteArchiveNoModify | kLocalArchiveNoModify | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete },
{ kRemoteArchiveNoModify | kLocalArchiveModify | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete | kActionLog },
{ kRemoteArchiveNoModify | kLocalDelete | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete },
// { kRemoteArchiveNoModify | kLocalAdd | kRecordDataEqual , kSyncError },
{ kRemoteArchiveNoModify | kLocalNoRecord | kRecordDataEqual , kSyncError },
{ kRemoteArchiveNoModify | kLocalNoChange | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete },
{ kRemoteArchiveModify | kLocalModify | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete },
{ kRemoteArchiveModify | kLocalArchiveNoModify | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete },
{ kRemoteArchiveModify | kLocalArchiveModify | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete },
{ kRemoteArchiveModify | kLocalDelete | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete },
// { kRemoteArchiveModify | kLocalAdd | kRecordDataEqual , kSyncError },
{ kRemoteArchiveModify | kLocalNoRecord | kRecordDataEqual , kSyncError },
{ kRemoteArchiveModify | kLocalNoChange | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete },
{ kRemoteDelete | kLocalModify | kRecordDataEqual , kActionLocalReplaceRemote | kActionLog },
{ kRemoteDelete | kLocalArchiveNoModify | kRecordDataEqual , kActionRemoteDelete | kActionLocalArchive },
{ kRemoteDelete | kLocalArchiveModify | kRecordDataEqual , kActionRemoteDelete | kActionLocalArchive },
{ kRemoteDelete | kLocalDelete | kRecordDataEqual , kActionRemoteDelete | kActionLocalDelete },
// { kRemoteDelete | kLocalAdd | kRecordDataEqual , kSyncError },
{ kRemoteDelete | kLocalNoRecord | kRecordDataEqual , kSyncError },
{ kRemoteDelete | kLocalNoChange | kRecordDataEqual , kActionRemoteDelete },
// { kRemoteAdd | kLocalModify | kRecordDataEqual , kSyncError },
// { kRemoteAdd | kLocalArchiveNoModify | kRecordDataEqual , kSyncError },
// { kRemoteAdd | kLocalArchiveModify | kRecordDataEqual , kSyncError },
// { kRemoteAdd | kLocalDelete | kRecordDataEqual , kSyncError },
// { kRemoteAdd | kLocalAdd | kRecordDataEqual , kSyncError },
// { kRemoteAdd | kLocalNoRecord | kRecordDataEqual , kSyncError },
// { kRemoteAdd | kLocalNoChange | kRecordDataEqual , kSyncError },
{ kRemoteNoRecord | kLocalModify | kRecordDataEqual , kSyncError },
{ kRemoteNoRecord | kLocalArchiveNoModify | kRecordDataEqual , kSyncError },
{ kRemoteNoRecord | kLocalArchiveModify | kRecordDataEqual , kSyncError },
{ kRemoteNoRecord | kLocalDelete | kRecordDataEqual , kSyncError },
// { kRemoteNoRecord | kLocalAdd | kRecordDataEqual , kSyncError },
{ kRemoteNoRecord | kLocalNoRecord | kRecordDataEqual , kSyncError },
{ kRemoteNoRecord | kLocalNoChange | kRecordDataEqual , kActionLocalAddToRemote },
{ kRemoteNoChange | kLocalModify | kRecordDataUnequal , kActionLocalReplaceRemote },
{ kRemoteNoChange | kLocalArchiveNoModify | kRecordDataUnequal , kActionRemoteDelete | kActionLocalArchive },
{ kRemoteNoChange | kLocalArchiveModify | kRecordDataUnequal , kActionRemoteDelete | kActionLocalArchive },
{ kRemoteNoChange | kLocalDelete | kRecordDataUnequal , kActionRemoteDelete | kActionLocalDelete },
// { kRemoteNoChange | kLocalAdd | kRecordDataUnequal , kSyncError },
{ kRemoteNoChange | kLocalNoRecord | kRecordDataUnequal , kActionRemoteAddToLocal },
{ kRemoteNoChange | kLocalNoChange | kRecordDataUnequal , kActionLocalAddToRemote | kActionRemoteAddToLocal | kActionLog },
{ kRemoteModify | kLocalModify | kRecordDataUnequal , kActionLocalAddToRemote | kActionRemoteAddToLocal | kActionLog },
{ kRemoteModify | kLocalArchiveNoModify | kRecordDataUnequal , kActionRemoteReplaceLocal | kActionLog },
{ kRemoteModify | kLocalArchiveModify | kRecordDataUnequal , kActionLocalAddToRemote | kActionRemoteAddToLocal | kActionLog },
{ kRemoteModify | kLocalDelete | kRecordDataUnequal , kActionRemoteReplaceLocal | kActionLog },
// { kRemoteModify | kLocalAdd | kRecordDataUnequal , kSyncError },
{ kRemoteModify | kLocalNoRecord | kRecordDataUnequal , kActionRemoteAddToLocal },
{ kRemoteModify | kLocalNoChange | kRecordDataUnequal , kActionRemoteReplaceLocal },
{ kRemoteArchiveNoModify | kLocalModify | kRecordDataUnequal , kActionLocalReplaceRemote | kActionLog },
{ kRemoteArchiveNoModify | kLocalArchiveNoModify | kRecordDataUnequal , kActionRemoteArchive | kActionLocalArchive },
{ kRemoteArchiveNoModify | kLocalArchiveModify | kRecordDataUnequal , kActionRemoteArchive | kActionLocalArchive },
{ kRemoteArchiveNoModify | kLocalDelete | kRecordDataUnequal , kActionRemoteArchive | kActionLocalDelete },
// { kRemoteArchiveNoModify | kLocalAdd | kRecordDataUnequal , kSyncError },
{ kRemoteArchiveNoModify | kLocalNoChange | kRecordDataUnequal , kActionRemoteArchive | kActionLocalDelete },
{ kRemoteArchiveNoModify | kLocalNoRecord | kRecordDataUnequal , kActionRemoteArchive },
{ kRemoteArchiveModify | kLocalModify | kRecordDataUnequal , kActionLocalAddToRemote | kActionRemoteAddToLocal | kActionLog },
{ kRemoteArchiveModify | kLocalArchiveNoModify | kRecordDataUnequal , kActionRemoteArchive | kActionLocalArchive },
{ kRemoteArchiveModify | kLocalArchiveModify | kRecordDataUnequal , kActionRemoteArchive | kActionLocalArchive },
{ kRemoteArchiveModify | kLocalDelete | kRecordDataUnequal , kActionRemoteArchive | kActionLocalDelete },
// { kRemoteArchiveModify | kLocalAdd | kRecordDataUnequal , kSyncError },
{ kRemoteArchiveModify | kLocalNoChange | kRecordDataUnequal , kActionRemoteArchive | kActionLocalDelete },
{ kRemoteArchiveModify | kLocalNoRecord | kRecordDataUnequal , kActionRemoteArchive },
{ kRemoteDelete | kLocalModify | kRecordDataUnequal , kActionRemoteReplaceLocal | kActionLog },
{ kRemoteDelete | kLocalArchiveNoModify | kRecordDataUnequal , kActionRemoteDelete | kActionLocalArchive },
{ kRemoteDelete | kLocalArchiveModify | kRecordDataUnequal , kActionRemoteDelete | kActionLocalArchive },
{ kRemoteDelete | kLocalDelete | kRecordDataUnequal , kActionRemoteDelete | kActionLocalDelete },
// { kRemoteDelete | kLocalAdd | kRecordDataUnequal , kSyncError },
{ kRemoteDelete | kLocalNoRecord | kRecordDataUnequal , kActionRemoteDelete },
{ kRemoteDelete | kLocalNoChange | kRecordDataUnequal , kActionRemoteDelete | kActionLocalDelete },
// { kRemoteAdd | kLocalModify | kRecordDataUnequal , kSyncError },
// { kRemoteAdd | kLocalArchiveNoModify | kRecordDataUnequal , kSyncError },
// { kRemoteAdd | kLocalArchiveModify | kRecordDataUnequal , kSyncError },
// { kRemoteAdd | kLocalDelete | kRecordDataUnequal , kSyncError },
// { kRemoteAdd | kLocalAdd | kRecordDataUnequal , kSyncError },
// { kRemoteAdd | kLocalNoChange | kRecordDataUnequal , kSyncError },
// { kRemoteAdd | kLocalNoRecord | kRecordDataUnequal , kActionRemoteAddToLocal },
{ kRemoteNoRecord | kLocalModify | kRecordDataUnequal , kActionLocalAddToRemote },
{ kRemoteNoRecord | kLocalArchiveNoModify | kRecordDataUnequal , kActionLocalArchive },
{ kRemoteNoRecord | kLocalArchiveModify | kRecordDataUnequal , kActionLocalArchive },
{ kRemoteNoRecord | kLocalDelete | kRecordDataUnequal , kActionLocalDelete },
// { kRemoteNoRecord | kLocalAdd | kRecordDataUnequal , kActionLocalAddToRemote },
{ kRemoteNoRecord | kLocalNoRecord | kRecordDataUnequal , kSyncError },
{ kRemoteNoRecord | kLocalNoChange | kRecordDataUnequal , kActionLocalAddToRemote },
{ kRemoteNoChange | kLocalReadOnly | kRecordDataUnequal , kActionLocalReplaceRemote },
{ kRemoteModify | kLocalReadOnly | kRecordDataUnequal , kActionLocalAddToRemote | kActionRemoteAddToLocal | kActionLog },
{ kRemoteArchiveNoModify | kLocalReadOnly | kRecordDataUnequal , kActionRemoteArchive | kActionLocalAddToRemote | kActionLog },
{ kRemoteArchiveModify | kLocalReadOnly | kRecordDataUnequal , kActionRemoteArchive | kActionLocalAddToRemote | kActionLog },
{ kRemoteDelete | kLocalReadOnly | kRecordDataUnequal , kActionRemoteDelete | kActionLocalAddToRemote | kActionLog },
// { kRemoteAdd | kLocalReadOnly | kRecordDataUnequal , kSyncError },
{ kRemoteNoRecord | kLocalReadOnly | kRecordDataUnequal , kSyncError },
{ kRemoteNoChange | kLocalReadOnly | kRecordDataEqual , kActionNone },
{ kRemoteModify | kLocalReadOnly | kRecordDataEqual , kActionNone },
{ kRemoteArchiveNoModify | kLocalReadOnly | kRecordDataEqual , kActionRemoteArchive | kActionLocalAddToRemote | kActionLog },
{ kRemoteArchiveModify | kLocalReadOnly | kRecordDataEqual , kActionRemoteArchive | kActionLocalAddToRemote | kActionLog },
{ kRemoteDelete | kLocalReadOnly | kRecordDataEqual , kActionLog },
// { kRemoteAdd | kLocalReadOnly | kRecordDataEqual , kSyncError },
{ kRemoteNoRecord | kLocalReadOnly | kRecordDataEqual , kSyncError }
};
const int kNumberofStates = sizeof(kStateToActionMap) / sizeof(StateAndAction);
#ifdef _DEBUG
const char* kStateToActionMapStrings[kNumberofStates] =
{ // State Actions
// ----- -------
"[ kRemoteNoChange | kLocalModify | kRecordDataEqual , kActionNone ]",
"[ kRemoteNoChange | kLocalArchiveNoModify | kRecordDataEqual , kActionLocalArchive | kActionRemoteDelete ]",
"[ kRemoteNoChange | kLocalArchiveModify | kRecordDataEqual , kActionLocalArchive | kActionRemoteDelete ]",
"[ kRemoteNoChange | kLocalDelete | kRecordDataEqual , kActionLocalDelete | kActionRemoteDelete ]",
// "[ kRemoteNoChange | kLocalAdd | kRecordDataEqual , kSyncError ]",
"[ kRemoteNoChange | kLocalNoRecord | kRecordDataEqual , kSyncError ]",
"[ kRemoteNoChange | kLocalNoChange | kRecordDataEqual , kActionNone ]",
"[ kRemoteModify | kLocalModify | kRecordDataEqual , kActionNone ]",
"[ kRemoteModify | kLocalArchiveNoModify | kRecordDataEqual , kActionRemoteReplaceLocal | kActionLog ]",
"[ kRemoteModify | kLocalArchiveModify | kRecordDataEqual , kActionRemoteDelete | kActionLocalArchive ]",
"[ kRemoteModify | kLocalDelete | kRecordDataEqual , kActionRemoteReplaceLocal | kActionLog ]",
// "[ kRemoteModify | kLocalAdd | kRecordDataEqual , kSyncError ]",
"[ kRemoteModify | kLocalNoRecord | kRecordDataEqual , kSyncError ]",
"[ kRemoteModify | kLocalNoChange | kRecordDataEqual , kActionNone ]",
"[ kRemoteArchiveNoModify | kLocalModify | kRecordDataEqual , kActionLocalReplaceRemote | kActionLog ]",
"[ kRemoteArchiveNoModify | kLocalArchiveNoModify | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete ]",
"[ kRemoteArchiveNoModify | kLocalArchiveModify | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete | kActionLog ]",
"[ kRemoteArchiveNoModify | kLocalDelete | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete ]",
// "[ kRemoteArchiveNoModify | kLocalAdd | kRecordDataEqual , kSyncError ]",
"[ kRemoteArchiveNoModify | kLocalNoRecord | kRecordDataEqual , kSyncError ]",
"[ kRemoteArchiveNoModify | kLocalNoChange | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete ]",
"[ kRemoteArchiveModify | kLocalModify | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete ]",
"[ kRemoteArchiveModify | kLocalArchiveNoModify | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete ]",
"[ kRemoteArchiveModify | kLocalArchiveModify | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete ]",
"[ kRemoteArchiveModify | kLocalDelete | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete ]",
// "[ kRemoteArchiveModify | kLocalAdd | kRecordDataEqual , kSyncError ]",
"[ kRemoteArchiveModify | kLocalNoRecord | kRecordDataEqual , kSyncError ]",
"[ kRemoteArchiveModify | kLocalNoChange | kRecordDataEqual , kActionRemoteArchive | kActionLocalDelete ]",
"[ kRemoteDelete | kLocalModify | kRecordDataEqual , kActionLocalReplaceRemote | kActionLog ]",
"[ kRemoteDelete | kLocalArchiveNoModify | kRecordDataEqual , kActionRemoteDelete | kActionLocalArchive ]",
"[ kRemoteDelete | kLocalArchiveModify | kRecordDataEqual , kActionRemoteDelete | kActionLocalArchive ]",
"[ kRemoteDelete | kLocalDelete | kRecordDataEqual , kActionRemoteDelete | kActionLocalDelete ]",
// "[ kRemoteDelete | kLocalAdd | kRecordDataEqual , kSyncError ]",
"[ kRemoteDelete | kLocalNoRecord | kRecordDataEqual , kSyncError ]",
"[ kRemoteDelete | kLocalNoChange | kRecordDataEqual , kActionRemoteDelete ]",
// "[ kRemoteAdd | kLocalModify | kRecordDataEqual , kSyncError ]",
// "[ kRemoteAdd | kLocalArchiveNoModify | kRecordDataEqual , kSyncError ]",
// "[ kRemoteAdd | kLocalArchiveModify | kRecordDataEqual , kSyncError ]",
// "[ kRemoteAdd | kLocalDelete | kRecordDataEqual , kSyncError ]",
// "[ kRemoteAdd | kLocalAdd | kRecordDataEqual , kSyncError ]",
// "[ kRemoteAdd | kLocalNoRecord | kRecordDataEqual , kSyncError ]",
// "[ kRemoteAdd | kLocalNoChange | kRecordDataEqual , kSyncError ]",
"[ kRemoteNoRecord | kLocalModify | kRecordDataEqual , kSyncError ]",
"[ kRemoteNoRecord | kLocalArchiveNoModify | kRecordDataEqual , kSyncError ]",
"[ kRemoteNoRecord | kLocalArchiveModify | kRecordDataEqual , kSyncError ]",
"[ kRemoteNoRecord | kLocalDelete | kRecordDataEqual , kSyncError ]",
// "[ kRemoteNoRecord | kLocalAdd | kRecordDataEqual , kSyncError ]",
"[ kRemoteNoRecord | kLocalNoRecord | kRecordDataEqual , kSyncError ]",
"[ kRemoteNoRecord | kLocalNoChange | kRecordDataEqual , kActionLocalAddToRemote ]",
"[ kRemoteNoChange | kLocalModify | kRecordDataUnequal , kActionLocalReplaceRemote ]",
"[ kRemoteNoChange | kLocalArchiveNoModify | kRecordDataUnequal , kActionRemoteDelete | kActionLocalArchive ]",
"[ kRemoteNoChange | kLocalArchiveModify | kRecordDataUnequal , kActionRemoteDelete | kActionLocalArchive ]",
"[ kRemoteNoChange | kLocalDelete | kRecordDataUnequal , kActionRemoteDelete | kActionLocalDelete ]",
// "[ kRemoteNoChange | kLocalAdd | kRecordDataUnequal , kSyncError ]",
"[ kRemoteNoChange | kLocalNoRecord | kRecordDataUnequal , kActionRemoteAddToLocal ]",
"[ kRemoteNoChange | kLocalNoChange | kRecordDataUnequal , kActionLocalAddToRemote | kActionRemoteAddToLocal | kActionLog ]",
"[ kRemoteModify | kLocalModify | kRecordDataUnequal , kActionLocalAddToRemote | kActionRemoteAddToLocal | kActionLog ]",
"[ kRemoteModify | kLocalArchiveNoModify | kRecordDataUnequal , kActionRemoteReplaceLocal | kActionLog ]",
"[ kRemoteModify | kLocalArchiveModify | kRecordDataUnequal , kActionLocalAddToRemote | kActionRemoteAddToLocal | kActionLog ]",
"[ kRemoteModify | kLocalDelete | kRecordDataUnequal , kActionRemoteReplaceLocal | kActionLog ]",
// "[ kRemoteModify | kLocalAdd | kRecordDataUnequal , kSyncError ]",
"[ kRemoteModify | kLocalNoRecord | kRecordDataUnequal , kActionRemoteAddToLocal ]",
"[ kRemoteModify | kLocalNoChange | kRecordDataUnequal , kActionRemoteReplaceLocal ]",
"[ kRemoteArchiveNoModify | kLocalModify | kRecordDataUnequal , kActionLocalReplaceRemote | kActionLog ]",
"[ kRemoteArchiveNoModify | kLocalArchiveNoModify | kRecordDataUnequal , kActionRemoteArchive | kActionLocalArchive ]",
"[ kRemoteArchiveNoModify | kLocalArchiveModify | kRecordDataUnequal , kActionRemoteArchive | kActionLocalArchive ]",
"[ kRemoteArchiveNoModify | kLocalDelete | kRecordDataUnequal , kActionRemoteArchive | kActionLocalDelete ]",
// "[ kRemoteArchiveNoModify | kLocalAdd | kRecordDataUnequal , kSyncError ]",
"[ kRemoteArchiveNoModify | kLocalNoChange | kRecordDataUnequal , kActionRemoteArchive | kActionLocalDelete ]",
"[ kRemoteArchiveNoModify | kLocalNoRecord | kRecordDataUnequal , kActionRemoteArchive ]",
"[ kRemoteArchiveModify | kLocalModify | kRecordDataUnequal , kActionLocalAddToRemote | kActionRemoteAddToLocal | kActionLog ]",
"[ kRemoteArchiveModify | kLocalArchiveNoModify | kRecordDataUnequal , kActionRemoteArchive | kActionLocalArchive ]",
"[ kRemoteArchiveModify | kLocalArchiveModify | kRecordDataUnequal , kActionRemoteArchive | kActionLocalArchive ]",
"[ kRemoteArchiveModify | kLocalDelete | kRecordDataUnequal , kActionRemoteArchive | kActionLocalDelete ]",
// "[ kRemoteArchiveModify | kLocalAdd | kRecordDataUnequal , kSyncError ]",
"[ kRemoteArchiveModify | kLocalNoChange | kRecordDataUnequal , kActionRemoteArchive | kActionLocalDelete ]",
"[ kRemoteArchiveModify | kLocalNoRecord | kRecordDataUnequal , kActionRemoteArchive ]",
"[ kRemoteDelete | kLocalModify | kRecordDataUnequal , kActionRemoteReplaceLocal | kActionLog ]",
"[ kRemoteDelete | kLocalArchiveNoModify | kRecordDataUnequal , kActionRemoteDelete | kActionLocalArchive ]",
"[ kRemoteDelete | kLocalArchiveModify | kRecordDataUnequal , kActionRemoteDelete | kActionLocalArchive ]",
"[ kRemoteDelete | kLocalDelete | kRecordDataUnequal , kActionRemoteDelete | kActionLocalDelete ]",
// "[ kRemoteDelete | kLocalAdd | kRecordDataUnequal , kSyncError ]",
"[ kRemoteDelete | kLocalNoRecord | kRecordDataUnequal , kActionRemoteDelete ]",
"[ kRemoteDelete | kLocalNoChange | kRecordDataUnequal , kActionRemoteDelete | kActionLocalDelete ]",
// "[ kRemoteAdd | kLocalModify | kRecordDataUnequal , kSyncError ]",
// "[ kRemoteAdd | kLocalArchiveNoModify | kRecordDataUnequal , kSyncError ]",
// "[ kRemoteAdd | kLocalArchiveModify | kRecordDataUnequal , kSyncError ]",
// "[ kRemoteAdd | kLocalDelete | kRecordDataUnequal , kSyncError ]",
// "[ kRemoteAdd | kLocalAdd | kRecordDataUnequal , kSyncError ]",
// "[ kRemoteAdd | kLocalNoChange | kRecordDataUnequal , kSyncError ]",
// "[ kRemoteAdd | kLocalNoRecord | kRecordDataUnequal , kActionRemoteAddToLocal ]",
"[ kRemoteNoRecord | kLocalModify | kRecordDataUnequal , kActionLocalAddToRemote ]",
"[ kRemoteNoRecord | kLocalArchiveNoModify | kRecordDataUnequal , kActionLocalArchive ]",
"[ kRemoteNoRecord | kLocalArchiveModify | kRecordDataUnequal , kActionLocalArchive ]",
"[ kRemoteNoRecord | kLocalDelete | kRecordDataUnequal , kActionLocalDelete ]",
// "[ kRemoteNoRecord | kLocalAdd | kRecordDataUnequal , kActionLocalAddToRemote ]",
"[ kRemoteNoRecord | kLocalNoRecord | kRecordDataUnequal , kSyncError ]",
"[ kRemoteNoRecord | kLocalNoChange | kRecordDataUnequal , kActionLocalAddToRemote ]",
"[ kRemoteNoChange | kLocalReadOnly | kRecordDataUnequal , kActionLocalReplaceRemote ]",
"[ kRemoteModify | kLocalReadOnly | kRecordDataUnequal , kActionLocalAddToRemote | kActionRemoteAddToLocal | kActionLog ]",
"[ kRemoteArchiveNoModify | kLocalReadOnly | kRecordDataUnequal , kActionRemoteArchive | kActionLocalAddToRemote | kActionLog ]",
"[ kRemoteArchiveModify | kLocalReadOnly | kRecordDataUnequal , kActionRemoteArchive | kActionLocalAddToRemote | kActionLog ]",
"[ kRemoteDelete | kLocalReadOnly | kRecordDataUnequal , kActionRemoteDelete | kActionLocalAddToRemote | kActionLog ]",
// "[ kRemoteAdd | kLocalReadOnly | kRecordDataUnequal , kSyncError ]",
"[ kRemoteNoRecord | kLocalReadOnly | kRecordDataUnequal , kActionLocalAddToRemote ]",
"[ kRemoteNoChange | kLocalReadOnly | kRecordDataEqual , kActionNone ]",
"[ kRemoteModify | kLocalReadOnly | kRecordDataEqual , kActionNone ]",
"[ kRemoteArchiveNoModify | kLocalReadOnly | kRecordDataEqual , kActionRemoteArchive | kActionLocalAddToRemote | kActionLog ]",
"[ kRemoteArchiveModify | kLocalReadOnly | kRecordDataEqual , kActionRemoteArchive | kActionLocalAddToRemote | kActionLog ]",
"[ kRemoteDelete | kLocalReadOnly | kRecordDataEqual , kActionLog ]",
// "[ kRemoteAdd | kLocalReadOnly | kRecordDataEqual , kSyncError ]",
"[ kRemoteNoRecord | kLocalReadOnly | kRecordDataEqual , kSyncError ]"
};
#endif //_DEBUG
#endif //__SyncStates__
|
C
|
/*
* ClientsInterface.h
*
* Created on: 11/11/2017
* Author: Francisco Maria / Joo Gama Amaral
*/
#ifndef CLIENTSINTERFACE_H_
#define CLIENTSINTERFACE_H_
#include "MovingCompany.h"
#include <ctime>
/**
* @brief Prints a client
* @param company The company object itself.
* @return 0 or -1 depending on the input.
*/
int checkClient(MovingCompany& company);
/**
* @brief Searches a client thats belongs to the company by name.
* @param company The company object itself.
* @return 0 or -1 depending on the input.
*/
int searchClientByName(MovingCompany& company);
/**
* @brief Searches a client that belongs to the company by ID.
* @param company The company object itself.
* @return 0 or -1 depending on the input.
*/
int searchClientByID(MovingCompany& company);
/**
* @brief Searches a client that belongs to the company by NIF.
* @param company The company object itself.
* @return 0 or -1 depending on the input.
*/
int searchClientByNIF(MovingCompany& company);
/**
* @brief Adds a new company to the company.
* @param company The company object itself.
* @return 0 or -1 depending on the input.
*/
int addNewClient(MovingCompany& company);
/**
* @brief Removes a client of the company.
* @param company The company object itself.
* @return 0 or -1 depending on the input.
*/
int removeClient(MovingCompany& company);
/**
* @brief Prints only particulars clients.
* @param company The company object itself.
* @return 0 or -1 depending on the input.
*/
int printParticulars(MovingCompany& company);
/**
* @brief Prints only companies clients.
* @param company The company object itself.
* @return 0 or -1 depending on the input.
*/
int printCompanies(MovingCompany& company);
/**
* @brief Prints all clients of the company
* @param company The company object itself
* @return 0 or -1 depending on the input
*/
int printClients(MovingCompany& company);
/**
* @brief Prints all vehicles of the company.
* @param company The company object itself
* @return 0 or -1 depending on the input
*/
int printVehicles(MovingCompany& company);
/**
* @brief Prints all available vehicles of the company
* @param company company itself
* @return 0 or -1 depending on the input
*/
int printAvailableVehicles(MovingCompany& company);
/**
* @brief Prints all non active clients
* @param The company object itself
* @return 0 or -1 depending on the input.
*/
int printNonActiveClients(MovingCompany& company);
/**
* @brief Updates a certain client information
* @param company The company object itself
* @return 0 or -1 depending on the input.
*/
int updateClientsInfo(MovingCompany& company);
#endif /* CLIENTSINTERFACE_H_ */
|
C
|
/* Andre Amirsaleh
* Partner: Nazmul Hossain
* date/time of your lab section
* lab 04 - csv_avg.c
* compile with: gcc
* notes: none
*/
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include "fileio.h"
// The CSV data is stored as a 2-D array of floats
float data[MAXROWS][MAXCOLS];
// The column names are stored in a 2-D array of chars
// (aka a 1-D array of MAXLEN strings)
char names[MAXCOLS][MAXLEN];
float average(int numrows, int col, float data[MAXROWS][MAXCOLS]) {
float sum = 0.0;
int row;
for (row = 0; row < numrows; row++) {
sum += data[row][col];
}
return sum / numrows;
}
int main(int argc, char* argv[])
{
if (argc < 2){
// missing required argument
printf("Usage %s <filename>\n",
argv[0]);
exit(-1);
}
int cols = 0;
int rows = 0;
// open the file to use the standard IO library.
FILE *fd = fopen(argv[1], "r");
// read the column names
if ( (cols = read_csv_row(fd, names)) < 0){
printf("Failed to read names from CSV file.\n");
exit(-2);
}else{
#ifdef DEBUG
// #define DEBUG to see debug output
// or compile with gcc -DDEBUG
int i;
for (i=0; i<MAXCOLS; i++){
printf("Col[%03d]: %s\n", i, names[i]);
}
#endif
}
// the remaining lines are the rows, read them
// into the data array.
if ( (rows = read_csv_cols(fd, data)) <= 0){
printf("Error: could not read file!\n");
exit(-3);
}
fclose(fd);
// compute the average for each column.
int i;
for (i=0; i<cols; i++){
printf("Average for column %50s is %12.6f\n",
names[i],
average(rows, i, data));
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SID 13
#define MAX_NAME 64
#define MAX_EMAILID 32
#define MAX_DOB 11
#define MAX_DOMAIN_SUFFIX 16
#define MAX_STATE 32
#define MAX_CATEGORY 5
const char domain_suffix[MAX_DOMAIN_SUFFIX] = "@iitjammu.ac.in";
typedef struct date
{
unsigned short day; // DD
unsigned short month; // MM
unsigned int year; // YYYY
} DATE;
// Student record
typedef struct student
{
char sid[MAX_SID]; // e.g. 2017KUCP1001
char name[MAX_NAME];
char emailid[MAX_EMAILID]; // e.g. 2017KUCP1001@iiitjammu.ac.in
char gender; // M = Male / F = Female
char dob[MAX_DOB]; // DD-MM-YYYY e.g. 01-01-2001
//DATE date_enrolled;
enum student_status
{
ss_Active,
ss_Passed_Out,
ss_Inactive
} status;
// student's state of domicile
char state[MAX_STATE];
// student's admission category: SC/ST/PH/OBC/Open
char category[MAX_CATEGORY];
// student's family income group:
// IG_LT1 -> SC/ST/PH
// IG_LT1 -> family income below 1 lac
// IG_LT5 -> family income above 1 lac and below 5 lac
// IG_GT5 -> family income above 5 lac
enum income_group
{
ig_SC,
ig_ST,
ig_PH,
ig_IG_LT1,
ig_IG_LT5,
ig_IG_GT5
} family_income_group;
} STUDENT;
int main()
{
printf("\n\tIIT Jammu student records: entry\n");
int n = 0;
unsigned int i = 0;
char enter;
printf("\nHow many student records are there? ");
scanf("%d", &n);
// Check input for student record count
if (n <= 0)
{
printf("\nInvalid number!\n");
return -1;
}
// Declare n array of pointers to structure student
STUDENT *s[n];
for (i = 0; i < n; i++)
{
// Allocate memory to individual structures
s[i] = (STUDENT *) malloc(sizeof(STUDENT));
// Check for memory allocation errors
if (NULL == s[i])
{
printf("\nMemory allocation error!\n");
return -2;
}
}
enter = getchar();
// Read student record details
for (i = 0; i < n; i++)
{
printf("\nDetails of student[%d]\n", i+1);
printf("\nEnter student id: ");
scanf("%[^\n]s", s[i]->sid);
enter = getchar();
printf("\nEnter student's name: ");
scanf("%[^\n]s", s[i]->name);
enter = getchar();
// Create email id from student id and domain_suffix
strncat(s[i]->emailid, s[i]->sid, strlen(s[i]->sid));
strncat(s[i]->emailid, domain_suffix, strlen(domain_suffix));
printf("\nEnter student's gender [M/F]: ");
scanf(" %c", &s[i]->gender);
enter = getchar();
printf("\nEnter student's DOB: ");
scanf("%[^\n]s", s[i]->dob);
enter = getchar();
// Compute status from enrollment date
s[i]->status = ss_Active;
} // student record entry ends here
printf("\n\tIIT Jammu student records: display\n");
for (i = 0; i < n; i++)
{
printf("\nDetails of student[%d]\n", i+1);
printf("\tstudent id: %s\n", s[i]->sid);
printf("\tstudent's name: %s\n", s[i]->name);
printf("\tstudent's email id: %s\n", s[i]->emailid);
printf("\tstudent's gender: %c\n", s[i]->gender);
printf("\tstudent's DOB: %s\n", s[i]->dob);
switch (s[i]->status)
{
case ss_Active:
printf("\tstudent status: Active \n");
break;
case ss_Passed_Out:
printf("\tstudent status: Active \n");
break;
case ss_Inactive:
printf("\tstudent status: Active \n");
break;
default:
printf("Invalid status!\n");
}
} // student record display ends here
// Free memory
for (i = 0; i < n; i++)
{
free(s[i]);
s[i] = NULL;
}
return 0;
}
|
C
|
/*
27/11/17
erik grunner
labs 10
problem 1
*/
#include <stdio.h>
#include <stdlib.h>
#define PI 3.14
int main()
{
float radius;
float area;
float diameter;
float *ptr1;
float *ptr2;
float *ptr3;
ptr1 = &radius;
ptr2 = &area;
ptr3 = &diameter;
printf("PLease input the radius of the circle");
scanf("%f",&*ptr1);
*ptr2 = (PI*((*ptr1)*(*ptr1)));
*ptr3 = (*ptr1*2);
printf("Your circle of %.1f radius\nHas a diameter of %.1f\nAn area of %.1f^2",*ptr1,*ptr3,*ptr2);
}
|
C
|
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <k_api.h>
#include <lwip/netif.h>
#include <lwip/dns.h>
#include <lwip/tcp.h>
#include <lwip/priv/tcp_priv.h>
#include <stdio.h>
void list_if(void)
{
unsigned int index;
struct netif * netif;
krhino_sched_disable();
netif = netif_list;
while( netif != NULL )
{
printf("network interface: %c%c%s\n",
netif->name[0],
netif->name[1],
(netif == netif_default)?" (Default)":"");
printf("MTU: %d\n", netif->mtu);
printf("MAC: ");
for (index = 0; index < netif->hwaddr_len; index ++)
printf("%02x ", netif->hwaddr[index]);
printf("\nFLAGS:");
if (netif->flags & NETIF_FLAG_UP) printf(" UP");
else printf(" DOWN");
if (netif->flags & NETIF_FLAG_LINK_UP) printf(" LINK_UP");
else printf(" LINK_DOWN");
//if (netif->flags & NETIF_FLAG_DHCP) printf(" DHCP");
//if (netif->flags & NETIF_FLAG_POINTTOPOINT) printf(" PPP");
if (netif->flags & NETIF_FLAG_ETHARP) printf(" ETHARP");
if (netif->flags & NETIF_FLAG_IGMP) printf(" IGMP");
printf("\n");
printf("ip address: %s\n", ipaddr_ntoa(&(netif->ip_addr)));
printf("gw address: %s\n", ipaddr_ntoa(&(netif->gw)));
printf("net mask : %s\n", ipaddr_ntoa(&(netif->netmask)));
printf("\r\n");
netif = netif->next;
}
#if LWIP_DNS
{
const ip_addr_t* ip_addr;
for(index=0; index<DNS_MAX_SERVERS; index++)
{
ip_addr = dns_getserver(index);
printf("dns server #%d: %s\n", index, ipaddr_ntoa(ip_addr));
}
}
#endif /**< #if LWIP_DNS */
krhino_sched_enable();
}
void set_if(char* netif_name, char* ip_addr, char* gw_addr, char* nm_addr)
{
ip_addr_t *ip;
ip_addr_t addr;
struct netif * netif = netif_list;
if(strlen(netif_name) > sizeof(netif->name))
{
printf("network interface name too long!\r\n");
return;
}
while(netif != NULL)
{
if(strncmp(netif_name, netif->name, sizeof(netif->name)) == 0)
break;
netif = netif->next;
if( netif == NULL )
{
printf("network interface: %s not found!\r\n", netif_name);
return;
}
}
ip = (ip_addr_t *)&addr;
/* set ip address */
if ((ip_addr != NULL) && ipaddr_aton(ip_addr, &addr))
{
netif_set_ipaddr(netif, ip);
}
/* set gateway address */
if ((gw_addr != NULL) && ipaddr_aton(gw_addr, &addr))
{
netif_set_gw(netif, ip);
}
/* set netmask address */
if ((nm_addr != NULL) && ipaddr_aton(nm_addr, &addr))
{
netif_set_netmask(netif, ip);
}
}
void cmd_ifconfig(char *pwbuf, int blen, int argc, char **argv)
{
if (argc == 1)
{
list_if();
}
else if (argc == 5)
{
printf("config : %s\n", argv[1]);
printf("IP addr: %s\n", argv[2]);
printf("Gateway: %s\n", argv[3]);
printf("netmask: %s\n", argv[4]);
set_if(argv[1], argv[2], argv[3], argv[4]);
}
else
{
printf("bad parameter! e.g: ifconfig e0 192.168.1.30 192.168.1.1 255.255.255.0\n");
}
return;
}
static const char * const tcp_state_str[] = {
"CLOSED",
"LISTEN",
"SYN_SENT",
"SYN_RCVD",
"ESTABLISHED",
"FIN_WAIT_1",
"FIN_WAIT_2",
"CLOSE_WAIT",
"CLOSING",
"LAST_ACK",
"TIME_WAIT"
};
void cmd_netstat(char *pwbuf, int blen, int argc, char **argv)
{
unsigned int num = 0;
struct tcp_pcb *pcb;
char local_ip_str[16];
char remote_ip_str[16];
extern struct tcp_pcb *tcp_active_pcbs;
extern union tcp_listen_pcbs_t tcp_listen_pcbs;
extern struct tcp_pcb *tcp_tw_pcbs;
krhino_sched_disable();
printf("Active PCB states:\n");
for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next)
{
strcpy(local_ip_str, ipaddr_ntoa(&(pcb->local_ip)));
strcpy(remote_ip_str, ipaddr_ntoa(&(pcb->remote_ip)));
printf("#%d %s:%d <==> %s:%d snd_nxt 0x%08lX rcv_nxt 0x%08lX ",
num++,
local_ip_str,
pcb->local_port,
remote_ip_str,
pcb->remote_port,
pcb->snd_nxt,
pcb->rcv_nxt);
printf("state: %s\n", tcp_state_str[pcb->state]);
}
printf("Listen PCB states:\n");
num = 0;
for(pcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs; pcb != NULL; pcb = pcb->next)
{
printf("#%d local port %d ", num++, pcb->local_port);
printf("state: %s\n", tcp_state_str[pcb->state]);
}
printf("TIME-WAIT PCB states:\n");
num = 0;
for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next)
{
strcpy(local_ip_str, ipaddr_ntoa(&(pcb->local_ip)));
strcpy(remote_ip_str, ipaddr_ntoa(&(pcb->remote_ip)));
printf("#%d %s:%d <==> %s:%d snd_nxt 0x%08lX rcv_nxt 0x%08lX ",
num++,
local_ip_str,
pcb->local_port,
remote_ip_str,
pcb->remote_port,
pcb->snd_nxt,
pcb->rcv_nxt);
printf("state: %s\n", tcp_state_str[pcb->state]);
}
krhino_sched_enable();
}
|
C
|
#include <stdio.h>
int
main ()
{
int i,j; short B[50]; float n;
while(true)
{
for (i=0; i<50; i++) B[i] = 0; i = 0;
printf("Enter decimal fraction starting with a decimal point: ");
scanf("%f",&n);
while (n != 0 && i < 50)
{ n = 2.0*n;
if (n < 1.0)
{ B[i] = 0;}
else
{ B[i] = 1; n = n - 1.0; }
i = i + 1;
}
printf("Binary fraction is: ");
for (j=0; j<i; j++) printf("%d",B[j]);
printf("\n");
}
}
|
C
|
#include "catalog.h"
#include <stdio.h>
int main() {
catalog c =catalog_create("file/catalog.txt");
printf("nb occ a =%d\n", catalog_nbOccurrence(c, "a"));
printf("nb occ b =%d\n", catalog_nbOccurrence(c, "b"));
printf("nb occ z =%d\n", catalog_nbOccurrence(c, "z"));
printf("nb occ ab =%d\n", catalog_nbOccurrence(c, "ab"));
printf("pos 1er a =%d\n", catalog_posIthOccurrence(c, "a", 1));
printf("pos 2eme a =%d\n", catalog_posIthOccurrence(c, "a", 2));
printf("pos 1er ab =%d\n", catalog_posIthOccurrence(c, "ab", 1));
/* printf("pos 1er z =%d\n", catalog_posIthOccurrence(c, "z", 1)); */
/* printf("pos 2eme g =%d\n", catalog_posIthOccurrence(c, "g", 2)); */
printf("nb line =%d\n", catalog_nbLine(c));
catalog_insertAtLine(c, catalog_nbLine(c) +1, "test 1\ntest 2");
catalog_eraseLineBand(c, 2, 2);
char str[80];
catalog_getLine(c, 1, str);
printf("getLine ='%s'\n", str);
catalog_destroy(&c);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.