language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include<stdio.h>
void main()
{
int a=11;
if(a>10)
{
printf("Hello\n");
}
else{
printf("Indore\n");
}
}
|
C
|
/*
* metronom.c
*
* This module implements the timer callback facility for Dreamreel.
*/
#include <kos.h>
#include "dreamreel.h"
#include "metronom.h"
/* total vblank counter */
static int counter = 0;
static volatile int metronom_started;
/*static*/ volatile int64_t pts_counter;
static int pts_inc;
static int vblank_handler_handle;
/*static*/ volatile int64_t next_video_pts;
static void (*video_pts_callback)(void);
static volatile int64_t next_audio_pts;
static void (*audio_pts_callback)(void);
void set_next_video_pts(int64_t next_pts, void (*callback)(void)) {
next_video_pts = next_pts;
debug_printf (" set next video pts for %lld, vbl counter = %d\n", next_pts, counter);
video_pts_callback = callback;
}
void set_next_audio_pts(int64_t next_pts, void (*callback)(void)) {
next_audio_pts = next_pts;
audio_pts_callback = callback;
}
static void vblank_handler(uint32 code) {
counter++;
if (metronom_started) {
if (pts_counter >= next_video_pts) {
// next_video_pts = MAX_PTS;
video_pts_callback();
}
if (pts_counter >= next_audio_pts) {
next_audio_pts = MAX_PTS;
audio_pts_callback();
}
pts_counter += pts_inc;
}
}
void metronom_set(int64_t new_pts) {
debug_printf (" metronon_set: %lld\n", new_pts);
pts_counter = new_pts;
}
/* This function kicks off the periodic interrupt based on the refresh rate
* and sets up the pts ISR. */
void init_metronom(void) {
next_video_pts = next_audio_pts = MAX_PTS;
pts_counter = 0;
metronom_started = 0;
/* install a vblank handler */
vblank_handler_handle = vblank_handler_add(vblank_handler);
// if (ntsc)
pts_inc = 90000 / 60;
// else
// pts_inc = 90000 / 50;
}
void start_metronom(void) {
debug_printf (" metronom started (vbl counter = %d)\n", counter);
metronom_started = 1;
}
void stop_metronom(void) {
metronom_started = 0;
}
|
C
|
/*
The function int hthread_cond_broadcast(hthread_cond_t *cond); shall unblock
all threads, hardware or software, currently blocked on the specified
condition variable cond.
Hardware must be tested on the board
Methodology
1. Create a number of threads that will wait on the condvar
2. Wait until all threads have started
3. Lock the mutex
4. Issue a broadcast, all threads should wake up
5. Check that all threads woke up
*/
#include <hthread.h>
#include <stdlib.h>
#include <stdio.h>
#include "hthreadtest.h"
#define THREAD_NUM 3
#define EXPECTED_RESULT THREAD_NUM
struct testdata {
hthread_mutex_t * mutex;
hthread_cond_t * cond;
int * start_num;
int * waken_num;
void * function;
hthread_t thread[THREAD_NUM];
};
void * a_thread_function(void * arg) {
struct testdata * data = (struct testdata *) arg;
printf( "Thread %d Running\n", (int)hthread_self() );
hthread_mutex_lock( data->mutex );
*(data->start_num) += 1;
hthread_cond_wait( data->cond, data->mutex );
*(data->waken_num) += 1;
hthread_mutex_unlock( data->mutex);
return NULL;
}
void * testThread ( void * arg ) {
int retVal, i;
struct testdata * data = (struct testdata *) arg;
for( i=0; i<THREAD_NUM; i++ )
hthread_create( &data->thread[i], NULL, data->function, (void *) data );
while( *(data->start_num) != THREAD_NUM ) hthread_yield();
hthread_mutex_lock( data->mutex );
hthread_cond_broadcast( data->cond );
hthread_mutex_unlock( data->mutex );
for( i=0; i<THREAD_NUM; i++ )
hthread_join( data->thread[i], NULL );
retVal = *(data->waken_num);
hthread_exit( (void *) retVal );
return NULL;
}
int main() {
hthread_t test_thread;
hthread_attr_t test_attr;
int arg, retVal, start_num, waken_num;
struct testdata data;
hthread_mutex_t mutex;
hthread_cond_t cond;
//Print the name of the test to the screen
printf( "Starting test cond_broadcast_1\n" );
//Set up the arguments for the test
hthread_cond_init( &cond, NULL );
hthread_mutex_init( &mutex, NULL );
start_num = 0;
waken_num = 0;
data.mutex = &mutex;
data.cond = &cond;
data.start_num = &start_num;
data.waken_num = &waken_num;
data.function = a_thread_function;
arg = (int) &data;
//Initialize RPC
rpc_setup();
//Run the tests
hthread_attr_init( &test_attr );
if ( HARDWARE ) hthread_attr_sethardware( &test_attr, HWTI_ONE_BASEADDR );
hthread_create( &test_thread, &test_attr, testThread, (void *) arg );
hthread_join( test_thread, (void *) &retVal );
if ( HARDWARE ) readHWTStatus( HWTI_ONE_BASEADDR );
//Evaluate the results
if ( retVal == EXPECTED_RESULT ) {
printf("Test PASSED\n");
return PTS_PASS;
} else {
printf("Test FAILED [expecting %d, received %d]\n", EXPECTED_RESULT, retVal );
return PTS_FAIL;
}
}
|
C
|
#include <omp>
#include <stdio>
int main(int argc, char* argv[])
{
printf("I am the main thread.\n");
#pragma omp parallel
{
printf("I am thread %d of %d.\n", omp_get_thread_num(), omp_get_num_threads());
}
return 0;
}
|
C
|
// 2016-03-02 Daniel Stenekap och Gran Forstrm
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE -1
#define FALSE 0
// Defines fr flushRestOfLine
#define C_RADSLUT 10
// Defines fr itemStruct
#define C_ITEM_NAME_LENGTH 30
#define C_UNIT_NAME_LENGTH 30
#define C_LIST_LENGTH 3
// Defines for readLine
#define C_BUFFER_SIZE 80
struct itemStruct
{
char isName[C_ITEM_NAME_LENGTH];
float isAmount;
char isUnit[C_UNIT_NAME_LENGTH];
int isId;
};
typedef struct itemStruct ItemStruct;
// ============================================================================
// Returns FALSE if: Nothing was read, Input out of range, Input cut off by fgets before EOL.
// Return TRUE if a line was read including EOL, which is stripped from the target-array.
int readLine(char* ior_chArr, int i_sizeChArr)
{
int index = 0;
char bufferChArr[C_BUFFER_SIZE];
void *fgetsReturnPtr;
fgetsReturnPtr = fgets(bufferChArr, C_BUFFER_SIZE, stdin);
if (fgetsReturnPtr == NULL)
{
return FALSE;
}
do
{
if (index >= i_sizeChArr || index >= C_BUFFER_SIZE)
{
ior_chArr[index - 1] = '\0';
return FALSE;
}
if (bufferChArr[index] == '\0')
{
ior_chArr[index] = '\0';
return FALSE;
}
// Vi har en korrekt, inlsning spara den.
if (bufferChArr[index] == C_RADSLUT)
{
ior_chArr[index] = '\0';
return TRUE;
}
ior_chArr[index] = bufferChArr[index];
index++;
} while (TRUE);
} // readLine
// ============================================================================
static void flushRestOfLine(void)
{
// Call ONLY when EOL expected from the keyboardstream.
char ch;
do
{
scanf_s("%c", &ch, 1);
//printf_s("\n%d\n", ch);
} while (ch != C_RADSLUT);
} // flushRestOfLine
// ============================================================================
void inputItem(ItemStruct* ior_item)
{
int numberOfArgumentsRecived;
int okFlag;
// Get name as char arr...
do
{
printf_s("Name of item %d: ", (*ior_item).isId);
okFlag = readLine(ior_item->isName, sizeof(ior_item->isName));
if ('\0' == ior_item->isName[0])
{
okFlag = FALSE;
}
if (!okFlag)
{
// Clear isName if any error!
ior_item->isName[0] = '\0';
printf("*** Name not accepted! Try again!\n");
}
// "scanf_s" stops at space!
// scanf_s("%s", &ior_item->isName[0], sizeof(ior_item->isName)); // Bryter vid mellanslag
// flushRestOfLine();
} while (!okFlag);
// Get amount as float...
do
{
printf_s("Number of this item: ");
numberOfArgumentsRecived = scanf_s("%f", &ior_item->isAmount, sizeof(ior_item->isAmount));
flushRestOfLine();
if (numberOfArgumentsRecived == 1)
{
break;
}
else
{
printf_s("*** Please enter a number! ***\n");
}
} while (TRUE);
// Get unit as char arr...
do
{
printf_s("Enter the Unit: ");
okFlag = readLine(ior_item->isUnit, sizeof(ior_item->isUnit));
if ('\0' == ior_item->isUnit[0])
{
okFlag = FALSE;
}
if (!okFlag)
{
// Clear isName if any error!
ior_item->isUnit[0] = '\0';
printf("*** Unit not accepted! Try again!\n");
}
} while (!okFlag);
} // inputItem
// ============================================================================
void printList(ItemStruct* ior_item, int listLength)
{
int i = 0;
unsigned int maxNameLength = 0;
unsigned int maxUnitLength = 0;
char formatStr[100];
printf_s("The items on the list are...\n");
// Find length of longest text string...
for (i = 0; i < C_LIST_LENGTH; i++)
{
if (strlen(ior_item[i].isName) > maxNameLength)
{
maxNameLength = strlen(ior_item[i].isName);
}
if (strlen(ior_item[i].isUnit) > maxUnitLength)
{
maxUnitLength = strlen(ior_item[i].isUnit);
}
}
// Created adapted format string for the list
sprintf_s(&formatStr[0], 100, "Name: %%%ds Amount: %%6.2f Unit: %%%ds Unikt Id: %%3d\n", maxNameLength, maxUnitLength);
// Print list...
for (i = 0; i < C_LIST_LENGTH; i++)
{
printf_s(formatStr, (ior_item + i)->isName, (ior_item + i)->isAmount, (ior_item + i)->isUnit, (ior_item + i)->isId);
}
} // printList
// ============================================================================
void main(void)
{
ItemStruct itemList[C_LIST_LENGTH];
int i = 0;
printf_s("Welcome to the shopping list!\n\n");
printf_s("You may now enter your items!\n");
// Stter unikt id till vilket nummer den har p listan
for (i = 0; i < C_LIST_LENGTH; i++)
{
itemList[i].isId = i + 1;
inputItem(&itemList[i]);
printf_s("\n");
}
printList(itemList, C_LIST_LENGTH);
} // labb_51
|
C
|
/*
============================================================================
Name : SwitchSample.c
Author :
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int C;
setbuf(stdout,NULL);
printf("1 for Porotta \n2 for Chappathi \n3 for Manthi \n4 for Biriyani \n Enter your choice ");
scanf("%d",&C);
if (C==1){
printf("You have selected Porotta");
}else if(C==2){
printf("You have selected Chappathi");
}else if(C==3){
printf("You have selected Manthi");
}else if(C==4){
printf("You have selected Biriryani");
}else{
printf("idiot");
}
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include "Big_Block.h"
#include <limits.h>
#include <error.h>
big_block_list bigBlockList;
void BigBlockList_init()
{
for (int i = 0; i < MAX_SIZE_FOR_BIG_BLOCK; i++)
{
bigBlockList.bigBlock[i].blockptr = NULL;
bigBlockList.bigBlock[i].availablesize = 0;
bigBlockList.bigBlock[i].offset = 0;
}
return;
}
int splitBigBlock(meta_data mptr, size_t bytes)
{
if (mptr->blockSize <= bytes)
{
return INT_MIN;
}
meta_data temp = NULL, next = NULL;
size_t size = mptr->blockSize;
temp = mptr;
temp->blockSize = bytes;
temp->next = (meta_data)(((char *)temp) + METABLOCK_SIZE + bytes);
next = temp->next;
next->prev = temp;
next->next = temp->next->next;
next->blockSize = (size - (METABLOCK_SIZE + bytes));
next->isFree = TRUE;
next->head = temp->head;
return 1;
}
int mergeBigBlock(meta_data B1)
{
if (!B1 || B1->next == NULL || B1->isFree == FALSE || B1->next->isFree == FALSE)
return INT_MIN;
meta_data m;
m = B1->next;
size_t nextsize = m->blockSize;
B1->next = m->next;
m->next->prev = B1;
B1->blockSize += METABLOCK_SIZE + nextsize;
return 1;
}
void *ReturnBigBlock(size_t bytes)
{
int i = 0, requirepages;
while (i <= bigBlockList.count && bytes <= bigBlockList.bigBlock[i].availablesize)
{
i++;
}
if (i >= bigBlockList.count && bigBlockList.bigBlock[0].blockptr == NULL && bigBlockList.bigBlock[0].availablesize == 0 && bigBlockList.bigBlock[0].offset == 0)
{
requirepages = 4 > ((bytes + METABLOCK_SIZE) / SYSTEM_PAGE_SIZE) ? 4 : ((bytes + METABLOCK_SIZE) / SYSTEM_PAGE_SIZE) + 1;
bigBlockList.bigBlock[0].blockptr = (meta_data)mm_getnewvm(requirepages);
bigBlockList.bigBlock[0].offset = 0;
bigBlockList.bigBlock[0].availablesize = bytes;
bigBlockList.count = 0;
meta_data temp;
temp = bigBlockList.bigBlock[0].blockptr;
temp->blockSize = bytes;
temp->prev = NULL;
temp->next = NULL;
temp->isFree = TRUE;
temp->head = temp;
i = 0;
}
if (i <= bigBlockList.count)
{
meta_data ptr;
ptr = bigBlockList.bigBlock[i].blockptr;
while (ptr->blockSize < bytes)
{
ptr = ptr->next;
}
ptr->head = bigBlockList.bigBlock[i].blockptr;
int buf = ptr->blockSize % bytes;
if (buf < (METABLOCK_SIZE + 1024))
{
return (void *)(ptr + 1);
}
else
{
if (splitBigBlock(ptr, bytes) == INT_MIN)
{
return NULL;
}
else
{
return (void *)(ptr + 1);
}
}
}
else
{
bigBlockList.count += 1;
if (bigBlockList.count >= MAX_SIZE_FOR_BIG_BLOCK)
{
return NULL;
}
requirepages = 4 > ((bytes + METABLOCK_SIZE) / SYSTEM_PAGE_SIZE) ? 4 : ((bytes + METABLOCK_SIZE) / SYSTEM_PAGE_SIZE) + 1;
bigBlockList.bigBlock[bigBlockList.count].blockptr = (meta_data)mm_getnewvm(requirepages);
bigBlockList.bigBlock[bigBlockList.count].offset = 0;
bigBlockList.bigBlock[bigBlockList.count].availablesize = requirepages * SYSTEM_PAGE_SIZE - METABLOCK_SIZE;
meta_data temp, a;
temp = bigBlockList.bigBlock[bigBlockList.count].blockptr;
temp->blockSize = bytes;
temp->prev = NULL;
temp->next = (meta_data)((char *)temp + bytes + METABLOCK_SIZE);
temp->isFree = FALSE;
temp->head = temp;
bigBlockList.bigBlock[bigBlockList.count].availablesize -= (bytes + METABLOCK_SIZE);
bigBlockList.bigBlock[bigBlockList.count].offset = METABLOCK_SIZE + bytes;
a = temp->next;
a->prev = temp;
a->next = NULL;
a->blockSize = bigBlockList.bigBlock[bigBlockList.count].availablesize;
a->isFree = TRUE;
a->head = temp;
return (void *)(temp + 1);
}
}
int isBigBlockPageEmpty(meta_data head)
{
meta_data block = head;
while (block != NULL)
{
if (block->isFree == FALSE)
{
return FALSE;
}
block = block->next;
}
return TRUE;
}
void RemoveBigBlockPage(meta_data head)
{
int i = 0;
while (i < MAX_SIZE_FOR_BIG_BLOCK && head != bigBlockList.bigBlock[i].blockptr)
{
i++;
}
if (i == MAX_SIZE_FOR_BIG_BLOCK)
return;
big_block temp = bigBlockList.bigBlock[i];
bigBlockList.bigBlock[i] = bigBlockList.bigBlock[bigBlockList.count];
bigBlockList.bigBlock[bigBlockList.count].offset = 0;
bigBlockList.bigBlock[bigBlockList.count].availablesize = 0;
bigBlockList.bigBlock[bigBlockList.count].blockptr = NULL;
bigBlockList.count -= 1;
mm_returnvm(head, 4);
return;
}
|
C
|
// #############################################################################################
//
// Data taken from https://www.ticketcity.com/nba/nba-finals-tickets/nba-finals-champions.html
//
//
// This project explores whether the NBA Finals outcomes are consistent with two
// equally matched teams. The metric is the "number of games won by the loser".
//
// First, it calculates the "ideal" N_games_won_by_loser under the assumption that
// each team had a 50% chance to win each game. Incidentally, this "ideal" distribution
// can also be calculated analytically !
//
// Second, it runs toys to determine a compatibility distribution (in this case, chi2)
// when compared to the "ideal".
//
// Third, it calculates the actaul chi2 of the data compared to the "ideal".
//
// Finally, it calculates the p-value of getting the actual historical results.
//
// We compare the chi2 distribution to an ideal chisq distribution with the appropriate
// degrees of freedom. Moreover, the p-value is ~0.8, indicating that the NBA Finals outcomes
// (since 1947) are consistent with the teams being equally matched (ie. each team always has
// a 50% chance to win). We should note, however, that 70 years worth of data is actually
// pretty low statistics. In our N_games_won_by_loser distribution, there are 4 bins [0,1,2,3]
// and each bin has between 8 and 26 counts. The uncertainties are therefore quite large.
//
//
// run macro with ROOT by:
// $ root -l NBAFinalsOutcomes.C
//
// #############################################################################################
TH1D *h_winsloser;
TH1D *h_NULL;
TH1D *h_toys[10000];
TH2D *h2_toys;
TH1D *h_chisq;
TF1 *f_chisq;
double CalcChiSq(TH1D *h1, TH1D *h2, int firstBin, int lastBin);
int FindNGamesLoser(int nGamesToWin, double equality=0.5);
char saythis[500];
void NBAFinalsOutcomes()
{
h_winsloser = new TH1D("h_winsloser","h_winsloser",6,-0.5,5.5);
h_winsloser->SetTitle("metric");
h_winsloser->GetXaxis()->SetTitle("N_{wins} by losing team");
h_winsloser->GetYaxis()->SetTitle("N_{finals}");
h2_toys = new TH2D("h2_toys","h2_toys", 6,-0.5,5.5, 51,-0.5,50.5);
h2_toys->SetTitle("toy distributions");
h2_toys->GetXaxis()->SetTitle("N_{wins} by losing team");
h2_toys->GetYaxis()->SetTitle("N_{finals}");
h2_toys->GetZaxis()->SetTitle("N_{toys}");
h_chisq = new TH1D("h_chisq","h_chisq",200,0,40);
h_chisq->SetTitle("compatibility distribution");
h_chisq->GetXaxis()->SetTitle("#chi^{2}");
h_chisq->GetYaxis()->SetTitle("N_{toys}");
h_chisq->SetMarkerStyle(20);
h_chisq->SetMarkerSize (0.5);
int year[70] = {
2016,
2015,
2014,
2013,
2012,
2011,
2010,
2009,
2008,
2007,
2006,
2005,
2004,
2003,
2002,
2001,
2000,
1999,
1998,
1997,
1996,
1995,
1994,
1993,
1992,
1991,
1990,
1989,
1988,
1987,
1986,
1985,
1984,
1983,
1982,
1981,
1980,
1979,
1978,
1977,
1976,
1975,
1974,
1973,
1972,
1971,
1970,
1969,
1968,
1967,
1966,
1965,
1964,
1963,
1962,
1961,
1960,
1959,
1958,
1957,
1956,
1955,
1954,
1953,
1952,
1951,
1950,
1949,
1948,
1947
};
int WinsLoser[70] = {
3,
2,
1,
3,
1,
2,
3,
1,
2,
0,
2,
3,
1,
2,
0,
1,
2,
1,
2,
2,
2,
0,
3,
2,
2,
1,
1,
0,
3,
2,
2,
2,
3,
0,
2,
2,
2,
1,
3,
2,
2,
0,
3,
1,
1,
0,
3,
3,
2,
2,
3,
1,
1,
2,
3,
1,
3,
0,
2,
3,
1,
3,
3,
1,
3,
3,
2,
2,
2,
1
};
for(int i=0; i<70; i++){
h_winsloser->Fill(WinsLoser[i]);
}
h_NULL = (TH1D*)h_winsloser->Clone("h_NULL");
h_NULL->Reset();
//for(int i=1; i<5; i++){
// h_NULL->SetBinContent(i,70.0/4.0);
// h_NULL->SetBinError (i,0);
//}
for(int i=0; i<10000; i++)
h_NULL->Fill(FindNGamesLoser(4));
h_NULL->Sumw2();
h_NULL->Scale(70.0/h_NULL->GetEntries());
h_NULL->SetMarkerStyle(24);
h_NULL->SetMarkerColor(1);
h_NULL->SetLineColor (1);
h_winsloser->SetMarkerStyle(20);
h_winsloser->SetMarkerColor(2);
h_winsloser->SetLineColor (2);
TCanvas *c1 = new TCanvas("c1","c1");
h_winsloser->Draw("pe");
h_NULL ->Draw("pe,same");
TLegend *leg1 = new TLegend(0.5,0.2,0.89,0.4);
leg1->AddEntry(h_winsloser, "historical data","PL");
leg1->AddEntry(h_NULL , "ideal distribution (50% / 50%)","PL");
leg1->Draw();
double chisq_data = CalcChiSq(h_winsloser,h_NULL,1,4);
cout << "chisq/ndf = " << chisq_data << "/3 = " << chisq_data/3.0 << endl;
TCanvas *c2 = new TCanvas("c2","c2",1000,500);
c2->Divide(2,1);
if(1){//running toys...
for(int i=0; i<10000; i++){
sprintf(saythis,"h_toys_%d",i);
h_toys[i] = (TH1D*)h_NULL->Clone(saythis);
h_toys[i]->Reset();
for(int j=0; j<70; j++){
int jj = FindNGamesLoser(4);
h_toys[i]->Fill(jj);
}
for(int j=1; j<h_toys[i]->GetNbinsX()+1; j++)
h2_toys->Fill(h_toys[i]->GetBinCenter(j),h_toys[i]->GetBinContent(j));
h_chisq->Fill( CalcChiSq(h_toys[i],h_NULL,1,4) );
c2->cd(1);
if(i==0) h_toys[i]->Draw();
else h_toys[i]->Draw("same");
}
c2->cd(2);
h_chisq->Draw("pe");
}
c2->cd(1)->Clear();
h2_toys->Draw("colz");
c2->cd(2);
f_chisq = new TF1("f_chisq","[1]*(pow(x,[0]/2-1)*TMath::Exp(-x/2))/(pow(2,[0]/2)*TMath::Gamma([0]/2))",0,50);
f_chisq->SetParameter(1,1);
f_chisq->SetParameter(0,3);
f_chisq->SetParameter(1,h_chisq->Integral(-1,-1,"width")/f_chisq->Integral(0,50));
f_chisq->SetLineColor(8);
f_chisq->SetLineWidth(2);
f_chisq->SetLineStyle(2);
f_chisq->Draw("same");
TLine *linedata = new TLine(chisq_data,0,chisq_data,h_chisq->GetMaximum());
linedata->SetLineStyle(2);
linedata->SetLineWidth(2);
linedata->SetLineColor(2);
linedata->Draw("same");
TLegend *leg2 = new TLegend(0.5,0.5,0.89,0.7);
leg2->AddEntry(h_chisq, "toy distribution","PL");
leg2->AddEntry(f_chisq, "ideal #chi^{2}, ndf = 3","L");
leg2->AddEntry(linedata,"#chi^{2} of data","L");
leg2->Draw();
cout << "p-value = " << h_chisq->Integral(h_chisq->GetXaxis()->FindBin(chisq_data)+1,-1)/h_chisq->Integral(-1,-1) << endl;
}
double CalcChiSq(TH1D *h1, TH1D *h2, int firstBin, int lastBin)
{
double chisq = 0.0;
double delta = 0.0;
double errsq = 0.0;
if(h1->GetNbinsX() != h2->GetNbinsX()){
cout << "JJ::CalcChiSq() --> histograms don't have same number of bins !!" << endl;
return 0;
}
if(firstBin<0)
firstBin=1;
if(lastBin<0)
lastBin=h1->GetNbinsX();
for(int i=firstBin; i<lastBin+1; i++){
double h1cont = h1->GetBinContent(i);
double h2cont = h2->GetBinContent(i);
double h1err = h1->GetBinError (i);
double h2err = h2->GetBinError (i);
if(h1cont !=0 && h2cont !=0){
delta = (h1cont-h2cont);
errsq = h1err*h1err + h2err*h2err;
chisq += delta*delta/errsq;
}
}
return chisq;
}
int FindNGamesLoser(int nGamesToWin, double equality=0.5)
{
int nGamesLoser = 0;
int nGamesT1 = 0;
int nGamesT2 = 0;
TRandom randTemp;
randTemp.SetSeed(0);
while(nGamesT1<nGamesToWin && nGamesT2<nGamesToWin){
if(randTemp.Rndm()>equality)
nGamesT1++;
else
nGamesT2++;
}
if(nGamesT1==nGamesToWin)
nGamesLoser = nGamesT2;
else
nGamesLoser = nGamesT1;
return nGamesLoser;
}
|
C
|
#pragma once
#include<iostream>
struct ArrayList {
/* */
int count;
int capacity;
int* data;
/* */
ArrayList(); //
ArrayList(int cap); //
/* */
~ArrayList();
void push_back(int element); //
void print(); //
};
|
C
|
#include <stdlib.h>
#include <assert.h>
/*
Doubly linked list
*/
typedef struct llnode {
struct llnode * left;
struct llnode * right;
void* value;
} llnode;
typedef struct linkedlist {
llnode * left;
llnode * right;
int count;
} linkedlist;
linkedlist * ll_ctor() {
linkedlist * ll = malloc(sizeof(linkedlist));
*ll = (linkedlist) {
.left = NULL,
.right = NULL,
.count = 0
};
return ll;
}
void ll_free(linkedlist * ll) {
llnode * node = ll->left;
while (node != NULL) {
if (node->value) free(node->value);
llnode * next = node->right;
free(node);
node = next;
}
free(ll);
}
void ll_addright(linkedlist * ll, void * value) {
assert(ll != NULL);
assert(value != NULL);
llnode * node = malloc(sizeof(llnode));
*node = (llnode) {.left = ll->right, .right = NULL, .value = value};
if (ll->right != NULL) {
ll->right->right = node;
}
ll->right = node;
if (ll->left == NULL){
ll->left = ll->right;
}
ll->count++;
}
void ll_addleft(linkedlist * ll, void * value) {
assert(ll != NULL);
assert(value != NULL);
llnode * node = malloc(sizeof(llnode));
*node = (llnode) {.left = NULL, .right = ll->left, .value = value};
if (ll->left != NULL) {
ll->left->left = node;
}
ll->left = node;
if (ll->right == NULL){
ll->right = ll->left;
}
ll->count++;
}
void * ll_popright(linkedlist * ll) {
if (ll->right == NULL) return NULL;
llnode * node = ll->right;
if (node->left) {
ll->right = node->left;
node->left->right = NULL;
node->left = NULL;
}
else {
assert(ll->left == node);
ll->right = NULL;
ll->left = NULL;
}
void * value = node->value;
free(node);
return value;
}
void * ll_popleft(linkedlist * ll) {
if (ll->left == NULL) return NULL;
llnode * node = ll->left;
if (node->right) {
ll->left = node->right;
node->right->left = NULL;
node->right = NULL;
}
else {
assert(ll->right == node);
ll->left = NULL;
ll->right = NULL;
}
void * value = node->value;
free(node);
return value;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef scalar_t__ u_int8_t ;
struct ata_security_password {int ctrl; int /*<<< orphan*/ password; } ;
struct ata_cmd {scalar_t__ command; } ;
typedef int /*<<< orphan*/ cmd ;
/* Variables and functions */
int ATA_SECURITY_LEVEL_MAXIMUM ;
int ATA_SECURITY_PASSWORD_MASTER ;
scalar_t__ ATA_SECURITY_SET_PASSWORD ;
char* ata_op_string (struct ata_cmd*) ;
int /*<<< orphan*/ bzero (struct ata_cmd*,int) ;
int /*<<< orphan*/ printf (char*,...) ;
int /*<<< orphan*/ strncpy (char*,int /*<<< orphan*/ ,int) ;
__attribute__((used)) static void
atasecurity_notify(u_int8_t command, struct ata_security_password *pwd)
{
struct ata_cmd cmd;
bzero(&cmd, sizeof(cmd));
cmd.command = command;
printf("Issuing %s", ata_op_string(&cmd));
if (pwd != NULL) {
char pass[sizeof(pwd->password)+1];
/* pwd->password may not be null terminated */
pass[sizeof(pwd->password)] = '\0';
strncpy(pass, pwd->password, sizeof(pwd->password));
printf(" password='%s', user='%s'",
pass,
(pwd->ctrl & ATA_SECURITY_PASSWORD_MASTER) ?
"master" : "user");
if (command == ATA_SECURITY_SET_PASSWORD) {
printf(", mode='%s'",
(pwd->ctrl & ATA_SECURITY_LEVEL_MAXIMUM) ?
"maximum" : "high");
}
}
printf("\n");
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* client_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mmonarch <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/06 13:57:49 by mmonarch #+# #+# */
/* Updated: 2021/11/06 13:57:53 by mmonarch ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/minitalk.h"
void ft_send_str(int pid, char *str)
{
int bit;
char symbol;
while (*str)
{
bit = -1;
symbol = *str++;
while (++bit < 8)
{
if ((symbol >> bit) & 1)
kill(pid, SIGUSR1);
else
kill(pid, SIGUSR2);
usleep(150);
}
usleep(150);
}
}
void ft_send_finish(int pid)
{
int bit;
bit = -1;
while (++bit < 8)
{
kill(pid, SIGUSR2);
usleep(150);
}
}
static void ft_handler(int signal)
{
static int counter = 0;
if (signal == SIGUSR1)
counter++;
else
{
ft_putstr("Сharacters received: ");
ft_putnbr(counter);
ft_putchar('\n');
exit(0);
}
}
int main(int argc, char **argv)
{
struct sigaction sig;
int pid;
char *str;
if (argc != 3 || !argv[2])
{
ft_putendl_fd("Don't right arguments. Need PID and \"string\"", 2);
return (1);
}
pid = ft_atoi(argv[1]);
str = argv[2];
ft_putstr("Сharacters sent: ");
ft_putnbr(ft_strlen(str) + 1);
ft_putchar('\n');
sig.sa_handler = ft_handler;
sig.sa_flags = 0;
sigaction(SIGUSR1, &sig, NULL);
sigaction(SIGUSR2, &sig, NULL);
ft_send_str(pid, str);
ft_send_str(pid, "\n");
ft_send_finish(pid);
while (1)
usleep(150);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#include<math.h>
//Function for selection of random number n
int selectn(){
int i;
i= rand() % 9;
if(i<4){
return (i+4);
}
return i;
}
int randomprofit(){ //Function to create randomised profits between 10-30
//Use current time as seed for random generator
int i;
//srand(56);
i= rand() % 31;
if(i<10){
return (i+11);
}
return i;
}
int randomweight(){//Function to create randomised weights between 5-20
//Use current time as seed for random generator
int i;
//srand(32);
i= rand() % 21;
if(i<5){
return (i+7);
}
return i;
}
//Create structure for list of items
struct list_of_items {
char name[7];
int profit_pi;
int weight_wi;
};
int main(int argc, char *argv[]){
if(argc!=3){
printf("Invalid Arguments: Syntax is './createkn01 -k knapsack01.txt' \n");
return -1;
}
//Set seed for random number generator
srand(time(0));
//Get randomised n
int n= selectn();
struct list_of_items items[n];
int i=0;
int wcapacity = 0;
for(i=0;i<n;i++){
char buf[7];
//Give names to each element we create item0, item1, etc
snprintf(buf, 7, "item%d", i);
strcpy(items[i].name,buf);
items[i].profit_pi = randomprofit();
items[i].weight_wi = randomweight();
wcapacity += items[i].weight_wi;
}
//Calculate capacity of the weight
wcapacity = 0.6 * wcapacity;
wcapacity = floor(wcapacity);
char * filename = argv[2];
FILE* file = fopen(filename, "w");
//Write the data to file
fprintf(file,"%d %d\n",n,wcapacity);
for(i=0;i<n;i++){
fprintf(file,"%s %d %d\n",items[i].name,items[i].profit_pi,items[i].weight_wi);
}
fclose(file);
return 0;
}
|
C
|
/*
* PRACTICA 1 - EJERCICIO 2
* Realiza un programa que escriba en pantalla las constantes ‘A’, 3 y 3.3 como datos de
* tipo char, int y float respectivamente.
*/
#include <stdio.h>
int main()
{
#define A 'A'
#define tres 3
#define tres_con_tres 3.3
printf("%c %d %0.1f", A, tres, tres_con_tres);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
#define ITEM_MAX 10
#define THREAD_SIZE 5
sem_t Empty_check; //생산자의 세마포어
sem_t Item_exist; //소비자의 세마포어
sem_t mutex; //상호 배재를 위한 선언
int count = 0; //공유 변수
int ItemList[ITEM_MAX]; //Item 목록
int in = 0; //생산
int out = 0; //소비
void *Producer(void * i)
{
int producer = *(int *)i + 1;
while(1)
{
sem_wait(&Empty_check); //List 채우기 시작 , 다른 프로세스 접근 차단
sem_wait(&mutex); //binary semaphore
ItemList[in] = in+1; //1~10 으로 표현하기 위해서
printf("[%d]producer produce %d \n",producer,ItemList[in]);
in = (in+1) % ITEM_MAX; //in 증가
sem_post(&mutex); //다른 생산자가 임계영역 사용 가능
sem_post(&Item_exist); //생산을 끝냈으므로 item 공간 증가
sleep(1); //context switching time 확보
}
}
void *Consumer(void * i)
{
int consumer = *(int *)i + 1;
while(1)
{
sem_wait(&Item_exist); //Item 소비
sem_wait(&mutex);
int item = ItemList[out];
printf("[%d]consumer consume : %d\n",consumer,item );
out =(out + 1) % ITEM_MAX; //out 증가
sem_post(&mutex);
sem_post(&Empty_check); //소비를 끝냈으니 빈공간 증가
sleep(1); //context switching time 확보
}
}
int main()
{
pthread_t pthread[THREAD_SIZE];
pthread_t cthread[THREAD_SIZE];
pthread_attr_t attr;
int i;
int pi;
if(sem_init(&Empty_check,0,ITEM_MAX)==-1) { //생산자 세마포어, 생성해야하므로 ITEM_MAX로 초기화
printf("semaphore init error!\n");
exit(-1);
}
if(sem_init(&Item_exist,0,0)==-1) //소비자 세마포어,처음부터 소비가능하지 않음으로 0으로 초기화
{
printf("semaphore init error!\n");
exit(-1);
}
if(sem_init(&mutex,0,1)==-1) //상호배재를 위한 binary semaphore
{
printf("semaphore init error!\n");
exit(-1);
}
if(pthread_attr_init(&attr)==-1)
{
printf("attr_init error!!\n");
exit(-1);
}
for(pi = 0; pi<1;pi++)
{
if(pthread_create(&pthread[pi],&attr,Producer,(void*)&i)!=0) //생산자 생성
{
printf("pthread_create error!!\n");
exit(-1);
}
sleep(1); //인자 전달 시간 확보
}
for(i =0;i<3;i++)
{
if(pthread_create(&cthread[i],&attr,Consumer,(void*)&i)!=0) //소비자 생성
{
printf("pthread_create error!!\n");
exit(-1);
}
sleep(1); //인자 전달 시간 확보
}
for(pi=0;pi<1;pi++)
{
if(pthread_join(pthread[i],NULL)!=0)
{
printf("pthread_join error!!\n");
exit(-1);
}
}
for (i = 0; i < 3; i++)
{
if(pthread_join(cthread[i],NULL)!=0)
{
printf("pthread_join error!!\n");
exit(-1);
}
}
sem_destroy(&Empty_check);
sem_destroy(&Item_exist);
sem_destroy(&mutex);
pthread_exit(NULL);
return 0;
}
|
C
|
//#include "unistd.h"
#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"
//#include "stdlib.h"
char buf[502];
int
main(int argc, char *argv[]){
if(argc <= 1){
printf(1, "touch: missing file operand\n");
exit();
}
int ret =chdir(argv[1]);
if(ret==0){
printf(1,"fail to access %s\n", argv[1]);
printf(1, "the current directory now is %s\n", argv[1]);
exit();
}
else{
printf(1, "the current directory now is %s\n", argv[1]);
}
exit();
}
|
C
|
#include <cholmod.h>
#include <math.h>
#include <assert.h>
#include "photospline/detail/splineutil.h"
int
ndsparse_allocate(struct ndsparse* s, size_t rows, size_t ndim)
{
s->rows = rows;
s->ndim = ndim;
s->i = calloc(ndim, sizeof(int*));
if (!s->i)
return (1);
s->ranges = calloc(ndim, sizeof(int));
if (!s->ranges) {
free(s->i);
return (1);
}
s->x = calloc(rows, sizeof(double));
if (!s->x) {
free(s->i);
free(s->ranges);
return (1);
}
for (size_t i=0; i<ndim; i++) {
s->i[i] = calloc(rows, sizeof(int));
if (!s->i[i]) {
free(s->x);
free(s->ranges);
for (size_t j=0; j<i; j++)
free(s->i[j]);
free(s->i);
return(1);
}
}
return (0);
}
void
ndsparse_free(struct ndsparse* s)
{
free(s->x);
free(s->ranges);
for (size_t i=0; i<s->ndim; i++)
free(s->i[i]);
free(s->i);
}
cholmod_sparse *
cholmod_tril(int dim, cholmod_common *c)
{
cholmod_dense *dtril;
cholmod_sparse *stril;
int row, col;
dtril = cholmod_l_zeros(dim, dim, CHOLMOD_REAL, c);
/* CHOLMOD dense matrices are in column-major order */
for (col = 0; col < dim; col++) for (row = col; row < dim; row++)
((double *)(dtril->x))[col*dim + row] = 1;
stril = cholmod_l_dense_to_sparse(dtril, 1, c);
cholmod_l_free_dense(&dtril, c);
return (stril);
}
static double
bspline(const double *knots, double x, int i, int n)
{
double result;
if (n == 0) {
/*
* Special case the 0th order case, where B-Splines
* are constant functions from one knot to the next.
*/
if (x >= knots[i] && x < knots[i+1])
return 1.0;
else
return 0.0;
}
result = (x - knots[i])*bspline(knots, x, i, n-1) /
(knots[i+n] - knots[i]);
result += (knots[i+n+1] - x)*bspline(knots, x, i+1, n-1) /
(knots[i+n+1] - knots[i+1]);
return result;
}
cholmod_sparse*
bsplinebasis(const double* knots, size_t nknots, const double* x, size_t npts, int order,
cholmod_common* c)
{
cholmod_dense* basis;
cholmod_sparse* sbasis;
size_t nsplines;
int row,col,k;
/*
* This matrix has npts rows and nknots-order-1 columns, with order+1
* maximum non-zero elements per row (basis functions have limited
* extent).
*
* XXX: We could do this more efficiently by filling a triplet matrix,
* but this has little effect on total execution time.
*/
nsplines = nknots-order-1;
basis = cholmod_l_allocate_dense(npts, nsplines, npts, CHOLMOD_REAL, c);
/* CHOLMOD dense matrices are in column-major order */
k = 0;
for (col = 0; col < nsplines; col++)
for (row = 0; row < npts; row++, k++)
((double *)(basis->x))[k] = bspline(knots, x[row],
col, order);
sbasis = cholmod_l_dense_to_sparse(basis, 1, c);
cholmod_l_free_dense(&basis, c);
return (sbasis);
}
/*
* slicemultiply() multiplies an n-dimensional array by a sparse matrix along
* the axis specified by dim, returning the result in the original array. It
* is equivalent to glam.rho() in the Python implementation, and the
* function 'rho' defined by Eilers and Currie.
*
* If you want to understand how it works, look at the Python implementation.
*/
int
slicemultiply(struct ndsparse *a, cholmod_sparse *b, int dim,
cholmod_common *c)
{
cholmod_triplet *section;
cholmod_sparse *ssection;
int cols, i, j, k, stride;
/* Check that the dimensions match */
if (b->nrow != a->ranges[dim])
return -1;
/*
* Construct a matrix with a->ranges[dim] rows based on flattening a
* transposed version of a.
*
* Since we are just shuffling things about, the max number of
* non-zero elements is just the number of elements in a.
*/
cols = 1;
for (i = 0; i < a->ndim; i++)
if (i != dim) cols *= a->ranges[i];
section = cholmod_l_allocate_triplet(a->ranges[dim], cols, a->rows, 0,
CHOLMOD_REAL,c);
section->nnz = a->rows;
/* We rotate the array so that dim is at the front, then flatten. */
assert(a->ndim>0);
for (i = 0; i < a->rows; i++) {
/* The flattened row number is straightforward: it is
* the dim'th coordinate. */
((long *)(section->i))[i] = a->i[dim][i];
/* The fastest running index is the dimension we are looking at.
* The next fastest is that the one that came after that, in a
* modular fashion. For non-primary (dim) indices, build up
* an aggregate range step.
*/
stride = 1;
((long *)(section->j))[i] = 0;
for (k = dim + a->ndim - 1; k > dim; k--) {
((long *)(section->j))[i] += stride*a->i[k % a->ndim][i];
stride *= a->ranges[k % a->ndim];
}
/* Copy the data */
((double *)(section->x))[i] = a->x[i];
}
/* Now obtain the sparse representation */
ssection = cholmod_l_triplet_to_sparse(section, 0, c);
if (c->status != CHOLMOD_OK) {
return(-1);
}
cholmod_l_free_triplet(§ion, c);
/* Compute bT . ssection, putting the result in ssection */
{
cholmod_sparse *bt, *bta;
bt = cholmod_l_transpose(b,1,c);
bta = cholmod_l_ssmult(bt,ssection,0 /*assymmetric */,
1 /* compute values */, 0 /* don't bother sorting */,c);
cholmod_l_free_sparse(&bt,c);
cholmod_l_free_sparse(&ssection,c);
ssection = bta;
}
/* Now we need to undo the rotation and flattening from above */
section = cholmod_l_sparse_to_triplet(ssection,c);
cholmod_l_free_sparse(&ssection,c);
/* Set up the nd-array again, bearing in mind that it need not have
* the same number of non-zero elements as before, and that the range
* along dimension dim is also now the number of columns in b */
for (i = 0; i < a->ndim; i++)
a->i[i] = realloc(a->i[i],sizeof(int)*section->nnz);
a->x = realloc(a->x,sizeof(double)*section->nnz);
a->rows = section->nnz;
a->ranges[dim] = b->ncol;
/* We unflatten the array and rotate so that the front is at dim */
for (i = 0; i < a->rows; i++) {
/* The flattened column number is straightforward: it is
* the dim'th coordinate. */
a->i[dim][i] = ((long *)(section->i))[i];
/* The fastest running index is the dimension we are looking at.
* The next fastest is that the one that came after that, in a
* modular fashion. For non-primary (dim) indices, build up
* an aggregate range step.
*/
stride = 1;
for (k = dim + a->ndim - 1; k > dim; k--)
stride *= a->ranges[k % a->ndim];
j = ((long *)(section->j))[i];
for (k = dim+1; k < dim + a->ndim; k++) {
/* See how many of this dimension's strides we fit */
stride /= a->ranges[k % a->ndim];
a->i[k % a->ndim][i] = j/stride;
/* Collect the remainder */
j = j % stride;
}
/* Copy the data */
a->x[i] = ((double *)(section->x))[i];
}
cholmod_l_free_triplet(§ion,c);
return 0;
}
/* Computes the kronecker product of sparse matrices a and b */
cholmod_sparse *
kronecker_product(cholmod_sparse *a, cholmod_sparse *b, cholmod_common *c)
{
cholmod_sparse *final;
cholmod_triplet *ta, *tb, *tf;
int i, j;
ta = cholmod_l_sparse_to_triplet(a,c);
tb = cholmod_l_sparse_to_triplet(b,c);
tf = cholmod_l_allocate_triplet(ta->nrow*tb->nrow, ta->ncol*tb->ncol,
ta->nnz*tb->nnz, (ta->stype == tb->stype) ? ta->stype : 0,
CHOLMOD_REAL, c);
tf->nnz = ta->nnz*tb->nnz;
for (i = 0; i < ta->nnz; i++) {
for (j = 0; j < tb->nnz; j++) {
/* New data is x_a*x_b */
((double *)(tf->x))[i*tb->nnz + j] = ((double *)(ta->x))[i]
* ((double *)(tb->x))[j];
/* New column index is col_a*ncol_b + col_b */
((long *)(tf->j))[i*tb->nnz + j] = ((long *)(ta->j))[i]*tb->ncol
+ ((long *)(tb->j))[j];
/* New row index is row_a*nrow_b + row_b */
((long *)(tf->i))[i*tb->nnz + j] = ((long *)(ta->i))[i]*tb->nrow
+ ((long *)(tb->i))[j];
}
}
final = cholmod_l_triplet_to_sparse(tf, 0, c);
cholmod_l_free_triplet(&ta,c);
cholmod_l_free_triplet(&tb,c);
cholmod_l_free_triplet(&tf,c);
return final;
}
/*
* box is implemented as follows in python:
* def box(A,B):
* ea = numpy.ones((1,A.shape[1]),float)
* eb = numpy.ones((1,B.shape[1]),float)
* return numpy.matrix(numpy.asarray(numpy.kron(A, eb)) * \
* numpy.asarray(numpy.kron(ea, B)))
*
* What it does is form a new matrix with the same number of rows as A and B,
* where each element is the row is the product of an element of A and the
* corresponding row of B. For example:
*
* [ A_00*B_00 A_00*B_01 A_00*B_02 A_01*B_00 A_01*B_01 ... ]
* [ A_10*B_10 A_10*B_11 ... ]
*/
cholmod_sparse *
box(cholmod_sparse *a, cholmod_sparse *b, cholmod_common *c)
{
cholmod_sparse *final;
cholmod_triplet *ta, *tb, *tf;
int i, rownum;
struct rowitem {
long col;
double val;
struct rowitem *next;
};
struct rowitem **brows, **curbrows;
struct rowitem *item;
/* We need the number of rows in both matrices to be equal */
if (a->nrow != b->nrow)
return NULL;
ta = cholmod_l_sparse_to_triplet(a,c);
tb = cholmod_l_sparse_to_triplet(b,c);
/*
* The number of non-zero entries cannot be larger than the number
* of nonzero entries in a times the length of a row in b
*/
tf = cholmod_l_allocate_triplet(ta->nrow, ta->ncol*tb->ncol,
ta->nnz*tb->ncol, 0, CHOLMOD_REAL, c);
tf->nnz = 0;
/* Decompose b into its (sparse) rows */
brows = calloc(tb->nrow,sizeof(struct rowitem *));
curbrows = calloc(tb->nrow,sizeof(struct rowitem *)); /* fast lookup for list end*/
for (i = 0; i < tb->nnz; i++) {
rownum = ((long *)(tb->i))[i];
item = malloc(sizeof(struct rowitem));
item->next = NULL;
item->col = ((long *)(tb->j))[i];
item->val = ((double *)(tb->x))[i];
if (brows[rownum] == NULL)
brows[rownum] = item;
else
curbrows[rownum]->next = item;
curbrows[rownum] = item;
}
/* Free curbrows now that we are done with it */
free(curbrows);
for (i = 0; i < ta->nnz; i++) {
rownum = ((long *)(ta->i))[i];
for (item = brows[rownum]; item != NULL; item = item->next) {
((long *)(tf->i))[tf->nnz] = rownum;
((long *)(tf->j))[tf->nnz] = ((long *)(ta->j))[i]*tb->ncol +
item->col;
((double *)(tf->x))[tf->nnz] = ((double *)(ta->x))[i] * item->val;
tf->nnz++;
}
}
/* Free all the row items */
for (i = 0; i < tb->nrow; i++) {
struct rowitem *tmp;
item = brows[i];
while (item != NULL) {
tmp = item;
item = item->next;
free(tmp);
}
}
free(brows);
final = cholmod_l_triplet_to_sparse(tf, 0, c);
/* clean up */
cholmod_l_free_triplet(&ta, c);
cholmod_l_free_triplet(&tb, c);
cholmod_l_free_triplet(&tf, c);
return (final);
}
void
print_sparse(cholmod_sparse *a, cholmod_common *c)
{
cholmod_dense *dense;
int i,j;
double val;
dense = cholmod_l_sparse_to_dense(a,c);
printf("----\n");
for (i = 0; i < dense->nrow; i++) {
for (j = 0; j < dense->ncol; j++) {
val = ((double *)(dense->x))[j*dense->nrow + i];
if (fabs(val) <= 1e-12) {
printf(" - ");
} else {
printf(" %- .1e",val);
}
}
printf("\n");
}
printf("----\n");
cholmod_l_free_dense(&dense,c);
}
void
print_factor(cholmod_factor *L, cholmod_common *c)
{
cholmod_sparse *Lsparse;
cholmod_factor *Lcopy;
cholmod_dense *Ldense;
int i, j;
double val;
Lcopy = cholmod_l_copy_factor(L, c);
Lsparse = cholmod_l_factor_to_sparse(Lcopy, c);
Ldense = cholmod_l_sparse_to_dense(Lsparse, c);
printf("----\n");
for (i = 0; i < Ldense->nrow; i++) {
for (j = 0; j < i+1; j++) {
val = ((double*)(Ldense->x))[j*(Ldense->nrow)+i];
if (i >= j) {
if (val == 0) printf(" - ");
else if (val == 1) printf(" %d ",
(int)val);
else printf(" % -.1e",val);
} else {
printf(" ");
}
}
printf("\n");
}
printf("----\n");
cholmod_l_free_factor(&Lcopy, c);
cholmod_l_free_dense(&Ldense, c);
cholmod_l_free_sparse(&Lsparse, c);
}
|
C
|
#include<stdio.h>
int main()
{
int rupee,i;
double money,dob=100.0,paisa;
scanf("%lf",&money);
rupee=(int)money;
//paisa=(int)((double)(money-rupee)*100);
paisa=money-rupee;
if(((int)money)%2!=0 && ((int)money)%5!=0 )
paisa+=100;
printf("NOTAS:\n");
for(i=100; ;i/=2)
{
if(i>1){
printf("%d nota(s) de R$ %d.00\n",rupee/i,i);
rupee%=i;
if(i==50)
i-=10;
if(i==25)
i-=5;
}
else{
printf("%d MOEDA(s) de %0.2lf\n",(int)(paisa/dob),dob);
paisa=paisa-(paisa/dob);
dob/=2;
if(dob==0)
break;
}
//if(i<2)
}
printf("%lf",0.50/0.25);
/* printf("MOEDAS\n");
for(i=100;i>0;i/=2)
{
if(i=)
printf("%d moeda(s) de R$ %d\n",i,paisa/i);
paisa%=i;
if(i==25)
i-=5;
if(i==5)
i-=4;
}*/
return 0;
}
|
C
|
// Juliet CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_fixed_string_05.c
// Original structure: conditional-mem-leak
// #################################################################
// ## Variant: conditional-mem-leak_01
// ## CHANGE: Made global variable `const`
// #################################################################
#include <stdlib.h>
// CHANGE: Made global variable constant.
static const int staticTrue = 1;
int main(void)
{
char * data = (char *)malloc(10*sizeof(char));
if(staticTrue)
{
free(data);
}
// Tool C FP: none
// Tool B FP: none
// Tool A FP: none
// Note: Adding a return statement here causes the Tool A FP to go away.
}
|
C
|
#include "defs.h"
#define NITERMAX 30
/* Exact solver functions */
real fk_prime(const real p, const real pk, const real dk, const real ak, const real Ak, const real Bk, const real gamma_5) {
if (p > pk) {
return ( 1 - .5*(p-pk)/(Bk+p) ) * sqrt(Ak/(p+Bk));
}
else {
return 1./(ak*dk) * pow(p/pk,-gamma_5);
}
}
real fk(const real p, const real pk, const real ak, const real Ak, const real Bk, const real gamma_1,const real gamma_2) {
if (p > pk) {
return (p-pk)*sqrt(Ak/(p+Bk));
}
else {
return 2*ak/gamma_1 *( pow(p/pk,gamma_2) - 1.);
}
}
int exact_star_region(const real *WL, const real *WR, real g, real *ps, real *us, real tol) {
/* Exact Riemann solver */
int niter;
real pstar, ustar;
real dL = WL[0];
real uL = WL[1];
real pL = WL[2];
real aL = sqrt(g*pL/dL);
real dR = WR[0];
real uR = WR[1];
real pR = WR[2];
real aR = sqrt(g*pR/dR);
real du = uR - uL;
real gamma_1 = g-1;
real gamma_2 = gamma_1/(2*g);
real gamma_3 = gamma_1/(g+1);
real gamma_4 = 2./(g+1);
real gamma_5 = gamma_2/gamma_3;
/* Use ANRS for initial guess */
real Al = gamma_4 / dL;
real Ar = gamma_4 / dR;
real Bl = gamma_3 * pL;
real Br = gamma_3 * pR;
/* Newton-Raphson iteration to convergence */
real pold;
// pold = .5*(pL + pR);
anrs(WL,WR,aL,aR,g,&pold,&ustar,gamma_1,gamma_2,gamma_3,gamma_4);
//printf("Guessing %.3e\n",pold);
real resid = 1.0;
niter = 0;
real fR,fL,dfR,dfL;
while ((resid > tol)&&(niter < NITERMAX)) {
fR = fk(pold,pR,aR, Ar,Br,gamma_1,gamma_2);
fL = fk(pold,pL,aL, Al,Bl,gamma_1,gamma_2);
dfR = fk_prime(pold,pR,dR,aR,Ar,Br,gamma_5);
dfL = fk_prime(pold,pL,dL,aL,Al,Bl,gamma_5);
pstar = pold - (fL+fR + du)/(dfL+dfR);
pstar = fmax(pstar,tol);
resid = fabs(pstar-pold)*2/(pold+pstar);
niter += 1;
pold = pstar;
}
*us = .5*(uL + uR+ fR-fL);
*ps = pstar;
return niter;
}
int exact_sample(const real *WL, const real *WR, const real ps, const real us, real *W, real g, real S, real tol) {
/* Full solution to the Riemann problem with exact solver at x/t
* includes support for vacuum.
*/
/* Sample solution for left and right density in star region */
real dL = WL[0];
real uL = WL[1];
real pL = WL[2];
real aL = sqrt(g*pL/dL);
real dR = WR[0];
real uR = WR[1];
real pR = WR[2];
real aR = sqrt(g*pR/dR);
real gp = (g+1)/(2*g);
real gm = (g-1)/(2*g);
real g3 = (g-1)/(g+1);
real d_f, u_f, p_f;
real SL,SHL,STL,SR, SHR, STR;
pL = fmax(pL,PRESSUREFLOOR);
pR = fmax(pR,PRESSUREFLOOR);
/* Left and right stats are not vacuum */
aL = sqrt(g*pL/dL);
aR = sqrt(g*pR/dR);
if (S < us) {
// Left of contact
if (ps > pL) {
// Shock
SL = uL - aL*sqrt( gp * ps/pL + gm);
if (S <= SL) {
u_f = uL;
p_f = pL;
d_f = dL;
}
else {
u_f = us;
p_f = ps;
d_f = dL*(ps/pL +g3)/(g3*ps/pL+1);
}
}
else {
// Rarefaction
SHL = uL - aL;
STL = us - aL* pow(ps/pL,gm);
if (S <= SHL) {
u_f = uL;
p_f = pL;
d_f = dL;
}
else {
if (S <= STL) {
u_f = 2./(g+1) *(aL + (g-1)*uL/2. + S);
d_f = dL*pow(2./(g+1) + (g-1)*(uL-S)/(aL*(g+1)),2./(g-1));
p_f = pL*pow(2./(g+1) + (uL-S)*(g-1)/(aL*(g+1)),1/gm);
}
else {
u_f = us;
p_f = ps;
d_f = dL *pow(ps/pL,1./g);
}
}
}
}
else {
if (ps > pR) {
SR = uR + aR*sqrt( gp *ps/pR + gm);
if (S<=SR) {
p_f = ps;
u_f = us;
d_f = dR*(ps/pR + g3)/(g3 *ps/pR+1);
}
else {
p_f = pR;
d_f = dR;
u_f = uR;
}
}
else {
SHR = uR + aR;
STR = us + aR* pow(ps/pR,gm);
if (S <= STR) {
u_f = us;
p_f = ps;
d_f = dR * pow(ps/pR,1./g);
}
else {
if (S <= SHR) {
u_f = 2./(g+1) *(-aR + (g-1)*uR/2. + S);
p_f = pR*pow(2./(g+1) - g3 *(uR-S)/aR , 1./gm);
d_f = dR*pow( 2./(g+1) - g3*(uR-S)/aR, 2./(g-1));
}
else {
u_f = uR;
p_f = pR;
d_f = dR;
}
}
}
}
/* Done */
W[0] = d_f;
W[1] = u_f;
W[2] = p_f;
/* For passive scalars and normal velocities
* we return whether or not to take
* the left or right state
* True = left
* False = right
*/
return (us >= S);
}
void exact_flux(const real *UL, const real *UR, real *F,real g, real g1, int nf) {
/* Flux using exact riemann solver.
* U = (rho, rho*u, rho*v, rho*w, E, rho*si)
* F = (rho*u, rho*u*u+p, rho*u*v, rho*u*w,u*(E+p), rho*u*si)
* G = (rho*v, rho*u*v, rho*v*v+p, rho*v*w,u*(E+p), rho*v*si)
* H = (rho*w, rho*u*w, rho*v*w, rho*w*w+p, rho*w*w,w*(E+p), rho*w*si)
*/
/* Flux using HLL scheme */
int n;
real WL[3], WR[3];
real WS[3] = {0,0,0};
real ps, us, ds;
real SL, SR, rhoL,uL,pL, eL,aL,uL2,uL3;
real rhoR,uR,pR,eR,aR,uR2,uR3;
rhoL = UL[0];
uL = UL[1]/rhoL;
uL2 = UL[2]/rhoL;
uL3 = UL[3]/rhoL;
eL = UL[4];
pL = (eL - .5*(uL*uL + uL2*uL2 + uL3*uL3)*rhoL)*g1;
rhoR = UR[0];
uR = UR[1]/rhoR;
uR2 = UR[2]/rhoR;
uR3 = UR[3]/rhoR;
eR = UR[4];
pR = (eR - .5*(uR*uR + uR2*uR2 + uR3*uR3)*rhoR)*g1;
pL = fmax(pL,PRESSUREFLOOR);
pR = fmax(pR,PRESSUREFLOOR);
WL[0] = rhoL; WL[1] = uL; WL[2] = pL;
WR[0] = rhoR; WR[1] = uR; WR[2] = pR;
exact_star_region(WL,WR,g,&ps,&us,1e-6);
int use_left = exact_sample(WL,WR,ps,us,WS,g,0.,1e-6);
ds = WS[0];
us = WS[1];
ps = WS[2];
F[0] = ds*us;
F[1] = ds*us*us + ps;
if (use_left) {
F[2] = ds*us*uL2 ;
F[3] = ds*us*uL3 ;
F[4] = us*( ps/g1 + .5*ds*(us*us + uL2*uL2 + uL2*uL2) + ps);
for(n=5;n<nf;n++) {
F[n] = ds*us*UL[n]/rhoL;
}
}
else {
F[2] = ds*us*uR2 ;
F[3] = ds*us*uR3 ;
F[4] = us*( ps/g1 + .5*ds*(us*us + uR2*uR2 + uR3*uR3) + ps);
for(n=5;n<nf;n++) {
F[n] = ds*us*UR[n]/rhoR;
}
}
return;
}
|
C
|
#include "CacheManager.h"
#include "FileSystem.h"
#include "DynamicMemory.h"
// 파일 시스템 캐시 자료구조
static CACHEMANAGER gs_stCacheManager;
// 내부 함수
static void kCutDownAccessTime(int iCacheTableIndex);
// 파일 시스템 캐시를 초기화
BOOL kInitializeCacheManager(void)
{
int i;
// 자료구조 초기화
kMemSet(&gs_stCacheManager,0,sizeof(gs_stCacheManager));
// 접근 시간 초기화
gs_stCacheManager.vdwAccessTime[CACHE_CLUSTERLINKTABLEAREA]=0;
gs_stCacheManager.vdwAccessTime[CACHE_DATAAREA]=0;
// 캐시 버퍼의 최댓값 설정
gs_stCacheManager.vdwMaxCount[CACHE_CLUSTERLINKTABLEAREA]=CACHE_MAXCLUSTERLINKTABLEAREACOUNT;
gs_stCacheManager.vdwMaxCount[CACHE_DATAAREA]=CACHE_MAXDATAAREACOUNT;
// 클러스터 링크 테이블 영역용 메모리 할당, 클러스터 링크 테이블은 512바이트로 관리함
gs_stCacheManager.vpbBuffer[CACHE_CLUSTERLINKTABLEAREA]=(BYTE*)kAllocateMemory(CACHE_MAXCLUSTERLINKTABLEAREACOUNT*512);
if(gs_stCacheManager.vpbBuffer[CACHE_CLUSTERLINKTABLEAREA]==NULL)
{
kFreeMemory(gs_stCacheManager.vpbBuffer[CACHE_CLUSTERLINKTABLEAREA]);
return FALSE;
}
// 할당받은 메모리 영역으르 나누어서 캐시 버퍼에 등록
for(i=0;i<CACHE_MAXCLUSTERLINKTABLEAREACOUNT;i++)
{
// 캐시 버퍼에 메모리 공간 할당
gs_stCacheManager.vvstCacheBuffer[CACHE_CLUSTERLINKTABLEAREA][i].pbBuffer=gs_stCacheManager.vpbBuffer[CACHE_CLUSTERLINKTABLEAREA]+(i*512);
// 태크를 유효하지 않은 것으로 설정하여 빈 것으로 만듦
gs_stCacheManager.vvstCacheBuffer[CACHE_CLUSTERLINKTABLEAREA][i].dwTag=CACHE_INVALIDTAG;
}
// 데이터 영역용 메모리 할당, 데이터 영역은 클러스터 단위(4KB)로 관리함
gs_stCacheManager.vpbBuffer[CACHE_DATAAREA] = (BYTE*)kAllocateMemory(CACHE_MAXDATAAREACOUNT*FILESYSTEM_CLUSTERSIZE);
if(gs_stCacheManager.vpbBuffer[CACHE_DATAAREA]==NULL)
{
// 실패하면 이전에 할당받은 메모리를 해제해야 함
kFreeMemory(gs_stCacheManager.vpbBuffer[CACHE_DATAAREA]);
return FALSE;
}
// 할당받은 메모리 영역을 나누어서 캐시 버퍼에 등록
for(i=0;i<CACHE_MAXDATAAREACOUNT;i++)
{
// 캐시 버퍼에 메모리 공간 할당
gs_stCacheManager.vvstCacheBuffer[CACHE_DATAAREA][i].pbBuffer=gs_stCacheManager.vpbBuffer[CACHE_DATAAREA]+(i*FILESYSTEM_CLUSTERSIZE);
// 태크를 유효하지 않은 것으로 설정하여 빈 것으로 만듦
gs_stCacheManager.vvstCacheBuffer[CACHE_DATAAREA][i].dwTag=CACHE_INVALIDTAG;
}
return TRUE;
}
// 캐시 버퍼에서 빈 것을 찾아서 반환
CACHEBUFFER* kAllocateCacheBuffer(int iCacheTableIndex)
{
CACHEBUFFER* pstCacheBuffer;
int i;
// 캐시 테이블의 최대 개수를 넘어서면 실패
if(iCacheTableIndex>CACHE_MAXCACHETABLEINDEX)
{
return NULL;
}
// 접근 시간 필드가 최댓값까지 가면 전체적으로 접근 시간을 낮춰줌
kCutDownAccessTime(iCacheTableIndex);
// 최대 개수만큼 검색하여 빈 것을 반환
pstCacheBuffer = gs_stCacheManager.vvstCacheBuffer[iCacheTableIndex];
for(i=0;i<gs_stCacheManager.vdwMaxCount[iCacheTableIndex];i++)
{
if(pstCacheBuffer[i].dwTag==CACHE_INVALIDTAG)
{
// 임시로 캐시 태그를 설정하여 할당된 것으로 만듦
pstCacheBuffer[i].dwTag = CACHE_INVALIDTAG-1;
// 접근 시간을 갱신
pstCacheBuffer[i].dwAccessTime = gs_stCacheManager.vdwAccessTime[iCacheTableIndex]++;
return &(pstCacheBuffer[i]);
}
}
return NULL;
}
// 캐시 버퍼에서 태그가 일치하는 것을 찾아서 반환
CACHEBUFFER* kFindCacheBuffer(int iCacheTableIndex,DWORD dwTag)
{
CACHEBUFFER* pstCacheBuffer;
int i;
// 캐시 테이블의 최대 개수를 넘어서면 실패
if(iCacheTableIndex>CACHE_MAXCACHETABLEINDEX)
{
return NULL;
}
// 접근 시간 필드가 최댓값까지 증가하면 전체적으로 접근 시간을 낮춤
kCutDownAccessTime(iCacheTableIndex);
// 최대 개수만큼 검색하여 빈 것을 반환
pstCacheBuffer = gs_stCacheManager.vvstCacheBuffer[iCacheTableIndex];
for(i=0;i<gs_stCacheManager.vdwMaxCount[iCacheTableIndex];i++)
{
if(pstCacheBuffer[i].dwTag==dwTag)
{
// 접근 시간을 갱신
pstCacheBuffer[i].dwAccessTime=gs_stCacheManager.vdwAccessTime[iCacheTableIndex]++;
return &(pstCacheBuffer[i]);
}
}
return NULL;
}
// 접근한 시간을 전체적으로 낮춤
static void kCutDownAccessTime(int iCacheTableIndex)
{
CACHEBUFFER stTemp;
CACHEBUFFER* pstCacheBuffer;
BOOL bSorted;
int i,j;
// 캐시 테이블의 최대 개수를 넘어서면 실패
if(iCacheTableIndex>CACHE_MAXCACHETABLEINDEX)
{
return;
}
// 접근 시간이 아직 최대치를 넘지 않았담녀 접근시간을 줄일 필요 없음
if(gs_stCacheManager.vdwAccessTime[iCacheTableIndex]<0xfffffffe)
{
return ;
}
// 캐시 버퍼를 오름차순으로 정렬함
// 버블 정렬(Bubble Sort)사용
pstCacheBuffer = gs_stCacheManager.vvstCacheBuffer[iCacheTableIndex];
for(j=0;j<gs_stCacheManager.vdwMaxCount[iCacheTableIndex]-1;j++)
{
// 기본은 정렬된 것으로 저장
bSorted=TRUE;
for(i=0;i<gs_stCacheManager.vdwMaxCount[iCacheTableIndex]-1-j;i++)
{
// 인접한 두 데이터를 비교하여 접근 시간이 큰 것을 오른쪽(i+1)에 위치시킴
if(pstCacheBuffer[i].dwAccessTime>pstCacheBuffer[i+1].dwAccessTime)
{
// 두 데이터를 교환하므로 정렬되지 않은 것으로 표시
bSorted = FALSE;
// i 번재 캐시와 i+1번째 캐시를 교환
kMemCpy(&stTemp,&(pstCacheBuffer[i]),sizeof(CACHEBUFFER));
kMemCpy(&(pstCacheBuffer[i]),&(pstCacheBuffer[i+1]),sizeof(CACHEBUFFER));
kMemCpy(&(pstCacheBuffer[i+1]),&stTemp,sizeof(CACHEBUFFER));
}
}
// 다 정렬되었으면 루프를 빠져나감
if(bSorted==TRUE)
{
break;
}
}
// 오름차순으로 정렬했으므로 인덱스가 증가할수록 접근 시간 큰(최신) 캐시 버퍼임
// 접근 시간을 0부터 순차적으로 설정하여 데이터 갱신
for(i=0;i<gs_stCacheManager.vdwMaxCount[iCacheTableIndex];i++)
{
pstCacheBuffer[i].dwAccessTime=i;
}
// 접근 시간을 파일 시스템 캐시 자료구조에 저장해 다음부터는 변경된 값으로 접근 시간을 설정하게 함
gs_stCacheManager.vdwAccessTime[iCacheTableIndex]=i;
}
// 캐시 버퍼에서 내보낼 것을 찾음
CACHEBUFFER* kGetVictimInCacheBuffer(int iCacheTableIndex)
{
DWORD dwOldTime;
CACHEBUFFER* pstCacheBuffer;
int iOldIndex;
int i;
// 캐시 테이블의 최대 개수를 넘어서면 실패
if(iCacheTableIndex>CACHE_MAXCACHETABLEINDEX)
{
return NULL;
}
// 접근 시간을 최대로 해서 접근 시간이 가장 오래된(값이 작은) 캐시 버퍼를 검색
iOldIndex = -1;
dwOldTime = 0xFFFFFFFF;
// 캐시 버퍼에서 사용 중이지 않거나 접근한 지 가장 오래된 것을 찾아서 반환
pstCacheBuffer = gs_stCacheManager.vvstCacheBuffer[iCacheTableIndex];
for(i=0;i<gs_stCacheManager.vdwMaxCount[iCacheTableIndex];i++)
{
// 빈 캐시 버퍼가 있으면 빈 것을 반환
if(pstCacheBuffer[i].dwTag == CACHE_INVALIDTAG)
{
iOldIndex = i;
break;
}
// 접근 시간이 현재 값보다 오래되었으면 저장해둠
if(pstCacheBuffer[i].dwAccessTime<dwOldTime)
{
dwOldTime = pstCacheBuffer[i].dwAccessTime;
iOldIndex=i;
}
}
// 캐시 버퍼를 찾지 못하면 문제가 발생한 것임
if(iOldIndex==-1)
{
kPrintf("Cache Buffer Find Error\n");
return NULL;
}
// 선택된 캐시 버퍼의 접근 시간을 갱신
pstCacheBuffer[iOldIndex].dwAccessTime = gs_stCacheManager.vdwAccessTime[iCacheTableIndex]++;
return &(pstCacheBuffer[iOldIndex]);
}
// 캐시 버퍼의 내용을 모두 비움
void kDiscardAllCacheBuffer(int iCacheTableIndex)
{
CACHEBUFFER* pstCacheBuffer;
int i;
// 캐시 버퍼를 모두 빈 것으로 설정
pstCacheBuffer = gs_stCacheManager.vvstCacheBuffer[iCacheTableIndex];
for(i=0;i<gs_stCacheManager.vdwMaxCount[iCacheTableIndex];i++)
{
pstCacheBuffer[i].dwTag = CACHE_INVALIDTAG;
}
// 접근 시간을 초기화
gs_stCacheManager.vdwAccessTime[iCacheTableIndex]=0;
}
// 캐시 버퍼의 포인터와 최대 개수를 반환
BOOL kGetCacheBufferAndCount(int iCacheTableIndex,CACHEBUFFER** ppstCacheBuffer,int* piMaxCount)
{
// 캐시 테이블의 최대 개수를 넘어서면 실패
if(iCacheTableIndex>CACHE_MAXCACHETABLEINDEX)
{
return FALSE;
}
// 캐시 버퍼의 포인터와 최댓값을 반환
*ppstCacheBuffer = gs_stCacheManager.vvstCacheBuffer[iCacheTableIndex];
*piMaxCount = gs_stCacheManager.vdwMaxCount[iCacheTableIndex];
return TRUE;
}
|
C
|
#include <string.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include "reunion.h"
static int debug= 1;
typedef struct {
pthread_mutex_t m;
pthread_cond_t c;
int entraron, salieron, esperados;
} Verif;
typedef struct {
Reunion *r;
int delay;
char *nombre;
Verif *pv;
} Param;
static void *fun(void *ptr) {
Param *param= ptr;
Verif *pv= param->pv;
pthread_mutex_lock(&pv->m);
if (debug)
printf("Entrar de %s\n", param->nombre);
pthread_mutex_unlock(&pv->m);
entrar(param->r);
pthread_mutex_lock(&pv->m);
pv->entraron++;
pthread_cond_broadcast(&pv->c);
pthread_mutex_unlock(&pv->m);
if (param->delay>0) sleep(param->delay);
pthread_mutex_lock(&pv->m);
pthread_cond_broadcast(&pv->c);
while (pv->entraron<pv->esperados)
pthread_cond_wait(&pv->c, &pv->m);
pv->salieron++;
if (debug)
printf("Concluir de %s\n", param->nombre);
pthread_mutex_unlock(&pv->m);
concluir(param->r);
pthread_mutex_lock(&pv->m);
pthread_cond_broadcast(&pv->c);
if (pv->salieron!=pv->esperados) {
fprintf(stderr, "Funcionario %s salio antes de que todos concluyeran\n",
param->nombre);
exit(1);
}
pthread_mutex_unlock(&pv->m);
return NULL;
}
static void *testEnun(void *ptr) {
Reunion *r= nuevaReunion();
pthread_t f1, f2, f3;
Verif v= { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0, 0, 3 };
Param p1= { r, 1, "F1", &v };
Param p2= { r, 4, "F2", &v };
Param p3= { r, 4, "F3", &v };
pthread_create(&f3, 0, fun, &p3);
sleep(1);
pthread_create(&f2, 0, fun, &p2);
sleep(1);
pthread_create(&f1, 0, fun, &p1);
pthread_join(f1, NULL);
pthread_join(f2, NULL);
pthread_join(f3, NULL);
destruirReunion(r);
pthread_cond_destroy(&v.c);
pthread_mutex_destroy(&v.m);
return NULL;
}
static void *testSinPausa(void *ptr) {
int n= (intptr_t)ptr;
Reunion *r= nuevaReunion();
Verif v= { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0, 0, n };
pthread_t f[n];
Param p[n];
for (int i= 0; i<n; i++) {
p[i].r= r;
p[i].delay= 0;
p[i].nombre= malloc(10);
sprintf(p[i].nombre, "F%d", i);
p[i].pv= &v;
pthread_create(&f[i], 0, fun, &p[i]);
}
for (int i= 0; i<n; i++) {
pthread_join(f[i], NULL);
free(p[i].nombre);
}
destruirReunion(r);
pthread_cond_destroy(&v.c);
pthread_mutex_destroy(&v.m);
return NULL;
}
int main() {
{
printf("Test 1: un solo participante\n");
Reunion *r= nuevaReunion();
pthread_t f;
Verif v= { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0, 0, 1 };
Param p= { r, 1, "F", &v };
pthread_create(&f, 0, fun, &p);
pthread_join(f, NULL);
destruirReunion(r);
pthread_cond_destroy(&v.c);
pthread_mutex_destroy(&v.m);
printf("Test 1 aprobado\n");
}
{
printf("Test 2: 3 participantes, igual al diagrama del enunciado\n");
int pausa= 1;
testEnun(&pausa);
printf("Test 2 aprobado\n");
}
{
int n= 10;
printf("Test 3: el mismo test 2 con %d instancias en paralelo\n", n);
debug= 0;
pthread_t af[n];
for (int i= 0; i<n; i++) {
if (pthread_create(&af[i], 0, testEnun, NULL)!=0) {
perror("pthread_create");
exit(i);
}
}
for (int i= 0; i<n; i++) {
pthread_join(af[i], NULL);
}
printf("Test 3 aprobado\n");
}
{
#ifdef VALGRIND
int m= 100, maxthr= 10;
#else
int m= 10000, maxthr= 20;
#endif
int fin= 0;
printf("Test de robustez: %d instancias en paralelo sin espera\n", m);
pthread_t t[m];
for (int i= 0; i<m; i++) {
if (i-fin>=maxthr) {
pthread_join(t[fin], NULL);
fin++;
}
if (pthread_create( &t[i], NULL, testSinPausa,
(void*)(intptr_t)(i%6+1) )) {
perror("pthread_create");
exit(1);
}
}
while (fin<m) {
pthread_join(t[fin], NULL);
fin++;
}
}
printf("Felicitaciones: su tarea ha aprobado todos los tests.\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAX 100000
int LerDados()
{
int aux;
scanf("%d",&aux);
return aux;
}
int main()
{
int num,j=0,i,flag=1,tam;
int cont=0,cont2=0,A[MAX],B[MAX];
int *contador;// = (int*)calloc(MAX,sizeof(int));
scanf("%d",&num);
contador = (int*)calloc(num,sizeof(int));
tam=num;
for(i=0; i<num; i++)
{
A[i]=LerDados();
B[i]=LerDados();
contador[B[i]-1] = contador[B[i]-1] + 1;
}
int aux;
while(flag==1)
{
i=0;
flag = 0;
while(i < num)
{
if(contador[i]==0) ///Coloco contador negativo para saber que já foi removido
{
contador[i] = -1;
contador[B[i]-1]--;
flag=1;
}
else i++;
}
}
printf("\n");
for(i=0; i<num; i++)
{
if(contador[i]!=-1)
printf("%d ",A[i]);
}
return 0;
}
|
C
|
#include "types.h"
#include "stat.h"
#include "user.h"
void
printf(int fd, char *s, ...)
{
write(fd, s, strlen(s));
}
int
main(void)
{
int pid;
if ((pid=fork2())==0){
printf( 1,"Filho aki\n");
int i=0;
while(i<100000)i++;
printf( 1,"Filho is dead\n");
}else{
printf( 1,"Pai aki\n");
int i=0;
while(i<100000)i++;
printf( 1,"wait for its\n");
wait();
printf( 1,"Filho is dead on fathers arms\n");
}
printf( 1,"Father is dead\n");
exit();
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: toh <toh@student.42seoul.kr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/04 18:58:30 by seomoon #+# #+# */
/* Updated: 2021/06/13 14:03:47 by seomoon ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
#include<stdio.h>
void exit_minishell(void)
{
exit(0);
}
void show_prompt(void)
{
ft_putstr_fd("minishell$ ", STDOUT);
}
void get_input(char **input, t_env *env_head)
{
get_next_line(STDIN, input);
if (ft_strcmp(*input, "exit") == 0)
{
free(*input);
printf("exit\n");
exit_minishell();
return ;
}
if (ft_strcmp(*input, "env") == 0)
print_env(env_head);
}
int main(int argc, char **argv, char **envp)
{
char *input;
t_env env_head;
t_cmd cmd_head;
parse_env(&env_head, envp);
while (1)
{
show_prompt();
get_input(&input, &env_head);
parse_input(&cmd_head, &env_head, input);
free(input);
//print_command(cmd_head);
}
}
|
C
|
#include "sam.h"
#define PORTA_Ena(data) PIOA->PIO_PER=(1<<data); //PIOA I/O 사용 설정
#define PORTA_Out(data) PIOA->PIO_OER=(1<<data); //PIOA 출력 사용 설정
#define PORTA_In(data) PIOA->PIO_ODR=(1<<data); //PIOA 입력 사용 설정
#define PORTA_Set(data) PIOA->PIO_SODR=(1<<data); //PIOA data set 설정
#define PORTA_Stat PIOA->PIO_PDSR; //PIOA data 읽어오기
#define PORTD_Ena(data) PIOD->PIO_PER=(1<<data); //PIOD I/O 사용 설정
#define PORTD_Out(data) PIOD->PIO_OER=(1<<data); //PIOA 출력 사용 설정
#define PORTD_In(data) PIOD->PIO_ODR=(1<<data); //PIOD 입력 사용 설정
#define PORTD_Set(data) PIOD->PIO_SODR=(1<<data); //PIOD data set 설정
void PIO_Init()
{
//PORTA 초기화
PMC->PMC_PCER0|=(1<<ID_PIOA);
PORTA_Ena(0x0F);
PORTA_In(0x0F);
//PORTD 초기화
PMC->PMC_PCER0|=(1<<ID_PIOD);
PORTD_Ena(0xFF);
PORTD_In(0xFF);
}
void MyDelay(volatile uint32_t delay)
{
while(delay)
{
delay--;
}
}
void MyDelay2(volatile uint32_t delay1,volatile uint32_t delay2)
{
while(delay1)
{
MyDelay(delay2);
delay1--;
}
}
//텍스트 LCD로 부터 상태(명령)를 읽는 함수
unsigned char LCD_rCommand()
{
unsigned char temp=1;
PORTD_In(0xFF);
PORTA_Set(0x06); //명령 읽기 동작 시작 (0Bit clr, 1Bit set, 2Bit Set)
MyDelay2(1000,10);
temp=PORTA_Stat; //명령 읽기
MyDelay2(1000,10);
PORTA_Set(0x02); //명령 읽기 동작 끝 (0Bit clr, 1Bit set, 2Bit clr)
PORTD_Out(0xFF);
MyDelay2(1000,10);
return temp;
}
//텍스트 LCD의 비지 플래그 상태를 확인하는 함수
char LCD_BusyCheck(unsigned char temp)
{
if (temp & 0x80) return 1;
else return 0;
}
//텍스트 LCD에 명령을 출력하는 함수 - 단, 비지플래그 체크하지 않음
void LCD_wCommand(char cmd)
{
PORTA_Set(0x04); //명령 쓰기 동작 시작 (0Bit clr, 1Bit clr, 2Bit set)
PORTD_Set(cmd);
MyDelay2(1000,10);
PORTA_Set(0x00); //명령 쓰기 동작 끝 (0Bit clr, 1Bit clr, 2Bit clr)
MyDelay2(1000,10);
}
//텍스트 LCD에 명령을 출력하는 함수 - 단, 비지플래그 체크 함
void LCD_wBCommande(char cmd)
{
while(LCD_BusyCheck(LCD_rCommand()))
MyDelay2(1000,10);
PORTA_Set(0x04); //명령 쓰기 동작 시작 (0Bit clr, 1Bit clr, 2Bit set)
PORTD_Set(cmd);
MyDelay2(1000,10);
PORTA_Set(0x00); //명령 쓰기 동작 끝 (0Bit clr, 1Bit clr, 2Bit clr)
MyDelay2(1000,10);
}
//텍스트 LCD를 초기화하는 함수
void LCD_Init()
{
MyDelay2(1000,100000);
LCD_wCommand(0x30); //비지 플래그를 체크하지 않는 Function Set
MyDelay2(1000,10000);
LCD_wCommand(0x30); //비지 플래그를 체크하지 않는 Function Set
MyDelay2(1000,200000);
LCD_wCommand(0x30); //비지 플래그를 체크하지 않는 Function Set
MyDelay2(1000,200000);
LCD_wBCommande(0x38); //비지 플래그를 체크하는 Function Set
LCD_wBCommande(0x0c); //비지 플래그를 체크하는 Display On/Off Control
LCD_wBCommande(0x01); //비지 플래그를 체크하는 Clear Display
}
//텍스트 LCD에 1바이트 데이터를 출력하는 함수
void LCD_wData(char dat)
{
while(LCD_BusyCheck(LCD_rCommand()))
MyDelay2(1000,10);
PORTA_Set(0x00000005); //데이터 쓰기 동작 시작 (0Bit set, 1Bit clr, 2Bit set)
PORTD_Set(dat);
MyDelay2(1000,10);
PORTA_Set(0x00000001); //데이터 쓰기 동작 끝 (0Bit set, 1Bit clr, 2Bit clr)
MyDelay2(1000,10);
}
//텍스트 LCD에 문자열을 출력하는 함수
void LCD_wString(char *str)
{
while(*str)
LCD_wData(*str++);
}
int main(void)
{
SystemInit();
WDT->WDT_MR|=(1<<15);
PIO_Init();
LCD_Init();
LCD_wBCommande(0x80|0x00); //DDRAM Address = 0 설정
LCD_wString("HELLO WORLD!"); //텍스트 LCD 문자열 출력
LCD_wBCommande(0x80|0x40); //DDRAM Address = 0 설정
LCD_wString("GOOD BYE!"); //WESNET 문자열 출력
return 1;
while (1)
{
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void result(int a, int b, int *x, int *y, int *z);
int samsam(void)
{
char c = '.';
int i, j, k, start, round;
int x = 0, y = 0, z = 0;
const char *a[3] = { "Rock", "Paper", "Scissors" };
const char *b[3] = { "Rock", "Paper", "Scissors" };
srand(time(0));
printf("RockVpaperVscissors Game\n~~~~~~~~~~~~~~~~~~~~~~~~~~\nPress Enter to start");
while (1){
scanf_s("%c", &c);
if (c == '\n'){
break;
}
}
printf("\nChoose the number of round you like to play:");
scanf_s("%d", &round);
for (j = 1; j <= round; j++)
{
printf("\n---------------------------------------------------\n\nRound%d\n", j);
printf("\nChoose your weapon: Rock[0], Paper[1], Scissors[2]\n");
scanf_s("%d", &i);
if (i > 2 || i < 0){ j--; printf("input error!!\n"); continue; }
printf("\nYou chose the %s\n", a[i]);
k = rand() % 3;
printf("And your opponent chose the %s\n\n", b[k]);
result(i, k, &x, &y, &z);
}
printf("\n---------------------------------------------------\n\nWins:%d\nDraws:%d\nLose:%d\n\n", x, z, y);
printf("Your sorce: %d/%d\n\n", (x * 2 + z), round * 2);
system("pause");
return 0;
}
void result(int a, int b, int *x, int *y, int *z)
{
if (a == b){ printf("Draw"); (*z)++; }
else if (a == 0 && b == 2) { printf("You win!"); (*x)++; }
else if (a == 2 && b == 0) { printf("You lose!"); (*y)++; }
else if (a == 1 && b == 0) { printf("You win!"); (*x)++; }
else if (a == 0 && b == 1) { printf("You lose!"); (*y)++; }
else if (a == 2 && b == 1) { printf("You win!"); (*x)++; }
else if (a == 1 && b == 2) { printf("You lose!"); (*y)++; }
}
|
C
|
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
struct book
{
char number[100];
char tittle[100];
char writer[100];
char publisher[100];
char date[100];
char price[100];
char status[100];
char reader[100];
};
void search_book();
void borrow_book();
void return_book();
void add_book();
void delete_book();
void modify_book();
void scan_book();
int main()
{
int c1 = 0, c2, c3;
int l, x, z;
while (1)
{
system("color 2C");
printf("\t\t\t ^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^ \n");
printf("\t\t\t| * - * - * -???????? * - * - * |\n");
printf("\t\t\t* [1] ?????? *\n");
printf("\t\t\t* [2] ???????? *\n");
printf("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^ \n");
printf("\n");
printf("??????????? ??");
scanf("%d", &c1);
system("cls");
break;
}
if (c1 == 1)
{
while (1)
{
system("color 2C");
printf("\t\t\t ^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^ \n");
printf("\t\t\t| * - * - * -???????? * - * - * |\n");
printf("\t\t\t* [1] ?????? *\n");
printf("\t\t\t| [2] ??????? |\n");
printf("\t\t\t* [3] ?T??? *\n");
printf("\t\t\t* [4] ????????? *\n");
printf("\t\t\t| [5] ??????????? |\n");
printf("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^ \n");
printf("\n");
printf("??????????? ??");
scanf("%d", &c2);
getchar();
switch (c2)
{
case 1:
search_book();
break;
case 2:
borrow_book();
break;
case 3:
return_book();
break;
case 4:
scan_book();
break;
case 5:
system("cls");
return 0;
}
}
}
if (c1 == 2)
{
while (1)
{
system("color 2C");
printf("\t\t\t ^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^ \n");
printf("\t\t\t| * - * - * -???????? * - * - * |\n");
printf("\t\t\t| [1] ??????? |\n");
printf("\t\t\t* [2] ?????? *\n");
printf("\t\t\t| [3] ????????? |\n");
printf("\t\t\t* [4] ????????? *\n");
printf("\t\t\t| [5] ??????????? |\n");
printf("\t\t\t^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^ \n");
printf("\n");
printf("??????????? ??");
scanf("%d", &c3);
getchar();
switch (c3)
{
case 1:
add_book();
break;
case 2:
delete_book();
break;
case 3:
modify_book();
break;
case 4:
scan_book();
break;
case 5:
system("cls");
return 0;
}
}
}
}
/*??????*/
void search_book()
{
FILE *fp;
struct book n;
struct book nn;
int l, r;
char x, z;
fp = fopen("F:\\?????\\????????.txt", "rb");
while (1)
{
l = 0;
system("cls");
printf("??????????????");
scanf("%s", n.tittle);
fflush(stdin);
rewind(fp);
while (1)
{
fread(&nn, sizeof(nn), 1, fp);
if (feof(fp))
break;
r = strcmp(n.tittle, nn.tittle);
if (r == 0)
{
l = 1;
break;
}
}
if (l == 0)
{
printf("???????????{????\n\n ");
}
else
{
printf("???????????");
printf("\n");
printf("****************************************\n");
printf("??? ???? ???? ?????? ??????? ??? ?? ??????\n");
printf("\n");
printf("%s %s %s %s %s %s %s", nn.number, nn.tittle, nn.writer, nn.publisher, nn.date, nn.price, nn.status, nn.reader);
printf("\n\n\n");
}
printf("???????????? ? [??(y)/??(n)] ? \n\n");
do
{
x = getche();
} while (x != 'n' && x != 'y');
if (x == 'n')
break;
}
fclose(fp);
system("cls");
}
//????
void add_book()
{
FILE *fp;
struct book n;
struct book nn;
char x, z;
int l, r;
fp = fopen("F:\\?????\\????????.txt", "ab+");
do
{
system("cls");
do
{
l = 0;
printf("\n");
printf("??? ???? ???? ?????? ??????? ??? ?? ??????\n");
fflush(stdin);
scanf("%s %s %s %s %s %s %s %s", n.number, n.tittle, n.writer, n.publisher, n.date, n.price, n.status, n.reader);
system("cls");
rewind(fp);
while (!feof(fp))
{
fread(&nn, sizeof(nn), 1, fp);
r = strcmp(n.tittle, nn.tittle);
if (r == 0)
{
l = 1;
printf(" ??????????????????????????: \n\n");
break;
}
}
} while (l);
fwrite(&n, sizeof(n), 1, fp);
printf("\n");
printf("???????????????????[y/n] \n\n");
do
{
x = getche();
} while (x != 'n' && x != 'y');
} while (x == 'y');
fclose(fp);
system("cls");
}
//??????
void delete_book()
{
FILE *fp, *fp1;
char x, z;
struct book n;
struct book nn;
int l, r;
fp = fopen("F:\\?????\\????????.txt", "ab+");
while (1)
{
l = 0;
system("cls");
printf("\n");
printf("???????????????????: \n\n");
fflush(stdin);
scanf("%s", &n.tittle);
rewind(fp);
while (1)
{
fread(&nn, sizeof(nn), 1, fp);
if (feof(fp))
break;
r = strcmp(n.tittle, nn.tittle);
if (r == 0)
{
l = 1;
break;
}
}
if (l == 0)
{
printf("\n");
printf("????????????? \n");
}
else
{
printf("\n");
printf("****************************************\n");
printf("??? ???? ???? ?????? ??????? ??? ?? ??????\n");
printf("\n");
printf("%s %s %s %s %s %s %s %s", nn.number, nn.tittle, nn.writer, nn.publisher, nn.date, nn.price, nn.status, nn.reader);
printf("\n");
printf("?????????????? [??(y)/??(n)]\n\n");
do
{
z = getche();
} while (z != 'n' && z != 'y');
if (z == 'n')
break;
else
{
fp1 = fopen("F:\\?????\\????????new.txt", "wb");
rewind(fp);
while (1)
{
fread(&nn, sizeof(nn), 1, fp);
if (feof(fp))
break;
r = strcmp(n.tittle, nn.tittle);
if (r != 0)
fwrite(&nn, sizeof(nn), 1, fp1);
}
fclose(fp);
fclose(fp1);
fp = fopen("F:\\?????\\????????.txt", "wb");
fp1 = fopen("F:\\?????\\????????new.txt", "rb");
while (1)
{
fread(&nn, sizeof(nn), 1, fp1);
if (feof(fp1))
break;
fwrite(&nn, sizeof(nn), 1, fp);
}
fclose(fp);
fclose(fp1);
}
}
printf("\n");
printf("????????????????? [??(y)/??(n)] \n");
do
{
x = getche();
} while (x != 'n' && x != 'y');
if (x == 'n')
break;
}
fclose(fp);
system("cls");
}
//?????????
void modify_book()
{
FILE *fp;
struct book n;
struct book nn;
int l, r;
char x, z;
fp = fopen("F:\\?????\\????????.txt", "rb+");
while (1)
{
l = 0;
printf("\n");
system("cls");
printf("??????????????????: \n\n");
fflush(stdin);
scanf("%s", &n.tittle);
system("cls");
rewind(fp);
while (1)
{
fread(&nn, sizeof(nn), 1, fp);
if (feof(fp))
break;
r = strcmp(n.tittle, nn.tittle);
if (r == 0)
{
l = 1;
break;
}
}
if (l == 0)
{
printf("\n");
printf("???????????????? \n\n");
}
else
{
printf("\n");
printf("****************************************\n");
printf("??? ???? ???? ?????? ??????? ??? ?? ??????\n");
printf("\n");
printf("%s %s %s %s %s %s %s %s", nn.number, nn.tittle, nn.writer, nn.publisher, nn.date, nn.price, nn.status, nn.reader);
printf("???????????????\n\n\n");
fflush(stdin);
scanf("%s %s %s %s %s %s %s %s", n.number, n.tittle, n.writer, n.publisher, n.date, n.price, n.status, n.reader);
fseek(fp, sizeof(nn), 1);
fwrite(&n, sizeof(nn), 1, fp);
}
printf("\n");
printf(" ???????????????[y/n]? \n\n");
do
{
x = getch();
} while (x != 'n' && x != 'y');
if (x == 'n')
break;
}
fclose(fp);
system("cls");
}
//????
void borrow_book()
{
FILE *fp;
struct book n;
struct book nn;
char x, z;
int l, r;
fp = fopen("F:\\?????\\????????.txt", "rb+");
while (1)
{
l = 0;
system("cls");
printf("\n");
printf("???????????????????: \n");
fflush(stdin);
scanf("%s", &n.tittle);
rewind(fp);
while (1)
{
fread(&nn, sizeof(nn), 1, fp);
if (feof(fp))
break;
r = strcmp(n.tittle, nn.tittle);
if (r == 0)
{
l = 1;
break;
}
}
if (l == 0)
{
printf("\n");
printf("???????????? \n");
}
else
{
printf("\n");
printf("****************************************\n");
printf("??? ???? ???? ?????? ??????? ??? ?? ??????\n");
printf("\n");
printf("%s %s %s %s %s %s %s %s", nn.number, nn.tittle, nn.writer, nn.publisher, nn.date, nn.price, nn.status, nn.reader);
printf("\n");
fflush(stdin);
printf("?????????????????????????????????");
printf("****************************************\n");
printf("??? ???? ???? ?????? ??????? ??? ?? ??????\n");
printf("\n");
scanf("%s %s %s %s %s %s %s %s", n.number, n.tittle, n.writer, n.publisher, n.date, n.price, n.status, n.reader);
fseek(fp, sizeof(nn), 1);
fwrite(&n, sizeof(nn), 1, fp);
}
printf("\n");
printf(" ????????? [??(y)/??(n)] \n\n");
do
{
x = getch();
} while (x != 'n' && x != 'y');
if (x == 'n')
break;
}
fclose(fp);
system("cls");
}
//????
void return_book()
{
FILE *fp;
struct book n;
struct book nn;
char x, z;
int l, r;
fp = fopen("F:\\?????\\????????.txt", "rb+");
while (1)
{
l = 0;
system("cls");
printf("\n");
printf("??????????T???????: \n");
fflush(stdin);
scanf("%s", &n.tittle);
rewind(fp);
while (1)
{
fread(&nn, sizeof(nn), 1, fp);
if (feof(fp))
break;
r = strcmp(n.tittle, nn.tittle);
if (r == 0)
{
l = 1;
break;
}
}
if (l == 0)
{
printf("\n");
printf("???????????? \n");
}
else
{
printf("\n");
printf("****************************************\n");
printf("??? ???? ???? ?????? ??????? ??? ?? ??????\n");
printf("\n");
printf("%s %s %s %s %s %s %s %s", nn.number, nn.tittle, nn.writer, nn.publisher, nn.date, nn.price, nn.status, nn.reader);
printf("\n");
fflush(stdin);
printf("?????????????????????? \n\n");
printf("****************************************\n");
printf("??? ???? ???? ?????? ??????? ??? ?? ??????\n");
printf("\n");
scanf("%s %s %s %s %s %s %s %s", n.number, n.tittle, n.writer, n.publisher, n.date, n.price, n.status, n.reader);
fseek(fp, -(int)sizeof(nn), 1);
fwrite(&n, sizeof(nn), 1, fp);
}
printf("\n");
printf("????????? [??(y)/??(n)] \n");
do
{
x = getche();
} while (x != 'n' && x != 'y');
if (x == 'n')
break;
}
fclose(fp);
system("cls");
}
//???
void scan_book()
{
FILE *fp;
char x, z;
struct book n;
fp = fopen("F:\\?????\\????????.txt", "rb");
rewind(fp);
system("cls");
while (1)
{
fread(&n, sizeof(n), 1, fp);
if (feof(fp))
break;
else
{
printf("********************************************\n");
printf("??? ???? ???? ?????? ??????? ??? ?? ??????\n");
printf("\n");
printf("%s %s %s %s %s %s %s %s", n.number, n.tittle, n.writer, n.publisher, n.date, n.price, n.status, n.reader);
printf("\n");
}
}
printf("\n");
printf("?????????????");
do
{
x = getche();
} while (x != '\r');
if (x == '\r')
{
fclose(fp);
system("cls");
}
}
|
C
|
//
// Created by Oleg Bukatchuk on 15/09/2017.
//
#include <stdio.h>
int main()
{
int num = 1234567890;
printf("Size of int data type is %d bytes\n", sizeof (int));
printf("Size of int variable is %d bytes\n", sizeof (num));
printf("Size of an int array is %d bytes\n", sizeof (int[3]));
struct {int score; char grade;} result;
printf("Size of a structure is %d bytes\n", sizeof (result));
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#define BUF_LEN 4096
#define HTTP_PORT 80
int main (int argc, char ** argv)
{
int sock, count;
char * buf;
struct hostent * host;
struct sockaddr_in addr;
if (argc < 2) {
fprintf (stderr, "Too few arguments\n");
return 1;
}
buf = (char *) malloc (BUF_LEN);
if (buf == NULL) {
fprintf (stderr, "malloc() error\n");
return 1;
}
sock = socket (PF_INET, SOCK_STREAM, 0);
if (sock == -1) {
fprintf (stderr, "socket() error\n");
return 1;
}
addr.sin_family = AF_INET;
host = gethostbyname (argv[1]);
if (host == NULL) {
fprintf (stderr, "Unknown server\n");
return 1;
}
addr.sin_addr = * (struct in_addr*)
host->h_addr_list[0];
addr.sin_port = htons (HTTP_PORT);
if (connect (sock, (struct sockaddr*) &addr,
sizeof (addr)) == -1) {
fprintf (stderr, "connect() error\n");
return 1;
}
strcpy (buf, "GET /\n");
write (sock, buf, strlen (buf));
while ((count = read (sock, buf, BUF_LEN)) > 0)
write (1, buf, count);
close (sock);
free (buf);
return 0;
}
|
C
|
#include<stdio.h>
#define N 10
int a[N];
int top=-1;
void push(int );
int pop();
void main()
{
char post[10];
int i=0,n1,n2,ans;
printf("Enter postfix expression : ");
scanf("%s",post);
while(post[i]!='\0')
{
if(post[i]>=48 &&post[i]<=57)
push(post[i]-48);
else
{
n2=pop();
n1=pop();
if(post[i]=='+')
ans=n1+n2;
else if(post[i]=='-')
ans=n1-n2;
else if(post[i]=='*')
ans=n1*n2;
else if(post[i]=='/')
ans=n1/n2;
push(ans);
}
i++;
}
printf("Answer =%d\n",pop());
}
int isempty()
{
if(top==-1)
return 1;
else
return 0;
}
int isfull()
{
if(top==N-1)
return 1;
else
return 0;
}
void push(int val)
{
if(isfull()==1)
{
printf("\nStack is overflow");
}
else
{
top++;
a[top]=val;
}
}
int pop()
{
int tmp;
if(isempty()==1)
{
printf("\nStack is underflow");
return -1;
}
else
{
tmp=a[top];
a[top]=0;
top--;
return tmp;
}
}
|
C
|
#include <stdio.h>
#if 0
int main()
{
unsigned i ;
for( i = 0 ; i < 4 ; ++i )
{
fprintf( stdout , "i = %d\n" , ("11213141") ) ;
}
getchar();
return 0 ;
}
#include <stdio.h>
char* fun()
{
return "awake";
}
int main()
{
printf("%s",fun()+ printf("I see you"));
getchar();
return 0;
}
#include<stdio.h>
int main()
{
int a;
char *x;
x = (char *) &a;
a = 512;
x[0] = 1;
x[1] = 2;
printf("%d\n",a);
getchar();
return 0;
}
#include<stdio.h>
int fun(char *str1)
{
char *str2 = str1;
while(*++str1);
return (str1-str2);
}
int main()
{
char *str = "geeksforgeeks";
printf("%d", fun(str));
getchar();
return 0;
}
#endif
int main()
{
unsigned int x = -1;
int y = ~0;
if(x == y)
printf("same");
else
printf("not same");
printf("\n x is %u, y is %u", x, y);
printf("\n x is %d, y is %d", x, y);
printf("\n x is %x, y is %x", x, y);
getchar();
return 0;
}
|
C
|
/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby,
C#, VB, Perl, Swift, Prolog, Javascript, Pascal, HTML, CSS, JS
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
//Queue using Array
#include <stdio.h>
#include <stdlib.h>
struct Queue
{
int size;
int front;
int rear;
int *Q;
};
void
create (struct Queue *q, int size)
{
q->size = size;
q->front = q->rear = -1;
q->Q = (int *) malloc (q->size * sizeof (int));
}
void
enqueue (struct Queue *q, int x)
{
if (q->rear == q->size - 1)
printf ("Queue is Full");
else
{
q->rear++;
q->Q[q->rear] = x;
}
}
int
dequeue (struct Queue *q)
{
int x = -1;
if (q->front == q->rear)
printf ("Queue is Empty\n");
else
{
q->front++;
x = q->Q[q->front];
}
return x;
}
void
Display (struct Queue q)
{
int i;
for (i = q.front + 1; i <= q.rear; i++)
printf ("%d ", q.Q[i]);
printf ("\n");
}
int
main ()
{
struct Queue q;
create (&q, 5);
enqueue (&q, 10);
enqueue (&q, 20);
enqueue (&q, 30);
Display (q);
printf ("%d ", dequeue (&q));
return 0;
}
//Queue using CPP
#include <iostream>
using namespace std;
class Queue
{
private:
int front;
int rear;
int size;
int *Q;
public:
Queue ()
{
front = rear = -1;
size = 10;
Q = new int[size];
}
Queue (int size)
{
front = rear = -1;
this - >size = size;
Q = new int[this->size];
}
void enqueue (int x);
int dequeue ();
void Display ();
};
void
Queue::enqueue (int x)
{
if (rear == size - 1)
printf ("Queue Full\n");
else
{
rear++;
Q[rear] = x;
}
}
int
Queue::dequeue ()
{
int x = -1;
if (front == rear)
printf ("Queue is Empty\n");
else
{
x = Q[front + 1];
front++;
}
return x;
}
void
Queue::Display ()
{
for (int i = front + 1; i <= rear; i++)
printf ("%d ", Q[i]);
printf ("\n");
}
int
main ()
{
Queue q (5);
q.enqueue (10);
q.enqueue (20);
q.enqueue (30);
q.Display ();
return 0;
}
//Circular Queue
#include <stdio.h>
#include <stdlib.h>
struct Queue
{
int size;
int front;
int rear;
int *Q;
};
void
create (struct Queue *q, int size)
{
q->size = size;
q->front = q->rear = 0;
q->Q = (int *) malloc (q->size * sizeof (int));
}
void
enqueue (struct Queue *q, int x)
{
if ((q->rear + 1) % q->size == q->front)
printf ("Queue is Full");
else
{
q->rear = (q->rear + 1) % q->size;
q->Q[q->rear] = x;
}
}
int
dequeue (struct Queue *q)
{
int x = -1;
if (q->front == q->rear)
printf ("Queue is Empty\n");
else
{
q->front = (q->front + 1) % q->size;
x = q->Q[q->front];
}
return x;
}
void
Display (struct Queue q)
{
int i = q.front + 1;
do
{
printf ("%d ", q.Q[i]);
i = (i + 1) % q.size;
}
while (i != (q.rear + 1) % q.size);
printf ("\n");
}
int
main ()
{
struct Queue q;
create (&q, 5);
enqueue (&q, 10);
enqueue (&q, 20);
enqueue (&q, 30);
enqueue (&q, 40);
enqueue (&q, 50);
enqueue (&q, 60);
Display (q);
printf ("%d ", dequeue (&q));
return 0;
}
//Queue using Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
} *front = NULL, *rear = NULL;
void
enqueue (int x)
{
struct Node *t;
t = (struct Node *) malloc (sizeof (struct Node));
if (t == NULL)
printf ("Queue is FUll\n");
else
{
t->data = x;
t->next = NULL;
if (front == NULL)
front = rear = t;
else
{
rear->next = t;
rear = t;
}
}
}
int
dequeue ()
{
int x = -1;
struct Node *t;
if (front == NULL)
printf ("Queue is Empty\n");
else
{
x = front->data;
t = front;
front = front->next;
free (t);
}
return x;
}
void
Display ()
{
struct Node *p = front;
while (p)
{
printf ("%d ", p->data);
p = p->next;
}
printf ("\n");
}
int
main ()
{
enqueue (10);
enqueue (20);
enqueue (30);
enqueue (40);
enqueue (50);
Display ();
printf ("%d ", dequeue ());
return 0;
}
|
C
|
#ifndef __SIMPLE_JSON_VALUE_H__
#define __SIMPLE_JSON_VALUE_H__
#include "simple_json_list.h"
#include "simple_json_string.h"
typedef enum
{
SJVT_NULL,
SJVT_Object,
SJVT_Array,
SJVT_String
}SJValueTypes;
/**
* @brief this is the abstract container structure for all json data
* This structure may be an object, array, string, null, boolean value, integer or float
*/
typedef struct SJson_S
{
SJValueTypes sjtype; /**<internal tracking of the type. DO NOT TOUCH*/
struct
{
SJList *array; /**<an array or values or an array of pairs*/
SJString *string; /**<the string if this is a string type*/
}v; /**<union of possible values*/
SJString *(*get_string)(struct SJson_S *json); /**<pointer to the function to convert this into json string*/
void (*json_free)(struct SJson_S *json); /**<pointer to the function to free this json*/
struct SJson_S *(*copy)(struct SJson_S *json); /**<pointer to the function to copy this json*/
}SJson;
/**
* @brief allocate a new empty json object
* @return NULL on error or a new json object
*/
SJson *sj_new();
/*forward declaration, documented in simple_json.h*/
void sj_free(SJson *sjs);
/**
* @brief make a jason value object out of a string
* @param string the string to convert
* @note the original string is put into the SJson object and is no longer owned by you do not free it!
* @return NULL on error or the newly allocated and set SJson object
*/
SJson *sj_string_to_value(SJString *string);
/**
* @brief get the contents of the string back formatted and escaped for json
* @param string the json string to conver
* @return NULL on error or the converted string
*/
SJString *sj_string_to_json_string(SJson *string);
/**
* @brief convert the json value into a json string
* @param json the value to convert
* @return NULL on error or the json string
*/
SJString *sj_value_to_json_string(SJson *json);
#endif
|
C
|
#define _GNU_SOURCE
#include<signal.h>
#include<sys/wait.h>
#include"library/common.h"
#include"library/merge_sort.h"
#include"library/priority.h"
#include"library/heap.h"
char N[MAX_PROCESS_NUM][PROCESS_NAME];
unsigned int R[MAX_PROCESS_NUM], T[MAX_PROCESS_NUM];
extern int nProcess;
extern int idProcess[MAX_PROCESS_NUM];
extern pid_t pid[MAX_PROCESS_NUM];
extern int ptr_Ready;
extern int run;
int nFinish = 0;
int now_time = 0;
int counting_time = 0;
struct Node *heap_root = NULL;
#define BLOCK_SIGCHILD() \
sigset_t set, oset; \
do \
{ \
sigfillset(&set); \
sigprocmask(SIG_BLOCK, &set, &oset); \
}while(0)
#define UNBLOCK_SIGCHILD() sigprocmask(SIG_SETMASK, &oset, NULL)
#define WAIT_CHILD() do \
{ \
BLOCK_SIGCHILD(); \
while(heap_root != NULL && waitpid(pid[heap_root->index], NULL, WNOHANG) != 0) \
{ \
nFinish++; \
heap_root = pop_heap(heap_root); \
run = 0; \
if(nFinish == nProcess) \
exit(0); \
} \
UNBLOCK_SIGCHILD(); \
}while(0)
void sig_child(int signum)
{
wait(NULL);
nFinish++;
heap_root = pop_heap(heap_root);
run = 0;
if(nFinish == nProcess)
exit(0);
}
void increase_next_process_priority()
{
BLOCK_SIGCHILD();
int i1 = heap_root->index;
heap_root = pop_heap(heap_root);
SET_PRIORITY(pid[i1], SCHED_FIFO, PRIORITY_HIGH);
WAIT_CHILD();
if(heap_root)
{
int i2 = heap_root->index;
SET_PRIORITY(pid[i2], SCHED_FIFO, PRIORITY_INIT);
}
heap_root = insert_heap(heap_root, T[i1], i1);
UNBLOCK_SIGCHILD();
}
void decrease_next_two_processes_priority()
{
BLOCK_SIGCHILD();
if(!run || heap_root == NULL)
return;
int i1 = heap_root->index;
heap_root = pop_heap(heap_root);
T[i1] -= counting_time;
WAIT_CHILD();
if(heap_root)
{
int i2 = heap_root->index;
SET_PRIORITY(pid[i2], SCHED_FIFO, PRIORITY_LOW);
}
SET_PRIORITY(pid[i1], SCHED_FIFO, PRIORITY_LOW);
heap_root = insert_heap(heap_root, T[i1], i1);
counting_time = 0;
UNBLOCK_SIGCHILD();
}
void run_next_process()
{
BLOCK_SIGCHILD();
int nextRun = heap_root->index;
SET_PRIORITY(pid[nextRun], SCHED_FIFO, PRIORITY_HIGH);
run = 1;
counting_time = 0;
UNBLOCK_SIGCHILD();
}
void change_priority()
{
WAIT_CHILD();
BLOCK_SIGCHILD();
if(!run && heap_root != NULL)
run_next_process();
if(run && heap_root != NULL)
increase_next_process_priority();
UNBLOCK_SIGCHILD();
}
int main (void)
{
READ_INPUT();
for(int i = 0; i < nProcess; i++)
idProcess[i] = i;
sort(nProcess, idProcess, T);
sort(nProcess, idProcess, R);
SIGACT_SIGCHILD();
int next_Ready = idProcess[ptr_Ready];
for(int t = 0;; t++)
{
change_priority();
while(ptr_Ready < nProcess && t == R[next_Ready])
{
decrease_next_two_processes_priority();
create_process(&pid[next_Ready], N[next_Ready], next_Ready, T[next_Ready]);
heap_root = insert_heap(heap_root, T[next_Ready], next_Ready);
next_Ready = idProcess[ptr_Ready++];
change_priority();
}
unit_time();
counting_time++;
now_time++;
WAIT_CHILD();
}
}
|
C
|
/*
============================================================================
Name : ElGamal-Test.c
Author : Albert Soliz Team 19
Version :
Copyright : Uses mini-gmp as the bignum library. Open-source.
Description : ElGamal Algorithm in C.
============================================================================
*/
#define CLOCKID CLOCK_REALTIME
#define SIG SIGALRM
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <time.h>
#include "mini-gmp.c"
//try to implement from gmp.h into mini-gmp.h to cut size of file
//Based on Lecture 15: Elgamal Encryption Scheme by Christof Paar
int time_diff(struct timeval * tp1, struct timeval * tp2) {
long sec = tp2->tv_sec - tp1->tv_sec;
long musec = tp2->tv_usec - tp1->tv_usec;
if (musec < 0) {
musec += (int)1e6;
sec--;
}
printf("\nSeconds:%ld \n",sec);
printf(" microsec:%ld \n",musec);
return sec;
}
int send_output(mpz_t message1,mpz_t message2){
int size1 = mpz_sizeinbase(message1,10);
size1 = size1 + 2;
char t[size1];
char * a = mpz_get_str(t,10,message1);
printf("%s\n",a);
int size2 = mpz_sizeinbase(message2,10);
size2 = size2 + 2;
char t2[size2];
char * b = mpz_get_str(t2,10,message2);
printf("%s\n",b);
FILE* fd;
//char* filename = "/home/bitnami/progs/output.txt";
char* filename1 = "./output.txt";
char* filename2 = "C:/Eclipse/Workspace/ELGAMAL-Test/src/output_ELGAMAL.txt";
int errno;
fd = fopen(filename1,"w+");
if(fd != NULL){
printf("Writing outputfile...\n");
fputs("c1=",fd);
fputs(a,fd);
fputs("\nc2=",fd);
fputs(b,fd);
fclose(fd);
}
else {
printf("\nfd failed:%s\n",strerror(errno) );
return -1;
}
return 0;
}
/* Tranform string from char array to decimal string
* */
int string_to_decimal(char * in, mpz_t out){
char text_message[] = "Hello";
printf("Input:%s\n",text_message);
//should be decimal 72,101,108,108,111
//(+100) to ensure each ascii is atleast 3digits long.
//172,201,208,208,211;
char * c = text_message;
char message_fixed[48];//TODO assumes only 16chars are ever GIVEN; Error check
message_fixed[0] = '\0';
printf ("message_fixed:%s\n", message_fixed);
//3digits per char
char temp[4];
temp[3] = '\0';
while(*c != '\0'){
printf("%c , ",*c);
printf(" decimal:%d \n",((int)*c)+100);
int num = 0;
num = ((int)*c);
num = num + 100;//num holds 3digit num
printf("%d",num);
printf ("message_fixed before:%s\n", message_fixed);
//TODO figure way to remove sprintf, uneccessary library for 1 function
sprintf(temp, "%d", num);//copy num(int) into temp(char array)
//temp should be ###
printf ("temp is now: %s\n",temp);
strcat(message_fixed,temp);
printf ("message_fixed is now:%s\n", message_fixed);
c++;
}
//mpz_init_set_str(message,"172201208208211",10);
mpz_init_set_str(out,message_fixed,10);
int base = 10;
printf("\n");
size_t print_size0 = mpz_out_str(stdout ,base , out);//output p to stdout return 0 if error
printf("\nDone with out,\nsize:%ld",print_size0);
printf("\n\n");
printf("Output:%s",message_fixed);
//172,201,208,208,211;
return 0;
}
int decimal_to_string(mpz_t in, char * out){
char decimal_message[] = "172201208208211";
//
printf("\nInput:%s\n",decimal_message);
char * c = decimal_message;
char message_fixed[48];//TODO assumes only 16chars are ever GIVEN; Error check
message_fixed[0] = '\0';
printf ("message_fixed before:%s\n", message_fixed);
//3digits per char
char temp[4]; //hold 3 digit
temp[3] = '\0';
int letters = 0;
int num_digits = 0;
//count number of letters = len / 3;
while(*c != '\0'){
num_digits++;
c++;
}
letters = num_digits/3;
printf("Num letters:%d", letters );
int a = 0;
c = decimal_message;
int parsed_num = 0;
while(*c != '\0'){
printf("%c , ",*c);
int dig = 0;
printf(" decimal:%c \n",*c);
dig = (int)*c;
printf ("message_fixed:%s\n", message_fixed);
//get 3 dig into char temp
temp[a] = dig;
a++;
if(a > 2 ){
a = 0;
//sprintf(temp, "%d", dig);//copy dig into temp
printf("temp is now: %s\n", temp);
//turn temp from digit to ascii by -100 then cast char
parsed_num = atoi(temp);
//fix the initial padding form str-dec conversion
parsed_num = parsed_num - 100;
printf("parsed_num is now: %d\n", parsed_num);
//ascii?
char parsed_letter[2];
parsed_letter[0] = (char)parsed_num;
parsed_letter[1] = '\0';
printf("parsed_letter is now: %c\n", parsed_letter[0]);
strcat(message_fixed,parsed_letter);
printf("message_fixed is now:%s\n", message_fixed);
}
c++;
//reset temp;
}
//mpz_init_set_str(message,"172201208208211",10);
/*mpz_init_set_str(in,message_fixed,10);
int base = 10;
printf("\n");
size_t print_size0 = mpz_out_str(stdout ,base , in);//output p to stdout return 0 if error
printf("\nDone with in,\nsize:%d",print_size0);
printf("\n\n");
*/
printf("Output:%s",message_fixed);
//"Hello"
return 0;
}
int encrypt_message(mpz_t message, mpz_t p, mpz_t q, mpz_t g ,mpz_t X,mpz_t c1,mpz_t c2){
//from https://www.di-mgt.com.au/public-key-crypto-discrete-logs-3-elgamal.html
//input p,q,g, recipeint public key X, message m (0,p-1)
//ouput ciphertext (c1,c2)
printf("\n\nEncrypting message...\n");
int base = 16;
printf("\n");
size_t print_size10 = mpz_out_str(stdout ,base , message);//output p to stdout return 0 if error
printf("\nusing message:,\nsize:%ld",print_size10);
printf("\n\n");
//choose k from 1 -> p-1;
mpz_t k;
mpz_t temp1;
mpz_t temp2;
mpz_t temp3;
mpz_init(temp1);
mpz_init(temp2);
mpz_init(temp3);
mpz_init(k);
mpz_t exp;
mpz_init(exp);
//set k = random for every message?;
mpz_init_set_str(k,"145654165165",10);
//c1 = g^k mod p
mpz_powm(c1,g,k,p);//c1
//m = message
//B = already set
//temp1 = m mod p
mpz_mod(temp1,message,p);
//Compute c2 = m * X^k mod p
//temp2 = powm X ^k mod p
mpz_powm(temp2, X,k,p);
//temp3 = (temp1 * temp2 ) mod p
//(A*B) mod n = (a mod n * b mod n) mod n
mpz_mul(temp3,temp1,temp2);
mpz_mod(c2,temp3,p);
//print
printf("\n");
size_t print_size0 = mpz_out_str(stdout ,base , c1);//output p to stdout return 0 if error
printf("\nDone encrypting with c1,\nsize:%ld",print_size0);
printf("\n\n");
printf("\n");
size_t print_size1 = mpz_out_str(stdout ,base , c2);//output p to stdout return 0 if error
printf("\nDone encrypting with c2,\nsize:%ld",print_size1);
printf("\n\n");
mpz_clear(temp1);
mpz_clear(temp2);
mpz_clear(temp3);
mpz_clear(exp);
mpz_clear(k);
//return c1,c2
return 0;
}
//https://www.di-mgt.com.au/public-key-crypto-discrete-logs-3-elgamal.html
int decrypt_message(mpz_t c1,mpz_t c2, mpz_t p, mpz_t q, mpz_t g, mpz_t x, mpz_t message){
//input p,q,g, recipeints private key x, ciperhetext (c1,c2)
//output m = message
printf("\n\nDecrytpting messsagee..\n");
int base = 16;
printf("\n");
size_t print_size10 = mpz_out_str(stdout ,base , c1);//output p to stdout return 0 if error
printf("\nusing c1:,\nsize:%ld",print_size10);
printf("\n\n");
size_t print_size11 = mpz_out_str(stdout ,base , c2);//output p to stdout return 0 if error
printf("\nusing c2:,\nsize:%ld",print_size11);
printf("\n\n");
mpz_t temp1;
mpz_t temp2;
mpz_t temp3;
mpz_init(temp1);
mpz_init(temp2);
mpz_init(temp3);
mpz_t exp;
mpz_init(exp);
//Compute m = c1^(p−x−1) c2 mod p
//aka (c1^p-x-1 mod p * c2 mod p ) mod p
//set exp = p - x - 1;
mpz_sub(exp,p,x);//p - x
unsigned long int oper_1 = 1;
mpz_sub_ui(exp,exp,oper_1);//p-b-1;
//set temp1 = c1^exp mod p;
mpz_powm(temp1,c1,exp,p);
//set temp2 = c2 mod p;
mpz_mod(temp2,c2,p);
mpz_mul(temp3,temp1,temp2);//line -10
//m = temp3 mod p
mpz_mod(message,temp3,p);
printf("\n");
size_t print_size0 = mpz_out_str(stdout ,base , message);//output p to stdout return 0 if error
printf("\nDone decrypting: message_dec,\nsize:%ld",print_size0);
printf("\n\n");
mpz_clear(exp);
mpz_clear(temp1);
mpz_clear(temp2);
mpz_clear(temp3);
//return m
return 0;
}
//based on theory/technique from https://www.di-mgt.com.au/multiplicative-group-mod-p.html
int generate_p_q_g(mpz_t p, mpz_t q , mpz_t g){
//select a prime p so that p = jq + 1 where j is a large even integer
//sometimes called the cofactor
//set q as 256 bit prime = 78 digits //https://security.stackexchange.com/questions/37907/how-long-is-a-2048-bit-rsa-key
//set p as prime 617 digit long
//mpz_init_set_str(pp,"259285516004991237904610998519859774324030594532751736827621729122927392202102856447445102732032054909127076144987063481173324548641005957405057813533022233920924436586536106720985119936293052303884274172392989827541435411699989981233114965119198963954361280362382857929807678478402693362461823089998035361280362382857929807678478402693362461823089998035361280362382857929807678478402693362461823089998035361280362382857929807678478402693362461823089998035361280362382857929807678478402693362461823089998035361280362382857929807678478402693362461823089998035361280362382857929807678478402693362461823089998035361280529461736109787829377629426551503887896042799049180307475911600113536618063604052",10);
//mpz_init_set_str(p,"19327210897467885519624495407304217845488409100133554803661172025039322784872775172789521895444178690740428588185031695453815386756662619555849446656794905221115788002016245291768283472480460523777510973085032471711187806590185987219179345022033106753600355795626394426859896564719805266547324204357196851217",10);
//1932 test vector
//mpz_init_set_str(q,"983633858469108611936846792207646525014934079943",10);
//98 test vector
//mpz_init_set_str(qq,"157662021640230088962448271877515019766202164023008896244827187751506546546544",10);
//TODO remove hardcoded test vector
//mpz_init_set_str(g,"2008851267811649301382055697326002225321501629224616043097959307844472637339783779480891271906681929732776937543331689329117914118665148580824850572191418544875109802154341862162654424065963144063936607375606796563706389362731767772194368576684632589065496658911743756860379357301492526015846031839304359976",10);
//print p & alpha
unsigned long int oper_1 = 1;
mpz_t j;
mpz_init_set_str(j,"19648785705229832512739279235719869326994578857372093636756123297040568424679124645400612341931690579457038046947983396198878406475643907265436455907971703045747694698970488141521321179649598545010351796154042242157997633368825998252795580916414671992092563312",10);
//19 is test vector
//mpz_init_set_str(j,"1644565465465465165165465465131651646548787654321326549879875316548435465494513515687546515486876546516516548488765465165184989874654654849879873213216546541332165165454651616482718775150197662021640230088962448271877515065465482718775150197662021640230088962448271877515065465482718775150197662021640230088962448271877515065465482718775150197662021640230088962448271877515065465482718775150197662021640230088962448271877515065465482718775150197662021640230088962448271877515065465482718775150197662021640230088962448271877515065465482718775150197662021640230088962448271877515065465482718775150197662021640230088962448",10);
int not_passed = 1;
int q_found = 0;
mpz_t temp;
mpz_init(temp);
while(not_passed){
//find q until prime
q_found = mpz_probab_prime_p(q ,50);//test if q probably a prime
if(q_found == 0){
mpz_add_ui(q, q, oper_1);//increment q by 1
}
//test q is prime?
if(q_found > 0){//if p is prime, q is prime factor, j is large even integer
//if random h 1<h<p-1 & g = h^j (mod p )
//if g > 1 done; else new h
int p_found = 0;
int p_continue = 1;
//test random ints such that p = qz + 1;
while(p_continue){
//test if p = qj + 1 is prime
//set p to value
//set temp = q*j;
mpz_mul(temp, q , j);
//set p to temp+1
mpz_add_ui(p, temp, oper_1);
//test new p = qz + 1
p_found = mpz_probab_prime_p(p ,50);//test again
if(p_found > 0){
p_continue = 0;//exit iwhiel loop
}
if(p_found == 0){
//if not add 1 to j reloop
mpz_add_ui(j, j , oper_1);
}
}//p cont
not_passed = 0;//escape global while looop
}
}//not passed
// p = qj + 1;
//make g
//j = p-1 / q
//set g = h^( (p-1)/q ) mod p
//set g = h^j mod p
mpz_t m;
mpz_t exp;
mpz_init(m);
mpz_init(exp);
mpz_t h;
mpz_init_set_str(h,"54165156651165",10);//TODO make actually random later
mpz_t p_sub1;
mpz_init(p_sub1);
mpz_t quotient;
mpz_t remainder;
mpz_init(quotient);
mpz_init(remainder);
//https://crypto.stackexchange.com/questions/56155/primitive-root-of-a-very-big-prime-number-elgamal-ds
/*
//m = random integer m modulo p is generated
//1738 mod
mpz_mod(m, h, p);//TODO remove this
int base = 10;
printf("\n");
size_t print_size10 = mpz_out_str(stdout ,base , m);//output p to stdout return 0 if error
printf("\nDone with m,\nsize:%d",print_size10);
printf("\n\n");
*/
// set exp = (p−1)/q
//exp = j
mpz_sub_ui(p_sub1, p , oper_1);//p_sub1 = p-1
mpz_cdiv_qr(exp,remainder ,p_sub1, q);//TODO check if div is exact or not?
unsigned long int oper_0 = 0;
int fail = 1;
while(fail==1){
//printf("FAILED TO find quotient with nonremainder\n\n");
int comp1 = mpz_cmp_ui(remainder,oper_0);
if(comp1 != 0){///add one to h rerun till not -1
mpz_add_ui(h,h,oper_1);
mpz_cdiv_qr(exp, remainder ,p_sub1, q);
}
if(comp1 == 0){
fail = 0;//exit whileloop
}
}
//https://www.di-mgt.com.au/public-key-crypto-discrete-logs-1-diffie-hellman.html
mpz_powm(g, h , j , p);//Set rop to base exp mod mod.
//TODO add powm vs hardcode
fail = 1;
while(fail==1){
int comp = mpz_cmp_ui(g,oper_1);//check if g == 1 //aka g > 1; g < p-1
if(comp == 0){
printf("\nFAILD TO FIND g != 1;\n");
printf("\n\nNeed to test with new value m or h");
return -1;
}
if(comp != 0){
fail = 0;//exit whileloop
}
}
//check that g !=1
mpz_clear(quotient);
mpz_clear(remainder);
mpz_clear(exp);
mpz_clear(h);
mpz_clear(p_sub1);
/*
printf("\n");
size_t print_size0 = mpz_out_str(stdout ,base , qq);//output p to stdout return 0 if error
printf("\nDone with q,\nsize:%d",print_size0);
printf("\n\n");
size_t print_size = mpz_out_str(stdout ,base , pp);//output p to stdout return 0 if error
printf("\nDone with p,\nsize:%d",print_size);
printf("\n");
size_t print_size1 = mpz_out_str(stdout ,base , j);//output p to stdout return 0 if error
printf("\nDone with j,\nsize:%d",print_size1);
printf("\n");
printf("\n");
size_t print_size2 = mpz_out_str(stdout ,base , gg);//output p to stdout return 0 if error
printf("\nDone with g,\nsize:%d",print_size2);
printf("\n");
*/
/*
mpz_clear(gg);
mpz_clear(pp);
mpz_clear(qq);
mpz_clear(j);*/
mpz_clear(temp);
return 0;
}
int generate_X_x(mpz_t p, mpz_t q, mpz_t g, mpz_t x, mpz_t X){
//input p,q,g
//output x = priv, X = publickey
//select x 2 -> q-2
//TODO fix this
//compute X = g^x mod p
mpz_powm(X,g,x,p);//
//return x, X//keep 'x' secret
int base = 10;
printf("\n");
size_t print_size0 = mpz_out_str(stdout ,base , X);//output p to stdout return 0 if error
printf("\nDone with X,\nsize:%ld",print_size0);
printf("\n\n");
return 0;
}
int generate_Z_x(mpz_t p, mpz_t q, mpz_t g, mpz_t X, mpz_t y, mpz_t Z){//computation of shared secret by party Y
//input p,q,g, X,y
//Shared secret Z
//check 1 < X < p
int temp = mpz_cmp(X,p);
if(temp >= 0){
return -1;
}
//check X^q mod p ==1
//TODO do this ^^^
//compute Z = X^y mod p
mpz_powm(Z,X,y,p);
//return Z
int base = 10;
printf("\n");
size_t print_size0 = mpz_out_str(stdout ,base , Z);//output p to stdout return 0 if error
printf("\nDone with Z from a,\nsize:%ld",print_size0);
printf("\n\n");
return 0;
}
int ELGAMAL(mpz_t p , mpz_t q,mpz_t g, mpz_t j ) {
printf("ElGamal.c\n\n"); /* prints ElGamal.c*/
//select public parameters : p & alpha
//p being a "safe prime" is an integer p which is such that both p and (p−1)/2 are prime
//cuts on computational time if p is safeprime according to
//https://crypto.stackexchange.com/questions/56155/primitive-root-of-a-very-big-prime-number-elgamal-ds
mpz_t A;
mpz_t B;
mpz_t a;
mpz_t b;
mpz_init_set_str(a,"443154410456340133792289316319263982636340525614",10);
mpz_init_set_str(b,"708552627548105121354432083524985769585714694203",10);
mpz_init(A);
mpz_init(B);
mpz_t Z;
mpz_init(Z);
mpz_t message;
mpz_t message_dec;
mpz_init_set_str(message,"172201208208211",10);
mpz_init(message_dec);
mpz_t c1;
mpz_t c2;
mpz_init(c1);
mpz_init(c2);
//generate parameters
generate_p_q_g(p, q, g);
int base = 16;
printf("\nUSING P : ");
size_t print_size0 = mpz_out_str(stdout ,base , p);//output p to stdout return 0 if error
printf("\nMAIN:p,\nsize:%ld",print_size0);
printf("\n\n");
size_t print_size1 = mpz_out_str(stdout ,base , q);//output p to stdout return 0 if error
printf("\nMAIN:q,\nsize:%ld",print_size1);
printf("\n\n");
size_t print_size2 = mpz_out_str(stdout ,base , g);//output p to stdout return 0 if error
printf("\nMAIN:g,\nsize:%ld",print_size2);
printf("\n\n");
//generate big X from little x
generate_X_x(p, q, g, a , A);
generate_X_x(p, q, g, b , B);
//generate Z from little x
generate_Z_x(p, q, g, B , a, Z);
generate_Z_x(p, q, g, A , b, Z);
//test vectors from : https://www.di-mgt.com.au/public-key-crypto-discrete-logs-1-diffie-hellman.html
//string_to_decimal(str ,message);
struct timeval enc_start, enc_end; /* Used to compute elapsed time. */
struct timeval dec_start, dec_end; /* Used to compute elapsed time. */
int pass = 0;
signed long int cnt = 0;
signed long int y = 0;
time_t tim;
srand( (unsigned) time(&tim) );
signed long int random1 = rand();
signed long int random2 = rand();
for(y = 0; y < 100; y++){//TODO too long to run
random1 = rand();
random2 = rand();
mpz_t val;mpz_init(val);
mpz_t ra1;mpz_init_set_si(ra1,random1);mpz_t ra2;mpz_init_set_si(ra2,random2);
// val = ra1 ^ 8 * ra2 ^ 8
mpz_addmul(val,ra1 ,ra2 );//val = ra1 * ra2;30k*30k
mpz_addmul(val,ra1 ,ra2 );//val = ra1 * ra2;
mpz_addmul(val,ra1 ,ra2 );//val = ra1 * ra2;
mpz_addmul(val,ra1 ,ra2 );//val = ra1 * ra2;
mpz_addmul(val,ra1 ,ra2 );//val = ra1 * ra2;12digits
mpz_addmul(val,ra1 ,ra2 );//val = ra1 * ra2;
mpz_addmul(val,ra1 ,ra2 );//val = ra1 * ra2;20digits
mpz_addmul(val,ra1 ,ra2 );//val = ra1 * ra2;
mpz_set(message ,val);//set msg to random1 * random2;
gettimeofday(&enc_start, 0); // start timer
encrypt_message(message, p, q , g, B, c1, c2);//encrypt from A to B
gettimeofday(&enc_end, 0);
mpz_t message_copy;
mpz_init(message_copy);
mpz_add(message_copy,message_copy,message);//0-> 0+x
gettimeofday(&dec_start, 0); // start timer
decrypt_message(c1 , c2, p, q , g, b, message_dec);//decrypt a msesgae from A, by B
gettimeofday(&dec_end, 0);
//test if message_copy == message
pass = mpz_cmp(message_copy,message_dec);
if(pass == 0){
printf("Time to encrypt: ");
time_diff(&enc_start, &enc_end);
printf("Time to decrypt: ");
time_diff(&dec_start, &dec_end);
//send_output(c1, c2);
cnt++;
}
mpz_clear(message_copy);
mpz_clear(val);
}
printf("Passed %ld/%ld\n",cnt,y);
mpz_init_set_str(message, "1976620216402300889624482718775150",10);
encrypt_message(message, p, q , g, B, c1, c2);//encrypt from A to B
mpz_out_str(stdout ,10 ,c1);//output arg2 to stdout return 0 if error
mpz_out_str(stdout, 10, c2);//messagepart2
send_output(c1,c2);
decrypt_message(c1 , c2, p, q , g, b, message_dec);//decrypt a msesgae from A, by B
//decimal_to_string(message, str);
printf("\n\n");
size_t print_size6 = mpz_out_str(stdout ,base , message_dec);//output p to stdout return 0 if error
printf("\nMAIN:message_dec:,\nsize:%ld",print_size6);
printf("\n\n");
mpz_clear(c1);
mpz_clear(c2);
mpz_clear(message);
mpz_clear(message_dec);
mpz_clear(g);
mpz_clear(A);
mpz_clear(B);
mpz_clear(Z);
mpz_clear(a);
mpz_clear(b);
return 0;
}
int main(int argc, char * argv[]) {
mpz_t test_p;
mpz_t test_q;
mpz_t test_g;
mpz_t test_j;
/*
mpz_init_set_str(p,"19327210897467885519624495407304217845488409100133554803661172025039322784872775172789521895444178690740428588185031695453815386756662619555849446656794905221115788002016245291768283472480460523777510973085032471711187806590185987219179345022033106753600355795626394426859896564719805266547324204357196851217",10);
//1932 test vector
mpz_init_set_str(q,"983633858469108611936846792207646525014934079943",10);
//98 test vector
//mpz_init_set_str(qq,"157662021640230088962448271877515019766202164023008896244827187751506546546544",10);
//TODO remove hardcoded test vector
mpz_init_set_str(g,"2008851267811649301382055697326002225321501629224616043097959307844472637339783779480891271906681929732776937543331689329117914118665148580824850572191418544875109802154341862162654424065963144063936607375606796563706389362731767772194368576684632589065496658911743756860379357301492526015846031839304359976",10);
//print p & alpha
unsigned long int oper_1 = 1;
//mpz_t j;
mpz_init_set_str(j,"19648785705229832512739279235719869326994578857372093636756123297040568424679124645400612341931690579457038046947983396198878406475643907265436455907971703045747694698970488141521321179649598545010351796154042242157997633368825998252795580916414671992092563312",10);
*/
mpz_init_set_str(test_p,"19327210897467885519624495407304217845488409100133554803661172025039322784872775172789521895444178690740428588185031695453815386756662619555849446656794905221115788002016245291768283472480460523777510973085032471711187806590185987219179345022033106753600355795626394426859896564719805266547324204357196851217",10);
mpz_init_set_str(test_q,"983633858469108611936846792207646525014934079943",10);
mpz_init_set_str(test_g,"2008851267811649301382055697326002225321501629224616043097959307844472637339783779480891271906681929732776937543331689329117914118665148580824850572191418544875109802154341862162654424065963144063936607375606796563706389362731767772194368576684632589065496658911743756860379357301492526015846031839304359976",10);
mpz_init_set_str(test_j,"19648785705229832512739279235719869326994578857372093636756123297040568424679124645400612341931690579457038046947983396198878406475643907265436455907971703045747694698970488141521321179649598545010351796154042242157997633368825998252795580916414671992092563312",10);
int opt = 0;
while ((opt = getopt(argc, argv, "p:q:")) != -1) {
switch (opt) {
case 'p':
mpz_init_set_str(test_p,optarg,16);
mpz_out_str(stdout ,16 ,test_p);//output
printf("\n");
break;
case 'q':
mpz_init_set_str(test_q,optarg,16);
mpz_out_str(stdout ,16 ,test_q);//output
break;
case 'j':
mpz_init_set_str(test_j,optarg,16);
mpz_out_str(stdout, 16, test_p);//output
break;
}
}
//test primality according to 'safe-prime' elgamal method
printf("Testing primality of p: ");
int prime_error_p = mpz_probab_prime_p(test_p,50);//test if prime
int prime_error_q = mpz_probab_prime_p(test_q,50);//test if prime
//0 = not prime; 1 = probably prime; 2 = definatley prime
if(prime_error_p > 0 && prime_error_q > 0){
printf("\nTEST result: POSITIVE\nRunning subsequent tests\n");
ELGAMAL(test_p,test_q, test_g, test_j);
}
else{
printf("\nTEST result: NEGATIVE\nTesting parameter generation\n");
struct timeval para_start, para_end; /* Used to compute elapsed time. */
gettimeofday(¶_start, 0);
generate_p_q_g(test_p,test_q, test_g);//parameters
gettimeofday(¶_end, 0);
printf("Time to generate parameters: ");
time_diff(¶_start, ¶_end);
}
mpz_clear(test_p);
mpz_clear(test_q);
printf("Done with ElGamal\n");
return 0;
}
|
C
|
#include<stdio.h>
#define N 40
#define M 4
int main(void){
int i, ih, j, k;
double theta[N]={0}, ripple[M]={0},kakudo[M]={0},counth;
FILE *input, *output;
input =fopen("theta.txt","r");
output =fopen("kakudo.txt","w");
if(input==(NULL)){
printf("thetaのデータが見つかりませんでした。\n");
return 0;
}
while((fscanf(input,"%lf",&counth))!=EOF){
if(counth==1)
fprintf(output,"\n\n");
for(i=0; i<N; i++){
fscanf(input,"%lf",&theta[i]);
if(i!=0 && theta[i]<theta[i-1])
break;
}
ripple[0]=theta[i];
theta[i]=0;
for(i=1; i<M-1; i++)
fscanf(input,"%lf",&ripple[i]);
ripple[3]=ripple[2];
ripple[2]=(ripple[1]-ripple[0])/2+ripple[0];
for(i=0; i<N; i++)
if(theta[i]>=ripple[0])
break;
ih=i;
kakudo[0]=(ripple[0]-theta[i-1]) * (180/ (theta[i]-theta[i-1]) );
if(ih%2==1)
kakudo[0]-=180;
for(j=1; j<=3; j++){
for(k=i; k<N; k++)
if(theta[k]>=ripple[j])
break;
kakudo[j]=(ripple[j]-theta[k-1]) * (180/ (theta[k]-theta[k-1]) );
if(ih%2==1)
kakudo[j]+=(180*(k-i-1));
else
kakudo[j]+=(180*(k-i));
}
// printf("%lf ",ripple[2]);
for(i=0; i<M; i++)
fprintf(output,"%lf ",kakudo[i]);
fprintf(output,"\n");
}
return 0;
}
|
C
|
//
// fileread.c
//
// Copyright (c) 2017 JesseChen <lkchan0719@gmail.com>
//
#include "fileread.h"
/*
* Return the file size of `filename` or -1
*/
size_t
file_size(FILE *stream) {
size_t size = 0;
fseek(stream, 0, SEEK_END);
size = ftell(stream);
rewind(stream);
return size;
}
/*
* read the conetents of `filename` or return NULL
*/
char *
file_read(const char *filename) {
FILE *fh = fopen(filename, "r");
size_t len = file_size(fh);
char *buf = malloc(len + 1);
if(!buf) return NULL;
size_t read = fread(buf, sizeof(char), len, fh);
fclose(fh);
buf[read] = 0;
return buf;
}
/*
* read `stream` until EOF
*/
char *
read_until_eof(FILE *stream) {
off_t len = 0;
char buf[1024];
char *str = malloc(1);
assert(str);
while (!feof(stream) && !ferror(stream)) {
size_t n = fread(buf, 1, 1024, stream);
len += strlen(buf);
str = realloc(str, len);
strncat(str, buf, n);
}
return str;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_add_to_stack.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cghael <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/24 14:31:57 by cghael #+# #+# */
/* Updated: 2019/11/05 13:23:55 by cghael ### ########.fr */
/* */
/* ************************************************************************** */
/*
** This file contains functions which create stack.
*/
#include "fillit_head.h"
/*
** \brief Creates a new node which points left and right to itself and
** head points to a queue of covered nodes from destination list.
** \params new The queue of cowered nodes.
*/
static t_cwr *ft_create_stack_elem(t_list *new)
{
t_cwr *tmp;
tmp = (t_cwr*)malloc(sizeof(t_cwr));
if (!new)
return (NULL);
tmp->right = NULL;
tmp->head = new;
return (tmp);
}
/*
** \brief Creates a new stack node and add it in the end of stack.
** \params new The queue of cowered nodes.
** stack The head of the stack.
*/
t_cwr *ft_add_to_stack(t_cwr **stack, t_list *new)
{
t_cwr *tmp;
if (!stack || !new)
return (NULL);
tmp = ft_create_stack_elem(new);
if (!tmp)
return (NULL);
if (!*stack)
*stack = tmp;
else
{
tmp->right = *stack;
*stack = tmp;
}
return (*stack);
}
|
C
|
#include "holberton.h"
/**
* append_text_to_file - appends text at the end of a file.
* @filename: filename.
* @text_content: string.
* Return: 1 on success, -1 on failure.
*/
int append_text_to_file(const char *filename, char *text_content)
{
int fd, wr;
int lenTextContent;
if (filename == NULL)
return (-1);
fd = open(filename, O_WRONLY | O_APPEND);
if (fd == -1)
return (-1);
lenTextContent = 0;
if (text_content)
{
while (text_content[lenTextContent])
{
lenTextContent++;
}
wr = write(fd, text_content, lenTextContent);
if (wr == -1)
return (-1);
}
close(fd);
return (1);
}
|
C
|
#include "fractol.h"
#include <stdio.h>
/*
int ft_exit(t_mlx *mlx)
{
mlx_destroy_image(mlx->ptr, mlx->img.img_ptr);
mlx_destroy_window(mlx->ptr, mlx->wdw);
exit(1);
}
*/
void ft_error(void)
{
write(2, "Error mlx\n", 10);
exit(1);
}
void ft_init_mlx(t_mlx *mlx)
{
if (!(mlx->ptr = mlx_init()))
ft_error();
if (!(mlx->wdw = mlx_new_window(mlx->ptr, WIN_WIDTH, WIN_HEIGHT, "Fractol")))
ft_error();
if (!(mlx->img.img_ptr = mlx_new_image(mlx->ptr, WIN_WIDTH, WIN_HEIGHT)))
ft_error();
mlx->img.data = (int *)mlx_get_data_addr(mlx->img.img_ptr, &(mlx->img.bpp), &(mlx->img.s_l),
&(mlx->img.endian));
}
int main(void)
{
int i;
int x = 0;
int y = 0;
int z;
int c_r;
int c_i;
int z_r;
int z_i;
int tmp;
t_mlx mlx;
t_img img;
double x1 = -2.1;
double x2 = 0.6;
double y1 = -1.2;
double y2 = 1.2;
z = 0;
int zoom_x = WIN_WIDTH / (x2 -x1);
int zoom_y = WIN_HEIGHT / (y2 -y1);
img = mlx.img;
ft_init_mlx(&mlx);
while (x < WIN_WIDTH)
{
while (y > WIN_HEIGHT)
{
c_r = x / zoom_x + x1;
c_i = y / zoom_y + y1;
z_r = 0;
z_i = 0;
i = 0;
while ((z_r*z_r + z_i*z_i) < 4 && i < 51)
{
tmp = z_r;
z_r = z_r*z_r - z_i*z_i + c_r;
z_i = 2*z_i*tmp + c_i;
if (i == 50)
img.data[z_i * WIN_WIDTH + z_r] = 0xFFFFFF;
// mlx_pixel_put (mlx->ptr, mlx->win, z_r, z_i, 0xFFFFFF);
i++;
}
y++;
}
x++;
}
printf("hello\n");
mlx_put_image_to_window(mlx.ptr, mlx.wdw, mlx.img.img_ptr, 0, 0);
mlx_loop(mlx.ptr);
return (0);
}
|
C
|
//**************************************
// Name: Lexical Analyzer in C
// Description:It will lexically Analyze the given file(C program) and it willgive the various tokens present in it..
// By: Aditya Siddharth Dutt (from psc cd)
//
// Inputs:Input the Complete file name with pateh... It can also be given in the program itsel.. i have commented the section...
//
// Returns:keywords,identifiers,operators,headers,arguments,constants
//
// Side Effects:Be sure the path is correct
//**************************************
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#define MAX_TOKEN_LENGTH 32
#define NAME_ROOT "root"
struct Token;
void keyw(char *p);
void add_token(const char*, const char*);
void print_all_tokens();
void free_token(struct Token *);
void free_tokens();
int i = 0;
int id = 0;
int kernelkw = 0;
int kw = 0;
int num = 0;
int op = 0;
char keys[19][MAX_TOKEN_LENGTH] = { "auto", "break", "case", "continue", "default", "do",
"else", "enum", "for", "goto", "if", "register", "return", "sizeof",
"struct", "switch", "typedef", "union", "while" };
char kernelkeys[16][MAX_TOKEN_LENGTH] = { "__global", "global", "__local", "local",
"__constant", "constant", "__private", "private", "__kernel", "kernel",
"__read_only", "read_only", "__write_only", "write_only",
"__read_write", "read_write" };
char typekeys[64][MAX_TOKEN_LENGTH] = { "char", "const", "double", "extern", "float", "int",
"long", "short", "signed", "static", "unsigned", "void", "volatile",
"bool", "uchar", "ushort", "uint", "ulong", "half", "size_t",
"char2", "char4", "char8", "char16", "uchar2", "uchar4", "uchar8", "uchar16",
"short2", "short4", "short8", "short16", "ushort2", "ushort4", "ushort8", "ushort16",
"int2", "int4", "int8", "int16", "uint2", "uint4", "uint8", "uint16",
"long2", "long4", "long8", "long16", "ulong2", "ulong4", "ulong8", "ulong16",
"float2", "float4", "float8", "float16", "double2", "double4", "double8", "double16",
"half2", "half4", "half8", "half16"
};
FILE *outfile;
int isOutputFile = 0;
int isVerbose = 0;
struct Token {
struct Token* prev;
char* name;
char identification[64];
int offset;
struct Token* next;
};
struct Token* tokens;
struct Token* first;
int offset;
//
typedef struct SN {
char data;
struct SN *link;
}stackN;
stackN *top = NULL;
void push(char item) {
stackN * new = (stackN *)malloc(sizeof(stackN));
new->data = item;
new->link = top;
top = new;
}
char pop() {
char item;
stackN * old = top;
if (top) {
item = old->data;
top = old->link;
free(old);
return item;
}
printf("\n\n Stack is EMPTY ! \n");
}
struct Token* function_token;
void main(int argc, char *argv[]) {
char ch;
char str[25];
char seps[15] = " \t\n,;(){}[]#\"<>";
char oper[] = "!%^&*-+=~|.<>/?";
int j;
char fname[50];
FILE *f1;
//clrscr();
//printf("Argument count : %d\n", argc);
if (argc == 1) {
printf("Usage : cparser input_file_name (-f output_file_name)\n");
return;
}
//scanf("%s",fname);
sprintf(fname, "%s\0", argv[1]);
f1 = fopen(fname, "r");
//f1 = fopen("Input","r");
if (f1 == NULL) {
printf("file not found");
exit(0);
}
if (argc == 2) {
isVerbose = 1;
}
else {
int i;
for (i = 2; i < argc; i++) {
if (!strcmp(argv[i], "-v")) {
isVerbose = 1;
}
else if (!strcmp(argv[i], "-f")) {
if ((!isVerbose && argc == 3) || (isVerbose && argc == 4)) {
printf("Please give the value of -f\n");
exit(1);
}
i++;
sprintf(fname, "%s\0", argv[i]);
outfile = fopen(fname, "w");
if (outfile != NULL) {
isOutputFile = 1;
}
}
}
}
tokens = (struct Token*) malloc(sizeof(struct Token));
tokens->prev = NULL;
tokens->next = NULL;
tokens->name = (char*)malloc(sizeof(char) * (MAX_TOKEN_LENGTH + 1));
tokens->offset = -1;
sprintf(tokens->name, "%s\0", NAME_ROOT);
sprintf(tokens->identification, "%s\0", NAME_ROOT);
first = tokens;
offset = -1;
while ((ch = fgetc(f1)) != EOF) {
offset++;
for (j = 0; j <= 14; j++) {
if (ch == oper[j]) {
char tmp[2];
sprintf(tmp, "%c\0", ch);
add_token(tmp, "operator");
//printf("%c:operator\n",ch);
//if (isOutputFile) {
// fprintf(outfile, "%c:operator\n", ch);
//}
op++;
str[i] = '\0';
keyw(str);
if (tokens->prev != NULL && tokens->prev->prev != NULL) {
if (!strcmp(tokens->prev->identification, "identifier")) {
if (!strcmp(tokens->prev->prev->identification, "type_keyword")) {
sprintf(tokens->prev->identification, "variable_declaration\0");
}
else if (tokens->prev->prev->prev != NULL) {
if (!strcmp(tokens->prev->prev->identification, "operator")
&& !strcmp(tokens->prev->prev->prev->identification, "type_keyword")) {
sprintf(tokens->prev->identification, "variable_declaration\0");
}
}
}
}
}
}
for (j = 0; j <= 14; j++) {
if (i == -1)
break;
if (ch == seps[j]) {
char wds[128];
int m;
if (ch == '#') {
m = 0;
while (ch != '>') {
wds[m++] = ch;
//printf("%c",ch);
//if (isOutputFile) {
// fprintf(outfile, "%c", ch);
//}
ch = fgetc(f1);
offset++;
}
wds[m++] = ch;
wds[m] = '\0';
add_token(wds, "header_file");
//printf("%c:header_file\n",ch);
//if (isOutputFile) {
// fprintf(outfile, "%c:header_file\n", ch);
//}
i = -1;
break;
}
if (ch == '"') {
m = 0;
do {
ch = fgetc(f1);
offset++;
wds[m++] = ch;
//printf("%c",ch);
//if (isOutputFile) {
// fprintf(outfile, "%c", ch);
//}
} while (ch != '"');
wds[m] = '\0';
add_token(wds, "argument");
//printf(":argument\n");
//if (isOutputFile) {
// fprintf(outfile, ":argument\n");
//}
i = -1;
break;
}
str[i] = '\0';
keyw(str);
if (ch == '(') {
if (tokens->prev != NULL) {
if (!strcmp(tokens->identification, "identifier")) {
if (!strcmp(tokens->prev->identification, "type_keyword")) {
sprintf(tokens->identification, "function_declaration");
function_token = tokens;
}
else if (tokens->prev->prev != NULL) {
if (!strcmp(tokens->prev->identification, "operator")
&& !strcmp(tokens->prev->prev->identification, "type_keyword")) {
sprintf(tokens->identification, "function_declaration");
function_token = tokens;
}
}
}
}
}
else if (ch == '{') {
if (function_token != NULL) {
if (top) {
}
else {
sprintf(function_token->identification, "%s/%d", function_token->identification, (offset - 1));
}
push(ch);
}
}
else if (ch == '}') {
if (function_token != NULL) {
pop();
if (top) {
}
else {
sprintf(function_token->identification, "%s,%d\0", function_token->identification, (offset - 1));
}
}
}
else if (ch == ';' || ch == '[') {
if (tokens->prev != NULL) {
if (!strcmp(tokens->identification, "identifier")) {
if (!strcmp(tokens->prev->identification, "type_keyword")) {
sprintf(tokens->identification, "variable_declaration\0");
}
else if (tokens->prev->prev != NULL) {
if (!strcmp(tokens->prev->identification, "operator")
&& !strcmp(tokens->prev->prev->identification, "type_keyword")) {
sprintf(tokens->identification, "variable_declaration\0");
}
}
}
}
}
else if (ch == '\n') {
strcat(tokens->name, "_newline");
}
}
}
if (i != -1) {
str[i] = ch;
i++;
}
else
i = 0;
}
print_all_tokens();
free_tokens();
//printf(
// "\n\nKeywords: %d\nKernel Keywords: %d\nIdentifiers: %d\nOperators: %d\nNumbers: %d\n",
// kw, kernelkw, id, op, num);
if (isOutputFile) {
// fprintf(outfile,
// "\n\nKeywords: %d\nKernel Keywords: %d\nIdentifiers: %d\nOperators: %d\nNumbers: %d\n",
// kw, kernelkw, id, op, num);
fclose(outfile);
}
fclose(f1);
//getch();
}
void print_all_tokens() {
struct Token* tok = first;
tok = tok->next;
while (tok->next != NULL) {
if (isVerbose) {
printf("%s:%s:%d\n", tok->name, tok->identification, tok->offset);
}
if (isOutputFile) {
fprintf(outfile, "%s:%s:%d\n", tok->name, tok->identification,
tok->offset);
}
tok = tok->next;
}
}
void keyw(char *p) {
int k, flag = 0;
for (k = 0; k <= 18; k++) {
if (strcmp(keys[k], p) == 0) {
add_token(p, "keyword");
//printf("%s:keyword\n", p);
//if (isOutputFile) {
// fprintf(outfile, "%s:keyword\n", p);
//}
kw++;
flag = 1;
break;
}
}
for (k = 0; k <= 15; k++) {
if (strcmp(kernelkeys[k], p) == 0) {
add_token(p, "kernel_keyword");
//printf("%s:kernel_keyword\n", p);
//if (isOutputFile) {
// fprintf(outfile, "%s:kernel_keyword\n", p);
//}
kernelkw++;
flag = 1;
break;
}
}
for (k = 0; k <= 63; k++) {
if (strcmp(typekeys[k], p) == 0) {
add_token(p, "type_keyword");
//printf("%s:kernel_keyword\n", p);
//if (isOutputFile) {
// fprintf(outfile, "%s:kernel_keyword\n", p);
//}
kernelkw++;
flag = 1;
break;
}
}
if (flag == 0) {
if (isdigit(p[0])) {
add_token(p, "number");
//printf("%s:number\n", p);
//if (isOutputFile) {
// fprintf(outfile, "%s:number\n", p);
//}
num++;
}
else {
//if(p[0]!=13&&p[0]!=10)
if (p[0] != '\0') {
add_token(p, "identifier");
//printf("%s:identifier\n", p);
//if (isOutputFile) {
// fprintf(outfile, "%s:identifier\n", p);
//}
id++;
}
}
}
i = -1;
}
void add_token(const char* name, const char* indentification) {
struct Token *tok;
int namelen = strlen(name);
tok = (struct Token*) malloc(sizeof(struct Token));
tok->name = (char*)malloc(sizeof(char) * (MAX_TOKEN_LENGTH + 1));
sprintf(tok->name, "%s\0", name);
sprintf(tok->identification, "%s\0", indentification);
if (offset >= namelen) {
tok->offset = offset - namelen;
}
else {
tok->offset = -1;
}
tok->prev = tokens;
tok->next = NULL;
tokens->next = tok;
tokens = tok;
}
void free_token(struct Token *token) {
if (token != NULL) {
if (token->name != NULL) {
free(token->name);
token->name = NULL;
}
free(token);
token = NULL;
}
}
void free_tokens() {
struct Token *tok;
tokens = first;
while (tokens != NULL) {
tok = tokens->next;
free_token(tokens);
tokens = tok;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "../Vector.h"
#include "../interp.h"
int main(int argc, char** argv) {
size_t ndata=10;
size_t ninterp=100;
double step = ((double)ndata)/ninterp;
struct f64vector* x=f64vector_range(ndata);
struct f64vector* y=f64vector_new(ndata);
for (size_t i=0; i<x->size; i++) {
y->data[i] = x->data[i]*x->data[i];
}
for (size_t i=0; i<ninterp; i++) {
double u = step*i;
double v = f64interplin(x, y, u);
printf("%lf %lf\n", u, v);
}
}
|
C
|
#include <stdio.h>
void fun1();
void fun2();
void fun3();
int main()
{
printf("Inside main starting\n");
fun1();
fun2();
fun3();
printf("Inside main: ending\n");
}
|
C
|
#include <stdio.h>
struct node
{
struct node *next;
int data;
};
int n,d,i,n1;
int main(void) {
scanf("%d%d",&n,&d);
while(n!=0&&d!=0)
{
struct node *temp=(struct node *)malloc(sizeof(struct node));
struct node *head;
head=temp;
temp->data=1;
for(i=2;i<=n;i++)
{
temp->next=(struct node *)malloc(sizeof(struct node));
temp=temp->next;
temp->data=i;
}
temp->next=head;
n1=n;
n--;
while(n--)
{ for(i=1;i<d;i++)
{
temp=temp->next;
}
//temp->data=temp->next->data;
temp->next=temp->next->next;
}
printf("%d %d %d\n",n1,d,temp->data);
scanf("%d%d",&n,&d);
}// your code goes here
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef scalar_t__ Oid ;
/* Variables and functions */
int
oid_cmp(const void *p1, const void *p2)
{
Oid v1 = *((const Oid *) p1);
Oid v2 = *((const Oid *) p2);
if (v1 < v2)
return -1;
if (v1 > v2)
return 1;
return 0;
}
|
C
|
#include <stdio.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <signal.h>
#include "socket.h"
/** Crée une socket serveur qui écoute sur toute les interfaces IPv4
de la machine sur le port passé en paramètre . La socket retournée
doit pouvoir être utilisée directement par un appel à accept .
La fonction retourne -1 en cas d ’ erreur ou le descripteur de la
socket créée . */
int creer_serveur(int port)
{
/** Creation de la socket */
int socket_serveur;
socket_serveur = socket(AF_INET, SOCK_STREAM, 0);
if (socket_serveur == -1)
{
perror ("socket_serveur");
return -1;
}
int optval = 1;
if (setsockopt(socket_serveur, SOL_SOCKET, SO_REUSEADDR, &optval,
sizeof(int)) == -1)
perror("Can not set SO_REUSEADDR option");
/* Utilisation de la socket serveur */
/** Configuration de la socket */
struct sockaddr_in saddr;
saddr.sin_family = AF_INET; /* Socket ipv4 */
saddr.sin_port = htons(port); /* Port d ’ écoute */
saddr.sin_addr.s_addr = INADDR_ANY; /* écoute sur toutes les interfaces */
if (bind(socket_serveur, (struct sockaddr *) &saddr , sizeof(saddr)) == -1)
{
perror ("bind socker_serveur");
return -1;
}
/** Démarer l'attente de connexions */
if (listen(socket_serveur,10) == -1)
{
perror("listen socket_serveur");
return -1;
}
return socket_serveur;
}
/* renovie la fonction waitpid*/
void traitement_signal(int sig) {
printf("Signal %d reçu \n", sig);
int status;
waitpid(-1, &status, WNOHANG | WUNTRACED);
}
/* permet d'intialiser les signaux pour ignorer le signal SIGPIPE et
de recuperer le signal SIGCHLD qui renverra sur traitement_signal */
void initialiser_signaux(void)
{
/* if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
{
perror("signal");
}*/
struct sigaction sa;
sa.sa_handler = traitement_signal;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1)
{
perror ("sigaction(SIGCHLD)");
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "grafos.h"
static void free_vertice(Vertice *vertice);
Grafo cria_grafo(int n_vertices, int orientado) {
Grafo grafo = {.n = n_vertices, .orientado = orientado};
grafo.vertices = (Vertice *) malloc(sizeof(Vertice) * n_vertices); // cria n vértices no grafo
// inicializa os vértices apontando para NULL
for (int i = 0; i < n_vertices; ++i) {
grafo.vertices[i].prox = NULL;
}
return grafo;
}
void adiciona_aresta(Grafo *grafo, Aresta aresta) {
Vertice *ultimo;
for (int i = 0; i < 2; i++) {
// encontra o último vértice da lista
ultimo = &grafo->vertices[aresta.ant];
while (ultimo->prox != NULL) {
ultimo = ultimo->prox;
}
ultimo->prox = (Vertice *) malloc(sizeof(Vertice));
ultimo->prox->prox = NULL;
ultimo->v = aresta.prox;
ultimo->peso = aresta.peso;
// se o gráfico não é orientado swap arestas pra fazer o caminho reverso
if (!(grafo->orientado)) {
int aux = aresta.ant;
aresta.ant = aresta.prox;
aresta.prox = aux;
} else break;
}
}
// printa lista de adjacẽncia
void print_grafo(Grafo grafo) {
Vertice vertice;
for (int i = 0; i < grafo.n; ++i) {
printf("[%d] -> ", i);
vertice = grafo.vertices[i];
while (vertice.prox != NULL) {
printf("[%d; %d] -> ", vertice.v, vertice.peso);
vertice = *vertice.prox;
}
printf("NULL\n");
}
}
void free_grafo(Grafo grafo) {
// free cada vértice
for (int i = 0; i < grafo.n; ++i) {
free_vertice(&grafo.vertices[i]);
}
free(grafo.vertices);
}
static void free_vertice(Vertice *vertice) {
if (vertice->prox != NULL) {
free_vertice(vertice->prox);
}
free(vertice->prox);
}
|
C
|
#ifndef __POWER_BAR_H__
#define __POWER_BAR_H__
// In this file we define how we render the health bars of the tanks
#include "body.h"
typedef struct power_bar {
body_t *outer;
body_t *inner;
body_t *power_level;
} power_bar_t;
// Creates a new power bar for the tank and assigns the power_bar field of t1
// to the new power bar
power_bar_t *power_bar_init(body_t *t1, vector_t center);
// Updates the power bar of a tank
void update_power_bar(body_t *t1);
#endif // #ifndef __POWER_BAR_H__
|
C
|
typedef struct
{
int idMarca;
char descripcion[20];
}eMarca;
typedef struct{
int dia;
int mes;
int anio;
}eFecha;
typedef struct{
int idColor;
char nombreColor[20];
}eColor;
typedef struct{
int idAuto;
char patente[7];
int idMarca;
int idColor;
int modeloAnio;
int isEmpty;
}eAuto;
typedef struct{
int idServicio;
char descripcion[25];
int precioServicio;
}eServicio;
/** \brief pongo el estado de los autos en 0
*
* \param array autos
* \param tamanio del array
* \return nada
*
*/
void initAutos(eAuto* list, int len);
/** \brief busco un indice del array vacio
*
* \param array autos
* \param tamanio del array
* \return el indice vacio
*
*/
int findEmptyAuto(eAuto* list, int len);
/** \brief se le pasa una patente por referencia y la busca en el array autos
*
* \param array uatos
* \param tamanio del array
* \param patente que se busca en formato char
* \return el indice si la encontro o -1 si no.
*
*/
int findAutoByPatente(eAuto* list, int len, char* patente);
/** \brief genera un id autoincremental para los autos
* \return devuelve el id.
*
*/
int getIdAuto();
/** \brief pide los datos necesarios para agregar un nuevo auto, los valida y los ingresa.
*
* \param array auto
* \param tamanio del array
* \param array marcas
* \param tamanio del array
* \param array colores
* \param tamanio del array
* \return devuelve 1 si pudo agregar un nuevo auto.
*
*/
int addAuto(eAuto* list, int len, eMarca* marcas, int lenM, eColor* colores, int lenC);
/** \brief se le ingresa un msg o un mensaje error y pregunta si esta seguro.
*
* \param msg
* \param msg error
* \return s si esta seguro n si no.
*
*/
char preguntarSiEstaSeguro(char* msg, char* msgerror);
/** \brief muestra los autosm pide la patente y da la baja logica si el usuario lo desea.
*
* \param array autos
* \param tamanio del array
* \return 1 si dio la baja -1 si no.
*
*/
int removeAuto(eAuto* list, int len);
/** \brief esta funcion sabe mostrar un auto
*
* \param un auto
* \param array colores
* \param tamanio del array
* \param array marcas
* \param tamanio del array
* \return no devuelve nada, solo muestra un auto.
*
*/
void printAuto(eAuto list, eColor* color,int lenc,eMarca* marcas, int lenM);
/** \brief esta funcion sabe mostrar muchos autos
*
* \param array autos
* \param tamanio del array
* \param array marcas
* \param tamanio del array
* \param array colores
* \param tamanio del array
* \return no devuelve nada, solo muestra los autos
*/
void printAutos(eAuto* list, int len, eMarca* marca, int lenM, eColor* color, int lenC);
/** \brief muestra un menu de opciones para acceder a modificaciones
*
* \param
* \param
* \return la opcion elegida en ese menu.
*
*/
int menuModificar();
/** \brief esta funcion modifica parametros de un auto
*
* \param array autos
* \param tamanio del array
* \param array color
* \param tamanio del array
* \param array marcas
* \param tamanio del array
* \return devuelve 1 si pudo modificarlo -1 si no pudo.
*/
int modifyAuto(eAuto* list, int len, eColor* color, int lenc, eMarca* marcas, int lenM);
/** \brief muestra un menu de opciones del abm
*
* \param
* \param
* \return la opcion elegida en ese menu.
*
*/
int menuAbm();
/** \brief muestra los modelos su id e descripcion.
*
* \param array marcas
* \param tamanio array
* \return nada
*
*/
void mostrarModelos( eMarca* marca, int len);
/** \brief muestra los servicicios, su id e precios..
*
* \param array servicios
* \param tamanio array
* \return nada
*
*/
void mostrarServicios(eServicio* servicio, int lenS);
/** \brief muestra los colores id e descripcion.
*
* \param array colores
* \param tamanio array
* \return nada
*
*/
void mostrarColores( eColor* color, int lenC);
/** \brief obtiene la descripcion de los colores
*
* \param array colores
* \param tamanio del array
* \param un ID de color
* \param un puntero a char para copiar la desc del color.
* \return devuelve 1 si pudo copiar la desc del color en el puntero que se ingreso por referencia.
*
*/
int obtenerColores(eColor* colores, int lenC, int idColor, char* desc);
/** \brief obtiene la descripcion de los marcas
*
* \param array marcas
* \param tamanio del array
* \param un ID de marca
* \param un puntero a char para copiar la desc de la marca.
* \return devuelve 1 si pudo copiar la desc de la marca en el puntero que se ingreso por referencia.
*
*/
int obtenerMarcas(eMarca* marcas, int lenM, int idMarca, char* desc);
/** \brief ordena los autos por marcas y patentes.
*
* \param array autos
* \param tamanio del arrray
* \return nada
*
*/
void sortAutos(eAuto* list, int len);
/** \brief se le pasa una id Servicio y la busca en el array servicios
*
* \param array servicios
* \param tamanio del array
* \param id Servicio que se busca en formato int
* \return el indice si lo encontro o -1 si no.
*
*/
int findServicioById(eServicio* servicio, int lenS, int idServicio);
/** \brief veo si hay algun auto cargado en el array para poder setear las flags.
*
* \param array autos
* \param tamanio array
* \return !=-1 si esta cargado o -1 si esta vacio.
*
*/
int findArrayAuto(eAuto* autos, int lenA);
/** \brief pasa una cadena a mayuscula
*
* \param puntero a la cadena
* \return nada modifica la cadena y la pasa a mayuscula
*
*/
void Tstrupr(char* cadena);
/** \brief hardcodea autos en el array.
*
* \param array autos
* \param tamanio del array
* \return nada, solo los ingresa al sistema.
*
*/
void hardCodearAutos(eAuto* autos, int tam);
|
C
|
/*
Write a function that searches for a number in an array of integers. If the number is stored, the function should return the position of its first occurrence, otherwise −1. Write a program that declares an array of integers sorted in ascending order. The program should read an integer and use the function to display its array position.
*/
#include <stdio.h>
int binary_search(int arr[],int num, int size);
int main ()
{
int array[] = {10,20,30,40,50,60,70};
int position,search_num;
printf("Enter the number to search:");
scanf("%d",&search_num);
position = binary_search(array,search_num,sizeof(array)/sizeof(int));
if(position == -1)
printf("The number is not in the array");
else
printf("The first occurrence of number %d is %d",search_num,position);
return 0;
}
int binary_search(int arr[],int num, int size){
int start,middle,end;
start = 0;
end = size-1;
while(start<=end){
middle = (start+end)/2;
if(num<arr[middle]){
end = middle -1;
}
else if(num>arr[middle]){
start = middle+1;
}
else
return middle;
}
return -1;
}
|
C
|
#include "global.h"
#include "ast.h"
void free_pipeline_node(struct s_pipeline_node *node)
{
if (node == NULL)
return;
if (node->commands != NULL)
{
for (int i = 0; i < node->nb_commands; i++)
free_ast_node(node->commands[i]);
free(node->commands);
}
free(node);
}
void free_and_or_node(struct s_and_or_node *node)
{
if (node == NULL)
return;
if (node->left != NULL)
free_ast_node(node->left);
if (node->right != NULL)
free_ast_node(node->right);
free(node);
}
void free_list_node(struct s_list_node *node)
{
if (node == NULL)
return;
if (node->left != NULL)
free_ast_node(node->left);
if (node->right != NULL)
free_ast_node(node->right);
free(node);
}
|
C
|
#include "ButtonsReader.h"
#include "Pin.h"
#include "Sequencer.h"
uint8_t inputsValues = 0;
struct inputsState inputToggle[SR_MAX_BUTTONS];
inline static void ButtonsReader_StartTimerInt(void);
inline static void ButtonsReader_StopTimerInt(void);
void ButtonsReader_Init() {
PIN_Set(SR_LOAD_PIN, PIN_OUTPUT);
PIN_Set(SR_CLOCK_PIN, PIN_OUTPUT);
PIN_Set(SR_OUTPUT_PIN, PIN_INPUT);
PIN_On(SR_LOAD_PIN);
PIN_Off(SR_CLOCK_PIN);
// prescaler to 8
TCCR3B |= (0<<CS32)|(1<<CS31)|(0<<CS30);
// Toggle on compare match
TCCR3A |= (0 << COM3A0)|(1 << COM3A1);
// Enable compare interrupt
TIMSK3 |= (1 << OCIE3A);
// counter range = 10000
OCR3AH = 0x27;
OCR3AL = 0x10;
// Initialize the counter to 0
TCNT3 = 0;
// Set CTC mode
TCCR3B |= 1 << WGM32;
}
inline static void ButtonsReader_StartTimerInt() {
// Enable compare interrupt
TIMSK3 |= (1 << OCIE3A);
}
inline static void ButtonsReader_StopTimerInt() {
// Enable compare interrupt
TIMSK3 |= (0 << OCIE3A);
}
uint8_t ButtonsReader_Read(uint8_t buttonNumber) {
uint8_t mask = 1 << buttonNumber;
return (inputsValues & mask) >> buttonNumber;
}
void ButtonsReader_Store(uint8_t buttonNumber, uint8_t value) {
if (value > 0)
{
inputsValues |= (1 << buttonNumber);
}
else
{
uint8_t mask = ~(1 << buttonNumber);
inputsValues &= mask;
}
}
ISR(TIMER3_COMPA_vect)
{
ButtonsReader_StartTimerInt();
// Store parallel inputs values in the shift register
PIN_Off(SR_LOAD_PIN);
// Inhibit parallel inputs loading
PIN_On(SR_LOAD_PIN);
// Get values
uint8_t buttonId = 0;
for (buttonId = 0; buttonId < SR_MAX_BUTTONS; buttonId++) {
// We got value at the pin, just read and store it
uint8_t pinValue = PIN_Read(SR_OUTPUT_PIN);
if (pinValue > 0) {
pinValue = 1;
}
if (ButtonsReader_Read(buttonId) != pinValue) {
ButtonsReader_Store(buttonId, pinValue);
if (inputToggle[buttonId].btnToggled == 1) {
inputToggle[buttonId].btnToggled = 0;
/*
Here we will change corresponding button flag
*/
switch (buttonId) {
case BUTTON_ST:
sequencerSignals.PLAYING_START_STOP = 1;
break;
case BUTTON_REC:
sequencerSignals.RECORDING_START_STOP = 1;
break;
case BUTTON_RESET:
sequencerSignals.ERASE = 1;
break;
}
} else {
inputToggle[buttonId].btnToggled = 1;
}
}
// We need a positive going edge to have the next value at the SR_OUTPUT_PIN
PIN_On(SR_CLOCK_PIN);
PIN_Off(SR_CLOCK_PIN);
}
ButtonsReader_StartTimerInt();
}
void ButtonsReader_Load() {
}
|
C
|
#include "common.h"
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include "com.h"
#include "commands.h"
#include "consult_constants.h"
typedef enum
{
state_RUNNING,
state_STOPPING,
state_FINALISED
} state_t;
static FILE *s_file;
static state_t s_state;
int com_init( char *path )
{
s_state = state_RUNNING;
return( !( s_file = fopen( path, "r" ) ) );
}
int com_finalise( void )
{
s_state = state_FINALISED;
return fclose( s_file );
}
static int send_one_byte( uint8_t byte )
{
if( byte == cmd_STOP )
{
assert( s_state == state_RUNNING );
s_state = state_STOPPING;
}
printf( "COM_REPLAY > 0x%02x\n", byte );
return 0;
}
ssize_t write_wrapper( void *buf, size_t count )
{
unsigned i;
uint8_t *bytes = buf;
for( i = 0; i < count; ++i )
{
send_one_byte( bytes[i] );
}
return count;
}
static int read_one_byte( uint8_t *byte )
{
unsigned x;
usleep(100 * 1000);
switch( s_state )
{
case state_STOPPING:
*byte = c_end_of_response;
break;
case state_RUNNING:
fscanf( s_file, "%x ", &x );
*byte = (uint8_t)x;
break;
default:
assert( 0 );
}
printf( "COM_REPLAY < 0x%02x\n", *byte );
return 0;
}
ssize_t read_wrapper( void *buf, size_t count )
{
unsigned i;
uint8_t *bytes = buf;
for( i = 0; i < count; ++i )
{
read_one_byte( &(bytes[i]) );
}
return count;
}
|
C
|
/* find, substitute subst.c */
/* letzte aenderung:So 18.01.87 11:29:20 */
#include "cswitches.h"
#include "cportab.h"
#include "cestack.h"
#include "cedit.h"
#include "cscred.h"
#include "cencod.h"
#include "ctred.h"
extern char msg[];
static VOID ende(a,b)
STACK *a,*b;
{
register STACKELEM el;
while ( (el = pop(U1ST)) != ENDSYMB ) {
push(a,el);
}
while ( (el = pop(U2ST)) != ENDSYMB ) {
push(b,el);
}
}
static int end2(a,b,el1,el2)
STACK *a,*b;
STACKELEM el1,el2;
{
push(a,el1); push(b,el2);
while(pop(MST) != ENDSYMB)
;
ende(a,b);
return(NO);
}
/* ========== findp =================================== */
/* vergleicht die auf a und b liegenden ausdruecke */
/* falls auf a PLACEH, so b egal */
int findp(a,b)
STACK *a,*b;
{
register STACKELEM el,el2;
register int w;
push(U1ST,ENDSYMB);
push(U2ST,ENDSYMB);
push(MST,ENDSYMB);
FOREVER {
w = YES;
while (w) {
el = pop(a); el2 = pop(b);
if (noedit(el) == PLACEH) {
push(U1ST,el);
push(b,el2);
stransp(b,U2ST);
w = NO;
} else
if (class(el) != class(el2) || value(el) != value(el2)) {
return(end2(a,b,el,el2));
} else
if (isconstr(el)) { /* => isconstr(el2) ! */
if (arity(el) == arity(el2)) {
push(U1ST,el);
push(U2ST,el2);
push(MST,el);
w = NO;
}
else {
return(end2(a,b,el,el2));
}
} else
if (single_atom(el) || marked0(el)) { /* vgl. oben */
push(U1ST,el);
push(U2ST,el2);
w = NO;
} else
{ /* multi_atom */
push(U1ST,el);
push(U2ST,el2);
}
}
w = YES;
while (w) {
el = pop(MST);
if (el == ENDSYMB) {
ende(a,b);
return(YES);
} else
if (isconstr(el)) {
if (arity(el) > 0) {
push(MST,el);
decrarity(MST);
w=NO;
}
} else
{
sprintf(msg,"Illegal element %lx in findp",el);
error(msg);
}
}
}
}
/* ======= find ================= */
int find(a,b,next)
STACK *a,*b;
register int next;
{
register int found,n;
/*
dsplstack(a,"a in find",1,1);
dsplstack(b,"b in find",1,1);
*/
n = 0;
found = FALSE;
if (next) {
if (isempty(b)) return(FAILURE);
else {
if (notdisp(topof(b))) {
pop(b);
++n;
}
++n;
if (isconstr(topof(b))) pop(b);
else delete(b);
}
}
while (!found && !isempty(b)) {
found = findp(a,b);
if (!found) {
if (isconstr(topof(b))) pop(b);
else delete(b);
++n;
}
}
/*
printf("found: %d\n",n);
*/
return(found ? n : FAILURE);
}
/* ----------- copywhole ----------------- */
copywhole(st)
STACK *st;
{
register STACKELEM m;
register int p;
if ((m = topof(MST)) != STBOTTOM && notdisp(m) &&
arity(m) == arity(topof(M1ST))) {
move(MST,EST);
p = 1;
}
else
p = 0;
copyst(EST,st);
while (p-- > 0)
move(EST,MST);
}
/* -------- stransp --------------------------- */
stransp(st1,st2)
STACK *st1,*st2;
{
static STACKELEM m;
register int n;
if ((m = topof(st1)) != STBOTTOM)
if (isconstr(m)) {
move(st1,st2);
for (n = arity(m) ; n > 0 ; n-- )
stransp(st1,st2);
}
else {
if (single_atom(m) || marked0(m))
move(st1,st2);
else {
move(st1,st2);
while (marked1(move(st1,st2)))
;
}
}
}
/* end of subst.c */
|
C
|
/*
** EPITECH PROJECT, 2021
** B_CPP_300_BER_3_1_CPPD02M_karl_erik_stoerzel
** File description:
** func_ptr.c
*/
#include "func_ptr.h"
void print_normal(const char *str)
{
printf("%s\n", str);
}
void print_reverse(const char *str)
{
int len = (int)strlen(str);
for (int i = len - 1; i >= 0; i--)
{
printf("%c", str[i]);
}
printf("\n");
}
void print_upper(const char *str)
{
int len = (int)strlen(str);
for (int i = 0; i < len; i++)
{
printf("%c", toupper(str[i]));
}
printf("\n");
}
void print_42(const char *str)
{
printf("%s", "42\n");
}
void (*f_pointer[4])(const char *) =
{
print_normal,
print_reverse,
print_upper,
print_42
};
void do_action(action_t action, const char *str)
{
f_pointer[action](str);
}
|
C
|
#include<stdio.h>
int main()
{
int arr[3][3],i,j,sum;
int *ptr;
ptr=&arr[0][0];
//input array elements
printf("The elements are:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&arr[i][j]);
}
}
//access array elements
printf("\nThe matrix is:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",*((ptr+i*3)+j));
}
printf("\n");
}
//to find and print sum of all diagonal elements
printf("\nThe diagonal elements are:%d,%d,%d",arr[0][0],arr[1][1],arr[2][2]);
sum=arr[0][0]+arr[1][1]+arr[2][2];
printf("\n The sum of diagonal elements is %d",sum);
return 0;
}
|
C
|
int i,j,a[]={1,4,3,7,5,9,8,3,10},*b;
void ft_sort_integer_table(int *tab, int size);
void ft_sort_integer_table(int *tab, int size){
for(i=0;i<size;i++){
for(j=i;tab[j]<tab[j-1];j--){
tab[j-1]=tab[j];
}
}
}
int main(){
b=a;
ft_sort_integer_table(b,9);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
void getString(char a[]){
char c = '\0'; int i = 0;
while( (c = getchar()) != '\n'){
a[i++] = c;
} a[i] = '\0';
}
int StringToIntger(char a[]){
int i = 0;
int len = strlen(a);
int Integer = 0, sign = 1;
for (i = 0; i < len; ++i) {
if (a[i] == '-') {
sign = (-1);
}
Integer *= 10;
if (isdigit(a[i])) {
Integer += a[i] - '0';
}
}
return sign * Integer;
}
int main(int argc, char const *argv[]) {
char A[100];
getString(A);
printf("%s\n", A);
printf("%d\n", StringToIntger(A));
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
int cpuWordSize()
{
void *p = 0;
return sizeof(&p);
}
int main()
{
printf("CPU word size: %d\n",cpuWordSize());
return 0;
}
|
C
|
/*===============================================================================================
PlaySound Example
Copyright (c), Firelight Technologies Pty, Ltd 2004-2016.
This example shows how to simply load and play multiple sounds. This is about the simplest
use of FMOD.
This makes FMOD decode the into memory when it loads. If the sounds are big and possibly take
up a lot of ram, then it would be better to use the FMOD_CREATESTREAM flag so that it is
streamed in realtime as it plays.
===============================================================================================*/
#include <jni.h>
#include <android/log.h>
#include <stdlib.h>
#include "fmod.h"
#include "fmod_errors.h"
#define NUM_SOUNDS 3
FMOD_SYSTEM *gSystem = 0;
FMOD_CHANNEL *gChannel = 0;
FMOD_SOUND *gSound[NUM_SOUNDS];
#define CHECK_RESULT(x) \
{ \
FMOD_RESULT _result = x; \
if (_result != FMOD_OK) \
{ \
__android_log_print(ANDROID_LOG_ERROR, "fmod", "FMOD error! (%d) %s\n%s:%d", _result, FMOD_ErrorString(_result), __FILE__, __LINE__); \
exit(-1); \
} \
}
void Java_org_fmod_playsound_Example_cBegin(JNIEnv *env, jobject thiz)
{
FMOD_RESULT result = FMOD_OK;
result = FMOD_System_Create(&gSystem);
CHECK_RESULT(result);
result = FMOD_System_Init(gSystem, 32, FMOD_INIT_NORMAL, 0);
CHECK_RESULT(result);
result = FMOD_System_CreateSound(gSystem, "/sdcard/fmod/drumloop.wav", FMOD_DEFAULT | FMOD_LOOP_OFF, 0, &gSound[0]);
CHECK_RESULT(result);
result = FMOD_System_CreateSound(gSystem, "/sdcard/fmod/jaguar.wav", FMOD_DEFAULT, 0, &gSound[1]);
CHECK_RESULT(result);
result = FMOD_System_CreateSound(gSystem, "/sdcard/fmod/swish.wav", FMOD_DEFAULT, 0, &gSound[2]);
CHECK_RESULT(result);
}
void Java_org_fmod_playsound_Example_cUpdate(JNIEnv *env, jobject thiz)
{
FMOD_RESULT result = FMOD_OK;
result = FMOD_System_Update(gSystem);
CHECK_RESULT(result);
}
void Java_org_fmod_playsound_Example_cEnd(JNIEnv *env, jobject thiz)
{
FMOD_RESULT result = FMOD_OK;
unsigned int i = 0;
for (i = 0; i < NUM_SOUNDS; i++)
{
result = FMOD_Sound_Release(gSound[i]);
CHECK_RESULT(result);
}
result = FMOD_System_Release(gSystem);
CHECK_RESULT(result);
}
void Java_org_fmod_playsound_Example_cPlaySound(JNIEnv *env, jobject thiz, int id)
{
FMOD_RESULT result = FMOD_OK;
result = FMOD_System_PlaySound(gSystem, FMOD_CHANNEL_FREE, gSound[id], 0, &gChannel);
CHECK_RESULT(result);
}
jint Java_org_fmod_playsound_Example_cGetChannelsPlaying(JNIEnv *env, jobject thiz)
{
FMOD_RESULT result = FMOD_OK;
int chans = 0;
result = FMOD_System_GetChannelsPlaying(gSystem, &chans);
CHECK_RESULT(result);
return chans;
}
jboolean Java_org_fmod_playsound_Example_cGetPlaying(JNIEnv *env, jobject thiz)
{
FMOD_RESULT result = FMOD_OK;
FMOD_BOOL playing = 0;
if (gChannel)
{
result = FMOD_Channel_IsPlaying(gChannel, &playing);
if (result != FMOD_ERR_INVALID_HANDLE && result != FMOD_ERR_CHANNEL_STOLEN)
{
CHECK_RESULT(result);
}
}
return playing;
}
jint Java_org_fmod_playsound_Example_cGetPosition(JNIEnv *env, jobject thiz)
{
FMOD_RESULT result = FMOD_OK;
int position = 0;
if (gChannel)
{
result = FMOD_Channel_GetPosition(gChannel, &position, FMOD_TIMEUNIT_MS);
if (result != FMOD_ERR_INVALID_HANDLE && result != FMOD_ERR_CHANNEL_STOLEN)
{
CHECK_RESULT(result);
}
}
return position;
}
jint Java_org_fmod_playsound_Example_cGetLength(JNIEnv *env, jobject thiz)
{
FMOD_RESULT result = FMOD_OK;
FMOD_SOUND *sound = 0;
int length = 0;
if (gChannel)
{
result = FMOD_Channel_GetCurrentSound(gChannel, &sound);
if (result != FMOD_ERR_INVALID_HANDLE && result != FMOD_ERR_CHANNEL_STOLEN)
{
CHECK_RESULT(result);
}
}
if (sound)
{
result = FMOD_Sound_GetLength(sound, &length, FMOD_TIMEUNIT_MS);
CHECK_RESULT(result);
}
return length;
}
|
C
|
//--------------------------------
// Lab 4 - Sample - Lab04_sample.c
//--------------------------------
//
//
#include "init.h"
#include <stdint.h>
#include <stdlib.h>
ADC_HandleTypeDef hADC3;
DAC_HandleTypeDef hDAC1;
uint32_t voltage=0;
//uint32_t x=0; //uint32_t with name of x, x_1, x_2 and putout are for C language implement
//uint32_t x_1 =0;
//uint32_t x_2=0;
//uint32_t putout=0;
float x=0;//float with name of x, x_1, x_2, putout and putout_1 are for assembly language implement
float x_1 =0;
float x_2=0;
float putout=0;
float putout_1=0;
float a = 0.3125;// Coefficient for assembly language implement
float b = 0.240385;
float c = 0.296875;
void configureDAC();
void configureADC();
uint16_t readvoltage();
// Main Execution Loop
int main(void)
{
//Initialize the system
Sys_Init();
configureDAC();
HAL_DAC_Start(&hDAC1, DAC_CHANNEL_1);
configureADC();
while(1){
// //Use c to implemet
// x_2 = x_1;
// x_1 = x;
// x = readvoltage();
// putout = 0.312500*x + 0.240385*x_1 + 0.312500*x_2 + 0.296875*putout;
// HAL_DAC_SetValue(&hDAC1, DAC_CHANNEL_1,DAC_ALIGN_12B_R, putout);
//Use assembly language
asm ("VMOV.F32 %0,%1":"+t"(x_2):"t"(x_1));//Shifting the input value by 1 time unit
asm ("VMOV.F32 %0,%1":"+t"(x_1):"t"(x));
asm ("VMOV.F32 %0,%1":"+t"(putout_1):"t"(putout));
x = readvoltage();
asm volatile("VMUL.F32 %0,%1,%2":"+t"(putout):"t"(x),"t"(a));
asm volatile("VMLA.F32 %0,%1,%2":"+t"(putout):"t"(x_1),"t"(b));
asm volatile("VMLA.F32 %0,%1,%2":"+t"(putout):"t"(x_2),"t"(a));
asm volatile("VMLA.F32 %0,%1,%2":"+t"(putout):"t"(putout_1),"t"(c));
HAL_DAC_SetValue(&hDAC1, DAC_CHANNEL_1,DAC_ALIGN_12B_R, putout);
}
}
void configureDAC(){
__HAL_RCC_DAC_CLK_ENABLE();
//Configure DAC_HandleTypeDef
hDAC1.Instance = DAC;
HAL_DAC_Init(&hDAC1);
//Configure DAC_ChannelConfTypeDef
DAC_ChannelConfTypeDef dacchan;
dacchan.DAC_Trigger = DAC_TRIGGER_NONE;
dacchan.DAC_OutputBuffer = DAC_OUTPUTBUFFER_ENABLE;
HAL_DAC_ConfigChannel(&hDAC1, &dacchan, DAC_CHANNEL_1);
}
void HAL_DAC_MspInit(DAC_HandleTypeDef *hdac)
{
GPIO_InitTypeDef GPIO_InitStruct;
if(hdac->Instance == DAC){
// Enable GPIO Clocks
__HAL_RCC_GPIOA_CLK_ENABLE();
// Initialize Pin
GPIO_InitStruct.Pin = GPIO_PIN_4;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
}
uint16_t readvoltage(){
HAL_ADC_Start(&hADC3);
HAL_ADC_PollForConversion(&hADC3,100);//wait for ADC conversion complete
return HAL_ADC_GetValue(&hADC3);
}
void configureADC()
{ //A3 =>PF10 (ADC3_IN8)
__HAL_RCC_ADC3_CLK_ENABLE();
//Configure ADC_HandleTypeDef
hADC3.Instance = ADC3;
hADC3.Init.Resolution = ADC_RESOLUTION_12B;
hADC3.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
hADC3.Init.ScanConvMode = DISABLE;
hADC3.Init.NbrOfConversion = 1;
hADC3.Init.ContinuousConvMode = ENABLE;
hADC3.Init.DiscontinuousConvMode = DISABLE;
hADC3.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hADC3.Init.DMAContinuousRequests = DISABLE;
hADC3.Init.EOCSelection = ADC_EOC_SEQ_CONV;
hADC3.Init.ExternalTrigConv = ADC_SOFTWARE_START;
HAL_ADC_Init(&hADC3);
//Configure ADC_ChannelConfTypeDef
ADC_ChannelConfTypeDef adcchan;
adcchan.Channel = ADC_CHANNEL_8;
adcchan.Rank = ADC_REGULAR_RANK_1;
adcchan.SamplingTime = ADC_SAMPLETIME_56CYCLES;
HAL_ADC_ConfigChannel(&hADC3,&adcchan);
}
void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc)
{
GPIO_InitTypeDef GPIO_InitStruct;
if(hadc->Instance == ADC3){
// Enable GPIO Clocks
__HAL_RCC_GPIOF_CLK_ENABLE();
// Initialize Pin
GPIO_InitStruct.Pin = GPIO_PIN_10;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
HAL_GPIO_Init(GPIOF, &GPIO_InitStruct);
}
}
|
C
|
#include <stdio.h>
void maior(float a, float b, float c)
{
float maior;
if(a > b && a > c)
maior = a;
else if(b > a && b > c)
maior = b;
else if(c > a && c > b)
maior = c;
printf("O numero maior e %.2f", maior);
}
int main()
{
float v[3];
for(int c = 0; c < 3; c++){
printf("Digite um numero: ");
scanf("%f", &v[c]);
}
maior(v[0], v[1], v[2]);
}
|
C
|
#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
void transverse_back(char *pathname, ino_t inum)
{
DIR *dp;
static char *pwd;
struct dirent *dir;
/*Base case - when the root has been reached return*/
if(strcmp("..",pathname) != 0)
return;
/*General case - when the root hasnt been reached*/
if((dp = opendir(".")) == NULL){
perror("open dir error");
exit(EXIT_FAILURE);
}
while((dir = readdir(dp)) != NULL && dir->d_name != "..")
;
chdir("..");
transverse_back(dir->d_name, dir->);
strcat(pwd, "/");
strcat(pwd, dir->d_name);
closedir(dp);
printf("directory %s\n");
}
/*./mypwd
*
*
* that performs the sam task as /bin/pwd withou using getcwd*/
int main(int argc, char *argv[])
{
transverse_back("..");
return 0;
}
|
C
|
#include "mesinkata.h"
#include <stdio.h>
void BacaKata(KATA *X){
int i;
i = 0;
(*X).length = 0;
while ( (i < 100) && (KATA(*X,i-1) != '\n' )){ //Memasukkan Command ke variabel KATA atau nulis apapund deh
scanf("%c", &KATA(*X, i) );
(*X).length = (*X).length + 1;
i = i + 1;
}
(*X).length = (*X).length - 1;
}
void TulisKata(KATA X){
int i;
i = 0;
while(i < X.length){
printf("%c", KATA(X, i) );
i = i + 1;
}
printf("%d", X.length);
printf("\n");
}
boolean IsKataSama(KATA X, KATA Y){
int i;
boolean sama;
sama = true;
i = 0;
while( (i < X.length) && (sama==true)){
if (KATA(X, i) != KATA(Y,i) ){
sama = false;
}
i = i + 1;
}
if (X.length != Y.length){
sama = false;
}
return sama;
}
|
C
|
#include<stdio.h>
int main()
{
int i,n,c=1;
scanf("%d",&n);
for(i=1;i<n;i++)
{
if(n%i==0)
{
c++;
}
}
if(c==2)
{
printf("is prime");
}
else
{
printf("is not prime");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "check.h"
#include "test_centering_measure.h"
#include "eval_cent_meas.h"
#include "OpenBLAS/cblas.h"
#include "test_util.h"
#include "smatvec.h"
#include "umfpack.h"
#include "spmat.h"
#include "linear_solvers.h"
#include "barriers.h"
START_TEST (test_centering_measure)
{
//The centering measure squared is defined as
//||s-mug(x)||^2_H(x)^{-1}
//Which is equivalent to s'H^{-1}s -2mu x's + mu^2 nu
//if we choose s = H(x)\hat s
//This becomes s'\hat s -2 mu x's + mu^2 ny
//We test the centering mesure by generating a sequence of
//random feasible points for a problem with positive constraints
//and exponential cones.
//We calculate the centrality in the alternative way and compare
//Define the problem structure
problem_t prob;
spmat A;
int n = 16;
A.n = n;
prob.A = A;
int tk[] = {0,3,3};
prob.tK = tk;
csi nK[] = {10,3,3};
prob.nK = nK;
prob.k_count = 3;
int nnzH = 28;
spmat H;
H.n = A.n;
H.m = A.n;
H.I = (csi*)calloc(nnzH,sizeof(csi));
H.J = (csi*)calloc(nnzH,sizeof(csi));
H.V = (double*)calloc(nnzH,sizeof(double));
H.nnz = nnzH;
state_t state;
state.H = H;
double *x = (double*)calloc(n,sizeof(double));
double *s = (double*)calloc(n,sizeof(double));
double *shat = (double*)calloc(n,sizeof(double));
//Create the working vectors for the centrality measure
double *psi = (double*)calloc(n,sizeof(double));
double *hpsi = (double*)calloc(n,sizeof(double));
//Allocate the space to compress to csr
int* Hi=(int*)calloc(nnzH,sizeof(int));
int* Hp=(int*)calloc(n+1,sizeof(int));
double* Hx=(double*)calloc(nnzH,sizeof(double));
int* Map=NULL;
//Define other vars
int status;
int i,j;
double sshat;
double mu;
double nu = 16;
double cent, cent_alt, cent_dif;
//How many tests
int tests = 100;
for(j=0;j<tests;j++)
{
//Pick a random s,
for(i=0;i<10;i++) s[i] = rand()/(double)RAND_MAX;
s[i] = rand()/(double)RAND_MAX - 0.5;
s[i+2] = rand()/(double)RAND_MAX+1.;
s[i+1] = -s[i+2]*exp(s[i]/s[i+2]-1) + rand()/(double)RAND_MAX;
i = i+3;
s[i] = rand()/(double)RAND_MAX - 0.5;
s[i+2] = rand()/(double)RAND_MAX+1.;
s[i+1] = -s[i+2]*exp(s[i]/s[i+2]-1) + rand()/(double)RAND_MAX;
//Generate a random feasible point
for(i=0;i<10;i++) x[i] = rand()/(double)RAND_MAX;
x[i] = rand()/(double)RAND_MAX - 0.5;
x[i+2] = rand()/(double)RAND_MAX+1.;
x[i+1] = x[i+2]*exp(x[i]/x[i+2]) + rand()/(double)RAND_MAX;
i = i+3;
x[i] = rand()/(double)RAND_MAX - 0.5;
x[i+2] = rand()/(double)RAND_MAX+1.;
x[i+1] = x[i+2]*exp(x[i]/x[i+2]) + rand()/(double)RAND_MAX;
//evaluate the hessian
eval_hess(prob,x,state);
//Calculate s
solve_linear_system(shat, H.I, H.J, H.V, nnzH, s , n);
sshat = cblas_ddot(n,s,1,shat,1);
mu = cblas_ddot(n,s,1,x,1);
mu = mu/nu;
cent = sqrt(sshat - mu*mu*nu);
cent_alt = eval_cent_meas(prob,x,s,state,mu,psi,hpsi);
cent_dif = fmax(cent-cent_alt,cent_alt-cent);
ck_assert_msg(cent_dif<1.e-12,"In test %i centrality measures do not match |c-c_alt| %g\n",j,cent_dif);
}
}
END_TEST
Suite* centering_measure_suite(void)
{
Suite* suite = suite_create("Centering Measure");
TCase *tc = tcase_create("Case1");
tcase_add_test(tc,test_centering_measure);
suite_add_tcase(suite,tc);
return suite;
}
|
C
|
/*
* UNIX threads
*/
#ifndef _AINTUTHR_H
#define _AINTUTHR_H
#include <pthread.h>
#include "allegro5/internal/aintern_thread.h"
#ifdef __cplusplus
extern "C" {
#endif
/* threads */
struct _AL_THREAD
{
/* private: */
pthread_t thread;
pthread_mutex_t mutex;
bool should_stop;
void (*proc)(struct _AL_THREAD *self, void *arg);
void *arg;
};
struct _AL_MUTEX
{
bool inited;
pthread_mutex_t mutex;
};
#define _AL_MUTEX_UNINITED { false, PTHREAD_MUTEX_INITIALIZER }
/* makes no sense, but shuts gcc up */
#define _AL_MARK_MUTEX_UNINITED(M) do { M.inited = false; } while (0)
struct _AL_COND
{
pthread_cond_t cond;
};
typedef struct ALLEGRO_TIMEOUT_UNIX ALLEGRO_TIMEOUT_UNIX;
struct ALLEGRO_TIMEOUT_UNIX
{
struct timespec abstime;
};
AL_INLINE(bool, _al_get_thread_should_stop, (struct _AL_THREAD *t),
{
bool ret;
pthread_mutex_lock(&t->mutex);
ret = t->should_stop;
pthread_mutex_unlock(&t->mutex);
return ret;
})
AL_FUNC(void, _al_mutex_init, (struct _AL_MUTEX*));
AL_FUNC(void, _al_mutex_destroy, (struct _AL_MUTEX*));
AL_INLINE(void, _al_mutex_lock, (struct _AL_MUTEX *m),
{
if (m->inited)
pthread_mutex_lock(&m->mutex);
})
AL_INLINE(void, _al_mutex_unlock, (struct _AL_MUTEX *m),
{
if (m->inited)
pthread_mutex_unlock(&m->mutex);
})
AL_INLINE(void, _al_cond_init, (struct _AL_COND *cond),
{
pthread_cond_init(&cond->cond, NULL);
})
AL_INLINE(void, _al_cond_destroy, (struct _AL_COND *cond),
{
pthread_cond_destroy(&cond->cond);
})
AL_INLINE(void, _al_cond_wait, (struct _AL_COND *cond, struct _AL_MUTEX *mutex),
{
pthread_cond_wait(&cond->cond, &mutex->mutex);
})
AL_INLINE(void, _al_cond_broadcast, (struct _AL_COND *cond),
{
pthread_cond_broadcast(&cond->cond);
})
AL_INLINE(void, _al_cond_signal, (struct _AL_COND *cond),
{
pthread_cond_signal(&cond->cond);
})
#ifdef __cplusplus
}
#endif
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include <signal.h>
#include <setjmp.h>
#define DATA_SIZE 512
#define MAX_FILENAME 255
#define INITIAL_BLOCK 0
#define MAX_TIMEOUTS 5
#define TIMEOUT_SECS 3
/* Opcodes */
#define RRQ 1
#define WRQ 2
#define DATA 3
#define ACK 4
#define ERROR 5
static const char *TFTP_error_messages[] = {
"Undefined error", // Error code 0
"File not found", // 1
"Access violation", // 2
"Disk full or allocation error", // 3
"Illegal TFTP operation", // 4
"Unknown transfer ID", // 5
"File already exists", // 6
"No such user" // 7
};
extern int errno;
typedef struct {
unsigned short int opcode;
char filename[MAX_FILENAME];
char zero_0;
char mode[MAX_FILENAME];
char zero_1;
} TFTP_Request;
typedef struct {
unsigned short int opcode;
unsigned short int block;
char data[DATA_SIZE];
} TFTP_Data;
typedef struct {
unsigned short int opcode;
unsigned short int block;
} TFTP_Ack;
/* Global vars */
static int is_debugging = 0, timeout;
jmp_buf timeoutbuf, endbuf;
int get_port(char* s) {
int retval = 0;
char *a = s;
while (*a != '\0') {
if (*a >= '0' && *a <= '9') {
retval = retval * 10 + (*a - '0');
} else {
return -1;
}
a++;
}
return retval;
}
/* Returns 0 for sucess, otherwise -1. */
int make_socket(struct sockaddr_in *s, char *host, int port) {
s->sin_family = AF_INET;
if (host != NULL) {
struct hostent *he = gethostbyname(host);
if (he == NULL) {
perror("gethostbyname");
return -1;
}
s->sin_addr = *((struct in_addr *)he->h_addr);
} else {
s->sin_addr.s_addr = htonl(INADDR_ANY);
}
s->sin_port = htons(port);
memset(&(s->sin_zero), 0, 8);
return 0;
}
/* Returns 0 a file that exists, other -1. */
int file_exists(char *filename) {
struct stat filebuf;
if ( stat(filename, &filebuf) == 0 ) {
return 0;
} else {
return -1;
}
}
/* Fill in the struct using data from buffer */
void packet_to_request(TFTP_Request *r, char *buf) {
char filename[MAX_FILENAME];
char mode[MAX_FILENAME];
short signed int code;
code = *(short signed int*)buf;
buf += sizeof(r->opcode);
strcpy(filename, buf);
buf += strlen(filename) + 1;
strcpy(mode, buf);
r->opcode = ntohs(code);
strcpy(r->filename, filename);
r->zero_0 = '\0';
strcpy(r->mode, mode);
r->zero_1 = '\0';
}
/* Fill the given buffer using data from the given request */
void request_to_packet(TFTP_Request *r, char *buf) {
char *pos = buf;
*(short signed int*)pos = htons(r->opcode);
pos += sizeof(r->opcode);
strcpy(pos, r->filename);
pos += strlen(r->filename) + 1;
*pos = r->zero_0;
strcpy(pos, r->mode);
pos += strlen(r->mode) + 1;
*pos = r->zero_1;
}
/* Computes length of request */
int request_length(TFTP_Request *r) {
int len = sizeof(r->opcode) + sizeof(r->zero_0) + sizeof(r->zero_1);
len += strlen(r->filename) + 1;
len += strlen(r->mode) + 1;
return len;
}
/* Returns 0 if request has the given mode, otherwise 0 */
int request_is_mode(TFTP_Request *r, char *mode) {
if (strcmp(r->mode, mode) == 0) return 0;
return -1;
}
void request_init(TFTP_Request *r, unsigned short int opcode, char *filename, char *mode) {
memset(r, 0, sizeof(TFTP_Request));
r->opcode = opcode;
strcpy(r->filename, filename);
r->zero_0 = '\0';
strcpy(r->mode, "octet");
r->zero_1 = '\0';
}
void timer(int sig) {
switch(sig) {
case SIGALRM: {
timeout++;
if (timeout >= MAX_TIMEOUTS) {
if (is_debugging) printf("Retransmission timed out.\n");
timeout = 0;
alarm(0);
longjmp(endbuf, sig);
}
if (is_debugging) printf("Retransmitting.\n");
longjmp(timeoutbuf, sig);
} break;
case SIGINT: {
if (is_debugging) printf("Transfer interrupted.\n");
timeout = 0;
alarm(0);
longjmp(endbuf, sig);
} break;
default: break;
}
}
void send_data(int sockfd, struct sockaddr *to_addr, socklen_t addr_len, char *filename) {
int filesize, n, pos = 0, nextAck = -1;
signed short int block = 0;
int fd = open(filename, O_RDONLY, 0006);
if (fd == -1) {
perror("open");
exit(1);
}
filesize = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
/* Allocate memory for DATA, ACK structs */
TFTP_Data *dataPacket;
TFTP_Ack *ack;
dataPacket = (TFTP_Data *)malloc(sizeof(TFTP_Data));
ack = (TFTP_Ack *)malloc(sizeof(TFTP_Ack));
memset(dataPacket, 0, sizeof(TFTP_Ack));
memset(ack, 0, sizeof(TFTP_Ack));
/* Read from file and send data to server */
while (pos < filesize) {
char dataBuf[DATA_SIZE] = {0};
n = read(fd, &dataBuf, DATA_SIZE);
if (n == -1) {
perror("read");
exit(1);
}
pos += n;
block++;
dataPacket->opcode = htons(DATA);
dataPacket->block = htons(block);
if (is_debugging) printf("Block #%d, %d bytes\n", block, n);
memset(dataPacket->data, 0, DATA_SIZE);
memcpy(dataPacket->data, dataBuf, n);
sigsetjmp(timeoutbuf, 1); // jump for retransmission
if (is_debugging) printf("Sending DATA for block #%d\n", block);
n = sendto(sockfd, dataPacket, 4 + n, 0, to_addr, addr_len);
if (n < 0) {
if (is_debugging) printf("Error sending DATA block #%d\n", block);
break;
}
if (sigsetjmp(endbuf, 1) != 0) {
// setup jump for retransmission timeout and interrupt
break;
}
signal(SIGINT, timer);
signal(SIGALRM, timer);
while (nextAck < 0) {
/* Receive ACK for the sent DATA */
if (is_debugging) printf("Waiting for ACK...\n");
alarm(TIMEOUT_SECS); // start new timer
n = recvfrom(sockfd, ack, sizeof(TFTP_Ack), 0, to_addr, &addr_len);
timeout = 0;
alarm(0);
if (n < 0) {
if (is_debugging) printf("Error receiving ACK for block #%d\n", block);
break;
}
if (ntohs(ack->opcode) == ERROR) {
if (is_debugging) printf("Received ERROR: %s\n", TFTP_error_messages[ntohs(ack->block)]);
}
else if (ntohs(ack->opcode) == ACK) {
/* Check block */
if (ntohs(ack->block) == block) {
nextAck = 1;
if (pos == filesize) {
if (is_debugging) printf("Received ACK for final block #%d\n", block);
break;
} else {
if (is_debugging) printf("Received ACK for block #%d\n", block);
continue;
}
} else if (ntohs(ack->block) < block) {
nextAck = -1;
}
}
}
nextAck = -1;
}
free(dataPacket);
free(ack);
close(fd);
}
void recv_data(int sockfd, char *filename) {
struct sockaddr client_addr;
int n;
socklen_t clilen;
short signed int block = 0, nextBlock = 1;
/* Allocate memory for DATA, ACK and FILE structs */
TFTP_Data *dataPacket = malloc(sizeof(TFTP_Data));
TFTP_Ack *ack = malloc(sizeof(TFTP_Ack));
memset(dataPacket, 0, sizeof(TFTP_Data));
memset(ack, 0, sizeof(TFTP_Ack));
FILE * file = fopen(filename, "ab");
while (1) {
clilen = sizeof(struct sockaddr);
int length;
if (sigsetjmp(endbuf, 1) != 0) {
// setup jump for retransmission timeout and interrupt
break;
}
signal(SIGINT, timer);
signal(SIGALRM, timer);
/* Receive the DATA */
if (is_debugging) printf("Waiting for DATA...\n");
alarm(TIMEOUT_SECS); // start new timer
memset(dataPacket, 0, sizeof(TFTP_Data));
n = recvfrom(sockfd, dataPacket, sizeof(TFTP_Data), 0, (struct sockaddr *)&client_addr, &clilen);
timeout = 0;
alarm(0); // void timer
if (n < 0) break;
/* Received a duplicate DATA block */
if (ntohs(dataPacket->block) < nextBlock) {
if (is_debugging) printf("Received duplicate DATA for block #%d\n", ntohs(dataPacket->block));
}
else {
length = strlen(dataPacket->data);
if (length == 0) break;
/* Fill the data buffer */
char dataBuf[DATA_SIZE+1];
strcpy(dataBuf, dataPacket->data);
if (length > DATA_SIZE) {
dataBuf[DATA_SIZE] = '\0';
length = strlen(dataBuf);
}
if (is_debugging) printf("Received DATA for block #%d of size %d\n", ntohs(dataPacket->block), length);
/* Write data to the file and check if disk is full */
fwrite(dataBuf, sizeof(char), length, file);
if (errno == ENOSPC) {
if (is_debugging) printf("Sending error: %s\n", TFTP_error_messages[3]);
ack->opcode = htons(ERROR);
ack->block = htons(3);
n = sendto(sockfd, ack, sizeof(TFTP_Ack), 0, &client_addr, clilen);
break;
}
/* Fill ACK if correct block received */
block = nextBlock;
nextBlock++;
ack->opcode = htons(ACK);
ack->block = htons(block);
}
sigsetjmp(timeoutbuf, 1); // jump for retransmission
if (is_debugging) printf("Sending ACK for block #%d\n", block);
n = sendto(sockfd, ack, sizeof(TFTP_Ack), 0, &client_addr, clilen);
if (n < 0) {
printf("Error sending ACK.\n");
break;
}
/* last block of DATA */
if (length < DATA_SIZE) break;
}
free(dataPacket);
free(ack);
fclose(file);
}
void send_error(int sockfd, struct sockaddr *to_addr, socklen_t addrlen, TFTP_Ack *ack, char *msg) {
int len = sizeof(TFTP_Ack)+strlen(msg)+1;
char *buf = (char *)malloc(len);
char *pbuf = buf;
memset(buf, 0, len);
*(short signed int*)pbuf = htons(ack->opcode);
pbuf += sizeof(ack->opcode);
*(short signed int*)pbuf = htons(ack->block);
pbuf += sizeof(ack->block);
strcpy(pbuf, msg);
sendto(sockfd, buf, len, 0, to_addr, addrlen);
free(buf);
}
int server_process(int oldsockfd, struct sockaddr *client_addr, TFTP_Request *request) {
int pid = fork();
if (pid < 0) {
perror("fork");
return -1;
}
if (pid == 0) {
close(oldsockfd);
int sockfd = 0;
if ((sockfd=socket(AF_INET,SOCK_DGRAM,0)) == -1) {
perror("socket");
exit(1);
}
struct sockaddr_in serv_addr;
make_socket(&serv_addr, NULL, 0);
if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(0);
}
unsigned int addr_len = sizeof(struct sockaddr);
if (getsockname(sockfd, (struct sockaddr *)&serv_addr, &addr_len) == -1) {
perror("getsockname");
exit(1);
}
if (is_debugging) printf("Child process listening on port %i\n", ntohs(serv_addr.sin_port));
/* Allocate memory for ACK struct */
TFTP_Ack *ack = (TFTP_Ack *)malloc(sizeof(TFTP_Ack));
memset(ack, 0, sizeof(TFTP_Ack));
/* Octet mode only */
if (request_is_mode(request, "octet") != 0) {
ack->opcode = htons(ERROR);
ack->block = htons(0);
send_error(sockfd, client_addr, addr_len, ack, "mode not supported");
free(ack);
close(sockfd);
free(request);
exit(1);
}
if (request->opcode == WRQ) {
/* file should not exist locally */
if ( file_exists(request->filename) == 0 ) {
exit(1);
}
/* Fill ACK struct and compute packet length */
ack->opcode = htons(ACK);
ack->block = htons(INITIAL_BLOCK);
/* Send ACK and start receiving DATA */
sendto(sockfd, ack, sizeof(TFTP_Ack), 0, client_addr, addr_len);
recv_data(sockfd, request->filename);
}
else if (request->opcode == RRQ) {
/* file must exist locally */
if ( file_exists(request->filename) == -1 ) {
exit(1);
}
/* Send data */
send_data(sockfd, client_addr, addr_len, request->filename);
}
else {
if (is_debugging) printf("Received request with unknown opcode: %i\n", request->opcode);
}
free(ack);
close(sockfd);
free(request);
exit(0);
}
return pid;
}
void chld_trap(int s) {
int pid = wait(NULL);
if (pid < 0) {
return; // wait went wrong, fly away
}
}
void run_server(int port) {
/* install signal handlers */
signal(SIGCHLD, chld_trap);
int sockfd;
struct sockaddr_in my_addr;
struct sockaddr_in client_addr;
unsigned int addr_len, numbytes;
char *buf;
/* Try to bind socket to the port */
if ((sockfd=socket(AF_INET,SOCK_DGRAM,0)) == -1) {
perror("socket");
exit(1);
}
make_socket(&my_addr, NULL, port);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
/* Listen for incoming requests until program is teminated */
if (is_debugging) printf("Listening on port %i\n", ntohs(my_addr.sin_port));
while (1) {
buf = (char *)malloc( sizeof(TFTP_Request) );
memset(buf, 0, sizeof(TFTP_Request));
addr_len = sizeof(struct sockaddr);
numbytes = recvfrom(sockfd, buf, sizeof(TFTP_Request), 0, (struct sockaddr *)&client_addr, &addr_len);
if (numbytes < 0) {
free(buf);
continue;
}
if (is_debugging) {
printf("Got packet from %s:%d, %i bytes.\n",
inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), numbytes
);
}
TFTP_Request *request = (TFTP_Request *)malloc( sizeof(TFTP_Request) );
packet_to_request(request, buf);
free(buf);
server_process(sockfd, (struct sockaddr *)&client_addr, request);
free(request);
}
close(sockfd);
}
void send_request_read(char *host, int port, char *filename) {
int n, len;
int mysockfd;
struct sockaddr_in serv_addr;
struct sockaddr_in my_addr;
unsigned int addr_len;
/* Prepare the sockets */
make_socket(&serv_addr, host, port);
if ((mysockfd=socket(AF_INET,SOCK_DGRAM,0)) == -1) {
perror("socket");
exit(1);
}
make_socket(&my_addr, NULL, 0);
if (bind(mysockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
addr_len = sizeof(struct sockaddr);
/* Allocate the Ack struct */
TFTP_Ack *ack = (TFTP_Ack *)malloc(sizeof(TFTP_Ack));
memset(ack, 0, sizeof(TFTP_Ack));
/* Create the request */
TFTP_Request *request = (TFTP_Request *)malloc(sizeof(TFTP_Request));
request_init(request, RRQ, filename, "octet");
len = request_length(request);
char *req_buffer = (char*)malloc(len);
memset(req_buffer, 0, len);
request_to_packet(request, req_buffer);
/* Send the request */
sigsetjmp(timeoutbuf, 1);
if (is_debugging) printf("Sending read request to server, %i bytes.\n", len);
n = sendto(mysockfd, req_buffer, len, 0, (struct sockaddr *)&serv_addr, addr_len);
if (n < 0) {
if (is_debugging) printf("Error sending read request!\n");
free(ack);
free(request);
free(req_buffer);
close(mysockfd);
exit(1);
}
/* Just receive data */
recv_data(mysockfd, filename);
free(ack);
free(request);
free(req_buffer);
close(mysockfd);
}
void send_request_write(char *host, int port, char *filename) {
int mysockfd, n, len;
struct sockaddr_in serv_addr, my_addr;
unsigned int addr_len;
/* Prepare the sockets */
make_socket(&serv_addr, host, port);
if ((mysockfd=socket(AF_INET,SOCK_DGRAM,0)) == -1) {
perror("socket");
exit(1);
}
make_socket(&my_addr, NULL, 0);
if (bind(mysockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
addr_len = sizeof(struct sockaddr);
/* Allocate the Ack struct */
TFTP_Ack *ack = (TFTP_Ack *)malloc(sizeof(TFTP_Ack));
memset(ack, 0, sizeof(TFTP_Ack));
/* Create the request */
TFTP_Request *request = (TFTP_Request *)malloc(sizeof(TFTP_Request));
request_init(request, WRQ, filename, "octet");
len = request_length(request);
char *req_buffer = (char*)malloc(len);
memset(req_buffer, 0, len);
request_to_packet(request, req_buffer);
/* Send the request */
sigsetjmp(timeoutbuf, 1); // jump for retransmission
if (is_debugging) printf("Sending write request to server, %i bytes.\n", len);
n = sendto(mysockfd, req_buffer, len, 0, (struct sockaddr *)&serv_addr, addr_len);
if (n < 0) {
if (is_debugging) printf("Error sending write request!\n");
exit(1);
}
if (sigsetjmp(endbuf, 1) != 0) {
// jump for retransmission failure or interrupt
free(ack);
free(request);
free(req_buffer);
close(mysockfd);
exit(1);
}
/* Wait for the Ack */
if (getsockname(mysockfd, (struct sockaddr *)&my_addr, &addr_len) == -1) {
if (is_debugging) perror("getsockname");
exit(1);
}
if (is_debugging) printf("Waiting for ACK on port %d...\n", ntohs( my_addr.sin_port ));
signal(SIGINT, timer);
signal(SIGALRM, timer);
alarm(TIMEOUT_SECS);
n = recvfrom(mysockfd, ack, sizeof(TFTP_Ack), 0, (struct sockaddr *)&serv_addr, &addr_len);
alarm(0);
timeout = 0;
if (n < 0) {
if (is_debugging) printf("Error receiving ACK from server!\n");
exit(1);
}
/* Check the Opcode */
if (ntohs(ack->opcode) == ERROR) {
if (is_debugging) printf("Received ERROR: %s\n", TFTP_error_messages[ntohs(ack->block)]);
}
else if ( ntohs(ack->opcode) == ACK && ntohs(ack->block) == INITIAL_BLOCK ) {
if (is_debugging) printf("Received ACK for block #%d\n", ntohs(ack->block));
send_data(mysockfd, (struct sockaddr *)&serv_addr, addr_len, filename);
} else {
if (is_debugging) printf("Received packet other than expected ACK\n");
}
free(ack);
free(request);
free(req_buffer);
close(mysockfd);
}
void run_client(char *host, int port, char mode, char *filename) {
void (* sender)(char *, int , char *) = NULL;
int exist = (mode == 'r') ? 0 : -1;
if (file_exists(filename) == exist) {
/* Nothing to do here */
exit(1);
}
sender = (mode == 'r') ? &send_request_read : &send_request_write;
if (sender != NULL) sender(host, port, filename);
}
/*
* Server: mytftp -l [-p port] [-v]
* Client: mytftp [-p port] [-v] [-r|w file] host
*/
int main(int argc, char** argv) {
int server = 0;
int port = 3335;
char mode = 0;
char *filename = NULL;
char *host = NULL;
/* Parse the arguments */
while (--argc > 0) {
char *str = *++argv;
if (*str != '-') {
host = (char *)malloc( sizeof(char)*(strlen(str)+1) );
strcpy(host, str);
continue;
}
str++;
if (*str == 'l') {
server = 1;
}
else if (*str == 'p') {
if (--argc > 0) {
port = get_port(*++argv);
if (port < 0) {
printf("Invalid port number: %s\n", *argv);
exit(0);
}
}
}
else if (*str == 'v') {
is_debugging = 1;
printf("Verbose mode on.\n");
}
else if (*str == 'r' || *str == 'w') {
mode = *str;
--argc;
filename = (char *)malloc( sizeof(char)*(strlen(*++argv)+1) );
strcpy(filename, *argv);
}
}
if (server == 1) {
run_server(port);
} else {
if (host != NULL && mode > 0 && filename != NULL) {
run_client(host, port, mode, filename);
free(host);
free(filename);
} else {
printf("Usage:\nServer: mytftp -l [-p port] [-v]\nClient: mytftp [-p port] [-v] [-r|w file] host\n");
}
}
return 0;
}
|
C
|
#include <stdio.h>
int average(int l, int a[l])
{
int sum = 0, i;
for (i = 0; i < l; i++)
{
sum += a[i];
}
sum /= l;
printf("ƽ %d", sum);
}
int main()
{
int i, l, a[l];
printf("\n");
scanf("%d", &l);
printf("ɼ\n");
for (i = 0; i < l; i++)
{
scanf("%d", &a[i]);
}
average(l, a);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sdl_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: afoures <afoures@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/15 16:23:23 by afoures #+# #+# */
/* Updated: 2018/05/04 15:40:27 by afoures ### ########.fr */
/* */
/* ************************************************************************** */
#include "visu.h"
void put_text(SDL_Surface *surface, SDL_Surface *text, int x, int y)
{
SDL_BlitSurface(text, NULL, surface, &((SDL_Rect){x, y, 0, 0}));
}
void put_pixel(SDL_Surface *surface, int x, int y, Uint32 pixel)
{
((Uint32 *)surface->pixels)[y * surface->w + x] = pixel;
}
void put_rect(SDL_Surface *surface, t_rect rectangle, Uint32 pixel)
{
int x;
int y;
y = 0;
while (y < rectangle.heigth)
{
x = 0;
while (x < rectangle.width)
{
put_pixel(surface, rectangle.x + x, rectangle.y + y, pixel);
x++;
}
y++;
}
}
void put_line(SDL_Surface *surface, t_point start, t_point end, Uint32 pixel)
{
t_point d;
t_point s;
int err1;
int err2;
d.x = ft_abs(start.x - end.x);
d.y = ft_abs(start.y - end.y);
s.x = -1 + 2 * (start.x < end.x);
s.y = -1 + 2 * (start.y < end.y);
err1 = ((d.x > d.y) * d.x + (d.x <= d.y) * -d.y) / 2;
while (1)
{
put_pixel(surface, start.x, start.y, pixel);
if (start.x == end.x && start.y == end.y)
break ;
err2 = err1;
err1 -= d.y * (err2 > -d.x);
start.x += s.x * (err2 > -d.x);
err1 += d.x * (err2 < d.y);
start.y += s.y * (err2 < d.y);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define CONST_Incidenza 50
#define CONST_Seguiti 50
#define CONST_Seguaci 1
#define CONST_SeguitiPesati 100
#define CONST_Sorensen 5
#define CONST_HDI 1
#define CONST_RA 100
#define CONST_RWR 100
#define CONST_RWRP 100
static const double Crwr = 0.5;
static const int numIterazioniPseudoInversa = 3;
static const int hashA = 1;
static const int hashB = 1;
static const int prime = 1000000007;
static const int DIMENSIONETABELLA = 1000;
//INFO HASH
// con tabella hash grande 1000 si hanno sovrapposizioni di al più 5 elementi in uno stesso bucket
//INFO GRAFO
// sono 959 nodi, 5000 archi
// max archi in uscita = 94
// max archi in entrata = 22
//TIPI
// tipo 0: rank 1 - 102, sono 43 elementi
// tipo 1: rank 104 - 7196, sono 127 elementi
// tipo 2: rank 7236 - 96059 sono 255 elementi
// tipo 3: rank 96228 - 2147483647 sono 429 elementi
// senza tipo sono 105 elementi
typedef struct nodo {
char *url;
int type;
long long int rank;
struct lista *inizioListaAdiacentiSeguaci; //siti che hanno copiato il nodo
struct lista *inizioListaAdiacentiSeguiti; //siti da cui il nodo ha copiato
int numSeguaci;
int numSeguiti;
int indice; //indice nell'array dei nodi
} nodo_t;
typedef struct arco {
int nodo1;
int nodo2;
double valore;
} arco_t;
typedef struct lista {
struct lista *next;
nodo_t *el;
} lista_t;
typedef struct hashTable {
int a, b;
int n_bucket;
int *overlap;
lista_t **table;
} hashTable_t;
nodo_t* newNodo (char *url) {
nodo_t *new = malloc(sizeof(nodo_t));
new->url = malloc((1+strlen(url))*sizeof(char));
stpcpy(new->url,url);
new->type = 2;
new->rank = 0;
new->inizioListaAdiacentiSeguaci = NULL;
new->inizioListaAdiacentiSeguiti = NULL;
new->numSeguaci = 0;
new->numSeguiti = 0;
return new;
}
lista_t* newElementoLista (nodo_t* elemento, lista_t* next) {
lista_t* new = malloc(sizeof(lista_t*));
new->el = elemento;
new->next = next;
return new;
}
int comparaArchi (const void * elem1, const void * elem2) {
arco_t* x1 = (arco_t*) elem1;
arco_t* x2 = (arco_t*) elem2;
if (x1->valore > x2->valore) return -1;
if (x1->valore < x2->valore) return 1;
return 0;
}
void stampaNodo(nodo_t *sito) {
lista_t* provv;
nodo_t* nodo;
printf("Il sito %s con rank %lli ", sito->url, sito->rank);
if (sito->type!=-1) printf("di tipo %d\n", sito->type);
else printf ("senza tipo\n");
printf("\t ha %d followers\n", sito->numSeguaci);
for (provv=sito->inizioListaAdiacentiSeguaci; provv!=NULL; provv=provv->next) {
nodo = provv->el;
printf("\t\t%s(%lli)\n",nodo->url,nodo->rank);
}
printf("\t ha %d copiati\n", sito->numSeguiti);
for (provv=sito->inizioListaAdiacentiSeguiti; provv!=NULL; provv=provv->next) {
nodo = provv->el;
printf("\t\t%s(%lli)\n",nodo->url,nodo->rank);
}
}
//OPERAZIONI TABELLA HASH
hashTable_t* newHashTable (int expected_size) {
hashTable_t* new = malloc(sizeof(hashTable_t));
new->a = hashA;
new->b = hashB;
new->n_bucket = expected_size;
new->overlap = calloc(expected_size, sizeof(int));
new->table = calloc(expected_size, sizeof(lista_t*));
return new;
}
int hash (hashTable_t* ht, char* parola) {
unsigned long long numero = 0;
int i, lunghezzaStringa = strlen(parola);
for (i = 0; i < lunghezzaStringa-2; i++) numero = 27*(numero + 1 + parola[i] - 'a');
return (((( (ht->a)*numero + (ht->b) ) % prime) + prime ) % prime) % (ht->n_bucket);
}
nodo_t* insert (hashTable_t* ht, char* url) {
int h = hash(ht,url);
(ht->overlap[h])++;
lista_t *provv = (ht->table)[h];
if (provv == NULL) {
ht->table[h] = newElementoLista(newNodo(url), NULL);
return ht->table[h]->el;
}
else {
while (provv->next!=NULL) provv=provv->next;
provv->next = newElementoLista(newNodo(url), NULL);
return provv->next->el;
}
}
nodo_t* urlToPointer (hashTable_t* ht, char *url) {
lista_t *provv;
nodo_t *nodo;
for (provv=(ht->table)[hash(ht,url)]; provv!=NULL; provv=provv->next) {
nodo = provv->el;
if (strcmp(nodo->url, url)==0) return nodo;
}
return NULL;
}
//OPERAZIONI CON MATRICI
void multiplicationMatrix(double* a, double* b, double* c, int size) {
int i,j,k;
for (i=0;i<size;i++) for (j=0;j<size;j++) {
c[i*size+j] = 0;
for (k=0;k<size;k++) c[i*size+j] += a[i*size+k] * b[k*size+j];
}
}
void multiplicationMatrixPerScalar(double* a, double scalar, int size) {
int i,j;
for (i=0;i<size;i++) for (j=0;j<size;j++) a[i*size+j] *= scalar;
}
void transposeMatrix(double* a, int size) {
double temp;
int i,j;
for (i=0;i<size;i++) for (j=0;j<i;j++) {
temp = a[i*size+j];
a[i*size+j] = a[j*size+i];
a[j*size+i] = temp;
}
}
double* pseudoInverseMatrix(double* P, int numIterazioni, int size) {
//calcola l'inversa di Id - P tramite serie geometrica troncata
double* potenzaDiP = malloc(size*size*sizeof(double));
double* potenzaDiPsuccessiva = malloc(size*size*sizeof(double));
int i,j,k;
double* result = calloc(size*size,sizeof(double));
for (i=0;i<size;i++) result[i*size+i] = 1;
for (i=0;i<size;i++) for (j=0;j<size;j++) result[i*size+j] += (potenzaDiP[i*size+j] = P[i*size+j]);
for (k=1;k<numIterazioni;k++) {
multiplicationMatrix(P, potenzaDiP, potenzaDiPsuccessiva, size);
for (i=0;i<size;i++) for (j=0;j<size;j++) result[i*size+j] += (potenzaDiP[i*size+j] = potenzaDiPsuccessiva[i*size+j]);
}
return result;
}
void normalizza(double* a, int size) {
int i,j;
double max=0;
for(i=0;i<size;i++) for(j=0;j<size;j++) if (a[i*size+j] > max) max=a[i*size+j];
if (max!=0) for(i=0;i<size;i++) for(j=0;j<size;j++) a[i*size+j] /= max;
}
//CHECK "TRANSITIVITA" DEI RISULTATI
double transitivityCheck_CasoMediano(double* a, double range, int size) {
// A[i,j] deve stare nel range giusto
int i,j,k,coppieBuone=0,coppieCattive=0;
for(i=0;i<size;i++) for(j=0;j<i;j++) for(k=0;k<size;k++) if(k!=i && k!=j) {
if ((a[i*size+j] > a[i*size+k]*a[k*size+j]-range) && (a[i*size+j] < a[i*size+k]*a[k*size+j]+range)) coppieBuone++;
else coppieCattive++;
}
return ((double)coppieBuone)/(coppieBuone+coppieCattive);
}
double transitivityCheck_CasoMinorato(double* a, int size) {
// A[i,j] deve valere almeno tot
int i,j,k,coppieBuone=0,coppieCattive=0;
for(i=0;i<size;i++) for(j=0;j<i;j++) for(k=0;k<size;k++) if(k!=i && k!=j) {
if ( a[i*size+j] >= 1 - (1-a[i*size+k]) - (1-a[k*size+j]) ) coppieBuone++;
else coppieCattive++;
}
return ((double)coppieBuone)/(coppieBuone+coppieCattive);
}
double transitivityCheck_CasoMaggiorato(double* a, int size) {
// A[i,j] deve valere al massimo tot
int i,j,k,differenza,coppieBuone=0,coppieCattive=0;
for(i=0;i<size;i++) for(j=0;j<i;j++) for(k=0;k<size;k++) if(k!=i && k!=j) {
differenza = a[i*size+k] - a[k*size+j];
if (differenza < 0) differenza = -differenza;
if ( a[i*size+j] <= 1 - differenza ) coppieBuone++;
else coppieCattive++;
}
return ((double)coppieBuone)/(coppieBuone+coppieCattive);
}
int main() {
FILE *archi = fopen("Input - archi.txt","r");
FILE *ranks = fopen("Input - ranks.txt","r");
int numNodi=0;
int i, j, c1, type;
long long int rank;
float c2;
double media,numero,max;
char urlStart[50];
char urlEnd[50];
nodo_t *nodoStart, *nodoEnd, *nodo1, *nodo2, *nodo;
lista_t *provv, *provv1, *provv2;
hashTable_t* ht = newHashTable(DIMENSIONETABELLA);
//METTO NODI E ARCHI IN TABELLA HASH
for (i=0; i<5000; i++) {
fscanf(archi, "%d %s %s %d %f %f %f", &c1, urlStart, urlEnd, &c1, &c2, &c2, &c2);
//INSERISCO I NODI SE NON CI SONO GIA
if ( (nodoStart = urlToPointer(ht, urlStart)) == NULL) {
numNodi++;
nodoStart = insert(ht,urlStart);
}
if ( (nodoEnd = urlToPointer(ht, urlEnd)) == NULL) {
numNodi++;
nodoEnd = insert(ht,urlEnd);
}
//INSERISCO L'ARCO
nodoStart->inizioListaAdiacentiSeguiti = newElementoLista(nodoEnd, nodoStart->inizioListaAdiacentiSeguiti);
nodoStart->numSeguiti++;
nodoEnd->inizioListaAdiacentiSeguaci = newElementoLista(nodoStart, nodoEnd->inizioListaAdiacentiSeguaci);
nodoEnd->numSeguaci++;
}
printf("\nCi sono %d nodi, con tabella hash grande %d\n",numNodi,DIMENSIONETABELLA);
//AGGIUNGO TIPO E RANK DATI DA AMAZON ALEXA
for (i=0; i<854; i++) {
fscanf(ranks, "%d %s %d %lli",&c1, urlStart, &type, &rank);
nodo = urlToPointer(ht, urlStart);
nodo->type = type;
nodo->rank = rank;
}
//METTO I NODI IN UN ARRAY (di puntatori)
j=0;
nodo_t** arrayNodi = malloc(numNodi*sizeof(nodo_t*));
for (i=0; i < ht->n_bucket; i++)
for (provv = ht->table[i]; provv!=NULL; provv=provv->next) {
nodo = provv->el;
nodo->indice = j;
arrayNodi[j] = nodo;
j++;
}
//CALCOLO ALCUNI INDICI DI (supposta) SIMILITUDINE
//INDICE 0
//TABELLA INCIDENZA
int *tabellaIncidenza = calloc(numNodi*numNodi, sizeof(int));
double *tabellaIncidenzaSimmetrica = malloc(numNodi*numNodi*sizeof(double));
if (CONST_Incidenza!=0) {
for (i=0;i<numNodi;i++)
for (provv = arrayNodi[i]->inizioListaAdiacentiSeguiti; provv!=NULL; provv=provv->next) {
nodo = provv->el;
tabellaIncidenza[i*numNodi + nodo->indice] = 1;
}
printf("\nHo calcolato la tabella di incidenza\n");
//simmetrizzo
for (i=0;i<numNodi;i++) for (j=0;j<i;j++) tabellaIncidenzaSimmetrica[i*numNodi+j] = tabellaIncidenza[i*numNodi+j]+tabellaIncidenza[j*numNodi+i];
}
//INDICE 1 (CN)
//NUMERO COPIATI IN COMUNE
double *seguitiInComune = calloc(numNodi*numNodi, sizeof(double));
FILE *seguitiInComuneFILE;
if (CONST_Seguiti!=0 && (CONST_Sorensen!=0 || CONST_HDI!=0)) {
for (i=0;i<numNodi;i++)
for (provv1=arrayNodi[i]->inizioListaAdiacentiSeguaci; provv1!=NULL; provv1=provv1->next) {
nodo1 = provv1->el;
for (provv2=provv1->next; provv2!=NULL; provv2=provv2->next) {
nodo2 = provv2->el;
if (nodo1->indice > nodo2->indice) seguitiInComune[nodo1->indice * numNodi + nodo2->indice]++;
else seguitiInComune[nodo2->indice * numNodi + nodo1->indice]++;
}
}
seguitiInComuneFILE = fopen("Index 1 - Common Neighbors Seguiti.txt","w");
for (i=0;i<numNodi;i++) {
for (j=0;j<i;j++) fprintf(seguitiInComuneFILE,"%0.0f ", seguitiInComune[i*numNodi+j]);
fprintf(seguitiInComuneFILE,"\n");
}
printf("Ho calcolato Common Neighbour Index (seguiti)\n");
}
//NUMERO SEGUACI IN COMUNE
FILE *seguaciInComuneFILE;
double *seguaciInComune = calloc(numNodi*numNodi, sizeof(double));
if (CONST_Seguaci!=0) {
for (i=0;i<numNodi;i++)
for (provv1=arrayNodi[i]->inizioListaAdiacentiSeguiti; provv1!=NULL; provv1=provv1->next) {
nodo1 = provv1->el;
for (provv2=provv1->next; provv2!=NULL; provv2=provv2->next) {
nodo2 = provv2->el;
if (nodo1->indice > nodo2->indice) seguaciInComune[nodo1->indice * numNodi + nodo2->indice]++;
else seguaciInComune[nodo2->indice * numNodi + nodo1->indice]++;
}
}
seguaciInComuneFILE = fopen("Index 1 - Common Neighbors Seguaci.txt","w");
for (i=0;i<numNodi;i++) {
for (j=0;j<i;j++) fprintf(seguaciInComuneFILE,"%0.0f ", seguaciInComune[i*numNodi+j]);
fprintf(seguaciInComuneFILE,"\n");
}
printf("Ho calcolato Common Neighbour Index (seguaci)\n");
}
//INDICE 2
//NUMERO COPIATI IN COMUNE PESATI CON RANK (Se due siti copiano entrambi un sito semisconosciuto vuol dire che avevano un buon motivo per farlo)
double *seguitiInComunePESATI = calloc(numNodi*numNodi, sizeof(double));
FILE *seguitiInComunePesatiFILE;
if (CONST_SeguitiPesati!=0) {
for (i=0;i<numNodi;i++)
for (provv1=arrayNodi[i]->inizioListaAdiacentiSeguaci; provv1!=NULL; provv1=provv1->next) {
nodo1 = provv1->el;
for (provv2=provv1->next; provv2!=NULL; provv2=provv2->next) {
nodo2 = provv2->el;
if (nodo1->indice > nodo2->indice) seguitiInComunePESATI[nodo1->indice * numNodi + nodo2->indice] += arrayNodi[i]->type;
else seguitiInComunePESATI[nodo2->indice * numNodi + nodo1->indice] += arrayNodi[i]->type;
}
}
seguitiInComunePesatiFILE = fopen("Index 2 - Common Neighbors Seguiti Pesati.txt","w");
for (i=0;i<numNodi;i++) {
for (j=0;j<i;j++) fprintf(seguitiInComunePesatiFILE,"%0.0f ", seguitiInComunePESATI[i*numNodi+j]);
fprintf(seguitiInComunePesatiFILE,"\n");
}
printf("Ho calcolato Common Neighbour Pesati Index\n");
}
//INDICE 3 (Sorensen index)
//NUMERO COPIATI IN COMUNE DIVISO PER MEDIA DI NUMERO DI NODI COPIATI DAI DUE
double *seguitiInComuneSorensen = calloc(numNodi*numNodi, sizeof(double));
FILE *seguitiInComuneSorensenFILE;
if (CONST_Sorensen!=0) {
for (i=0;i<numNodi;i++) for(j=0;j<i;j++) {
media = ( arrayNodi[i]->numSeguiti + arrayNodi[j]->numSeguiti )/2.0;
if (media!=0) seguitiInComuneSorensen[i*numNodi+j] = seguitiInComune[i*numNodi+j] / media;
else seguitiInComuneSorensen[i*numNodi+j] = 0;
}
seguitiInComuneSorensenFILE = fopen("Index 3 - Sorensen.txt","w");
for (i=0;i<numNodi;i++) {
for (j=0;j<i;j++) fprintf(seguitiInComuneSorensenFILE,"%0.3f ", seguitiInComuneSorensen[i*numNodi+j]);
fprintf(seguitiInComuneSorensenFILE,"\n");
}
printf("Ho calcolato Sorensen Index\n");
}
//INDICE 4 (HDI)
//NUMERO COPIATI IN COMUNE DIVSO PER MAX DI NUMERO DI NODI COPIATI DAI DUE
double *seguitiInComuneHubDepressed = calloc(numNodi*numNodi, sizeof(double));
FILE *seguitiInComuneHubDepressedFILE;
if (CONST_HDI!=0) {
for (i=0;i<numNodi;i++) for(j=0;j<i;j++) {
max = arrayNodi[i]->numSeguiti;
if (arrayNodi[j]->numSeguiti > max) max = arrayNodi[j]->numSeguiti;
if (max!=0) seguitiInComuneHubDepressed[i*numNodi+j] = seguitiInComune[i*numNodi+j] / max;
else seguitiInComuneHubDepressed[i*numNodi+j] = 0;
}
seguitiInComuneHubDepressedFILE = fopen("Index 4 - HDI.txt","w");
for (i=0;i<numNodi;i++) {
for (j=0;j<i;j++) fprintf(seguitiInComuneHubDepressedFILE,"%0.3f ", seguitiInComuneHubDepressed[i*numNodi+j]);
fprintf(seguitiInComuneHubDepressedFILE,"\n");
}
printf("Ho calcolato HDI Index\n");
}
//INDICE 5 (RA)
//SOMMA SUI SEGUITI IN COMUNE DI ( 1 / NUMERO SEGUACI )
double *resourceAllocation = calloc(numNodi*numNodi, sizeof(double));
FILE *resourceAllocationFILE;
if (CONST_RA!=0) {
for (i=0;i<numNodi;i++) //per comodità inverto l'ordine delle sommatorie e sommo prima sui nodi
for (provv1=arrayNodi[i]->inizioListaAdiacentiSeguaci; provv1!=NULL; provv1=provv1->next) {
nodo1 = provv1->el;
for (provv2=provv1->next; provv2!=NULL; provv2=provv2->next) {
nodo2 = provv2->el;
if (nodo1->indice > nodo2->indice) resourceAllocation[nodo1->indice * numNodi + nodo2->indice] += 1.0/arrayNodi[i]->numSeguaci;
else resourceAllocation[nodo2->indice * numNodi + nodo1->indice] += 1.0/arrayNodi[i]->numSeguaci;
}
}
resourceAllocationFILE = fopen("Index 5 - RA.txt","w");
for (i=0;i<numNodi;i++) {
for (j=0;j<i;j++) fprintf(resourceAllocationFILE,"%0.3f ", resourceAllocation[i*numNodi+j]);
fprintf(resourceAllocationFILE,"\n");
}
printf("Ho calcolato RA Index\n");
}
//INDICE 6 (RWR)
//RANDOM WALK WITH RESTART
double* randomWalkWithRestart = calloc(numNodi*numNodi,sizeof(double));
double* transitionMatrix;
double* pseudoInversa;
double* identity;
FILE *randomWalkWithRestartFILE;
FILE *identityFILE;
if (CONST_RWR!=0) {
//calcolo la matrice di transizione
transitionMatrix = calloc(numNodi*numNodi,sizeof(double));
for (i=0;i<numNodi;i++) {
if (arrayNodi[i]->numSeguiti != 0) {
numero = 1.0 / arrayNodi[i]->numSeguiti;
for (provv=arrayNodi[i]->inizioListaAdiacentiSeguiti; provv!=NULL; provv=provv->next) transitionMatrix[i*numNodi + provv->el->indice] = numero;
}
else {
numero = 1.0 / (numNodi-1);
for (j=0;j<numNodi;j++) if (i!=j) transitionMatrix[i*numNodi+j] = numero;
}
}
//calcolo la pseudoInversa = (Id - c*transitionMatrixT)^(-1)
transposeMatrix(transitionMatrix, numNodi);
multiplicationMatrixPerScalar(transitionMatrix, Crwr, numNodi);
pseudoInversa = pseudoInverseMatrix(transitionMatrix, numIterazioniPseudoInversa, numNodi);
//check inversa
for (i=0;i<numNodi;i++) for(j=0;j<numNodi;j++) transitionMatrix[i*numNodi+j] = -transitionMatrix[i*numNodi+j];
for (i=0;i<numNodi;i++) transitionMatrix[i*numNodi+i] += 1;
identity = calloc(numNodi*numNodi,sizeof(double));
multiplicationMatrix(transitionMatrix, pseudoInversa, identity, numNodi);
identityFILE = fopen("Identity Check.txt","w");
for (i=0;i<numNodi;i++) {
for (j=0;j<numNodi;j++) fprintf(identityFILE,"%5.5f ", identity[i*numNodi+j]);
fprintf(identityFILE,"\n");
}
//calcolo il Random Walk With Restart Index
multiplicationMatrixPerScalar(pseudoInversa, 1-Crwr, numNodi);
for (i=0;i<numNodi;i++) for (j=0;j<i;j++) randomWalkWithRestart[i*numNodi+j] = pseudoInversa[i*numNodi+j] + pseudoInversa[j*numNodi+i];
randomWalkWithRestartFILE = fopen("Index 6 - RWR.txt","w");
for (i=0;i<numNodi;i++) {
for (j=0;j<i;j++) fprintf(randomWalkWithRestartFILE,"%0.3f ", randomWalkWithRestart[i*numNodi+j]);
fprintf(randomWalkWithRestartFILE,"\n");
}
printf("Ho calcolato il RWR Index\n");
}
//INDICE 7 (RWR pesato)
//RANDOM WALK WITH RESTART CON MATRICE DI TRANSIZIONE PESATA CON RANK
int sommaTypeSeguiti;
double* randomWalkWithRestartPesato = calloc(numNodi*numNodi,sizeof(double));
double* transitionMatrixPesata;
double* pseudoInversaPesata;
double* identityPesata;
FILE *randomWalkWithRestartPesatoFILE;
FILE *identityPesataFILE;
if (CONST_RWRP!=0) {
//calcolo la matrice di transizione
transitionMatrixPesata = calloc(numNodi*numNodi,sizeof(double));
for (i=0;i<numNodi;i++) {
if (arrayNodi[i]->numSeguiti != 0) {
sommaTypeSeguiti=0;
for (provv=arrayNodi[i]->inizioListaAdiacentiSeguiti; provv!=NULL; provv=provv->next) sommaTypeSeguiti += provv->el->type + 1;
for (provv=arrayNodi[i]->inizioListaAdiacentiSeguiti; provv!=NULL; provv=provv->next) {
nodo = provv->el;
transitionMatrixPesata[i*numNodi + nodo->indice] = (nodo->type + 1.0)/sommaTypeSeguiti;
}
}
else {
numero = 1.0 / (numNodi-1);
for (j=0;j<numNodi;j++) if (i!=j) transitionMatrix[i*numNodi+j] = numero;
}
}
//calcolo la pseudoInversa = (Id - c*transitionMatrixT)^(-1)
transposeMatrix(transitionMatrixPesata, numNodi);
multiplicationMatrixPerScalar(transitionMatrixPesata, Crwr, numNodi);
pseudoInversaPesata = pseudoInverseMatrix(transitionMatrixPesata, numIterazioniPseudoInversa, numNodi);
//check inversa
for (i=0;i<numNodi;i++) for(j=0;j<numNodi;j++) transitionMatrixPesata[i*numNodi+j] = -transitionMatrixPesata[i*numNodi+j];
for (i=0;i<numNodi;i++) transitionMatrixPesata[i*numNodi+i] += 1;
identityPesata = calloc(numNodi*numNodi,sizeof(double));
multiplicationMatrix(transitionMatrixPesata, pseudoInversaPesata, identityPesata, numNodi);
identityPesataFILE = fopen("Identity Check PESATA.txt","w");
for (i=0;i<numNodi;i++) {
for (j=0;j<numNodi;j++) fprintf(identityPesataFILE,"%5.5f ", identityPesata[i*numNodi+j]);
fprintf(identityPesataFILE,"\n");
}
//calcolo il Random Walk With Restart Index
multiplicationMatrixPerScalar(pseudoInversaPesata, 1-Crwr, numNodi);
for (i=0;i<numNodi;i++) for (j=0;j<i;j++) randomWalkWithRestartPesato[i*numNodi+j] = pseudoInversaPesata[i*numNodi+j] + pseudoInversaPesata[j*numNodi+i];
randomWalkWithRestartPesatoFILE = fopen("Index 7 - RWRP.txt","w");
for (i=0;i<numNodi;i++) {
for (j=0;j<i;j++) fprintf(randomWalkWithRestartPesatoFILE,"%0.3f ", randomWalkWithRestartPesato[i*numNodi+j]);
fprintf(randomWalkWithRestartPesatoFILE,"\n");
}
printf("Ho calcolato il RWRP Index\n");
}
//INDICE FINALE
//Somma di tutti gli indici pesati con la costante scelta
normalizza(tabellaIncidenzaSimmetrica, numNodi);
normalizza(seguitiInComune, numNodi);
normalizza(seguaciInComune, numNodi);
normalizza(seguitiInComunePESATI, numNodi);
normalizza(seguitiInComuneSorensen, numNodi);
normalizza(seguitiInComuneHubDepressed, numNodi);
normalizza(resourceAllocation, numNodi);
normalizza(randomWalkWithRestart, numNodi);
normalizza(randomWalkWithRestartPesato, numNodi);
printf("\n\nIndice \tUpperBound \tLowerBound \tCheck 0.25 \tCheck 0.1 \tCheck 0.01\n");
printf ("I. Simmetrica =\t %0.3f,\t %0.3f,\t\t %0.5f,\t %0.5f,\t %0.5f\n",
transitivityCheck_CasoMaggiorato(tabellaIncidenzaSimmetrica,numNodi),
transitivityCheck_CasoMinorato(tabellaIncidenzaSimmetrica,numNodi),
transitivityCheck_CasoMediano(tabellaIncidenzaSimmetrica,0.25,numNodi),
transitivityCheck_CasoMediano(tabellaIncidenzaSimmetrica,0.1,numNodi),
transitivityCheck_CasoMediano(tabellaIncidenzaSimmetrica,0.01,numNodi) );
printf ("SeguitiIC =\t %0.3f,\t %0.3f,\t\t %0.5f,\t %0.5f,\t %0.5f\n",
transitivityCheck_CasoMaggiorato(seguitiInComune,numNodi),
transitivityCheck_CasoMinorato(seguitiInComune,numNodi),
transitivityCheck_CasoMediano(seguitiInComune,0.25,numNodi),
transitivityCheck_CasoMediano(seguitiInComune,0.1,numNodi),
transitivityCheck_CasoMediano(seguitiInComune,0.01,numNodi) );
printf ("SeguaciIC =\t %0.3f,\t %0.3f,\t\t %0.5f,\t %0.5f,\t %0.5f\n",
transitivityCheck_CasoMaggiorato(seguaciInComune,numNodi),
transitivityCheck_CasoMinorato(seguaciInComune,numNodi),
transitivityCheck_CasoMediano(seguaciInComune,0.25,numNodi),
transitivityCheck_CasoMediano(seguaciInComune,0.1,numNodi),
transitivityCheck_CasoMediano(seguaciInComune,0.01,numNodi) );
printf ("SeguitiICP =\t %0.3f,\t %0.3f,\t\t %0.5f,\t %0.5f,\t %0.5f\n",
transitivityCheck_CasoMaggiorato(seguitiInComunePESATI,numNodi),
transitivityCheck_CasoMinorato(seguitiInComunePESATI,numNodi),
transitivityCheck_CasoMediano(seguitiInComunePESATI,0.25,numNodi),
transitivityCheck_CasoMediano(seguitiInComunePESATI,0.1,numNodi),
transitivityCheck_CasoMediano(seguitiInComunePESATI,0.01,numNodi) );
printf ("SegSorensen =\t %0.3f,\t %0.3f,\t\t %0.5f,\t %0.5f,\t %0.5f\n",
transitivityCheck_CasoMaggiorato(seguitiInComuneSorensen,numNodi),
transitivityCheck_CasoMinorato(seguitiInComuneSorensen,numNodi),
transitivityCheck_CasoMediano(seguitiInComuneSorensen,0.25,numNodi),
transitivityCheck_CasoMediano(seguitiInComuneSorensen,0.1,numNodi),
transitivityCheck_CasoMediano(seguitiInComuneSorensen,0.01,numNodi) );
printf ("HDI =\t\t %0.3f,\t %0.3f,\t\t %0.5f,\t %0.5f,\t %0.5f\n",
transitivityCheck_CasoMaggiorato(seguitiInComuneHubDepressed,numNodi),
transitivityCheck_CasoMinorato(seguitiInComuneHubDepressed,numNodi),
transitivityCheck_CasoMediano(seguitiInComuneHubDepressed,0.25,numNodi),
transitivityCheck_CasoMediano(seguitiInComuneHubDepressed,0.1,numNodi),
transitivityCheck_CasoMediano(seguitiInComuneHubDepressed,0.01,numNodi) );
printf ("RA =\t\t %0.3f,\t %0.3f,\t\t %0.5f,\t %0.5f,\t %0.5f\n",
transitivityCheck_CasoMaggiorato(resourceAllocation,numNodi),
transitivityCheck_CasoMinorato(resourceAllocation,numNodi),
transitivityCheck_CasoMediano(resourceAllocation,0.25,numNodi),
transitivityCheck_CasoMediano(resourceAllocation,0.1,numNodi),
transitivityCheck_CasoMediano(resourceAllocation,0.01,numNodi) );
printf ("RWR =\t\t %0.3f,\t %0.3f,\t\t %0.5f,\t %0.5f,\t %0.5f\n",
transitivityCheck_CasoMaggiorato(randomWalkWithRestart,numNodi),
transitivityCheck_CasoMinorato(randomWalkWithRestart,numNodi),
transitivityCheck_CasoMediano(randomWalkWithRestart,0.25,numNodi),
transitivityCheck_CasoMediano(randomWalkWithRestart,0.1,numNodi),
transitivityCheck_CasoMediano(randomWalkWithRestart,0.01,numNodi) );
printf ("RWRP =\t\t %0.3f,\t %0.3f,\t\t %0.5f,\t %0.5f,\t %0.5f\n",
transitivityCheck_CasoMaggiorato(randomWalkWithRestartPesato,numNodi),
transitivityCheck_CasoMinorato(randomWalkWithRestartPesato,numNodi),
transitivityCheck_CasoMediano(randomWalkWithRestartPesato,0.25,numNodi),
transitivityCheck_CasoMediano(randomWalkWithRestartPesato,0.1,numNodi),
transitivityCheck_CasoMediano(randomWalkWithRestartPesato,0.01,numNodi) );
double *similarityIndex = calloc(numNodi*numNodi, sizeof(double));
for (i=0;i<numNodi;i++) for(j=0;j<i;j++) {
similarityIndex[i*numNodi+j] =
CONST_Incidenza * tabellaIncidenzaSimmetrica[i*numNodi+j] +
CONST_Seguiti * seguitiInComune[i*numNodi+j] +
CONST_Seguaci * seguaciInComune[i*numNodi+j] +
CONST_SeguitiPesati * seguitiInComunePESATI[i*numNodi+j] +
CONST_Sorensen * seguitiInComuneSorensen[i*numNodi+j] +
CONST_HDI * seguitiInComuneHubDepressed[i*numNodi+j] +
CONST_RA * resourceAllocation[i*numNodi+j] +
CONST_RWR * randomWalkWithRestart[i*numNodi+j] +
CONST_RWRP * randomWalkWithRestartPesato[i*numNodi+j];
}
normalizza(similarityIndex, numNodi);
printf ("\n\nFINALE =\t %0.3f,\t %0.3f,\t\t %0.5f,\t %0.5f,\t %0.5f\n",
transitivityCheck_CasoMaggiorato(similarityIndex,numNodi),
transitivityCheck_CasoMinorato(similarityIndex,numNodi),
transitivityCheck_CasoMediano(similarityIndex,0.25,numNodi),
transitivityCheck_CasoMediano(similarityIndex,0.1,numNodi),
transitivityCheck_CasoMediano(similarityIndex,0.01,numNodi) );
//ordino gli archi per valore finale
arco_t* arrayArchi = malloc(numNodi*(numNodi-1)/2 * sizeof(arco_t));
int counter=0;
for (i=0;i<numNodi;i++) for (j=0;j<i;j++) {
arrayArchi[counter].nodo1 = arrayNodi[i]->indice;
arrayArchi[counter].nodo2 = arrayNodi[j]->indice;
arrayArchi[counter].valore = similarityIndex[i*numNodi+j];
counter++;
}
qsort(arrayArchi, counter, sizeof(arco_t), comparaArchi);
FILE *OrderedPairsFILE = fopen("ORDERED PAIRS.txt","w");
fprintf(OrderedPairsFILE, "Punteggio \tUrl 1 \t- Url 2\n");
for (i=0; i<counter; i++) {
fprintf(OrderedPairsFILE, "%5.6f \t%s \t- %s\n", arrayArchi[i].valore, arrayNodi[arrayArchi[i].nodo1]->url, arrayNodi[arrayArchi[i].nodo2]->url);
}
FILE *BindingIndiceUrlFILE = fopen("Binding Indice-Url.txt","w");
fprintf(BindingIndiceUrlFILE, "Indice \tUrl\n");
for (i=0; i<numNodi; i++) {
fprintf(BindingIndiceUrlFILE, "%d\t- %s\n", i, arrayNodi[i]->url);
}
return 0;
}
|
C
|
/* _Fmtval function */
#include <limits.h>
#include "lr/locale.h"
#include <stdio.h>
#include <string.h>
/* marcos */
#define FN_INT_CUR -2 /* International Monetary Amount */
#define FN_LCL_CUR -1 /* Local Monetary Amount */
char *_Fmtval(char *buf, double d, int fdarg)
{
/* format number by locale-specific rules */
char *cur_sym, dec_pt, *grps, grp_sep, *sign;
const char *fmt;
int fd, neg;
struct lconv *p = localeconv();
if (0 <= d) {
neg = 0;
} else {
d = -d, neg = 1;
}
if (fdarg == FN_INT_CUR) {
/* get internatinal currency parameters */
cur_sym = p->int_curr_symbol;
dec_pt = p->mon_decimal_point[0];
fmt = "$-V";
fd = p->int_frac_digits;
grps = p->mon_grouping;
grp_sep = p->mon_thousands_sep[0];
sign = neg ? p->negative_sign : p->positive_sign;
} else if (fdarg == FN_LCL_CUR) {
/* get local currency parameter */
static const char *ftab[2][2][5] = {
{
{"(V$)", "-V$", "V$-", "V-$", "V$-"},
{"($V)", "-$V", "$V-", "-$V", "$-V"}
},
{
{"(V $)", "-V $", "V $-", "V- $", "V $-"},
{"($ V)", "-$ V", "$ V-", "-$ V", "$ -V"}
}
};
cur_sym = p->currency_symbol;
dec_pt = p->mon_decimal_point[0];
if (neg) {
fmt = ftab[p->n_sep_by_space == 1][p->n_cs_precedes == 1][p->n_sign_posn < 0 || 4 < p->p_sign_posn ? 0 : p->p_sign_posn];
} else {
fmt = ftab[p->p_sep_by_space == 1][p->p_cs_precedes == 1][p->p_sign_posn < 0 || 4 < p->p_sign_posn ? 0 : p->p_sign_posn];
}
fd = p->frac_digits;
grps = p->mon_grouping;
grp_sep = p->mon_thousands_sep[0];
sign = neg ? p->negative_sign : p->positive_sign;
} else {
/* get numeric parameters (cur-sym not used) */
dec_pt = p->decimal_point[0];
fmt = "-V";
fd = fdarg;
grps = p->grouping;
grp_sep = p->thousands_sep[0];
sign = neg ? "-" : "";
}
{
/* build string in buf under control of fmt */
char *end, *s;
const char *g;
size_t i, ns, ng;
for (s = buf; *fmt; ++fmt, s += strlen(s))
switch (*fmt) { /* process a format char */
case '$': /* insert currency symbol string */
strcpy(s, cur_sym);
break;
case '-': /* insert sign string */
strcpy(s, sign);
break;
default: /* insert literal format char */
*s++ = *fmt, *s = '\0';
break;
case 'V': /* insert formatted value */
sprintf(s, "%#.*f", 0 < fd && fd != CHAR_MAX ? fd : 0, d);
end = strchr(s, p->decimal_point[0]);
for (ns = 0, i = end - s, g = grps; 0 < i; ++ns) {
/* count separators to add */
ng = g[0] - '0';
if (ng <= 0 || i <= ng || ng == CHAR_MAX)
break;
i -= ng;
if (g[1] != '0')
++g;
}
memmove(end + ns, end, strlen(end) + 1);
i = end - s, end += ns;
*end = 0 <= fd && fd != CHAR_MAX ? dec_pt : '\0';
for (g = grps; 0 < i; --ns) {
/* copy up and insert separators */
ng = g[0] - '0';
if (ng <= 0 || i <= ng || ng == CHAR_MAX)
break;
i -= ng, end -= ng;
memmove(end, end - ns, ng);
*--end = grp_sep;
if (g[1] != '0')
++g;
}
}
}
return (buf);
}
|
C
|
#include <stdio.h>
int main(){
int i, sum = 0;
int mean[] = {1,2,3,4,5};
for(i=0;i<5;i++){
sum = sum + mean[i];
}
int length;
length = ( sizeof(mean) / sizeof(mean[0]) );
sum = sum / length;
printf(" = %d\n", sum);
return 0;
}
|
C
|
#include <stdio.h>
int main(int argc, char const *argv[])
{
int n;
scanf("%d", &n);
float bil[n];
int depan[n];
int belakang[n];
int i;
for(i=0; i<n; i++){
scanf("%f", &bil[i]);
}
for(i=0; i<n; i++){
depan[i] = bil[i];
belakang[i] = (bil[i] - depan[i]) * 10 + .5;
}
int j=0;
while(j<n){
if((depan[j] % 2 == 0) && (belakang[j] % 2 == 0)){
printf("%.1f\n",bil[j] );
}
j++;
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
void* tmain(void* arg) {
printf( "[thread %08lx] thread group id (pid): %d\n",
(unsigned long)pthread_self(), getpid() ); // requires <unistd.h>
return NULL;
}
int main ( int argc, char** argv ) {
pthread_t tid;
if ( pthread_create(&tid, NULL, &tmain, NULL) == 0 ) {
printf("[main] pthread created: %08lx\n", (unsigned long)tid);
}
else {
printf("[main] pthread creation has failed: %s\n", strerror(errno));
}
printf("[main] thread group id (pid): %d\n", getpid());
exit(0); // requires <stdlib.h>
}
|
C
|
/******************************************************************************/
/* */
/* COMPRESS.H */
/* */
/******************************************************************************/
/* */
/* Author : Ross Williams. */
/* Date : December 1989. */
/* */
/* This header file defines the interface to a set of functions called */
/* 'compress', each member of which implements a particular data compression */
/* algorithm. */
/* */
/* Normally in C programming, for each .H file, there is a corresponding .C */
/* file that implements the functions promised in the .H file. */
/* Here, there are many .C files corresponding to this header file. */
/* Each comforming implementation file contains a single function */
/* called 'compress' that implements a single data compression */
/* algorithm that conforms with the interface specified in this header file. */
/* Only one algorithm can be linked in at a time in this organization. */
/* */
/******************************************************************************/
/* */
/* DEFINITION OF FUNCTION COMPRESS */
/* =============================== */
/* */
/* Summary of Function Compress */
/* ---------------------------- */
/* The action that 'compress' takes depends on its first argument called */
/* 'action'. The function provides three actions: */
/* */
/* - Return information about the algorithm. */
/* - Compress a block of memory. */
/* - Decompress a block of memory. */
/* */
/* Parameters */
/* ---------- */
/* See the formal C definition later for a description of the parameters. */
/* */
/* Constants */
/* --------- */
/* COMPRESS_OVERRUN: The constant COMPRESS_OVERRUN defines by how many bytes */
/* an algorithm is allowed to expand a block during a compression operation. */
/* */
/* Although compression algorithms usually compress data, there will always */
/* be data that a given compressor will expand (this can be proven). */
/* Fortunately, the degree of expansion can be limited to a single bit, by */
/* copying over the input data if the data gets bigger during compression. */
/* To allow for this possibility, the first bit of a compressed */
/* representation can be used as a flag indicating whether the */
/* input data was copied over, or truly compressed. In practice, the first */
/* byte would be used to store this bit so as to maintain byte alignment. */
/* */
/* Unfortunately, in general, the only way to tell if an algorithm will */
/* expand a particular block of data is to run the algorithm on the data. */
/* If the algorithm does not continuously monitor how many output bytes it */
/* has written, it might write an output block far larger than the input */
/* block before realizing that it has done so. */
/* On the other hand, continuous checks on output length are inefficient. */
/* */
/* To cater for all these problems, this interface definition: */
/* > Allows a compression algorithm to return an output block that is up to */
/* COMPRESS_OVERRUN bytes longer than the input block. */
/* > Allows a compression algorithm to write up to COMPRESS_OVERRUN bytes */
/* more than the length of the input block to the memory of the output */
/* block regardless of the length of the output block eventually returned. */
/* This allows an algorithm to overrun the length of the input block in the */
/* output block by up to COMPRESS_OVERRUN bytes between expansion checks. */
/* */
/* The problem does not arise for decompression. */
/* */
/* Identity Action */
/* --------------- */
/* > action must be COMPRESS_ACTION_IDENTITY. */
/* > p_dst_len must point to a longword to receive a longword address. */
/* > The value of the other parameters does not matter. */
/* > After execution, the longword that p_dst_len points to will be a pointer */
/* to a structure of type compress_identity. */
/* Thus, for example, after the call, (*p_dst_len)->memory will return the */
/* number of bytes of working memory that the algorithm requires to run. */
/* > The values of the identity structure returned are fixed constant */
/* attributes of the algorithm and must not vary from call to call. */
/* */
/* Common Requirements for Compression and Decompression Actions */
/* ------------------------------------------------------------- */
/* > wrk_mem must point to an unused block of memory of a length specified in */
/* the algorithm's identity block. The identity block can be obtained by */
/* making a separate call to compress, specifying the identity action. */
/* > The INPUT BLOCK is defined to be Memory[src_addr,src_addr+src_len-1]. */
/* > dst_len will be used to denote *p_dst_len. */
/* > dst_len is not read by compress, only written. */
/* > The value of dst_len is defined only upon termination. */
/* > The OUTPUT BLOCK is defined to be Memory[dst_addr,dst_addr+dst_len-1]. */
/* */
/* Compression Action */
/* ------------------ */
/* > action must be COMPRESS_ACTION_COMPRESS. */
/* > src_len must be in the range [0,COMPRESS_MAX_ORG]. */
/* > The OUTPUT ZONE is defined to be */
/* Memory[dst_addr,dst_addr+src_len-1+COMPRESS_OVERRUN]. */
/* > The function can modify any part of the output zone regardless of the */
/* final length of the output block. */
/* > The input block and the output zone must not overlap. */
/* > dst_len will be in the range [0,src_len+COMPRESS_OVERRUN]. */
/* > dst_len will be in the range [0,COMPRESS_MAX_COM] (from prev fact). */
/* > The output block will consist of a representation of the input block. */
/* */
/* Decompression Action */
/* -------------------- */
/* > action must be COMPRESS_ACTION_DECOMPRESS. */
/* > The input block must be the result of an earlier compression operation. */
/* > If the previous fact is true, the following facts must also be true: */
/* > src_len will be in the range [0,COMPRESS_MAX_COM]. */
/* > dst_len will be in the range [0,COMPRESS_MAX_ORG]. */
/* > The input and output blocks must not overlap. */
/* > Only the output block is modified. */
/* > Upon termination, the output block will consist of the bytes contained */
/* in the input block passed to the earlier compression operation. */
/* */
/******************************************************************************/
#ifndef DONE_PORT /* Only do this if not previously done. */
#ifdef THINK_C
#define UBYTE unsigned char /* Unsigned byte */
#define UWORD unsigned int /* Unsigned word (2 bytes) */
#define uint32_t unsigned long /* Unsigned word (4 bytes) */
#define BOOL unsigned char /* Boolean */
#define FOPEN_BINARY_READ "rb" /* Mode string for binary reading. */
#define FOPEN_BINARY_WRITE "wb" /* Mode string for binary writing. */
#define FOPEN_TEXT_APPEND "a" /* Mode string for text appending. */
#define REAL double /* USed for floating point stuff. */
#endif
#define DONE_PORT /* Don't do all this again. */
#define MALLOC_FAIL NULL /* Failure status from malloc() */
#define LOCAL static /* For non-exported routines. */
#define EXPORT /* Signals exported function. */
#define then /* Useful for aligning ifs. */
/* Added by Matt Mahoney, Feb. 14, 2008 */
typedef unsigned char UBYTE;
typedef unsigned short UWORD;
#define TRUE 1
#define FALSE 0
#define REGISTER
#undef LOCAL
#define LOCAL
#define ass(p,m) if (!(p)) fprintf(stderr,"%s\n",m),exit(1)
/* End added section */
#endif
/******************************************************************************/
/* End of PORT.H */
/******************************************************************************/
#ifndef __KERNEL__
#include <stdint.h>
#endif
#define COMPRESS_ACTION_IDENTITY 0
#define COMPRESS_ACTION_COMPRESS 1
#define COMPRESS_ACTION_DECOMPRESS 2
#define COMPRESS_OVERRUN 1024
#define COMPRESS_MAX_COM 0x70000000
#define COMPRESS_MAX_ORG (COMPRESS_MAX_COM-COMPRESS_OVERRUN)
#define COMPRESS_MAX_STRLEN 255
/* The following structure provides information about the algorithm. */
/* > The top bit of id must be zero. The remaining bits must be chosen by */
/* the author of the algorithm by tossing a coin 31 times. */
/* > The amount of memory requested by the algorithm is specified in bytes */
/* and must be in the range [0,0x70000000]. */
/* > All strings s must be such that strlen(s)<=COMPRESS_MAX_STRLEN. */
struct compress_identity
{
uint32_t id; /* Identifying number of algorithm. */
uint32_t memory; /* Number of bytes of working memory required. */
char *name; /* Name of algorithm. */
char *version; /* Version number. */
char *date; /* Date of release of this version. */
char *copyright; /* Copyright message. */
char *author; /* Author of algorithm. */
char *affiliation; /* Affiliation of author. */
char *vendor; /* Where the algorithm can be obtained. */
};
int lzrw1a_compress( /* Single function interface to compression algorithm. */
UWORD action, /* Action to be performed. */
UBYTE *wrk_mem, /* Working memory temporarily given to routine to use. */
UBYTE *src_adr, /* Address of input data. */
uint32_t src_len, /* Length of input data. */
UBYTE *dst_adr, /* Address of output data. */
uint32_t *p_dst_len /* Pointer to a longword where routine will write: */
/* If action=..IDENTITY => Adr of id structure. */
/* If action=..COMPRESS => Length of output data. */
/* If action=..DECOMPRESS => Length of output data. */
);
void lzrw2_compress( /* Single function interface to compression algorithm. */
UWORD action, /* Action to be performed. */
UBYTE *wrk_mem, /* Working memory temporarily given to routine to use. */
UBYTE *src_adr, /* Address of input data. */
uint32_t src_len, /* Length of input data. */
UBYTE *dst_adr, /* Address of output data. */
uint32_t *p_dst_len /* Pointer to a longword where routine will write: */
/* If action=..IDENTITY => Adr of id structure. */
/* If action=..COMPRESS => Length of output data. */
/* If action=..DECOMPRESS => Length of output data. */
);
void lzrw3_compress( /* Single function interface to compression algorithm. */
UWORD action, /* Action to be performed. */
UBYTE *wrk_mem, /* Working memory temporarily given to routine to use. */
UBYTE *src_adr, /* Address of input data. */
uint32_t src_len, /* Length of input data. */
UBYTE *dst_adr, /* Address of output data. */
uint32_t *p_dst_len /* Pointer to a longword where routine will write: */
/* If action=..IDENTITY => Adr of id structure. */
/* If action=..COMPRESS => Length of output data. */
/* If action=..DECOMPRESS => Length of output data. */
);
void lzrw3a_compress( /* Single function interface to compression algorithm. */
UWORD action, /* Action to be performed. */
UBYTE *wrk_mem, /* Working memory temporarily given to routine to use. */
UBYTE *src_adr, /* Address of input data. */
uint32_t src_len, /* Length of input data. */
UBYTE *dst_adr, /* Address of output data. */
uint32_t *p_dst_len /* Pointer to a longword where routine will write: */
/* If action=..IDENTITY => Adr of id structure. */
/* If action=..COMPRESS => Length of output data. */
/* If action=..DECOMPRESS => Length of output data. */
);
uint32_t lzrw1a_req_mem(void);
uint32_t lzrw2_req_mem(void);
uint32_t lzrw3_req_mem(void);
void lzrw1_compress(UBYTE *p_src_first,uint32_t src_len,UBYTE *p_dst_first,uint32_t *p_dst_len);
void lzrw1_decompress(UBYTE *p_src_first,uint32_t src_len,UBYTE *p_dst_first,uint32_t *p_dst_len);
/******************************************************************************/
/* End of COMPRESS.H */
/******************************************************************************/
void fast_copy(void *src_adr, void *dst_adr, unsigned long src_len);
/* This function copies a block of memory very quickly. */
/* The exact speed depends on the relative alignment of the blocks of memory. */
/* PRE : 0<=src_len<=(2^32)-1 . */
/* PRE : Source and destination blocks must not overlap. */
/* POST : MEM[dst_adr,dst_adr+src_len-1]=MEM[src_adr,src_adr+src_len-1]. */
/* POST : MEM[dst_adr,dst_adr+src_len-1] is the only memory changed. */
|
C
|
//直接插入排序
void InsertSort(datatype arr[],int n)
{
for(i=2;i<=n;i--)
if(arr[i].key<arr[i-1].key)
{
arr[0]=arr[i];
for(j=i-1;arr[0].key<arr[j].key;j--)
arr[j]=arr[j+1];
arr[j+1]=arr[0];
}
}
//冒泡排序
void bubblesort(datatpye arr[],int bgn,int end)
{
bool isLoop = true ;
for (int i = end; true == isLoop && i > bgn; --i)
{
isLoop = false;
for (int j = bgn + 1; j < i; ++j)
{
if (arr[j] < arr[j-1])
{
mySwap(&arr[j],&arr[j-1]);
isLoop = true;
}
}
}
}
//快速排序
void QuickSort(datatype arr[], int s ,int t)
{
if (s<t)
{
i=Partition(arr,s,t)
QuickSort(arr,s,i-1);
QuickSort(arr,i+1,t);
}
}
//简单选择排序
void selectSort(datatype arr[],int bgn,int end)
{
for (int i=bgn ;i<end;++i)
{
int minIndex = i;
for (int j=i+1;j<end;++j)
{
if(arr[j]<arr[minIndex])
minIndex = j;
}
if (minIndex != i)
mySwap(&arr[i],&arr[minIndex]);
}
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
void forkExample()
{
// child process if it return 0 value
pid_t pid= fork();
if ( pid == 0){
pid_t pid= fork();
sleep(5);
if(pid == 0){
printf("\n\nHello from grand-Child!\nNumber of Id: %d\n", getpid());
printf("My parent is: %d\n",getppid());
sleep(5);
}
else{
sleep(5);
printf("\nHello from Child!\nNumber of Id: %d", getpid());
printf("\nMy parent is: %d",getppid());
}
}
// parent process if it return a value that diffrent from 0
else{
sleep(5);
printf("Hello from Parent! \nNumber of Id: %d\n", getpid());
printf("My parent is: %d\n",getppid());
}
}
int main()
{
forkExample();
return 0;
}
|
C
|
/* Problem 139 = 10057761 */
#include <stdio.h>
#include "../algorithms.h"
#define MAXPERIMETER 100000000
int main() {
int m = 2;
int n = 1;
int a;
int b;
int c;
int k;
int answer = 0;
a = 2 * m * n;
b = m * m - n * n;
c = m * m + n * n;
do {
while (a + b + c <= MAXPERIMETER) {
if (gcd(m, n) == 1 && (m + n) & 1) {
answer += ((c % (a - b)) == 0);
k = 2;
while (k * a + k * b + k * c <= MAXPERIMETER) {
answer += (((k * c) % (k * a - k * b)) == 0);
++k;
}
}
++m;
a = 2 * m * n;
b = m * m - n * n;
c = m * m + n * n;
}
++n;
m = n + 1;
a = 2 * m * n;
b = m * m - n * n;
c = m * m + n * n;
} while (a + b + c <= MAXPERIMETER);
printf("%d", answer);
return 0;
}
|
C
|
/*
** utils.h -- some useful wrapper functions
*/
#ifndef _UTILS_H
#define _UTILS_H
#include <stdio.h>
#include <ctype.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <sys/poll.h>
#include <arpa/inet.h>
/*
** read a '\n'-terminated line from a file into buffer, up to a max # of bytes
**
** @param: a file descriptor, a string buffer, a max size
** @return: # of bytes read, or -1 on error, or -2 on EOF (no more data)
** or 0 when an empty line is encountered
*/
int readLine(int file, char* buf, size_t size);
/*
** tokenize a string at blanks and save results in an array
**
** @param: a string str of length n, an array tokens
** @return: # of tokens tokenized
** @remark: continuous sequences of blanks are treated as one blank
** this function mutates the first argument str
** --------------------------------------------------
** @example: char str[100] = "sick and tired of tokenizers.";
** char* tokens[strlen(str)];
** int n = tokenize(str, tokens, strlen(str));
** for (int i = 0; i < n; i++) {
** cout << i << ": " << tokens[i] << "\n";
** }
** @produce: 0: sick
** 1: and
** 2: tired
** 3: of
** 4: tokenizers.
*/
size_t tokenize(char* str, char** tokens, size_t n);
// check if a string consists of only digits, returns 0(false)/1(true)
int checkDigit(const char* str);
// convert port in decimal number to a string
char* convertPort(unsigned short port);
// extract sin_addr from struct sockaddr, works for both IPv4 and IPv6
void* extractAddr(struct sockaddr* sa);
/*
** open a connection to a host on the specified port
**
** @param: a host name, a port number
** @return: a socket descriptor or err_code
** @remark: the port number can be a string, a service name or a decimal number
** @example: sock = socketConnect("www.google.com", "80");
** sock = socketConnect("www.google.com", "http");
** sock = socketConnect("www.google.com", convertPort(80));
*/
int socketConnect(const char* host, const char* port);
/*
** establish a server listener on the specified address and port (or loopback)
**
** @param: a host name, a port number, a backlog (max # of connections)
** @return: a listener socket descriptor or err_code
** @remark: the port number can be a string, a service name or a decimal number
** @example: listener = setListener(NULL, "9001", 20); // passive
** listener = setListener(NULL, "service", 20); // passive
** listener = setListener(NULL, convertPort(9001), 20); // passive
** listener = setListener("localhost", NULL, 20); // loopback
*/
int setListener(const char* host, const char* port, int backlog);
/*
** send string pointed by buf to the file descriptor fd, to a maximum bytes of len
**
** @return: -1 on failure, 0 on success, and updates the number of bytes actually sent in *len
** @remark: useful when a large piece of data cannot be completely sent by a single send() call
*/
int sendAll(int fd, const char* buf, int* len);
/*
** a wrapper of recv(sd, buf, len, 0) with a given timeout in milliseconds
**
** @return: # of bytes received on success, or 0 if connection closed on the other end
** -1 on error, -2 if timeout has been reached and no data received
*/
int recvTimeOut(int sd, char* buf, int len, int timeout);
// a wrapper of read(sd, buf, len) with a given timeout in milliseconds
int readTimeOut(int sd, char* buf, int len, int timeout);
#endif
|
C
|
#include<stdio.h>
int main(){
char* str[] = {"abc", "def", "xyz", "111", "222"};
for(int num = 0; num < 5; num++){
printf("%s\n",str[num]);
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vping <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/29 21:11:21 by vping #+# #+# */
/* Updated: 2020/11/30 19:53:22 by vping ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *check_ost(char **line, char **ost)
{
char *point;
point = NULL;
if (*ost)
{
if ((point = ft_strchr(*ost, '\n')))
{
*point = '\0';
*line = *ost;
point++;
*ost = ft_strdup(point);
}
else
{
*line = *ost;
*ost = NULL;
}
}
else
*line = ft_strdup("");
return (point);
}
int for_read(int fd, char **line, char **ost)
{
char *buf;
char *point;
int i;
point = NULL;
if (!(buf = (char *)malloc(BUFFER_SIZE + 1)))
return (-1);
while (!point && (i = read(fd, buf, BUFFER_SIZE)))
{
buf[i] = '\0';
if (i == -1)
return (-1);
if ((point = ft_strchr(buf, '\n')))
{
*point = '\0';
point++;
if (!(*ost = ft_strdup(point)))
return (-1);
}
if (!(*line = ft_strjoin(*line, buf)))
return (-1);
}
free(buf);
return (i);
}
int get_next_line(int fd, char **line)
{
static char *ost;
int rd;
rd = 0;
if (BUFFER_SIZE <= 0 || read(fd, NULL, 0) == -1 || !line)
return (-1);
if (!(check_ost(line, &ost)))
{
rd = for_read(fd, line, &ost);
}
if (rd == -1)
return (-1);
if (!rd && !ost)
return (0);
return (1);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void *mycalloc(unsigned, unsigned);
void *mycalloc(unsigned n,unsigned size)
{
unsigned i,nb;
char *p,*q;
nb = n * size;
if((p = q = malloc(nb)) != NULL)
for(i = 0; i <nb; i++)
*p++ = 0;
return q;
}
int main(int argc, char *argv[]) {
int *p = NULL;
int i = 0;
p = mycalloc(100, sizeof *p);
if (p == NULL) {
printf("mycalloc returned NULL");
}
free(p);
return 0;
}
|
C
|
#include <stdio.h>
#define CharArrayTo16(val, index) (val[index + 1] | val[index] << 8)
#define CharArrayTo24(val, index) (val[index + 1] << 8 | val[index + 2] | val[index] << 16)
#define CharArrayTo32(val, index) (val[index + 1] << 16 | val[index + 2] << 8 | val[index + 3] | val[index] << 24)
#define isNotBoundPad(pad) pad < 10000
#define getBoundPadNum(pad) pad - 10000
#define setBoundPadNum(pad) pad + 10000
#define M_TAU_F 6.2831855f
#define ByteToRadian(Byte) ((Byte * M_TAU_F) * (1.0f / 256.0f))
#define RadToDeg(RAD) (float)((RAD) / M_TAU_F * 360.0f)
#define TARGET_BOND 0x0001 /* Set target to bond (ignores target argument)*/
#define TARGET_FRONT_OF_CHR 0x0002 /* Set target to front of chr*/
#define TARGET_CHR 0x0004 /* Set target type to chr_num*/
#define TARGET_PAD 0x0008 /* Set target type to pad*/
#define TARGET_COMPASS 0x0010 /* Set target to compass direction (hex) N: 0000 E: C000 S: 8000: W: 4000*/
#define TARGET_AIM_ONLY 0x0020 /* Aim at target instead of firing*/
#define TARGET_DONTTURN 0x0040 /* Limits target to 180 degrees in front of guard (cannot be used with TARGET_BOND flag)*/
// command 68 - door states
char *DOORSTATE_ToString[] = {
" DOOR_STATE_CLOSED", /* Closed*/
" DOOR_STATE_OPEN", /* Opened*/
" DOOR_STATE_CLOSING", /* Closing*/
" DOOR_STATE_OPENING" /* Opening*/};
// command D7 - hud flags
#define HUD_HIDE_ALL 0x00 /* Hide all*/
#define HUD_SHOW_TEXT_TOP 0x01 /* Don't hide top text*/
#define HUD_SHOW_TEXT_BOTTOM 0x02 /* Don't hide bottom text*/
#define HUD_SHOW_HUD_COUNTDOWN 0x04 /* Don't hide hud countdown*/
/* special chr num IDs */
#define CHR_BOND_CINEMA -8 /* only works when bond has a third person model (intro/exit cutscene) */
#define CHR_CLONE -7
#define CHR_SEE_SHOT -6 /* stored as chr->chrseeshot */
#define CHR_SEE_DIE -5 /* stored as chr->chrseedie */
#define CHR_PRESET -4 /* stored as chr->chrpreset1 */
#define CHR_SELF -3
/* private chr ID, cannot be accessed with ai commands */
#define CHR_OBJECTIVE -2 /* objective ai list chr ID */
#define CHR_FREE -1 /* chr IDs when free'd (killed or removed from level) */
#define CHR_SPAWN_NUM_START 5000 /* default chr num for spawned guards with ai command BD/BE */
#define CHR_CLONED_NUM_START 10000 /* default chr num for cloed guards with ai command C1 */
/* Special ID for selecting PadPreset in AI list */
#define PAD_PRESET1 9000 /* stored as chr->padpreset1 */
#define isGlobalAIListID(ID) ((ID) < 18)
#define isBGAIListID(ID) ((ID) > 4097)
#define isChrAIListID(ID) (!isGlobalAIListID(ID) && !isBGAIListID(ID))
#define setGlobalAIListID(ID) ((ID) + 0)
#define setChrAIListID(ID) ((ID) + 1025)
#define setBGAIListID(ID) ((ID) + 4097)
#define getGlobalAIListID(ID) ((ID)-0)
#define getChrAIListID(ID) ((ID)-1025)
#define getBGAIListID(ID) ((ID)-4097)
char *ANIMATIONS_ToString[] = {
"ANIM_idle",
"ANIM_fire_standing",
"ANIM_fire_standing_fast",
"ANIM_fire_hip",
"ANIM_fire_shoulder_left",
"ANIM_fire_turn_right1",
"ANIM_fire_turn_right2",
"ANIM_fire_kneel_right_leg",
"ANIM_fire_kneel_left_leg",
"ANIM_fire_kneel_left",
"ANIM_fire_kneel_right",
"ANIM_fire_roll_left",
"ANIM_fire_roll_right1",
"ANIM_fire_roll_left_fast",
"ANIM_hit_left_shoulder",
"ANIM_hit_right_shoulder",
"ANIM_hit_left_arm",
"ANIM_hit_right_arm",
"ANIM_hit_left_hand",
"ANIM_hit_right_hand",
"ANIM_hit_left_leg",
"ANIM_hit_right_leg",
"ANIM_death_genitalia", /* Thank you Mr. Botwood", here is your award */
"ANIM_hit_neck",
"ANIM_death_neck",
"ANIM_death_stagger_back_to_wall",
"ANIM_death_forward_face_down",
"ANIM_death_forward_spin_face_up",
"ANIM_death_backward_fall_face_up1",
"ANIM_death_backward_spin_face_down_right",
"ANIM_death_backward_spin_face_up_right",
"ANIM_death_backward_spin_face_down_left",
"ANIM_death_backward_spin_face_up_left",
"ANIM_death_forward_face_down_hard",
"ANIM_death_forward_face_down_soft",
"ANIM_death_fetal_position_right",
"ANIM_death_fetal_position_left",
"ANIM_death_backward_fall_face_up2",
"ANIM_side_step_left",
"ANIM_fire_roll_right2",
"ANIM_walking",
"ANIM_sprinting",
"ANIM_running",
"ANIM_bond_eye_walk",
"ANIM_bond_eye_fire",
"ANIM_bond_watch",
"ANIM_surrendering_armed",
"ANIM_surrendering_armed_drop_weapon",
"ANIM_fire_walking",
"ANIM_fire_running",
"ANIM_null50", /* invalid slot */
"ANIM_null51", /* invalid slot */
"ANIM_fire_jump_to_side_left",
"ANIM_fire_jump_to_side_right",
"ANIM_hit_butt_long",
"ANIM_hit_butt_short",
"ANIM_death_head",
"ANIM_death_left_leg",
"ANIM_slide_right",
"ANIM_slide_left",
"ANIM_jump_backwards",
"ANIM_extending_left_hand",
"ANIM_fire_throw_grenade",
"ANIM_spotting_bond", /* used by chr ai command guard_points_at_bond */
"ANIM_look_around", /* used by chr ai command GUARD_ANIM_LOOKS_AROUND_SELF */
"ANIM_fire_standing_one_handed_weapon",
"ANIM_fire_standing_draw_one_handed_weapon_fast",
"ANIM_fire_standing_draw_one_handed_weapon_slow",
"ANIM_fire_hip_one_handed_weapon_fast",
"ANIM_fire_hip_one_handed_weapon_slow",
"ANIM_fire_hip_forward_one_handed_weapon",
"ANIM_fire_standing_right_one_handed_weapon",
"ANIM_fire_step_right_one_handed_weapon",
"ANIM_fire_standing_left_one_handed_weapon_slow",
"ANIM_fire_standing_left_one_handed_weapon_fast",
"ANIM_fire_kneel_forward_one_handed_weapon_slow",
"ANIM_fire_kneel_forward_one_handed_weapon_fast",
"ANIM_fire_kneel_right_one_handed_weapon_slow",
"ANIM_fire_kneel_right_one_handed_weapon_fast",
"ANIM_fire_kneel_left_one_handed_weapon_slow",
"ANIM_fire_kneel_left_one_handed_weapon_fast",
"ANIM_fire_kneel_left_one_handed_weapon",
"ANIM_aim_walking_one_handed_weapon",
"ANIM_aim_walking_left_one_handed_weapon",
"ANIM_aim_walking_right_one_handed_weapon",
"ANIM_aim_running_one_handed_weapon",
"ANIM_aim_running_right_one_handed_weapon",
"ANIM_aim_running_left_one_handed_weapon",
"ANIM_aim_sprinting_one_handed_weapon",
"ANIM_running_one_handed_weapon",
"ANIM_sprinting_one_handed_weapon",
"ANIM_null91", /* invalid slot */
"ANIM_null92", /* invalid slot */
"ANIM_null93", /* invalid slot */
"ANIM_null94", /* invalid slot */
"ANIM_null95", /* invalid slot */
"ANIM_null96", /* invalid slot */
"ANIM_draw_one_handed_weapon_and_look_around",
"ANIM_draw_one_handed_weapon_and_stand_up",
"ANIM_aim_one_handed_weapon_left_right",
"ANIM_cock_one_handed_weapon_and_turn_around",
"ANIM_holster_one_handed_weapon_and_cross_arms",
"ANIM_cock_one_handed_weapon_turn_around_and_stand_up",
"ANIM_draw_one_handed_weapon_and_turn_around",
"ANIM_step_foward_and_hold_one_handed_weapon",
"ANIM_holster_one_handed_weapon_and_adjust_suit",
"ANIM_idle_unarmed",
"ANIM_walking_unarmed",
"ANIM_fire_walking_dual_wield",
"ANIM_fire_walking_dual_wield_hands_crossed",
"ANIM_fire_running_dual_wield",
"ANIM_fire_running_dual_wield_hands_crossed",
"ANIM_fire_sprinting_dual_wield",
"ANIM_fire_sprinting_dual_wield_hands_crossed",
"ANIM_walking_female",
"ANIM_running_female",
"ANIM_fire_kneel_dual_wield",
"ANIM_fire_kneel_dual_wield_left",
"ANIM_fire_kneel_dual_wield_right",
"ANIM_fire_kneel_dual_wield_hands_crossed",
"ANIM_fire_kneel_dual_wield_hands_crossed_left",
"ANIM_fire_kneel_dual_wield_hands_crossed_right",
"ANIM_fire_standing_dual_wield",
"ANIM_fire_standing_dual_wield_left",
"ANIM_fire_standing_dual_wield_right",
"ANIM_fire_standing_dual_wield_hands_crossed_left",
"ANIM_fire_standing_dual_wield_hands_crossed_right",
"ANIM_fire_standing_aiming_down_sights",
"ANIM_fire_kneel_aiming_down_sights",
"ANIM_hit_taser", /* unused tazer boy hit reaction */
"ANIM_death_explosion_forward",
"ANIM_death_explosion_left1",
"ANIM_death_explosion_back_left",
"ANIM_death_explosion_back1",
"ANIM_death_explosion_right",
"ANIM_death_explosion_forward_right1",
"ANIM_death_explosion_back2",
"ANIM_death_explosion_forward_roll",
"ANIM_death_explosion_forward_face_down",
"ANIM_death_explosion_left2",
"ANIM_death_explosion_forward_right2",
"ANIM_death_explosion_forward_right2_alt", /* copy of right2 with different fall */
"ANIM_death_explosion_forward_right3",
"ANIM_null143", /* invalid slot */
"ANIM_null144", /* invalid slot */
"ANIM_null145", /* invalid slot */
"ANIM_null146", /* invalid slot */
"ANIM_running_hands_up",
"ANIM_sprinting_hands_up",
"ANIM_aim_and_blow_one_handed_weapon",
"ANIM_aim_one_handed_weapon_left",
"ANIM_aim_one_handed_weapon_right",
"ANIM_conversation",
"ANIM_drop_weapon_and_show_fight_stance", /* orthodox stance woo */
"ANIM_yawning",
"ANIM_swatting_flies",
"ANIM_scratching_leg",
"ANIM_scratching_butt",
"ANIM_adjusting_crotch",
"ANIM_sneeze",
"ANIM_conversation_cleaned", /* cleaned up copy of "ANIM_conversation (compare left wrist) */
"ANIM_conversation_listener",
"ANIM_startled_and_looking_around",
"ANIM_laughing_in_disbelief",
"ANIM_surrendering_unarmed",
"ANIM_coughing_standing",
"ANIM_coughing_kneel1",
"ANIM_coughing_kneel2",
"ANIM_standing_up",
"ANIM_null169", /* invalid slot */
"ANIM_dancing",
"ANIM_dancing_one_handed_weapon",
"ANIM_keyboard_right_hand1",
"ANIM_keyboard_right_hand2",
"ANIM_keyboard_left_hand",
"ANIM_keyboard_right_hand_tapping",
"ANIM_bond_eye_fire_alt", /* unused */
"ANIM_dam_jump",
"ANIM_surface_vent_jump",
"ANIM_cradle_jump",
"ANIM_cradle_fall",
"ANIM_credits_bond_kissing",
"ANIM_credits_natalya_kissing"};
char *AIRCRAFT_ANIMATION_ToString[] = {
"AIRCRAFT_ANIMATION_helicopter_cradle",
"AIRCRAFT_ANIMATION_plane_runway",
"AIRCRAFT_ANIMATION_helicopter_takeoff"};
// Add 1 to ID for correct string
char *DIFFICULTY_ToString[] = {
"DIFFICULTY_MULTI", //-1
"DIFFICULTY_AGENT",
"DIFFICULTY_SECRET",
"DIFFICULTY_00",
"DIFFICULTY_007",
};
char *ITEM_IDS_ToString[] = {
"ITEM_UNARMED",
"ITEM_FIST",
"ITEM_KNIFE",
"ITEM_THROWKNIFE",
"ITEM_WPPK",
"ITEM_WPPKSIL",
"ITEM_TT33",
"ITEM_SKORPION",
"ITEM_AK47",
"ITEM_UZI",
"ITEM_MP5K",
"ITEM_MP5KSIL",
"ITEM_SPECTRE",
"ITEM_M16",
"ITEM_FNP90",
"ITEM_SHOTGUN",
"ITEM_AUTOSHOT",
"ITEM_SNIPERRIFLE",
"ITEM_RUGER",
"ITEM_GOLDENGUN",
"ITEM_SILVERWPPK",
"ITEM_GOLDWPPK",
"ITEM_LASER",
"ITEM_WATCHLASER",
"ITEM_GRENADELAUNCH",
"ITEM_ROCKETLAUNCH",
"ITEM_GRENADE",
"ITEM_TIMEDMINE",
"ITEM_PROXIMITYMINE",
"ITEM_REMOTEMINE",
"ITEM_TRIGGER",
"ITEM_TASER",
"ITEM_TANKSHELLS",
"ITEM_BOMBCASE",
"ITEM_PLASTIQUE",
"ITEM_FLAREPISTOL",
"ITEM_PITONGUN",
"ITEM_BUNGEE",
"ITEM_DOORDECODER",
"ITEM_BOMBDEFUSER",
"ITEM_CAMERA",
"ITEM_LOCKEXPLODER",
"ITEM_DOOREXPLODER",
"ITEM_BRIEFCASE",
"ITEM_WEAPONCASE",
"ITEM_SAFECRACKERCASE",
"ITEM_KEYANALYSERCASE",
"ITEM_BUG",
"ITEM_MICROCAMERA",
"ITEM_BUGDETECTOR",
"ITEM_EXPLOSIVEFLOPPY",
"ITEM_POLARIZEDGLASSES",
"ITEM_DARKGLASSES",
"ITEM_CREDITCARD",
"ITEM_GASKEYRING",
"ITEM_DATATHIEF",
"ITEM_WATCHIDENTIFIER",
"ITEM_WATCHCOMMUNICATOR",
"ITEM_WATCHGEIGERCOUNTER",
"ITEM_WATCHMAGNETREPEL",
"ITEM_WATCHMAGNETATTRACT",
"ITEM_GOLDENEYEKEY",
"ITEM_BLACKBOX",
"ITEM_CIRCUITBOARD",
"ITEM_CLIPBOARD",
"ITEM_STAFFLIST",
"ITEM_DOSSIERRED",
"ITEM_PLANS",
"ITEM_SPYFILE",
"ITEM_BLUEPRINTS",
"ITEM_MAP",
"ITEM_AUDIOTAPE",
"ITEM_VIDEOTAPE",
"ITEM_DATTAPE",
"ITEM_SPOOLTAPE",
"ITEM_MICROFILM",
"ITEM_MICROCODE",
"ITEM_LECTRE",
"ITEM_MONEY",
"ITEM_GOLDBAR",
"ITEM_HEROIN",
"ITEM_KEYCARD",
"ITEM_KEYYALE",
"ITEM_KEYBOLT",
"ITEM_SUIT_LF_HAND",
"ITEM_JOYPAD",
"ITEM_NULL86",
"ITEM_NULL87",
"ITEM_TOKEN",
"ITEM_IDS_MAX"};
char *PROPDEF_TYPE_ToString[] = {
"PROPDEF_NOTHING",
"PROPDEF_DOOR",
"PROPDEF_DOOR_SCALE",
"PROPDEF_PROP",
"PROPDEF_KEY",
"PROPDEF_ALARM",
"PROPDEF_CCTV",
"PROPDEF_MAGAZINE",
"PROPDEF_COLLECTABLE",
"PROPDEF_GUARD",
"PROPDEF_MONITOR",
"PROPDEF_MULTI_MONITOR",
"PROPDEF_RACK",
"PROPDEF_AUTOGUN",
"PROPDEF_LINK",
"PROPDEF_UNK15",
"PROPDEF_UNK16",
"PROPDEF_HAT",
"PROPDEF_GUARD_ATTRIBUTE",
"PROPDEF_SWITCH",
"PROPDEF_AMMO",
"PROPDEF_ARMOUR",
"PROPDEF_TAG",
"PROPDEF_OBJECTIVE_START",
"PROPDEF_OBJECTIVE_END",
"PROPDEF_OBJECTIVE_DESTROY_OBJECT",
"PROPDEF_OBJECTIVE_COMPLETE_CONDITION",
"PROPDEF_OBJECTIVE_FAIL_CONDITION",
"PROPDEF_OBJECTIVE_COLLECT_OBJECT",
"PROPDEF_OBJECTIVE_DEPOSIT_OBJECT",
"PROPDEF_OBJECTIVE_PHOTOGRAPH",
"PROPDEF_OBJECTIVE_NULL",
"PROPDEF_OBJECTIVE_ENTER_ROOM",
"PROPDEF_OBJECTIVE_DEPOSIT_OBJECT_IN_ROOM",
"PROPDEF_OBJECTIVE_COPY_ITEM",
"PROPDEF_WATCH_MENU_OBJECTIVE_TEXT",
"PROPDEF_GAS_RELEASING",
"PROPDEF_RENAME",
"PROPDEF_LOCK_DOOR",
"PROPDEF_VEHICHLE",
"PROPDEF_AIRCRAFT",
"PROPDEF_UNK41",
"PROPDEF_GLASS",
"PROPDEF_SAFE",
"PROPDEF_SAFE_ITEM",
"PROPDEF_TANK",
"PROPDEF_CAMERAPOS", // canonical name
"PROPDEF_TINTED_GLASS",
"PROPDEF_END",
};
char *PROP_ToString[] = {
"PROP_ALARM1", /* Beta Alarm / Default Multi Weapon */
"PROP_ALARM2", /* Alarm */
"PROP_EXPLOSIONBIT", /* White Pyramid (Explosion Bit) */
"PROP_AMMO_CRATE1", /* Ammo Crate (Brown w/ Edge Brace", 6x240 Black) */
"PROP_AMMO_CRATE2", /* Ammo Crate (Brown w/ Center Brace", 12x8 Black) */
"PROP_AMMO_CRATE3", /* Ammo Crate (Green w/ Center Brace", 12x8 Brown) */
"PROP_AMMO_CRATE4", /* Ammo Crate (Green w/ Edge Brace", 6x8 White) */
"PROP_AMMO_CRATE5", /* Ammo Crate (Green w/ Double Brace", 24x60 Black) */
"PROP_BIN1", /* Rusted Trash Bin */
"PROP_BLOTTER1", /* Desk Blotter */
"PROP_BOOK1", /* Red Book */
"PROP_BOOKSHELF1", /* Bookshelf */
"PROP_BRIDGE_CONSOLE1A", /* Bridge Console w/ Monitor", Navigation + Keyboard 1A */
"PROP_BRIDGE_CONSOLE1B", /* Bridge Console w/ Navigation 1B */
"PROP_BRIDGE_CONSOLE2A", /* Bridge Console w/ Navigation", Monitor + Keyboard 2A */
"PROP_BRIDGE_CONSOLE2B", /* Bridge Console w/ Various Controls 2B */
"PROP_BRIDGE_CONSOLE3A", /* Bridge Console w/ Monitor", Navigation + Keyboard 3A */
"PROP_BRIDGE_CONSOLE3B", /* Bridge Console w/ Monitor", Keyboard + Navigation 3B */
"PROP_CARD_BOX1", /* Cardboard Box", Kapto|Enb */
"PROP_CARD_BOX2", /* Cardboard Box", Red Arrow", Bahko */
"PROP_CARD_BOX3", /* Cardboard Box", Scrawled Text", Bahah */
"PROP_CARD_BOX4_LG", /* Cardboard Box", Three Seams */
"PROP_CARD_BOX5_LG", /* Cardboard Box", Two Seams", Bahah */
"PROP_CARD_BOX6_LG", /* Cardboard Box", Bahko */
"PROP_CCTV", /* Surveillance Camera */
"PROP_CONSOLE1", /* Double Screen Consoles w/ Keyboards */
"PROP_CONSOLE2", /* Double Screen Consoles w/ Left Keyboard */
"PROP_CONSOLE3", /* Double Screen Consoles w/ Right Keyboard */
"PROP_CONSOLE_SEVA", /* Console w/ Keyboard */
"PROP_CONSOLE_SEVB", /* Console w/ Monitor + Keyboard */
"PROP_CONSOLE_SEVC", /* Console w/ Switches */
"PROP_CONSOLE_SEVD", /* Console w/ Five Gauges */
"PROP_CONSOLE_SEV2A", /* Console w/ Four Faders */
"PROP_CONSOLE_SEV2B", /* Console w/ Monitor", Keyboard + Switches */
"PROP_CONSOLE_SEV2C", /* Console w/ Three Gauges */
"PROP_CONSOLE_SEV2D", /* Console w/ Pressure Gauge */
"PROP_CONSOLE_SEV_GEA", /* Console w/ GoldenEye Key Slot */
"PROP_CONSOLE_SEV_GEB", /* Console w/ Faders + Pressure Gauge */
"PROP_DESK1", /* Desk w/ Kickplate */
"PROP_DESK2", /* Desk */
"PROP_DESK_LAMP2", /* Desk Lamp */
"PROP_DISC_READER", /* External Hard Drive */
"PROP_DISK_DRIVE1", /* Floppy Disc Drive */
"PROP_FILING_CABINET1", /* Filing Cabinet */
"PROP_JERRY_CAN1", /* Jerrycan (Fuel Container) */
"PROP_KEYBOARD1", /* Computer Keyboard */
"PROP_KIT_UNITS1", /* Kitchen Cabinets */
"PROP_LETTER_TRAY1", /* Letter Tray */
"PROP_MAINFRAME1", /* Mainframe", Basic */
"PROP_MAINFRAME2", /* Mainframe", Advanced */
"PROP_METAL_CHAIR1", /* Chair (Metal) */
"PROP_METAL_CRATE1", /* Metal Crate", 6 Top Corner */
"PROP_METAL_CRATE2", /* Metal Crate", 6 Bottom Corner */
"PROP_METAL_CRATE3", /* Metal Crate", Toxic Materials */
"PROP_METAL_CRATE4", /* Metal Crate", Double Stripe - Class D1 Hazard */
"PROP_MISSILE_RACK", /* Naval Harpoon Missile in Containment Rack */
"PROP_MISSILE_RACK2", /* Naval Harpoon Missiles in Containment Racks x4 */
"PROP_OIL_DRUM1", /* Oil Drum", Single Stripe", Ribbed */
"PROP_OIL_DRUM2", /* Oil Drum", Single Stripe", Ribbed - Class D1 Hazard */
"PROP_OIL_DRUM3", /* Oil Drum", Single Stripe", Ribbed - Toxic Materials */
"PROP_OIL_DRUM5", /* Oil Drum", Double Stripe - Toxic Materials */
"PROP_OIL_DRUM6", /* Oil Drum - Toxic Materials */
"PROP_OIL_DRUM7", /* Oil Drum", Double Dashes - Class D1 Hazard */
"PROP_PADLOCK", /* Padlock */
"PROP_PHONE1", /* Telephone */
"PROP_RADIO_UNIT1", /* Radio Tuner w/ 1 Knob + 2 Gauges */
"PROP_RADIO_UNIT2", /* Radio Tuner w/ 1 Knob + 5 Gauges */
"PROP_RADIO_UNIT3", /* Radio Tuner w/ 3 Knobs + 5 Gauges */
"PROP_RADIO_UNIT4", /* Radio Tuner w/ 3 Knobs + 2 Gauges */
"PROP_SAT1_REFLECT", /* GoldenEye Satellite */
"PROP_SATDISH", /* Satellite Dish (Arkangelsk) */
"PROP_SATBOX", /* Uplink Box */
"PROP_STOOL1", /* Wooden Stool */
"PROP_SWIVEL_CHAIR1", /* Swivel Chair */
"PROP_TORPEDO_RACK", /* Naval Torpedo Rack x3 */
"PROP_TV1", /* Television Monitor */
"PROP_TV_HOLDER", /* Hanging Monitor Rack */
"PROP_TVSCREEN", /* Wall Monitor Screen */
"PROP_TV4SCREEN", /* Wall Monitor Screens", 4-in-1 */
"PROP_WOOD_LG_CRATE1", /* Wooden Crate w/ #4 Label", Bahah */
"PROP_WOOD_LG_CRATE2", /* Wooden Crate", Darker Shading", Kapto|Enb */
"PROP_WOOD_MD_CRATE3", /* Wooden Crates x8", Bahko */
"PROP_WOOD_SM_CRATE4", /* Wooden Crate w/ #2 Label", Bahko */
"PROP_WOOD_SM_CRATE5", /* Wooden Crate w/ #4 Label", Darker Shading", Bahah */
"PROP_WOOD_SM_CRATE6", /* Wooden Crate w/ UP Arrow", Kapto|Enb */
"PROP_WOODEN_TABLE1", /* Wooden Table */
"PROP_SWIPE_CARD2", /* Keycard */
"PROP_BORG_CRATE", /* Blue and Gold Printed Circuit Cube (Borg Crate) */
"PROP_BOXES4X4", /* Metal Crate Stack", 4x4 */
"PROP_BOXES3X4", /* Metal Crate Stack", 3x4 */
"PROP_BOXES2X4", /* Metal Crate Stack", 2x4 */
"PROP_SEC_PANEL", /* Security Card Panel */
"PROP_ICBM_NOSE", /* Silo Missile (ICBM)", Nose Cone Only */
"PROP_ICBM", /* Silo Missile (ICBM) */
"PROP_TUNING_CONSOLE1", /* Dual Consoles on Castors */
"PROP_DESK_ARECIBO1", /* Computer Work Desk */
"PROP_LOCKER3", /* Lockers", Single Venting */
"PROP_LOCKER4", /* Lockers", Double Venting */
"PROP_ROOFGUN", /* Ceiling Mounted Drone Gun */
"PROP_DEST_ENGINE", /* Frigate Engine */
"PROP_DEST_EXOCET", /* Naval MK 29 Missile Launcher (Exocet) */
"PROP_DEST_GUN", /* Naval 100 mm Gun Turret (TR 100) */
"PROP_DEST_HARPOON", /* Naval MK 141 Launch Canisters (Harpoon) */
"PROP_DEST_SEAWOLF", /* Naval MK 26 Dual Missile Launcher (Seawolf) */
"PROP_WINDOW", /* Window Glass */
"PROP_WINDOW_LIB_LG1", /* Window Glass", Lattice Frame", 4x10 (single-sided) */
"PROP_WINDOW_LIB_SM1", /* Window Glass", Lattice Frame", 4x3 (double-sided) */
"PROP_WINDOW_COR11", /* Window Glass", Lattice Frame", 4x4 (single-sided) */
"PROP_JUNGLE3_TREE", /* Jungle Large Tree */
"PROP_PALM", /* Jungle Palm Tree */
"PROP_PALMTREE", /* Jungle Palm Tree", Resprouting After Loss of Fronds */
"PROP_PLANT2B", /* Jungle Plant", Low Shrub */
"PROP_LABBENCH", /* Laboratory Table w/ Sink Drains */
"PROP_GASBARREL", /* White Bin */
"PROP_GASBARRELS", /* White Bins x4 */
"PROP_BODYARMOUR", /* Body Armor */
"PROP_BODYARMOURVEST", /* Body Armor (Vest) */
"PROP_GASTANK", /* Bottling Tank */
"PROP_GLASSWARE1", /* Glass Cup */
"PROP_HATCHBOLT", /* Metallic Securing Strip (Hatch Bolt) */
"PROP_BRAKEUNIT", /* Train Brake Controller */
"PROP_AK47MAG", /* Gun Magazine (KF7 Soviet) */
"PROP_M16MAG", /* Gun Magazine (AR33 Assault Rifle) */
"PROP_MP5KMAG", /* Gun Magazine (D5K Deutsche) */
"PROP_SKORPIONMAG", /* Gun Magazine (Klobb) */
"PROP_SPECTREMAG", /* Gun Magazine (Phantom) */
"PROP_UZIMAG", /* Gun Magazine (ZMG (9mm)) */
"PROP_SILENCER", /* Silencer */
"PROP_CHREXTINGUISHER", /* Fire Extinguisher */
"PROP_BOXCARTRIDGES", /* Box of Shells (Shotgun Cartridges) */
"PROP_FNP90MAG", /* Gun Magazine (RC-P90) */
"PROP_GOLDENSHELLS", /* Box of Shells (Golden Gun Bullets) */
"PROP_MAGNUMSHELLS", /* Box of Shells (Magnum Rounds) */
"PROP_WPPKMAG", /* Gun Magazine (PP7) */
"PROP_TT33MAG", /* Gun Magazine (DD44 Dostovei) */
"PROP_SEV_DOOR", /* Grey Containment Door w/ Caution Stripes and Window */
"PROP_SEV_DOOR3", /* Grey Electronic Door w/ LEFT Arrow */
"PROP_SEV_DOOR3_WIND", /* BETA Electronic Door w/ LEFT Arrow and Fake Window */
"PROP_SEV_DOOR4_WIND", /* Grey Electronic Door w/ LEFT Arrow and Window */
"PROP_SEV_TRISLIDE", /* Glass Door w/ Stone Frame */
"PROP_SEV_DOOR_V1", /* Grey Electronic Door w/ UP Arrow */
"PROP_STEEL_DOOR1", /* Silver Corrugated Door w/ Caution Stripes */
"PROP_STEEL_DOOR2", /* Rusty Door w/ Handle */
"PROP_STEEL_DOOR3", /* Double Cross Brace Door */
"PROP_SILO_LIFT_DOOR", /* Elevator Door */
"PROP_STEEL_DOOR2B", /* Rusty Door w/o Handle */
"PROP_DOOR_ROLLER1", /* Blue Bay Door w/ Caution Stripes */
"PROP_DOOR_ROLLER2", /* Blue Bay Door w/ Venting and Caution Stripes */
"PROP_DOOR_ROLLER3", /* Blue Bay Door w/ Venting and Caution Stripes */
"PROP_DOOR_ROLLER4", /* Cargo Bay Door w/ UP Arrow and Transportation Stripes */
"PROP_DOOR_ST_AREC1", /* Blue Corrugated Door w/ Transportation Stripes */
"PROP_DOOR_ST_AREC2", /* Blue Reversed Corrugated Door w/ Transportation Stripes */
"PROP_DOOR_DEST1", /* Grey Frigate Door w/ Indents and Caution Stripes */
"PROP_DOOR_DEST2", /* Grey Frigate Door w/ Indents", Caution Stripes and KEEP CLEAR Label */
"PROP_GAS_PLANT_SW_DO1", /* Grey Swinging Door w/ Blue Stripe */
"PROP_GAS_PLANT_SW2_DO1", /* Grey Swinging Door", Darker */
"PROP_GAS_PLANT_SW3_DO1", /* Grey Swinging Door", Lighter */
"PROP_GAS_PLANT_SW4_DO1", /* Light Wooden Door (Looks Like Sand) */
"PROP_GAS_PLANT_MET1_DO1", /* Brown Electronic Door */
"PROP_GAS_PLANT_WC_CUB1", /* Bathroom Stall Door */
"PROP_GASPLANT_CLEAR_DOOR", /* Laboratory Glass Door */
"PROP_TRAIN_DOOR", /* Dark Wooden Door */
"PROP_TRAIN_DOOR2", /* Dark Wooden Door w/ Window */
"PROP_TRAIN_DOOR3", /* Dark Wooden Door w/ Window + Shutter */
"PROP_DOOR_EYELID", /* Eyelid Door */
"PROP_DOOR_IRIS", /* Iris Door */
"PROP_SEVDOORWOOD", /* Cabin Door */
"PROP_SEVDOORWIND", /* Weathered Swinging Door w/ Window */
"PROP_SEVDOORNOWIND", /* Weathered Swinging Door */
"PROP_SEVDOORMETSLIDE", /* Brown Corrugated Electronic Door */
"PROP_CRYPTDOOR1A", /* Stone Door w/ Prints (Set A) */
"PROP_CRYPTDOOR1B", /* Sand Door w/ Damage (Set A) */
"PROP_CRYPTDOOR2A", /* Stone Door w/ Prints", Darker (Set B) */
"PROP_CRYPTDOOR2B", /* Sand Door w/ Damage", Darker (Set B) */
"PROP_CRYPTDOOR3", /* Egyptian Moving Wall */
"PROP_CRYPTDOOR4", /* Brown Sand Door (Temple) */
"PROP_VERTDOOR", /* Blast Door (Control) */
"PROP_HATCHDOOR", /* Train Floor Hatch */
"PROP_DAMGATEDOOR", /* Security Gate (Dam) */
"PROP_DAMTUNDOOR", /* Tunnel Flood Door (Dam) */
"PROP_DAMCHAINDOOR", /* Mesh Gate */
"PROP_SILOTOPDOOR", /* Launch Tube Ceiling Shutter (Silo) */
"PROP_DOORPRISON1", /* Cell Door */
"PROP_DOORSTATGATE", /* Park Gate */
"PROP_CHRKALASH", /* KF7 Soviet */
"PROP_CHRGRENADELAUNCH", /* Grenade Launcher */
"PROP_CHRKNIFE", /* Hunting Knife */
"PROP_CHRLASER", /* Moonraker Laser */
"PROP_CHRM16", /* AR33 Assault Rifle */
"PROP_CHRMP5K", /* D5K Deutsche */
"PROP_CHRRUGER", /* Cougar Magnum */
"PROP_CHRWPPK", /* PP7 Special Issue */
"PROP_CHRSHOTGUN", /* Shotgun */
"PROP_CHRSKORPION", /* Klobb */
"PROP_CHRSPECTRE", /* Phantom */
"PROP_CHRUZI", /* ZMG (9mm) */
"PROP_CHRGRENADE", /* Hand Grenade */
"PROP_CHRFNP90", /* RC-P90 */
"PROP_CHRBRIEFCASE", /* Briefcase */
"PROP_CHRREMOTEMINE", /* Remote Mine */
"PROP_CHRPROXIMITYMINE", /* Proximity Mine */
"PROP_CHRTIMEDMINE", /* Timed Mine */
"PROP_CHRROCKET", /* Rocket */
"PROP_CHRGRENADEROUND", /* Grenade Round */
"PROP_CHRWPPKSIL", /* PP7 (Silenced) */
"PROP_CHRTT33", /* DD44 Dostovei */
"PROP_CHRMP5KSIL", /* D5K (Silenced) */
"PROP_CHRAUTOSHOT", /* Automatic Shotgun */
"PROP_CHRGOLDEN", /* Golden Gun */
"PROP_CHRTHROWKNIFE", /* Throwing Knife */
"PROP_CHRSNIPERRIFLE", /* Sniper Rifle */
"PROP_CHRROCKETLAUNCH", /* Rocket Launcher */
"PROP_HATFURRY", /* Fur Hat", Blue */
"PROP_HATFURRYBROWN", /* Fur Hat", Brown */
"PROP_HATFURRYBLACK", /* Fur Hat", Black */
"PROP_HATTBIRD", /* Side Cap", Light Green */
"PROP_HATTBIRDBROWN", /* Side Cap", Dark Green */
"PROP_HATHELMET", /* Combat Helmet", Green */
"PROP_HATHELMETGREY", /* Combat Helmet", Grey */
"PROP_HATMOON", /* Elite Headgear */
"PROP_HATBERET", /* Special Forces Beret", Black */
"PROP_HATBERETBLUE", /* Special Forces Beret", Navy */
"PROP_HATBERETRED", /* Special Forces Beret", Burgundy */
"PROP_HATPEAKED", /* Officer's Peaked Visor Cap */
"PROP_CHRWRISTDART", /* Pchrwristdart (BETA) */
"PROP_CHREXPLOSIVEPEN", /* Pchrexplosivepen (BETA) */
"PROP_CHRBOMBCASE", /* Bomb Case (Briefcase Laying Down) */
"PROP_CHRFLAREPISTOL", /* Pchrflarepistol (BETA Pickup) */
"PROP_CHRPITONGUN", /* Pchrpitongun (BETA Pickup) */
"PROP_CHRFINGERGUN", /* Pchrfingergun (BETA Pickup) */
"PROP_CHRSILVERWPPK", /* Pchrsilverwppk (BETA Pickup) */
"PROP_CHRGOLDWPPK", /* Pchrgoldwppk (BETA Pickup) */
"PROP_CHRDYNAMITE", /* Pchrdynamite (BETA Pickup) */
"PROP_CHRBUNGEE", /* Pchrbungee (BETA Pickup) */
"PROP_CHRDOORDECODER", /* Door Decoder */
"PROP_CHRBOMBDEFUSER", /* Bomb Defuser */
"PROP_CHRBUGDETECTOR", /* Pchrbugdetector (BETA Pickup) */
"PROP_CHRSAFECRACKERCASE", /* Safe Cracker Case (Briefcase Laying Down) */
"PROP_CHRCAMERA", /* Photo Camera (007) */
"PROP_CHRLOCKEXPLODER", /* Pchrlockexploder (BETA Pickup) */
"PROP_CHRDOOREXPLODER", /* Pchrdoorexploder (BETA Pickup) */
"PROP_CHRKEYANALYSERCASE", /* Key Analyzer Case (Briefcase Laying Down) */
"PROP_CHRWEAPONCASE", /* Weapon Case (Briefcase Standing Up) */
"PROP_CHRKEYYALE", /* Yale Key */
"PROP_CHRKEYBOLT", /* Bolt Key */
"PROP_CHRBUG", /* Covert Modem / Tracker Bug */
"PROP_CHRMICROCAMERA", /* Micro Camera */
"PROP_FLOPPY", /* Floppy Disc */
"PROP_CHRGOLDENEYEKEY", /* GoldenEye Key */
"PROP_CHRPOLARIZEDGLASSES", /* Polarized Glasses */
"PROP_CHRCREDITCARD", /* Pchrcreditcard (BETA Pickup) */
"PROP_CHRDARKGLASSES", /* Pchrdarkglasses (BETA Pickup) */
"PROP_CHRGASKEYRING", /* Gas Keyring */
"PROP_CHRDATATHIEF", /* Datathief */
"PROP_SAFE", /* Safe Body */
"PROP_BOMB", /* Pbomb (BETA Pickup) */
"PROP_CHRPLANS", /* Plans (Briefing Folder) */
"PROP_CHRSPYFILE", /* Pchrspyfile (BETA Pickup) */
"PROP_CHRBLUEPRINTS", /* Pirate Blueprints */
"PROP_CHRCIRCUITBOARD", /* Circuitboard */
"PROP_CHRMAP", /* Bunker Expansion Plans */
"PROP_CHRSPOOLTAPE", /* Pchrspooltape (BETA Pickup) */
"PROP_CHRAUDIOTAPE", /* Audiotape */
"PROP_CHRMICROFILM", /* Pchrmicrofilm (BETA Pickup) */
"PROP_CHRMICROCODE", /* Pchrmicrocode (BETA Pickup) */
"PROP_CHRLECTRE", /* Pchrlectre (BETA Pickup) */
"PROP_CHRMONEY", /* Pchrmoney (BETA Pickup) */
"PROP_CHRGOLDBAR", /* Pchrgoldbar (BETA Pickup) */
"PROP_CHRHEROIN", /* Pchrheroin (BETA Pickup) */
"PROP_CHRCLIPBOARD", /* Clipboard */
"PROP_CHRDOSSIERRED", /* Red Dossier */
"PROP_CHRSTAFFLIST", /* Staff List */
"PROP_CHRDATTAPE", /* DAT */
"PROP_CHRPLASTIQUE", /* Plastique */
"PROP_CHRBLACKBOX", /* Black Box (Orange Flight Recorder) */
"PROP_CHRVIDEOTAPE", /* CCTV Tape (GoldenEye VHS) */
"PROP_NINTENDOLOGO", /* Nintendo Logo */
"PROP_GOLDENEYELOGO", /* GoldenEye Logo */
"PROP_WALLETBOND", /* Classified Folder w/ Royal Crest (Folder Menus) */
"PROP_MILTRUCK", /* Supply Truck */
"PROP_JEEP", /* Military Jeep */
"PROP_ARTIC", /* Red Prime Mover */
"PROP_HELICOPTER", /* Transport Helicopter w/ Natalya */
"PROP_TIGER", /* Pirate Euro Chopper */
"PROP_MILCOPTER", /* Hound Helicopter */
"PROP_HIND", /* Soviet Camouflage Chopper */
"PROP_ARTICTRAILER", /* Black Trailer */
"PROP_MOTORBIKE", /* Motorbike */
"PROP_TANK", /* Tank */
"PROP_APC", /* Armored Personnel Carrier */
"PROP_SPEEDBOAT", /* Speedboat */
"PROP_PLANE", /* Aeroplane */
"PROP_GUN_RUNWAY1", /* Heavy Gun Emplacement */
"PROP_SAFEDOOR", /* Safe Door */
"PROP_KEY_HOLDER", /* Key Rack */
"PROP_HATCHSEVX", /* Grating (Ventshaft Hatch) */
"PROP_SEVDISH", /* Satellite Dish (Severnaya) */
"PROP_ARCHSECDOOR1", /* Archives Moving Wall (Dark) */
"PROP_ARCHSECDOOR2", /* Archives Moving Wall (Light) */
"PROP_GROUNDGUN", /* Free Standing Drone Gun */
"PROP_TRAINEXTDOOR", /* Train Exterior Door */
"PROP_CARBMW", /* White Car #1 (BMW) */
"PROP_CARESCORT", /* White Car #2 (Escort) */
"PROP_CARGOLF", /* White Car #3 (Golf) */
"PROP_CARWEIRD", /* Red Car (Cadillac) */
"PROP_CARZIL", /* Ourumov's Car (ZIL) */
"PROP_SHUTTLE_DOOR_L", /* Exhaust Bay Doors", Left Side */
"PROP_SHUTTLE_DOOR_R", /* Exhaust Bay Doors", Right Side */
"PROP_DEPOT_GATE_ENTRY", /* Metallic Gate w/ Red Star */
"PROP_DEPOT_DOOR_STEEL", /* Rusty Door w/ Handle (Lo-Res) */
"PROP_GLASSWARE2", /* Beaker w/ Blue Topper */
"PROP_GLASSWARE3", /* Erlenmeyer Flask */
"PROP_GLASSWARE4", /* Set of Five Beakers */
"PROP_LANDMINE", /* Land Mine */
"PROP_PLANT1", /* Jungle Plant", Withered and Dying */
"PROP_PLANT11", /* Jungle Plant", Turning Colour */
"PROP_PLANT2", /* Jungle Plant", Healthy and Thick */
"PROP_PLANT3", /* Jungle Plant", Tall Leaves */
"PROP_JUNGLE5_TREE", /* Jungle Tree", Moss Covered */
"PROP_LEGALPAGE", /* GoldenEye Certification Screen */
"PROP_ST_PETE_ROOM_1I", /* Roads and Buildings #1 (stretch of road) */
"PROP_ST_PETE_ROOM_2I", /* Roads and Buildings #2 (stretch of road) */
"PROP_ST_PETE_ROOM_3T", /* Roads and Buildings #3 (intersection) */
"PROP_ST_PETE_ROOM_5C", /* Roads and Buildings #4 (street corner) */
"PROP_ST_PETE_ROOM_6C", /* Roads and Buildings #5 (street corner) */
"PROP_DOOR_ROLLERTRAIN", /* Roller Door */
"PROP_DOOR_WIN", /* Glass Sliding Door (Aztec) */
"PROP_DOOR_AZTEC", /* Stone Sliding Door (Aztec) */
"PROP_SHUTTLE", /* Moonraker Shuttle */
"PROP_DOOR_AZT_DESK", /* Boardroom Table (Aztec Exhaust Bay) */
"PROP_DOOR_AZT_DESK_TOP", /* Boardroom Table Extension (Aztec Exhaust Bay) */
"PROP_DOOR_AZT_CHAIR", /* Boardroom Chair (Aztec Exhaust Bay) */
"PROP_DOOR_MF", /* Mainframe Door */
"PROP_FLAG", /* Flag Tag Token */
"PROP_BARRICADE", /* Road Barricade */
"PROP_MODEMBOX", /* Covert Modem Connection Screen */
"PROP_DOORPANEL", /* Sliding Door Activation Switch */
"PROP_DOORCONSOLE", /* Console w/ Activation Light */
"PROP_CHRTESTTUBE", /* Glass Test Tube */
"PROP_BOLLARD", /* Bollard */
};
char *CAMERAMODE_ToString[] = {
"CAMERAMODE_NONE",
"CAMERAMODE_INTRO",
"CAMERAMODE_FADESWIRL",
"CAMERAMODE_SWIRL",
"CAMERAMODE_FP",
"CAMERAMODE_UNK5",
"CAMERAMODE_UNK6",
"CAMERAMODE_POSEND",
"CAMERAMODE_FP_NOINPUT",
"CAMERAMODE_MP",
"CAMERAMODE_UNK10",
};
char *INTRO_TYPE_ToString[] = {
"INTROTYPE_SPAWN",
"INTROTYPE_ITEM",
"INTROTYPE_AMMO",
"INTROTYPE_SWIRL",
"INTROTYPE_ANIM",
"INTROTYPE_CUFF",
"INTROTYPE_CAMERA",
"INTROTYPE_WATCH",
"INTROTYPE_CREDITS",
"INTROTYPE_END",
};
char *MISSION_STATE_IDS_ToString[] = {
"MISSION_STATE_0",
"MISSION_STATE_1",
"MISSION_STATE_2",
"MISSION_STATE_3",
"MISSION_STATE_4",
"MISSION_STATE_5",
"MISSION_STATE_6"
};
char *OBJECTIVESTATUS_ToString[] = {
"OBJECTIVESTATUS_INCOMPLETE",
"OBJECTIVESTATUS_COMPLETE",
"OBJECTIVESTATUS_FAILED"
};
char *GAILIST_ToString[] = {
"GAILIST_AIM_AT_BOND",
"GAILIST_DEAD_AI",
"GAILIST_STANDARD_GUARD",
"GAILIST_PLAY_IDLE_ANIMATION",
"GAILIST_BASH_KEYBOARD",
"GAILIST_SIMPLE_GUARD_DEAF",
"GAILIST_ATTACK_BOND",
"GAILIST_SIMPLE_GUARD",
"GAILIST_RUN_TO_BOND",
"GAILIST_SIMPLE_GUARD_ALARM_RAISER",
"GAILIST_STARTLE_AND_RUN_TO_BOND",
"GAILIST_TRY_CLONE_SEND_OR_RUN_TO_BOND",
"GAILIST_STANDARD_CLONE",
"GAILIST_PERSISTENTLY_CHASE_AND_ATTACK_BOND",
"GAILIST_WAIT_ONE_SECOND",
"GAILIST_END_LEVEL",
"GAILIST_DRAW_TT33_AND_ATTCK_BOND",
"GAILIST_REMOVE_CHR"};
#pragma region lengths
#define AI_GotoNext_LENGTH 2
#define AI_GotoFirst_LENGTH 2
#define AI_Label_LENGTH 2
#define AI_Yield_LENGTH 1
#define AI_EndList_LENGTH /*canonical name*/ 1
#define AI_SetChrAiList_LENGTH 4
#define AI_SetReturnAiList_LENGTH 3
#define AI_Return_LENGTH 1
#define AI_Stop_LENGTH 1
#define AI_Kneel_LENGTH 1
#define AI_PlayAnimation_LENGTH 9
#define AI_IFPlayingAnimation_LENGTH 2
#define AI_PointAtBond_LENGTH 1
#define AI_LookSurprised_LENGTH 1
#define AI_TRYSidestepping_LENGTH 2
#define AI_TRYSideHopping_LENGTH 2
#define AI_TRYSideRunning_LENGTH 2
#define AI_TRYFiringWalk_LENGTH 2
#define AI_TRYFiringRun_LENGTH 2
#define AI_TRYFiringRoll_LENGTH 2
#define AI_TRYFireOrAimAtTarget_LENGTH 6
#define AI_TRYFireOrAimAtTargetKneel_LENGTH 6
#define AI_IFImFiring_LENGTH 2
#define AI_IFImFiringAndLockedForward_LENGTH 2
#define AI_TRYFireOrAimAtTargetUpdate_LENGTH 6
#define AI_TRYFacingTarget_LENGTH 6
#define AI_HitChrWithItem_LENGTH 4
#define AI_ChrHitChr_LENGTH 4
#define AI_TRYThrowingGrenade_LENGTH 2
#define AI_TRYDroppingItem_LENGTH 5
#define AI_RunToPad_LENGTH 3
#define AI_RunToPadPreset_LENGTH 1
#define AI_WalkToPad_LENGTH 3
#define AI_SprintToPad_LENGTH 3
#define AI_StartPatrol_LENGTH 2
#define AI_Surrender_LENGTH 1
#define AI_RemoveMe_LENGTH 1
#define AI_ChrRemoveInstant_LENGTH 2
#define AI_TRYTriggeringAlarmAtPad_LENGTH 4
#define AI_AlarmOn_LENGTH 1
#define AI_AlarmOff_LENGTH 1
#define AI_TRYRunFromBond_LENGTH 2
#define AI_TRYRunToBond_LENGTH 2
#define AI_TRYWalkToBond_LENGTH 2
#define AI_TRYSprintToBond_LENGTH 2
#define AI_TRYFindCover_LENGTH 2
#define AI_TRYRunToChr_LENGTH 3
#define AI_TRYWalkToChr_LENGTH 3
#define AI_TRYSprintToChr_LENGTH 3
#define AI_IFImOnPatrolOrStopped_LENGTH 2
#define AI_IFChrDyingOrDead_LENGTH 3
#define AI_IFChrDoesNotExist_LENGTH 3
#define AI_IFISeeBond_LENGTH 2
#define AI_SetNewRandom_LENGTH 1
#define AI_IFRandomLessThan_LENGTH 3
#define AI_IFRandomGreaterThan_LENGTH 3
#define AI_IFICanHearAlarm_LENGTH 2
#define AI_IFAlarmIsOn_LENGTH 2
#define AI_IFGasIsLeaking_LENGTH 2
#define AI_IFIHeardBond_LENGTH 2
#define AI_IFISeeSomeoneShot_LENGTH 2
#define AI_IFISeeSomeoneDie_LENGTH 2
#define AI_IFICouldSeeBond_LENGTH 2
#define AI_IFICouldSeeBondsStan_LENGTH 2
#define AI_IFIWasShotRecently_LENGTH 2
#define AI_IFIHeardBondRecently_LENGTH 2
#define AI_IFImInRoomWithChr_LENGTH 3
#define AI_IFIveNotBeenSeen_LENGTH 2
#define AI_IFImOnScreen_LENGTH 2
#define AI_IFMyRoomIsOnScreen_LENGTH 2
#define AI_IFRoomWithPadIsOnScreen_LENGTH 4
#define AI_IFImTargetedByBond_LENGTH 2
#define AI_IFBondMissedMe_LENGTH 2
#define AI_IFMyAngleToBondLessThan_LENGTH 3
#define AI_IFMyAngleToBondGreaterThan_LENGTH 3
#define AI_IFMyAngleFromBondLessThan_LENGTH 3
#define AI_IFMyAngleFromBondGreaterThan_LENGTH 3
#define AI_IFMyDistanceToBondLessThanDecimeter_LENGTH 4
#define AI_IFMyDistanceToBondGreaterThanDecimeter_LENGTH 4
#define AI_IFChrDistanceToPadLessThanDecimeter_LENGTH 7
#define AI_IFChrDistanceToPadGreaterThanDecimeter_LENGTH 7
#define AI_IFMyDistanceToChrLessThanDecimeter_LENGTH 5
#define AI_IFMyDistanceToChrGreaterThanDecimeter_LENGTH 5
#define AI_TRYSettingMyPresetToChrWithinDistanceDecimeter_LENGTH 4
#define AI_IFBondDistanceToPadLessThanDecimeter_LENGTH 6
#define AI_IFBondDistanceToPadGreaterThanDecimeter_LENGTH 6
#define AI_IFChrInRoomWithPad_LENGTH 5
#define AI_IFBondInRoomWithPad_LENGTH 4
#define AI_IFBondCollectedObject_LENGTH 3
#define AI_IFItemIsStationaryWithinLevel_LENGTH 3
#define AI_IFItemIsAttachedToObject_LENGTH 4
#define AI_IFBondHasItemEquipped_LENGTH 3
#define AI_IFObjectExists_LENGTH 3
#define AI_IFObjectNotDestroyed_LENGTH 3
#define AI_IFObjectWasActivated_LENGTH 3
#define AI_IFBondUsedGadgetOnObject_LENGTH 3
#define AI_ActivateObject_LENGTH 2
#define AI_DestroyObject_LENGTH 2
#define AI_DropObject_LENGTH 2
#define AI_ChrDropAllConcealedItems_LENGTH 2
#define AI_ChrDropAllHeldItems_LENGTH 2
#define AI_BondCollectObject_LENGTH 2
#define AI_ChrEquipObject_LENGTH 3
#define AI_MoveObject_LENGTH 4
#define AI_DoorOpen_LENGTH 2
#define AI_DoorClose_LENGTH 2
#define AI_IFDoorStateEqual_LENGTH 4
#define AI_IFDoorHasBeenOpenedBefore_LENGTH 3
#define AI_DoorSetLock_LENGTH 3
#define AI_DoorUnsetLock_LENGTH 3
#define AI_IFDoorLockEqual_LENGTH 4
#define AI_IFObjectiveNumComplete_LENGTH 3
#define AI_TRYUnknown6e_LENGTH 3
#define AI_TRYUnknown6f_LENGTH 3
#define AI_IFGameDifficultyLessThan_LENGTH 3
#define AI_IFGameDifficultyGreaterThan_LENGTH 3
#define AI_IFMissionTimeLessThan_LENGTH 4
#define AI_IFMissionTimeGreaterThan_LENGTH 4
#define AI_IFSystemPowerTimeLessThan_LENGTH 4
#define AI_IFSystemPowerTimeGreaterThan_LENGTH 4
#define AI_IFLevelIdLessThan_LENGTH 3
#define AI_IFLevelIdGreaterThan_LENGTH 3
#define AI_IFMyNumArghsLessThan_LENGTH 3
#define AI_IFMyNumArghsGreaterThan_LENGTH 3
#define AI_IFMyNumCloseArghsLessThan_LENGTH 3
#define AI_IFMyNumCloseArghsGreaterThan_LENGTH 3
#define AI_IFChrHealthLessThan_LENGTH 4
#define AI_IFChrHealthGreaterThan_LENGTH 4
#define AI_IFChrWasDamagedSinceLastCheck_LENGTH 3
#define AI_IFBondHealthLessThan_LENGTH 3
#define AI_IFBondHealthGreaterThan_LENGTH 3
#define AI_SetMyMorale_LENGTH 2
#define AI_AddToMyMorale_LENGTH 2
#define AI_SubtractFromMyMorale_LENGTH 2
#define AI_IFMyMoraleLessThan_LENGTH 3
#define AI_IFMyMoraleLessThanRandom_LENGTH 2
#define AI_SetMyAlertness_LENGTH 2
#define AI_AddToMyAlertness_LENGTH 2
#define AI_SubtractFromMyAlertness_LENGTH 2
#define AI_IFMyAlertnessLessThan_LENGTH 3
#define AI_IFMyAlertnessLessThanRandom_LENGTH 2
#define AI_SetMyHearingScale_LENGTH 3
#define AI_SetMyVisionRange_LENGTH 2
#define AI_SetMyGrenadeProbability_LENGTH 2
#define AI_SetMyChrNum_LENGTH 2
#define AI_SetMyHealthTotal_LENGTH 3
#define AI_SetMyArmour_LENGTH 3
#define AI_SetMySpeedRating_LENGTH 2
#define AI_SetMyArghRating_LENGTH 2
#define AI_SetMyAccuracyRating_LENGTH 2
#define AI_SetMyFlags2_LENGTH 2
#define AI_UnsetMyFlags2_LENGTH 2
#define AI_IFMyFlags2Has_LENGTH 3
#define AI_SetChrBitfield_LENGTH 3
#define AI_UnsetChrBitfield_LENGTH 3
#define AI_IFChrBitfieldHas_LENGTH 4
#define AI_SetObjectiveBitfield_LENGTH 5
#define AI_UnsetObjectiveBitfield_LENGTH 5
#define AI_IFObjectiveBitfieldHas_LENGTH 6
#define AI_SetMychrflags_LENGTH 5
#define AI_UnsetMychrflags_LENGTH 5
#define AI_IFMychrflagsHas_LENGTH 6
#define AI_SetChrchrflags_LENGTH 6
#define AI_UnsetChrchrflags_LENGTH 6
#define AI_IFChrchrflagsHas_LENGTH 7
#define AI_SetObjectFlags_LENGTH 6
#define AI_UnsetObjectFlags_LENGTH 6
#define AI_IFObjectFlagsHas_LENGTH 7
#define AI_SetObjectFlags2_LENGTH 6
#define AI_UnsetObjectFlags2_LENGTH 6
#define AI_IFObjectFlags2Has_LENGTH 7
#define AI_SetMyChrPreset_LENGTH 2
#define AI_SetChrChrPreset_LENGTH 3
#define AI_SetMyPadPreset_LENGTH 3
#define AI_SetChrPadPreset_LENGTH 4
#define AI_MyTimerStart_LENGTH 1
#define AI_MyTimerReset_LENGTH 1
#define AI_MyTimerPause_LENGTH 1
#define AI_MyTimerResume_LENGTH 1
#define AI_IFMyTimerIsNotRunning_LENGTH 2
#define AI_IFMyTimerLessThanTicks_LENGTH 5
#define AI_IFMyTimerGreaterThanTicks_LENGTH 5
#define AI_HudCountdownShow_LENGTH 1
#define AI_HudCountdownHide_LENGTH 1
#define AI_HudCountdownSet_LENGTH 3
#define AI_HudCountdownStop_LENGTH 1
#define AI_HudCountdownStart_LENGTH 1
#define AI_IFHudCountdownIsNotRunning_LENGTH 2
#define AI_IFHudCountdownLessThan_LENGTH 4
#define AI_IFHudCountdownGreaterThan_LENGTH 4
#define AI_TRYSpawningChrAtPad_LENGTH 12
#define AI_TRYSpawningChrNextToChr_LENGTH 11
#define AI_TRYGiveMeItem_LENGTH 9
#define AI_TRYGiveMeHat_LENGTH 8
#define AI_TRYCloningChr_LENGTH 5
#define AI_TextPrintBottom_LENGTH 3
#define AI_TextPrintTop_LENGTH 3
#define AI_SfxPlay_LENGTH 4
#define AI_SfxEmitFromObject_LENGTH 5
#define AI_SfxEmitFromPad_LENGTH 6
#define AI_SfxSetChannelVolume_LENGTH 6
#define AI_SfxFadeChannelVolume_LENGTH 6
#define AI_SfxStopChannel_LENGTH 2
#define AI_IFSfxChannelVolumeLessThan_LENGTH 5
#define AI_VehicleStartPath_LENGTH 2
#define AI_VehicleSpeed_LENGTH 5
#define AI_AircraftRotorSpeed_LENGTH 5
#define AI_IFCameraIsInIntro_LENGTH 2
#define AI_IFCameraIsInBondSwirl_LENGTH 2
#define AI_TvChangeScreenBank_LENGTH 4
#define AI_IFBondInTank_LENGTH /*canonical name*/ 2
#define AI_EndLevel_LENGTH /* canonical name */ 1
#define AI_CameraReturnToBond_LENGTH 1
#define AI_CameraLookAtBondFromPad_LENGTH 3
#define AI_CameraSwitch_LENGTH 6
#define AI_IFBondYPosLessThan_LENGTH 4
#define AI_BondDisableControl_LENGTH 2
#define AI_BondEnableControl_LENGTH 1
#define AI_TRYTeleportingChrToPad_LENGTH 5
#define AI_ScreenFadeToBlack_LENGTH 1
#define AI_ScreenFadeFromBlack_LENGTH 1
#define AI_IFScreenFadeCompleted_LENGTH 2
#define AI_HideAllChrs_LENGTH 1
#define AI_ShowAllChrs_LENGTH 1
#define AI_DoorOpenInstant_LENGTH 2
#define AI_ChrRemoveItemInHand_LENGTH 3
#define AI_IfNumberOfActivePlayersLessThan_LENGTH 3
#define AI_IFBondItemTotalAmmoLessThan_LENGTH 4
#define AI_BondEquipItem_LENGTH 2
#define AI_BondEquipItemCinema_LENGTH 2
#define AI_BondSetLockedVelocity_LENGTH 3
#define AI_IFObjectInRoomWithPad_LENGTH 5
#define AI_SwitchSky_LENGTH 1
#define AI_TriggerFadeAndExitLevelOnButtonPress_LENGTH 1
#define AI_IFBondIsDead_LENGTH 2
#define AI_BondDisableDamageAndPickups_LENGTH 1
#define AI_BondHideWeapons_LENGTH 1
#define AI_CameraOrbitPad_LENGTH 13
#define AI_CreditsRoll_LENGTH 1
#define AI_IFCreditsHasCompleted_LENGTH 2
#define AI_IFObjectiveAllCompleted_LENGTH 2
#define AI_IFFolderActorIsEqual_LENGTH 3
#define AI_IFBondDamageAndPickupsDisabled_LENGTH 2
#define AI_MusicPlaySlot_LENGTH 4
#define AI_MusicStopSlot_LENGTH 2
#define AI_TriggerExplosionsAroundBond_LENGTH 1
#define AI_IFKilledCiviliansGreaterThan_LENGTH 3
#define AI_IFChrWasShotSinceLastCheck_LENGTH 3
#define AI_BondKilledInAction_LENGTH 1
#define AI_RaiseArms_LENGTH 1
#define AI_GasLeakAndFadeFog_LENGTH 1
#define AI_ObjectRocketLaunch_LENGTH 2
#pragma endregion
int AI_CMD_LENGTHS_ToInt[] = {
AI_GotoNext_LENGTH,
AI_GotoFirst_LENGTH,
AI_Label_LENGTH,
AI_Yield_LENGTH,
AI_EndList_LENGTH,
AI_SetChrAiList_LENGTH,
AI_SetReturnAiList_LENGTH,
AI_Return_LENGTH,
AI_Stop_LENGTH,
AI_Kneel_LENGTH,
AI_PlayAnimation_LENGTH,
AI_IFPlayingAnimation_LENGTH,
AI_PointAtBond_LENGTH,
AI_LookSurprised_LENGTH,
AI_TRYSidestepping_LENGTH,
AI_TRYSideHopping_LENGTH,
AI_TRYSideRunning_LENGTH,
AI_TRYFiringWalk_LENGTH,
AI_TRYFiringRun_LENGTH,
AI_TRYFiringRoll_LENGTH,
AI_TRYFireOrAimAtTarget_LENGTH,
AI_TRYFireOrAimAtTargetKneel_LENGTH,
AI_TRYFireOrAimAtTargetUpdate_LENGTH,
AI_TRYFacingTarget_LENGTH,
AI_HitChrWithItem_LENGTH,
AI_ChrHitChr_LENGTH,
AI_TRYThrowingGrenade_LENGTH,
AI_TRYDroppingItem_LENGTH,
AI_RunToPad_LENGTH,
AI_RunToPadPreset_LENGTH,
AI_WalkToPad_LENGTH,
AI_SprintToPad_LENGTH,
AI_StartPatrol_LENGTH,
AI_Surrender_LENGTH,
AI_RemoveMe_LENGTH,
AI_ChrRemoveInstant_LENGTH,
AI_TRYTriggeringAlarmAtPad_LENGTH,
AI_AlarmOn_LENGTH,
AI_AlarmOff_LENGTH,
AI_TRYRunFromBond_LENGTH,
AI_TRYRunToBond_LENGTH,
AI_TRYWalkToBond_LENGTH,
AI_TRYSprintToBond_LENGTH,
AI_TRYFindCover_LENGTH,
AI_TRYRunToChr_LENGTH,
AI_TRYWalkToChr_LENGTH,
AI_TRYSprintToChr_LENGTH,
AI_IFImOnPatrolOrStopped_LENGTH,
AI_IFChrDyingOrDead_LENGTH,
AI_IFChrDoesNotExist_LENGTH,
AI_IFISeeBond_LENGTH,
AI_SetNewRandom_LENGTH,
AI_IFRandomLessThan_LENGTH,
AI_IFRandomGreaterThan_LENGTH,
AI_IFICanHearAlarm_LENGTH,
AI_IFAlarmIsOn_LENGTH,
AI_IFGasIsLeaking_LENGTH,
AI_IFIHeardBond_LENGTH,
AI_IFISeeSomeoneShot_LENGTH,
AI_IFISeeSomeoneDie_LENGTH,
AI_IFICouldSeeBond_LENGTH,
AI_IFICouldSeeBondsStan_LENGTH,
AI_IFIWasShotRecently_LENGTH,
AI_IFIHeardBondRecently_LENGTH,
AI_IFImInRoomWithChr_LENGTH,
AI_IFIveNotBeenSeen_LENGTH,
AI_IFImOnScreen_LENGTH,
AI_IFMyRoomIsOnScreen_LENGTH,
AI_IFRoomWithPadIsOnScreen_LENGTH,
AI_IFImTargetedByBond_LENGTH,
AI_IFBondMissedMe_LENGTH,
AI_IFMyAngleToBondLessThan_LENGTH,
AI_IFMyAngleToBondGreaterThan_LENGTH,
AI_IFMyAngleFromBondLessThan_LENGTH,
AI_IFMyAngleFromBondGreaterThan_LENGTH,
AI_IFMyDistanceToBondLessThanDecimeter_LENGTH,
AI_IFMyDistanceToBondGreaterThanDecimeter_LENGTH,
AI_IFChrDistanceToPadLessThanDecimeter_LENGTH,
AI_IFChrDistanceToPadGreaterThanDecimeter_LENGTH,
AI_IFMyDistanceToChrLessThanDecimeter_LENGTH,
AI_IFMyDistanceToChrGreaterThanDecimeter_LENGTH,
AI_TRYSettingMyPresetToChrWithinDistanceDecimeter_LENGTH,
AI_IFBondDistanceToPadLessThanDecimeter_LENGTH,
AI_IFBondDistanceToPadGreaterThanDecimeter_LENGTH,
AI_IFChrInRoomWithPad_LENGTH,
AI_IFBondInRoomWithPad_LENGTH,
AI_IFBondCollectedObject_LENGTH,
AI_IFItemIsStationaryWithinLevel_LENGTH,
AI_IFItemIsAttachedToObject_LENGTH,
AI_IFBondHasItemEquipped_LENGTH,
AI_IFObjectExists_LENGTH,
AI_IFObjectNotDestroyed_LENGTH,
AI_IFObjectWasActivated_LENGTH,
AI_IFBondUsedGadgetOnObject_LENGTH,
AI_ActivateObject_LENGTH,
AI_DestroyObject_LENGTH,
AI_DropObject_LENGTH,
AI_ChrDropAllConcealedItems_LENGTH,
AI_ChrDropAllHeldItems_LENGTH,
AI_BondCollectObject_LENGTH,
AI_ChrEquipObject_LENGTH,
AI_MoveObject_LENGTH,
AI_DoorOpen_LENGTH,
AI_DoorClose_LENGTH,
AI_IFDoorStateEqual_LENGTH,
AI_IFDoorHasBeenOpenedBefore_LENGTH,
AI_DoorSetLock_LENGTH,
AI_DoorUnsetLock_LENGTH,
AI_IFDoorLockEqual_LENGTH,
AI_IFObjectiveNumComplete_LENGTH,
AI_TRYUnknown6e_LENGTH,
AI_TRYUnknown6f_LENGTH,
AI_IFGameDifficultyLessThan_LENGTH,
AI_IFGameDifficultyGreaterThan_LENGTH,
AI_IFMissionTimeLessThan_LENGTH,
AI_IFMissionTimeGreaterThan_LENGTH,
AI_IFSystemPowerTimeLessThan_LENGTH,
AI_IFSystemPowerTimeGreaterThan_LENGTH,
AI_IFLevelIdLessThan_LENGTH,
AI_IFLevelIdGreaterThan_LENGTH,
AI_IFMyNumArghsLessThan_LENGTH,
AI_IFMyNumArghsGreaterThan_LENGTH,
AI_IFMyNumCloseArghsLessThan_LENGTH,
AI_IFMyNumCloseArghsGreaterThan_LENGTH,
AI_IFChrHealthLessThan_LENGTH,
AI_IFChrHealthGreaterThan_LENGTH,
AI_IFChrWasDamagedSinceLastCheck_LENGTH,
AI_IFBondHealthLessThan_LENGTH,
AI_IFBondHealthGreaterThan_LENGTH,
AI_SetMyMorale_LENGTH,
AI_AddToMyMorale_LENGTH,
AI_SubtractFromMyMorale_LENGTH,
AI_IFMyMoraleLessThan_LENGTH,
AI_IFMyMoraleLessThanRandom_LENGTH,
AI_SetMyAlertness_LENGTH,
AI_AddToMyAlertness_LENGTH,
AI_SubtractFromMyAlertness_LENGTH,
AI_IFMyAlertnessLessThan_LENGTH,
AI_IFMyAlertnessLessThanRandom_LENGTH,
AI_SetMyHearingScale_LENGTH,
AI_SetMyVisionRange_LENGTH,
AI_SetMyGrenadeProbability_LENGTH,
AI_SetMyChrNum_LENGTH,
AI_SetMyHealthTotal_LENGTH,
AI_SetMyArmour_LENGTH,
AI_SetMySpeedRating_LENGTH,
AI_SetMyArghRating_LENGTH,
AI_SetMyAccuracyRating_LENGTH,
AI_SetMyFlags2_LENGTH,
AI_UnsetMyFlags2_LENGTH,
AI_IFMyFlags2Has_LENGTH,
AI_SetChrBitfield_LENGTH,
AI_UnsetChrBitfield_LENGTH,
AI_IFChrBitfieldHas_LENGTH,
AI_SetObjectiveBitfield_LENGTH,
AI_UnsetObjectiveBitfield_LENGTH,
AI_IFObjectiveBitfieldHas_LENGTH,
AI_SetMychrflags_LENGTH,
AI_UnsetMychrflags_LENGTH,
AI_IFMychrflagsHas_LENGTH,
AI_SetChrchrflags_LENGTH,
AI_UnsetChrchrflags_LENGTH,
AI_IFChrchrflagsHas_LENGTH,
AI_SetObjectFlags_LENGTH,
AI_UnsetObjectFlags_LENGTH,
AI_IFObjectFlagsHas_LENGTH,
AI_SetObjectFlags2_LENGTH,
AI_UnsetObjectFlags2_LENGTH,
AI_IFObjectFlags2Has_LENGTH,
AI_SetMyChrPreset_LENGTH,
AI_SetChrChrPreset_LENGTH,
AI_SetMyPadPreset_LENGTH,
AI_SetChrPadPreset_LENGTH,
0,
AI_MyTimerStart_LENGTH,
AI_MyTimerReset_LENGTH,
AI_MyTimerPause_LENGTH,
AI_MyTimerResume_LENGTH,
AI_IFMyTimerIsNotRunning_LENGTH,
AI_IFMyTimerLessThanTicks_LENGTH,
AI_IFMyTimerGreaterThanTicks_LENGTH,
AI_HudCountdownShow_LENGTH,
AI_HudCountdownHide_LENGTH,
AI_HudCountdownSet_LENGTH,
AI_HudCountdownStop_LENGTH,
AI_HudCountdownStart_LENGTH,
AI_IFHudCountdownIsNotRunning_LENGTH,
AI_IFHudCountdownLessThan_LENGTH,
AI_IFHudCountdownGreaterThan_LENGTH,
AI_TRYSpawningChrAtPad_LENGTH,
AI_TRYSpawningChrNextToChr_LENGTH,
AI_TRYGiveMeItem_LENGTH,
AI_TRYGiveMeHat_LENGTH,
AI_TRYCloningChr_LENGTH,
AI_TextPrintBottom_LENGTH,
AI_TextPrintTop_LENGTH,
AI_SfxPlay_LENGTH,
AI_SfxEmitFromObject_LENGTH,
AI_SfxEmitFromPad_LENGTH,
AI_SfxSetChannelVolume_LENGTH,
AI_SfxFadeChannelVolume_LENGTH,
AI_SfxStopChannel_LENGTH,
AI_IFSfxChannelVolumeLessThan_LENGTH,
AI_VehicleStartPath_LENGTH,
AI_VehicleSpeed_LENGTH,
AI_AircraftRotorSpeed_LENGTH,
AI_IFCameraIsInIntro_LENGTH,
AI_IFCameraIsInBondSwirl_LENGTH,
AI_TvChangeScreenBank_LENGTH,
AI_IFBondInTank_LENGTH,
AI_EndLevel_LENGTH,
AI_CameraReturnToBond_LENGTH,
AI_CameraLookAtBondFromPad_LENGTH,
AI_CameraSwitch_LENGTH,
AI_IFBondYPosLessThan_LENGTH,
AI_BondDisableControl_LENGTH,
AI_BondEnableControl_LENGTH,
AI_TRYTeleportingChrToPad_LENGTH,
AI_ScreenFadeToBlack_LENGTH,
AI_ScreenFadeFromBlack_LENGTH,
AI_IFScreenFadeCompleted_LENGTH,
AI_HideAllChrs_LENGTH,
AI_ShowAllChrs_LENGTH,
AI_DoorOpenInstant_LENGTH,
AI_ChrRemoveItemInHand_LENGTH,
AI_IfNumberOfActivePlayersLessThan_LENGTH,
AI_IFBondItemTotalAmmoLessThan_LENGTH,
AI_BondEquipItem_LENGTH,
AI_BondEquipItemCinema_LENGTH,
AI_BondSetLockedVelocity_LENGTH,
AI_IFObjectInRoomWithPad_LENGTH,
AI_IFImFiringAndLockedForward_LENGTH,
AI_IFImFiring_LENGTH,
AI_SwitchSky_LENGTH,
AI_TriggerFadeAndExitLevelOnButtonPress_LENGTH,
AI_IFBondIsDead_LENGTH,
AI_BondDisableDamageAndPickups_LENGTH,
AI_BondHideWeapons_LENGTH,
AI_CameraOrbitPad_LENGTH,
AI_CreditsRoll_LENGTH,
AI_IFCreditsHasCompleted_LENGTH,
AI_IFObjectiveAllCompleted_LENGTH,
AI_IFFolderActorIsEqual_LENGTH,
AI_IFBondDamageAndPickupsDisabled_LENGTH,
AI_MusicPlaySlot_LENGTH,
AI_MusicStopSlot_LENGTH,
AI_TriggerExplosionsAroundBond_LENGTH,
AI_IFKilledCiviliansGreaterThan_LENGTH,
AI_IFChrWasShotSinceLastCheck_LENGTH,
AI_BondKilledInAction_LENGTH,
AI_RaiseArms_LENGTH,
AI_GasLeakAndFadeFog_LENGTH,
AI_ObjectRocketLaunch_LENGTH};
typedef enum AI_CMD
{
AI_GotoNext,
AI_GotoFirst,
AI_Label,
AI_Yield,
AI_EndList,
AI_SetChrAiList,
AI_SetReturnAiList,
AI_Return,
AI_Stop,
AI_Kneel,
AI_PlayAnimation,
AI_IFPlayingAnimation,
AI_PointAtBond,
AI_LookSurprised,
AI_TRYSidestepping,
AI_TRYSideHopping,
AI_TRYSideRunning,
AI_TRYFiringWalk,
AI_TRYFiringRun,
AI_TRYFiringRoll,
AI_TRYFireOrAimAtTarget,
AI_TRYFireOrAimAtTargetKneel,
AI_TRYFireOrAimAtTargetUpdate,
AI_TRYFacingTarget,
AI_HitChrWithItem,
AI_ChrHitChr,
AI_TRYThrowingGrenade,
AI_TRYDroppingItem,
AI_RunToPad,
AI_RunToPadPreset,
AI_WalkToPad,
AI_SprintToPad,
AI_StartPatrol,
AI_Surrender,
AI_RemoveMe,
AI_ChrRemoveInstant,
AI_TRYTriggeringAlarmAtPad,
AI_AlarmOn,
AI_AlarmOff,
AI_TRYRunFromBond,
AI_TRYRunToBond,
AI_TRYWalkToBond,
AI_TRYSprintToBond,
AI_TRYFindCover,
AI_TRYRunToChr,
AI_TRYWalkToChr,
AI_TRYSprintToChr,
AI_IFImOnPatrolOrStopped,
AI_IFChrDyingOrDead,
AI_IFChrDoesNotExist,
AI_IFISeeBond,
AI_SetNewRandom,
AI_IFRandomLessThan,
AI_IFRandomGreaterThan,
AI_IFICanHearAlarm,
AI_IFAlarmIsOn,
AI_IFGasIsLeaking,
AI_IFIHeardBond,
AI_IFISeeSomeoneShot,
AI_IFISeeSomeoneDie,
AI_IFICouldSeeBond,
AI_IFICouldSeeBondsStan,
AI_IFIWasShotRecently,
AI_IFIHeardBondRecently,
AI_IFImInRoomWithChr,
AI_IFIveNotBeenSeen,
AI_IFImOnScreen,
AI_IFMyRoomIsOnScreen,
AI_IFRoomWithPadIsOnScreen,
AI_IFImTargetedByBond,
AI_IFBondMissedMe,
AI_IFMyAngleToBondLessThan,
AI_IFMyAngleToBondGreaterThan,
AI_IFMyAngleFromBondLessThan,
AI_IFMyAngleFromBondGreaterThan,
AI_IFMyDistanceToBondLessThanDecimeter,
AI_IFMyDistanceToBondGreaterThanDecimeter,
AI_IFChrDistanceToPadLessThanDecimeter,
AI_IFChrDistanceToPadGreaterThanDecimeter,
AI_IFMyDistanceToChrLessThanDecimeter,
AI_IFMyDistanceToChrGreaterThanDecimeter,
AI_TRYSettingMyPresetToChrWithinDistanceDecimeter,
AI_IFBondDistanceToPadLessThanDecimeter,
AI_IFBondDistanceToPadGreaterThanDecimeter,
AI_IFChrInRoomWithPad,
AI_IFBondInRoomWithPad,
AI_IFBondCollectedObject,
AI_IFItemIsStationaryWithinLevel,
AI_IFItemIsAttachedToObject,
AI_IFBondHasItemEquipped,
AI_IFObjectExists,
AI_IFObjectNotDestroyed,
AI_IFObjectWasActivated,
AI_IFBondUsedGadgetOnObject,
AI_ActivateObject,
AI_DestroyObject,
AI_DropObject,
AI_ChrDropAllConcealedItems,
AI_ChrDropAllHeldItems,
AI_BondCollectObject,
AI_ChrEquipObject,
AI_MoveObject,
AI_DoorOpen,
AI_DoorClose,
AI_IFDoorStateEqual,
AI_IFDoorHasBeenOpenedBefore,
AI_DoorSetLock,
AI_DoorUnsetLock,
AI_IFDoorLockEqual,
AI_IFObjectiveNumComplete,
AI_TRYUnknown6e,
AI_TRYUnknown6f,
AI_IFGameDifficultyLessThan,
AI_IFGameDifficultyGreaterThan,
AI_IFMissionTimeLessThan,
AI_IFMissionTimeGreaterThan,
AI_IFSystemPowerTimeLessThan,
AI_IFSystemPowerTimeGreaterThan,
AI_IFLevelIdLessThan,
AI_IFLevelIdGreaterThan,
AI_IFMyNumArghsLessThan,
AI_IFMyNumArghsGreaterThan,
AI_IFMyNumCloseArghsLessThan,
AI_IFMyNumCloseArghsGreaterThan,
AI_IFChrHealthLessThan,
AI_IFChrHealthGreaterThan,
AI_IFChrWasDamagedSinceLastCheck,
AI_IFBondHealthLessThan,
AI_IFBondHealthGreaterThan,
AI_SetMyMorale,
AI_AddToMyMorale,
AI_SubtractFromMyMorale,
AI_IFMyMoraleLessThan,
AI_IFMyMoraleLessThanRandom,
AI_SetMyAlertness,
AI_AddToMyAlertness,
AI_SubtractFromMyAlertness,
AI_IFMyAlertnessLessThan,
AI_IFMyAlertnessLessThanRandom,
AI_SetMyHearingScale,
AI_SetMyVisionRange,
AI_SetMyGrenadeProbability,
AI_SetMyChrNum,
AI_SetMyHealthTotal,
AI_SetMyArmour,
AI_SetMySpeedRating,
AI_SetMyArghRating,
AI_SetMyAccuracyRating,
AI_SetMyFlags2,
AI_UnsetMyFlags2,
AI_IFMyFlags2Has,
AI_SetChrBitfield,
AI_UnsetChrBitfield,
AI_IFChrBitfieldHas,
AI_SetObjectiveBitfield,
AI_UnsetObjectiveBitfield,
AI_IFObjectiveBitfieldHas,
AI_SetMychrflags,
AI_UnsetMychrflags,
AI_IFMychrflagsHas,
AI_SetChrchrflags,
AI_UnsetChrchrflags,
AI_IFChrchrflagsHas,
AI_SetObjectFlags,
AI_UnsetObjectFlags,
AI_IFObjectFlagsHas,
AI_SetObjectFlags2,
AI_UnsetObjectFlags2,
AI_IFObjectFlags2Has,
AI_SetMyChrPreset,
AI_SetChrChrPreset,
AI_SetMyPadPreset,
AI_SetChrPadPreset,
AI_PRINT,
AI_MyTimerStart,
AI_MyTimerReset,
AI_MyTimerPause,
AI_MyTimerResume,
AI_IFMyTimerIsNotRunning,
AI_IFMyTimerLessThanTicks,
AI_IFMyTimerGreaterThanTicks,
AI_HudCountdownShow,
AI_HudCountdownHide,
AI_HudCountdownSet,
AI_HudCountdownStop,
AI_HudCountdownStart,
AI_IFHudCountdownIsNotRunning,
AI_IFHudCountdownLessThan,
AI_IFHudCountdownGreaterThan,
AI_TRYSpawningChrAtPad,
AI_TRYSpawningChrNextToChr,
AI_TRYGiveMeItem,
AI_TRYGiveMeHat,
AI_TRYCloningChr,
AI_TextPrintBottom,
AI_TextPrintTop,
AI_SfxPlay,
AI_SfxEmitFromObject,
AI_SfxEmitFromPad,
AI_SfxSetChannelVolume,
AI_SfxFadeChannelVolume,
AI_SfxStopChannel,
AI_IFSfxChannelVolumeLessThan,
AI_VehicleStartPath,
AI_VehicleSpeed,
AI_AircraftRotorSpeed,
AI_IFCameraIsInIntro,
AI_IFCameraIsInBondSwirl,
AI_TvChangeScreenBank,
AI_IFBondInTank,
AI_EndLevel,
AI_CameraReturnToBond,
AI_CameraLookAtBondFromPad,
AI_CameraSwitch,
AI_IFBondYPosLessThan,
AI_BondDisableControl,
AI_BondEnableControl,
AI_TRYTeleportingChrToPad,
AI_ScreenFadeToBlack,
AI_ScreenFadeFromBlack,
AI_IFScreenFadeCompleted,
AI_HideAllChrs,
AI_ShowAllChrs,
AI_DoorOpenInstant,
AI_ChrRemoveItemInHand,
AI_IfNumberOfActivePlayersLessThan,
AI_IFBondItemTotalAmmoLessThan,
AI_BondEquipItem,
AI_BondEquipItemCinema,
AI_BondSetLockedVelocity,
AI_IFObjectInRoomWithPad,
AI_IFImFiringAndLockedForward,
AI_IFImFiring,
AI_SwitchSky,
AI_TriggerFadeAndExitLevelOnButtonPress,
AI_IFBondIsDead,
AI_BondDisableDamageAndPickups,
AI_BondHideWeapons,
AI_CameraOrbitPad,
AI_CreditsRoll,
AI_IFCreditsHasCompleted,
AI_IFObjectiveAllCompleted,
AI_IFFolderActorIsEqual,
AI_IFBondDamageAndPickupsDisabled,
AI_MusicPlaySlot,
AI_MusicStopSlot,
AI_TriggerExplosionsAroundBond,
AI_IFKilledCiviliansGreaterThan,
AI_IFChrWasShotSinceLastCheck,
AI_BondKilledInAction,
AI_RaiseArms,
AI_GasLeakAndFadeFog,
AI_ObjectRocketLaunch,
AI_CMD_COUNT
} AI_CMD;
char *AI_CMD_ToString[] = {
"GotoNext",
"GotoFirst",
"Label",
"Yield",
"EndList",
"SetChrAiList",
"SetReturnAiList",
"Return",
"Stop",
"Kneel",
"PlayAnimation",
"IFPlayingAnimation",
"PointAtBond",
"LookSurprised",
"TRYSidestepping",
"TRYSideHopping",
"TRYSideRunning",
"TRYFiringWalk",
"TRYFiringRun",
"TRYFiringRoll",
"TRYFireOrAimAtTarget",
"TRYFireOrAimAtTargetKneel",
"TRYFireOrAimAtTargetUpdate",
"TRYFacingTarget",
"HitChrWithItem",
"ChrHitChr",
"TRYThrowingGrenade",
"TRYDroppingItem",
"RunToPad",
"RunToPadPreset",
"WalkToPad",
"SprintToPad",
"StartPatrol",
"Surrender",
"RemoveMe",
"ChrRemoveInstant",
"TRYTriggeringAlarmAtPad",
"AlarmOn",
"AlarmOff",
"TRYRunFromBond",
"TRYRunToBond",
"TRYWalkToBond",
"TRYSprintToBond",
"TRYFindCover",
"TRYRunToChr",
"TRYWalkToChr",
"TRYSprintToChr",
"IFImOnPatrolOrStopped",
"IFChrDyingOrDead",
"IFChrDoesNotExist",
"IFISeeBond",
"SetNewRandom",
"IFRandomLessThan",
"IFRandomGreaterThan",
"IFICanHearAlarm",
"IFAlarmIsOn",
"IFGasIsLeaking",
"IFIHeardBond",
"IFISeeSomeoneShot",
"IFISeeSomeoneDie",
"IFICouldSeeBond",
"IFICouldSeeBondsStan",
"IFIWasShotRecently",
"IFIHeardBondRecently",
"IFImInRoomWithChr",
"IFIveNotBeenSeen",
"IFImOnScreen",
"IFMyRoomIsOnScreen",
"IFRoomWithPadIsOnScreen",
"IFImTargetedByBond",
"IFBondMissedMe",
"IFMyAngleToBondLessThan",
"IFMyAngleToBondGreaterThan",
"IFMyAngleFromBondLessThan",
"IFMyAngleFromBondGreaterThan",
"IFMyDistanceToBondLessThanDecimeter",
"IFMyDistanceToBondGreaterThanDecimeter",
"IFChrDistanceToPadLessThanDecimeter",
"IFChrDistanceToPadGreaterThanDecimeter",
"IFMyDistanceToChrLessThanDecimeter",
"IFMyDistanceToChrGreaterThanDecimeter",
"TRYSettingMyPresetToChrWithinDistanceDecimeter",
"IFBondDistanceToPadLessThanDecimeter",
"IFBondDistanceToPadGreaterThanDecimeter",
"IFChrInRoomWithPad",
"IFBondInRoomWithPad",
"IFBondCollectedObject",
"IFItemIsStationaryWithinLevel",
"IFItemIsAttachedToObject",
"IFBondHasItemEquipped",
"IFObjectExists",
"IFObjectNotDestroyed",
"IFObjectWasActivated",
"IFBondUsedGadgetOnObject",
"ActivateObject",
"DestroyObject",
"DropObject",
"ChrDropAllConcealedItems",
"ChrDropAllHeldItems",
"BondCollectObject",
"ChrEquipObject",
"MoveObject",
"DoorOpen",
"DoorClose",
"IFDoorStateEqual",
"IFDoorHasBeenOpenedBefore",
"DoorSetLock",
"DoorUnsetLock",
"IFDoorLockEqual",
"IFObjectiveNumComplete",
"TRYUnknown6e",
"TRYUnknown6f",
"IFGameDifficultyLessThan",
"IFGameDifficultyGreaterThan",
"IFMissionTimeLessThan",
"IFMissionTimeGreaterThan",
"IFSystemPowerTimeLessThan",
"IFSystemPowerTimeGreaterThan",
"IFLevelIdLessThan",
"IFLevelIdGreaterThan",
"IFMyNumArghsLessThan",
"IFMyNumArghsGreaterThan",
"IFMyNumCloseArghsLessThan",
"IFMyNumCloseArghsGreaterThan",
"IFChrHealthLessThan",
"IFChrHealthGreaterThan",
"IFChrWasDamagedSinceLastCheck",
"IFBondHealthLessThan",
"IFBondHealthGreaterThan",
"SetMyMorale",
"AddToMyMorale",
"SubtractFromMyMorale",
"IFMyMoraleLessThan",
"IFMyMoraleLessThanRandom",
"SetMyAlertness",
"AddToMyAlertness",
"SubtractFromMyAlertness",
"IFMyAlertnessLessThan",
"IFMyAlertnessLessThanRandom",
"SetMyHearingScale",
"SetMyVisionRange",
"SetMyGrenadeProbability",
"SetMyChrNum",
"SetMyHealthTotal",
"SetMyArmour",
"SetMySpeedRating",
"SetMyArghRating",
"SetMyAccuracyRating",
"SetMyFlags2",
"UnsetMyFlags2",
"IFMyFlags2Has",
"SetChrBitfield",
"UnsetChrBitfield",
"IFChrBitfieldHas",
"SetObjectiveBitfield",
"UnsetObjectiveBitfield",
"IFObjectiveBitfieldHas",
"SetMychrflags",
"UnsetMychrflags",
"IFMychrflagsHas",
"SetChrchrflags",
"UnsetChrchrflags",
"IFChrchrflagsHas",
"SetObjectFlags",
"UnsetObjectFlags",
"IFObjectFlagsHas",
"SetObjectFlags2",
"UnsetObjectFlags2",
"IFObjectFlags2Has",
"SetMyChrPreset",
"SetChrChrPreset",
"SetMyPadPreset",
"SetChrPadPreset",
"PRINT",
"MyTimerStart",
"MyTimerReset",
"MyTimerPause",
"MyTimerResume",
"IFMyTimerIsNotRunning",
"IFMyTimerLessThanTicks",
"IFMyTimerGreaterThanTicks",
"HudCountdownShow",
"HudCountdownHide",
"HudCountdownSet",
"HudCountdownStop",
"HudCountdownStart",
"IFHudCountdownIsNotRunning",
"IFHudCountdownLessThan",
"IFHudCountdownGreaterThan",
"TRYSpawningChrAtPad",
"TRYSpawningChrNextToChr",
"TRYGiveMeItem",
"TRYGiveMeHat",
"TRYCloningChr",
"TextPrintBottom",
"TextPrintTop",
"SfxPlay",
"SfxEmitFromObject",
"SfxEmitFromPad",
"SfxSetChannelVolume",
"SfxFadeChannelVolume",
"SfxStopChannel",
"IFSfxChannelVolumeLessThan",
"VehicleStartPath",
"VehicleSpeed",
"AircraftRotorSpeed",
"IFCameraIsInIntro",
"IFCameraIsInBondSwirl",
"TvChangeScreenBank",
"IFBondInTank",
"EndLevel",
"CameraReturnToBond",
"CameraLookAtBondFromPad",
"CameraSwitch",
"IFBondYPosLessThan",
"BondDisableControl",
"BondEnableControl",
"TRYTeleportingChrToPad",
"ScreenFadeToBlack",
"ScreenFadeFromBlack",
"IFScreenFadeCompleted",
"HideAllChrs",
"ShowAllChrs",
"DoorOpenInstant",
"ChrRemoveItemInHand",
"IfNumberOfActivePlayersLessThan",
"IFBondItemTotalAmmoLessThan",
"BondEquipItem",
"BondEquipItemCinema",
"BondSetLockedVelocity",
"IFObjectInRoomWithPad",
"IFImFiringAndLockedForward",
"IFImFiring",
"SwitchSky",
"TriggerFadeAndExitLevelOnButtonPress",
"IFBondIsDead",
"BondDisableDamageAndPickups",
"BondHideWeapons",
"CameraOrbitPad",
"CreditsRoll",
"IFCreditsHasCompleted",
"IFObjectiveAllCompleted",
"IFFolderActorIsEqual",
"IFBondDamageAndPickupsDisabled",
"MusicPlaySlot",
"MusicStopSlot",
"TriggerExplosionsAroundBond",
"IFKilledCiviliansGreaterThan",
"IFChrWasShotSinceLastCheck",
"BondKilledInAction",
"RaiseArms",
"GasLeakAndFadeFog",
"ObjectRocketLaunch"};
#define MAX 10
int top = -1;
char stack[MAX];
/*PUSH FUNCTION*/
int push(int item)
{
if (top == (MAX - 1))
{
return 0;
}
else
{
++top;
stack[top] = item;
return 1;
}
}
/*POP */
int pop()
{
if (top == -1)
{
return 0;
}
else
{
--top;
return stack[top + 1];
}
}
/*Sniff */
int sniff()
{
if (top == -1)
{
return 0;
}
else
{
return stack[top];
}
}
void displayStack()
{
int i;
printf("\nThe label Stack is: ");
if (top == -1)
{
printf("empty");
}
else
{
for (i = top; i >= 0; --i)
{
printf("\n%3d", stack[i]);
}
}
printf("\n---------------\n\n");
}
/**
* @brief Parse AI list and print out C Macros
* @param AiList: Bytestream for ai
* @param ID: List ID
*/
void ai(unsigned char *AiList, short ID)
{
for (int Offset = 0;;)
{
char tabs[MAX + 1];
for (int k = 0; k < MAX; k++)
{
tabs[k] = 0;
}
for (int k = 0; k < top + 2 && k < MAX; k++)
{
tabs[k] = '\t';
}
switch (AiList[Offset])
{
case AI_GotoNext: // BYTE(LABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n\n");
Offset += AI_GotoNext_LENGTH;
break;
}
case AI_GotoFirst: // BYTE(LABEL)
{
if (AiList[Offset + 1] == sniff())
{
pop();
for (int k = top + 2; k < MAX; k++)
{
tabs[k] = 0;
}
printf("%sLOOP(", tabs);
}
else
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
}
printf("lbl%d", AiList[Offset + 1]);
printf(")\n\n");
Offset += AI_GotoFirst_LENGTH;
break;
}
case AI_Label: // BYTE(ID)
{
if (AiList[Offset + 2] == AI_Yield)
{
if (AiList[Offset + 3] != AI_GotoFirst)
{
push(AiList[Offset + 1]);
printf("\n%sDO(", tabs);
printf("lbl%d", AiList[Offset + 1]);
Offset += AI_Yield_LENGTH;
}
else
{
printf("\n%sYIELD_FOREVER(", tabs);
printf("lbl%d", AiList[Offset + 1]);
Offset += AI_Yield_LENGTH + AI_GotoFirst_LENGTH;
}
}
else
{
printf("\n%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
}
printf(")\n");
Offset += AI_Label_LENGTH;
break;
}
case AI_Yield: // /*NONE*/
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_Yield_LENGTH;
break;
}
case AI_EndList /*canonical name*/: // /*NONE*/
{
printf("\n%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n\n");
return;
}
case AI_SetChrAiList: // BYTE(CHR_NUM), DBYTE(AI_LIST_ID)
{
unsigned short AI_LIST_ID = CharArrayTo16(AiList, (Offset + 1 + 1)); /* This is the only way to match despite assetrs below */
signed char CHR_NUM = AiList[Offset + 1];
if (CHR_NUM == CHR_SELF)
{
if (AiList[Offset - AI_SetReturnAiList_LENGTH] == AI_SetReturnAiList &&
CharArrayTo16(AiList, Offset + 1 - AI_SetReturnAiList_LENGTH) == ID)
{
printf("%sCALL(", tabs);
}
else
{
printf("%sJumpTo(", tabs);
}
}
else if (CHR_NUM == CHR_BOND_CINEMA)
{
printf("%sSetBondsAiList(", tabs);
}
else
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,", CHR_NUM);
}
if (isGlobalAIListID(AI_LIST_ID))
{
printf("%s", GAILIST_ToString[AI_LIST_ID]);
}
else if (isBGAIListID(AI_LIST_ID))
{
printf("setBGAIListID(%d)", getBGAIListID(AI_LIST_ID));
}
else
{
printf("setChrAIListID(%d)", getChrAIListID(AI_LIST_ID));
}
printf(")\n");
Offset += AI_SetChrAiList_LENGTH;
break;
}
case AI_SetReturnAiList: // DBYTE(AI_LIST_ID)
{
unsigned short AI_LIST_ID = CharArrayTo16(AiList, (Offset + 1));
if (!(AiList[Offset + AI_SetReturnAiList_LENGTH] == AI_SetChrAiList &&
AI_LIST_ID == ID &&
(signed char)AiList[Offset + AI_SetReturnAiList_LENGTH + 1] == CHR_SELF))
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AI_LIST_ID);
printf(")\n");
}
Offset += AI_SetReturnAiList_LENGTH;
break;
}
case AI_Return: // /*NONE*/
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_Return_LENGTH;
;
break;
}
case AI_Stop: // /*NONE*/
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_Stop_LENGTH;
break;
}
case AI_Kneel: // /*NONE*/
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_Kneel_LENGTH;
break;
}
case AI_PlayAnimation: // DBYTE(ANIMATION_ID), DBYTE(START_TIME30),DBYTE(END_TIME30), BYTE(BITFIELD), BYTE(INTERPOL_TIME60)
{
int startframe, anim_id, zero, endframe;
anim_id = CharArrayTo16(AiList, Offset + 1 + 0);
startframe = CharArrayTo16(AiList, Offset + 1 + 2);
endframe = CharArrayTo16(AiList, Offset + 1 + 4);
if (startframe == -1 && endframe == -1 && AiList[Offset + 1 + 6] == 6 && AiList[Offset + 1 + 7] == 16)
{
printf("%sPlayAnimationSimple(", tabs);
printf("%d", anim_id);
}
else
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,%d,%d,%d", anim_id, startframe, endframe, AiList[Offset + 1 + 6], AiList[Offset + 1 + 7]);
}
printf(")\n");
Offset += AI_PlayAnimation_LENGTH;
break;
}
case AI_IFPlayingAnimation: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFPlayingAnimation_LENGTH;
break;
}
case AI_PointAtBond: // /*NONE*/
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_PointAtBond_LENGTH;
break;
}
case AI_LookSurprised: // /*NONE*/
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_LookSurprised_LENGTH;
break;
}
case AI_IFImOnPatrolOrStopped: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFImOnPatrolOrStopped_LENGTH;
break;
}
case AI_IFChrDyingOrDead: // BYTE(CHR_NUM), BYTE(GOTOLABEL)
{
signed char chr = AiList[Offset + 1];
if (chr == CHR_SELF)
{
printf("%sIFImDyingOrDead(", tabs);
}
else
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,", chr);
}
printf("lbl%d", AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFChrDyingOrDead_LENGTH;
break;
}
case AI_IFChrDoesNotExist: // BYTE(CHR_NUM), BYTE(GOTOLABEL)
{
signed char chr = AiList[Offset + 1];
if (chr == CHR_SELF)
{
printf("%sIFIDoNotExist(", tabs);
}
else
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,", chr);
}
printf("lbl%d", AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFChrDoesNotExist_LENGTH;
break;
}
case AI_IFISeeBond: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFISeeBond_LENGTH;
break;
}
case AI_TRYSidestepping: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_TRYSidestepping_LENGTH;
break;
}
case AI_TRYSideHopping: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_TRYSideHopping_LENGTH;
break;
}
case AI_TRYSideRunning: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_TRYSideRunning_LENGTH;
break;
}
case AI_TRYFiringWalk: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_TRYFiringWalk_LENGTH;
break;
}
case AI_TRYFiringRun: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_TRYFiringRun_LENGTH;
break;
}
case AI_TRYFiringRoll: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_TRYFiringRoll_LENGTH;
break;
}
case AI_TRYFireOrAimAtTarget: // DBYTE(BITFIELD), DBYTE(TARGET), BYTE(GOTOLABEL)
{
int targetid = CharArrayTo16(AiList, Offset + 1 + 2);
int targettype = CharArrayTo16(AiList, Offset + 1 + 0);
if (targettype == 1)
{
printf("%sTRYFireAtBond(", tabs);
printf("lbl%d", AiList[Offset + 5]);
}
else if (targettype == 4)
{
printf("%sTRYFireAtPad(", tabs);
printf("lbl%d", AiList[Offset + 5]);
}
else if (targettype == 33)
{
printf("%sTRYAimAtBond(", tabs);
printf("lbl%d", AiList[Offset + 5]);
}
else if (targettype == 36)
{
printf("%sTRYAimAtPad(", tabs);
printf("lbl%d", AiList[Offset + 5]);
}
else
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,lbl%d", targettype, targetid, AiList[Offset + 5]);
}
printf(")\n");
Offset += AI_TRYFireOrAimAtTarget_LENGTH;
break;
}
case AI_TRYFireOrAimAtTargetKneel: // DBYTE(BITFIELD), DBYTE(TARGET), BYTE(GOTOLABEL)
{
int targetid = CharArrayTo16(AiList, Offset + 1 + 2);
int targettype = CharArrayTo16(AiList, Offset + 1 + 0);
if (targettype == 1)
{
printf("%sTRYFireAtBondKneeling(", tabs);
printf("lbl%d", AiList[Offset + 5]);
}
else if (targettype == 4)
{
printf("%sTRYFireAtPadKneeling(", tabs);
printf("lbl%d", AiList[Offset + 5]);
}
else if (targettype == 33)
{
printf("%sTRYAimAtBondKneeling(", tabs);
printf("lbl%d", AiList[Offset + 5]);
}
else if (targettype == 36)
{
printf("%sTRYAimAtPadKneeling(", tabs);
printf("lbl%d", AiList[Offset + 5]);
}
else
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,lbl%d", targettype, targetid, AiList[Offset + 5]);
}
printf(")\n");
Offset += AI_TRYFireOrAimAtTargetKneel_LENGTH;
break;
}
case AI_IFImFiringAndLockedForward: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFImFiringAndLockedForward_LENGTH;
break;
}
case AI_IFImFiring: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFImFiring_LENGTH;
break;
}
case AI_TRYFireOrAimAtTargetUpdate: // DBYTE(BITFIELD), DBYTE(TARGET), BYTE(GOTOLABEL)
{
int targetid = CharArrayTo16(AiList, Offset + 1 + 2);
int targettype = CharArrayTo16(AiList, Offset + 1 + 0);
if (targettype == 1)
{
printf("%sTRYFireAtBondUpdate(", tabs);
printf("lbl%d", AiList[Offset + 5]);
}
else if (targettype == 4)
{
printf("%sTRYFireAtPadUpdate(", tabs);
printf("lbl%d", AiList[Offset + 5]);
}
else if (targettype == 33)
{
printf("%sTRYAimAtBondUpdate(", tabs);
printf("lbl%d", AiList[Offset + 5]);
}
else if (targettype == 36)
{
printf("%sTRYAimAtPadUpdate(", tabs);
printf("lbl%d", AiList[Offset + 5]);
}
else
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,lbl%d", targettype, targetid, AiList[Offset + 5]);
}
printf(")\n");
Offset += AI_TRYFireOrAimAtTargetUpdate_LENGTH;
break;
}
case AI_TRYFacingTarget: // DBYTE(BITFIELD),DBYTE(TARGET),BYTE(GOTOLABEL)
{
int targetid = CharArrayTo16(AiList, Offset + 1 + 2);
int targettype = CharArrayTo16(AiList, Offset + 1 + 0);
if (targettype == 1)
{
printf("%sTRYFacingBond(", tabs);
printf("lbl%d", AiList[Offset + 5]);
}
else if (targettype == 4)
{
printf("%sTRYFacingPad(", tabs);
printf("lbl%d", AiList[Offset + 5]);
}
else
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,lbl%d", targettype, targetid, AiList[Offset + 5]);
}
printf(")\n");
Offset += AI_TRYFacingTarget_LENGTH;
break;
}
case AI_HitChrWithItem: // BYTE(CHR_NUM),BYTE(PART_NUM),BYTE(ITEM_NUM)
{
if (AiList[Offset + 1] == CHR_SELF)
{
printf("%sHitMeWithItem(", tabs);
printf("%d,%d", AiList[Offset + 2], AiList[Offset + 1 + 2]);
}
else
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,%d", AiList[Offset + 1], AiList[Offset + 1 + 1], AiList[Offset + 1 + 2]);
}
printf(")\n");
Offset += AI_HitChrWithItem_LENGTH;
break;
}
case AI_ChrHitChr: // BYTE(CHR_NUM),BYTE(CHR_NUM_TARGET),BYTE(PART_NUM)
{
if ((signed char)AiList[Offset + 1] == CHR_SELF)
{
printf("%sIHitChr(", tabs);
printf("%d,%d", AiList[Offset + 2], AiList[Offset + 1 + 2]);
}
else if ((signed char)AiList[Offset + 2] == CHR_SELF)
{
printf("%sChrHitMe(", tabs);
printf("%d,%d", AiList[Offset + 1], AiList[Offset + 1 + 2]);
}
else
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,%d", AiList[Offset + 1], AiList[Offset + 1 + 1], AiList[Offset + 1 + 2]);
}
printf(")\n");
Offset += AI_ChrHitChr_LENGTH;
break;
}
case AI_TRYThrowingGrenade: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_TRYThrowingGrenade_LENGTH;
break;
}
case AI_TRYDroppingItem: // DBYTE(PROP_NUM),BYTE(ITEM_NUM),BYTE(GOTOLABEL)
{
unsigned short modelnum = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,lbl%d", modelnum, AiList[Offset + 1 + 2], AiList[Offset + 1 + 3]);
printf(")\n");
Offset += AI_TRYDroppingItem_LENGTH;
break;
}
case AI_Surrender: // /*NONE*/
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_Surrender_LENGTH;
break;
}
case AI_RemoveMe: // /*NONE*/
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_RemoveMe_LENGTH;
break;
}
case AI_ChrRemoveInstant: // BYTE(CHR_NUM)
{
if ((signed char)AiList[Offset + 1] == CHR_SELF)
{
printf("%sRemoveMeInstantly(", tabs);
}
else
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
}
printf(")\n");
Offset += AI_ChrRemoveInstant_LENGTH;
break;
}
case AI_TRYTriggeringAlarmAtPad: // DBYTE(PAD),BYTE(GOTOLABEL)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
if (isNotBoundPad(pad))
{
printf("%d,", pad);
}
else
{
printf("setBoundPadNum(%d),", getBoundPadNum(pad));
}
printf("lbl%d", AiList[Offset + 3]);
printf(")\n");
Offset += AI_TRYTriggeringAlarmAtPad_LENGTH;
break;
}
case AI_AlarmOn:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_AlarmOn_LENGTH;
break;
}
case AI_AlarmOff:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_AlarmOff_LENGTH;
break;
}
case AI_TRYRunFromBond: // BYTE(GOTOLABEL)
{ // run from bond
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_TRYRunFromBond_LENGTH;
break;
}
case AI_TRYRunToBond: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_TRYRunToBond_LENGTH;
break;
}
case AI_TRYWalkToBond: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_TRYWalkToBond_LENGTH;
break;
}
case AI_TRYSprintToBond: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_TRYSprintToBond_LENGTH;
break;
}
case AI_TRYFindCover: // BYTE(GOTOLABEL)
{ // Find Cover
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_TRYFindCover_LENGTH;
break;
}
case AI_TRYRunToChr: // BYTE(CHR_NUM), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_TRYRunToChr_LENGTH;
break;
}
case AI_TRYWalkToChr: // BYTE(CHR_NUM), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_TRYWalkToChr_LENGTH;
break;
}
case AI_TRYSprintToChr: // BYTE(CHR_NUM), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_TRYSprintToChr_LENGTH;
break;
}
case AI_SetNewRandom:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_SetNewRandom_LENGTH;
break;
}
case AI_IFRandomLessThan: // BYTE(BYTE), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFRandomLessThan_LENGTH;
break;
}
case AI_IFRandomGreaterThan: // BYTE(BYTE), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFRandomGreaterThan_LENGTH;
break;
}
case AI_RunToPad: // DBYTE(PAD)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
if (isNotBoundPad(pad))
{
printf("%d", pad);
}
else
{
printf("setBoundPadNum(%d)", getBoundPadNum(pad));
}
printf(")\n");
Offset += AI_RunToPad_LENGTH;
break;
}
case AI_RunToPadPreset: // /*NONE*/
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_RunToPadPreset_LENGTH;
break;
}
case AI_WalkToPad: // DBYTE(PAD)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
if (isNotBoundPad(pad))
{
printf("%d", pad);
}
else
{
printf("setBoundPadNum(%d)", getBoundPadNum(pad));
}
printf(")\n");
Offset += AI_WalkToPad_LENGTH;
break;
}
case AI_SprintToPad: // DBYTE(PAD)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
if (isNotBoundPad(pad))
{
printf("%d", pad);
}
else
{
printf("setBoundPadNum(%d)", getBoundPadNum(pad));
}
printf(")\n");
Offset += AI_SprintToPad_LENGTH;
break;
}
case AI_StartPatrol: // BYTE(PATH_NUM)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_StartPatrol_LENGTH;
break;
}
case AI_IFICanHearAlarm: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFICanHearAlarm_LENGTH;
break;
}
case AI_IFAlarmIsOn: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFAlarmIsOn_LENGTH;
break;
}
case AI_IFGasIsLeaking: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFGasIsLeaking_LENGTH;
break;
}
case AI_IFIHeardBond: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFIHeardBond_LENGTH;
break;
}
case AI_IFISeeSomeoneShot: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFISeeSomeoneShot_LENGTH;
break;
}
case AI_IFISeeSomeoneDie: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFISeeSomeoneDie_LENGTH;
break;
}
case AI_IFICouldSeeBond: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFICouldSeeBond_LENGTH;
break;
}
case AI_IFICouldSeeBondsStan: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFICouldSeeBondsStan_LENGTH;
break;
}
case AI_IFIWasShotRecently: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFIWasShotRecently_LENGTH;
break;
}
case AI_IFIHeardBondRecently: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFIHeardBondRecently_LENGTH;
break;
}
case AI_IFImInRoomWithChr: // BYTE(CHR_NUM), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFImInRoomWithChr_LENGTH;
break;
}
case AI_IFIveNotBeenSeen:// BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFIveNotBeenSeen_LENGTH;
break;
}
case AI_IFImOnScreen:// BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFImOnScreen_LENGTH;
break;
}
case AI_IFMyRoomIsOnScreen:// BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFMyRoomIsOnScreen_LENGTH;
break;
}
case AI_IFRoomWithPadIsOnScreen: // DBYTE(PAD), BYTE(GOTOLABEL)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
if (isNotBoundPad(pad))
{
printf("%d,", pad);
}
else
{
printf("setBoundPadNum(%d),", getBoundPadNum(pad));
}
printf("lbl%d)\n", AiList[Offset + 3]);
Offset += AI_IFRoomWithPadIsOnScreen_LENGTH;
break;
}
case AI_IFImTargetedByBond: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFImTargetedByBond_LENGTH;
break;
}
case AI_IFBondMissedMe: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFBondMissedMe_LENGTH;
break;
}
case AI_IFMyAngleToBondLessThan: // BYTE(ANGLE), BYTE(GOTOLABEL)
{
printf("%s%sDeg(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,lbl%d", RadToDeg(ByteToRadian((AiList[Offset + 1 + 0]))), AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFMyAngleToBondLessThan_LENGTH;
break;
}
case AI_IFMyAngleToBondGreaterThan: // BYTE(ANGLE), BYTE(GOTOLABEL)
{
printf("%s%sDeg(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,lbl%d", RadToDeg(ByteToRadian((AiList[Offset + 1 + 0]))), AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFMyAngleToBondGreaterThan_LENGTH;
break;
}
case AI_IFMyAngleFromBondLessThan: // BYTE(ANGLE), BYTE(GOTOLABEL)
{
printf("%s%sDeg(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,lbl%d", RadToDeg(ByteToRadian((AiList[Offset + 1 + 0]))), AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFMyAngleFromBondLessThan_LENGTH;
break;
}
case AI_IFMyAngleFromBondGreaterThan: // BYTE(ANGLE), BYTE(GOTOLABEL)
{
printf("%s%sDeg(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,lbl%d", RadToDeg(ByteToRadian((AiList[Offset + 1 + 0]))), AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFMyAngleFromBondGreaterThan_LENGTH;
break;
}
case AI_IFMyDistanceToBondLessThanDecimeter: // DBYTE(DISTANCE), BYTE(GOTOLABEL)
{
float distance = CharArrayTo16(AiList, Offset + 1 + 0) * 10.0f;
printf("%s%s(", tabs, "IFMyDistanceToBondLessThanMeter");
printf("%f,lbl%d", distance / 100, AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFMyDistanceToBondLessThanDecimeter_LENGTH;
break;
}
case AI_IFMyDistanceToBondGreaterThanDecimeter: // DBYTE(DISTANCE), BYTE(GOTOLABEL)
{
float distance = CharArrayTo16(AiList, Offset + 1 + 0) * 10.0f;
printf("%s%s(", tabs, "IFMyDistanceToBondGreaterThanMeter");
printf("%f,lbl%d", distance / 100, AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFMyDistanceToBondGreaterThanDecimeter_LENGTH;
break;
}
case AI_IFChrDistanceToPadLessThanDecimeter: // BYTE(CHR_NUM), DBYTE(DISTANCE), DBYTE(PAD), BYTE(GOTOLABEL)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 3);
float value = CharArrayTo16(AiList, Offset + 1 + 1) * 10.0f;
if ((signed char)AiList[Offset + 1 + 0] == CHR_SELF)
{
printf("%sIFMyDistanceToPadLessThanMeter(", tabs);
printf("%f,", value / 100);
}
else
{
printf("%sIFChrDistanceToPadLessThanMeter(", tabs);
printf("%d,%f,", AiList[Offset + 1 + 0], value / 100);
}
if (isNotBoundPad(pad))
{
printf("%d,", pad);
}
else
{
printf("setBoundPadNum(%d),", getBoundPadNum(pad));
}
printf("lbl%d", AiList[Offset + 6]);
printf(")\n");
Offset += AI_IFChrDistanceToPadLessThanDecimeter_LENGTH;
break;
}
case AI_IFChrDistanceToPadGreaterThanDecimeter: // BYTE(CHR_NUM), DBYTE(DISTANCE), DBYTE(PAD), BYTE(GOTOLABEL)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 3);
float value = CharArrayTo16(AiList, Offset + 1 + 1) * 10.0f;
if ((signed char)AiList[Offset + 1 + 0] == CHR_SELF)
{
printf("%sIFMyDistanceToPadGreaterThanMeter(", tabs);
printf("%f,", value / 100);
}
else
{
printf("%sIFChrDistanceToPadGreaterThanMeter(", tabs);
printf("%d,%f,", AiList[Offset + 1 + 0], value / 100);
}
if (isNotBoundPad(pad))
{
printf("%d,", pad);
}
else
{
printf("setBoundPadNum(%d),", getBoundPadNum(pad));
}
printf("lbl%d", AiList[Offset + 6]);
printf(")\n");
Offset += AI_IFChrDistanceToPadGreaterThanDecimeter_LENGTH;
break;
}
case AI_IFMyDistanceToChrLessThanDecimeter: // DBYTE(DISTANCE), BYTE(CHR_NUM), BYTE(GOTOLABEL)
{
float cutoff = CharArrayTo16(AiList, Offset + 1 + 0) * 10.0f;
printf("%s%s(", tabs, "AIFMyDistanceToChrLessThanMeter");
printf("%f,%d,lbl%d", cutoff / 100, AiList[Offset + 3], AiList[Offset + 4]);
printf(")\n");
Offset += AI_IFMyDistanceToChrLessThanDecimeter_LENGTH;
break;
}
case AI_IFMyDistanceToChrGreaterThanDecimeter: // DBYTE(DISTANCE), BYTE(CHR_NUM), BYTE(GOTOLABEL)
{
float cutoff = CharArrayTo16(AiList, Offset + 1 + 0) * 10.0f;
printf("%s%s(", tabs, "AIFMyDistanceToChrGreaterThanMeter");
printf("%f,%d,lbl%d", cutoff / 100, AiList[Offset + 3], AiList[Offset + 4]);
printf(")\n");
Offset += AI_IFMyDistanceToChrGreaterThanDecimeter_LENGTH;
break;
}
case AI_TRYSettingMyPresetToChrWithinDistanceDecimeter: // DBYTE(DISTANCE), BYTE(GOTOLABEL)
{
float distance = CharArrayTo16(AiList, Offset + 1 + 0) * 10.0f;
printf("%s%s(", tabs, "TRYSettingMyPresetToChrWithinDistanceMeter");
printf("%f,lbl%d", distance / 100, AiList[Offset + 3]);
printf(")\n");
Offset += AI_TRYSettingMyPresetToChrWithinDistanceDecimeter_LENGTH;
break;
}
case AI_IFBondDistanceToPadLessThanDecimeter: // DBYTE(DISTANCE), DBYTE(PAD), BYTE(GOTOLABEL)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 2);
float value = CharArrayTo16(AiList, Offset + 1 + 0) * 10.0f;
printf("%s%s(", tabs, "IFBondDistanceToPadLessThanMeter");
printf("%f,", value / 100);
if (isNotBoundPad(pad))
{
printf("%d,", pad);
}
else
{
printf("setBoundPadNum(%d),", getBoundPadNum(pad));
}
printf("lbl%d)\n", AiList[Offset + 5]);
Offset += AI_IFBondDistanceToPadLessThanDecimeter_LENGTH;
break;
}
case AI_IFBondDistanceToPadGreaterThanDecimeter: // DBYTE(DISTANCE), DBYTE(PAD), BYTE(GOTOLABEL)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 2);
float value = CharArrayTo16(AiList, Offset + 1 + 0) * 10.0f;
printf("%s%s(", tabs, "IFBondDistanceToPadGreaterThanMeter");
printf("%f,", value / 100);
if (isNotBoundPad(pad))
{
printf("%d,", pad);
}
else
{
printf("setBoundPadNum(%d),", getBoundPadNum(pad));
}
printf("lbl%d)\n", AiList[Offset + 5]);
Offset += AI_IFBondDistanceToPadGreaterThanDecimeter_LENGTH;
break;
}
case AI_IFChrInRoomWithPad: // BYTE(CHR_NUM), DBYTE(PAD), BYTE(GOTOLABEL)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,", AiList[Offset + 1 + 0]);
if (isNotBoundPad(pad))
{
printf("%d,", pad);
}
else
{
printf("setBoundPadNum(%d),", getBoundPadNum(pad));
}
printf("lbl%d)\n", AiList[Offset + 4]);
Offset += AI_IFChrInRoomWithPad_LENGTH;
break;
}
case AI_IFBondInRoomWithPad: // DBYTE(PAD), BYTE(GOTOLABEL)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
if (isNotBoundPad(pad))
{
printf("%d,", pad);
}
else
{
printf("setBoundPadNum(%d),", getBoundPadNum(pad));
}
printf("lbl%d)\n", AiList[Offset + 3]);
Offset += AI_IFBondInRoomWithPad_LENGTH;
break;
}
case AI_IFBondCollectedObject: // BYTE(OBJECT_TAG), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFBondCollectedObject_LENGTH;
break;
}
case AI_IFItemIsStationaryWithinLevel: // BYTE(ITEM_NUM), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFItemIsStationaryWithinLevel_LENGTH;
break;
}
case AI_IFItemIsAttachedToObject: // BYTE(ITEM_NUM), BYTE(OBJECT_TAG), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2], AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFItemIsAttachedToObject_LENGTH;
break;
}
case AI_IFBondHasItemEquipped: // BYTE(ITEM_NUM), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFBondHasItemEquipped_LENGTH;
break;
}
case AI_IFObjectExists: // BYTE(OBJECT_TAG), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFObjectExists_LENGTH;
break;
}
case AI_IFObjectNotDestroyed:// BYTE(OBJECT_TAG), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFObjectNotDestroyed_LENGTH;
break;
}
case AI_IFObjectWasActivated:// BYTE(OBJECT_TAG), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFObjectWasActivated_LENGTH;
break;
}
case AI_IFBondUsedGadgetOnObject:// BYTE(OBJECT_TAG), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFBondUsedGadgetOnObject_LENGTH;
break;
}
case AI_ActivateObject: // BYTE(OBJECT_TAG)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_ActivateObject_LENGTH;
break;
}
case AI_DestroyObject: // BYTE(OBJECT_TAG)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_DestroyObject_LENGTH;
break;
}
case AI_DropObject: // BYTE(OBJECT_TAG)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_DropObject_LENGTH;
break;
}
case AI_ChrDropAllConcealedItems: // BYTE(CHR_NUM)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_ChrDropAllConcealedItems_LENGTH;
break;
}
case AI_ChrDropAllHeldItems: // BYTE(CHR_NUM)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_ChrDropAllHeldItems_LENGTH;
break;
}
case AI_BondCollectObject: // BYTE(OBJECT_TAG)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_BondCollectObject_LENGTH;
break;
}
case AI_ChrEquipObject: // BYTE(OBJECT_TAG), BYTE(CHR_NUM)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_ChrEquipObject_LENGTH;
break;
}
case AI_MoveObject: // BYTE(OBJECT_TAG), DBYTE(PAD)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,", AiList[Offset + 1]);
if (isNotBoundPad(pad))
{
printf("%d", pad);
}
else
{
printf("setBoundPadNum(%d)", getBoundPadNum(pad));
}
Offset += AI_MoveObject_LENGTH;
break;
}
case AI_DoorOpen: // BYTE(OBJECT_TAG)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_DoorOpen_LENGTH;
break;
}
case AI_DoorClose: // BYTE(OBJECT_TAG)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_DoorClose_LENGTH;
break;
}
case AI_IFDoorStateEqual: // BYTE(OBJECT_TAG), BYTE(DOOR_STATE), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%s,lbl%d", AiList[Offset + 1], DOORSTATE_ToString[AiList[Offset + 2] >> 1], AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFDoorStateEqual_LENGTH;
break;
}
case AI_IFDoorHasBeenOpenedBefore: // BYTE(OBJECT_TAG), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFDoorHasBeenOpenedBefore_LENGTH;
break;
}
case AI_DoorSetLock: // BYTE(OBJECT_TAG), BYTE(LOCK_FLAG)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_DoorSetLock_LENGTH;
break;
}
case AI_DoorUnsetLock: // BYTE(OBJECT_TAG), BYTE(LOCK_FLAG)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_DoorUnsetLock_LENGTH;
break;
}
case AI_IFDoorLockEqual: // BYTE(OBJECT_TAG), BYTE(LOCK_FLAG), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,%d", AiList[Offset + 1], AiList[Offset + 2], AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFDoorLockEqual_LENGTH;
break;
}
case AI_IFObjectiveNumComplete: // BYTE(OBJ_NUM), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFObjectiveNumComplete_LENGTH;
break;
}
case AI_TRYUnknown6e: // BYTE(UNKNOWN_FLAG), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_TRYUnknown6e_LENGTH;
break;
}
case AI_TRYUnknown6f: // BYTE(UNKNOWN_FLAG), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_TRYUnknown6f_LENGTH;
break;
}
case AI_IFMyNumArghsLessThan: // BYTE(HIT_NUM), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFMyNumArghsLessThan_LENGTH;
break;
}
case AI_IFMyNumArghsGreaterThan: // BYTE(HIT_NUM), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFMyNumArghsGreaterThan_LENGTH;
break;
}
case AI_IFMyNumCloseArghsLessThan: // BYTE(MISSED_NUM), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFMyNumCloseArghsLessThan_LENGTH;
break;
}
case AI_IFMyNumCloseArghsGreaterThan: // BYTE(MISSED_NUM), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFMyNumCloseArghsGreaterThan_LENGTH;
break;
}
case AI_IFChrHealthLessThan: // BYTE(CHR_NUM), BYTE(HEALTH), BYTE(GOTOLABEL)
{
float value = (AiList[Offset + 1 + 1]) * 0.1f;
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%f,lbl%d", AiList[Offset + 1], value * 10, AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFChrHealthLessThan_LENGTH;
break;
}
case AI_IFChrHealthGreaterThan: // BYTE(CHR_NUM), BYTE(HEALTH), BYTE(GOTOLABEL)
{
float value = (AiList[Offset + 1 + 1]) * 0.1f;
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%f,lbl%d", AiList[Offset + 1], value * 10, AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFChrHealthGreaterThan_LENGTH;
break;
}
case AI_IFChrWasDamagedSinceLastCheck: // BYTE(CHR_NUM), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFChrWasDamagedSinceLastCheck_LENGTH;
break;
}
case AI_IFBondHealthLessThan: // BYTE(HEALTH), BYTE(GOTOLABEL)
{
float val = (AiList[Offset + 1 + 0]) / 255.0f;
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,lbl%d", val * 255, AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFBondHealthLessThan_LENGTH;
break;
}
case AI_IFBondHealthGreaterThan: // BYTE(HEALTH), BYTE(GOTOLABEL)
{
float val = (AiList[Offset + 1 + 0]) / 255.0f;
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,lbl%d", val * 255, AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFBondHealthGreaterThan_LENGTH;
break;
}
case AI_IFGameDifficultyLessThan: // BYTE(DIFICULTY_ID), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFGameDifficultyLessThan_LENGTH;
break;
}
case AI_IFGameDifficultyGreaterThan: // BYTE(DIFICULTY_ID), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFGameDifficultyGreaterThan_LENGTH;
break;
}
case AI_IFMissionTimeLessThan: // DBYTE(SECONDS), BYTE(GOTOLABEL)
{
float target = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,lbl%d", target, AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFMissionTimeLessThan_LENGTH;
break;
}
case AI_IFMissionTimeGreaterThan: // DBYTE(SECONDS), BYTE(GOTOLABEL)
{
float target = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,lbl%d", target, AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFMissionTimeGreaterThan_LENGTH;
break;
}
case AI_IFSystemPowerTimeLessThan: // DBYTE(MINUTES), BYTE(GOTOLABEL)
{
float target = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,%d", target, AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFSystemPowerTimeLessThan_LENGTH;
break;
}
case AI_IFSystemPowerTimeGreaterThan: // DBYTE(MINUTES), BYTE(GOTOLABEL)
{
float target = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,lbl%d", target, AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFSystemPowerTimeGreaterThan_LENGTH;
break;
}
case AI_IFLevelIdLessThan: // BYTE(LEVEL_ID), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFLevelIdLessThan_LENGTH;
break;
}
case AI_IFLevelIdGreaterThan: // BYTE(LEVEL_ID), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFLevelIdGreaterThan_LENGTH;
break;
}
case AI_SetMyMorale:// BYTE(CHRBYTE)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_SetMyMorale_LENGTH;
break;
}
case AI_AddToMyMorale:// BYTE(CHRBYTE)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_AddToMyMorale_LENGTH;
break;
}
case AI_SubtractFromMyMorale:// BYTE(CHRBYTE)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_SubtractFromMyMorale_LENGTH;
break;
}
case AI_IFMyMoraleLessThan: // BYTE(CHRBYTE), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFMyMoraleLessThan_LENGTH;
break;
}
case AI_IFMyMoraleLessThanRandom:// BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFMyMoraleLessThanRandom_LENGTH;
break;
}
case AI_SetMyAlertness: // BYTE(CHRBYTE)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_SetMyAlertness_LENGTH;
break;
}
case AI_AddToMyAlertness: // BYTE(CHRBYTE)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_AddToMyAlertness_LENGTH;
break;
}
case AI_SubtractFromMyAlertness: // BYTE(CHRBYTE)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_SubtractFromMyAlertness_LENGTH;
break;
}
case AI_IFMyAlertnessLessThan: // BYTE(CHRBYTE), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFMyAlertnessLessThan_LENGTH;
break;
}
case AI_IFMyAlertnessLessThanRandom: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFMyAlertnessLessThanRandom_LENGTH;
break;
}
case AI_SetMyHearingScale: // DBYTE(HEARING_SCALE)
{
float distance = CharArrayTo16(AiList, Offset + 1 + 0) / 1000.0f;
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f", distance * 1000);
printf(")\n");
Offset += AI_SetMyHearingScale_LENGTH;
break;
}
case AI_SetMyVisionRange:// BYTE(VISION_RANGE)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_SetMyVisionRange_LENGTH;
break;
}
case AI_SetMyGrenadeProbability: // BYTE(GRENADE_PROB)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_SetMyGrenadeProbability_LENGTH;
break;
}
case AI_SetMyChrNum: // BYTE(CHR_NUM)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_SetMyChrNum_LENGTH;
break;
}
case AI_SetMyHealthTotal: // DBYTE(HEALTH)
{
float amount = CharArrayTo16(AiList, Offset + 1 + 0) * 0.1f;
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f", amount * 10);
printf(")\n");
Offset += AI_SetMyHealthTotal_LENGTH;
break;
}
case AI_SetMyArmour: // DBYTE(AMOUNT)
{
float amount = CharArrayTo16(AiList, Offset + 1 + 0) * 0.1f; /*if (cheatIsActive(CHEAT_ENEMYSHIELDS)) { amount = amount < 8 ? 8 : amount; } */
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f", amount * 10);
printf(")\n");
Offset += AI_SetMyArmour_LENGTH;
break;
}
case AI_SetMySpeedRating: // BYTE(SPEED_RATING)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_SetMySpeedRating_LENGTH;
break;
}
case AI_SetMyArghRating: // BYTE(ARGH_RATING)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_SetMyArghRating_LENGTH;
break;
}
case AI_SetMyAccuracyRating: // BYTE(ACCURACY_RATING)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_SetMyAccuracyRating_LENGTH;
break;
}
case AI_SetMyFlags2:// BYTE(BITS)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("0x%x", AiList[Offset + 1]);
printf(")\n");
Offset += AI_SetMyFlags2_LENGTH;
break;
}
case AI_UnsetMyFlags2:// BYTE(BITS)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("0x%x", AiList[Offset + 1]);
printf(")\n");
Offset += AI_UnsetMyFlags2_LENGTH;
break;
}
case AI_IFMyFlags2Has:// BYTE(BITS) BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("0x%x,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFMyFlags2Has_LENGTH;
break;
}
case AI_SetChrBitfield:// BYTE(CHR_NUM), BYTE(BITS)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,0x%x", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_SetChrBitfield_LENGTH;
break;
}
case AI_UnsetChrBitfield:// BYTE(CHR_NUM), BYTE(BITS)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,0x%x", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_UnsetChrBitfield_LENGTH;
break;
}
case AI_IFChrBitfieldHas: // BYTE(CHR_NUM), BYTE(BITS), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,0x%x,lbl%d", AiList[Offset + 1], AiList[Offset + 2], AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFChrBitfieldHas_LENGTH;
break;
}
case AI_SetObjectiveBitfield: // QBYTE(BITFIELD)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("0x%x", flags);
printf(")\n");
Offset += AI_SetObjectiveBitfield_LENGTH;
break;
}
case AI_UnsetObjectiveBitfield: // QBYTE(BITFIELD)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("0x%x", flags);
printf(")\n");
Offset += AI_UnsetObjectiveBitfield_LENGTH;
break;
}
case AI_IFObjectiveBitfieldHas:// QBYTE(BITS), BYTE(GOTOLABEL)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("0x%x,lbl%d", flags, AiList[Offset + 5]);
printf(")\n");
Offset += AI_IFObjectiveBitfieldHas_LENGTH;
break;
}
case AI_SetMychrflags:// QBYTE(CHRFLAGS)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("0x%x", flags);
printf(")\n");
Offset += AI_SetMychrflags_LENGTH;
break;
}
case AI_UnsetMychrflags:// QBYTE(CHRFLAGS)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("0x%x", flags);
printf(")\n");
Offset += AI_UnsetMychrflags_LENGTH;
break;
}
case AI_IFMychrflagsHas: // QBYTE(CHRFLAGS), BYTE(GOTOLABEL)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("0x%x,lbl%d", flags, AiList[Offset + 5]);
printf(")\n");
Offset += AI_IFMychrflagsHas_LENGTH;
break;
}
case AI_SetChrchrflags: // BYTE(CHR_NUM), QBYTE(CHRFLAGS)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,0x%x", AiList[Offset + 1], flags);
printf(")\n");
Offset += AI_SetChrchrflags_LENGTH;
break;
}
case AI_UnsetChrchrflags: // BYTE(CHR_NUM), QBYTE(CHRFLAGS)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,0x%x", AiList[Offset + 1], flags);
printf(")\n");
Offset += AI_UnsetChrchrflags_LENGTH;
break;
}
case AI_IFChrchrflagsHas: // BYTE(CHR_NUM), QBYTE(CHRFLAGS), BYTE(GOTOLABEL)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,0x%x,lbl%d", AiList[Offset + 1], flags, AiList[Offset + 6]);
printf(")\n");
Offset += AI_IFChrchrflagsHas_LENGTH;
break;
}
case AI_SetObjectFlags: // BYTE(OBJECT_TAG), QBYTE(BITFIELD)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,0x%x", AiList[Offset + 1], flags);
printf(")\n");
Offset += AI_SetObjectFlags_LENGTH;
break;
}
case AI_UnsetObjectFlags: // BYTE(OBJECT_TAG), QBYTE(BITFIELD)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,0x%x", AiList[Offset + 1], flags);
printf(")\n");
Offset += AI_UnsetObjectFlags_LENGTH;
break;
}
case AI_IFObjectFlagsHas: // BYTE(OBJECT_TAG), QBYTE(BITS), BYTE(GOTOLABEL)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,0x%x,lbl%d", AiList[Offset + 1], flags, AiList[Offset + 6]);
printf(")\n");
Offset += AI_IFObjectFlagsHas_LENGTH;
break;
}
case AI_SetObjectFlags2: // BYTE(OBJECT_TAG), QBYTE(BITS)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,0x%x", AiList[Offset + 1], flags);
printf(")\n");
Offset += AI_SetObjectFlags2_LENGTH;
break;
}
case AI_UnsetObjectFlags2: // BYTE(OBJECT_TAG), QBYTE(BITS)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,0x%x", AiList[Offset + 1], flags);
printf(")\n");
Offset += AI_UnsetObjectFlags2_LENGTH;
break;
}
case AI_IFObjectFlags2Has: // BYTE(OBJECT_TAG), QBYTE(BITFIELD), BYTE(GOTOLABEL)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,0x%x,lbl%d", AiList[Offset + 1], flags, AiList[Offset + 6]);
printf(")\n");
Offset += AI_IFObjectFlags2Has_LENGTH;
break;
}
case AI_SetMyChrPreset: // BYTE(CHR_PRESET)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_SetMyChrPreset_LENGTH;
break;
}
case AI_SetChrChrPreset: // BYTE(CHR_NUM), BYTE(CHR_PRESET)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_SetChrChrPreset_LENGTH;
break;
}
case AI_SetMyPadPreset: // DBYTE(PAD_PRESET)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
if (isNotBoundPad(pad))
{
printf("%d", pad);
}
else
{
printf("setBoundPadNum(%d)", getBoundPadNum(pad));
}
printf(")\n");
Offset += AI_SetMyPadPreset_LENGTH;
break;
}
case AI_SetChrPadPreset: // BYTE(CHR_NUM), DBYTE(PAD_PRESET)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 1);
printf("%s(%d,", AI_CMD_ToString[AiList[Offset]], AiList[Offset + 1]);
if (isNotBoundPad(pad))
{
printf("%d", pad);
}
else
{
printf("setBoundPadNum(%d)", getBoundPadNum(pad));
}
printf(")\n");
Offset += AI_SetChrPadPreset_LENGTH;
break;
}
case AI_PRINT:
{
int j = 1;
printf("%sPRINT(\"", tabs);
for (; AiList[Offset + j] != 0; j++)
{
if (AiList[Offset + j] == '\n')
{
printf("\\n");
}
else
{
printf("%c", AiList[Offset + j]);
}
}
Offset += j + 1;
printf("\")\n");
break;
}
case AI_MyTimerStart:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_MyTimerStart_LENGTH;
break;
}
case AI_MyTimerReset:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_MyTimerReset_LENGTH;
break;
}
case AI_MyTimerPause:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_MyTimerPause_LENGTH;
break;
}
case AI_MyTimerResume:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_MyTimerResume_LENGTH;
break;
}
case AI_IFMyTimerIsNotRunning: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFMyTimerIsNotRunning_LENGTH;
break;
}
case AI_IFMyTimerLessThanTicks: // TBYTE(TICKS), BYTE(GOTOLABEL)
{
float valf = ((unsigned)CharArrayTo24(AiList, Offset + 1 + 0));
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,lbl%d", valf, AiList[Offset + 4]);
printf(")\n");
Offset += AI_IFMyTimerLessThanTicks_LENGTH;
break;
}
case AI_IFMyTimerGreaterThanTicks: // TBYTE(TICKS), BYTE(GOTOLABEL)
{
float valf = ((unsigned)CharArrayTo24(AiList, Offset + 1 + 0));
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,lbl%d", valf, AiList[Offset + 4]);
printf(")\n");
Offset += AI_IFMyTimerGreaterThanTicks_LENGTH;
break;
}
case AI_HudCountdownShow:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_HudCountdownShow_LENGTH;
break;
}
case AI_HudCountdownHide:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_HudCountdownHide_LENGTH;
break;
}
case AI_HudCountdownSet: // DBYTE(SECONDS)
{
float seconds = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f", seconds);
printf(")\n");
Offset += AI_HudCountdownSet_LENGTH;
break;
}
case AI_HudCountdownStop:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_HudCountdownStop_LENGTH;
break;
}
case AI_HudCountdownStart:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_HudCountdownStart_LENGTH;
break;
}
case AI_IFHudCountdownIsNotRunning: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFHudCountdownIsNotRunning_LENGTH;
break;
}
case AI_IFHudCountdownLessThan: // DBYTE(SECONDS), BYTE(GOTOLABEL)
{
float value = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,lbl%d", value, AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFHudCountdownLessThan_LENGTH;
break;
}
case AI_IFHudCountdownGreaterThan: // DBYTE(SECONDS), BYTE(GOTOLABEL)
{
float value = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,lbl%d", value, AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFHudCountdownGreaterThan_LENGTH;
break;
}
case AI_TRYSpawningChrAtPad: // BYTE(BODY_NUM), BYTE(HEAD_NUM), DBYTE(PAD), DBYTE(AI_LIST_ID), QBYTE(BITFIELD), BYTE(GOTOLABEL)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 2);
int flags = CharArrayTo32(AiList, Offset + 1 + 6);
unsigned short ailistid = CharArrayTo16(AiList, Offset + 1 + 4);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,", AiList[Offset + 1]);
if (isNotBoundPad(pad))
{
printf("%d,", pad);
}
else
{
printf("setBoundPadNum(%d),", getBoundPadNum(pad));
}
printf("%d,0x%x,%d,lbl%d", ailistid, flags, AiList[Offset + 10], AiList[Offset + 11]);
printf(")\n");
Offset += AI_TRYSpawningChrAtPad_LENGTH;
break;
}
case AI_TRYSpawningChrNextToChr: // BYTE(BODY_NUM), BYTE(HEAD_NUM), BYTE(CHR_NUM_TARGET), DBYTE(AI_LIST_ID), QBYTE(BITFIELD), BYTE(GOTOLABEL)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 5);
unsigned short ailistid = CharArrayTo16(AiList, Offset + 1 + 3);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,%d,%d,0x%x,lbl%d", AiList[Offset + 1], AiList[Offset + 1 + 1], AiList[Offset + 1 + 2], ailistid, flags, AiList[Offset + 10]);
printf(")\n");
Offset += AI_TRYSpawningChrNextToChr_LENGTH;
break;
}
case AI_TRYGiveMeItem: // DBYTE(PROP_NUM), BYTE(ITEM_NUM), QBYTE(PROPFLAG), BYTE(GOTOLABEL)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 3);
int model = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,0x%x,lbl%d", model, AiList[Offset + 1 + 2], flags, AiList[Offset + 8]);
printf(")\n");
Offset += AI_TRYGiveMeItem_LENGTH;
break;
}
case AI_TRYGiveMeHat: // DBYTE(PROP_NUM), QBYTE(PROP_BITFIELD), BYTE(GOTOLABEL)
{
int flags = CharArrayTo32(AiList, Offset + 1 + 2);
int modelnum = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,0x%x,lbl%d", modelnum, flags, AiList[Offset + 7]);
printf(")\n");
Offset += AI_TRYGiveMeHat_LENGTH;
break;
}
case AI_TRYCloningChr: // BYTE(CHR_NUM), DBYTE(AI_LIST_ID), BYTE(GOTOLABEL)
{
unsigned short ailistid = CharArrayTo16(AiList, Offset + 1 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,lbl%d", AiList[Offset + 4], ailistid, AiList[Offset + 4]);
printf(")\n");
Offset += AI_TRYCloningChr_LENGTH;
break;
}
case AI_TextPrintBottom:// DBYTE(TEXT_SLOT)
{
printf("//USING HUD MESSAGE Stringy = %d, ai->txt = %d\n", 0, CharArrayTo16(AiList, Offset + 1 + 0));
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("TEXT(%d,%d)", (CharArrayTo16(AiList, Offset + 1 + 0)) / 1024, (CharArrayTo16(AiList, Offset + 1 + 0)) % 1024);
printf(")\n");
Offset += AI_TextPrintBottom_LENGTH;
break;
}
case AI_TextPrintTop:// DBYTE(TEXT_SLOT)
{
printf("//USING HUD MESSAGE Stringy = %d, ai->txt = %d\n", 0, CharArrayTo16(AiList, Offset + 1 + 0));
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("TEXT(%d,%d)", (CharArrayTo16(AiList, Offset + 1 + 0)) / 1024, (CharArrayTo16(AiList, Offset + 1 + 0)) % 1024);
printf(")\n");
Offset += AI_TextPrintTop_LENGTH;
break;
}
case AI_SfxPlay: // DBYTE(SOUND_NUM), BYTE(CHANNEL_NUM)
{
short audio_id = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d", audio_id, AiList[Offset + 3]);
printf(")\n");
Offset += AI_SfxPlay_LENGTH;
break;
}
case AI_SfxStopChannel: // BYTE(CHANNEL_NUM)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 3]);
printf(")\n");
Offset += AI_SfxStopChannel_LENGTH;
break;
}
case AI_SfxSetChannelVolume: // BYTE(CHANNEL_NUM), DBYTE(TARGET_VOLUME), DBYTE(TRANSITION_TIME60)
{
short vol = CharArrayTo16(AiList, Offset + 2 + 0);
unsigned short sfxID = CharArrayTo16(AiList, Offset + 2 + 2);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d, %d,%d", AiList[Offset + 1], vol, sfxID);
printf(")\n");
Offset += AI_SfxSetChannelVolume_LENGTH;
break;
}
case AI_SfxFadeChannelVolume: // BYTE(CHANNEL_NUM), DBYTE(TARGET_VOLUME), DBYTE(TRANSITION_TIME60)
{
short vol = CharArrayTo16(AiList, Offset + 2 + 0);
unsigned short sfxID = CharArrayTo16(AiList, Offset + 2 + 2);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d, %d,%d", AiList[Offset + 1], vol, sfxID);
printf(")\n");
Offset += AI_SfxFadeChannelVolume_LENGTH;
break;
}
case AI_SfxEmitFromObject: // BYTE(CHANNEL_NUM), BYTE(OBJECT_TAG), DBYTE(VOL_DECAY_TIME60)
{
unsigned short sfxID = CharArrayTo16(AiList, Offset + 2 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d, %d,%d", AiList[Offset + 1], AiList[Offset + 2], sfxID);
printf(")\n");
Offset += AI_SfxEmitFromObject_LENGTH;
break;
}
case AI_SfxEmitFromPad: // BYTE(CHANNEL_NUM), DBYTE(PAD), DBYTE(VOL_DECAY_TIME60)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 2 + 0);
unsigned short sfxID = CharArrayTo16(AiList, Offset + 2 + 2);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,", AiList[Offset + 1]);
if (isNotBoundPad(pad))
{
printf("%d,", pad);
}
else
{
printf("setBoundPadNum(%d),", getBoundPadNum(pad));
}
printf("%d", sfxID);
printf(")\n");
Offset += AI_SfxEmitFromPad_LENGTH;
break;
}
case AI_IFSfxChannelVolumeLessThan: // BYTE(CHANNEL_NUM), DBYTE(VOLUME), BYTE(GOTOLABEL)
{
short vol = CharArrayTo16(AiList, Offset + 2 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d, %d,lbl%d", AiList[Offset + 1], vol, AiList[Offset + 4]);
printf(")\n");
Offset += AI_IFSfxChannelVolumeLessThan_LENGTH;
break;
}
case AI_VehicleStartPath: // BYTE(PATH_NUM)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1 + 0]);
printf(")\n");
Offset += AI_VehicleStartPath_LENGTH;
break;
}
case AI_VehicleSpeed: // DBYTE(TOP_SPEED), DBYTE(ACCELERATION_TIME60)
{
float speedtime = CharArrayTo16(AiList, Offset + 1 + 2);
float speedaim = CharArrayTo16(AiList, Offset + 1 + 0) * 100.0f / 15360.0f;
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%f", CharArrayTo16(AiList, Offset + 1 + 0), speedtime);
printf(")\n");
Offset += AI_VehicleSpeed_LENGTH;
break;
}
case AI_AircraftRotorSpeed: // DBYTE(ROTOR_SPEED), DBYTE(ACCELERATION_TIME60)
{
float speedtime = CharArrayTo16(AiList, Offset + 1 + 2);
float speedaim = CharArrayTo16(AiList, Offset + 1 + 0) * M_TAU_F / 3600.0f;
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%f", CharArrayTo16(AiList, Offset + 1 + 0), speedtime);
printf(")\n");
Offset += AI_AircraftRotorSpeed_LENGTH;
break;
}
case AI_IFCameraIsInIntro: // BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1 + 0]);
printf(")\n");
Offset += AI_IFCameraIsInIntro_LENGTH;
break;
}
case AI_IFCameraIsInBondSwirl:// BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1 + 0]);
printf(")\n");
Offset += AI_IFCameraIsInBondSwirl_LENGTH;
break;
}
case AI_TvChangeScreenBank: // BYTE(OBJECT_TAG), BYTE(SCREEN_INDEX), BYTE(SCREEN_BANK)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,$d", AiList[Offset + 1], AiList[Offset + 2], AiList[Offset + 3]);
printf(")\n");
Offset += AI_TvChangeScreenBank_LENGTH;
break;
}
case AI_IFBondInTank: // canonical name
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1 + 0]);
printf(")\n");
Offset += AI_IFBondInTank_LENGTH;
break;
}
case AI_EndLevel: // canonical name
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_EndLevel_LENGTH;
break;
}
case AI_CameraReturnToBond:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_CameraReturnToBond_LENGTH;
break;
}
case AI_CameraLookAtBondFromPad: // DBYTE(PAD)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
if (isNotBoundPad(pad))
{
printf("%d", pad);
}
else
{
printf("setBoundPadNum(%d),", getBoundPadNum(pad));
}
printf(")\n");
Offset += AI_CameraLookAtBondFromPad_LENGTH;
break;
}
case AI_CameraSwitch: // BYTE(OBJECT_TAG), DBYTE(LOOK_AT_BOND_FLAG), DBYTE(UNUSED_FLAG)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,%d", AiList[Offset + 1 + 0], CharArrayTo16(AiList, Offset + 1 + 1), CharArrayTo16(AiList, Offset + 1 + 3));
printf(")\n");
Offset += AI_CameraSwitch_LENGTH;
break;
}
case AI_IFBondYPosLessThan: // DBYTE(Y_POS), BYTE(GOTOLABEL)
{
float bondpos = (short)CharArrayTo16(AiList, Offset + 1 + 0);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%f,%d", bondpos, AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFBondYPosLessThan_LENGTH;
break;
}
case AI_BondDisableControl: // BYTE(BITFIELD)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_BondDisableControl_LENGTH;
break;
}
case AI_BondEnableControl:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_BondEnableControl_LENGTH;
break;
}
case AI_TRYTeleportingChrToPad: // BYTE(CHR_NUM), DBYTE(PAD), BYTE(GOTOLABEL)
{
int pad = CharArrayTo16(AiList, Offset + 1 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,", AiList[Offset + 1]);
if (isNotBoundPad(pad))
{
printf("%d,", pad);
}
else
{
printf("setBoundPadNum(%d),", getBoundPadNum(pad));
}
printf("lbl%d", AiList[Offset + 4]);
printf(")\n");
Offset += AI_TRYTeleportingChrToPad_LENGTH;
break;
}
case AI_ScreenFadeToBlack:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_ScreenFadeToBlack_LENGTH;
break;
}
case AI_ScreenFadeFromBlack:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_ScreenFadeFromBlack_LENGTH;
break;
}
case AI_IFScreenFadeCompleted:// BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFScreenFadeCompleted_LENGTH;
break;
}
case AI_HideAllChrs:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_HideAllChrs_LENGTH;
break;
}
case AI_ShowAllChrs:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_ShowAllChrs_LENGTH;
break;
}
case AI_DoorOpenInstant: // BYTE(OBJECT_TAG)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_DoorOpenInstant_LENGTH;
break;
}
case AI_ChrRemoveItemInHand: // BYTE(CHR_NUM), BYTE(HAND_INDEX)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%s", AiList[Offset + 1], AiList[Offset + 2] == 0 ? "GUNRIGHT" : "GUNLEFT");
printf(")\n");
Offset += AI_ChrRemoveItemInHand_LENGTH;
break;
}
case AI_IfNumberOfActivePlayersLessThan: // BYTE(NUMBER), BYTE(GOTOLABEL)
{
if (AiList[Offset + 1] == 2)
{
printf("%sIFSinglePlayer(", tabs);
printf("lbl%d", AiList[Offset + 2]);
}
else
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
}
printf(")\n");
Offset += AI_IfNumberOfActivePlayersLessThan_LENGTH;
break;
}
case AI_IFBondItemTotalAmmoLessThan: // BYTE(ITEM_NUM), BYTE(AMMO_TOTAL), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2], AiList[Offset + 3]);
printf(")\n");
Offset += AI_IFBondItemTotalAmmoLessThan_LENGTH;
break;
}
case AI_BondEquipItem: // BYTE(ITEM_NUM)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_BondEquipItem_LENGTH;
break;
}
case AI_BondEquipItemCinema: // BYTE(ITEM_NUM)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_BondEquipItemCinema_LENGTH;
break;
}
case AI_BondSetLockedVelocity: // BYTE(X_SPEED60), BYTE(Z_SPEED60)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_BondSetLockedVelocity_LENGTH;
break;
}
case AI_IFObjectInRoomWithPad: // BYTE(OBJECT_TAG), DBYTE(PAD), BYTE(GOTOLABEL)
{
unsigned short pad = CharArrayTo16(AiList, Offset + 1 + 1);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,", AiList[Offset + 1]);
if (isNotBoundPad(pad))
{
printf("%d,", pad);
}
else
{
printf("setBoundPadNum(%d),", getBoundPadNum(pad));
}
printf("lbl%d", AiList[Offset + 4]);
printf(")\n");
Offset += AI_IFObjectInRoomWithPad_LENGTH;
break;
}
case AI_SwitchSky:
{ // SWITCHENVIRONMENT
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_SwitchSky_LENGTH;
break;
}
case AI_TriggerFadeAndExitLevelOnButtonPress:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_TriggerFadeAndExitLevelOnButtonPress_LENGTH;
break;
}
case AI_IFBondIsDead:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFBondIsDead_LENGTH;
break;
}
case AI_BondDisableDamageAndPickups:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_BondDisableDamageAndPickups_LENGTH;
break;
}
case AI_BondHideWeapons:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_BondHideWeapons_LENGTH;
break;
}
case AI_CameraOrbitPad:
{
int pad;
int speed60;
int camDististance;
int targetHeight;
int camHeight;
int start;
camDististance = CharArrayTo16(AiList, Offset + 1 + 0);
camHeight = (short)CharArrayTo16(AiList, Offset + 1 + 2);
speed60 = (short)CharArrayTo16(AiList, Offset + 1 + 4);
pad = CharArrayTo16(AiList, Offset + 1 + 6);
targetHeight = (short)CharArrayTo16(AiList, Offset + 1 + 8);
start = CharArrayTo16(AiList, Offset + 1 + 10);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,%d,", camDististance, camHeight, speed60);
if (isNotBoundPad(pad))
{
printf("%d,", pad);
}
else
{
printf("setBoundPadNum(%d),", getBoundPadNum(pad));
}
printf("%d,%d", targetHeight, start);
printf(")\n");
Offset += AI_CameraOrbitPad_LENGTH;
break;
}
case AI_CreditsRoll:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_CreditsRoll_LENGTH;
break;
}
case AI_IFCreditsHasCompleted:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFCreditsHasCompleted_LENGTH;
break;
}
case AI_IFObjectiveAllCompleted:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFObjectiveAllCompleted_LENGTH;
break;
}
case AI_IFFolderActorIsEqual: // BYTE(BOND_ACTOR_INDEX), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFFolderActorIsEqual_LENGTH;
break;
}
case AI_IFBondDamageAndPickupsDisabled:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("lbl%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_IFBondDamageAndPickupsDisabled_LENGTH;
break;
}
case AI_MusicPlaySlot: // BYTE(MUSIC_SLOT), BYTE(SECONDS_STOPPED_DURATION), BYTE(SECONDS_TOTAL_DURATION)
{
printf("//ai: enery tune on (%d, %d, %d)\n", AiList[Offset + 1 + 0], AiList[Offset + 1 + 1], AiList[Offset + 1 + 2]);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,%d,%d", AiList[Offset + 1 + 0], AiList[Offset + 1 + 1], AiList[Offset + 1 + 2]);
printf(")\n");
Offset += AI_MusicPlaySlot_LENGTH;
break;
}
case AI_MusicStopSlot:
{
printf("//ai: enery tune off (%d)\n", AiList[Offset + 1 + 0]);
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1 + 0]);
printf(")\n");
Offset += AI_MusicStopSlot_LENGTH;
break;
}
case AI_TriggerExplosionsAroundBond:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_TriggerExplosionsAroundBond_LENGTH;
break;
}
case AI_IFKilledCiviliansGreaterThan:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFKilledCiviliansGreaterThan_LENGTH;
break;
}
case AI_IFChrWasShotSinceLastCheck: // BYTE(CHR_NUM), BYTE(GOTOLABEL)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d,lbl%d", AiList[Offset + 1], AiList[Offset + 2]);
printf(")\n");
Offset += AI_IFChrWasShotSinceLastCheck_LENGTH;
break;
}
case AI_BondKilledInAction:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_BondKilledInAction_LENGTH;
break;
}
case AI_RaiseArms:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_RaiseArms_LENGTH;
break;
}
case AI_GasLeakAndFadeFog:
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf(")\n");
Offset += AI_GasLeakAndFadeFog_LENGTH;
break;
}
case AI_ObjectRocketLaunch: // BYTE(OBJECT_TAG)
{
printf("%s%s(", tabs, AI_CMD_ToString[AiList[Offset]]);
printf("%d", AiList[Offset + 1]);
printf(")\n");
Offset += AI_ObjectRocketLaunch_LENGTH;
break;
} //============================================================================================================
default:
/*
* No Command found, advance ailist by 1.
* This is attempting to handle situations where the command
* type is invalid by passing over them and continuing
* execution.
* chraiitemsize returns 1 which is pointless really
* could have done it here without a jump
*
* Outcome:crash
*/
{
Offset++;
}
} // switch
}
}
enum chrAIListIDs
{
chrai_0 = setChrAIListID(0),
chrai_1,
chrai_2,
chrai_3,
chrai_4,
chrai_5,
chrai_6,
chrai_7,
chrai_8,
chrai_9,
chrai_10,
chrai_11,
chrai_12,
chrai_13,
chrai_14,
chrai_15,
chrai_16,
chrai_17,
chrai_18
};
int main()
{
unsigned char
ai_0[] = {0x02, 0x03, 0x03, 0xeb, 0x36, 0x55, 0x00, 0xd0, 0x2a, 0x01, 0x03, 0x02, 0x2a, 0xec, 0xd7, 0x00, 0xda, 0x02, 0x08, 0x03, 0xdc, 0x2a, 0x01, 0x08, 0x02, 0x2a, 0xf1, 0x2a, 0x05, 0xfd, 0x00, 0x0f, 0x02, 0x2a, 0xdd, 0xea, 0x59, 0x18, 0x2a, 0x59, 0x19, 0x2a, 0x59, 0x04, 0x2a, 0x59, 0x05, 0x2a, 0x59, 0x06, 0x2a, 0x59, 0x07, 0x2a, 0x59, 0x08, 0x2a, 0x59, 0x09, 0x2a, 0x59, 0x0a, 0x2a, 0x59, 0x0b, 0x2a, 0x59, 0x0c, 0x2a, 0x59, 0x0d, 0x2a, 0x59, 0x0e, 0x2a, 0x59, 0x0f, 0x2a, 0x59, 0x10, 0x2a, 0x59, 0x11, 0x2a, 0x59, 0x12, 0x2a, 0x59, 0x13, 0x2a, 0x59, 0x16, 0x2a, 0x59, 0x14, 0x2a, 0x59, 0x15, 0x2a, 0xe4, 0x04, 0x02, 0x2a, 0xed, 0x03, 0x03, 0x03, 0xd5, 0x05, 0x00, 0x02, 0x00, 0x00, 0xd9, 0xf8, 0x00, 0xab, 0x2a, 0x02, 0x2a, 0x05, 0xf8, 0x04, 0x12, 0xa1, 0x00, 0x00, 0x00, 0x04, 0x00, 0xd9, 0x00, 0x00, 0xaa, 0x2a, 0x02, 0x2a, 0x05, 0x00, 0x04, 0x13, 0xdb, 0xf4, 0x00, 0x00, 0xff, 0x05, 0xfd, 0x00, 0x01, 0x02, 0x36, 0x05, 0xfd, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00};
short ID = 1;
// char str[999];
// printf("Enter a string: ");
// gets(str);
if (isChrAIListID(ID))
{
printf("u8 chrAI_%d[] = {\n #define THIS chrai_%d\n", getChrAIListID(ID), getChrAIListID(ID));
}
else
{
printf("u8 bgAi_%d[] = {\n #define THIS bgai_%d\n", getBGAIListID(ID), getBGAIListID(ID));
}
ai(ai_0, ID);
// un-closed loops
if (top != -1) displayStack();
printf("#undef THIS \n};\n");
return 0;
}
|
C
|
#include "SeqList.h"
int main(void){
SeqList sl = newList();
sl=insertAtFront(sl,5);
printList(sl);
sl=insertAtEnd(sl,21);
printList(sl);
sl=insertInOrder(sl,18);
sl=insertInOrder(sl,2);
sl=insertInOrder(sl,40);
printList(sl);
sl=deleted(sl,2);
printList(sl);
sl=deleted(sl,40);
printList(sl);
sl=deleteAtFront(sl);
printList(sl);
return 0;
}
SeqList newList(void){
SeqList sl = (SeqList*)malloc(sizeof(SeqList));
sl->head=NULL;
sl->tail=NULL;
sl->count=0;
return sl;
}
void printList(SeqList sl){
printf("inside printList\n");
if(sl == NULL){
printf("List is null");
return;
}
SeqList p = sl;
while(p!=NULL){
printf("%d\n",p->e);
p=p->next;
}
return ;
}
SeqList insertAtFront(SeqList sl,Element e){
if(sl !=NULL){
e->next = head;
sl->head = e;
sl->count++;
return sl;
}
else{
SeqList newSl = newList();
newSl->head = e;
newSl->tail = e;
e->next =NULL;
newSl->count++;
return newSl;
}
}
SeqList insertAtEnd(SeqList sl,Element e){
if(sl==NULL){
SeqList newSl = newList();
newSl->head = e;
newSl->tail = e;
e->next =NULL;
newSl->count++;
return newSl;
return newSL;
}
sl->tail->next=e;
sl->tail=e;
sl->count++;
return sl;
}
SeqList deleted(SeqList sl,Element e){
if(sl==NULL){
printf("null list:nothing to delete");
return sl;
}
if(sl->head==e){
free(sl);
return sl;
}SeqList prev = sl;
SeqList n =sl->next;
int flag=0;
while(n !=NULL){
if(n->e ==e){
prev->next=n->next;
free(n);
flag=1;
}
prev=prev->next;
n = n->next;
}
if(flag==0)
printf("Element not found");
return sl;
}
SeqList deleteAtFront(SeqList sl){
if(sl==NULL){
printf("Null list:nothing to delete");
return sl;
}
SeqList p =sl;
sl = sl->next;
free(p);
return sl;
}
Element find(SeqList sl,Key k){
if(sl==NULL)
return 0;
SeqList p = sl;
while(p!=NULL){
if(p->e ==k){
return p->e;
}
}
printf("could not find key %d in list",k);
return 0;
}
SeqList insertInOrder(SeqList sl, Element e){
if(sl==NULL){
SeqList newsl = (SeqList)malloc(sizeof(SeqList));
newsl->e =e;
newsl->next=NULL;
return newsl;
}
SeqList prev = sl;
SeqList newsl = (SeqList)malloc(sizeof(SeqList));
newsl->e=e;
SeqList n = sl->next;
if(newsl->e < sl->e){
newsl->next = sl;
sl = newsl;
return sl;
}
while(n!=NULL){
if((newsl->e)>prev->e&& newsl->e < n->e){
newsl->next =n;
prev->next = newsl;
return sl;
}
prev=prev->next;
n=n->next;
}
prev->next = newsl;
newsl->next =NULL;
return sl;
}
|
C
|
//
// main.c
// 14_08 - refining prototypes
//
// Created by jim Veneskey on 2/3/16.
// Copyright © 2016 Jim Veneskey. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
// Prototypes are defined here
// note - no sample var names included, just their types
double func(double, double);
int main(int argc, const char * argv[]) {
// insert code here...
double result = func(10, 20);
printf("Result = %lf\n", result);
return EXIT_SUCCESS;
}
// function definitions
double func(double x, double y) {
return x * y;
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <stdint.h>
#include <signal.h>
#include <unistd.h>
#include <sys/time.h>
#include <errno.h>
#include <string.h>
#include <math.h>
#include <pthread.h>
#include <stdlib.h>
#include "pt3_ioctl.h"
#include "ptx_ctrl.h"
#define MSG_SIZE 188*256
#define MAX_DEV_NUM 99
#define STATE_READ 0
#define STATE_COMPLETED 1
#define STATE_END 2
typedef struct {
int fd;
uint8_t buf[MSG_SIZE];
int readsize;
int remain;
int state;
pthread_t worker;
pthread_mutex_t mutex;
pthread_cond_t cond;
} ptx_ctrl_t;
static int gettime_ms(uint64_t *ms)
{
struct timeval tv;
if(gettimeofday(&tv, NULL) == 0) {
*ms = (uint64_t)tv.tv_sec*1000 + tv.tv_usec/1000;
return 0;
} else {
return -1;
}
}
static void* worker_thread(void* param)
{
ssize_t ret;
int end = 0;
ptx_ctrl_t *pc = (ptx_ctrl_t*)param;
while(1) {
pthread_mutex_lock(&pc->mutex);
while( pc->state == STATE_COMPLETED ) {
pthread_cond_wait(&pc->cond, &pc->mutex);
}
if(pc->state == STATE_END) {
end = 1;
}
pthread_mutex_unlock(&pc->mutex);
if(end) {
break;
}
ret = read(pc->fd, pc->buf, MSG_SIZE);
pthread_mutex_lock(&pc->mutex);
pc->state = STATE_COMPLETED;
pc->remain = pc->readsize = (int)ret;
pthread_cond_signal(&pc->cond);
pthread_mutex_unlock(&pc->mutex);
}
return NULL;
}
static ptx_handle_t ptx_open(const char *devfmt, tuner_type_t tuner_type)
{
int i, fd;
char dev[128];
ptx_ctrl_t *pc;
if(tuner_type == ISDB_T) {
i = 2;
} else {
i = 0;
}
while(i <= MAX_DEV_NUM) {
sprintf(dev, devfmt, i);
//fd = ptx_open_device(dev);
fd = open(dev, O_RDONLY);
if(fd < 0) {
if( errno == ENOENT ) {
return NULL;
}
} else {
//printf("open: %s\n", dev);
pc = (ptx_ctrl_t*)malloc(sizeof(ptx_ctrl_t));
pc->fd = fd;
pthread_mutex_init(&pc->mutex, NULL);
pthread_cond_init(&pc->cond, NULL);
pc->state = STATE_READ;
pthread_create( &pc->worker, NULL, worker_thread, (void*)pc );
return (ptx_handle_t)pc;
}
if(i%2 == 0) {
i++;
} else {
i+=3;
}
}
return NULL;
}
PTXCTRL_FUNC ptx_handle_t pt3_open(tuner_type_t tuner_type)
{
return ptx_open("/dev/pt3video%d", tuner_type);
}
PTXCTRL_FUNC ptx_handle_t pt1_open(tuner_type_t tuner_type)
{
return ptx_open("/dev/pt1video%d", tuner_type);
}
PTXCTRL_FUNC int ptx_close(ptx_handle_t handle)
{
int fd;
ptx_ctrl_t *pc = (ptx_handle_t)handle;
pthread_mutex_lock(&pc->mutex);
while(pc->state == STATE_READ) {
pthread_cond_wait(&pc->cond, &pc->mutex);
}
pc->state = STATE_END;
pthread_cond_signal(&pc->cond);
pthread_mutex_unlock(&pc->mutex);
pthread_join(pc->worker, NULL);
fd = pc->fd;
free(pc);
return close(fd);
}
static int until(struct timespec *ts_ref)
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
if( ts.tv_sec > ts_ref->tv_sec ) {
return 0;
} else if( ts.tv_sec < ts_ref->tv_sec ) {
return 1;
}
if( ts.tv_nsec > ts_ref->tv_nsec ) {
return 0;
}
return 1;
}
PTXCTRL_FUNC int ptx_select(ptx_handle_t handle, int timeout_ms)
{
int retval;
struct timespec ts;
ptx_ctrl_t *pc = (ptx_handle_t)handle;
pthread_mutex_lock(&pc->mutex);
if( timeout_ms > 0 ) {
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += timeout_ms / 1000;
ts.tv_nsec += (timeout_ms % 1000) * 1000 * 1000;
//printf("select %d ms\n", timeout_ms);
while( pc->state == STATE_READ ) {
pthread_cond_timedwait(&pc->cond, &pc->mutex, &ts);
if(!until(&ts)) {
//printf("select timeout! errno=%d\n", errno);
break;
}
}
} else if( timeout_ms < 0 ) { /* infinite */
while( pc->state == STATE_READ ) {
pthread_cond_wait(&pc->cond, &pc->mutex);
}
}
if( pc->state == STATE_COMPLETED ) {
retval = 1;
} else {
retval = 0;
}
pthread_mutex_unlock(&pc->mutex);
return retval;
}
PTXCTRL_FUNC int ptx_read(ptx_handle_t handle, uint8_t *buf, int maxsize)
{
int size;
ptx_ctrl_t *pc = (ptx_handle_t)handle;
pthread_mutex_lock(&pc->mutex);
while( pc->state == STATE_READ ) {
pthread_cond_wait(&pc->cond, &pc->mutex);
}
if( pc->readsize < 0 ) {
size = pc->readsize;
pc->state = STATE_READ;
pthread_cond_signal(&pc->cond);
} else if( pc->remain > maxsize ) {
size = maxsize;
memcpy(buf, &pc->buf[pc->readsize - pc->remain], size);
pc->remain -= size;
} else {
size = pc->remain;
memcpy(buf, &pc->buf[pc->readsize - size], size);
pc->state = STATE_READ;
pthread_cond_signal(&pc->cond);
}
pthread_mutex_unlock(&pc->mutex);
//printf("read %d bytes\n", size);
return size;
}
PTXCTRL_FUNC void ptx_purge(ptx_handle_t handle)
{
uint8_t tmp[188*256];
uint64_t t1, t;
if(gettime_ms(&t1) < 0) {
return;
}
while(ptx_select(handle, 0) > 0) {
//printf("purge read! ...\n");
if(ptx_read(handle, tmp, 188*256) <= 0) {
//printf("read 0\n");
return;
}
if(gettime_ms(&t) < 0 ) {
return;
}
if(t-t1 >= 1000) {
/* 1000ms timeout */
//printf("1000ms timeout!\n");
return;
}
//printf("end\n");
}
}
PTXCTRL_FUNC int ptx_tune(ptx_handle_t handle, FREQUENCY *freq)
{
ptx_ctrl_t *pc = (ptx_handle_t)handle;
//printf("tune: %d %d\n", freq->frequencyno, freq->slot);
//return ioctl(fd, SET_CHANNEL, freq);
ptx_select(handle, -1);
int ret = ioctl(pc->fd, SET_CHANNEL, freq);
//ptx_getlevel_t(fd); ??????
return ret;
}
PTXCTRL_FUNC double ptx_getlevel_t(ptx_handle_t handle)
{
ptx_ctrl_t *pc = (ptx_handle_t)handle;
int rc;
double p;
ptx_select(handle, -1);
if( ioctl(pc->fd, GET_SIGNAL_STRENGTH, (uint64_t)(&rc)) < 0 ) {
return 0.0;
}
//printf("rc=%d\n", rc);
p = log10(5505024/(double)rc) * 10;
return (0.000024 * p * p * p * p) - (0.0016 * p * p * p) +
(0.0398 * p * p) + (0.5491 * p)+3.0965;
}
PTXCTRL_FUNC double ptx_getlevel_s(ptx_handle_t handle)
{
ptx_ctrl_t *pc = (ptx_handle_t)handle;
int rc;
unsigned char sigbuf[4];
float fMixRate;
/* apply linear interpolation */
static const float afLevelTable[] = {
24.07f, // 00 00 0 24.07dB
24.07f, // 10 00 4096 24.07dB
18.61f, // 20 00 8192 18.61dB
15.21f, // 30 00 12288 15.21dB
12.50f, // 40 00 16384 12.50dB
10.19f, // 50 00 20480 10.19dB
8.140f, // 60 00 24576 8.140dB
6.270f, // 70 00 28672 6.270dB
4.550f, // 80 00 32768 4.550dB
3.730f, // 88 00 34816 3.730dB
3.630f, // 88 FF 35071 3.630dB
2.940f, // 90 00 36864 2.940dB
1.420f, // A0 00 40960 1.420dB
0.000f // B0 00 45056 -0.01dB
};
ptx_select(handle, -1);
if( ioctl(pc->fd, GET_SIGNAL_STRENGTH, (uint64_t)(&rc)) < 0 ) {
return 0.0;
}
memset(sigbuf, '\0', sizeof(sigbuf));
sigbuf[0] = (((rc & 0xFF00) >> 8) & 0XFF);
sigbuf[1] = (rc & 0xFF);
/* calculate signal level */
if(sigbuf[0] <= 0x10U) {
/* clipped maximum */
return 24.07f;
} else if (sigbuf[0] >= 0xB0U) {
/* clipped minimum */
return 0.0f;
} else {
/* linear interpolation */
fMixRate =
(float)(((unsigned short)(sigbuf[0] & 0x0FU) << 8) |
(unsigned short)sigbuf[0]) / 4096.0f;
return (double)( afLevelTable[sigbuf[0] >> 4] * (1.0f - fMixRate) +
afLevelTable[(sigbuf[0] >> 4) + 0x01U] * fMixRate );
}
}
PTXCTRL_FUNC int ptx_start(ptx_handle_t handle)
{
ptx_ctrl_t *pc = (ptx_handle_t)handle;
ptx_select(handle, -1);
return ioctl(pc->fd, START_REC, 0);
}
PTXCTRL_FUNC int ptx_stop(ptx_handle_t handle)
{
ptx_ctrl_t *pc = (ptx_handle_t)handle;
ptx_select(handle, -1);
return ioctl(pc->fd, STOP_REC, 0);
}
/*
int main()
{
int fd = pt3_open(ISDB_T);
if(fd < 0) {
printf("open failed!\n");
return 0;
}
ptx_start(fd);
sleep(10);
ptx_stop(fd);
ptx_close_device(fd);
return 0;
}
*/
|
C
|
#include <stdio.h>
#include <fcntl.h>
#include <zconf.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/mman.h>
int file;
char* buf;
void print_file (int sig) {
for (int i = 0; *(buf + i) != '\0'; ++i) {
printf("%c", *(buf + i));
}
exit(0);
}
int time_scan (int sec, char* input) {
signal(SIGALRM, print_file);
alarm(sec);
int res = scanf("%s", input);
alarm(0);
return res;
}
int main() {
if ((file = open("crusoe", O_RDONLY)) == -1) {
perror("Can't open file");
return 1;
}
int str_cnt = 0;
int off = 0;
int count_of_pages = 0;
int end_of_file = 0;
while (!end_of_file) {
char* c = (char*) mmap(0, getpagesize(), PROT_READ, MAP_PRIVATE, file, off);
count_of_pages++;
for (int i = 0; i < getpagesize(); ++i) {
if (*(c + i) == '\0') {
end_of_file = 1;
break;
}
if (*(c + i) == '\n') {
str_cnt++;
}
//printf("%c", *(c + i));
}
off += getpagesize();
}
int break_indexes[str_cnt + 1];
int str_lens[str_cnt];
break_indexes[0] = -1;
printf("%d\n", str_cnt);
buf = (char*) mmap(0, count_of_pages * getpagesize(), PROT_READ, MAP_PRIVATE, file, 0);
int cur_str = 1;
for (int i = 0; *(buf + i) != '\0'; ++i) {
if (*(buf + i) == '\n') {
break_indexes[cur_str] = i;
str_lens[cur_str - 1] = break_indexes[cur_str] - break_indexes[cur_str - 1] - 1;
cur_str++;
}
}
char* end;
char* input = (char*) malloc(30 * sizeof(char));
int res = time_scan(5, input);
if (res == EOF) {
printf("Don't press Ctrl+D, mudila!\n");
exit(1);
}
int query = strtol(input, &end, 10);
while (query != 0 || end == input) {
if (query < 0 || query > str_cnt || end == input) {
fprintf(stderr, "Wrong input\n");
int res = time_scan(5, input);
if (res == EOF) {
printf("Don't press Ctrl+D, mudila!\n");
exit(1);
}
query = strtol(input, &end, 10);
continue;
}
query--;
for (int i = 0; i < str_lens[query]; ++i) {
printf("%c", *(buf + break_indexes[query] + i + 1));
}
printf("\n");
int res = time_scan(5, input);
if (res == EOF) {
printf("Don't press Ctrl+D, mudila!\n");
exit(1);
}
query = strtol(input, &end, 10);
}
close(file);
return 0;
}
|
C
|
#pragma once
void sbus_setup() {
// The SBUS protocol uses inverted serial logic with:
// - Baud rate of 100000
// - 8 data bits
// - Even parity bit
// - 2 stop bits
HardwareSerial *bus = &Serial1;
bus->begin(100000, SERIAL_8E2);
bus->flush();
}
uint8_t sbus_read_byte() {
return Serial1.read();
}
void sbus_read(uint8_t *data, const size_t size) {
Serial1.readBytes(data, size);
}
void sbus_write_byte(const uint8_t data) {
Serial1.write(data);
}
void sbus_write(const uint8_t *data, const size_t size) {
Serial1.write(data, size);
}
void sbus_update(uart_t *uart) {
// Get sbus frame data
/* uint8_t frame[25] = {0}; */
/* frame[0] = sbus_read_byte(); */
/* if (frame[0] != 0x0F) { */
/* uart_printf(uart, "Failed!\n"); */
/* return; */
/* } else { */
/* sbus_read(&frame[1], 24); */
/* } */
if (Serial1.available()) {
uart_printf(uart, "%X\n", sbus_read_byte());
} else {
uart_printf(uart, "nothing...\n");
}
// Parse sbus frame
// -- Parse flag
/* uint8_t frame_lost = (frame[23] & (1 << 5)); */
/* uint8_t failsafe_activated = (frame[23] & (1 << 4)); */
// -- Parse channel data
/* uint16_t ch[16] = {0}; */
/* ch[0] = ((frame[1] | frame[2] << 8) & 0x07FF); */
/* ch[1] = ((frame[2] >> 3 | frame[3] << 5) & 0x07FF); */
/* ch[2] = ((frame[3] >> 6 | frame[4] << 2 | frame[5] << 10) & 0x07FF); */
/* ch[3] = ((frame[5] >> 1 | frame[6] << 7) & 0x07FF); */
/* ch[4] = ((frame[6] >> 4 | frame[7] << 4) & 0x07FF); */
/* ch[5] = ((frame[7] >> 7 | frame[8] << 1 | frame[8] << 9) & 0x07FF); */
/* ch[6] = ((frame[9] >> 2 | frame[10] << 6) & 0x07FF); */
/* ch[7] = ((frame[10] >> 5 | frame[11] << 3) & 0x07FF); */
/* ch[8] = ((frame[12] | frame[13] << 8) & 0x07FF); */
/* ch[9] = ((frame[13] >> 3 | frame[14] << 5) & 0x07FF); */
/* ch[10] = ( (frame[14] >> 6 | frame[15] << 2 | frame[16] << 10) & 0x07FF); */
/* ch[11] = ((frame[16] >> 1 | frame[17] << 7) & 0x07FF); */
/* ch[12] = ((frame[17] >> 4 | frame[18] << 4) & 0x07FF); */
/* ch[13] = ( (frame[18] >> 7 | frame[19] << 1 | frame[20] << 9) & 0x07FF); */
/* ch[14] = ((frame[20] >> 2 | frame[21] << 6) & 0x07FF); */
/* ch[15] = ((frame[21] >> 5 | frame[22] << 3) & 0x07FF); */
/* */
/* char ch_str[10] = {0}; */
/* itoa(ch[0], ch_str, 10); */
/* uart_printf(uart, "HERE!\n"); */
/* uart_printf(uart, "%d, ", ch[0]); */
/* uart_printf(uart, "%d, ", ch[1]); */
/* uart_printf(uart, "%d, ", ch[2]); */
/* uart_printf(uart, "%d\n", ch[3]); */
/* uart_printf(uart, ch_str); */
/* uart_printf(uart, "\r\n"); */
}
|
C
|
&a[0]=2000
&a[1]=2002
&a[2]=2004
&a[3]=2006
&a[4]=2008
a = constant pointer to the first element = &a[0] = 2000
a+1 = constant pointer to the second element = &a[0] + 1*sizeof(int) = 2000 + 2 =2002
a+2 = constant pointer to the third element = &a[0] + 2*sizeof(int) = 2000 + 4 =2004
a+3 = constant pointer to the fourth element = &a[0] + 3*sizeof(int) = 2000 + 6 =2006
a+4 = constant pointer to the fifth element = &a[0] + 4*sizeof(int) = 2000 + 8 =2008
*a = *2000 = 1
*(a+1)=*(2002)=2
*(a+2)=*(2004)=3
*(a+3)=*(2006)=4
*(a+4)=*(2008)=5
|
C
|
#include "binary_trees.h"
/**
* binary_trees_ancestor - find lowest common ancestor
* @first: first node to check
* @second: second node to check
*
* Return: the ancestor or NULL on failure
*/
binary_tree_t *binary_trees_ancestor(const binary_tree_t *first,
const binary_tree_t *second)
{
size_t df, ds;
if (first == NULL || second == NULL)
return (NULL);
if (first == second)
return (first->left->parent);
df = depth(first);
ds = depth(second);
if (df < ds)
return (binary_trees_ancestor(first, second->parent));
else if (ds < df)
return (binary_trees_ancestor(first->parent, second));
else
return (binary_trees_ancestor(first->parent, second->parent));
}
/**
* depth - finds depth of btree
* @tree: binary tree
*
* Return: depth of binary tree or 0 if NULL
*/
size_t depth(const binary_tree_t *tree)
{
binary_tree_t *temp;
size_t counter = 1;
if (tree == NULL || tree->parent == NULL)
return (0);
temp = tree->parent;
while (temp->parent != NULL)
{
temp = temp->parent;
counter++;
}
return (counter);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "undos.h"
void struct2file(STACKUNDOS a, char *user)
{
char fname[200];
sprintf(fname, "/var/www/html/%sstack.txt", user);
STACKUNDOS ant = a;
FILE *fp;
fp = fopen(fname, "w");
while (ant != NULL)
{
fprintf(fp, "%d %d %d %d\n", ant->isSave, ant->x, ant->y, ant->valor);
ant = ant->prox;
}
fclose(fp);
}
STACKUNDOS file2struct(char *user)
{
char fname[200];
sprintf(fname, "/var/www/html/%sstack.txt", user);
char str[10];
STACKUNDOS first;
FILE *fp;
fp = fopen(fname, "r");
if (fgets(str, 10, fp) != NULL)
{
first = malloc(sizeof(struct stackUndos));
sscanf(str, "%d %d %d %d", &first->isSave, &first->x, &first->y, &first->valor);
}
else
return NULL;
STACKUNDOS pt = first;
STACKUNDOS new;
while (fgets(str, 10, fp) != NULL)
{
new = malloc(sizeof(struct stackUndos));
sscanf(str, "%d %d %d %d", &new->isSave, &new->x, &new->y, &new->valor);
pt->prox = new;
pt = pt->prox;
}
pt = NULL;
return first;
}
void undoS(STACKUNDOS *a, ESTADO *e)
{
STACKUNDOS pt = *a;
if (*a)
{
e->grelha[pt->x][pt->y] = pt->valor; //nao testado
STACKUNDOS dps = pt->prox;
free(pt);
*a = dps;
}
}
void addUndo(STACKUNDOS *a, int x, int y, VALOR c)
{
STACKUNDOS new = malloc(sizeof(struct stackUndos));
new->isSave = 0;
new->x = x;
new->y = y;
new->valor = c;
new->prox = *a;
*a = new;
}
void loadS(STACKUNDOS *a, ESTADO *e)
{
STACKUNDOS pt = *a;
STACKUNDOS dps = NULL;
while (pt != NULL && pt->isSave != 1)
{
e->grelha[pt->x][pt->y] = pt->valor; //nao testado
dps = pt;
pt = pt->prox;
free(dps);
}
*a = pt;
if (*a)
(*a)->isSave = 0;
}
void toggleSave(STACKUNDOS *a, char *user)
{
if (*a)
{
(*a)->isSave = 1;
struct2file(*a, user);
}
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
char c;
int b;
scanf("%d%c%d",&a,&c,&b);
if(c=='/')
{
printf("%d",a/b);
}
if(c=='%')
{
printf("%d",a%b);
}
getch();
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_asigning.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ashulha <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/12 14:28:49 by ashulha #+# #+# */
/* Updated: 2017/03/12 14:28:51 by ashulha ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
int ft_fits(char *t, char c, char *map, int i)
{
int j;
int d;
int l;
int map_size;
j = -1;
d = 0;
l = i;
map_size = 0;
while (map[map_size] != '\n')
map_size = map_size + 1;
while (t[++j])
{
if (t[j] == '\n')
{
i = i + map_size + 1;
d = 0;
j = j + 1;
}
if (t[j] == c && map[i + d] != '.')
return (0);
d = d + 1;
}
ft_asigning(t, c, map, l);
return (1);
}
void ft_asigning(char *t, char c, char *map, int i)
{
int j;
int d;
int map_size;
j = -1;
d = 0;
map_size = 0;
while (map[map_size] != '\n')
map_size = map_size + 1;
while (t[++j])
{
if (t[j] == '\n')
{
d = 0;
j = j + 1;
i = map_size + i + 1;
}
if (t[j] == c)
map[i + d] = c;
d = d + 1;
}
}
void ft_reasigning(char *t, char c, char *map, int i)
{
int j;
int d;
int map_size;
j = -1;
d = 0;
map_size = 0;
while (map[map_size] != '\n')
map_size = map_size + 1;
while (t[++j])
{
if (t[j] == '\n')
{
i = i + map_size + 1;
d = 0;
j = j + 1;
}
if (t[j] == c)
map[i + d] = '.';
d = d + 1;
}
}
int ft_solve(char *map, int map_size, char **t, int k)
{
int x;
int y;
int i;
x = 1;
y = 1;
while (y <= map_size)
{
i = ft_xytoi(x, y, map_size);
if (ft_fits(t[k], 'A' + k, map, i))
{
if (t[k + 1] == NULL || ft_solve(map, map_size, t, k + 1) != 0)
return (1);
else
ft_reasigning(t[k], 'A' + k, map, i);
}
if (x == map_size)
{
x = 0;
y = y + 1;
}
x = x + 1;
}
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "Fila.h"
struct fila {
int capacidade; //Tamanho do array F
int ini; //Posicao do "primeiro" elemento
int fim; //Posição livre onde um elemento deve ser inserido
int n; //Número de elementos na estrutura
int *F; //Array para armazenar os elementos
};
Fila *criaFila(int capacidade) {
/*Verifique se o valor em capacidade é válido */
/*Se for, inicialize n, ini e fim com 0 (indicando que a estrutura está vazia) */
/*Aloque o array 'F' e retorne o ponteiro da estrutura */
Fila *fila = malloc(sizeof(Fila));
fila->capacidade = capacidade;
fila->ini = fila->fim = fila->n = 0;
fila->F = malloc(sizeof(int)*capacidade);
return fila;
}
void liberaFila(Fila *fila) {
/* Faz a desalocação de memória */
free(fila->F);
free(fila);
}
void enqueue(Fila *fila, int v) {
/* Adiciona um elemento no fim do vetor */
/* Lembre-se de verificar se há espaço para adicionar o elemento */
/* Complexidade: O(1) */
if(filaCheia(fila)) {
printf("ERRO: Fila cheia!\n");
}
else {
fila->F[fila->fim] = v;
fila->fim = (fila->fim + 1) % fila->capacidade;
fila->n++;
}
}
void dequeue(Fila *fila) {
/* Retira o primeiro elemento*/
/* Complexidade: O(???) */
if (filaVazia(fila)) {
printf("ERRO: Fila vazia!");
return;
}
else {
fila->ini = (fila->ini + 1) % fila->capacidade;
fila->n--;
}
}
int front(Fila *fila){
/* Retorna o primeiro elemento */
/* Complexidade: O(???) */
if (filaVazia(fila)) {
printf("ERRO: Fila vazia!");
return -1;
}
return fila->F[fila->ini];
}
bool filaVazia(Fila *fila) {
/* Verifica se a estrutura está vazia */
/* Complexidade: O(???) */
return fila->n == 0;
}
bool filaCheia(Fila *fila) {
/* Verifica se a estrutura está cheia */
/* Complexidade: O(1) */
return fila->n == fila->capacidade;
}
int tamanhoFila(Fila *fila) {
/* Retorna o número de elementos que a estrutura armazena */
/* Complexidade: O(1) */
return fila->n;
}
|
C
|
#ifndef __STRING_PICO_H_
#define __STRING_PICO_H_
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
extern size_t strlen(const char *s);
extern size_t strnlen(const char *s, size_t n);
extern char* strcpy(char* dest, const char *s);
extern char* strncpy(char* dest, const char* src, size_t n);
extern void* memcpy(void* dest, const void* s, size_t len);
extern void* memset(void* dest, int val, size_t len);
extern int memcmp(const void* a, const void* b, size_t len);
extern int strcmp (char const *a, char const *b) ;
extern int strncmp (char const *a, char const *b, size_t n);
#ifdef __cplusplus
}
#endif // __cplusplus
// bcopy und bzero sind laut POSIX standard nicht mehr erwünscht, wir sollten sie besser ganz weglassen, das ist einfacher.
// Die Argumente source und destinationen sind bei bcopy vertauscht gegenüber
// memcpy, das führt nur zu Irrtümern. Also auch daher sollten wir es vermeiden
#define bcopy(src, dest, n) memcpy(dest, src, n)
#define bzero(dest, len) memset(dest, 0, len)
#endif // __STRING_PICO_H_
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
uint64_t usec_diff(struct timeval start_time)
{
struct timeval tv;
gettimeofday(&tv,NULL);
return
(uint64_t)((tv.tv_usec + tv.tv_sec*1e6) -
(start_time.tv_usec + start_time.tv_sec*1e6));
}
void bubble_sort(int *arr, int arr_len)
{
int i,j, swap;
for (i = 0 ; i < ( arr_len - 1 ); i++)
{
for (j = 0 ; j < arr_len - i - 1; j++)
{
if (arr[j] > arr[j+1])
/* For decreasing order use < */
{
swap = arr[j];
arr[j] = arr[j+1];
arr[j+1] = swap;
}
}
}
}
int main()
{
struct timeval start_time;
int array_length = 10000;
int *arr;
int i,j;
uint64_t msec_time = 0;
arr = (int *)malloc(sizeof(int) * array_length);
memset(arr, 0, array_length);
for(i=0,j=array_length; i<array_length && j>0; i++, j--)
{
arr[i] = j;
}
gettimeofday(&start_time,NULL);
bubble_sort(arr, array_length);
msec_time = usec_diff(start_time) / 1000;
printf("Worst case time in ms is %d\n", msec_time);
free(arr);
arr = (int *)malloc(sizeof(int) * array_length);
memset(arr, 0, array_length);
gettimeofday(&start_time,NULL);
bubble_sort(arr, array_length);
msec_time = usec_diff(start_time) / 1000;
printf("Best case time in ms is %d\n", msec_time);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(){
char input[40] = "";
printf("Warning: do not strings this program, just input something:\n");
fgets(input, sizeof(input), stdin);
for(int i = 6 ; i < strlen(input)-2 ; i++){
input[i] = input[i] ^ 16;
}
if(!strcmp(input, "CGCTF{Th15_0ne_1s_N0t_th5_F14g}\n")){
printf("You will dominate the world!!\n CGCTF{Y0u_sh0u1d_n3v3r_5u6mit_7hi5_0n3}");
}
return 0;
}
|
C
|
#include <stdio.h>
#define MAX 255
struct Book{
char bookName[255];
int bookID;
double bookPrice;
};
void push(struct Book* bookInstance,struct Book* bookArray,int* top){
if(*top==MAX-1){
printf("Stack Full!\n");
}else{
(*top)++;
bookArray[*top]=*bookInstance;
printf("Book has been added!\n");
}
}
struct Book* pop(int* top,struct Book* bookArray){
if(*top!=-1){
struct Book* bookInstance=malloc(sizeof(struct Book));
*bookInstance=bookArray[*top];
(*top)--;
printf("Deleted Top Most Book!\n");
return bookInstance;
}else{
printf("Empty Stack!\n");
}
}
void peep(int* top,struct Book* bookArray){
if(*top!=-1)
printf("Display Top Book\nBook Name:- %s\nBook ID:- %d\nBook Price:- %.3lf\n",(bookArray+*top)->bookName,(bookArray+*top)->bookID,(bookArray+*top)->bookPrice);
else
printf("Empty Stack!\n");
}
void getSize(int* top){
printf("Total Books: %d \n",*top+1);
}
int main(){
printf("------------------------------------------\n");
printf("Assignment 3 - Book Management using Stack\n");
printf("------------------------------------------\n");
printf("--------------------\n");
printf(" Menu \n");
printf("1 - Add a Book\n");
printf("2 - Display Top Book\n");
printf("3 - Delete Top Book\n");
printf("4 - Total Books\n");
printf("5 - Exit\n");
printf("--------------------\n");
printf("Enter Task:- ");
int i,top=-1;
struct Book* bookArray=(struct Book* )malloc(MAX*sizeof(struct Book));
scanf("%d",&i);
fflush(stdin);
while(i!=5){
switch(i){
case 1:
printf("Add a Book\nPlease enter a Book's Name:- ");
struct Book* bookInstance=(struct Book* )malloc(1*sizeof(struct Book));
scanf(" %[^\n]s",bookInstance->bookName);
fflush(stdin);
printf("Please enter Book ID:- ");
scanf("%d",&(bookInstance->bookID));
fflush(stdin);
printf("Please enter Book Price:- ");
scanf("%lf",&(bookInstance->bookPrice));
fflush(stdin);
push(bookInstance,bookArray,&top);
break;
case 2:
peep(&top,bookArray);
break;
case 3:
printf("");
struct Book* removedBook=pop(&top,bookArray);
break;
case 4:
getSize(&top);
break;
}
printf("Please enter a new task:- ");
scanf("%d",&i);
fflush(stdin);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.