language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<stdlib.h>
int count=1;
char *org(char *name)
{
char* tmp=name;
while (*tmp!='\0')
{
if(*tmp=='@')
*tmp=' ';
tmp++;
}
return name;
}
int red_num(char *file)
{
FILE *file_ptr;
char c;
file_ptr=fopen(file,"r");
if(file_ptr == NULL)
{
printf("cat: %s: No such file or directory\n",file);
return(0);
}
printf(" %d ",count);
while (1)
{
c = fgetc(file_ptr);
if(c==EOF)
break;
else
{
printf("%c", c);
if(c=='\n')
{
count+=1;
printf(" %d ",count);
}
}
}
fclose(file_ptr);
}
int red(char *file)
{
FILE *file_ptr;
char c;
file_ptr=fopen(file,"r");
if(file_ptr == NULL)
{
printf("cat: %s: No such file or directory\n",file);
return(0);
}
while (1)
{
c = fgetc(file_ptr);
if(c==EOF)
break;
else
printf("%c", c);
}
fclose(file_ptr);
}
int red_dol(char *file)
{
FILE *file_ptr;
char c;
file_ptr=fopen(file,"r");
if(file_ptr == NULL)
{
printf("cat: %s: No such file or directory\n",file);
return(0);
}
while (1)
{
c = fgetc(file_ptr);
if(c==EOF)
break;
else
{
if(c=='\n')
printf("$");
printf("%c", c);
}
}
fclose(file_ptr);
}
int main(int argc,char **argv)
{
if(strcmp(argv[1],"-n")==0)
{
int i=2;
int flag=0;
while(argv[i]!=NULL)
{
flag=1;
red_num(org(argv[i]));
i+=1;
}
count=0;
if(flag==0)
{
while(1)
{
char *st;
fgets(st,10000,stdin);
printf("%s",st);
}
}
return(0);
}
if(strcmp(argv[1],"-E")==0)
{
int i=2;
int flag=0;
while(argv[i]!=NULL)
{
flag=1;
red_dol(org(argv[i]));
i+=1;
}
if(flag==0)
{
while(1)
{
char *st;
fgets(st,10000,stdin);
printf("%s",st);
}
}
return(0);
}
else if(strcmp(argv[1],"--help")==0)
{
printf("Usage: cat [OPTION]... [FILE]...\n");
printf("Concatenate FILE(s) to standard output.\n\n");
printf("With no FILE, or when FILE is -, read standard input.\n\n");
printf(" -n, number all output lines\n\n");
printf(" -E, display $ at end of each line\n");
printf(" --help display this help and exit\n\n");
printf("cat f - g Output f's contents, then standard input, then g's contents.\n");
printf("cat Copy standard input to standard output.");
return(0);
}
else
{
char* tmp=argv[1];
if (*tmp=='-')
{
printf("cat: invalid option -- '%s'\n",argv[1]);
printf("Try 'cat --help' for more information.\n");
return(-1);
}
int i=1;
int flag=0;
while(argv[i]!=NULL)
{
flag=1;
red(org(argv[i]));
i+=1;
}
if(flag==0)
{
while(1){}
}
return(0);
}
}
|
C
|
#include <stdio.h>
//Declaring the 'Node' struct.
struct Node{
char* next;
int key;
int value;
};
//Declaring the 'LinkedList' struct
struct LinkedList{
char* head;
char* tail;
char* FP;
int numberOfBlocks;
int memSize;
int blockSize;
int listSize;
};
//Declaring the project's necessary functions.
//void Init(int M, int C);
//void Destroy();
//int Insert(int x, char* value_ptr, int value_len);
//void Delete(int x);
//char* Lookup(int x);
//void PrintList();
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
struct node
{
int data;
struct node* next;
//struct node* random;
};
int main()
{
int t,z;
scanf("%d",&t);
for(z=0;z<t;z++)
{
struct node* head1=NULL;
struct node* head2=NULL;
int n,x,y,m,i;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&x);
insert(head1,x);
}
scanf("%d",&m);
for(i=0;i<n;i++)
{
scanf("%d",&x);
insert(head2,y);
}
merge(head1,head2);
//reverse();
show();
}
return 0;
}
void insert(struct node* head,int x)
{
struct node* temp=(struct node*)malloc(sizeof(struct node));
struct node* ptr=NULL;
temp->data=x;
if(head==NULL)
{
head=temp;
temp->next=NULL;
}
else
{
ptr=head;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=temp;
temp->next=NULL;
}
}
void merge(Struct node* head1,struct node* head2)
{
}
|
C
|
#include<stdio.h>
char *strcpy (char *dest, char source[]){
int i = 0;
while(source[i] != '\0'){
dest[i] = source[i];
i++;
}
dest[i] = '\0';
}
int main(){
char source[100];
char destination[100];
int n = 1;
while (n) {
printf("Que string?\n");
//isto lê do teclado até encontrar o caracter depois do ^, neste caso, o enter.
scanf("%[^\n]", source);
getchar();
strcpy(destination ,source);
printf("%s\n", destination);
}
}
|
C
|
/* General Settings */
#define NUM_PIECES 7 // number of pieces
#define NUM_BLOCKS 4 // number of blocks in a piece
#define NUM_ROTATIONS 4 // number of rotations per piece
#define BOARD_WIDTH 10 // number of tiles wide
#define BOARD_HEIGHT 20 // number of tiles high
#define START_ROW 0
#define START_COL 60
#define PREV_ROW 20
#define PREV_COL 0
#define PPI 8 // "pixels per inch"
#define EMPTY_CELL 0
#define INIT_SPEED 30
/* Tetromino Piece Definitions */
#define TETROMINO_I 0
#define TETROMINO_L 1
#define TETROMINO_J 2
#define TETROMINO_O 3
#define TETROMINO_S 4
#define TETROMINO_T 5
#define TETROMINO_Z 6
/* Game states */
#define TITLE 0
#define NORMAL 1
#define GAMEOVER 2
/* Struture representing a tetromino */
typedef struct {
/**
* X goes left to right.
* Y goes top to bottom.
* The size of the array is 4x4, specified in the NUM_BLOCKS constant.
*/
u16 color;
int cells[NUM_BLOCKS][NUM_BLOCKS];
int rotation;
int x;
int y;
int size;
int type;
} TETROMINO;
/* External variables */
extern int state;
extern const int PIECES[NUM_PIECES][NUM_ROTATIONS][NUM_BLOCKS][2];
extern u16 board[BOARD_HEIGHT][BOARD_WIDTH];
extern TETROMINO nextBlock;
extern TETROMINO currentBlock;
void refresh();
void reset();
void startGame();
void endGame();
void setBlock(int type, TETROMINO *block, int rotation);
void moveBlock(int dx, int dy);
void drawBlock();
void drawPreview();
void blockMoved();
void redraw(int r, int c);
TETROMINO makeBlock();
void rotateBlock(int clockwise);
int collides(TETROMINO newBlock);
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include "a2.h"
void free_array (struct Double_Array* new_struct){
int i;
for ( i = 0; i < new_struct->rowsize; i++) {
free(new_struct -> array[i]); /* free rows */
}
free(new_struct -> array); /* free the array */
free(new_struct); /* free the struct itself */
}
|
C
|
/*xsh_process_ring.c - process_ring */
#include <xinu.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <process_ring.h>
/*------------------------------------------------------------------------
* xsh_process_ring - Count downs a number equal to number of processes times the number of rounds.
*------------------------------------------------------------------------
*/
shellcmd xsh_process_ring(int nargs, char *args[]) {
/* Output info for '--help' argument */
int num_process = 4;
int rounds = 5;
char version[6];
int inbox[NPROC];
strncpy(version, "work", 6);
if (nargs == 2 && (strncmp(args[1], "--help", 7) == 0 || strncmp(args[1], "-h", 7) == 0)) {
printf("Usage: %s\n\n", args[0]);
printf("Description:\n");
printf("\tThe processes coordinate with each other to count down a number from its starting value and prints the value after each decrementation.\n");
printf("\tThe initial value of the number is set to a value which is equal to multiplication of number of processes and number of rounds.\n");
printf("\tIn each round each processes run in a order and decrement the value of the number by 1 and displays the number.\n");
printf("\tWhen all the rounds are finished the final value of the number is zero.\n");
printf("Options (can be used in combination):\n");
printf("\t-p or --processes int\tSets the number of processes. Default value is 4. Maximum is 100.\n");
printf("\t-r or --round int\tSets the number of rounds. Default value is 5.\n");
printf("\t-v or --version mode\tHere mode can be worok, hang, loop and chaos. Default mode is work.\n");
printf("\t--help\tdisplay this help and exit\n");
return 0;
}
if (nargs > 1){
int i;
for(i=1; i < nargs; i++){
if (strncmp(args[i], "--processes", 15) == 0 || strncmp(args[i], "-p", 15) == 0){
num_process = atoi(args[++i]);
if(num_process <= 0 || num_process > NPROC){
fprintf(stderr, "%s: Please enter a valid value for number of processes.\n", args[0]);
fprintf(stderr, "Try %s: --help or -h for more information\n", args[0]);
return 1;
}
}
else if (strncmp(args[i], "--round", 15) == 0 || strncmp(args[i], "-r", 15) == 0){
rounds = atoi(args[++i]);
if(rounds <= 0){
fprintf(stderr, "%s: The value of rounds exceeds maximum integer value.\n", args[0]);
fprintf(stderr, "Try %s: --help or -h for more information\n", args[0]);
return 1;
}
}
else if (strncmp(args[i], "--version", 15) == 0 || strncmp(args[i], "-v", 15) == 0){
if(strncmp(args[i+1], "work", 15) == 0 || strncmp(args[i+1], "hang", 15) == 0 || strncmp(args[i+1], "loop", 15) == 0 || strncmp(args[i+1], "chaos", 15) == 0){
strncpy(version, args[++i], 6);
}
else{
fprintf(stderr, "%s: Invalid mode. Please enter a valid mode.\n", args[0]);
fprintf(stderr, "Try %s: --help or -h for more information\n", args[0]);
return 1;
}
}
else{
fprintf(stderr, "%s: Invalid Arguments.\n", args[0]);
fprintf(stderr, "Try %s: --help or -h for more information\n", args[0]);
return 1;
}
}
int sum = 0;
for (i = 0; i < num_process; i++){
sum+=rounds;
if(sum <= 0){
fprintf(stderr, "%s: Invalid Arguments.\n", args[0]);
fprintf(stderr, "Try %s: --help or -h for more information\n", args[0]);
return 1;
}
}
}
sid32 semaphores[num_process];
int i;
char processName[num_process];
printf("Number of Processes: %d\n", num_process);
printf("Number of Rounds: %d\n", rounds);
if (strncmp(version, "work", 15) == 0 || strncmp(version, "hang", 15) == 0 || strncmp(version, "loop", 15) == 0){
for(i = 0; i < num_process; i++){
inbox[i] = num_process * rounds;
if (i == (num_process-1) && (strncmp(version, "work", 15) == 0 || strncmp(version, "loop", 15) == 0)){
semaphores[i] = semcreate(1);
}
else{
semaphores[i] = semcreate(0);
}
}
for(i = 0; i < num_process; i++){
sprintf(processName, "process%d",i);
if(i == 0){
resume(create(process_rounds, 1024, 20, processName, 7, semaphores[i], semaphores[num_process-1], i, num_process, rounds, version, inbox));
}
else{
resume(create(process_rounds, 1024, 20, processName, 7, semaphores[i], semaphores[i-1], i, num_process, rounds, version, inbox));
}
}
}
if (strncmp(version, "chaos", 15) == 0){
for(i = 0; i < num_process; i++){
inbox[i] = num_process * rounds;
sprintf(processName, "process%d", i);
resume(create(process_rounds_without_semaphore, 1024, 20, processName, 3, i, rounds, inbox));
}
}
if(strncmp(version, "hang", 15) == 0){
wait(semaphores[0]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <setjmp.h>
#include "problem.h"
jmp_buf out;
tProblema *problemAB(tProblema *No)
{
int linhaAux=0, colunaAux=0, numPassosAux = 0, auxMovimento = 0, i, j;
linhaAux = No->linha0;
colunaAux = No->coluna0;
No = createVisited(No);
if(No->resposta != -1)
{
if(!setjmp(out))
{
if(strcmp(&No->problema, "A") == 0)
No = solveProblemAC(No, linhaAux, colunaAux, &numPassosAux);
if(strcmp(&No->problema, "B") == 0)
No = solveProblemBD(No, linhaAux, colunaAux, &numPassosAux);
}
}
if(No->visited[No->numPassos-1][0] == -1 && No->visited[No->numPassos-1][1]== -1) /*se nao encontrou um camino com o numero de passos pretendido */
No->resposta = -1;
return No;
}
tProblema *problemCD(tProblema *No)
{
int i, j, exit = 0;
int linhaAux=0, colunaAux=0, numPassosAux = 0;
No = createVisited(No);
for(i = 0 ; i < No->linhas && exit == 0 ; i++)
{
for( j = 0; j < No->colunas && exit == 0; j++)
{
numPassosAux = 0;
linhaAux = i;
colunaAux = j;
No->linha0 = linhaAux;
No->coluna0 = colunaAux;
if(!setjmp(out))
{
if(strcmp(&No->problema, "C") == 0)
{
No = solveProblemAC(No, linhaAux, colunaAux, &numPassosAux);
}
if(strcmp(&No->problema, "D") == 0)
No = solveProblemBD(No, linhaAux, colunaAux, &numPassosAux);
}
if(No->visited[No->numPassos-1][0] == -1 && No->visited[No->numPassos-1][1]== -1)
No->resposta = -1;
if(No->resposta != -1)
exit = 1;
}
}
if(No->resposta == -1)
{
No->linha0 = No->linha0Aux;
No->coluna0 = No->coluna0Aux;
}
return No;
}
tProblema *createVisited(tProblema *No)
{
int i, colunas = 2;
No->alocaV = 1;
No->visited = (int**)malloc((No->numPassos) * sizeof(int*));
if(No->visited == NULL)
exit(0);
for(i = 0; i < No->numPassos; i++)
{
No->visited[i] = (int*) malloc(colunas * sizeof(int));
if(No->visited[i] == NULL)
exit(0);
}
for(i = 0; i < No->numPassos; i++)
{
No->visited[i][0] = -1;
No->visited[i][1] = -1;
}
return No;
}
tProblema *solveProblemAC(tProblema *No, int linhaP, int colunaP, int *numPassosAux)
{
int linhaI, colunaI, linhaF, colunaF, i, j;
linhaI = linhaP-1;
colunaI = colunaP-1;
linhaF = linhaP+1;
colunaF = colunaP+1;
if(*numPassosAux == No->numPassos)
{
No->resposta = No->numPassos;
longjmp(out, 1); /* salta para a funçao de que foi chamada (ProblemAB ou ProblemaCD) */
}
if((*numPassosAux != No->numPassos))
{
if(linhaP-1 <= 0)
linhaI = 0;
if(colunaP-1 <= 0)
colunaI = 0;
if(linhaP+1 >= No->linhas)
linhaF = linhaP;
if(colunaP+1 >= No->colunas)
colunaF = colunaP;
for(i = linhaI; i <= linhaF ; i++)
{
for(j = colunaI; j <= colunaF ; j++)
{
if(No->matriz[i][j] > No->matriz[linhaP][colunaP])
{
if(visited(No, *numPassosAux, i, j) == 0) /* se o caminho nao tiver ja passado por esse ponto*/
{
No->visited[*numPassosAux][0] = i;
No->visited[*numPassosAux][1] = j;
*numPassosAux = *numPassosAux + 1;
solveProblemAC(No, i, j, numPassosAux);
}
}
}
}
}
*numPassosAux = *numPassosAux - 1; /* diminui o numero de passos para fazer o backtracking */
if(*numPassosAux == -1)
longjmp(out, 1);
for(i = *numPassosAux; i < No->numPassos; i++) /*limpa a matriz visited */
{
No->visited[i][0] = -1;
No->visited[i][1] = -1;
}
}
int visited(tProblema *No, int numPassos, int linha, int coluna)
{
int i;
for(i = 0; i < numPassos; i++)
{
if(linha == No->visited[i][0] && coluna == No->visited[i][1])
return 1; /* se ja passou nesse ponto */
}
return 0;
}
tProblema *solveProblemBD(tProblema *No, int linhaP, int colunaP, int *numPassosAux)
{
int linhaI, colunaI, linhaF, colunaF, i, j;
linhaI = linhaP-1;
colunaI = colunaP-1;
linhaF = linhaP+1;
colunaF = colunaP+1;
if(*numPassosAux == No->numPassos)
{
No->resposta = No->numPassos;
longjmp(out, 1);
}
if((*numPassosAux != No->numPassos))
{
if(linhaP-1 <= 0)
linhaI = 0;
if(colunaP-1 <= 0)
colunaI = 0;
if(linhaP+1 >= No->linhas)
linhaF = linhaP;
if(colunaP+1 >= No->colunas)
colunaF = colunaP;
for(i = linhaI; i <= linhaF ; i++)
{
for(j = colunaI; j <= colunaF ; j++)
{
if(No->matriz[i][j] % 2 == 0)
{
if( (visited(No, *numPassosAux, i, j) == 0) && ((i!=No->linha0) || (j!=No->coluna0)))
{
No->visited[*numPassosAux][0] = i;
No->visited[*numPassosAux][1] = j;
*numPassosAux = *numPassosAux + 1;
solveProblemBD(No, i, j, numPassosAux);
}
}
}
}
}
*numPassosAux = *numPassosAux - 1;
if(*numPassosAux == -1)
longjmp(out, 1);
for(i = *numPassosAux; i < No->numPassos; i++)
{
No->visited[i][0] = -1;
No->visited[i][1] = -1;
}
}
tProblema *problemE(tProblema *No)
{
int i, j, z, exit = 0;
int linhaAux=0, colunaAux=0, numPassosAux = 0, maiorNumPassos = 0, maiorCaminho = 0, maxNumPassos;
maxNumPassos = No->linhas * No->colunas - 1;
No = createVisitedE(No);
No = createBiggestGlobalPath(No);
No = createDP(No);
for(i = 0 ; i < No->linhas; i++)
{
for( j = 0; j < No->colunas; j++)
{
maiorNumPassos = 0;
numPassosAux = 0;
linhaAux = i;
colunaAux = j;
No->linha0Aux = linhaAux;
No->coluna0Aux = colunaAux;
if(!setjmp(out))
{
if(No->dp[i][j] == -1)
No = solveProblemE(No, linhaAux, colunaAux, &numPassosAux, &maiorNumPassos, &maiorCaminho);
}
if(maiorCaminho == maxNumPassos)
{
i = No->linhas;
j = No->colunas;
}
}
}
if(maiorCaminho == 0)
No->resposta = -1;
return No;
}
tProblema *createVisitedE(tProblema *No)
{
int i, colunas = 2, maxNumPassos;
No->alocaV = 1;
maxNumPassos = No->linhas * No->colunas -1;
No->visited = (int**)malloc((maxNumPassos) * sizeof(int*));
if(No->visited == NULL)
exit(0);
for(i = 0; i < maxNumPassos; i++)
{
No->visited[i] = (int*) malloc(colunas * sizeof(int));
if(No->visited[i] == NULL)
exit(0);
}
for(i = 0; i < maxNumPassos; i++)
{
No->visited[i][0] = -1;
No->visited[i][1] = -1;
}
return No;
}
tProblema *createBiggestGlobalPath(tProblema *No)
{
int i, colunas = 2, maxNumPassos;
No->alocaV = 1;
maxNumPassos = No->linhas * No->colunas -1;
No->maiorCaminhoGeral = (int**)malloc((maxNumPassos) * sizeof(int*));
if(No->maiorCaminhoGeral == NULL)
exit(0);
for(i = 0; i < maxNumPassos; i++)
{
No->maiorCaminhoGeral[i] = (int*) malloc(colunas * sizeof(int));
if(No->maiorCaminhoGeral[i] == NULL)
exit(0);
}
for(i = 0; i < maxNumPassos; i++)
{
No->maiorCaminhoGeral[i][0] = -1;
No->maiorCaminhoGeral[i][1] = -1;
}
return No;
}
tProblema *solveProblemE(tProblema *No, int linhaP, int colunaP, int *numPassosAux, int *maiorNumPassos, int *maiorCaminho)
{
int linhaI, colunaI, linhaF, colunaF, i, j, flag = 0, maxNumPassos;
linhaI = linhaP-1;
colunaI = colunaP-1;
linhaF = linhaP+1;
colunaF = colunaP+1;
maxNumPassos = No->linhas * No->colunas - 1;
if(*maiorNumPassos > 0 && linhaP == No->linha0Aux && colunaP == No->coluna0Aux)
{
No->resposta = *maiorNumPassos;
longjmp(out, 1);
}
if(*numPassosAux == maxNumPassos)
{
No->resposta = *numPassosAux;
longjmp(out, 1);
}
if(linhaP-1 <= 0)
linhaI = 0;
if(colunaP-1 <= 0)
colunaI = 0;
if(linhaP+1 >= No->linhas)
linhaF = linhaP;
if(colunaP+1 >= No->colunas)
colunaF = colunaP;
for(i = linhaI; i <= linhaF ; i++)
{
for(j = colunaI; j <= colunaF ; j++)
{
if(No->matriz[i][j] > No->matriz[linhaP][colunaP])
{
if(visited(No, *numPassosAux, i, j) == 0)
{
flag = 1;
No->visited[*numPassosAux][0] = i;
No->visited[*numPassosAux][1] = j;
*numPassosAux = *numPassosAux + 1;
solveProblemE(No, i, j, numPassosAux, maiorNumPassos, maiorCaminho);
}
}
}
}
if(flag == 0)
{
if(*numPassosAux > *maiorNumPassos)
{
*maiorNumPassos = *numPassosAux;
if(*maiorNumPassos > *maiorCaminho) /* compara com o maior caminho ate a data */
{
*maiorCaminho = *maiorNumPassos;
No->resposta = *maiorCaminho;
No->linha0 = No->linha0Aux;
No->coluna0 = No->coluna0Aux;
for(i = 0; i < *maiorNumPassos; i++)
{
No->maiorCaminhoGeral[i][0] = No->visited[i][0];
No->maiorCaminhoGeral[i][1] = No->visited[i][1];
}
}
}
}
*numPassosAux = *numPassosAux - 1;
if(*numPassosAux == -1)
longjmp(out, 1);
for(i = *numPassosAux; i < maxNumPassos; i++)
{
No->visited[i][0] = -1;
No->visited[i][1] = -1;
}
No->dp[linhaP][colunaP] = 1;
}
tProblema *problemF(tProblema *No)
{
int i, j, z, exit = 0;
int linhaAux=0, colunaAux=0, numPassosAux = 0, maiorNumPassos = 0, maiorCaminho = 0, maxNumPassos, tudoPar = 0;
maxNumPassos = No->linhas * No->colunas - 1;
No = createVisitedE(No);
No = createBiggestGlobalPath(No);
No = createDP(No);
for(i = 0 ; i < No->linhas; i++)
{
for( j = 0; j < No->colunas; j++)
{
maiorNumPassos = 0;
numPassosAux = 0;
linhaAux = i;
colunaAux = j;
No->linha0Aux = linhaAux;
No->coluna0Aux = colunaAux;
tudoPar = checkPares(No); /* verifica se a matriz nao e toda par para nao ter que encontrar o caminho atraves do DFS para poupar tempo */
if(tudoPar == maxNumPassos+1)
{
maiorCaminho = maxNumPassos;
No->resposta = maxNumPassos;
No->linha0 = 0;
No->coluna0 = 0;
No = addCaminhoGeral(No);
}else{
if(!setjmp(out))
{
if(No->dp[i][j] == -1)
No = solveProblemF(No, linhaAux, colunaAux, &numPassosAux, &maiorNumPassos, &maiorCaminho);
}
}
if(maiorCaminho == maxNumPassos)
{
i = No->linhas;
j = No->colunas;
}
}
}
if(maiorCaminho == 0)
No->resposta = -1;
return No;
}
tProblema *createDP(tProblema *No)
{
int i, j;
No->dp = (int**)malloc((No->linhas) * sizeof(int*));
if(No->dp == NULL)
exit(0);
for(i = 0; i < No->linhas; i++)
{
No->dp[i] = (int*) malloc(No->colunas * sizeof(int));
if(No->dp[i] == NULL)
exit(0);
}
for(i = 0; i < No->linhas; i++)
{
for(j = 0; j < No->colunas; j++)
No->dp[i][j] = -1;
}
return No;
}
int checkPares(tProblema *No)
{
int i, j, pares = 0;
for(i = 0; i < No->linhas; i++)
{
for(j = 0; j < No->colunas; j++)
{
if(No->matriz[i][j] % 2 == 0)
pares++; /* numero de pares namatriz */
}
}
return pares;
}
tProblema *addCaminhoGeral(tProblema *No)
{
int i, j, z=0;
for(i = 0; i < No->linhas ; i++)
{
if(i % 2 == 0)
{
for(j = 1; j < No->colunas ; j++)
{
No->maiorCaminhoGeral[z][0] = i;
No->maiorCaminhoGeral[z][1] = j;
z++;
}
}else{
for(j = No->colunas-1; j >= 0; j--)
{
No->maiorCaminhoGeral[z][0] = i;
No->maiorCaminhoGeral[z][1] = j;
z++;
}
}
}
return No;
}
tProblema *solveProblemF(tProblema *No, int linhaP, int colunaP, int *numPassosAux, int *maiorNumPassos, int *maiorCaminho)
{
int linhaI, colunaI, linhaF, colunaF, i, j, flag = 0, maxNumPassos;
linhaI = linhaP-1;
colunaI = colunaP-1;
linhaF = linhaP+1;
colunaF = colunaP+1;
maxNumPassos = No->linhas * No->colunas - 1;
if(*maiorNumPassos > 0 && linhaP == No->linha0Aux && colunaP == No->coluna0Aux)
{
No->resposta = *maiorNumPassos;
longjmp(out, 1);
}
if(*numPassosAux == maxNumPassos)
{
No->resposta = *numPassosAux;
longjmp(out, 1);
}
if(linhaP-1 <= 0)
linhaI = 0;
if(colunaP-1 <= 0)
colunaI = 0;
if(linhaP+1 >= No->linhas)
linhaF = linhaP;
if(colunaP+1 >= No->colunas)
colunaF = colunaP;
for(i = linhaI; i <= linhaF ; i++)
{
for(j = colunaI; j <= colunaF ; j++)
{
if(No->matriz[i][j] % 2 == 0)
{
if(visited(No, *numPassosAux, i, j) == 0 && (i != No->linha0Aux || j != No->coluna0Aux))
{
flag = 1;
No->visited[*numPassosAux][0] = i;
No->visited[*numPassosAux][1] = j;
*numPassosAux = *numPassosAux + 1;
solveProblemF(No, i, j, numPassosAux, maiorNumPassos, maiorCaminho);
}
}
}
}
if(flag == 0)
{
if(*numPassosAux > *maiorNumPassos)
{
*maiorNumPassos = *numPassosAux;
if(*maiorNumPassos > *maiorCaminho)
{
*maiorCaminho = *maiorNumPassos;
No->resposta = *maiorCaminho;
No->linha0 = No->linha0Aux;
No->coluna0 = No->coluna0Aux;
for(i = 0; i < *maiorNumPassos; i++)
{
No->maiorCaminhoGeral[i][0] = No->visited[i][0];
No->maiorCaminhoGeral[i][1] = No->visited[i][1];
}
}
}
}
*numPassosAux = *numPassosAux - 1;
if(*numPassosAux == -1)
longjmp(out, 1);
for(i = *numPassosAux; i < maxNumPassos; i++)
{
No->visited[i][0] = -1;
No->visited[i][1] = -1;
}
No->dp[linhaP][colunaP] = 1;
}
|
C
|
/**
* Copyright (C) 2019-2020 Tristan
* For conditions of distribution and use, see copyright notice in the COPYING file.
*/
#include "thread_manager.h"
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "base/global_settings.h"
#define THREADS_STEP_SIZE 16
static unsigned max_threads;
static unsigned thread_count;
static unsigned threads_size; /* the size of */
static pthread_t *threads = NULL;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static unsigned umin(unsigned a, unsigned b) {
return a > b ? b : a;
}
int thread_manager_setup(config_t config) {
const char *max_child_threads_s = config_get(config, "max-child-threads");
if (max_child_threads_s) {
if (sscanf(max_child_threads_s, "%u", &max_threads) != 1 || max_threads == 0) {
fprintf(stderr, "\x1b[31m[Config] Invalid number: \"%s\" (it should be 1 to 2147483648)\x1b[0m\n", max_child_threads_s);
return 0;
}
} else {
max_threads = 100;
fprintf(stderr, "\x1b[33m[Config] Config option 'max-child-threads' is missing! Setting to default: %u\x1b[0m\n", max_threads);
}
thread_count = 0;
threads_size = umin(max_threads, THREADS_STEP_SIZE);
threads = calloc(threads_size, sizeof(pthread_t));
return 1;
}
void thread_manager_wait_or_kill(void) {
struct timespec wait_time;
wait_time.tv_sec = 0;
wait_time.tv_nsec = 10000;
size_t retries = 0;
while (thread_count > 0) {
nanosleep(&wait_time, NULL);
wait_time.tv_nsec = 100000;
if (++retries == 10) {
pthread_mutex_lock(&mutex);
if (thread_count > 0) {
printf("ThreadManager: Killing all %u thread(s) remaining...\n", thread_count);
pthread_t *the_threads = threads;
threads = NULL;
size_t i;
for (i = 0; i < thread_count; i++) {
pthread_cancel(the_threads[i]);
nanosleep(&wait_time, NULL);
pthread_kill(the_threads[i], SIGQUIT);
}
free(the_threads);
}
pthread_mutex_unlock(&mutex);
break;
}
}
free(threads);
}
/* -2 = pthread error
-1 = allocation error
0 = thread pool full.
1 = success.
*/
int thread_manager_add(void *(*start_routine) (void *), void *arguments) {
pthread_mutex_lock(&mutex);
if (thread_count == threads_size) {
if (threads_size != max_threads) {
pthread_t *new_threads = realloc(threads, umin(threads_size + THREADS_STEP_SIZE, max_threads));
if (new_threads == NULL) {
pthread_mutex_unlock(&mutex);
puts("ThreadManager: allocation error.");
return -1;
}
threads = threads;
} else {
pthread_mutex_unlock(&mutex);
puts("ThreadManager: thread pool full.");
return 0;
}
}
if (pthread_create(&threads[thread_count], NULL, start_routine, arguments) != 0) {
pthread_mutex_unlock(&mutex);
puts("ThreadManager: pthread_create error.");
return -2;
}
thread_count += 1;
pthread_mutex_unlock(&mutex);
return 1;
}
void thread_manager_finished(void) {
pthread_t current = pthread_self();
pthread_mutex_lock(&mutex);
size_t i;
for (i = 0; i < thread_count; i++) {
if (threads[i] == current) {
if (i == thread_count - 1) {
threads[i] = 0;
} else {
memcpy(threads+i, threads+i+1, thread_count - i - 1);
}
thread_count -= 1;
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
return;
}
}
fputs("ThreadManager: Couldn't find thread in thread pool[?][!]\n", stderr);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
|
C
|
// greatest common divisor and lowest common multiple
// Input:
// First line: Enter a single integer n to represent the number of positive integers to enter
// Second line: The input depends on the number of n to determine the need to enter a few positive integers,
// separated by a blank key
// Output:
// The largest common factor and the least common multiple are separated by a blank key.
// Made by Stanley Fang
// warning: This code is not completed
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int input = 0;
int lcm = 0;
int m, n;
int i, j;
// input
printf("How many number you gonna enter?\n");
scanf("%d", &input);
if (input <= 1)
{
printf("error: wrong value\n");
system("pause");
return 0;
}
// array
int a[input];
printf("Now enter your numbers, seperate by space: \n");
scanf("%d", &a[input]);
// loop
m = a[0];
for (i = 0; i < input; i++)
{
j = i + 1;
n = a[j];
//lcm = m * n;
//lcm *= n;
if (j == input)
break;
while (m != 0 && n != 0)
{
if (m > n)
m = m % n;
else if (n > m)
n = n % m;
}
if (m == 0)
m = n;
}
//ans
//lcm = all array times / m
printf("gcd = %d\n", m);
system("pause");
return 0;
}
|
C
|
#include "mystack.h"
#define Share 100
struct sharestack
{
int data[Share];
int top1;
int top2;
}S_S;
void S_Initialize(sharestack &S)//ʼջָ벻ָκԪ
{
S.top1=-1;
S.top2=Share;
}
bool S_StackEmpty(sharestack S)//жջǷΪ
{
if(S.top1==-1&&S.top2==Share)
return true;
else
return false;
}
bool S_Push(sharestack &S,int a,bool choose)//int aջ,boolΪ1ջΪ0Ҳջ
//ҪSҪõַʽͬ
{
if(S.top2-S.top1==1)
return false;
if(choose)
S.data[++S.top1]=a;
else
S.data[--S.top2]=a;
return true;
}
bool S_Pop(sharestack &S,int &x,bool choose)
{
if(choose)
{
if(S.top1==-1)
return false;
x=S.data[S.top1--];
return true;
}
else
{
if(S.top2==Share)
return false;
x=S.data[S.top2++];
return true;
}
}
|
C
|
#include <stdio.h>
int main(void)
{
int nAge = 0;
scanf("%d", &nAge);
if (nAge >= 20)
printf("%d\n", nAge);
nAge = 20;
printf("Final: %d\n", nAge);
return 0;
}
|
C
|
/*ijϷнսʵ˺㹫ʽΪ
ʵ˺ = ˺ * + 100/100
˺256Ҫҵӡʵ˺
*/
#include <stdio.h>
#include <stdlib.h>
// 1.Ҫ弸 ==> ʵ˺ҵ˺
// 2.Ӧʲôͣ ==> double int double
int main()
{
double shanghai_fact; //ʵ˺
int strength; //
double shanghai_max = 256; //˺
//ϣʼùʽ
printf("뵱ǰɫ");
//&ȡַ
scanf("%d", &strength);
//ùʽ
shanghai_fact = shanghai_max * (strength + 100)/100;
printf("ʵ˺Ϊ%.2lf", shanghai_fact); //ֵ
return 0;
}
|
C
|
/* flash_wcet - try and find the worst latency for writing an image to flash
(c) burin 2020
For fun, but no profit, try running this on a remote
machine while testing:
watch rsync -avh 10.0.0.17:~/ecen5623/simple-capture/wcet/*.ppm .
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "../buffer.h"
#include "../dumptools.h"
#include "../timetools.h"
int printf_on = 0;
#define TEST_ITERS (1800 * 10)
#define NUM_IMAGES 10
#define BBP_PPM 3
int main() {
buffer_t random_images[NUM_IMAGES];
for (int i=0; i<NUM_IMAGES; i++) {
allocate_buffer(&random_images[i], BBP_PPM);
}
for (int j=0; j < NUM_IMAGES; j++) {
unsigned char* p = random_images[j].start;
for (int i=0; i < random_images[j].size; i++) {
*p++ = rand() % 256;
}
}
int random_index = 0;
struct timespec start_time;
struct timespec end_time;
struct timespec timestamp;
struct timespec last_timestamp;
last_timestamp.tv_sec = 0;
struct timespec diff_time;
int max_ms = 0;
int total_count = 0;
struct timespec write_frequency;
write_frequency.tv_sec = 0;
write_frequency.tv_nsec = 100000000; //100ms, 10Hz
clock_gettime(CLOCK_MONOTONIC, &start_time);
for (int i=0; i < TEST_ITERS; i++) {
clock_gettime(CLOCK_MONOTONIC, ×tamp);
if (last_timestamp.tv_sec != 0) {
timespec_subtract(&diff_time, ×tamp, &last_timestamp);
int diff_ms = diff_time.tv_sec * 1000 + diff_time.tv_nsec/1000000;
if (diff_ms > max_ms) {
max_ms = diff_ms;
printf("New max found: %dms\n", max_ms);
}
}
last_timestamp = timestamp;
//Since flash is so slow, we don't care if nanosleep lags
nanosleep(&write_frequency, NULL);
dump_rgb_raw_buffer(&random_images[random_index]);
random_index++;
if (random_index == NUM_IMAGES) {
random_index = 0;
}
total_count++;
}
clock_gettime(CLOCK_MONOTONIC, &end_time);
if (timespec_subtract(&diff_time, &end_time, &start_time) == 1) {
printf("negative!\n");
} else {
printf("Total elapsed time: %llds\n", (long long)diff_time.tv_sec);
printf("average write time per (%d bytes) image: %fs\n", random_images[0].size, (float)diff_time.tv_sec/total_count);
}
}
|
C
|
#ifndef PRACTICAL_H_
#define PRACTICAL_H_
#include <stdbool.h>
#include <stdio.h>
#include <sys/socket.h>
// Handle error with user msg
void DieWithUserMessage(const char *msg, const char *detail);
// Handle error with sys msg
void DieWithSystemMessage(const char *msg);
// Print socket address
void PrintSocketAddress(const struct sockaddr *address, FILE *stream);
// Test socket address equality
bool SockAddrsEqual(const struct sockaddr *addr1, const struct sockaddr *addr2);
// Create, bind, and listen a new TCP server socket
int SetupTCPServerSocket(const char *service);
// Accept a new TCP connection on a server socket
int AcceptTCPConnection(int servSock);
// Handle new TCP client
void HandleTCPClient(int clntSocket, int N);
// Create and connect a new TCP client socket
int SetupTCPClientSocket(const char *server, const char *service);
HttpMessage readRequest(int sockfd); //what is the logic inside readRequest?
HttpRequest parseRequest(HttpMessage m); // what logic?
HttpResponse serveRequest(HttpRequest req);
returnResponse(sockfd, res);
enum sizeConstants {
MAXSTRINGLENGTH = 128,
BUFSIZE = 8192,
MAXHEADERS = 100,
};
// struct InitialLine{
// char* method[2] = "GET";
// char* uri;
// char* httpVersion[9] = "TritonHTTP"
// };
// typedef struct InitialLine InitialLine;
// struct HttpHeader{
// char* fieldName[MAXSTRINGLENGTH];
// char* fieldValue[MAXSTRINGLENGTH];
// };
// typedef struct HttpHeader HttpHeader;
struct HttpRequest{
/* GET /images/myimg.jpg HTTP/1.1 */
char * messageTokens[5];
char * method = messageTokens[0];
char * uri = messageTokens[1];
char * httpVersion= messageTokens[2];
char * host = messageTokens[4];
// HttpHeader headers[MAXHEADERS];
};
typedef struct HttpRequest HttpRequest;
struct HttpResponse{
/* HTTP/1.1 200 OK */
char * status;
char * server;
char * lastModified; // Last-Modified: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT (required only if return type is 200)
char * contentType; // (required if return type is 200; if you create a custom error page, you can set this to ‘text/html’)
char * contentLength; // (required if return type is 200; if you create a custom error page, you can set this to the length of that page)
//HttpHeader headers[MAXHEADERS];
/*
200 OK: The request was successful
400 Client Error: The client sent a malformed or invalid request that the server doesn’t understand
403 Forbidden: The request was not served because the client wasn’t allowed to access the requested content
404 Not Found: The requested content wasn’t there
500 Server Error: An error occured internal to the server. In this project we do not implement plugins, server-side scripting, or other extensions, and so you shouldn’t expect to use this return code
*/
};
typedef struct HttpResponse HttpResponse;
struct HttpMessage{
// uint16_t currRead;
uint16_t numBytes;
uint8_t error;
char* buffer[BUFSIZE];
};
typedef struct HttpMessage HttpMessage;
#endif // PRACTICAL_H_
|
C
|
#include "includes.h"
static SDL_Surface *screen;
toggleFullScreen() {
SDL_Surface *screen;
screen = SDL_GetVideoSurface();
SDL_WM_ToggleFullScreen(screen);
} /* toggleFullScreen */
void *doBlit (int srcX,
int srcY,
int srcW,
int srcH,
int destX,
int destY,
int destW,
int destH,
SDL_Surface *bmp) {
SDL_Rect src, dest;
src.x = srcX;
src.y = srcY;
src.w = srcW;
src.h = srcH;
dest.x = destX;
dest.y = destY;
dest.w = destW;
dest.h = destH;
SDL_BlitSurface(bmp, &src, screen, &dest);
} /* doBlit */
/*
Function to Load, Convert and then set color key of a bmp file.
if RGB is 0,0,0 do not set a color key for that bmp.
*/
static SDL_Surface *fetchBitmap(char *filespec, int r, int g, int b) {
SDL_Surface *rawBMP, *convertedBMP;
fprintf(stderr, "loading \"%s\"\n", filespec);
rawBMP = SDL_LoadBMP(filespec);
if (!rawBMP) {
fprintf (stderr, "Unable to load bitmap %s\n", filespec);
myExit (-10);
} /* if */
fprintf(stderr, "converting \"%s\"\n", filespec);
convertedBMP = SDL_DisplayFormat(rawBMP);
if (!convertedBMP) {
fprintf (stderr, "Unable to convert bitmap %s\n", filespec);
myExit (-10);
} /* if */
if (!((r == 0) && (g == 0) && (b == 0)))
SDL_SetColorKey(convertedBMP, SDL_SRCCOLORKEY, (SDL_MapRGB(convertedBMP->format, r, g, b)));
SDL_FreeSurface(rawBMP);
return(convertedBMP);
} /* fetchBitmap */
int ScreenThreadEntryPoint(void *data) {
char *threadname;
SDL_Surface *arenaBMP, *scoreboardBMP, *fontBMP;
SDL_Surface *shotBMP[8], *zombieBMP[8], *playerBMP[8];
SDL_Surface *wordPane, *scorePane;
SDL_Color scoreColor;
threadname = (char *) data;
char buffer[1025];
char scoreString[14];
int i;
zlist_t *currentZombie;
screen = SDL_SetVideoMode(800, 700, 16, SDL_DOUBLEBUF);
if (screen == NULL) {
fprintf(stderr, "Unable to set video mode: %s\n", SDL_GetError());
myExit (-10);
} /* if */
arenaBMP = fetchBitmap("bitmaps/arena.bmp", 0,0,0);
scoreboardBMP = fetchBitmap("bitmaps/scoreboard.bmp", 0,0,0);
fontBMP = fetchBitmap("bitmaps/zombieFont.bmp", 255,255,255);
scoreColor.r = 0;
scoreColor.b = 70;
scoreColor.g = 90;
for (i=0; i<9; i++) {
sprintf((char *) &buffer, "bitmaps/Player.%i.bmp", i);
playerBMP[i] = fetchBitmap(buffer, 255, 255, 255);
sprintf((char *) &buffer, "bitmaps/Zombie.%i.bmp", i);
zombieBMP[i] = fetchBitmap(buffer, 255, 255, 255);
sprintf((char *) &buffer, "bitmaps/Shot.%i.bmp", i);
shotBMP[i] = fetchBitmap(buffer, 255, 255, 255);
} /* for */
/* loop until main() sets the flag */
while(!exit_flag) {
/* update the player */
updatePlayerPosition (playerBMP[player.direction]->h, playerBMP[player.direction]->w);
/* update the shot */
if (shot.show)
updateShotPosition();
/* update the zombies */
currentZombie = zombieList;
while(currentZombie) {
updateZombiePosition(currentZombie->zombie,
zombieBMP[currentZombie->zombie->direction]->w,
zombieBMP[currentZombie->zombie->direction]->h);
currentZombie = currentZombie->next;
} /* while */
/* check for collisions */
collisionDetect();
/* draw background and score board */
doBlit(0, 0, arenaBMP->w, arenaBMP->h, 0, 0, arenaBMP->w, arenaBMP->h, arenaBMP);
doBlit(0, 0, scoreboardBMP->w, scoreboardBMP->h, 0,600, scoreboardBMP->w, scoreboardBMP->h, scoreboardBMP);
/* draw the word */
wordPane = TTF_RenderText_Blended(wordFont, word, wordColor);
doBlit(0, 0, wordPane->w, wordPane->h, 130, 602, wordPane->w, wordPane->h, wordPane);
/* draw the score */
sprintf(scoreString, "%i", score);
scorePane = TTF_RenderText_Blended(scoreFont, scoreString, scoreColor);
doBlit(0, 0, scorePane->w, scorePane->h, 150, 647, scorePane->w, scorePane->h, scorePane);
/* draw the player */
doBlit(0, 0, playerBMP[player.direction]->w, playerBMP[player.direction]->h,
player.x - playerBMP[player.direction]->w / 2, player.y - playerBMP[player.direction]->h / 2,
playerBMP[player.direction]->w, playerBMP[player.direction]->h, playerBMP[player.direction]);
/* draw any zombies that are on screen */
currentZombie = zombieList;
while(currentZombie) {
doBlit(0, 0, zombieBMP[currentZombie->zombie->direction]->w, zombieBMP[currentZombie->zombie->direction]->h,
currentZombie->zombie->x - zombieBMP[currentZombie->zombie->direction]->w / 2,
currentZombie->zombie->y - zombieBMP[currentZombie->zombie->direction]->h / 2,
zombieBMP[currentZombie->zombie->direction]->w, zombieBMP[currentZombie->zombie->direction]->h,
zombieBMP[currentZombie->zombie->direction]);
doBlit(1084 + ((currentZombie->zombie->letter - 65) * 34), 0, 30, 30,
currentZombie->zombie->x - zombieBMP[currentZombie->zombie->direction]->w / 2,
currentZombie->zombie->y - zombieBMP[currentZombie->zombie->direction]->h / 2,
30, 30, fontBMP);
currentZombie = currentZombie->next;
} /* while */
/* draw the shot */
if(shot.show)
doBlit(0, 0, shotBMP[shot.direction]->w, shotBMP[shot.direction]->h,
shot.x - shotBMP[shot.direction]->w / 2, shot.y - shotBMP[shot.direction]->h / 2,
shotBMP[shot.direction]->w, shotBMP[shot.direction]->h, shotBMP[shot.direction]);
/* now update the whole screen */
SDL_UpdateRect(screen, 0, 0, 0, 0);
SDL_Delay(20);
} /* while */
/* clean up and die */
SDL_FreeSurface(arenaBMP);
SDL_FreeSurface(scoreboardBMP);
for (i=0; i<9; i++) {
SDL_FreeSurface(playerBMP[i]);
SDL_FreeSurface(shotBMP[i]);
} /* for */
fprintf(stderr, "%s is now exiting.\n", threadname);
myExit(1);
} /* ScreenThreadEntryPoint */
|
C
|
/*
Program testira funkcije strstr(s,t) i strchr(s,c)
*/
#include <stdio.h>
#include <string.h>
int main()
{
char s1[21];
char s2[21];
char c;
char* p;
printf("Unesi dva stringa:");
scanf("%s%s",s1,s2);
/*
Funkcija strstr(s,t) je ugradjena funkcija koja utvrdjuje da li je string t
podstring stringa t i ako jeste, vraca pokazivac (char*) na karakter
stringa s odakle pocinje prvo pojavljivanje stringa t, a NULL u suprotnom.
NULL je pokazivac koji ne pokazuje ni na sta, odnosno ne sadrzi adresu
nijedne promenljive.
Podsetimo se veze nizova(a time i stringova) i pokazivaca:
ako je string deklarisan sa s1[21], tada je njegov naziv s1
ekvivalentan adresi prvog karaktera stringa:
s1 <=> &s1[0]
i nadalje redom:
s1+1 <=> &s1[1]
...
u opstem slucaju:
s1+i <=> &s1[i]
To znaci da se indeks elementa na koji pokazuje s1+i moze
dobiti tako sto od s1+i oduzmemo pokazivac na pocetak niza:
s1+i-s1 <=> i. Ovako od pokazivaca na karakter u stringu
dobijamo njegov indeks u stringu.
*/
p = strstr(s1,s2);
if (p!=NULL)
printf("%s jeste podstring od %s pocev od pozicije : %d\n", s2,s1, p-s1);
else
printf("%s NIJE podstring od %s\n", s2,s1);
printf("Unesite karakter:\n");
getchar(); // da se pokupi novi red nakon drugog stringa
c = getchar();
/*
Funkcija strchr(s,c) je ugradjena funkcija koja vraca pokazivac
na prvi karakter u stringu s koji je jednak karakteru c, ako takav
postoji, a NULL u suprotnom.
Indeks od pokazivaca dobijamo na isti nacin kao u prethodnom zadatku
sa strstr.
*/
p = strchr(s1,c);
if(p!=NULL)
printf("%c se pojavljuje u %s na poziciji %d\n", c, s1, p-s1);
else
printf("%c se NE pojavljuje u %s\n",c, s1);
return 0;
}
|
C
|
/**
* @file activity3.c
* @author Prachi Tanna
* @brief activity 3
* @version 0.1
* @date 2021-04-30
*
* @copyright Copyright (c) 2021
*
*/
#include "activity1.h"
#include "activity2.h"
#include "activity3.h"
#include "activity4.h"
/**
* @brief Initalize PWM
*
*/
void init_pwm(void)
{
TCCR0A |= (1<<COM0A1)|(1<<WGM01)|(1<<WGM00);
// Non inverting mode of pin PD6
TCCR0B |= (1<<CS00);
}
/**
* @brief Initialize PWM pins
*
*/
void init_pin_pwm(void)
{
DDRB |= (1<<PB1); // set PB1 for output
}
/**
* @brief comparing the ADC data to decide the duty cycle
*
*/
void compare_adc(void)
{
// changing duty cycle of waveform
if (ADC>0 && ADC<200){
OCR0A = 51;
}
else if(ADC > 210 && ADC < 500){
OCR0A = 101;
}
else if(ADC > 510 && ADC < 700){
OCR0A = 178;
}
else if (ADC > 710 && ADC < 1024){
OCR0A = 242;
}
}
|
C
|
#include"stdio.h"
void main()
{
int num, i,j,prime=1;
printf("enter no to test:-");
scanf("%d",&num);
for(i=2;i<=num;i++)
{
if(num%i==0)
{
prime=1;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
{
prime=0;
break;
}
}
if(prime==1)
{
printf("%d ,",i);
}
}
}
}
|
C
|
#include <compound.h>
#define MAX_POOL_COMPOUNDS 100
static struct compound compound_pool[MAX_POOL_COMPOUNDS];
static unsigned int is_compound_creation;
void compound_pool_init(void)
{
unsigned int i;
for (i = 0; i < MAX_POOL_COMPOUNDS; i++)
compound_pool[i].in_use = FALSE;
}
struct compound *compound_create(void)
{
spin_lock(&is_compound_creation);
unsigned int i;
for (i = 0; i < MAX_POOL_COMPOUNDS; i++) {
if (compound_pool[i].in_use == FALSE) {
compound_pool[i].in_use = TRUE;
spin_unlock(&is_compound_creation);
compound_pool[i].list.next = NULL;
compound_pool[i].len = 0;
return &compound_pool[i];
}
}
spin_unlock(&is_compound_creation);
return NULL;
}
struct compound *compound_create_with_elements(
element_t *elem_arry, unsigned int elem_len)
{
struct compound *comp = compound_create();
if (comp == NULL)
return NULL;
memcpy(comp->elements.bytes, elem_arry, elem_len);
comp->len = elem_len;
return comp;
}
struct compound *compound_create_with_data(bio_data_t data)
{
struct compound *comp = compound_create();
if (comp == NULL)
return NULL;
comp->elements.data = data;
comp->len = sizeof(bio_data_t);
return comp;
}
void compound_dump_entry(struct compound *comp)
{
if (compound_is_data(comp) == TRUE) {
putchar('[');
puth(comp->elements.data ,16);
putchar(']');
} else {
putchar('<');
unsigned long long i;
for (i = 0; i < comp->len; i++) {
puth(comp->elements.bytes[i], 2);
if (i < (comp->len - 1))
putchar(' ');
}
putchar('>');
}
}
bool_t compound_is_data(struct compound *comp)
{
if (comp->len == sizeof(bio_data_t))
return TRUE;
return FALSE;
}
void compound_dump_list(struct singly_list *list_head, enum comp_filter filter)
{
struct singly_list *entry;
unsigned char is_first = TRUE;
for (entry = list_head->next; entry != NULL; entry = entry->next) {
struct compound *comp = (struct compound *)entry;
if ((filter == COMP_FILTER_CODE)
&& (compound_is_data(comp) == TRUE))
continue;
if ((filter == COMP_FILTER_DATA)
&& (compound_is_data(comp) == FALSE))
continue;
if (is_first == TRUE)
is_first = FALSE;
else
putchar(',');
compound_dump_entry(comp);
}
}
|
C
|
// all the function use cases are based on the concept that function pointer can be passed as an argument to another function
// function pointers and callbacks
#include<bits/stdc++.h>
using namespace std;
int acompare(int a,int b)
{
// compare is callback function
// it compares the arguement and
// returns 1 if 1st elememt has higher rank
// else returns -1
// if we change ranking mechanism then this function would sort in dcreasing order
if( a> b) return 1; // or we could just return a-b
else return -1;
}
int dcompare(int a,int b)
{
if( b>a) return 1; // or we could just return a-b
else return -1;
}
void bubble_sort(int A[],int n,int (*compare)(int ,int) )
{
int i,j,temp;
for(i=0; i<n; i++)
for(j=0; j<n-1; j++)
{
if( (*compare)(A[j],A[j+1]) > 0 )
{
temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
}
}
}
int main()
{
int i,A[]={3,2,1,5,6,4};
bubble_sort(A,6,acompare); // passing the function pointer
// compare function decides ascending or descending
for(i=0; i<6; i++)
printf("%d,",A[i]);
bubble_sort(A,6,dcompare); // descending
// this saves alot of duplicate code
printf("\n");
for(i=0; i<6; i++)
printf("%d,",A[i]);
// the array is sorted in increasing order
// if we want to arrange in decreasing order
// could write one more sort function // duplicate code
// or we could pass one more parameter telling function to arrange inascend or descen
//we could also use function pointers
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char used[45];
int compar(const void *a,const void *b){
return *((int *)a)-*((int *)b);
}
char is_answer(int a[],int b[],int n,int n_b){
int i,j,k;
for(i=3;i<n;i++){
for(j=0;j<n_b&&used[j]==1;j++);
if(j==n_b) return 0;
a[i]=b[j]-a[0];
used[j]=1;
for(j=1;j<i;j++){
for(k=0;k<n_b&&a[i]+a[j]>=b[k];k++) if(used[k]==0&&a[i]+a[j]==b[k]) break;
if(used[k]==0&&a[i]+a[j]==b[k]) used[k]=1;
else return 0;
}
}
return 1;
}
int main(){
int n,n_b,sum;
int i,j;
int a[10],b[45];
while(scanf("%d",&n)==1){
n_b=n*(n-1)/2;
sum=0;
for(i=0;i<n_b;i++) scanf("%d",&b[i]),sum+=b[i];
qsort(b,n_b,sizeof(int),compar);
if(sum%(n-1)!=0){
puts("Impossible");
continue;
}
for(i=2;i<n_b;i++){
memset(used,0,sizeof(used));
if((b[0]+b[1]+b[i])%2==0){
a[0]=(b[0]+b[1]-b[i])/2;
a[1]=(b[0]-b[1]+b[i])/2;
a[2]=(-b[0]+b[1]+b[i])/2;
used[0]=used[1]=used[i]=1;
if(is_answer(a,b,n,n_b)){
printf("%d",a[0]);
for(j=1;j<n;j++) printf(" %d",a[j]);
puts("");
break;
}
}
}
if(i==n_b) puts("Impossible");
}
return 0;
}
|
C
|
#include <stdio.h>
int main ()
{
long long n, i, k, a, b, c, d;
scanf("%lld", &n);
for (i=1; i<= n; i++)
{
scanf("%lld", &k);
for (a = 2; a*a <= k; a++)
if (k%a == 0)
{
b = k/a;
break;
}
for (c = a+1; c*c <= k; c++)
if (k%c == 0)
{
d = k/c;
break;
}
printf("Case #%lld: %lld = %lld * %lld = %lld * %lld\n", i, k, a, b, c, d);
}
return 0;
}
|
C
|
#include "includes.h"
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* Infinite loop */
while (1)
{
}
}
#endif
#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
PUTCHAR_PROTOTYPE
{
/* Place your implementation of fputc here */
/* e.g. write a character to the USART */
USART_SendData(PC_UART, (uint16_t)ch);
/* Loop until the end of transmission */
while(RESET == USART_GetFlagStatus(PC_UART, USART_FLAG_TC));
return(ch);
}
void STM32_SoftReset(void)
{
__set_FAULTMASK(SET);
NVIC_SystemReset();
}
uint32_t STM32_EncodePriority(uint32_t PreemptPriority, uint32_t SubPriority)
{
uint32_t prioritygroup = 0x0;
/* Check the parameters */
assert_param(IS_NVIC_PREEMPTION_PRIORITY(PreemptPriority));
assert_param(IS_NVIC_SUB_PRIORITY(SubPriority));
prioritygroup = NVIC_GetPriorityGrouping();
return (NVIC_EncodePriority(prioritygroup, PreemptPriority, SubPriority));
}
/**
* @brief Set System clock frequency to 72MHz and configure HCLK, PCLK2
* and PCLK1 prescalers.
* @param None
* @retval None
*/
static void SetSysClockTo72(void)
{
ErrorStatus HSEStartUpStatus;
/* SYSCLK, HCLK, PCLK2 and PCLK1 configuration -----------------------------*/
/* RCC system reset(for debug purpose) */
RCC_DeInit();
/* Enable HSE */
RCC_HSEConfig(RCC_HSE_ON);
/* Wait till HSE is ready */
HSEStartUpStatus = RCC_WaitForHSEStartUp();
if (HSEStartUpStatus == SUCCESS)
{
/* Enable Prefetch Buffer */
FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable);
/* Flash 2 wait state */
FLASH_SetLatency(FLASH_Latency_2);
/* HCLK = SYSCLK */
RCC_HCLKConfig(RCC_SYSCLK_Div1);
/* PCLK2 = HCLK */
RCC_PCLK2Config(RCC_HCLK_Div1);
/* PCLK1 = HCLK/2 */
RCC_PCLK1Config(RCC_HCLK_Div2);
#ifdef STM32F10X_CL
/* Configure PLLs *********************************************************/
/* PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */
RCC_PREDIV2Config(RCC_PREDIV2_Div5);
RCC_PLL2Config(RCC_PLL2Mul_8);
/* Enable PLL2 */
RCC_PLL2Cmd(ENABLE);
/* Wait till PLL2 is ready */
while (RCC_GetFlagStatus(RCC_FLAG_PLL2RDY) == RESET)
{}
/* PLL configuration: PLLCLK = (PLL2 / 5) * 9 = 72 MHz */
RCC_PREDIV1Config(RCC_PREDIV1_Source_PLL2, RCC_PREDIV1_Div5);
RCC_PLLConfig(RCC_PLLSource_PREDIV1, RCC_PLLMul_9);
#else
/* PLLCLK = 8MHz * 9 = 72 MHz */
RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);
#endif
/* Enable PLL */
RCC_PLLCmd(ENABLE);
/* Wait till PLL is ready */
while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET)
{
}
/* Select PLL as system clock source */
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
/* Wait till PLL is used as system clock source */
while(RCC_GetSYSCLKSource() != 0x08)
{
}
}
else
{ /* If HSE fails to start-up, the application will have wrong clock configuration.
User can add here some code to deal with this error */
/* Go to infinite loop */
while (1)
{
}
}
}
void RCC_Configuration(void)
{
/* Set System clock frequency to 72MHz and configure HCLK, PCLK2 and PCLK1 prescalers */
SetSysClockTo72();
/* Enable the GPIO Clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOC, ENABLE);
/* Enable the AFIO Clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
/* Enable the USART1 Clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
/* Enable the USART2 Clock */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
}
void GPIO_Configuration(void)
{
GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable, ENABLE);
}
void NVIC_Configuration(void)
{
/* Configure 2 bits for preemption priority */
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
/*
0x00~0x03SysTickΪռȼ0
0x04~0x07SysTickΪռȼ1
0x08~0x0BSysTickΪռȼ2
0x0C~0x0FSysTickΪռȼ3
*/
NVIC_SetPriority(SysTick_IRQn, STM32_EncodePriority(SYS_TICK_PREEMPT_PRIO, SYS_TICK_SUB_PRIO));
}
void IWDG_Init(void)
{
/* Enable the LSI OSC */
RCC_LSICmd(ENABLE);
/* Wait till LSI is ready */
while(RESET == RCC_GetFlagStatus(RCC_FLAG_LSIRDY));
/* IWDG timeout equal to 250 ms (the timeout may varies due to LSI frequency
dispersion) */
/* Enable write access to IWDG_PR and IWDG_RLR registers */
IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);
/* IWDG counter clock: 40KHz(LSI) / 32 = 1.25KHz */
IWDG_SetPrescaler(IWDG_Prescaler_32);
/* Set counter reload value to obtain 250ms IWDG TimeOut.
Counter Reload Value = 250ms / IWDG counter clock period
= 250ms / (LSI / 32)
= 0.25s / (LsiFreq / 32)
= LsiFreq / (32 * 4)
= LsiFreq / 128
*/
IWDG_SetReload(1250); /* 1250 / 1.25KHz = 1000ms */
/* Reload IWDG counter */
IWDG_ReloadCounter();
/* Enable IWDG (the LSI oscillator will be enabled by hardware) */
IWDG_Enable();
}
void LED_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11 | GPIO_Pin_12;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
void KEY_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
/* Configure Button GPIOx Pin as input floating */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOC, &GPIO_InitStructure);
/* Connect EXTIx Line to Button GPIOx Pin */
GPIO_EXTILineConfig(GPIO_PortSourceGPIOC, GPIO_PinSource0);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOC, GPIO_PinSource1);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOC, GPIO_PinSource2);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOC, GPIO_PinSource3);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOC, GPIO_PinSource4);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOC, GPIO_PinSource5);
/* Configure EXTIx Line */
EXTI_InitStructure.EXTI_Line = EXTI_Line0;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
/* Configure EXTIx Line */
EXTI_InitStructure.EXTI_Line = EXTI_Line1;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
/* Configure EXTIx Line */
EXTI_InitStructure.EXTI_Line = EXTI_Line2;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
/* Configure EXTIx Line */
EXTI_InitStructure.EXTI_Line = EXTI_Line3;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
/* Configure EXTIx Line */
EXTI_InitStructure.EXTI_Line = EXTI_Line4;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
/* Configure EXTIx Line */
EXTI_InitStructure.EXTI_Line = EXTI_Line5;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
/* Assign ISR handler */
BSP_IntVectSet(BSP_INT_ID_EXTI0, EXTI0_IRQHandler);
/* Assign ISR priority */
BSP_IntPrioSet(BSP_INT_ID_EXTI0, STM32_EncodePriority(EXTI_PREEMPT_PRIO, EXTI_SUB_PRIO));
/* Enable EXTIx Interrupt */
BSP_IntEn(BSP_INT_ID_EXTI0);
/* Assign ISR handler */
BSP_IntVectSet(BSP_INT_ID_EXTI1, EXTI1_IRQHandler);
/* Assign ISR priority */
BSP_IntPrioSet(BSP_INT_ID_EXTI1, STM32_EncodePriority(EXTI_PREEMPT_PRIO, EXTI_SUB_PRIO));
/* Enable EXTIx Interrupt */
BSP_IntEn(BSP_INT_ID_EXTI1);
/* Assign ISR handler */
BSP_IntVectSet(BSP_INT_ID_EXTI2, EXTI2_IRQHandler);
/* Assign ISR priority */
BSP_IntPrioSet(BSP_INT_ID_EXTI2, STM32_EncodePriority(EXTI_PREEMPT_PRIO, EXTI_SUB_PRIO));
/* Enable EXTIx Interrupt */
BSP_IntEn(BSP_INT_ID_EXTI2);
/* Assign ISR handler */
BSP_IntVectSet(BSP_INT_ID_EXTI3, EXTI3_IRQHandler);
/* Assign ISR priority */
BSP_IntPrioSet(BSP_INT_ID_EXTI3, STM32_EncodePriority(EXTI_PREEMPT_PRIO, EXTI_SUB_PRIO));
/* Enable EXTIx Interrupt */
BSP_IntEn(BSP_INT_ID_EXTI3);
/* Assign ISR handler */
BSP_IntVectSet(BSP_INT_ID_EXTI4, EXTI4_IRQHandler);
/* Assign ISR priority */
BSP_IntPrioSet(BSP_INT_ID_EXTI4, STM32_EncodePriority(EXTI_PREEMPT_PRIO, EXTI_SUB_PRIO));
/* Enable EXTIx Interrupt */
BSP_IntEn(BSP_INT_ID_EXTI4);
/* Assign ISR handler */
BSP_IntVectSet(BSP_INT_ID_EXTI9_5, EXTI9_5_IRQHandler);
/* Assign ISR priority */
BSP_IntPrioSet(BSP_INT_ID_EXTI9_5, STM32_EncodePriority(EXTI_PREEMPT_PRIO, EXTI_SUB_PRIO));
/* Enable EXTIx Interrupt */
BSP_IntEn(BSP_INT_ID_EXTI9_5);
}
void LCD_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOC, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_15;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void RTC_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void USART1_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
/* Configure USART1 Rx as input floating */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Configure USART1 Tx as alternate function push-pull */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Disable the USART1 */
USART_Cmd(USART1, DISABLE);
/* Disable USART1 Receive and Transmit interrupts */
USART_ITConfig(USART1, USART_IT_RXNE, DISABLE);
USART_ITConfig(USART1, USART_IT_TXE, DISABLE);
/* Assign ISR handler */
BSP_IntVectSet(BSP_INT_ID_USART1, USART1_IRQHandler);
/* Assign ISR priority */
BSP_IntPrioSet(BSP_INT_ID_USART1, STM32_EncodePriority(USART1_PREEMPT_PRIO, USART1_SUB_PRIO));
/* Enable USART1 Interrupt */
BSP_IntEn(BSP_INT_ID_USART1);
/* USART1 configured as follow:
- BaudRate = 9600 baud
- Word Length = 8 Bits
- One Stop Bit
- No parity
- Hardware flow control disabled (RTS and CTS signals)
- Receive and transmit enabled
*/
USART_StructInit(&USART_InitStructure);
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
/* Configure USART1 */
USART_Init(USART1, &USART_InitStructure);
/* Enable the USART1 */
USART_Cmd(USART1, ENABLE);
}
void USART2_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
/* Configure USART2 Rx as input floating */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Configure USART2 Tx as alternate function push-pull */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Disable the USART2 */
USART_Cmd(USART2, DISABLE);
/* Disable USART2 Receive and Transmit interrupts */
USART_ITConfig(USART2, USART_IT_RXNE, DISABLE);
USART_ITConfig(USART2, USART_IT_TXE, DISABLE);
/* Assign ISR handler */
BSP_IntVectSet(BSP_INT_ID_USART2, USART2_IRQHandler);
/* Assign ISR priority */
BSP_IntPrioSet(BSP_INT_ID_USART2, STM32_EncodePriority(USART2_PREEMPT_PRIO, USART2_SUB_PRIO));
/* Enable USART2 Interrupt */
BSP_IntEn(BSP_INT_ID_USART2);
/* USART2 configured as follow:
- BaudRate = 38400 baud
- Word Length = 9 Bits
- One Stop Bit
- No parity
- Hardware flow control disabled (RTS and CTS signals)
- Receive and transmit enabled
*/
USART_StructInit(&USART_InitStructure);
USART_InitStructure.USART_BaudRate = 38400;
USART_InitStructure.USART_WordLength = USART_WordLength_9b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
/* Configure USART2 */
USART_Init(USART2, &USART_InitStructure);
/* Enable the USART2 */
USART_Cmd(USART2, ENABLE);
}
void BEEP_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void RELAY_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void BSP_Init(void)
{
/* System clocks configuration ---------------------------------------------*/
RCC_Configuration();
/* GPIO configuration ------------------------------------------------------*/
GPIO_Configuration();
/* NVIC configuration ------------------------------------------------------*/
NVIC_Configuration();
#if (WDT_EN > 0u)
IWDG_Init();
#endif
LED_Init();
KEY_Init();
RTC_Init();
USART1_Init();
USART2_Init();
BEEP_Init();
RELAY_Init();
}
/*
*********************************************************************************************************
* BSP_CPU_ClkFreq()
*
* Description : This function reads CPU registers to determine the CPU clock frequency of the chip in KHz.
*
* Argument(s) : none.
*
* Return(s) : The CPU clock frequency, in Hz.
*
* Caller(s) : none.
*
* Note(s) : none.
*********************************************************************************************************
*/
CPU_INT32U BSP_CPU_ClkFreq (void)
{
static RCC_ClocksTypeDef rcc_clocks;
RCC_GetClocksFreq(&rcc_clocks);
return ((CPU_INT32U)rcc_clocks.HCLK_Frequency);
}
/*
*********************************************************************************************************
*********************************************************************************************************
* OS CORTEX-M3 FUNCTIONS
*********************************************************************************************************
*********************************************************************************************************
*/
/*
*********************************************************************************************************
* OS_CPU_SysTickClkFreq()
*
* Description : Get system tick clock frequency.
*
* Argument(s) : none.
*
* Return(s) : Clock frequency (of system tick).
*
* Caller(s) : BSP_Init().
*
* Note(s) : none.
*********************************************************************************************************
*/
INT32U OS_CPU_SysTickClkFreq (void)
{
INT32U freq;
freq = BSP_CPU_ClkFreq();
return (freq);
}
/*
*********************************************************************************************************
* MODULE END
*********************************************************************************************************
*/
|
C
|
/*******
* Acm_Problem_KTX
* resolver : Kong ji yeon
* date: 2014/02/09
* comment : 폴더만드는법을 몰라 소스만 첨부합니다.
*******/
#include<stdio.h>
#include<stdlib.h>
void Input(int *T,int **M,int ***N);
int* Calculate(int T,int *M,int **N);
void Output(int T,int *answer);
int main(int argc,char *argv[]){
int T; //test case
int *M; //train
int **N; //train level
int *answer;
Input(&T,&M,&N);
answer=Calculate(T,M,N);
Output(T,answer);
return 0;
}
void Input(int *T,int **M,int ***N){
int i,j; //for loop control
char filename[32]; //input file
FILE *fp;
printf("Input filename : ");
scanf("%s",filename);
fp=fopen(filename,"r");
fscanf(fp,"%d",T);
*M=(int*)calloc(*T,sizeof(int));
*N=(int**)calloc(*T,sizeof(int*));
for(i=0;i<*T;i++){
fscanf(fp,"%d",(*M)+i);
*((*N)+i)=(int*)calloc(*(*M+i),sizeof(int));
for(j=0;j<*(*M+i);j++){
fscanf(fp,"%d",(*((*N)+i)+j));
}
}
fclose(fp);
}
int* Calculate(int T,int *M,int **N){
int i,j,k; //for loop control
int *answer; //answer
int destination=1; //train level
int pass; //testing train
int count; //pass count
answer=(int*)calloc(T,sizeof(int));
for(i=0;i<T;i++){
destination=1;
pass=3;
count=0;
for(j=0;j<*(M+i);j++){
k=0;
while(k<pass && destination>j){
if(*(*(N+i)+k)==destination){
destination+=1;
pass+=1;
count+=1;
}
k++;
}
}
if(*(N+i)!=NULL){
free(*(N+i));
*(N+i)=NULL;
}
if(count==*(M+i)){
*(answer+i)=1;
}
}
if(M!=NULL){
free(M);
M=NULL;
}
if(N!=NULL){
free(N);
N=NULL;
}
return answer;
}
void Output(int T,int *answer){
int i;
for(i=0;i<T;i++){
if(*(answer+i)==0){
printf("NO\n");
}else{
printf("YES\n");
}
}
if(answer!=NULL){
free(answer);
answer=NULL;
}
}
|
C
|
#include <stdio.h>
void swap(int* p, int* q);
int main(void) {
int a, b;
printf("Enter two integer: ");
scanf("%d %d", &a, &b);
printf("Before swap: %d %d\n", a, b);
swap(&a, &b);
printf("After swap: %d %d\n", a, b);
return 0;
}
void swap(int* p, int* q) {
int temp;
temp = *q;
*q = *p;
*p = temp;
}
|
C
|
#include <stdio.h>
int main() {
int x,y;
do{
scanf("%d %d", &x,&y);
if(y>x) printf("Crescente\n");
if(y<x) printf("Decescente\n");
}while(x!=y);
return 0;
}
|
C
|
//使用malloc在堆区申请动态内存
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int* p1 = (int*)malloc(4);
int* p2 = (int*)malloc(4);
int* p3 = (int*)malloc(4);
int* p4 = (int*)malloc(4);
int* p5 = (int*)malloc(4);
printf("p1 = %p\n",p1);
printf("p2 = %p\n",p2);
printf("p3 = %p\n",p3);
printf("p4 = %p\n",p4);
printf("p5 = %p\n",p5);
printf("-----------------------\n");
*p1 = 1;
//*(p1+1) = 2;
//*(p1+2) = 3;
//*(p1+3) = 4;
*(p1+4) = 5;
//释放p1指向的动态内存
free(p1); p1 = NULL;
printf("*p2 = %d\n",*p2);
return 0;
}
|
C
|
/* prog10_19, HܼƫVr */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char name[20];
char *ptr="How are you?"; /* NЫVr"How are you?" */
printf("what's your name? ");
gets(name); /* LŪJr */
printf("Hi, %s, ",name); /* LXr}Cnamee */
puts(ptr); /* LXptrҫVr */
system("pause");
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* remind_2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bcharity <bcharity@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/02 14:09:41 by bcharity #+# #+# */
/* Updated: 2020/02/02 17:45:28 by bcharity ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/push_swap.h"
void extrem_pnt(int *st, int n, int **extr)
{
int i;
int *max;
int *min;
i = st[0];
min = &(st[i]);
max = &(st[i]);
while (i <= n + st[0] - 1)
{
if (st[i] > *max)
max = &(st[i]);
if (st[i] < *min)
min = &(st[i]);
i++;
}
extr[0] = min;
extr[1] = max;
}
void parsecarry_op3(int *sta, int **extr)
{
swap_stack(sta);
print_op("sa\n");
rot_stack(sta);
print_op("ra\n");
swap_stack(sta);
print_op("sa\n");
revrot_stack(sta);
print_op("rra\n");
swap_stack(sta);
print_op("sa\n");
}
void parsecarry_op2(int *sta, int **extr)
{
if ((extr[1] - &(sta[sta[0]])) > 0)
{
rot_stack(sta);
print_op("ra\n");
swap_stack(sta);
print_op("sa\n");
revrot_stack(sta);
print_op("rra\n");
swap_stack(sta);
print_op("sa\n");
}
else if ((extr[1] - &(sta[sta[0]])) == 0)
{
swap_stack(sta);
print_op("sa\n");
rot_stack(sta);
print_op("ra\n");
swap_stack(sta);
print_op("sa\n");
revrot_stack(sta);
print_op("rra\n");
}
}
void parsecarry_op1(int *sta, int **extr)
{
if (extr[0] == &(sta[sta[0]]))
{
rot_stack(sta);
print_op("ra\n");
swap_stack(sta);
print_op("sa\n");
revrot_stack(sta);
print_op("rra\n");
}
else if ((extr[0] - &(sta[sta[0]])) > 0)
{
swap_stack(sta);
print_op("sa\n");
}
}
void parse_carry_a(int *sta, int n)
{
int *extr[2];
printf("pushcarry\n");
print_st(sta);
extrem_pnt(sta, n, &((extr)[0]));
if ((extr[1] - extr[0]) == 1 && n > 2)
parsecarry_op1(sta, extr);
else if ((extr[1] - extr[0]) == -1 && n > 2)
parsecarry_op2(sta, extr);
else if ((extr[1] - extr[0]) == -1 && n == 2)
{
swap_stack(sta);
print_op("sa\n");
}
else if ((extr[1] - extr[0]) == -2 && n > 2)
parsecarry_op3(sta, extr);
else if ((extr[1] - extr[0]) == 2 && n > 2)
{
printf("after_pushcarry\n");
print_st(sta);
return ;
}
printf("after_pushcarry\n");
print_st(sta);
return ;
}
|
C
|
#include <stdio.h>
int main ()
{
int x, y, z, cont;
x=0;
y=1;
for (int i=1; i<=32; i++)
{
z=x+y;
printf("%d\n",z);
if (z%2==0)
{
cont=cont+z;
}
x=y;
y=z;
}
printf("La suma total es de: %d\n", cont);
return 0;
}
|
C
|
typedef unsigned char uchar;
#define LOBYTE(x) ((uchar)((x) & 0xFF))
#define HIBYTE(x) ((uchar)((x) >> 8))
unsigned char lin[256] = "asdffeagewaHAFEFaeDsFEawFdsFaefaeerdjgp";
unsigned short icrc1(unsigned short crc, unsigned char onech)
{
int i;
unsigned short ans=(crc^onech << 8);
for (i=0;i<8;i++) {
if (ans & 0x8000)
ans = (ans <<= 1) ^ 4129;
else
ans <<= 1;
}
return ans;
}
unsigned short icrc(unsigned short crc, unsigned long len,
short jinit, int jrev)
{
unsigned short icrc1(unsigned short crc, unsigned char onech);
static unsigned short icrctb[256],init=0;
static uchar rchr[256];
unsigned short tmp1, tmp2, j,cword=crc;
static uchar it[16]={0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15};
if (!init) {
init=1;
for (j=0;j<=255;j++) {
icrctb[j]=icrc1(j << 8,(uchar)0);
rchr[j]=(uchar)(it[j & 0xF] << 4 | it[j >> 4]);
}
}
if (jinit >= 0) cword=((uchar) jinit) | (((uchar) jinit) << 8);
else if (jrev < 0)
cword=rchr[HIBYTE(cword)] | rchr[LOBYTE(cword)] << 8;
#ifdef DEBUG
printf("len = %d\n", len);
#endif
for (j=1;j<=len;j++) {
if (jrev < 0) {
tmp1 = rchr[lin[j]]^ HIBYTE(cword);
}
else {
tmp1 = lin[j]^ HIBYTE(cword);
}
cword = icrctb[tmp1] ^ LOBYTE(cword) << 8;
}
if (jrev >= 0) {
tmp2 = cword;
}
else {
tmp2 = rchr[HIBYTE(cword)] | rchr[LOBYTE(cword)] << 8;
}
return (tmp2 );
}
int main(void)
{
unsigned short i1,i2;
unsigned long n;
n=40;
lin[n+1]=0;
i1=icrc(0,n,(short)0,1);
lin[n+1]=HIBYTE(i1);
lin[n+2]=LOBYTE(i1);
i2=icrc(i1,n+2,(short)0,1);
return 0;
}
|
C
|
/******************************************************************************/
/* DESԳԿ㷨ܽģ */
/******************************************************************************/
#include <stdio.h>
#include <string.h>
//#include "BottomFunction.h"
#define ENCRYPT 0
#define DESCRYPT 1
#define PINLEN 9
/*
* Initial permutation,
*/
static unsigned char IP[] = {
58,50,42,34,26,18,10, 2,
60,52,44,36,28,20,12, 4,
62,54,46,38,30,22,14, 6,
64,56,48,40,32,24,16, 8,
57,49,41,33,25,17, 9, 1,
59,51,43,35,27,19,11, 3,
61,53,45,37,29,21,13, 5,
63,55,47,39,31,23,15, 7,
};
/*
* Final permutation, FP = IP^(-1)
*/
static unsigned char FP[] = {
40, 8,48,16,56,24,64,32,
39, 7,47,15,55,23,63,31,
38, 6,46,14,54,22,62,30,
37, 5,45,13,53,21,61,29,
36, 4,44,12,52,20,60,28,
35, 3,43,11,51,19,59,27,
34, 2,42,10,50,18,58,26,
33, 1,41, 9,49,17,57,25,
};
/*
* Permuted-choice 1 from the key bits
* to yield C and D.
* Note that bits 8,16... are left out:
* They are intended for a parity check.
*/
static unsigned char PC1_C[] = {
57,49,41,33,25,17, 9,
1,58,50,42,34,26,18,
10, 2,59,51,43,35,27,
19,11, 3,60,52,44,36,
};
static unsigned char PC1_D[] = {
63,55,47,39,31,23,15,
7,62,54,46,38,30,22,
14, 6,61,53,45,37,29,
21,13, 5,28,20,12, 4,
};
/*
* Sequence of shifts used for the key schedule.
*/
static unsigned char shifts[] = {
1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1,
};
/*
* Permuted-choice 2, to pick out the bits from
* the CD array that generate the key schedule.
*/
static unsigned char PC2_C[] = {
14,17,11,24, 1, 5,
3,28,15, 6,21,10,
23,19,12, 4,26, 8,
16, 7,27,20,13, 2,
};
static unsigned char PC2_D[] = {
41,52,31,37,47,55,
30,40,51,45,33,48,
44,49,39,56,34,53,
46,42,50,36,29,32,
};
/*
* The C and D arrays used to calculate the key schedule.
*/
static unsigned char C[64];
static unsigned char D[64];
/*
* The key schedule.
* Generated from the key.
*/
static unsigned char KS[16][48];
/*
* The E bit-selection table.
*/
static unsigned char E[64];
static unsigned char e[] = {
32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9,10,11,12,13,
12,13,14,15,16,17,
16,17,18,19,20,21,
20,21,22,23,24,25,
24,25,26,27,28,29,
28,29,30,31,32, 1,
};
/*
* Set up the key schedule from the key.
*/
static void setkey(unsigned char *key)
{
int i, j, k;
int t;
/*
* First, generate C and D by permuting
* the key. The low order bit of each
* 8-bit unsigned char is not used, so C and D are only 28
* bits apiece.
*/
for (i=0; i<28; i++) {
C[i] = key[PC1_C[i]-1];
D[i] = key[PC1_D[i]-1];
}
/*
* To generate Ki, rotate C and D according
* to schedule and pick up a permutation
* using PC2.
*/
for (i=0; i<16; i++) {
/*
* rotate.
*/
for (k=0; k<shifts[i]; k++) {
t = C[0];
for (j=0; j<28-1; j++)
C[j] = C[j+1];
C[27] = t;
t = D[0];
for (j=0; j<28-1; j++)
D[j] = D[j+1];
D[27] = t;
}
/*
* get Ki. Note C and D are concatenated.
*/
for (j=0; j<24; j++) {
KS[i][j] = C[PC2_C[j]-1];
KS[i][j+24] = D[PC2_D[j]-28-1];
}
}
for(i=0;i<48;i++)
E[i] = e[i];
}
/*
* The 8 selection functions.
* For some reason, they give a 0-origin
* index, unlike everything else.
*/
static unsigned char S[8][64] = {
14, 4,13, 1, 2,15,11, 8, 3,10, 6,12, 5, 9, 0, 7,
0,15, 7, 4,14, 2,13, 1,10, 6,12,11, 9, 5, 3, 8,
4, 1,14, 8,13, 6, 2,11,15,12, 9, 7, 3,10, 5, 0,
15,12, 8, 2, 4, 9, 1, 7, 5,11, 3,14,10, 0, 6,13,
15, 1, 8,14, 6,11, 3, 4, 9, 7, 2,13,12, 0, 5,10,
3,13, 4, 7,15, 2, 8,14,12, 0, 1,10, 6, 9,11, 5,
0,14, 7,11,10, 4,13, 1, 5, 8,12, 6, 9, 3, 2,15,
13, 8,10, 1, 3,15, 4, 2,11, 6, 7,12, 0, 5,14, 9,
10, 0, 9,14, 6, 3,15, 5, 1,13,12, 7,11, 4, 2, 8,
13, 7, 0, 9, 3, 4, 6,10, 2, 8, 5,14,12,11,15, 1,
13, 6, 4, 9, 8,15, 3, 0,11, 1, 2,12, 5,10,14, 7,
1,10,13, 0, 6, 9, 8, 7, 4,15,14, 3,11, 5, 2,12,
7,13,14, 3, 0, 6, 9,10, 1, 2, 8, 5,11,12, 4,15,
13, 8,11, 5, 6,15, 0, 3, 4, 7, 2,12, 1,10,14, 9,
10, 6, 9, 0,12,11, 7,13,15, 1, 3,14, 5, 2, 8, 4,
3,15, 0, 6,10, 1,13, 8, 9, 4, 5,11,12, 7, 2,14,
2,12, 4, 1, 7,10,11, 6, 8, 5, 3,15,13, 0,14, 9,
14,11, 2,12, 4, 7,13, 1, 5, 0,15,10, 3, 9, 8, 6,
4, 2, 1,11,10,13, 7, 8,15, 9,12, 5, 6, 3, 0,14,
11, 8,12, 7, 1,14, 2,13, 6,15, 0, 9,10, 4, 5, 3,
12, 1,10,15, 9, 2, 6, 8, 0,13, 3, 4,14, 7, 5,11,
10,15, 4, 2, 7,12, 9, 5, 6, 1,13,14, 0,11, 3, 8,
9,14,15, 5, 2, 8,12, 3, 7, 0, 4,10, 1,13,11, 6,
4, 3, 2,12, 9, 5,15,10,11,14, 1, 7, 6, 0, 8,13,
4,11, 2,14,15, 0, 8,13, 3,12, 9, 7, 5,10, 6, 1,
13, 0,11, 7, 4, 9, 1,10,14, 3, 5,12, 2,15, 8, 6,
1, 4,11,13,12, 3, 7,14,10,15, 6, 8, 0, 5, 9, 2,
6,11,13, 8, 1, 4,10, 7, 9, 5, 0,15,14, 2, 3,12,
13, 2, 8, 4, 6,15,11, 1,10, 9, 3,14, 5, 0,12, 7,
1,15,13, 8,10, 3, 7, 4,12, 5, 6,11, 0,14, 9, 2,
7,11, 4, 1, 9,12,14, 2, 0, 6,10,13,15, 3, 5, 8,
2, 1,14, 7, 4,10, 8,13,15,12, 9, 0, 3, 5, 6,11,
};
/*
* P is a permutation on the selected combination
* of the current L and key.
*/
static unsigned char P[] = {
16, 7,20,21,
29,12,28,17,
1,15,23,26,
5,18,31,10,
2, 8,24,14,
32,27, 3, 9,
19,13,30, 6,
22,11, 4,25,
};
/*
* The current block, divided into 2 halves.
*/
static unsigned char L[64], R[64];
static unsigned char tempL[64];
static unsigned char f[64];
/*
* The combination of the key and the input, before selection.
*/
static unsigned char preS[64];
/*
* The payoff: encrypt a block.
*/
static void encrypt(unsigned char *block, int edflag)
{
int i, ii;
int t, j, k;
/*
* First, permute the bits in the input
*/
for (j=0; j<64; j++)
L[j] = block[IP[j]-1];
/*============================================== */
for (j=0;j<32;j++)
R[j] = L[j+32];
/*============================================== */
/*
* Perform an encryption operation 16 times.
*/
for (ii=0; ii<16; ii++) {
/*
* Set direction
*/
if (edflag)
i = 15-ii;
else
i = ii;
/*
* Save the R array,
* which will be the new L.
*/
for (j=0; j<32; j++)
tempL[j] = R[j];
/*
* Expand R to 48 bits using the E selector;
* exclusive-or with the current key bits.
*/
for (j=0; j<48; j++)
preS[j] = R[E[j]-1] ^ KS[i][j];
/*
* The pre-select bits are now considered
* in 8 groups of 6 bits each.
* The 8 selection functions map these
* 6-bit quantities into 4-bit quantities
* and the results permuted
* to make an f(R, K).
* The indexing into the selection functions
* is peculiar; it could be simplified by
* rewriting the tables.
*/
for (j=0; j<8; j++) {
t = 6*j;
k = S[j][(preS[t+0]<<5)+
(preS[t+1]<<3)+
(preS[t+2]<<2)+
(preS[t+3]<<1)+
(preS[t+4]<<0)+
(preS[t+5]<<4)];
t = 4*j;
f[t+0] = (k>>3)&01;
f[t+1] = (k>>2)&01;
f[t+2] = (k>>1)&01;
f[t+3] = (k>>0)&01;
}
/*
* The new R is L ^ f(R, K).
* The f here has to be permuted first, though.
*/
for (j=0; j<32; j++)
R[j] = L[j] ^ f[P[j]-1];
/*
* Finally, the new L (the original R)
* is copied back.
*/
for (j=0; j<32; j++)
L[j] = tempL[j];
}
/*
* The output L and R are reversed.
*/
for (j=0; j<32; j++) {
t = L[j];
L[j] = R[j];
R[j] = t;
}
/*============================================== */
for (j=32;j<64;j++)
L[j] = R[j-32];
/*============================================== */
/*
* The final output
* gets the inverse permutation of the very original.
*/
for (j=0; j<64; j++)
block[j] = L[FP[j]-1];
}
static void compress(unsigned char *in,unsigned char *out)
{
int temp;
int i,j;
for(i=0;i<8;i++){
out[i] = 0;
temp = 1;
for (j=7;j>=0;j--){
out[i] = out[i] + ( in[i*8+j] * temp);
temp *= 2;
}
}
}
/*
** expand takes the eight character string in
** and converts it to a 64 character array containing
** zero or one (bit stream).
*/
static void expand(unsigned char *in,unsigned char *out)
{
int i,j;
for (i=0;i<8;i++){
for (j=0;j<8;j++){
*out = (in[i] <<j) & 0x80;
if (*out == 0x80)
*out = 0x01;
out++;
}
}
}
void gDes( unsigned char *pin, unsigned char *workkey, unsigned char *cipher_pin )
{
int i;
unsigned char clear_txt[PINLEN],cipher_txt[PINLEN];
unsigned char pin_block[PINLEN],pan_block[PINLEN];
unsigned char key_block[PINLEN];
unsigned char bits[64];
for(i=0;i<8;i++)
key_block[i]=workkey[i];
for (i=0;i<8;i++)
clear_txt[i] = pin[i];
expand(key_block,bits);
setkey(bits);
expand(clear_txt,bits); /* expand to bit stream */
encrypt(bits,ENCRYPT); /* encrypt */
compress(bits,cipher_txt); /* compress to 8 characters */
memcpy(cipher_pin ,cipher_txt,8);
}
void gUndes( unsigned char *pin,unsigned char *workkey,unsigned char *cipher_pin )
{
int i;
unsigned char clear_txt[PINLEN],cipher_txt[17];
unsigned char pin_block[PINLEN],pan_block[PINLEN];
unsigned char key_block[PINLEN];
unsigned char bits[64];
for(i=0;i<8;i++)
key_block[i]=workkey[i];
/* get pan_block */
expand(key_block,bits);
setkey(bits);
/* set key */
expand(pin,bits); /* expand to bit stream */
encrypt(bits,DESCRYPT); /* descrypt */
compress(bits,clear_txt); /* compress to 8 characters */
for (i=0;i<8;i++)
pin_block[i] = clear_txt[i];
memcpy(cipher_pin ,pin_block, 8);
}
void gTriDes(unsigned char *input, unsigned char *doublekey,unsigned char *output )
{
unsigned char left_key[9];
unsigned char right_key[9];
unsigned char tmpstr1[9], tmpstr2[9];
memcpy( left_key, doublekey, 8 );
memcpy( right_key, doublekey+8, 8 );
gDes( input, left_key, tmpstr1 );
gUndes( tmpstr1, right_key, tmpstr2 );
gDes( tmpstr2, left_key, output );
}
void key_des_Bcd( unsigned char *input, unsigned char *workkey, unsigned char *output )
{
int i;
unsigned char clear_txt[PINLEN],cipher_txt[PINLEN];
unsigned char pin_block[PINLEN],pan_block[PINLEN];
unsigned char key_block[PINLEN];
unsigned char bits[64];
for(i=0;i<8;i++)
key_block[i]=workkey[i];
for (i=0;i<8;i++)
clear_txt[i] = input[i];
expand(key_block,bits);
setkey(bits);
expand(clear_txt,bits); /* expand to bit stream */
encrypt(bits,ENCRYPT); /* encrypt */
compress(bits,cipher_txt); /* compress to 8 characters */
memcpy(output ,cipher_txt,8);
}
void key_des_Asc( unsigned char *input, unsigned char *workkey, unsigned char *output )
{
char cdesinput[PINLEN],cdeskey[PINLEN],cdesoutput[PINLEN];
memset(cdesinput, '\0', PINLEN);
memset(cdeskey, '\0', PINLEN);
memset(cdesoutput, '\0', PINLEN);
gCompressAsc( input, 16, cdesinput );
gCompressAsc( workkey, 16, cdeskey );
key_des_Bcd( cdesinput, cdeskey, cdesoutput );
gSplitBcd( cdesoutput, 16, output );
}
void key_undes_Bcd( unsigned char *input,unsigned char *workkey,unsigned char *output )
{
int i;
unsigned char clear_txt[PINLEN],cipher_txt[17];
unsigned char pin_block[PINLEN],pan_block[PINLEN];
unsigned char key_block[PINLEN];
unsigned char bits[64];
for(i=0;i<8;i++)
key_block[i]=workkey[i];
/* get pan_block */
expand(key_block,bits);
setkey(bits);
/* set key */
expand(input,bits); /* expand to bit stream */
encrypt(bits,DESCRYPT); /* descrypt */
compress(bits,clear_txt); /* compress to 8 characters */
for (i=0;i<8;i++)
pin_block[i] = clear_txt[i];
memcpy(output ,pin_block, 8);
}
void key_undes_Asc( unsigned char *input, unsigned char *workkey, unsigned char *output )
{
unsigned char cdesinput[PINLEN],cdeskey[PINLEN],cdesoutput[PINLEN];
memset(cdesinput, '\0', PINLEN);
memset(cdeskey, '\0', PINLEN);
memset(cdesoutput, '\0', PINLEN);
gCompressAsc( input, 16, cdesinput );
gCompressAsc( workkey, 16, cdeskey );
key_undes_Bcd( cdesinput, cdeskey, cdesoutput );
gSplitBcd( cdesoutput, 8, output );
}
void pan_des_Bcd(unsigned char* input, unsigned char* pan,unsigned char* key, unsigned char *output)
{
int i,len;
unsigned char clear_txt[8],cipher_txt[8];
unsigned char pin_block[8],pan_block[8];
unsigned char key_block[8];
unsigned char bits[64];
unsigned char cdesinput[PINLEN],cdeskey[PINLEN],cdesoutput[PINLEN],cascoutput[17];
memcpy(cdeskey, key, 8 );
memcpy(cdesinput,input, 8 );
cdeskey[8] ='\0';
cdesinput[6] = '\0';
memset(cascoutput,'\0',17);
pan[16] = '\0';
// printf("input[%s] pan[%s] key[%s]\n",cdesinput,pan,cdeskey);
for(i=0;i<8;i++)
key_block[i]=cdeskey[i];
pan_block[0]=pan_block[1]='\0';
for (i=1;i<7;i++)
pan_block[i+1] = ( (pan[2*i+1]-'0') <<4) | (pan[2*i+2]-'0') ;
//len=strlen((const char*) cdesinput);
len=strlen(cdesinput);
//if(len%2)
//{
//printf("벻Ϊ..0!!\n");
// }
pin_block[0]=len;
for(i=len/2+1;i<8;i++)
pin_block[i] = 0xff;
for ( i=0;i<len/2;i++)
pin_block[i+1] = ((cdesinput[2*i]-'0')<<4) | (cdesinput[2*i+1]-'0');
for (i=0;i<8;i++)
clear_txt[i] = pin_block[i] ^ pan_block[i];
expand(key_block,bits);
setkey(bits);
expand(clear_txt,bits); /* expand to bit stream */
encrypt(bits,ENCRYPT); /* encrypt */
compress(bits,cipher_txt); /* compress to 8 characters */
memcpy(output, cipher_txt, 8);
output[8] = '\0';
// gSplitBcd(output, 8, cascoutput);
}
void pan_des_Asc(unsigned char *input, unsigned char *pan, unsigned char *key,unsigned char *output)
{
unsigned char cdesinput[9],cdeskey[9],cdesoutput[9];
memset(cdesinput,'\0',9);
memset(cdeskey,'\0',9);
memset(cdesoutput, '\0', 9);
gCompressAsc( input, 16, cdesinput );
gCompressAsc( key, 16, cdeskey );
pan_des_Bcd( cdesinput, pan, cdeskey, cdesoutput );
gSplitBcd(cdesoutput, 8, output);
}
void pan_undes_Bcd(unsigned char *input,unsigned char *pan,unsigned char *key,unsigned char *output)
{
int i,len;
unsigned char clear_txt[PINLEN],cipher_txt[17];
unsigned char pin_block[PINLEN],pan_block[PINLEN];
unsigned char key_block[PINLEN];
unsigned char bits[64];
unsigned char cdesinput[9],cdeskey[9],cdesoutput[9],cascoutput[17];
memcpy(cdeskey, key, 8 );
memcpy(cdesinput, input, 8 );
for(i=0;i<8;i++)
key_block[i]=cdeskey[i];
/*****
key_block[0] = 0x31; key_block[1] = 0x31;
key_block[2] = 0x31; key_block[3] = 0x31;
key_block[4] = 0x31; key_block[5] = 0x31;
key_block[6] = 0x31; key_block[7] = 0x31;
*****/
/* get pan_block */
pan_block[0]=pan_block[1]='\0';
for (i=1;i<7;i++)
pan_block[i+1] = ( (pan[2*i+1]-'0') <<4) | (pan[2*i+2]-'0') ;
expand(key_block,bits);
setkey(bits); /* set key */
/********
pin[0] = 0x65; pin[1] = 0x5e;
pin[2] = 0xa6; pin[3] = 0x28;
pin[4] = 0xcf; pin[5] = 0x62;
pin[6] = 0x58; pin[7] = 0x5f;
*********/
expand(cdesinput,bits); /* expand to bit stream */
encrypt(bits,DESCRYPT); /* descrypt */
compress(bits,clear_txt); /* compress to 8 characters */
for (i=0;i<8;i++)
pin_block[i] = clear_txt[i] ^ pan_block[i];
/* get pin_block */
len=pin_block[0]&0x0f;
for(i=0;i<len/2;i++){
cipher_txt[2*i]= ((pin_block[i+1]>>4)&0x0f)+'0';
cipher_txt[2*i+1]= (pin_block[i+1]&0x0f)+'0';
}
memcpy(output, cipher_txt, 8);
output[8] = '\0';
}
void pan_undes_Asc(unsigned char *input, unsigned char *pan, unsigned char *key,unsigned char *output)
{
unsigned char cdesinput[9],cdeskey[9],cdesoutput[9];
memset(cdesinput,'\0',9);
memset(cdeskey,'\0',9);
memset(cdesoutput, '\0', 9);
gCompressAsc( input, 16, cdesinput );
gCompressAsc( key, 16, cdeskey );
pan_undes_Bcd( cdesinput, pan, cdeskey, cdesoutput );
gSplitBcd(cdesoutput, 8, output);
}
|
C
|
#include"header.h"
void cetak(int angka){
if(angka==15){
}
else {
if(angka%2==1){
printf(" %d ",angka);
}
cetak(angka+1);
}
}
void CetakGanjil(int n){
// BASIS
if (n==0){
}
// REKURENS
else{
//CetakGanjil(n-1); //ASCENDING
if(n%2==1){
// printf("%i ",n);
}
printf("%i ",n); //(UNTUK MENGURUTKAN)
CetakGanjil(n-1); //DESCENDING
}
}
|
C
|
#ifndef ENEMY_H_
#define ENEMY_H_
#define ENEMY_NUM 26
#define ENEMY_SNUM 50
#include "main.h"
struct ENEMY {
//W
D3DXVECTOR2 enemy_position;
//摜TCY
float width, height;
//oA~AAҁA˃^C~O
int in_time, stop_time, shot_time, out_time;
//G̎
int type;
//e̎
int shotType;
//ړp^[
int move_pattern;
//Vbgp^[
int shot_pattern;
//Health Point
int hp;
//ĂACe^Cv
int item;
//GoẴJE
int count;
//Control how many bullets an enemy shoots once
int bulletNum;
//Shooting bullet's radian
double shootingRadian;
//GŃtO
bool deadFlag;
//GNXŃtO
bool endFlag;
//e\
E_SHOT shot[ENEMY_SNUM];
//VbgĂ悤ɂȂ̃tO
bool sFlag;
//VbgłĂ悤ɂȂẴJEg
int sCount;
};
struct ENEMYDATA {
int type; //G
int shotType; //e
int move_pattern; //ړp^[
int shot_pattern; //˃p^[
int in_time; //o
int stop_time; //~
int shot_time; //eˎ
int out_time; //AҎ
int x; //xW
int y; //yW
int speed; //eXs[h
int hp; //HP
int item; //ACe
};
void enemyInit();
void enemyUpdate();
void enemyDraw();
void enemyMove();
void enemyShot();
void readENEMYDATA();
bool checkOutOfRange(ENEMY enemy);
bool checkEnemyShotOutOfRange(ENEMY enemy, int index);
void getEnemyPosition(int index, float *x, float *y);
bool getEnemyPositions(int index, float *x, float *y);
bool getEnemyShotPosition(int enemyIndex, int shotIndex, float *x, float *y);
void setEnemyShotFlag(int enemyIndex, int shotIndex, bool flag);
int getEnemyShotType(int enemyIndex);
void setEnemyDeadFlag(int index);
bool getEnemyDeadFlag(int index);
int getEnemyInTime(int index);
int getEnemyItemType(int index);
void setEnemyHp(int index, int num);
int getEnemyHP(int index);
int getEnemyLeft();
void setEnemyLeft(int num);
#endif // !ENEMY_H_
|
C
|
#include "types.h"
#include <stdlib.h>
#include <stdio.h>
Color *init_color(unsigned char r, unsigned char g, unsigned char b)
{
Color *color = malloc(sizeof(Color));
color->r = r;
color->g = g;
color->b = b;
return color;
}
void puts_map(float height_map[SCREEN_HEIGHT][SCREEN_WIDTH])
{
for (int i = 0; i < SCREEN_HEIGHT; i++)
{
for (int j = 0; j < SCREEN_WIDTH; j++)
printf("%15f ", height_map[i][j]);
puts("");
}
}
|
C
|
// Binary operator / division
int main(){
int a = 35;
int b = 5;
return a/b;
}
|
C
|
#include <stdio.h>
#define BUFSIZE 1024
int main(void)
{
char line[BUFSIZE];
while (fgets(line, BUFSIZE, stdin) != NULL) {
int words = 0, letters = 0;
int i = 0;
while (line[i] != '\n') {
if ((i == 0 && line[i] != ' ') ||
(i > 0 && line[i-1] == ' ' && line[i] != ' ')) //단어의 수는 공백을 기준으로 나눕니다.
words++;
if (line[i] != ' ') letters++; //문자의 수는 공백이 아닌 것을 기준으로 나눕니다.
i++;
}
printf("%d %d\n", words, letters);
}
return 0;
}
|
C
|
#include <sys/socket.h>
#include <string.h>
#include <sys/time.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <pthread.h>
#include <ctype.h>
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
//GLOBALS
//Max Connections
#define N 5
#define MAX 5000
//Struct of a tunnel
struct tunnel{
//info about server I want to tunnel to
char servIP[50];
char servPort[50];
//info about where to listen for info
int myPort;
};
//List of tunnels
struct tunnel tuns[N];
//Amount of tunnels
int amountT;
//THREADED
//Takes the tunnel number
void *connectionListen(void* tunNum){
int *tunTest = (int*)tunNum;
int tun = *tunTest;
char IP[50];
char outPort[50];
int myport = tuns[tun].myPort;
strcpy(IP,tuns[tun].servIP);
strcpy(outPort,tuns[tun].servPort);
char buf[MAX];
//CREATE myADDR and stuff TO TALK WITH A
struct sockaddr_in myaddr; //OUR ADDRESS
struct sockaddr_in remaddr; //REMOTE ADDRESS
socklen_t addrlen = sizeof(remaddr);
int recvlen;
int fd;
//make udp socket
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
printf("SOCKET ERROR\n");
}
//bind the socket to any valid IP and specific port
memset((char*)&myaddr, 0,sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = htons(myport);
if (bind(fd, (struct sockaddr*)&myaddr, sizeof(myaddr)) < 0) {
printf("BIND FAIL\n");
}
//CREATE HOSTENT and SERVADDR TO TALK WITH B
struct hostent *hp; //host info
struct sockaddr_in servaddr; //server address
socklen_t servlen = sizeof(servaddr);
//fill in server info
memset((char*)&servaddr,0,sizeof(servaddr));
servaddr.sin_family = AF_INET;
//servaddr.sin_port = htons(atoi(outPort));
servaddr.sin_port = htons(atoi(outPort));
//look up address of server with name
hp = gethostbyname(IP);
if(!hp){
printf("Could not find IP\n");
}
//put hte hosts address into the server address struct
memcpy((void*)&servaddr.sin_addr, hp->h_addr_list[0], hp->h_length);
while(1) {
printf("\nPORT %d is Waiting\n",myport);
bzero(buf,MAX);
//LISTEN TO myport FOR A
recvlen = recvfrom(fd,buf,MAX,0,(struct sockaddr *)&remaddr,&addrlen);
printf("RECIEVED at PORT %d:\n'%s'\n",myport,buf);
//cull down length
char *b = buf;
int i = 0;
while (*b) {
i++;
b++;
}
b=buf;
if (*b == '$') {
printf("PING PROTOCOL\n");
//SEND INFO TO IP (B)
printf("SENDING TO %s-%s\n",IP,outPort);
sendto(fd,buf,i,0,(struct sockaddr*)&servaddr, sizeof(servaddr));
//LISTEN FOR RESPONSE? (B)
bzero(buf,MAX);
//this sometimes hangs
struct timeval timeout={5,0};
setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout,sizeof(struct timeval));
int rec = recvfrom(fd,buf,MAX,0,(struct sockaddr*)&servaddr, &servlen);
if (rec > 0) {
printf("RECIEVED from %s-%s:%s\n",IP,outPort,buf);
b = buf;
i = 0;
while (*b) {
i++;
b++;
}
//FWD RESPONSE TO (A)
sendto(fd,buf,i,0,(struct sockaddr *) &remaddr, addrlen);
} else {
printf("Hanged! Skipping!\n");
}
} else if (*b == 'L') {
printf("TRAFFIC PROTOCOL\n");
//SEND INFO TO IP (B)
printf("SENDING TO %s-%s\n",IP,outPort);
sendto(fd,buf,i,0,(struct sockaddr*)&servaddr, sizeof(servaddr));
//LISTEN FOR RESPONSES for X times (B)
for (int x = 0; x < i-1; ++x) {
//Get message
bzero(buf,MAX);
recvlen = recvfrom(fd,buf,MAX,0,(struct sockaddr *)&remaddr,&addrlen);
printf("RECIEVED at PORT %d:\n'%s'\n",myport,buf);
//send message
printf("SENDING TO %s-%s\n",IP,outPort);
sendto(fd,buf,i,0,(struct sockaddr*)&servaddr, sizeof(servaddr));
}
for (int x = 0; x < 3; ++x) {
bzero(buf,MAX);
recvlen = recvfrom(fd,buf,MAX,0,(struct sockaddr *)&remaddr,&addrlen);
printf("RECIEVED at PORT %d:\n'%s'\n",myport,buf);
//send message
printf("SENDING TO %s-%s\n",IP,outPort);
sendto(fd,buf,3,0,(struct sockaddr*)&servaddr, sizeof(servaddr));
}
printf("TRAFFIC PROTOCOL END\n");
}
}
}
//Listens for incoming stuff
int main (int argc, char *argv[]) {
//GET PORT
int port = 0;
if (argc <= 1) {
port = 8000;
} else {
try{
port = atoi(argv[1]);
} catch(...){
port = 8000;
}
if (port == 0 || port < 1024){
printf("Illegal Port Entered, assuming port 8000\n");
port = 8000;
}
printf("Assigned Port is %d\n",port);
}
//init connections
amountT = 0;
//START LISTENING FOR INPUTS
//CODE TAKEN from CS.rutgers
struct sockaddr_in myaddr; /* our address */
struct sockaddr_in remaddr; /* remote address */
socklen_t addrlen = sizeof(remaddr); /* length of addresses */
int recvlen; /* # bytes received */
int fd; /* our socket */
char buf[MAX]; /* receive buffer */
/* create a UDP socket */
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
printf("cannot create socket\n");
return 0;
}
/* bind the socket to any valid IP address and a specific port */
memset((char *)&myaddr, 0, sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = htons(port);
if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
printf("bind failed\n");
return 0;
}
/* now loop, receiving data and printing what we received */
for (;;) {
printf("waiting on port %d\n", port);
recvlen = recvfrom(fd, buf, MAX, 0, (struct sockaddr *)&remaddr, &addrlen);
printf("received %d bytes\n", recvlen);
if (recvlen > 0) {
buf[recvlen] = 0;
printf("received message: \"%s\"\n", buf);
}
//PULL APART MESSAGE
//Language:MYIP MYPORT targetIP targetPort (we can ignore MY*)
char *targetIP;
char *targetPort;
char *w = buf;
int flag = 0;
while (*w != 0) {
if (*w == ' ') {
*w = 0;
flag++;
if (flag == 2)
targetIP = (w+1);
else if (flag ==3){
targetPort = (w+1);
break;
}
}
++w;
}
//Open up connection
if (amountT >= N) {
// SEND FULL
char reply[50];
strcpy(reply, "Full on Connections\n");
sendto(fd,reply,50,0,(struct sockaddr *)&remaddr,addrlen);
} else {
//ADD CONNECTION
strcpy(tuns[amountT].servIP,targetIP);
strcpy(tuns[amountT].servPort,targetPort);
//Get port number
int returnPort = 8010;
returnPort += amountT;
tuns[amountT].myPort = returnPort;
//START LISTENING THREAD
pthread_t listen;
int send = amountT;
pthread_create(&listen,NULL, connectionListen,&send);
//RETURN PORT TO USER
//use SENDTO to report port back
char portNumber[50];
sprintf(portNumber, "%d",returnPort);
sendto(fd,portNumber,50,0,(struct sockaddr *)&remaddr,addrlen);
++amountT;
}
} /* never exits */
}
|
C
|
#include "holberton.h"
/**
* print_diagonal - If else statement
* @n: integer number
* Return: 0 (Succes)
*/
void print_diagonal(int n)
{
int c, i;
c = 0;
while (n > 0)
{
i = c;
while (i > 0)
{
_putchar(' ');
i--;
}
_putchar('\\');
_putchar('\n');
c++;
n--;
}
if (c < 1)
_putchar('\n');
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
pid_t child_pid, parent_pid;
double s=0.0;
child_pid=fork();
if(child_pid!=0){
s+=3.14;
fprintf(stdout, "CHILD: %i s=%g &s=%u\n", (int) getpid(),s,&s);
}
else{
s+=2.72;
fprintf(stdout, "PARENT: %i s=%g &s=%u\n", (int) getpid(),s, &s);
}
return 0;
}
|
C
|
#ifndef RECTANGLE_H
#define RECTANGLE_H
#include <stdbool.h>
typedef struct {int x, y;} point;
typedef struct {point upper_left, lower_right; } rectangle;
int area(rectangle r);
point center(rectangle r);
rectangle move(rectangle r, int x, int y);
bool is_inside(rectangle r, point p);
int height(rectangle r);
int width(rectangle r);
#endif
|
C
|
/*
* File: data.h
* Author: daniel
*
* Created on July 27, 2013, 3:22 PM
*/
#ifndef DATA_H
#define DATA_H
#include "types.h"
#include "memory.h"
/* represents the Data Section of the code */
typedef struct
{
/* the underlying memory buffer */
Memory *memory;
/* the base offset of the data */
Word dataBaseAddress;
} DataSection;
#define DATA_PARSE_ERROR -2
#define DATA_WRITE_ERROR -1
DataSection *initDataSection();
void freeDataSection(DataSection *dataSection);
int writeDataArray(DataSection *dataSection, SourceLinePtr sourceLine);
int writeDataString(DataSection *dataSection, SourceLinePtr sourceLine);
void writeDataSection(DataSection *dataSection, FILE *file);
void printDataSection(DataSection *dataSection);
Word getDataSectionSize(DataSection *dataSection);
/* used to add the code section offset to the data. */
void increaseDataSectionOffset(DataSection *dataSection, Word offset);
#endif /* DATA_H */
|
C
|
//
// Created by dholl_000 on 3/24/2018.
//
#define malloc(x) myallocate(x, __FILE__, __LINE__, THREADREQ)
#define free(x) mydeallocate(x, __FILE__, __LINE__, THREADREQ)
#define BLOCK_SIZE 8000000;
#include "myallocate.h"
#include<stddef.h>
#include<stdio.h>
char memory[BLOCK_SIZE] ;
struct block* blocklist ;
int main{
blocklist = (void*)memory ;
}
void initialize(struct block *ptr){
blocklist->size = BLOCK_SIZE - sizeof(struct block); //avaialbbe space for malloc
blocklist->free = '1'; // initalize the block to signal it is free
blocklist->next = NULL ;
}
void split(struct block *fill, size_t size) {//use to split memory for a requested sized that is smaller than what we have
struct block *partiation = (void *)((void *)fill+size+sizeof(struct block));
partiation->size = (fill->size) - size - sizeof(struct block);
partiation->free = '1';
partiation->next = fill->next;
fill->size = size;
fill->free = '0';
fill->next = partiation->next;
}
void myMalloc(size_t sizeBits,RequestType){
struct block *current, *prev; //the current and previous memory blocks
if(blocklist->size >= BLOCK_SIZE){
printf("Error, not initialized");
}
//partiation the memory block
if(sizeBits >= sizeof(blocklist->size)){
printf("error, request of memory too large") ;
}
current = blocklist; //set pointer to first block;
//loop through to find the first free block to use for allocation
while(((current->size <sizeBits)||(current->free.equals('0')))&&(current.next!=NULL)){
prev = current;
current = current.next;
}
//will loop until find a block that can be allocated
//case 1, requested size fits
if(sizeBits >=8) { //for small allocations
}
}
void merge() { //to help elimatante space, merge consective free blocks of data
struct block *current, *prev;
current = blocklist;
while((current->next)!= NULL){
if(current->free.equals(1''))
}
}
void mydeallocate(void *ptr){
if(((void *)memory <=ptr)&&(ptr<=(void*)memory+BLOCK_SIZE)){
struct block *current = ptr;
--current;
current->free =1;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
//A - tar en beskjed som kommandolinjearg. lagrer beskjeden i variabelen msg
//skriver ut beskjeden "Input: " etterfulgt av msg.
//B - skal gi en feilmelding/hjelpetekst hvis brukeren ikke sender med noe argument
//på kommandolinjen
//C - sjekk om msg er et heltall
if(argc == 0) {
printf("Usage: ./a.out <beskjed>");
return 0;
}
char *msg[argc];
int msgTall;
int i;
for(i = 0; i < argc; i++) {
if(msg[i] == 0 || msg[i] == 1 || msg[i] == 2 || msg[i] == 3 || msg[i] == 4 || msg[i] == 5 || msg[i] == 6 || msg[i] == 7 || msg[i] == 8 || msg[i] == 9) {
msgTall[i] = msg[i];
}
msg[i] = argv[i];
}
printf("%s\n", msg);
printf("%d", msgTall);
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
int fp;
int p, bytesleidos;
char saludo[] = "Un saludo!!!\n", buffer[10];
p = mknod("FIFO2", S_IFIFO | 0666, 0); //permiso de lectura y escritura
if (p == -1)
{
printf("HA OCURRIDO UN ERROR... \n");
exit(0);
}
while (1)
{
fp = open("FIFO2", 0);
bytesleidos = read(fp, buffer, 1);
printf("OBTENIENDO Informacion...");
while (bytesleidos != 0)
{
printf("%s", buffer);
bytesleidos = read(fp, buffer, 1); //leo otro byte
}
close(fp);
}
return (0);
}
|
C
|
/*-------------------------------------------------------------------------
*
* Copyright (c) 2013, Max Planck Institute for Marine Microbiology
*
* This software is released under the PostgreSQL License
*
* Author: Michael Schneider <mschneid@mpi-bremen.de>
*
* IDENTIFICATION
* src/sequence/generation.c
*
*-------------------------------------------------------------------------
*/
#include <stdlib.h>
#include "postgres.h"
#include "fmgr.h"
#include "sequence/sequence.h"
#include "types/alphabet.h"
#include "utils/debug.h"
Datum generate_sequence (PG_FUNCTION_ARGS);
/**
* generate_sequence()
* Generate a random sequence.
*
* PB_Alphabet* input : Alphabet
* int32 : sequence length
*/
PG_FUNCTION_INFO_V1 (generate_sequence);
Datum generate_sequence (PG_FUNCTION_ARGS) {
PB_Alphabet* input =
(PB_Alphabet*) PG_DETOAST_DATUM(PG_GETARG_POINTER(0));
int32 sequence_length = PG_GETARG_INT32(1);
text* result;
char* output_pointer;
PB_Symbol* symbols;
PB_SymbolProbability* probabilities;
PB_SymbolProbability* cumulative_probabilities;
PB_SymbolProbability sum;
int i,j;
int mem_size;
PB_TRACE(errmsg("->generate_sequence() of length %d", sequence_length));
symbols = PB_ALPHABET_SYMBOL_POINTER(input);
if (PB_ALPHABET_TYPE(input) == PB_ALPHABET_WITH_PROBABILITIES)
probabilities = PB_ALPHABET_SYMBOL_PROBABILITY_POINTER(input);
else
{
/*
* If there are no probabilities in the alphabet, assume equal distribution
*/
PB_SymbolProbability equal_probability = 1.0f / PB_ALPHABET_SIZE(input);
probabilities = palloc0(PB_ALPHABET_SIZE(input) * sizeof(PB_SymbolProbability));
for (i = 0; i < PB_ALPHABET_SIZE(input); i++)
{
probabilities[i] = equal_probability;
}
}
/*
* Compute cumulative probabilities.
*/
cumulative_probabilities = palloc0(PB_ALPHABET_SIZE(input) * sizeof(PB_SymbolProbability));
sum = 0.0f;
for (i = 0; i < PB_ALPHABET_SIZE(input); i++)
{
cumulative_probabilities[i] = sum;
sum += probabilities[i];
PB_DEBUG2(errmsg("generate_sequence(): symbol %c cumprob %f", symbols[i],sum));
}
mem_size = VARHDRSZ + sequence_length * sizeof(PB_Symbol);
result = palloc0(mem_size);
SET_VARSIZE(result,mem_size);
output_pointer = VARDATA(result);
/*
* Generate random number between 0 and 1, use cumulative
* probabilites to find the respective symbol.
*/
for (j = sequence_length - 1; j >= 0; output_pointer++, j--)
{
PB_SymbolProbability random_number;
random_number = (PB_SymbolProbability) rand() / (PB_SymbolProbability) RAND_MAX;
for (i = PB_ALPHABET_SIZE(input) - 1; i >= 0 ; i--)
{
if (random_number >= cumulative_probabilities[i])
{
*output_pointer = symbols[i];
break;
}
}
}
pfree(cumulative_probabilities);
if (PB_ALPHABET_TYPE(input) == PB_ALPHABET_WITHOUT_PROBABILITIES)
pfree(probabilities);
PB_TRACE(errmsg("<-generate_sequence()"));
PG_RETURN_TEXT_P(result);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "final_project.h"
typedef struct {
int id;
int variant_id;
char selling_price[20];
char rrp_price[20];
int order_limit;
int show_in_price_history;
int active;
char created_at[50];
int product_id;
int marketplace_seller_id;
} ProductHistory;
static void parse_csv(char *line, ProductHistory *product, const char *sep) {
int i = 0;
char *token;
while ((token = strsep(&line, sep)) != NULL) {
sscanf(token, "\"%[^\"]\"", token);
switch (i++) {
case 0:
product->id = atoi(token);
break;
case 1:
product->variant_id = atoi(token);
break;
case 2:
strcpy(product->selling_price, token);
break;
case 3:
strcpy(product->rrp_price, token);
break;
case 6:
product->order_limit = atoi(token);
break;
case 10:
product->show_in_price_history = atoi(token);
break;
case 11:
product->active = atoi(token);
break;
case 12:
strcpy(product->created_at, token);
break;
case 13:
product->product_id = atoi(token);
break;
case 14:
product->marketplace_seller_id = atoi(token);
break;
default:
break;
}
}
}
int insert_product_history(ProductHistory *productHistory) {
char insert_cmd[8000];
sprintf(insert_cmd,
"INSERT INTO product_history (product_history_id, product_variant_id, selling_price, rrp_price, order_limit, show_in_price_history, active, created_at, product_id, marketplace_seller_id) VALUE (%d, %d, %s, %s, %d, %d, %d, '%s', %d, %d);",
productHistory->id, productHistory->variant_id, productHistory->selling_price, productHistory->rrp_price,
productHistory->order_limit, productHistory->show_in_price_history,
productHistory->active, productHistory->created_at, productHistory->product_id,
productHistory->marketplace_seller_id);
if (mysql_query(mysql, insert_cmd) != 0)
return -1;
return 0;
}
int write_file(const char *path, ProductHistory *productHistory) {
FILE *file;
file = fopen(path, "a");
if (file == NULL)
return -1;
fprintf(file, "%d,%d,%s,%s,%d,%d,%d,\"%s\",%d,%d\n",
productHistory->id, productHistory->variant_id, productHistory->selling_price, productHistory->rrp_price,
productHistory->order_limit, productHistory->show_in_price_history,
productHistory->active, productHistory->created_at, productHistory->product_id,
productHistory->marketplace_seller_id);
fclose(file);
return 0;
}
int load_products_history() {
FILE *fp;
fp = fopen(products_history_dataset_path, "r");
if (fp == NULL)
return -1;
char line[10000];
ProductHistory productHistory = {0};
while (fscanf(fp, "%[^\n]\n", line) != EOF) {
parse_csv(line, &productHistory, ",");
// // Insert product history
// if (insert_product_history(&productHistory) == -1) {
// printf("\tInsert product history #%d failed: %s\n", productHistory.id, mysql_error(mysql));
// continue;
// }
// Write to file
if (write_file("./data/product_history.csv", &productHistory) == -1) {
printf("Cannot write to file.\n");
return -1;
}
}
if (mysql_query(mysql,
"LOAD DATA LOCAL INFILE './data/product_history.csv' INTO TABLE product_history FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\\n';") !=
0) {
printf("\tInsert product history #%d failed: %s\n", productHistory.id, mysql_error(mysql));
fclose(fp);
return -1;
}
fclose(fp);
return 0;
}
|
C
|
/*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_INTERNAL_TIME_H
# define OSSL_INTERNAL_TIME_H
# pragma once
# include <openssl/e_os2.h> /* uint64_t */
# include "internal/e_os.h" /* for struct timeval */
# include "internal/safe_math.h"
/*
* Internal type defining a time.
* This should be treated as an opaque structure.
*
* The time datum is Unix's 1970 and at nanosecond precision, this gives
* a range of 584 years roughly.
*/
typedef struct {
uint64_t t; /* Ticks since the epoch */
} OSSL_TIME;
/* The precision of times allows this many values per second */
# define OSSL_TIME_SECOND ((uint64_t)1000000000)
/* One millisecond. */
# define OSSL_TIME_MS (OSSL_TIME_SECOND / 1000)
/* One microsecond. */
# define OSSL_TIME_US (OSSL_TIME_MS / 1000)
/* One nanosecond. */
# define OSSL_TIME_NS (OSSL_TIME_US / 1000)
#define ossl_seconds2time(s) ossl_ticks2time((s) * OSSL_TIME_SECOND)
#define ossl_time2seconds(t) (ossl_time2ticks(t) / OSSL_TIME_SECOND)
#define ossl_ms2time(ms) ossl_ticks2time((ms) * OSSL_TIME_MS)
#define ossl_time2ms(t) (ossl_time2ticks(t) / OSSL_TIME_MS)
#define ossl_us2time(us) ossl_ticks2time((us) * OSSL_TIME_US)
#define ossl_time2us(t) (ossl_time2ticks(t) / OSSL_TIME_US)
/* Convert a tick count into a time */
static ossl_unused ossl_inline
OSSL_TIME ossl_ticks2time(uint64_t ticks)
{
OSSL_TIME r;
r.t = ticks;
return r;
}
/* Convert a time to a tick count */
static ossl_unused ossl_inline
uint64_t ossl_time2ticks(OSSL_TIME t)
{
return t.t;
}
/* Get current time */
OSSL_TIME ossl_time_now(void);
/* The beginning and end of the time range */
static ossl_unused ossl_inline
OSSL_TIME ossl_time_zero(void)
{
return ossl_ticks2time(0);
}
static ossl_unused ossl_inline
OSSL_TIME ossl_time_infinite(void)
{
return ossl_ticks2time(~(uint64_t)0);
}
/* Convert time to timeval */
static ossl_unused ossl_inline
struct timeval ossl_time_to_timeval(OSSL_TIME t)
{
struct timeval tv;
#ifdef _WIN32
tv.tv_sec = (long int)(t.t / OSSL_TIME_SECOND);
#else
tv.tv_sec = (time_t)(t.t / OSSL_TIME_SECOND);
#endif
tv.tv_usec = (t.t % OSSL_TIME_SECOND) / OSSL_TIME_US;
return tv;
}
/* Convert timeval to time */
static ossl_unused ossl_inline
OSSL_TIME ossl_time_from_timeval(struct timeval tv)
{
OSSL_TIME t;
#ifndef __DJGPP__ /* tv_sec is unsigned on djgpp. */
if (tv.tv_sec < 0)
return ossl_time_zero();
#endif
t.t = tv.tv_sec * OSSL_TIME_SECOND + tv.tv_usec * OSSL_TIME_US;
return t;
}
/* Convert OSSL_TIME to time_t */
static ossl_unused ossl_inline
time_t ossl_time_to_time_t(OSSL_TIME t)
{
return (time_t)(t.t / OSSL_TIME_SECOND);
}
/* Convert time_t to OSSL_TIME */
static ossl_unused ossl_inline
OSSL_TIME ossl_time_from_time_t(time_t t)
{
OSSL_TIME ot;
ot.t = t;
ot.t *= OSSL_TIME_SECOND;
return ot;
}
/* Compare two time values, return -1 if less, 1 if greater and 0 if equal */
static ossl_unused ossl_inline
int ossl_time_compare(OSSL_TIME a, OSSL_TIME b)
{
if (a.t > b.t)
return 1;
if (a.t < b.t)
return -1;
return 0;
}
/* Returns true if an OSSL_TIME is ossl_time_zero(). */
static ossl_unused ossl_inline
int ossl_time_is_zero(OSSL_TIME t)
{
return ossl_time_compare(t, ossl_time_zero()) == 0;
}
/* Returns true if an OSSL_TIME is ossl_time_infinite(). */
static ossl_unused ossl_inline
int ossl_time_is_infinite(OSSL_TIME t)
{
return ossl_time_compare(t, ossl_time_infinite()) == 0;
}
/*
* Arithmetic operations on times.
* These operations are saturating, in that an overflow or underflow returns
* the largest or smallest value respectively.
*/
OSSL_SAFE_MATH_UNSIGNED(time, uint64_t)
static ossl_unused ossl_inline
OSSL_TIME ossl_time_add(OSSL_TIME a, OSSL_TIME b)
{
OSSL_TIME r;
int err = 0;
r.t = safe_add_time(a.t, b.t, &err);
return err ? ossl_time_infinite() : r;
}
static ossl_unused ossl_inline
OSSL_TIME ossl_time_subtract(OSSL_TIME a, OSSL_TIME b)
{
OSSL_TIME r;
int err = 0;
r.t = safe_sub_time(a.t, b.t, &err);
return err ? ossl_time_zero() : r;
}
/* Returns |a - b|. */
static ossl_unused ossl_inline
OSSL_TIME ossl_time_abs_difference(OSSL_TIME a, OSSL_TIME b)
{
return a.t > b.t ? ossl_time_subtract(a, b)
: ossl_time_subtract(b, a);
}
static ossl_unused ossl_inline
OSSL_TIME ossl_time_multiply(OSSL_TIME a, uint64_t b)
{
OSSL_TIME r;
int err = 0;
r.t = safe_mul_time(a.t, b, &err);
return err ? ossl_time_infinite() : r;
}
static ossl_unused ossl_inline
OSSL_TIME ossl_time_divide(OSSL_TIME a, uint64_t b)
{
OSSL_TIME r;
int err = 0;
r.t = safe_div_time(a.t, b, &err);
return err ? ossl_time_zero() : r;
}
static ossl_unused ossl_inline
OSSL_TIME ossl_time_muldiv(OSSL_TIME a, uint64_t b, uint64_t c)
{
OSSL_TIME r;
int err = 0;
r.t = safe_muldiv_time(a.t, b, c, &err);
return err ? ossl_time_zero() : r;
}
/* Return higher of the two given time values. */
static ossl_unused ossl_inline
OSSL_TIME ossl_time_max(OSSL_TIME a, OSSL_TIME b)
{
return a.t > b.t ? a : b;
}
/* Return the lower of the two given time values. */
static ossl_unused ossl_inline
OSSL_TIME ossl_time_min(OSSL_TIME a, OSSL_TIME b)
{
return a.t < b.t ? a : b;
}
#endif
|
C
|
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// ????
#define D_CHAR_MAX 200005 // ?????
#define D_CHAR_CNT 26 // ?????
// ????
static FILE *szpFpI; // ??
static char sc1StrFrom[D_CHAR_MAX]; // ??? - ?
static char sc1StrTo[D_CHAR_MAX]; // ??? - ?
static int siSCnt; // ????
static char sc1ChgFrom[D_CHAR_CNT]; // ???? - ?
static char sc1ChgTo[D_CHAR_CNT]; // ???? - ?
// ???? - ????
#ifdef D_TEST
static int siRes;
static FILE *szpFpA;
#endif
// ?????
// ???????
int
fCutCrLf(
char *pcpStr // <I> ???
)
{
int i;
for (i = 0; pcpStr[i] != '\0'; i++) {
if (pcpStr[i] == '\n') {
pcpStr[i] = '\0';
break;
}
}
return i;
}
// ??
int
fJudge(
)
{
int i;
// ???????
for (i = 0; i < siSCnt; i++) {
int liFNo = sc1StrFrom[i] - 'a';
int liTNo = sc1StrTo[i] - 'a';
// ???? - ?
if (sc1ChgFrom[liFNo] == 0) { // ??
sc1ChgFrom[liFNo] = liTNo;
}
else if (sc1ChgFrom[liFNo] != liTNo) { // ???
return -1;
}
// ???? - ?
if (sc1ChgTo[liTNo] == 0) { // ??
sc1ChgTo[liTNo] = liFNo;
}
else if (sc1ChgTo[liTNo] != liFNo) { // ???
return -1;
}
}
return 0;
}
// ?????
int
fMain(
int piTNo // <I> ????? 1?
)
{
int liRet;
char lc1Buf[1024], lc1Out[1024];
// ??? - ???
memset(sc1ChgFrom, 0, sizeof(sc1ChgFrom)); // ???? - ?
memset(sc1ChgTo, 0, sizeof(sc1ChgTo)); // ???? - ?
// ?? - ???
#ifdef D_TEST
sprintf(lc1Buf, ".\\Test\\T%d.txt", piTNo);
szpFpI = fopen(lc1Buf, "r");
sprintf(lc1Buf, ".\\Test\\A%d.txt", piTNo);
szpFpA = fopen(lc1Buf, "r");
siRes = 0;
#else
szpFpI = stdin;
#endif
// ??? - ??
fgets(sc1StrFrom, sizeof(sc1StrFrom), szpFpI);
fgets(sc1StrTo, sizeof(sc1StrTo), szpFpI);
// ?????
siSCnt = fCutCrLf(sc1StrFrom);
// ??
liRet = fJudge();
// ?? - ???
if (liRet == 0) {
sprintf(lc1Out, "Yes\n");
}
else {
sprintf(lc1Out, "No\n");
}
// ?? - ??
#ifdef D_TEST
fgets(lc1Buf, sizeof(lc1Buf), szpFpA);
if (strcmp(lc1Buf, lc1Out)) {
siRes = -1;
}
#else
printf("%s", lc1Out);
#endif
// ???????????
#ifdef D_TEST
fclose(szpFpI);
fclose(szpFpA);
#endif
// ?????
#ifdef D_TEST
if (siRes == 0) {
printf("OK %d\n", piTNo);
}
else {
printf("NG %d\n", piTNo);
}
#endif
return 0;
}
int
main()
{
#ifdef D_TEST
int i;
for (i = D_TEST_SNO; i <= D_TEST_ENO; i++) {
fMain(i);
}
#else
fMain(0);
#endif
return 0;
} ./Main.c: In function fMain:
./Main.c:102:2: warning: ignoring return value of fgets, declared with attribute warn_unused_result [-Wunused-result]
fgets(sc1StrFrom, sizeof(sc1StrFrom), szpFpI);
^
./Main.c:103:2: warning: ignoring return value of fgets, declared with attribute warn_unused_result [-Wunused-result]
fgets(sc1StrTo, sizeof(sc1StrTo), szpFpI);
^
|
C
|
/*
* reimplementation of Daniel Bernstein's byte library.
* placed in the public domain by Uwe Ohse, uwe@ohse.de.
*/
#include "str.h"
int
str_start(const char *s,const char *t)
{
unsigned int i=0;
for (;;) {
if (!t[i]) return 1;
if (s[i]!=t[i]) return 0;
i++;
if (!t[i]) return 1;
if (s[i]!=t[i]) return 0;
i++;
if (!t[i]) return 1;
if (s[i]!=t[i]) return 0;
i++;
if (!t[i]) return 1;
if (s[i]!=t[i]) return 0;
i++;
}
}
|
C
|
/******************************************************************************
Stephanie Lampotang - March 19, 2020
Open Source Contribution for Free Distribution
University of Southern California
Computer Science
Equipment: Arduino Uno, LCD display, wires, buttons, breadboard
Link to purchase:
*******************************************************************************/
#include <avr/io.h>
#include <util/delay.h>
#include <stdlib.h>
#include <stdio.h>
#include <avr/interrupt.h>
#include "lcd.h"
volatile int bpm_chosen; // current breaths per minute that system is operating at
volatile int inhale_time; // amount of time in 1/100 secs that the inhale valve should remain open
volatile int exhale_time; // amount of time in 1/100 secs that the exhale valve should remain open
volatile int inhale_complete; // flag signifying the end of an inhale
volatile int exhale_complete; // flag signifying the end of an exhale
volatile int secs; // hundredths of seconds that have passed in this inhale or exhale
volatile int inhale; // true if system is in the inhale state of the breath, false if in the exhale state of the breath
volatile int exhale_to_inhale; // ration of the duration of the exhale to the duration of the inhale
int main(void)
{
// Initialize the LCD
lcd_init();
// Write splash screen
lcd_writecommand(1);
lcd_stringout("fight me covid19 :(");
// breaths per minute from 10 - 30 in increments of 5
int bpms[5] = {10, 15, 20, 25, 30};
// tidal volumes in milliliters from 450 - 800 in increments of 50
int tidal_volumes[8] = {450, 500, 550, 600, 650, 700, 750, 800};
_delay_ms(2000);
lcd_writecommand(1);
// set up the default parameters
int bpm_index = 0;
int vt_index = 5;
int vt_chosen = tidal_volumes[vt_index];
exhale_to_inhale = 2;
// SET parameters
bpm_chosen = bpms[bpm_index];
// times are in tenths of a second, so 600 represents 60 secs or 1 min
inhale_time = 600/(bpm_chosen)/(exhale_to_inhale+1);
exhale_time = 600/(bpm_chosen)*(exhale_to_inhale)/(exhale_to_inhale+1);
inhale_complete = 0;
exhale_complete = 0;
secs = 0;
inhale = 1;
char bpm_string[17];
snprintf(bpm_string, 17, "bpm: %d, etoi: %d", bpm_chosen, exhale_to_inhale);
lcd_stringout(bpm_string);
// Initializing pull-up resistors on PC5, PC4, and PC3 of the arduino
PORTC |= ((1 << PC5) | (1 << PC4) | (1 << PC3));
// Set up interrupts for every 1/100th of a second
TCCR1B |= (1 << WGM12);
TIMSK1 |= (1 << OCIE1A);
OCR1A = 6250;
TCCR1B |= (1 << CS12);
// turn on interrupts
sei();
while (1)
{ // Loop forever
if ((PINC & (1 << PC5)) == 0) { // button pressed -> recalculate
// debouncing code
_delay_ms(5);
while ((PINC & (1 << PC5)) == 0) {}
bpm_index++;
if (bpm_index >= 5) { // goes out of bounds -> loop around
bpm_index = 0;
}
// RESET parameters
bpm_chosen = bpms[bpm_index];
// times are in tenths of a second, so 600 represents 60 secs or 1 min
inhale_time = 600/(bpm_chosen)/(exhale_to_inhale+1);
exhale_time = 600/(bpm_chosen)*(exhale_to_inhale)/(exhale_to_inhale+1);
inhale_complete = 0;
exhale_complete = 0;
secs = 0;
inhale = 1;
snprintf(bpm_string, 17, "bpm: %d, etoi: %d", bpm_chosen, exhale_to_inhale);
lcd_stringout(bpm_string);
}
if ((PINC & (1 << PC4)) == 0) { // button pressed -> switch exhale_to_inhale
_delay_ms(5);
while ((PINC & (1 << PC4)) == 0) {}
if (exhale_to_inhale == 2) {
exhale_to_inhale = 1;
} else if (exhale_to_inhale == 1) {
exhale_to_inhale = 2;
}
// RESET parameters
bpm_chosen = bpms[bpm_index];
// times are in tenths of a second, so 600 represents 60 secs or 1 min
inhale_time = 600/(bpm_chosen)/(exhale_to_inhale+1);
exhale_time = 600/(bpm_chosen)*(exhale_to_inhale)/(exhale_to_inhale+1);
inhale_complete = 0;
exhale_complete = 0;
secs = 0;
inhale = 1;
snprintf(bpm_string, 17, "bpm: %d, etoi: %d", bpm_chosen, exhale_to_inhale);
lcd_stringout(bpm_string);
}
if ((PINC & (1 << PC3)) == 0) { // button pressed -> increase tidal volume by 50 mL
_delay_ms(5);
while ((PINC & (1 << PC3)) == 0) {}
vt_index++;
if (vt_index >= 8) { // goes out of bounds -> loop around
vt_index = 0;
}
// print the change in tidal volume
char vt_string[8];
snprintf(vt_string, 8, "vt: %d", vt_chosen);
lcd_moveto(1, 7);
lcd_stringout(vt_string);
}
if (inhale_complete) { // inhale is complete -> switch to exhale state
lcd_moveto(1, 0);
lcd_stringout("EXHALE");
inhale_complete = 0;
secs = 0;
inhale = 0;
} else if (exhale_complete) { // exhale is complete -> switch to inhale state
lcd_moveto(1, 0);
lcd_stringout("INHALE");
exhale_complete = 0;
secs = 0;
inhale = 1;
}
}
return 0; /* never reached */
}
ISR(TIMER1_COMPA_vect) {
secs++;
if (inhale) { // inhaling
if (secs >= inhale_time) {
inhale_complete = 1;
}
} else { // must be exhaling
if (secs >= exhale_time) {
exhale_complete = 1;
}
}
}
|
C
|
#include<stdio.h>
int main()
{
FILE *fp=NULL;
char ch;
int cnt, lines, tabs, spaces, digits, alphabets;
// path mode
fp= fopen("file1.txt","r");
if(fp==NULL)
printf("\n unable to open file");
else
{
cnt= lines= tabs= spaces= digits= alphabets=0;
while( (ch=fgetc(fp))!=EOF)
{
fputc(ch,stdout);
cnt++;
if((ch>=65 && ch<=90) || (ch>=97 && ch<=122))
alphabets++;
else if(ch>=48 && ch<=57)
digits++;
else if(ch==32 || ch==' ')
spaces++;
else if( ch=='\n')
lines++ ;
else if(ch=='\t')
tabs++;
//getchar();
}
fclose(fp); //close file fcloseall();
printf("\n %d char are added to file", cnt);
printf("\n no of alphabets %d ", alphabets);
printf("\n no of digits %d ", digits);
printf("\n no of lines %d ", lines);
printf("\n no of tabs %d ", tabs);
printf("\n no of spaces %d ", spaces);
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "aes-decrypt.h"
void testInvSubBytes();
void testInvShiftRows();
void testInvMixColumns();
int main() {
printf("? TESTING aes-decrypt ...\n");
testInvSubBytes();
testInvShiftRows();
testInvMixColumns();
printf("+ FINISHED aes-decrypt\n");
return 0;
}
void testInvSubBytes() {
printf("? \tTESTING invSubBytes ...\n");
unsigned char input[4][4] = {
{0x19,0xdb,0xa1,0xb4},
{0xe3,0x86,0xf8,0xc6},
{0x32,0x6a,0x3e,0xe8},
{0x65,0x5e,0x78,0xdd}
};
unsigned char output[4][4] = {
{0x8e,0x9f,0xf1,0xc6},
{0x4d,0xdc,0xe1,0xc7},
{0xa1,0x58,0xd1,0xc8},
{0xbc,0x9d,0xc1,0xc9}
};
unsigned char** state = (unsigned char**) malloc(4*sizeof(unsigned char*));
for (int i = 0; i < 4; i++) {
state[i] = (unsigned char*) malloc(4*sizeof(char));
for (int j = 0; j < 4; j++) {
state[i][j] = input[i][j];
}
}
invSubBytes(state);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (state[i][j] != output[i][j]) {
printf("! \t\tEXPECTED %d RECEIVED %d, (%d, %d)\n", output[i][j], state[i][j], i, j);
}
}
}
printf("+ \tFINISHED invSubBytes\n");
}
void testInvShiftRows() {
printf("? \tTESTING invShiftRows ...\n");
unsigned char input[4][4] = {
{0x8e,0x9f,0x01,0xc6},
{0xdc,0x01,0xc6,0x4d},
{0x01,0xc6,0xa1,0x58},
{0xc6,0xbc,0x9d,0x01}
};
unsigned char output[4][4] = {
{0x8e,0x9f,0x01,0xc6},
{0x4d,0xdc,0x01,0xc6},
{0xa1,0x58,0x01,0xc6},
{0xbc,0x9d,0x01,0xc6}
};
unsigned char** state = (unsigned char**) malloc(4*sizeof(unsigned char*));
for (int i = 0; i < 4; i++) {
state[i] = (unsigned char*) malloc(4*sizeof(char));
for (int j = 0; j < 4; j++) {
state[i][j] = input[i][j];
}
}
invShiftRows(state);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (state[i][j] != output[i][j]) {
printf("! \t\tEXPECTED %d RECEIVED %d, (%d, %d)\n", output[i][j], state[i][j], i, j);
}
}
}
printf("+ \tFINISHED invShiftRows\n");
}
void testInvMixColumns() {
printf("? \tTESTING invMixColumns ...\n");
unsigned char input[4][4] = {
{0x8e,0x9f,0x01,0xc6},
{0x4d,0xdc,0x01,0xc6},
{0xa1,0x58,0x01,0xc6},
{0xbc,0x9d,0x01,0xc6}
};
unsigned char output[4][4] = {
{0xdb,0xf2,0x01,0xc6},
{0x13,0x0a,0x01,0xc6},
{0x53,0x22,0x01,0xc6},
{0x45,0x5c,0x01,0xc6}
};
unsigned char** state = (unsigned char**) malloc(4*sizeof(unsigned char*));
for (int i = 0; i < 4; i++) {
state[i] = (unsigned char*) malloc(4*sizeof(char));
for (int j = 0; j < 4; j++) {
state[i][j] = input[i][j];
}
}
invMixColumns(state);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (state[i][j] != output[i][j]) {
printf("! \t\tEXPECTED %d RECEIVED %d, (%d, %d)\n", output[i][j], state[i][j], i, j);
}
}
}
printf("+ \tFINISHED invMixColumns\n");
}
|
C
|
/**
6.16 Write a program to print a square of size 5 by using the character S as shown below
a) S S S S S b) S S S S S
S S S S S S S
S S S S S S S
S S S S S S S
S S S S S S S S S S
*/
///program begin
#include<stdio.h>
#include<conio.h>
//main() function begin
int main()
{
int j,i;
for (i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
printf("S ");
printf("\n");
}
printf("\n\n");
for (i=1;i<=5;i++)
printf("S ");
for(j=2;j<=4;j++)
{
printf("\nS S");
}
printf("\n");
for (i=1;i<=5;i++)
printf("S ");
return 0;
}
///main() end
///program end
/**
output
S S S S S
S S S S S
S S S S S
S S S S S
S S S S S
S S S S S
S S
S S
S S
S S S S S
Process returned 0 (0x0) execution time : 0.021 s
Press any key to continue.
*/
|
C
|
#pragma once
#ifndef STRING_STREAM_H
#define STRING_STREAM_H
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include "macros.h"
#define STRING_STREAM_OK 1
#define STRING_STREAM_ERR_NO_MEMORY 2
#define STRING_STREAM_ERR_NULL_OBJ 3
#define CHECK_STREAM_PTR(stream) if (stream == NULL) return STRING_STREAM_ERR_NULL_OBJ;
#define CHECK_VECTOR_PTR(vector) if (vector == NULL) return STRING_STREAM_ERR_NULL_OBJ;
#define string_stream_init(context) string_stream_init_(context, __FILE__, __LINE__)
#define string_stream_add(stream, data) string_stream_add_(stream, data, __FILE__, __LINE__)
#define string_stream_add_char(stream, data) string_stream_add_char_(stream, data, __FILE__, __LINE__)
#define string_stream_get(stream, data) string_stream_get_(stream, data, __FILE__, __LINE__)
#define string_stream_destroy(stream) string_stream_destroy_(stream, __FILE__, __LINE__)
typedef struct _t_context* t_context_ptr;
typedef struct {
size_t length;
size_t text_length;
size_t index;
char** data;
t_context_ptr context;
} t_string_stream;
t_string_stream* string_stream_init_ (t_context_ptr context, char* file_name, size_t line_number);
int string_stream_add_ (t_string_stream* stream, char const* data, char* file_name, size_t line_number);
int string_stream_add_char_ (t_string_stream* stream, char data, char* file_name, size_t line_number);
int string_stream_get_ (t_string_stream* stream, char** data, char* file_name, size_t line_number);
int string_stream_destroy_ (t_string_stream* stream, char* file_name, size_t line_number);
#endif // STRING_STREAM_H
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int row,line;
char str[100] = {0};
char *p =str;
scanf("%d",&row);
scanf("%d",&line);
getchar();
int i,j,k,flag = 0;
int array[row][line];
memset(array,0,sizeof(array));
for(i = 0;i<row;i++)
{
memset(str,0,sizeof(str));
k = 0;
p = str;
gets(str);
while(*p != '\0')
{
if(*p == ' ')
{
if(flag ==1 ){
array[i][k] = array[i][k]*(-1);
flag = 0;
}
p++;
k++;
}
if(*p == '-'){
flag = 1;
}else{
array[i][k] = array[i][k]*10 + (*p-'0');
}
p++;
}
}
for(i = 0;i<line;i++)
{
for(j = 0;j<row;j++)
{
printf("%d ",array[j][i]);
}
printf("\n");
}
printf("%d\n",row);
printf("%d\n",line);
return 0;
}
|
C
|
/*
Autoria: Eduardo Cortez
Esse programa simula um sistema de cadastro e busca de carros;
Os dados referentes aos carros são:
- marca do veículo
- modelo
- ano de fabricação
- placa (formato XXX-YYYY)
As funções do sistema são:
- Listar os veículos cadastrados;
- Inserir um novo veículo (o sistema reordena os carros por ano de fabricação);
- Listar os veículos filtrando-se por ano de fabricação;
- Listar os veículos com o ano de fabricação acima de um certo valor especificado pelo usuário
- Listar os veículos filtrando-se pelo modelo.
*/
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
typedef struct placa
{
char xxx[4];
char yyyy[5];
}PLACA;
typedef struct carro
{
char marca[20];
char modelo[20];
int ano;
PLACA pl;
}CARRO;
void cadastrar(CARRO *c)
{
printf("\nPreencha as seguintes informações\n\n");
printf("Marca do veículo: ");
fgets(c->marca, 20, stdin);
c->marca[strcspn(c->marca, "\n")] = 0;
printf("Modelo do veículo: ");
fgets(c->modelo, 20, stdin);
c->modelo[strcspn(c->modelo, "\n")] = 0;
printf("Ano do veículo: ");
scanf("%4d", &c->ano);
fflush(stdin);
//Verifgicar se o valor digitado é um número
while(c->ano == 0)
{
printf("\nValor incompatível com o ano do carro. Por favor, digite novamente\n");
printf("Ano do veículo: ");
scanf("%4d", &c->ano);
fflush(stdin);
}
printf("Placa do veículo:\n");
printf("\tLetras: ");
fgets(c->pl.xxx, 4, stdin);
fflush(stdin);
// Checar se o formato é válido
int i;
for(i = 0; i < 3; i++)
{
while (c->pl.xxx[i] < 'A' || c->pl.xxx[i] > 'Z')
{
printf("\nDigitação incorreta. Utilize letras maiúsculas\n\n");
printf("\tLetras: ");
fgets(c->pl.xxx, 4, stdin);
fflush(stdin);
}
}
printf("\tNúmeros: ");
fgets(c->pl.yyyy, 5, stdin);
fflush(stdin);
// Checar se o formato é válido
for(i = 0; i < 4; i++)
{
while (c->pl.yyyy[0] < '0' || c->pl.yyyy[0] > '9')
{
printf("\nDigitação incorreta. Utilize números\n\n");
printf("\tNúmeros: ");
fgets(c->pl.yyyy, 5, stdin);
fflush(stdin);
}
}
}
int main()
{
setlocale(LC_ALL, "Portuguese");
CARRO carros[10]; //Criei um array de carros;
// Garante que nenhum lixo da memória será interpretado como carro no ordenamento dos veículos enquanto os 10 carros não forem preenchidos pelo usuário
carros[0].ano = 0;
carros[1].ano = 0;
carros[2].ano = 0;
carros[3].ano = 0;
carros[4].ano = 0;
carros[5].ano = 0;
carros[6].ano = 0;
carros[7].ano = 0;
carros[8].ano = 0;
carros[9].ano = 0;
int numCadast = 0;
int print;
int opt = 0; //Opção do Case Switch Geral
int opt2; // Controla o Loop do cadastro (default = 1)
int resposta2; // Confirma o loop do castro (default = 0)
int resposta1; // Aplicação de filtros na listagem
int resposta11; // Verifica se a saída do filtro é para a lista completa ou para o início do programa
int filtroAno;
char filtroMarca[20];
do{
opt2 = 1; // Loop do cadastro por default
resposta2 = 0; // resposta para confirmar o loop do castro
printf("\n");
printf("##############################################\n");
printf("##############################################\n");
printf("## ##\n");
printf("## BEM VIND AO GESTOR DE VEÍCULOS ##\n");
printf("## ##\n");
printf("## O QUE DESEJA FAZER? ##\n");
printf("## ##\n");
printf("## 1 - LISTAR VEÍCULOS CADASTRADOS ##\n");
printf("## (Selecione para ver mais opções) ##\n");
printf("## 2 - CADASTRAR VEÍCULO ##\n");
printf("## 3 - SAIR ##\n");
printf("## ##\n");
printf("## ##\n");
printf("##############################################\n");
printf("##############################################\n");
printf("\n\n");
printf("Opção: ");
scanf("%d", &opt);
fflush(stdin);
switch (opt) //Case Switch Geral
{
case 1: //Listar veículos
{
// Verificar se já há veículo cadastrado
if(numCadast == 0)
{
printf("\n\nVocê ainda não tem veículos cadastrados.\n");
printf("Gostaria de cadastrar um veículo? S/N \n");
char resposta = 'a';
while(resposta != 'S' && resposta != 'N')
{
scanf("%c", &resposta);
fflush(stdin);
resposta = toupper(resposta);
switch(resposta)
{
case 'S':
cadastrar(&carros[numCadast]);
numCadast = numCadast + 1;
// Confirmar que o veículo foi cadastrado e imprimir suas informações
printf("\n\nVeículo cadastrado com sucesso.");
printf("\n\nANO \tPLACA \t\tMARCA \t\tMODELO \n");
printf("%d \t%s-%s \t%s \t\t%s \n", carros[numCadast-1].ano, carros[numCadast-1].pl.xxx, carros[numCadast-1].pl.yyyy, carros[numCadast-1].marca, carros[numCadast-1].modelo);
printf("\nPressione \"enter\" para continuar.\n");
getchar();
opt = 0;
break;
case 'N':
opt = 0;
break;
default:
printf("Resposta inválida. Digite S ou N.\n");
}
}
}
else
{
resposta11 = 1; // default para retornar para cá
while(resposta11 == 1)
{
// Imprimir todos
printf("\n\nLista completa de veículos:");
printf("\n\nANO \tPLACA \t\tMARCA \t\tMODELO \n");
for(print = 0; print < numCadast; print++)
{
printf("%d \t%s-%s \t%s \t\t%s \n", carros[print].ano, carros[print].pl.xxx, carros[print].pl.yyyy, carros[print].marca, carros[print].modelo);
}
resposta1 = 0;
while(resposta1 == 0)
{
//Oferecer filtros
printf("\n\nSelecione uma das opções abaixo:\n\n");
printf("1 - Filtrar veículos por ANO DE FABRICAÇÃO ESPECÍFICO.\n");
printf("2 - Filtrar veículos A PARTIR de determinado ano de fabricação.\n");
printf("3 - Filtrar veículos por MARCA ESPECÍFICA.\n");
printf("4 - Voltar ao início.\n");
//Seleção da opção
scanf("%d", &resposta1);
fflush(stdin);
switch(resposta1)
{
case 1:
{
printf("\nDigite o ano de fabricação ESPECÍFICO: ");
scanf("%d", &filtroAno);
fflush(stdin);
//Impressão de carros de um ano específico
printf("\n\nANO \tPLACA \t\tMARCA \t\tMODELO \n");
for(print = 0; print < numCadast; print++)
{
if(carros[print].ano == filtroAno)
{
printf("%d \t%s-%s \t%s 't\t%s \n", carros[print].ano, carros[print].pl.xxx, carros[print].pl.yyyy, carros[print].marca, carros[print].modelo);
}
}
//Voltar para a lista completa ou para o início
do
{
printf("\nSelecione a opção desejada:\n");
printf("1 - Retornar à lista compeleta de carros;\n");
printf("2 - Retornar ao início.\n");
scanf("%d", &resposta11);
fflush(stdin);
if(resposta11 == 2)
opt = 0;
else if(resposta11 != 1) // Se for 1, volta no início do programa
printf("\n\nResposta inválida.\n");
} while(resposta11 != 1 && resposta11 != 2); // Volta nesta pergunta
}
break;
case 2:
{
printf("\nDigite o ano de fabricação A PARTIR do qual será impressa a lista de carros: ");
scanf("%d", &filtroAno);
fflush(stdin);
//Impressão de carros a partir de um determinado ano
printf("\n\nANO \tPLACA \t\tMARCA \t\tMODELO \n");
for(print = 0; print < numCadast; print++)
{
if(carros[print].ano >= filtroAno)
{
printf("%d \t%s-%s \t%s \t\t%s \n", carros[print].ano, carros[print].pl.xxx, carros[print].pl.yyyy, carros[print].marca, carros[print].modelo);
}
}
//Voltar para a lista completa ou para o início
do
{
printf("\nSelecione a opção desejada:\n");
printf("1 - Retornar à lista compeleta de carros;\n");
printf("2 - Retornar ao início.\n");
scanf("%d", &resposta11);
fflush(stdin);
if(resposta11 == 2)
opt = 0;
else if(resposta11 != 1) // Se for 1, volta no início do programa
printf("\n\nResposta inválida.\n");
} while(resposta11 != 1 && resposta11 != 2); // Volta nesta pergunta
}
break;
case 3:
{
printf("\nDigite a MARCA específica dos carros que quer ver: ");
fflush(stdin);
fgets(filtroMarca, 20, stdin);
filtroMarca[strcspn(filtroMarca, "\n")] = 0;
//Impressão de carros de uma determinada marca
printf("\n\nANO \tPLACA \t\tMARCA \t\tMODELO \n");
for(print = 0; print < numCadast; print++)
{
if(strcmp(carros[print].marca, filtroMarca) == 0)
{
printf("%d \t%s-%s \t%s \t\t%s \n", carros[print].ano, carros[print].pl.xxx, carros[print].pl.yyyy, carros[print].marca, carros[print].modelo);
}
}
//Voltar para a lista completa ou para o início
do
{
printf("\nSelecione a opção desejada:\n");
printf("1 - Retornar à lista compeleta de carros;\n");
printf("2 - Retornar ao início.\n");
scanf("%d", &resposta11);
fflush(stdin);
if(resposta11 == 2)
opt = 0;
else if(resposta11 != 1) // Se for 1, volta no início do programa
printf("\n\nResposta inválida.\n");
} while(resposta11 != 1 && resposta11 != 2); // Volta nesta pergunta
}
break;
case 4:
{
resposta11 = 2;
opt = 0; // Volta ao início
}
break;
default:
{
printf("\n\nResposta inválida.\n");
resposta1 = 0;
}
}
}
}
}
}
break;
case 2: //Cadastrar veículos
{
do
{
resposta2 = 0;
if(numCadast < 10) // Checa se ainda há espaço para cadastrar veículos
{
cadastrar(&carros[numCadast]);
numCadast = numCadast + 1;
// Confirmação de cadastro
printf("\n\nVeículo cadastrado com sucesso.");
printf("\n\nANO \tPLACA \t\tMARCA \t\tMODELO \n");
printf("%d \t%s-%s \t%s \t\t%s \n", carros[numCadast-1].ano, carros[numCadast-1].pl.xxx, carros[numCadast-1].pl.yyyy, carros[numCadast-1].marca, carros[numCadast-1].modelo);
// Reordenar por ano
int c1, c2, posNovo;
CARRO carTemp, maisNovo;
for(c1 = 0; c1 <= numCadast; c1++)
{
maisNovo = carros[c1];
posNovo = c1;
for(c2 = c1+1; c2 <= numCadast; c2++)
{
if(carros[c2].ano > carros[c1].ano)
{
maisNovo = carros[c2];
posNovo = c2;
}
}
if(posNovo != c1)
{
carTemp = carros[c1];
carros[c1] = carros[posNovo];
carros[posNovo] = carTemp;
}
}
// Questionar se o usuário deseja cadastrar novo veículo ou retornar ao início.
while(resposta2 != 1)
{
printf("\nO que deseja fazer?\n");
printf("\n1 - Cadastrar novo veículo; \n2 - Retornar ao início.\n");
scanf("%d", &resposta2);
fflush(stdin);
if(resposta2 == 2)
{
resposta2 = 1;
opt2 = 2;
opt = 0;
}
else if(resposta2 != 1)
{
printf("\n\nResposta inválida.\n");
}
}
}
else //Já possui 10 veículos cadastrados
{
printf("\n\nVocê já cadastrou o máximo de 10 veículos em nosso sistema.\n\n");
printf("Pressione \"enter\" para retornar ao início.");
getchar();
opt = 0;
}
}while(opt2 == 1);
}
break;
case 3 : return 0;
default:
printf("Opção inválida. Tente novamente.\n\n");
}
} while(opt < 1 || opt > 3);
}
|
C
|
#pragma once
#include<stdio.h>
void hexprint(const char* s,size_t len)
{
size_t i;
for(i=0;i<len;++i)
fprintf(stderr,"%.02x ",0xff&s[i]);
fprintf(stderr,"\n");
}
|
C
|
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include "exe_funct.h"
#include "macro.h"
#include "parse.h"
static char cmd[MAX_COMMAND_LENGTH + 1];
// static char parse[MAX_COMMAND_LENGTH + 1];
// static bool quit_flag;
// static bool thread_flag = false;
static bool reading_flag;
// void execute(struct parse *parsed_cmd);
void stop_threads(int signo)
{
// printf("catch you\n");
if (signo == SIGINT)
{
// thread_flag = true;
if (reading_flag == 1)
{
printf("\nmumsh $ ");
fflush(stdout);
}
else
{
printf("\n");
fflush(stdout);
}
// char out = '\n';
// write(STDIN_FILENO,&out,1);
// exit(0);
}
// printf("flage change to %d\n", thread_flag);
}
int main()
{
// printf("test\n");
/* PID manager initialization*/
struct PID_manager PID_m;
PID_m.childP_number = 0;
PID_m.finish_index = -1;
/* Signal Ctrl+C*/
signal(SIGINT, stop_threads);
/* Quit_flage for exit and ctrl+D*/
// bool quit_flag = false;
/* Store the standard input and output*/
int inFds = dup(STDIN_FILENO);
int outFds = dup(STDOUT_FILENO);
/* Reading comman loop*/
while (1)
{
reading_flag = true;
/* Prompt*/
fflush(stdin);
printf("mumsh $ ");
fflush(stdout);
/* Read Loop*/
bool ctn = false;
char wtchr;
int index = 0;
if (Read_cmd(&wtchr, &ctn, cmd, &index) == 1)
{
prepare_quit(inFds, outFds, &PID_m);
return 0;
}
/* Finish Reading*/
/* Judge the status of quit reading*/
if (ctn == 1)
{
printf("syntax error near unexpected token `%c'\n", wtchr);
fflush(stdout);
ctn = 0;
continue;
}
/* Reading flag about the appear time of Ctrl + D*/
reading_flag = false;
/* if index == 0, read nothin*/
if (index == 0) continue;
/* temporary storage of cmd*/
char *midT = (char*) malloc(strlen(cmd) + 1);
strcpy(midT, cmd);
bool back_flag = find_bk(cmd, index);
/* if the command has a &*/
if (back_flag == 1)
{
/* store the corresponding cmd with & */
PID_m.cmd_origin[PID_m.childP_number] = (char*) malloc(strlen(midT) + 1);
strcpy(PID_m.cmd_origin[PID_m.childP_number], midT);
free(midT);
// PID_m.cmd_origin[PID_m.childP_number][index] = 0;
/* Number ++*/
PID_m.childP_number++;
/*print background running hint*/
printf("[%d] %s\n", PID_m.childP_number, PID_m.cmd_origin[PID_m.childP_number - 1]);
fflush(stdout);
/* Fork a thread */
pid_t pid = fork();
// PID_m.PIDs[PID_m.childP_number - 1] = getpid();
if (pid == -1)
{
/* fail in forking a thread*/
// int ret = -1;
}
/* The child process do*/
else if (pid == 0)
{
parse_exe_all(outFds, inFds, cmd, &PID_m);
exit(0);
}
/* The Father process do*/
else
{
/* thread the pid of child process*/
PID_m.PIDs[PID_m.childP_number - 1] = pid;
continue;
}
}
/* If the comman is a normal one without &*/
else
{
free(midT);
if (parse_exe_all(outFds, inFds, cmd, &PID_m) == 1)
{
return 0;
}
// fprintf(stderr, "tes\n\n\n\n");
}
}
wait_all();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *left;
struct Node *right;
};
struct Node * newNode(int data){
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
void printInorder(struct Node *);
void printPreorder(struct Node *);
void printPostorder(struct Node *);
int size(struct Node *);
int height(struct Node *);
int countLeaveNodes(struct Node *);
int countFullNodes(struct Node *);
int width(struct Node *,int);
int getWidth(struct Node *,int );
int main(){
struct Node *root = newNode(25);
root->left = newNode(15);
root->right = newNode(50);
root->left->left = newNode(10);
root->left->right = newNode(22);
root->left->left->left = newNode(4);
root->left->left->right = newNode(12);
root->left->right->left = newNode(18);
root->left->right->right = newNode(24);
root->right->left = newNode(35);
root->right->right = newNode(70);
root->right->left->left = newNode(31);
root->right->left->right = newNode(44);
root->right->right->left = newNode(66);
root->right->right->right= newNode(90);
int choice,s,h,l,f,w;
while(1){
printf("\n-----------------------------------------------------------------------------------------------------------------------\n");
printf("\n 1.Inorder Traversal \n");
printf("\n 2.Preorder Traversal \n");
printf("\n 3.Postorder Traversal \n");
printf("\n 4.Size Of Tree \n");
printf("\n 5.Height Of Tree \n");
printf("\n 6.Total No Of Leave Nodes \n");
printf("\n 7.Total No Of Non Leave Nodes \n");
printf("\n 8.Total No Of Full Nodes \n");
printf("\n 9.Total Width Of Tree \n");
printf("\n 10.Exit \n");
printf("\n-----------------------------------------------------------------------------------------------------------------------\n");
printf("\nEnter your choice: ");
scanf("%d", &choice);
printf("\n------------------------------------------------------------------------------------------------------------------------\n");
switch(choice)
{
case 1:
printInorder(root);
break;
case 2:
printPreorder(root);
break;
case 3:
printPostorder(root);
break;
case 4:
s = size(root);
printf("Size Of Tree:-\t%d\n",s);
break;
case 5:
h = height(root);
printf("Height Of Tree:-\t%d\n",h);
break;
case 6:
l = countLeaveNodes(root);
printf("Total No Of Leave Nodes:-\t%d\n",l);
break;
case 7:
printf("Total No Of Non Leave Nodes:-\t%d\n",s-l);
break;
case 8:
f = countFullNodes(root);
printf("Total No Of Full Nodes:-\t%d\n",f);
break;
case 9:
w = width(root,height(root));
printf("Total Width Of Tree:-\t%d\n",w);
break;
case 10:
exit(0);
break;
default:
printf("\n Wrong Choice:\n");
break;
}
}
}
void printInorder(struct Node *t){
if(t)
{
printInorder(t->left);
printf("%d\t",t->data);
printInorder(t->right);
}
}
void printPreorder(struct Node *t){
if (t)
{
printf("%d\t",t->data);
printPreorder(t->left);
printPreorder(t->right);
}
}
void printPostorder(struct Node *t){
if (t)
{
printPostorder(t->left);
printPostorder(t->right);
printf("%d\t",t->data);
}
}
int size(struct Node *t){
if(t==NULL){
return 0;
}else{
return 1+(size(t->left)+size(t->right));
}
}
int height(struct Node *t){
if (!t)
{
return 0;
}else if(!t->left && !t->right){
return 0;
}else{
int a = height(t->left);
int b = height(t->right);
return 1+((a>b)?a:b);
}
}
int countLeaveNodes(struct Node *t){
if (!t)
{
return 0;
}else if(!t->left && !t->right){
return 1;
}else{
return countLeaveNodes(t->left)+countLeaveNodes(t->right);
}
}
int countFullNodes(struct Node *t){
if (!t)
{
return 0;
}else if(!t->left && !t->right){
return 0;
}else{
return countFullNodes(t->left)+countFullNodes(t->right)+((t->left!=NULL && t->right!=NULL)?1:0);
}
}
int width(struct Node *t,int h){
int max_width = 0;
int width;
for (int i = 1; i <=h+1; ++i)
{
width = getWidth(t,i);
if (width>max_width)
max_width = width;
}
return max_width;
}
int getWidth(struct Node *t,int l){
if (t==NULL)
{
return 0;
}else if(l==1){
return 1;
}else if(l>1){
return (getWidth(t->left,l-1) + getWidth(t->right,l-1));
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* f_fractals_b.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ykopiika <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/01 20:28:07 by ykopiika #+# #+# */
/* Updated: 2019/06/01 20:28:10 by ykopiika ### ########.fr */
/* */
/* ************************************************************************** */
#include "fractol.h"
t_vrbl f_fish_mandelbrot(t_vrbl v)
{
v.c_re = 1.5 * (v.x - WIN_W / 2) / (0.5 * v.zoom * WIN_W) + v.mv_x;
v.c_im = (v.y - WIN_H / 2) / (0.5 * v.zoom * WIN_H) + v.mv_y;
v.n_re = 0;
v.n_im = 0;
v.i = 0;
while (v.i < v.max_i)
{
v.o_re = v.n_re;
v.o_im = v.n_im;
v.n_re = fabs(v.o_re * v.o_re - v.o_im * v.o_im) + v.c_re;
v.n_im = 2 * v.o_re * v.o_im + v.c_im;
if ((v.n_re * v.n_re + v.n_im * v.n_im) > 4)
break ;
v.i++;
}
return (v);
}
t_vrbl f_cubic_mandelbrot(t_vrbl v)
{
v.c_re = 1.5 * (v.x - WIN_W / 2) / (0.5 * v.zoom * WIN_W) + v.mv_x;
v.c_im = (v.y - WIN_H / 2) / (0.5 * v.zoom * WIN_H) + v.mv_y;
v.n_re = 0;
v.n_im = 0;
v.i = 0;
while (v.i < v.max_i)
{
v.o_re = v.n_re;
v.o_im = v.n_im;
v.n_im = ((3 * v.o_re * v.o_re) - v.o_im * v.o_im) * v.o_im + v.c_im;
v.n_re = (v.o_re * v.o_re - (v.o_im * v.o_im * 3)) * v.o_re + v.c_re;
if ((v.n_re * v.n_re + v.n_im * v.n_im) > 4)
break ;
v.i++;
}
return (v);
}
t_vrbl f_arm_mandelbrot(t_vrbl v)
{
v.c_re = 1.5 * (v.x - WIN_W / 2) / (0.5 * v.zoom * WIN_W) + v.mv_x;
v.c_im = (v.y - WIN_H / 2) / (0.5 * v.zoom * WIN_H) + v.mv_y;
v.n_re = 0;
v.n_im = 0;
v.i = 0;
while (v.i < v.max_i)
{
v.o_re = v.n_re;
v.o_im = v.n_im;
v.n_im = ((3 * v.o_re * v.o_re) - v.o_im * v.o_im) * v.o_im + v.c_im;
v.n_re = -(v.o_re * v.o_re - (v.o_im * v.o_im * 3)) * v.o_re + v.c_re;
if ((v.n_re * v.n_re + v.n_im * v.n_im) > 4)
break ;
v.i++;
}
return (v);
}
t_vrbl f_trngl_mandelbrot(t_vrbl v)
{
double resqr;
double imsqr;
v.c_re = 1.5 * (v.x - WIN_W / 2) / (0.5 * v.zoom * WIN_W) + v.mv_x;
v.c_im = (v.y - WIN_H / 2) / (0.5 * v.zoom * WIN_H) + v.mv_y;
v.n_re = 0;
v.n_im = 0;
v.i = 0;
while (v.i < v.max_i)
{
v.o_re = v.n_re;
v.o_im = v.n_im;
imsqr = v.n_im * v.n_im;
resqr = v.n_re * v.n_re;
v.n_im = 4 * v.o_im * v.o_re * (resqr - imsqr) + v.c_re;
v.n_re = (imsqr * imsqr + resqr * resqr) - 6 * resqr * imsqr + v.c_im;
if ((v.n_re * v.n_re + v.n_im * v.n_im) > 4)
break ;
v.i++;
}
return (v);
}
|
C
|
/* Dana Alibrandi
* CS 50
* Project 5
* May 7, 2018
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define UPPER_LIMIT 20
#define LOWER_LIMIT 14
#define DATA_UPPER_LIMIT 99
#define DATA_LOWER_LIMIT 10
#define FALSE 0
#define TRUE 1
/* Function Prototypes */
void initializeProject( int [], int, int );
void printArray( int [], int, int, int );
void sequentialSearch( int [], int, int);
void swap( int *, int * );
int partition( int [], int, int );
void quickSort( int [], int, int );
void binSearch( int [], int, int, int, int * );
int main( void )
{
srand(time(NULL));
int sampleSize = rand() % (UPPER_LIMIT + 1 - LOWER_LIMIT) + LOWER_LIMIT;
int searchElement = rand() % (DATA_UPPER_LIMIT + 1 - DATA_LOWER_LIMIT) + DATA_LOWER_LIMIT;
int array[sampleSize], pivot = 99, counter = 0;
initializeProject( array, sampleSize, pivot );
sequentialSearch( array, sampleSize, searchElement );
printf("\nSorting...\n");
quickSort( array, 0, sampleSize );
printf("Sorted:\n");
printArray( array, 0, sampleSize, pivot );
binSearch(array, 0, sampleSize, searchElement, &counter);
printf("Number of searches: %d\n\n", counter);
printf("\nDana Alibrandi - End of Project 5\n\n");
return 0;
}
/*********************Function Definitions**********************/
void initializeProject( int array [], int sampleSize, int pivot)
/*
* Generates random elements for the array based on sampleSize.
* Prints general project info so printArray can be reused elsewhere.
*/
{
for ( int i = 0; i < sampleSize; i++ ) {
array[i] = rand() % (DATA_UPPER_LIMIT + 1 - DATA_LOWER_LIMIT) + DATA_LOWER_LIMIT;
}
printf("\nDana Alibrandi - Project 5\n");
printf("\nSample size = %d\n", sampleSize);
printf("\nArray elements:\n");
printArray(array, 0, sampleSize, pivot);
}
void printArray( int array [], int first, int last, int pivot )
{
/*
* Uses pivot variable for formatting when printing during
* the quickSort.
*
*/
for ( int i = first; i < last; i++ ) {
if ( i == pivot ) {
printf("<%d> ", array[i]);
}
else {
printf("%d ", array[i]);
}
}
printf("\n\n");
}
void sequentialSearch ( int array [], int sampleSize, int searchElement )
{
int found = FALSE;
printf("Search element: %d\n", searchElement);
for ( int i = 0; i < sampleSize; i++ ) {
if ( array[i] == searchElement ) {
found = TRUE;
printf("\nItem found: %d\n", searchElement);
printf("Number of searches: %d\n", i + 1);
break;
}
}
if ( found == FALSE ) {
printf("\nItem not found: %d\n", searchElement);
printf("Number of searches: %d\n", sampleSize);
}
}
void swap( int *a, int *b )
{
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int array [], int first, int last )
{
int pivot = array[last - 1];
int leftIndex = first;
for ( int i = first; i <= last - 1; i++ ) {
if ( array[i] < pivot ) {
swap(&array[i], &array[leftIndex]);
leftIndex++;
}
}
swap(&array[leftIndex], &array[last - 1]);
return leftIndex;
}
void quickSort( int array [], int first, int last )
{
int pivot;
if ( first < last ) {
pivot = partition(array, first, last);
if ( array[last - 1] != array[first] ) printArray( array, first, last, pivot );
quickSort( array, first, pivot );
quickSort( array, pivot + 1, last );
}
}
void binSearch( int array [], int first, int last, int searchElement, int *counter )
{
/*
* Binary search using recursion to locate item. *counter is used
* to keep track of the number of searches.
*
*/
int midIndex;
if ( first <= last ) {
midIndex = (first + last) / 2;
*counter += 1;
if ( searchElement < array[midIndex] ) {
binSearch(array, first, midIndex - 1, searchElement, counter);
}
else if ( searchElement > array[midIndex] ) {
binSearch(array, midIndex + 1, last, searchElement, counter);
}
else
printf("Item Found: %d, Element Position: %d\n", searchElement, midIndex);
}
else {
printf("Item not found: %d \n", searchElement);
}
}
|
C
|
/* Author: James Ridey 44805632
* james.ridey@students.mq.edu.au
* Creation Date: 10-08-2016
* Last Modified: Wed 10 Aug 2016 09:13:19 AM CDT
*/
#include "file.h"
Data* read_file(FILE* file, Array* array)
{
static Data data = {0};
if(!fread(&data.news, sizeof(short), 1, file)) return NULL;
fread(&data.edge, sizeof(short), 1, file);
fread(&data.error, sizeof(char), 1, file);
fread(&data.cent, sizeof(int), 1, file);
fread(&data.holiday, sizeof(char), 1, file);
fread(&data.shake, sizeof(char), 1, file);
fread(&data.hair, sizeof(float), 1, file);
fread(&data.snakes, sizeof(long), 1, file);
fread(&data.toad, sizeof(char), 1, file);
fread(&data.window, sizeof(char), 1, file);
fread(&data.space, sizeof(short), 1, file);
fread(&data.cemetery, 10*sizeof(char), 1, file);
fread(&data.fang, sizeof(double), 1, file);
fread(&data.chance, sizeof(long), 1, file);
fread(&data.development, sizeof(double), 1, file);
fread(&data.spy, sizeof(int), 1, file);
return &data;
}
void write_file(FILE* file, Array* array)
{
int i;
for (i = 0; i < array->counter; i++)
{
Data data = array->data[i];
fwrite(&data.news, sizeof(short), 1, file);
fwrite(&data.edge, sizeof(short), 1, file);
fwrite(&data.error, sizeof(char), 1, file);
fwrite(&data.cent, sizeof(int), 1, file);
fwrite(&data.holiday, sizeof(char), 1, file);
fwrite(&data.shake, sizeof(char), 1, file);
fwrite(&data.hair, sizeof(float), 1, file);
fwrite(&data.snakes, sizeof(long), 1, file);
fwrite(&data.toad, sizeof(char), 1, file);
fwrite(&data.window, sizeof(char), 1, file);
fwrite(&data.space, sizeof(short), 1, file);
fwrite(&data.cemetery, 10*sizeof(char), 1, file);
fwrite(&data.fang, sizeof(double), 1, file);
fwrite(&data.chance, sizeof(long), 1, file);
fwrite(&data.development, sizeof(double), 1, file);
fwrite(&data.spy, sizeof(int), 1, file);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_check_bol.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tcabon <tcabon@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/09/14 18:39:56 by tcabon #+# #+# */
/* Updated: 2016/09/14 20:45:50 by tcabon ### ########.fr */
/* */
/* ************************************************************************** */
#include "fractol.h"
static int bolbur_check(t_boller *bol)
{
if (bol->bur == 0)
{
bol->bur = 1;
return (0);
}
else
return (1);
}
static int boljul_check(t_boller *bol)
{
if (bol->jul == 0)
{
bol->jul = 1;
return (0);
}
else
return (1);
}
static int bolmand_check(t_boller *bol)
{
if (bol->mand == 0)
{
bol->mand = 1;
return (0);
}
else
return (1);
}
void ft_check_bol(char *str, t_boller *bol)
{
str = ft_strtolower(str);
if (ft_strcmp(str, "mandelbrot") == 0)
bol->ret = bolmand_check(bol);
else if (ft_strcmp(str, "julia") == 0)
bol->ret = boljul_check(bol);
else if (ft_strcmp(str, "burning") == 0)
bol->ret = bolbur_check(bol);
else
bol->ret = 1;
}
|
C
|
#include <stdio.h>
#include <limits.h>
void
test0(float a0 , double a1, float a2, double a3, double a4, double a5, double a6, double a7,
double a8, double a9, double a10, double a11, double a12, double a13, double a14, double a15, double a16) {
printf("%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f\n",
a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16);
}
int
main() {
test0(1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10, 11.11, 12.12, 13.13, 14.14, 15.15, 16.16, 17.17);
return 0;
}
|
C
|
#include <stdint.h>
typedef enum _direction {
GPIO_OUT = 0, GPIO_IN = 1
} direction_t;
typedef enum {
GPIO_1 = 1,
GPIO_2 = 2,
GPIO_3 = 3,
GPIO_4 = 4,
GPIO_5 = 5,
GPIO_6 = 6,
GPIO_7 = 7,
GPIO_8 = 8,
} gpio_pin;
uint8_t gpio_init();
void gpio_exit();
void gpio_set(gpio_pin gpionum, uint8_t set);
uint8_t gpio_get(gpio_pin gpionum);
direction_t gpio_get_direction(gpio_pin gpionum);
void gpio_set_direction(gpio_pin gpionum, direction_t dir);
|
C
|
/**
* Ideal Indirection Lab
* CS 241 - Spring 2019
*/
#pragma once
#include "kernel.h"
#include "page_table.h"
#include "segments.h"
#include "tlb.h"
/**
* The file is responsible to excuting the logic of a Memory Management Unit
* (MMU).
*/
// 32768 is the largest process id on most linux systems
#define MAX_PROCESS_ID 32768
/*
* Struct used to represent an MMU
*/
typedef struct {
/* An array of pointers to top level page directories (one per process)
* details in page_table.h*/
page_directory *page_directories[MAX_PROCESS_ID];
/* An array of pointers to segmentations (one per process) details in
* segments.h*/
vm_segmentations *segmentations[MAX_PROCESS_ID];
/* Pointer to a translation lookaside buffer; details in tlb.h */
tlb *tlb;
/* Statistics to check if MMU is correctly translating addresses */
size_t num_page_faults;
size_t num_segmentation_faults;
size_t num_tlb_misses;
/*
* Current pid that is reading or writing to memory.
* Changes whenever there is a context switch
*/
size_t curr_pid;
} mmu;
/*
* Creates a default MMU with all fields intialized on the heap.
* Call on mmu_delete() to free all memory used.
*/
mmu *mmu_create();
/*
* Get the page_table_entry that corresponds to the 'virtual_address' for 'pid'.
* Note that this function does interact with the tlb, raises a
* pagefault/segfault.
* This function assumes that all paging structures (page directory and page
* table)
* are paged in memory and does no error checking.
* NOTE: You do not need to implement this function. However, you may choose
* to implement this and use this as a helper function, or use this in
* your own test cases if you choose to do so
*/
page_table_entry *mmu_get_pte(mmu *this, uintptr_t virtual_address, size_t pid);
/**
The following applies to both mmu_read_from_virtual address and
mmu_write_to_virtual_address:
Reads from or writes 'num_bytes' to a 'virtual_address' for the process with
'pid' if it has already been assigned.
Whenever possible you should see if the page_table entry corresponding to a
`virtual_address`
is stored in the tlb before going through multiple page tables.
This is because page tables are orders of magnitude slower than the cache of a
tlb.
Make sure to keep your cache valid by checking for context switches.
If a pointer trys to access a page of address space that's currently not
mapped onto physical memory,
then you should raise a page_fault(mmu_raise_page_fault) (hint there is a
useful bit in the page table entry)
and load that page into memory (ask_kernel_for_frame() and
read_page_from_disk()).
If a program tries to access an invalid or illegal memory address,
then you should raise a segmentation fault(mmu_raise_segmentation_fault).
A memory address is invalid if the address is not in any segmentation or
if the user does not have the correct permissions for it (hint there are
useful bit in the page table entry).
Set the appropriate flags (see page_table.h).
Note: Your tlb needs to be updated whenever this method is called.
Note: All process pagetables when been set up at this point.
Note: All read and writes will be contained within a single page.
*/
void mmu_read_from_virtual_address(mmu *this, addr32 virtual_address,
size_t pid, void *buffer, size_t num_bytes);
void mmu_write_to_virtual_address(mmu *this, addr32 virtual_address, size_t pid,
const void *buffer, size_t num_bytes);
/**
You need to call this function every time the mmu cache misses with the tlb
and needs to check the page tables.
*/
void mmu_tlb_miss(mmu *this);
/**
Raises a page_fault.
*/
void mmu_raise_segmentation_fault(mmu *this);
/**
Raises a segfault.
*/
void mmu_raise_page_fault(mmu *this);
/**
Adds a process with 'pid' to the mmu by creating it's page_tables.
*/
void mmu_add_process(mmu *this, size_t pid);
/**
Free all the physical memory used by a certain process given by 'pid', so that
other process can use that space.
*/
void mmu_remove_process(mmu *this, size_t pid);
/**
Fress all memory used by the mmu
*/
void mmu_delete(mmu *this);
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,t,a=150,b=160,rem,result=0;
printf("the first interval %d",a);
printf("the second interval %d",b);
{
for(i=150;i<=160;i++)
{
t=n;
while(n!=0)
{
rem=n%10;
result=result+rem*rem*rem;
n=n/10;
}
if(t==result)
{
printf("armstrong number between two intervals are %d ",result);
}
}
}
}
|
C
|
#include "libft.h"
char *ft_strmapi(char const *s, char (*f)(unsigned int, char))
{
char *new;
unsigned int i;
size_t len;
i = 0;
len = ft_strlen(s) + 1;
if (s == NULL || !f)
return (NULL);
new = (char *)malloc(sizeof(char) * len);
if (new == NULL)
return (NULL);
while (s[i] != '\0')
{
new[i] = (*f)(i, s[i]);
i++;
}
new[i] = '\0';
return (new);
}
|
C
|
/*
* ordered_list.h
*
* Created on: Apr 3, 2019
* Author: akos
*/
#ifndef DATA_STRUCTURES_GENERIC_ORDERED_LIST_H_
#define DATA_STRUCTURES_GENERIC_ORDERED_LIST_H_
#include "list.h"
#include <stdlib.h>
typedef int (*comp_function)(void*, void*);
typedef struct __ordered_list_item {
void* data; //a generic pointer to the data type stored in the list
struct __ordered_list_item* next; //a pointer to the next element in the list (NULL if this item is the last element)
struct __ordered_list_item* prev; //a pointer to the previous element in the list (NULL if this item is the first element)
}ordered_list_item;
typedef struct _ordered_list {
short size; //number of elements in the list
ordered_list_item* head; //pointer to the head of the list
ordered_list_item* tail; //pointer to the tail of the list
comp_function compare; //a function to compare the elements in the list
}ordered_list;
/**
* Initialize an empty ordered list
* @param compare the function used to compare (and order) the elements in the list
* @return a pointer to a an empty ordered list configured to order by the provided function
*/
ordered_list* ordered_list_init(comp_function compare);
/**
* Add an item to the ordered list
* @param l the ordered list to be added to
* @param item the item to be added
*/
void ordered_list_add_item(ordered_list* l, void* item);
/**
* Remove the item pointed by item from the ordered list
* @param l the ordered list to be removed from
* @param item the item to be removed
* @return the removed item data or NULL if no item was removed
*/
void* ordered_list_remove(ordered_list* l, ordered_list_item* item);
/**
* Remove a specific item from the ordered list
* @param l the ordered list to be removed from
* @param equal a function to compare items in the list (exact match boolean)
* @param to_remove the item to be removed
* @return the removed item data or NULL if no item was removed
*/
void* ordered_list_remove_item(ordered_list* l, comparator_function equal, void* to_remove);
/**
* Find a specific item from the ordered list
* @param l the ordered list
* @param equal a function to compare items in the list (exact match boolean)
* @param to_find the item to be found
* @return the found item data or NULL if no item was found
*/
void* ordered_list_find_item(ordered_list* l, comparator_function equal, void* to_find);
/**
* Return the item in ordered list that has the given index
* @param l the ordered list
* @param index the index of the desired item
* @return the retrieved item data or NULL if no item was found
*/
void* ordered_list_get_item_by_index(ordered_list* l, int index);
/**
* Remove from the head of the ordered list
* @param l the ordered list
* @return the removed item data or NULL if no item was removed
*/
void* ordered_list_remove_head(ordered_list* l);
/**
* Remove from the tail of the ordered list
* @param l the ordered list
* @return the removed item data or NULL if no item was removed
*/
void* ordered_list_remove_tail(ordered_list* l);
/**
* Update the item pointed by newdata in the ordered list.
* Newdata will be added to list, while the old data will be removed.
* If newdata does not exist in the ordered list the item is added to the ordered list
* @param l the ordered list
* @param equal a function to compare items in the ordered list (exact match boolean)
* @param newdata the data to be updated
* @return a pointer to the old data or NULL if newdata was not in the list.
*/
void* ordered_list_update_item(ordered_list* l, comparator_function equal, void* newdata);
#endif /* DATA_STRUCTURES_GENERIC_ORDERED_LIST_H_ */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "listas.h"
#include "funcoes_para_contas.h"
Contas* Contas_busca (Contas* inicio, int v)
{//encontra agencia com mesmo cdigo
Contas* p = inicio;
while(p!=NULL){
if (p->numero_conta == v)
return p;
p=p->prox;
}
return NULL; /* no achou o elemento */
}
void excluir_contas_pelo_codigo(Contas** inicio, int v)
{
Contas* p = Contas_busca(*inicio,v);
if (p == NULL)
return ;/* no achou o elemento: */
/* retira elemento do encadeamento */
if (*inicio == p) /* testa se o primeiro elemento */
*inicio = p->prox;
else
p->ant->prox = p->prox;
if (p->prox != NULL) /* testa se o ltimo elemento */
p->prox->ant = p->ant;
free(p);
}
void excluir_contas_de_um_cliente(Contas** inicio, int cpf_ver)
{
Contas* p = *inicio;
if(p == NULL){
printf("no tem contas para retirar\n");
return;
}
while(p != NULL){
if(p->cpf_cliente_conta == cpf_ver){
/* retira elemento do encadeamento */
if (*inicio == p){/* testa se o primeiro elemento */
*inicio = p->prox;
free(p);
}else{
p->ant->prox = p->prox;
free(p);
}
if (p->prox != NULL){ /* testa se o ltimo elemento */
p->prox->ant = p->ant;
free(p);
}
}
p = p->prox;
}
}
void excluir_contas_de_uma_agencia(Contas** inicio, int codigo_ag)
{
Contas* p = *inicio;
if(p == NULL){
printf("no tem contas para retirar\n");
return;
}
while(p != NULL){
if(p->codigo_agencia_conta == codigo_ag){
/* retira elemento do encadeamento */
if (*inicio == p){/* testa se o primeiro elemento */
*inicio = p->prox;
free(p);
}else{
p->ant->prox = p->prox;
free(p);
}
if (p->prox != NULL){ /* testa se o ltimo elemento */
p->prox->ant = p->ant;
free(p);
}
}
p = p->prox;
}
}
void excluir_contas_todas(Contas** inicio)
{
Contas* p = *inicio;
if(p == NULL){
printf("no tem contas para retirar\n");
return;
}
while(p != NULL){
/* retira elemento do encadeamento */
if (*inicio == p){/* testa se o primeiro elemento */
*inicio = p->prox;
free(p);
}else{
p->ant->prox = p->prox;
free(p);
}
if (p->prox != NULL){ /* testa se o ltimo elemento */
p->prox->ant = p->ant;
free(p);
}
p = p->prox;
}
}
void listar_contas_de_um_cliente(Contas** inicio)
{
Contas* p = *inicio;
int cpf_ver;
printf("\nDIGITE O CPF DO CLIENTE QUE DESEJA VER AS CONTAS:\n");
scanf("%d", &cpf_ver);
printf("\n\nA LISTA DE CONTAS: \n");
if(p == NULL)
printf("lista vazia\n");
while(p != NULL){
if(p->cpf_cliente_conta == cpf_ver){
printf("----------------------------------------------------------------------");
printf("\nCDIGO DA CONTA: %d\nCDIGO DA AGNCIA DA CONTA: %d\nCPF DO DONO DA CONTA: %d\n", p->numero_conta,p->codigo_agencia_conta, p->cpf_cliente_conta);
printf("\nDATA DE CRIAO DA CONTA: %d / %d / %d\n", p->dia, p->mes, p->ano);
printf("\nSALDO DA CONTA: %f LIMITE DA CONTA: %f\n", p->saldo, p->limite);
printf("----------------------------------------------------------------------");
printf("\n");
}
p = p->prox;
}
printf("\n");
}
void listar_contas_de_uma_agencia(Contas** inicio)
{
Contas* p = *inicio;
int codigo_agencia_ver;
printf("\nDIGITE O CDIGO DA AGNCIA QUE DESEJA VER AS CONTAS:\n");
scanf("%d", &codigo_agencia_ver);
printf("\n\nA LISTA DE CONTAS: \n");
if(p == NULL)
printf("lista vazia\n");
while(p != NULL){
if(p->codigo_agencia_conta == codigo_agencia_ver){
printf("----------------------------------------------------------------------");
printf("\nCDIGO DA CONTA: %d\nCDIGO DA AGNCIA DA CONTA: %d\nCPF DO DONO DA CONTA: %d\n", p->numero_conta,p->codigo_agencia_conta, p->cpf_cliente_conta);
printf("\nDATA DE CRIAO DA CONTA: %d / %d / %d\n", p->dia, p->mes, p->ano);
printf("\nSALDO DA CONTA: %f LIMITE DA CONTA: %f\n", p->saldo, p->limite);
printf("----------------------------------------------------------------------");
printf("\n");
}
p = p->prox;
}
printf("\n");
}
void listar_contas_todas(Contas** inicio)
{
Contas* p = *inicio;
printf("\n\nA LISTA DE CONTAS: \n");
if(p == NULL)
printf("lista vazia\n");
while(p != NULL){
printf("----------------------------------------------------------------------");
printf("\nCDIGO DA CONTA: %d\nCDIGO DA AGNCIA DA CONTA: %d\nCPF DO DONO DA CONTA: %d\n", p->numero_conta,p->codigo_agencia_conta, p->cpf_cliente_conta);
printf("\nDATA DE CRIAO DA CONTA: %d / %d / %d\n", p->dia, p->mes, p->ano);
printf("\nSALDO DA CONTA: %f LIMITE DA CONTA: %f\n", p->saldo, p->limite);
printf("----------------------------------------------------------------------");
printf("\n");
p = p->prox;
}
printf("\n");
}
///***************insere na conta******************///
void Conta_insere (Contas** inicio,int dia_cad,int mes_cad,int ano_cad,float saldo_cad,float limite_cad,int codigo_agencia_ver,int cpf_ver,int codigo_conta)
{
Contas* novo = (Contas*) malloc(sizeof(Contas));
novo->codigo_agencia_conta = codigo_agencia_ver;
novo->cpf_cliente_conta = cpf_ver;
novo->numero_conta = codigo_conta;
novo->dia = dia_cad;
novo->mes = mes_cad;
novo->ano = ano_cad;
novo->saldo = saldo_cad;
novo->limite = limite_cad;
novo->total = (novo->limite + novo->saldo);
novo->prox = *inicio;
novo->ant = NULL;
printf("\n%d\n", novo->codigo_agencia_conta);
printf("%d\n", novo->cpf_cliente_conta);
printf("%d\n", novo->numero_conta);
printf("%f\n", novo->saldo);
printf("%f\n", novo->limite);
if (*inicio != NULL)
(*inicio)->ant = novo;
*inicio = novo;
}
int verifica_se_codigo_conta_ja_existe(Contas* inicio, int v)
{
Contas* p = inicio;
while(p!=NULL){
if (p->numero_conta == v)
return 1; /* retorna "1" se achou o elemento */
p=p->prox;
}
return 0;/* retorna "0" se no achou o elemento */
}
int Clientes_busca_para_contas(Clientes* CL, int cpf_ver,int codigo_agencia_ver)
{
Clientes* p = CL;
while(p!=NULL){
if((p->codigo_agencia == codigo_agencia_ver) && (p->cpf == cpf_ver)){
return 1;
}
p=p->prox;
}
return 0;
}
///***************funes de imprimir***************///
void imprime_menu_contas()
{
printf("==========================================\n");
printf(" SEO CONTAS!\n");
printf("==========================================\n");
printf("||ESCOLHA UMA DAS OPES: ||\n");
printf("|| 1 - CADASTRAR CONTAS. ||\n");
printf("|| 2 - EXCLUIR CONTAS. ||\n");
printf("|| 3 - LISTAR CONTAS. ||\n");
printf("|| 4 - SAIR ||\n");
printf("==========================================\n");
}
void imprime_menu_contas_listar()
{
printf("==========================================\n");
printf(" SEO LISTAR CONTAS!\n");
printf("==========================================\n");
printf("||ESCOLHA UMA DAS OPES: ||\n");
printf("|| 1 - LISTAR CONTAS DE UM CLIENTE. ||\n");
printf("|| 2 - LISTAR CONTAS DE UMA AGENCIA. ||\n");
printf("|| 3 - LISTAR TODAS AS CONTAS . ||\n");
printf("|| 4 - SAIR ||\n");
printf("==========================================\n");
}
void imprime_menu_contas_excluir()
{
printf("==========================================\n");
printf(" SEO LISTAR CONTAS!\n");
printf("==========================================\n");
printf("||ESCOLHA UMA DAS OPES: ||\n");
printf("|| 1 - EXCLUIR CONTAS DE UM CLIENTE. ||\n");
printf("|| 2 - EXCLUIR CONTAS DE UMA AGENCIA. ||\n");
printf("|| 3 - EXCLUIR UMA CONTA. ||\n");
printf("|| 4 - EXCLUIR TODAS AS CONTAS . ||\n");
printf("|| 5 - SAIR ||\n");
printf("==========================================\n");
}
|
C
|
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main(){
printf ("Лабораторная работа №4 Часть 2, выполнили Клементьев С.В., группа ИСТбд-21\n");
int fd[2], res;
size_t size;
char string[] = "Hi, my name is Sergio";
char resstring[21];
/* Создаем pipe */
int er=pipe(fd); // Создаём канал с двумя файловыми дескрипторами - потоки ввода и вывода
if (er==0){ //ошибка -1 ,0 при нормальном исполнении
//fd[0]-дескриптор, соответствующий входному потоку данных
//канала и позволяющий выполнять только операцию чтения,
//fd[1] - будет занесен файловый дескриптор, соответствующий
//выходному потоку данных и позволяющий выполнять только операцию записи
/* Порождаем дочерний процесс */
res = fork();
if (res > 0){
printf("Работу начал родительский процесс\n");
/* Родитель записывает строку в канал через входной поток */
close(fd[0]);
printf("Начали запись строки...\n");
/*Запись всей строки вместе с признаком конца строки в канал*/
size = write(fd[1],string, 21);
printf("Записали строку...\n");
/* Закрыть выходной поток */
close(fd[1]);
/* Если есть процессы, у которых этот pipe открыт для записи, то системный вызов read блокируется иждет появления информации. */
printf("Закрыли выходной поток! \n");
}
else{
printf("Работу начал дочерний процесс\n");
/* Потомок читает строку из канала через входной поток */
/* Закрыть выходной поток */
close(fd[1]);
printf("Начали чтение строки...\n");
/* Если читается из пустого канала, то процесс блокируется(write,read - блокирующие системные вызовы) */
size = read(fd[0], resstring, 21);
printf("Прочитали строку...\n");
printf("Прочитанная строка: \n");
printf("%s\n", resstring);
/* Закрыть входной поток */
close(fd[0]);
printf("Закрыли входной поток! \n");
}
}
else printf("Ошибка создания канала...\n");
return 0;
/* Когда все процессы, использующие pipe,закрывают все ассоциированные с ним файловые дескрипторы, операционная система ликвидирует pipe. */
}
|
C
|
/* display.c -- How to display Info windows.
$Id$
Copyright (C) 1993, 1997, 2003, 2004 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Originally written by Brian Fox (bfox@ai.mit.edu). */
#include "info.h"
#include "display.h"
extern int info_any_buffered_input_p (void); /* Found in session.c. */
static void free_display (DISPLAY_LINE **display);
static DISPLAY_LINE **make_display (int width, int height);
void handle_tag (char *tag);
void handle_tag_start (char *tag);
void handle_tag_end (char *tag);
/* An array of display lines which tell us what is currently visible on
the display. */
DISPLAY_LINE **the_display = (DISPLAY_LINE **)NULL;
/* Non-zero means do no output. */
int display_inhibited = 0;
/* Initialize THE_DISPLAY to WIDTH and HEIGHT, with nothing in it. */
void
display_initialize_display (int width, int height)
{
free_display (the_display);
the_display = make_display (width, height);
display_clear_display (the_display);
}
/* Clear all of the lines in DISPLAY making the screen blank. */
void
display_clear_display (DISPLAY_LINE **display)
{
register int i;
for (i = 0; display[i]; i++)
{
display[i]->text[0] = '\0';
display[i]->textlen = 0;
display[i]->inverse = 0;
}
}
/* Non-zero if we didn't completely redisplay a window. */
int display_was_interrupted_p = 0;
/* Update the windows pointed to by WINDOW in the_display. This actually
writes the text on the screen. */
void
display_update_display (WINDOW *window)
{
register WINDOW *win;
display_was_interrupted_p = 0;
/* For every window in the list, check contents against the display. */
for (win = window; win; win = win->next)
{
/* Only re-display visible windows which need updating. */
if (((win->flags & W_WindowVisible) == 0) ||
((win->flags & W_UpdateWindow) == 0) ||
(win->height == 0))
continue;
display_update_one_window (win);
if (display_was_interrupted_p)
break;
}
/* Always update the echo area. */
display_update_one_window (the_echo_area);
}
void
handle_tag_start (char *tag)
{
/* TODO really handle this tag. */
return;
}
void
handle_tag_end (char *tag)
{
/* TODO really handle this tag. */
return;
}
void
handle_tag (char *tag)
{
if (tag[0] == '/')
{
tag++;
handle_tag_end (tag);
}
else
handle_tag_start (tag);
}
/* Display WIN on the_display. Unlike display_update_display (), this
function only does one window. */
void
display_update_one_window (WINDOW *win)
{
register char *nodetext; /* Current character to display. */
register char *last_node_char; /* Position of the last character in node. */
register int i; /* General use index. */
char *printed_line; /* Buffer for a printed line. */
int pl_index = 0; /* Index into PRINTED_LINE. */
int line_index = 0; /* Number of lines done so far. */
int pl_ignore = 0; /* How many chars use zero width on screen. */
int allocated_win_width;
DISPLAY_LINE **display = the_display;
/* If display is inhibited, that counts as an interrupted display. */
if (display_inhibited)
display_was_interrupted_p = 1;
/* If the window has no height, or display is inhibited, quit now. */
if (!win->height || display_inhibited)
return;
/* If the window's first row doesn't appear in the_screen, then it
cannot be displayed. This can happen when the_echo_area is the
window to be displayed, and the screen has shrunk to less than one
line. */
if ((win->first_row < 0) || (win->first_row > the_screen->height))
return;
/* Print each line in the window into our local buffer, and then
check the contents of that buffer against the display. If they
differ, update the display. */
allocated_win_width = win->width + 1;
printed_line = (char *)xmalloc (allocated_win_width);
if (!win->node || !win->line_starts)
goto done_with_node_display;
nodetext = win->line_starts[win->pagetop];
last_node_char = win->node->contents + win->node->nodelen;
for (; nodetext < last_node_char; nodetext++)
{
char *rep = NULL, *rep_carried_over, rep_temp[2];
int replen;
if (isprint (*nodetext))
{
rep_temp[0] = *nodetext;
replen = 1;
rep_temp[1] = '\0';
rep = rep_temp;
}
else
{
if (*nodetext == '\r' || *nodetext == '\n')
{
replen = win->width - pl_index + pl_ignore;
}
else if (*nodetext == '\0'
&& (nodetext + 2) < last_node_char
&& *(nodetext + 1) == '\b'
&& *(nodetext + 2) == '[')
{
/* Found new style tag/cookie \0\b[
Read until the closing tag \0\b] */
int element_len = 0;
char *element;
/* Skip the escapes. */
nodetext += 3;
while (!(*nodetext == '\0'
&& *(nodetext + 1) == '\b'
&& *(nodetext + 2) == ']'))
{
nodetext++;
element_len++;
}
element = (char *) malloc (element_len + 1);
strncpy (element, nodetext - element_len, element_len);
/* Skip the escapes. */
nodetext += 2;
pl_ignore += element_len + 5;
/* Append string terminator. */
element[element_len] = '\0';
handle_tag (element);
/* Over and out */
free (element);
continue;
}
else
{
rep = printed_representation (*nodetext, pl_index);
replen = strlen (rep);
}
}
/* Support ANSI escape sequences under -R. */
if (raw_escapes_p
&& *nodetext == '\033'
&& nodetext[1] == '['
&& isdigit (nodetext[2]))
{
if (nodetext[3] == 'm')
pl_ignore += 4;
else if (isdigit (nodetext[3]) && nodetext[4] == 'm')
pl_ignore += 5;
}
while (pl_index + 2 >= allocated_win_width - 1)
{
allocated_win_width *= 2;
printed_line = (char *)xrealloc (printed_line, allocated_win_width);
}
/* If this character can be printed without passing the width of
the line, then stuff it into the line. */
if (replen + pl_index < win->width + pl_ignore)
{
/* Optimize if possible. */
if (replen == 1)
{
printed_line[pl_index++] = *rep;
}
else
{
for (i = 0; i < replen; i++)
printed_line[pl_index++] = rep[i];
}
}
else
{
DISPLAY_LINE *entry;
/* If this character cannot be printed in this line, we have
found the end of this line as it would appear on the screen.
Carefully print the end of the line, and then compare. */
if (*nodetext == '\n' || *nodetext == '\r' || *nodetext == '\t')
{
printed_line[pl_index] = '\0';
rep_carried_over = (char *)NULL;
}
else
{
/* The printed representation of this character extends into
the next line. Remember the offset of the last character
printed out of REP so that we can carry the character over
to the next line. */
for (i = 0; pl_index < (win->width + pl_ignore - 1);)
printed_line[pl_index++] = rep[i++];
rep_carried_over = rep + i;
/* If printing the last character in this window couldn't
possibly cause the screen to scroll, place a backslash
in the rightmost column. */
if (1 + line_index + win->first_row < the_screen->height)
{
if (win->flags & W_NoWrap)
printed_line[pl_index++] = '$';
else
printed_line[pl_index++] = '\\';
}
printed_line[pl_index] = '\0';
}
/* We have the exact line as it should appear on the screen.
Check to see if this line matches the one already appearing
on the screen. */
entry = display[line_index + win->first_row];
/* If the screen line is inversed, then we have to clear
the line from the screen first. Why, I don't know.
(But don't do this if we have no visible entries, as can
happen if the window is shrunk very small.) */
if ((entry && entry->inverse)
/* Need to erase the line if it has escape sequences. */
|| (raw_escapes_p && strchr (entry->text, '\033') != 0))
{
terminal_goto_xy (0, line_index + win->first_row);
terminal_clear_to_eol ();
entry->inverse = 0;
entry->text[0] = '\0';
entry->textlen = 0;
}
/* Find the offset where these lines differ. */
for (i = 0; i < pl_index; i++)
if (printed_line[i] != entry->text[i])
break;
/* If the lines are not the same length, or if they differed
at all, we must do some redrawing. */
if ((i != pl_index) || (pl_index != entry->textlen))
{
/* Move to the proper point on the terminal. */
terminal_goto_xy (i, line_index + win->first_row);
/* If there is any text to print, print it. */
if (i != pl_index)
terminal_put_text (printed_line + i);
/* If the printed text didn't extend all the way to the edge
of the window, and text was appearing between here and the
edge of the window, clear from here to the end of the line. */
if ((pl_index < win->width + pl_ignore
&& pl_index < entry->textlen)
|| (entry->inverse))
terminal_clear_to_eol ();
fflush (stdout);
/* Update the display text buffer. */
if (strlen (printed_line) > (unsigned int) screenwidth)
/* printed_line[] can include more than screenwidth
characters if we are under -R and there are escape
sequences in it. However, entry->text was
allocated (in display_initialize_display) for
screenwidth characters only. */
entry->text = xrealloc (entry->text, strlen (printed_line)+1);
strcpy (entry->text + i, printed_line + i);
entry->textlen = pl_index;
/* Lines showing node text are not in inverse. Only modelines
have that distinction. */
entry->inverse = 0;
}
/* We have done at least one line. Increment our screen line
index, and check against the bottom of the window. */
if (++line_index == win->height)
break;
/* A line has been displayed, and the screen reflects that state.
If there is typeahead pending, then let that typeahead be read
now, instead of continuing with the display. */
if (info_any_buffered_input_p ())
{
free (printed_line);
display_was_interrupted_p = 1;
return;
}
/* Reset PL_INDEX to the start of the line. */
pl_index = 0;
pl_ignore = 0; /* this is computed per line */
/* If there are characters from REP left to print, stuff them
into the buffer now. */
if (rep_carried_over)
for (; rep[pl_index]; pl_index++)
printed_line[pl_index] = rep[pl_index];
/* If this window has chosen not to wrap lines, skip to the end
of the physical line in the buffer, and start a new line here. */
if (pl_index && (win->flags & W_NoWrap))
{
char *begin;
pl_index = 0;
printed_line[0] = '\0';
begin = nodetext;
while ((nodetext < last_node_char) && (*nodetext != '\n'))
nodetext++;
}
}
}
done_with_node_display:
/* We have reached the end of the node or the end of the window. If it
is the end of the node, then clear the lines of the window from here
to the end of the window. */
for (; line_index < win->height; line_index++)
{
DISPLAY_LINE *entry = display[line_index + win->first_row];
/* If this line has text on it then make it go away. */
if (entry && entry->textlen)
{
entry->textlen = 0;
entry->text[0] = '\0';
terminal_goto_xy (0, line_index + win->first_row);
terminal_clear_to_eol ();
}
}
/* Finally, if this window has a modeline it might need to be redisplayed.
Check the window's modeline against the one in the display, and update
if necessary. */
if ((win->flags & W_InhibitMode) == 0)
{
window_make_modeline (win);
line_index = win->first_row + win->height;
/* This display line must both be in inverse, and have the same
contents. */
if ((!display[line_index]->inverse) ||
(strcmp (display[line_index]->text, win->modeline) != 0))
{
terminal_goto_xy (0, line_index);
terminal_begin_inverse ();
terminal_put_text (win->modeline);
terminal_end_inverse ();
strcpy (display[line_index]->text, win->modeline);
display[line_index]->inverse = 1;
display[line_index]->textlen = strlen (win->modeline);
fflush (stdout);
}
}
/* Okay, this window doesn't need updating anymore. */
win->flags &= ~W_UpdateWindow;
free (printed_line);
fflush (stdout);
}
/* Scroll the region of the_display starting at START, ending at END, and
moving the lines AMOUNT lines. If AMOUNT is less than zero, the lines
are moved up in the screen, otherwise down. Actually, it is possible
for no scrolling to take place in the case that the terminal doesn't
support it. This doesn't matter to us. */
void
display_scroll_display (int start, int end, int amount)
{
register int i, last;
DISPLAY_LINE *temp;
/* If this terminal cannot do scrolling, give up now. */
if (!terminal_can_scroll)
return;
/* If there isn't anything displayed on the screen because it is too
small, quit now. */
if (!the_display[0])
return;
/* If there is typeahead pending, then don't actually do any scrolling. */
if (info_any_buffered_input_p ())
return;
/* Do it on the screen. */
terminal_scroll_terminal (start, end, amount);
/* Now do it in the display buffer so our contents match the screen. */
if (amount > 0)
{
last = end + amount;
/* Shift the lines to scroll right into place. */
for (i = 0; i < (end - start); i++)
{
temp = the_display[last - i];
the_display[last - i] = the_display[end - i];
the_display[end - i] = temp;
}
/* The lines have been shifted down in the buffer. Clear all of the
lines that were vacated. */
for (i = start; i != (start + amount); i++)
{
the_display[i]->text[0] = '\0';
the_display[i]->textlen = 0;
the_display[i]->inverse = 0;
}
}
if (amount < 0)
{
last = start + amount;
for (i = 0; i < (end - start); i++)
{
temp = the_display[last + i];
the_display[last + i] = the_display[start + i];
the_display[start + i] = temp;
}
/* The lines have been shifted up in the buffer. Clear all of the
lines that are left over. */
for (i = end + amount; i != end; i++)
{
the_display[i]->text[0] = '\0';
the_display[i]->textlen = 0;
the_display[i]->inverse = 0;
}
}
}
/* Try to scroll lines in WINDOW. OLD_PAGETOP is the pagetop of WINDOW before
having had its line starts recalculated. OLD_STARTS is the list of line
starts that used to appear in this window. OLD_COUNT is the number of lines
that appear in the OLD_STARTS array. */
void
display_scroll_line_starts (WINDOW *window, int old_pagetop,
char **old_starts, int old_count)
{
register int i, old, new; /* Indices into the line starts arrays. */
int last_new, last_old; /* Index of the last visible line. */
int old_first, new_first; /* Index of the first changed line. */
int unchanged_at_top = 0;
int already_scrolled = 0;
/* Locate the first line which was displayed on the old window. */
old_first = old_pagetop;
new_first = window->pagetop;
/* Find the last line currently visible in this window. */
last_new = window->pagetop + (window->height - 1);
if (last_new > window->line_count)
last_new = window->line_count - 1;
/* Find the last line which used to be currently visible in this window. */
last_old = old_pagetop + (window->height - 1);
if (last_old > old_count)
last_old = old_count - 1;
for (old = old_first, new = new_first;
old < last_old && new < last_new;
old++, new++)
if (old_starts[old] != window->line_starts[new])
break;
else
unchanged_at_top++;
/* Loop through the old lines looking for a match in the new lines. */
for (old = old_first + unchanged_at_top; old < last_old; old++)
{
for (new = new_first; new < last_new; new++)
if (old_starts[old] == window->line_starts[new])
{
/* Find the extent of the matching lines. */
for (i = 0; (old + i) < last_old; i++)
if (old_starts[old + i] != window->line_starts[new + i])
break;
/* Scroll these lines if there are enough of them. */
{
int start, end, amount;
start = (window->first_row
+ ((old + already_scrolled) - old_pagetop));
amount = new - (old + already_scrolled);
end = window->first_row + window->height;
/* If we are shifting the block of lines down, then the last
AMOUNT lines will become invisible. Thus, don't bother
scrolling them. */
if (amount > 0)
end -= amount;
if ((end - start) > 0)
{
display_scroll_display (start, end, amount);
/* Some lines have been scrolled. Simulate the scrolling
by offsetting the value of the old index. */
old += i;
already_scrolled += amount;
}
}
}
}
}
/* Move the screen cursor to directly over the current character in WINDOW. */
void
display_cursor_at_point (WINDOW *window)
{
int vpos, hpos;
vpos = window_line_of_point (window) - window->pagetop + window->first_row;
hpos = window_get_cursor_column (window);
terminal_goto_xy (hpos, vpos);
fflush (stdout);
}
/* **************************************************************** */
/* */
/* Functions Static to this File */
/* */
/* **************************************************************** */
/* Make a DISPLAY_LINE ** with width and height. */
static DISPLAY_LINE **
make_display (int width, int height)
{
register int i;
DISPLAY_LINE **display;
display = (DISPLAY_LINE **)xmalloc ((1 + height) * sizeof (DISPLAY_LINE *));
for (i = 0; i < height; i++)
{
display[i] = (DISPLAY_LINE *)xmalloc (sizeof (DISPLAY_LINE));
display[i]->text = (char *)xmalloc (1 + width);
display[i]->textlen = 0;
display[i]->inverse = 0;
}
display[i] = (DISPLAY_LINE *)NULL;
return (display);
}
/* Free the storage allocated to DISPLAY. */
static void
free_display (DISPLAY_LINE **display)
{
register int i;
register DISPLAY_LINE *display_line;
if (!display)
return;
for (i = 0; (display_line = display[i]); i++)
{
free (display_line->text);
free (display_line);
}
free (display);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
typedef int QUDataType;
typedef struct QueueNode
{
struct QueueNode* _next;
QUDataType _data;
}QueueNode;
typedef struct Queue
{
QueueNode* _front; // ͷ
QueueNode* _rear; // β
}Queue;
void QueueInit(Queue* pq);
void QueueDestory(Queue* pq);
QueueNode* BuyQueueNode(QUDataType x);
void QueuePush(Queue* pq, QUDataType x);
void QueuePop(Queue* pq);
QUDataType QueueFront(Queue* pq);
QUDataType QueueBack(Queue* pq);
int QueueEmpty(Queue* pq);
int QueueSize(Queue* pq);
void TestQueue();
|
C
|
#include "ia.h"
int ia_basique(plateau* p, point** point_1, point** point_2, point** point_3, point** point_4, int* size, int c){
/* initialisation d'une liste de tous les pions restants du robot */
liste* l = NULL;
liste* l2 = NULL;
liste_pion(p, &l, c);
while(1){
/* détecte si un pion est proche de la victoire */
if(c % 2 == 0){
if(est_present3(l, 0, *point_1, c)){
if(end_game(p, *point_1, (c+1))){
return 3;
}
}
}
else if(c % 2 == 1){
if(est_present3(l, 7, *point_1, c)){
if(end_game(p, *point_1, (c+1))){
return 3;
}
}
}
/* sélection aléatoire d'un des pions parmi la liste */
random_point(l, point_1);
/* création de la liste des coups envisageables pour ce pion) */
deplacements_envisageables(p, &l2, *point_1, c);
if(c % 2 == 0){
if(est_present3(l2, 0, *point_2, c)){
if(deplacement_possible(p, *point_1, *point_2, (c+1))){
return 1;
}
}
}
if(c % 2 == 1){
if(est_present3(l2, 7, *point_2, c)){
if(deplacement_possible(p, *point_1, *point_2, (c+1))){
return 1;
}
}
}
/* au lieu de choisir aléatoirement, on essaie d'aller le plus loin possible */
if(c % 2 == 0){
if(!est_present3(l2, ((*point_1)->y) - 3, *point_2, c)){
if(!est_present3(l2, ((*point_1)->y) - 2, *point_2, c)){
est_present3(l2, ((*point_1)->y) - 1, *point_2, c);
}
}
}
if(c % 2 == 1){
if(!est_present3(l2, ((*point_1)->y) + 3, *point_2, c)){
if(!est_present3(l2, ((*point_1)->y) + 2, *point_2, c)){
est_present3(l2, ((*point_1)->y) + 1, *point_2, c);
}
}
}
else{
random_point(l2, point_2);
}
if(deplacement_possible(p, *point_1, *point_2, (c+1))){
return 1;
}
}
return -1;
}
int ia_random(plateau* p, point** point_1, point** point_2, point** point_3, point** point_4, int* size, int c){
/* initialisation d'une liste de tous les pions restants du robot */
liste* l = NULL;
liste* l2 = NULL;
liste_pion(p, &l, c);
while(1){
/* sélection aléatoire d'un des pions parmi la liste */
random_point(l, point_1);
if(c % 2 == 0){
if((*point_1)->y == 0){
return 3;
}
}
if(c % 2 == 1){
if((*point_1)->y == 7){
return 3;
}
}
/* création de la liste des coups envisageables pour ce pion) */
deplacements_envisageables(p, &l2, *point_1, c);
/* sélection aléatoire d'un des mouvements possibles de la liste */
random_point(l2, point_2);
if(deplacement_possible(p, *point_1, *point_2, (c+1))){
return 1;
}
}
return -1;
}
void liste_pion(plateau* p, liste** l, int joueur){
int i,j;
for(i = 0 ; i < 8 ; i++){
for(j = 0 ; j < 8 ; j++){
if((p->cell[i][j] != NULL) && ((joueur) % 2 == p->cell[i][j]->couleur)){
append(l, j, i);
}
}
}
}
void deplacements_envisageables(plateau* p, liste** l, point* point, int joueur){
/* retourne la liste des positions parcourables par la pièce */
/* coordonnées de départ */
int x, y;
x = point->x;
y = point->y;
joueur ++;
switch(p->cell[y][x]->forme){
case 1:
if(joueur % 2 == 0){
s4(p, l, x, y, 1);
o4(p, l, x, y, 1);
e4(p, l, x, y, 1);
}
else{
n4(p, l, x, y, 1);
o4(p, l, x, y, 1);
e4(p, l, x, y, 1);
}
break;
case 2:
if(joueur % 2 == 0){
s4(p, l, x, y, 2);
o4(p, l, x, y, 2);
e4(p, l, x, y, 2);
}
else{
n4(p, l, x, y, 3);
o4(p, l, x, y, 3);
e4(p, l, x, y, 3);
}
break;
case 3:
if(joueur % 2 == 0){
s4(p, l, x, y, 3);
o4(p, l, x, y, 3);
e4(p, l, x, y, 3);
}
else{
n4(p, l, x, y, 3);
o4(p, l, x, y, 3);
e4(p, l, x, y, 3);
}
break;
case 4:
if(joueur % 2 == 0){
se4(p, l, x, y, 1);
so4(p, l, x, y, 1);
}
else{
no4(p, l, x, y, 1);
ne4(p, l, x, y, 1);
}
break;
case 5:
if(joueur % 2 == 0){
se4(p, l, x, y, 1);
so4(p, l, x, y, 1);
s4(p, l, x, y, 1);
o4(p, l, x, y, 1);
e4(p, l, x, y, 1);
}
else{
no4(p, l, x, y, 1);
ne4(p, l, x, y, 1);
n4(p, l, x, y, 1);
o4(p, l, x, y, 1);
e4(p, l, x, y, 1);
}
break;
case 6:
if(joueur % 2 == 0){
se4(p, l, x, y, 1);
so4(p, l, x, y, 1);
s4(p, l, x, y, 2);
o4(p, l, x, y, 2);
e4(p, l, x, y, 2);
}
else{
no4(p, l, x, y, 1);
ne4(p, l, x, y, 1);
n4(p, l, x, y, 3);
o4(p, l, x, y, 3);
e4(p, l, x, y, 3);
}
break;
case 8:
if(joueur % 2 == 0){
se4(p, l, x, y, 2);
so4(p, l, x, y, 2);
}
else{
no4(p, l, x, y, 2);
ne4(p, l, x, y, 2);
}
break;
case 9:
if(joueur % 2 == 0){
se4(p, l, x, y, 2);
so4(p, l, x, y, 2);
s4(p, l, x, y, 1);
o4(p, l, x, y, 1);
e4(p, l, x, y, 1);
}
else{
no4(p, l, x, y, 2);
ne4(p, l, x, y, 2);
n4(p, l, x, y, 1);
o4(p, l, x, y, 1);
e4(p, l, x, y, 1);
}
break;
case 12:
if(joueur % 2 == 0){
se4(p, l, x, y, 3);
so4(p, l, x, y, 3);
}
else{
no4(p, l, x, y, 3);
ne4(p, l, x, y, 3);
}
break;
}
}
void so4(plateau* p, liste** l, int x, int y, int taille){
int i;
for(i = 1 ; i <= taille ; i++){
if(coord_dans_tab(x - i, y + i)){
append(l, x - i, y + i);
}
}
}
void se4(plateau* p, liste** l, int x, int y, int taille){
int i;
for(i = 1 ; i <= taille ; i++){
if(coord_dans_tab(x + i, y + i)){
append(l, x + i, y + i);
}
}
}
void no4(plateau* p, liste** l, int x, int y, int taille){
int i;
for(i = 1 ; i <= taille ; i++){
if(coord_dans_tab(x - i, y - i)){
append(l, x - i, y - i);
}
}
}
void ne4(plateau* p, liste** l, int x, int y, int taille){
int i;
for(i = 1 ; i <= taille ; i++){
if(coord_dans_tab(x + i, y - i)){
append(l, x + i, y - i);
}
}
}
void s4(plateau* p, liste** l, int x, int y, int taille){
int i;
for(i = 1 ; i <= taille ; i++){
if(coord_dans_tab(x, y + i)){
append(l, x, y + i);
}
}
}
void n4(plateau* p, liste** l, int x, int y, int taille){
int i;
for(i = 1 ; i <= taille ; i++){
if(coord_dans_tab(x, y - i)){
append(l, x, y - i);
}
}
}
void e4(plateau* p, liste** l, int x, int y, int taille){
int i;
for(i = 1 ; i <= taille ; i++){
if(coord_dans_tab(x + i, y)){
append(l, x + i, y);
}
}
}
void o4(plateau* p, liste** l, int x, int y, int taille){
int i;
for(i = 1 ; i <= taille ; i++){
if(coord_dans_tab(x - i, y)){
append(l, x - i, y);
}
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printffd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lfujimot <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/10 17:39:51 by lfujimot #+# #+# */
/* Updated: 2018/04/10 17:39:54 by lfujimot ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_printf.h"
static void ft_init_ctx(t_ctx *ctx, const char *format, int fd)
{
ctx->format = format;
ctx->pos = 0;
ctx->size = 0;
ctx->fd = fd;
}
static void ft_init_arg(t_arg *current)
{
current->type = 0;
current->flags.moins = 0;
current->flags.plus = 0;
current->flags.zero = 0;
current->flags.space = 0;
current->flags.hash = 0;
current->width = 0;
current->prec = -1;
current->mod = NONE;
current->endpos = 0;
}
static int ft_do_printf(va_list va, t_ctx *ctx)
{
t_arg current;
int i;
int err;
i = 0;
while (ctx->format[i])
{
if (ctx->format[i] == '%')
{
ft_init_arg(¤t);
ft_parse(¤t, i, ctx);
err = ft_manage_type(¤t, va, ctx);
if (err == -1)
return (err);
if (ft_istype(current.type) == 0 && !ctx->format[i])
break ;
else if (ft_istype(current.type) == 0)
current.endpos--;
i = current.endpos + 1;
}
else
ft_flush(ctx, ctx->format[i++]);
}
return (0);
}
int ft_printffd(int fd, const char *format, ...)
{
va_list va;
t_ctx ctx;
int err;
ft_init_ctx(&ctx, format, fd);
va_start(va, format);
err = ft_do_printf(va, &ctx);
if (err == -1)
return (-1);
ctx.buf[ctx.pos] = '\0';
write(fd, ctx.buf, ctx.pos);
va_end(va);
return (ctx.size);
}
|
C
|
#pragma once
#define INF 65535
#include"grpAdjMatrix.h"
#include"seqQueue.h"
#include"seqStack.h"
#include"BiTree.h"
#include"forest.h"
typedef struct edgetype
{
int vBegin; //ߵʼţ1ʼ
int vEnd; //ߵһţ1ʼ
int eWeight; //ߵȨֵ
}EdgeType; //
typedef struct minEdgeType
{
int v;//һ˵Ķ
cellType eWeight;//ߵȨֵ
}MinEdgeType;//Ԫ
//1.ӡͼֱ
//DFSȱ㷨
//ڽӾDFSʵ
void DFS(Graph &G, int verID){
int w;
visit(G, verID);
w=firstAdj(G, verID);
while(w!=0){
if(!visited[w]) //wδ
DFS(G, w); //ݹȱ
w=nextAdj(G, verID, w); //ݹ鷵غverIDλwһڽӵ
}
}
void AdjMatrixDFSTraverse(Graph &G){
int vID=0;
cout << "ʵ:" ;
cin >> vID;
cin.get();
//ǵvisitʼΪfalse
for(vID=1; vID<=G.VerNum; vID++){
visited[vID]=false;
}
DFS(G, vID);//ָ
for(vID=1; vID<=G.VerNum; vID++){
//öıλΪfalse
if(!visited[vID]){
DFS(G, vID);
}
}
cout << "\nDFSȱ!" << endl;
}
//BFSȱ㷨
//ڽӾBFSʵ
void BFS(Graph &G, int verID){
visit(G, verID);
seqQueue Q;
initialSeqQueue(Q); //ʼѭ˳
seqEnQueue(Q, verID); //ΪverIDĶ
char v, w;
while(!seqQueueEmpty(Q)){ //вѭ
seqOutQueue(Q, v); //v
w=firstAdj(G, v); //vĵһڽӵ
while(w!=0){
if(!visited[w]){ //wδʣwѷ
visit(G, w);
seqEnQueue(Q, w); //w
}
w=nextAdj(G,v,w); //vλwһڽӵ
}
}
}
void AdjMatrixBFSTraverse(Graph &G){
int vID=0;
cout << "ʵ:" ;
cin >> vID;
cin.get();
for(vID=1; vID<=G.VerNum; vID++) //ʼ
visited[vID]=false;
BFS(G, vID); //ָĶ㣬ָĵһͨ
for(vID=1; vID<=G.VerNum; vID++){ //αͼͨ
if(!visited[vID])
BFS(G, vID);
}
cout << "\nBFSȱ!" << endl;
}
//2. ͼĻĿ.
void ArcNum(Graph &G){
cout << "ͼĻĿΪ:" << G.ArcNum << "." << endl;
}
//3. ȱ.
void DFS_CreatTree(Graph &G, csNode *&T, int verID){
csNode *p;
csNode *u;
int w;
visited[verID] = true;
w=firstAdj(G,verID);
if(w!=0){
while(visited[w] && w!=0)
w=nextAdj(G, verID, w);
if(w!=0){
p=new csNode;
p->data = G.Data[w];
p->firstChild=NULL;
p->nextSibling=NULL;
T->firstChild=p;
}
}
u=p;
while(w!=0){
if(!visited[w]) //wδ
DFS_CreatTree(G, u, w); //ݹȱ
w=nextAdj(G,verID, w); //ݹ鷵غverIDλwһڽӵ
if(w!=0 && !visited[w]){
p=new csNode;
p->data=G.Data[w];
p->firstChild=NULL;
p->nextSibling=NULL;
while(u->nextSibling!=NULL)
u=u->nextSibling;
u->nextSibling=p;
}
if(u!=NULL)
u=u->nextSibling;
}
}
void DFSTraverseCreatTree(Graph &G, csNode *&T){
int vID;
cout << "ʵ:" ;
cin >> vID;
cin.get();
csNode *p;
csNode *u;
for(vID=1;vID<=G.VerNum;vID++) //ʼ
visited[vID]=false;
T=new csNode;
T->data=G.Data[vID];
T->firstChild=NULL;
T->nextSibling=NULL;
u=T;
DFS_CreatTree(G, T, vID); //ָĶ㣬ָĵһͨ
for(vID=1; vID<=G.VerNum; vID++){ //αͼͨ
if(!visited[vID]){
p=new csNode;
p->data=G.Data[vID];
p->firstChild=NULL;
p->nextSibling=NULL;
while(u->nextSibling)
u=u->nextSibling;
u->nextSibling=p;
DFS_CreatTree(G, p, vID);
}
}
cout << "ڽӾɭֱΪ(DFS):";
prOrder(T);
destroyTree(T);
}
//4. ȱ.
void BFS_CreatTree(Graph &G, csNode *&T, int verID){
csNode *u=T;
csNode *p;
int v, w; //
v=verID;
seqQueue Q;
initialSeqQueue(Q); //ʼѭ˳
visited[verID]=true;
seqEnQueue(Q, verID); //ΪverIDĶ
while(!seqQueueEmpty(Q)){ //вѭ
seqOutQueue(Q, v); //v
w=firstAdj(G,v); //vverIDĵһڽӵ㣬صw
if(w!=0){
while(visited[w] && w!=0)
w=nextAdj(G,v,w);
if(w == 0)
break;
p=new csNode;
p->data=G.Data[w];
p->firstChild=NULL;
p->nextSibling=NULL;
u->firstChild=p;
}
u=p;
while(w!=0){
if(!visited[w]){ //wδʣwǣ
visited[w]=true;
seqEnQueue(Q,w);
}
w=nextAdj(G,v,w); //vλw֮һڽӵ
if(w!=0 && !visited[w]){
p=new csNode;
p->data=G.Data[w];
p->firstChild=NULL;
p->nextSibling=NULL;
while(u->nextSibling!=NULL)
u=u->nextSibling;
u->nextSibling=p;
}
}
}
}
int BFSTraverseCreatTree(Graph &G, csNode *&T){
int vID;
cout << "ʵ:" ;
cin >> vID;
cin.get();
csNode *p;
csNode *u;
for(vID=1;vID<=G.VerNum;vID++) //ʱʼ
visited[vID]=false;
T=new csNode;
T->data=G.Data[vID];
T->firstChild=NULL;
T->nextSibling=NULL;
u=T;
BFS_CreatTree(G, T, vID); //ָĶ㣬ָĵһͨ
for(vID=1; vID<=G.VerNum; vID++){ //αͼͨ
if(!visited[vID]){
p=new csNode;
p->data=G.Data[vID];
p->firstChild=NULL;
p->nextSibling=NULL;
while(u->nextSibling!=NULL)
u=u->nextSibling;
u->nextSibling=p;
BFS_CreatTree(G, p, vID);
}
}
cout << "ڽӾɭֱΪ(BFS):";
prOrder(T);
destroyTree(T);
}
//5. Prim㷨С.
int HasEdge(Graph &G, int vBegin, int vEnd){
if(G.gKind==UDN || G.gKind==DN){ //
if(G.AdjMatrix[vBegin][vEnd]!=INF) //Ȩֵб
return 1; //бߣ1
else
return 0; //ޱߣ0
}
else{ //ͼ
if(G.AdjMatrix[vBegin][vEnd]==1) //±1
return 1; //бߣ1
else
return 0; //ޱߣ0
}
}
void InitialTE(Graph &G, MinEdgeType TE[], int vID){
int i;
for(i=1;i<=G.VerNum;i++){
if(HasEdge(G, vID, i) == 1){
TE[i].v=vID;
TE[i].eWeight=G.AdjMatrix[vID][i];
}
else
TE[i].eWeight=INF;//ڸֵΪ
}
}
int GetMinEdge(Graph &G, MinEdgeType TE[]){
cellType eMin=INF; //СȨֵ
int i,j;
for(i=1;i<=G.VerNum;i++){
if(visited[i]== false && TE[i].eWeight<eMin){
j=i;//С±
eMin=TE[i].eWeight;
}
}
return j; //jΪV-UУС߹ı
}
void UpdateTE(Graph &G, MinEdgeType TE[], int vID){
//ѡıΪvIDĶ㣨¼뼯UУѡ
int i,j;
for(i=1;i<=G.VerNum;i++){
if(visited[i]== false){ //iV-UУU
if(HasEdge(G,vID,i) && G.AdjMatrix[vID][i]<=TE[i].eWeight){
TE[i].v=vID;
TE[i].eWeight=G.AdjMatrix[vID][i];
}
}
}
}
void Prim(Graph &G){
int vID;
cout << "ʵ:" ;
cin >> vID;
cin.get();
MinEdgeType TE[MaxVerNum];
int curID;
int i;
cellType wALL=0;//Ȩֵܺ
InitialTE(G, TE, vID);//ȡ㵽 vIDȨֵ
visited[vID]=true;//Ѿ
for(i=1; i<G.VerNum; i++){
curID=GetMinEdge(G, TE);
visited[curID]=true;
UpdateTE(G, TE, curID);
}
cout << "PrimСʼΪ:" << G.Data[vID] << endl;
cout << "ѡıߺȨֵ:" << endl;
for(i=1; i<=G.VerNum; i++){
if(i!=vID){
cout << "(" << G.Data[TE[i].v] << "," << G.Data[i] << ")";
wALL+=TE[i].eWeight;
}
}
cout << "СȨֵ:"<< wALL << endl;
}
//6. Kruskal㷨С.
void GetEdges(Graph &G, EdgeType edges[]){
int i,j;
int k=1;
for(i=1; i<=G.VerNum; i++){ //ѭ
for(j=1; j<=G.VerNum; j++){ //ѭ
if((G.AdjMatrix[i][j]>=1) && (G.AdjMatrix[i][j]<INF)){
edges[k].vBegin=i; //ߵĵһ
edges[k].vEnd=j; //ߵĵڶ
edges[k].eWeight=G.AdjMatrix[i][j]; //ߵȨֵ
k++;
}
}
}
}
EdgeType GetMinEdge(Graph &G, EdgeType edges[], int edgeUsed[], int &n){
//nΪصСedges[]е±
EdgeType minEdge;
cellType wMin=INF; //СȨֵ
int i;
int M; //ѭ
if(G.gKind==UDG || G.gKind==UDN)
M=G.ArcNum*2; //ͼӦΪԳԣڽӾЧDZ2
else
M=G.ArcNum; //ͼУMΪͼı
for(i=0; i<M ;i++){
//ΪͼڽӾԳУЧDZ2Գ2
if(edgeUsed[i]==0 && edges[i].eWeight<wMin){
wMin=edges[i].eWeight;
minEdge.eWeight=edges[i].eWeight;;
minEdge.vBegin=edges[i].vBegin;
minEdge.vEnd=edges[i].vEnd;
n = i;//¼С
}
}
return minEdge; //ȡõС
}
void Kruskal(Graph &G){
int conVerID[MaxVerNum]; //ͨ
EdgeType edges[MaxVerNum*MaxVerNum]; //ͼбϢ
EdgeType treeEdges[MaxVerNum]; //еıϢn-1
int edgeUsed[MaxVerNum*MaxVerNum];
EdgeType minEdge;
int i,j;
int k=0;
int conID; //ߵֹͨı
int n; //صСߵ
GetEdges(G, edges);//ȡб
int M; //ѭ
if(G.gKind==UDG ||G.gKind==UDN)
M=G.ArcNum*2;
else
M=G.ArcNum;
for(i=0; i<M; i++)
edgeUsed[i]=0;
for(i=1; i<=G.VerNum; i++)
conVerID[i]=i;
for(i=1; i<G.VerNum; i++){ //ȡn-1ߣ
minEdge=GetMinEdge(G, edges, edgeUsed, n );
while(conVerID[minEdge.vBegin] == conVerID[minEdge.vEnd]){
edgeUsed[n]=1; //Dz
minEdge=GetMinEdge( G, edges, edgeUsed, n );
}
treeEdges[i]=minEdge;//ѡС߷ŵ
conID=conVerID[minEdge.vEnd];
for(j=1; j<=G.VerNum; j++){ //ϲͨ
if(conVerID[j]==conID)
conVerID[j]=conVerID[minEdge.vBegin];
}
edgeUsed[n]=1; //Ѿʹù
}
cellType wAll=0; //Ȩֵ
cout << endl; //
cout << "ѡıߺȨֵ:" << endl;
for(i=1;i<G.VerNum;i++){ //n-1
cout << "("<<G.Data[treeEdges[i].vBegin]<<","<<G.Data[treeEdges[i].vEnd]<<")";
wAll+=treeEdges[i].eWeight;
}
cout << "СȨֵ:"<<wAll << endl;
cout << endl;
}
//7. Dijkstra㷨·.
void PrintDijkstra(Graph &G, int path[], int dist[], int vID ){
//sPath[]vIDĿ궥i·
int sPath[MaxVerNum];
int vPre; //ǰ
int top=-1; //·ϵĶԿ·
int i, j;
for(i=1; i<=G.VerNum; i++){
cout << G.Data[vID] << "" << G.Data[i] << "·";
if(dist[i]==INF)
cout << "ɴ·." << endl;
else{
cout << "̾:" <<dist[i] << endl;
cout << "·:";
}
top++;
sPath[top]=i; //sPath[]Ŀ궥i
vPre=path[i];
while(vPre!=-1){
top++;
sPath[top]=vPre;
vPre=path[vPre];
}
if(dist[i]!=INF){
//sPath[top]ΪָʼvID
for(j=top; j>=0; j-- ){
cout << G.Data[sPath[j]];
if(j != 0)
cout << "->";
}
}
top=-1;
cout << endl;
}
}
void Dijkstra(Graph &G){
int vID;
cout << "ʵ:" ;
cin >> vID;
cin.get();
int path[MaxVerNum];
int dist[MaxVerNum];
int solved[MaxVerNum];//Ƿ·
int i, j, v;
cellType minDist;//̾
for(i=1;i<=G.VerNum;i++){
solved[i]=0;//ʼǶδҵ
dist[i]=G.AdjMatrix[vID][i];//ʼ㵽
if(dist[i]!=INF)
path[i]=vID; //iǰΪvID
else
path[i]=-1; //ǰiǰ
}
solved[vID]=1;//ʼѽ
dist[vID]=0; //ʼڵ㵽ԼΪ0
path[vID]=-1;
for(i=1; i<G.VerNum; i++){
minDist=INF;
for(j=1;j<=G.VerNum;j++){
if(solved[j]==0 && dist[j]<minDist){
v=j;//ѽ±
minDist=dist[j];
}
}
if(minDist == INF){//δҵ
cout<<"ͼͨͼ"<<endl;
return;
}
solved[v]=1;
for(j=1; j<=G.VerNum; j++){
if(solved[j]==0 && (minDist+G.AdjMatrix[v][j])<dist[j]){
dist[j]=minDist+G.AdjMatrix[v][j];
path[j]=v; //¶jֱǰΪv
}
}
}
PrintDijkstra(G, path, dist, vID);
}
//8. Floyd㷨·.
void PrintFloyd(Graph &G, int dist[MaxVerNum][MaxVerNum], int path[MaxVerNum][MaxVerNum]){
int sPath[MaxVerNum];
int prior;
int top=-1;
for(int i=1; i<=G.VerNum; i++){
for(int j=1; j<=G.VerNum; j++){
cout << G.Data[i] << "" << G.Data[j];
if(dist[i][j]==INF)
cout << "·." << endl;
else{
cout << "̾:" << dist[i][j] << endl;
cout << "·Ϊ:";
top++;
sPath[top]=j; //sPath[0]Ϊǰi
prior=path[i][j]; //iǰ
while(prior!=i){
top++;
sPath[top]=prior;
prior=path[i][prior];
}
top++;
sPath[top]=i; //ӽʼi
if(dist[i][j]!=INF){
for(int m=top;m>=0;m--){
//sPath[top]Ϊָʼ
cout << G.Data[sPath[m]] << " ";
if(m != 0)
cout<<"->";
}
}
top=-1;
cout << endl << endl;
}
}
}
}
void Floyd(Graph &G){
int i, j, m;
int dist[MaxVerNum][MaxVerNum];
int path[MaxVerNum][MaxVerNum];
for(i=1; i<=G.VerNum; i++){ //ʼ·
for(j=1;j<=G.VerNum;j++){
//ʼΪڽӾ
dist[i][j]=G.AdjMatrix[i][j];
if(i!=j && G.AdjMatrix[i][j]<INF)
path[i][j]=i;
else
path[i][j]=-1;
}
}
for(m=1; m<=G.VerNum; m++){//m
for(i=1; i<=G.VerNum; i++){
for(j=1; j<=G.VerNum;j++){
//mΪ㣬ij֮СmΪת
if(i!=j && dist[i][m]+dist[m][j]<dist[i][j]){
//̾
dist[i][j]=dist[i][m]+dist[m][j];
path[i][j]=path[m][j];
}
}
}
}
PrintFloyd(G, dist, path);
}
//9. .
void GetInDegrees(Graph &G, int inds[]){
for(int j=1; j<=G.VerNum; j++){
for(int i=1; i<=G.VerNum; i++){
if(G.AdjMatrix[i][j]>=1 && G.AdjMatrix[i][j]<INF)
inds[j]++;
}
}
}
bool TopologicalSort(Graph &G, int topoList[]){
seqStack S;
initialStacksS(S);
int v, w;//
int ind[MaxVerNum];
for(int i=1; i<=G.VerNum; i++)
ind[i]=0; //ʼ
for(int i=1; i<G.VerNum; i++)
topoList[i]=-1;
GetInDegrees(G, ind);
for(int i=1; i<=G.VerNum; i++){
if(ind[i]==0)
pushStacksS(S, i);
}
int iCount=0;
while(!stackEmptysS(S)){
popStacksS(S, v); //ջһΪ0Ķŵv
cout << G.Data[v];
w = firstAdj(G,v);
iCount++;
topoList[iCount]=v;
while(w!=0){
ind[w]--;
if(ind[w]==0) //wѾΪ0ջ
pushStacksS(S,w);
w=nextAdj(G,v,w);
}
}
if(iCount == G.VerNum){
//nΪͼĶ
cout << endl << "Բ!" << endl;
return true;
}
else{
cout << endl << "Բ" << endl;
return false;
}
}
//10.AOEؼ·.
void PrintKeyPath(Graph &G ,int topoList[] , int vlt[],int vet[]){
int w, v; //жؼ·
cout << "ؼ·Ϊ:";
v=topoList[1];
cout << G.Data[v]; //Դ
while(v!=0){
w=firstAdj(G, v); //vĵһڽӵ
if(w!=0)
cout<<"->";
while(w!=0){
if(vet[w]==vlt[w]){
//ؼĶ
cout<<G.Data[w];
break;
}
else
w=nextAdj(G,v,w); //һڽӵ
}
v=w;
}
}
void _KeyPath(Graph &G, int topoList []){
int i,j;
int vet[MaxVerNum];//緢ʱ
int vlt[MaxVerNum];//ʼʱ
int vPre; //涥ǰ
int vSuc; //涥ĺ̶
for(i=1; i<=G.VerNum; i++)
vet[i]=0;
for(i=1; i<=G.VerNum; i++){
vPre=topoList[i];
for(j=1; j<=G.VerNum; j++){
if(G.AdjMatrix[vPre][j]>=1 && G.AdjMatrix[vPre][j]<INF)
if(vet[j]<vet[vPre]+G.AdjMatrix[vPre][j])
vet[j]=vet[vPre]+G.AdjMatrix[vPre][j];
}
}
for(i=1;i<=G.VerNum;i++)
vlt[i]=vet[G.VerNum];
for(i=G.VerNum; i>=1; i--){
vSuc=topoList[i];
for(j=G.VerNum;j>=1;j--){
//jvSuc
if(G.AdjMatrix[j][vSuc]>=1 && G.AdjMatrix[j][vSuc]<INF)
if(vlt[j] > vlt[vSuc]-G.AdjMatrix[j][vSuc])
vlt[j]=vlt[vSuc]-G.AdjMatrix[j][vSuc];
}
}
PrintKeyPath(G, topoList, vlt, vet);
}
void KeyPath(Graph &G, int topoList[]){
if(TopologicalSort(G, topoList)){
cout << "ڽӾʵ:" << endl;
_KeyPath(G, topoList);
}
else
cout << "ڹؼ·!" <<endl;
}
|
C
|
#include <sys/socket.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <string.h>
// gcc -g -o libmotan_tools.so -fpic -shared motan_tools.c
int get_local_ip(char * ifname, char * ip)
{
char *temp = NULL;
int inet_sock;
struct ifreq ifr;
inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
memset(ifr.ifr_name, 0, sizeof(ifr.ifr_name));
memcpy(ifr.ifr_name, ifname, strlen(ifname));
if(0 != ioctl(inet_sock, SIOCGIFADDR, &ifr))
{
perror("ioctl error");
return -1;
}
temp = inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr);
memcpy(ip, temp, strlen(temp));
close(inet_sock);
return 0;
}
|
C
|
#include <pebble.h>
#include <time.h>
// Shorthand for debug
#define D(fmt, args...) \
app_log(APP_LOG_LEVEL_DEBUG, __FILE__, __LINE__, fmt, ## args)
#define SEGMENT_RESOLUTION 20
#define RADIUS 50
#define TIME_STRING_BUFFER_SIZE 6
// extends it out a little further to chop off edge of circle
#define EDGE_OF_SEGMENT_COMPENSATION 5
Window *window;
TextLayer *time_display;
Layer *segment_display_layer;
GPath *triangle_path;
int twelve_oclock_rotation = -90,
angle_hour_interval = 360 / 12,
angle_minute_interval = 360 / 60;
char time_string[TIME_STRING_BUFFER_SIZE];
GPoint triangle_path_points[SEGMENT_RESOLUTION];
GPathInfo triangle_path_info = {
.num_points = SEGMENT_RESOLUTION,
.points = triangle_path_points
};
// parametric equation for a circle
// x = cx + r * cos(a)
// y = cy + r * sin(a)
GPoint point_on_circle(int radius, int angle) {
return (GPoint) {
.x = 0 + (radius + EDGE_OF_SEGMENT_COMPENSATION) *
cos_lookup(angle) / TRIG_MAX_RATIO,
.y = 0 + (radius + EDGE_OF_SEGMENT_COMPENSATION) *
sin_lookup(angle) / TRIG_MAX_RATIO
};
}
void render_segment(GContext *context, GPoint position, int radius, int rotation, int angle) {
angle = ((360 - angle) % 360) / 360.0 * TRIG_MAX_ANGLE;
rotation = (rotation % 360) / 360.0 * TRIG_MAX_ANGLE;
triangle_path_info.points[0] = GPointZero;
triangle_path_info.points[1] = point_on_circle(radius, 0);
int partial_angle;
for (int i = 1; i <= SEGMENT_RESOLUTION - 2; ++i) {
partial_angle = angle / (SEGMENT_RESOLUTION - 2) * i;
triangle_path_info.points[i + 1] = point_on_circle(radius, -partial_angle);
}
graphics_context_set_fill_color(context, GColorWhite);
graphics_fill_circle(context, position, radius);
graphics_context_set_fill_color(context, GColorBlack);
gpath_move_to(triangle_path, position);
gpath_rotate_to(triangle_path, rotation);
gpath_draw_filled(context, triangle_path);
}
void render_clock(GContext *context, GPoint position, struct tm *time_info) {
int hours, minutes, rotation, angle, hours_clock_angle_deg, minutes_clock_angle_deg;
angle = 0;
rotation = 0;
hours = time_info->tm_hour;
minutes = time_info->tm_min;
hours_clock_angle_deg = angle_hour_interval * hours % 360;
minutes_clock_angle_deg = angle_minute_interval * minutes % 360;
if (hours % 2 == 0 && minutes_clock_angle_deg >= hours_clock_angle_deg) {
rotation = hours_clock_angle_deg;
angle = minutes_clock_angle_deg - hours_clock_angle_deg;
} else if (hours % 2 == 0 && minutes_clock_angle_deg < hours_clock_angle_deg) {
rotation = minutes_clock_angle_deg;
angle = hours_clock_angle_deg - minutes_clock_angle_deg;
} else if (hours % 2 != 0 && minutes_clock_angle_deg >= hours_clock_angle_deg) {
rotation = minutes_clock_angle_deg;
angle = 360 + hours_clock_angle_deg - minutes_clock_angle_deg;
} else if (hours % 2 != 0 && minutes_clock_angle_deg < hours_clock_angle_deg) {
rotation = hours_clock_angle_deg;
angle = 360 - hours_clock_angle_deg + minutes_clock_angle_deg;
}
rotation += twelve_oclock_rotation;
render_segment(context, position, RADIUS, rotation, angle);
}
void segment_display_layer_update_callback(Layer *layer, GContext *context) {
time_t raw_time = time(NULL);
struct tm *time_info = localtime(&raw_time);
GRect bounds = layer_get_bounds(layer);
GPoint center = grect_center_point(&bounds);
center.y += 20; // HACK to better position the clock
render_clock(context, center, time_info);
strftime(time_string, sizeof(time_string), "%I:%M", time_info);
text_layer_set_text(time_display, time_string);
}
void handle_tick(struct tm *tick_time, TimeUnits units_changed) {
layer_mark_dirty(segment_display_layer);
}
void window_load(Window *window) {
Layer *layer = window_get_root_layer(window);
GRect layer_bounds = layer_get_bounds(layer);
window_set_background_color(window, GColorBlack);
time_display = text_layer_create(layer_bounds);
text_layer_set_background_color(time_display, GColorClear);
text_layer_set_text_color(time_display, GColorWhite);
text_layer_set_text_alignment(time_display, GTextAlignmentCenter);
text_layer_set_font(time_display, fonts_get_system_font(FONT_KEY_BITHAM_42_MEDIUM_NUMBERS));
triangle_path = gpath_create(&triangle_path_info);
segment_display_layer = layer_create(layer_bounds);
layer_set_update_proc(segment_display_layer, segment_display_layer_update_callback);
layer_add_child(layer, segment_display_layer);
layer_add_child(layer, text_layer_get_layer(time_display));
tick_timer_service_subscribe(MINUTE_UNIT, handle_tick);
}
void window_unload(Window *window) {
tick_timer_service_unsubscribe();
layer_destroy(segment_display_layer);
gpath_destroy(triangle_path);
text_layer_destroy(time_display);
}
void init(void) {
window = window_create();
window_set_window_handlers(window, (WindowHandlers) {
.load = window_load,
.unload = window_unload
});
window_stack_push(window, true);
}
void deinit(void) {
window_destroy(window);
}
int main(void) {
init();
D("Done initializing, pushed window: %p", window);
app_event_loop();
deinit();
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* exec.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jpfeffer <jpfeffer@student.42.us.org> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/06/03 21:33:29 by jpfeffer #+# #+# */
/* Updated: 2017/06/03 21:33:29 by jpfeffer ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
static void ft_s_ixusr(char *argv, char **path)
{
struct stat stats;
char *temp;
temp = ft_add_path(*path, argv);
while (*path)
{
lstat(temp, &stats);
if (S_ISREG(stats.st_mode) && (!(stats.st_mode & S_IXUSR)))
ft_print_error("permission denied:", argv);
free(temp);
path++;
if ((!(*path)))
ft_print_error("command not found:", argv);
temp = ft_add_path(*path, argv);
}
}
static void ft_run_path(char **path, char **argv, char **environ)
{
char **ptr;
char *temp;
ptr = path;
temp = ft_add_path(*path, argv[0]);
while (*path)
{
if (execve(temp, argv, environ) != -1)
exit(0);
free(temp);
path++;
if ((!(*path)))
ft_s_ixusr(argv[0], ptr);
temp = ft_add_path(*path, argv[0]);
}
}
static void ft_exec_path(char **argv, char **environ, char *cwd)
{
char **path;
char *temp;
temp = ft_add_path(cwd, argv[0]);
if (execve(temp, argv, environ) == -1)
{
free(temp);
while (*environ && ft_strncmp(*environ, "PATH=", 5) != 0)
environ++;
if (!(*environ))
ft_print_error("command not found:", argv[0]);
path = ft_strsplit(&(*environ)[5], ':');
ft_run_path(path, argv, environ);
}
exit(0);
}
void ft_exec(char **argv)
{
extern char **environ;
struct stat stats;
char *cwd;
cwd = malloc(PATH_MAX);
getcwd(cwd, PATH_MAX);
if (ft_strncmp(argv[0], "\033", 1) == 0)
exit(0);
if (*argv[0] != '/')
ft_exec_path(argv, environ, cwd);
else if (execve(*argv, argv, environ) == -1)
{
lstat(argv[0], &stats);
if (S_ISREG(stats.st_mode) && (!(stats.st_mode & S_IXUSR)))
ft_print_error("permission denied:", argv[0]);
else
ft_print_error("command not found:", argv[0]);
}
}
|
C
|
#include "libft.h"
void *ft_calloc(size_t nmemb, size_t size)
{
void *p;
p = (void *)malloc(nmemb * size);
if (!p)
return (NULL);
ft_bzero(p, nmemb * size);
return (p);
}
|
C
|
/* First version, didnot passed */
struct ListNode* reverseBetween(struct ListNode* head, int m, int n) {
if (!head) {
return head;
}
if (n <= m) {
return head;
}
int delta = n - m;
struct ListNode *fast = head;
struct ListNode *slow = head;
struct ListNode *pre = head;
int i = 0;
while(i < delta) {
fast = fast -> next;
i++;
}
i = 0;
while(i < m && fast->next) {
pre = slow;
fast = fast->next;
slow = slow->next;
i++;
}
while(slow != fast && slow->next) {
slow->next = fast->next;
fast->next = slow;
slow = slow->next;
}
pre->next = slow;
return head;
}
/* Second version, passed */
struct ListNode* reverseBetween(struct ListNode* head, int m, int n) {
if (!head) {
return head;
}
int i;
struct ListNode *dummy = (struct ListNode *)malloc(sizeof(struct ListNode));
dummy->next = head;
struct ListNode *pre = dummy;
for (i = 0; i < m-1; i++) {
pre = pre->next;
}
struct ListNode *cur = pre->next;
struct ListNode *move = cur->next;
for (i = 0; i < n-m; i++) {
cur->next = move->next;
move->next = pre->next;
pre->next = move;
move = cur->next;
}
return dummy->next;
}
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null) return null;
ListNode dummy = new ListNode(0); // create a dummy node to mark the head of this list
dummy.next = head;
ListNode pre = dummy; // make a pointer pre as a marker for the node before reversing
for(int i = 0; i<m-1; i++) pre = pre.next;
ListNode start = pre.next; // a pointer to the beginning of a sub-list that will be reversed
ListNode then = start.next; // a pointer to a node that will be reversed
// 1 - 2 -3 - 4 - 5 ; m=2; n =4 ---> pre = 1, start = 2, then = 3
// dummy-> 1 -> 2 -> 3 -> 4 -> 5
for(int i=0; i<n-m; i++)
{
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}
// first reversing : dummy->1 - 3 - 2 - 4 - 5; pre = 1, start = 2, then = 4
// second reversing: dummy->1 - 4 - 3 - 2 - 5; pre = 1, start = 2, then = 5 (finish)
return dummy.next;
}
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* new_head = new ListNode(0);
new_head -> next = head;
ListNode* pre = new_head;
for (int i = 0; i < m - 1; i++)
pre = pre -> next;
ListNode* cur = pre -> next;
for (int i = 0; i < n - m; i++) {
ListNode* move = cur -> next;
cur -> next = move -> next;
move -> next = pre -> next;
pre -> next = move;
}
return new_head -> next;
}
};
|
C
|
/*
NOMES DOS PARTICIPANTES:
SSC0112 - ORGANIZAO DE COMPUTADORES DIGITAIS I
2 TRABALHO - Simulador de uma CPU MIPS Multiciclo de 32 bits
Weslei Renato de Lima NUSP: 6511258
Wesley Tiozzo NUSP: 8077925
Andreas Munte Foerster NUSP: 7143997
Gabriel Rodrigues do Prado Rossales NUSP: 6608843
*/
/*
Funo auxiliar do procedimento UnidadeControle().
Obtm os sinais de controle a partir de uma microinstruo
*/
void obter_sinais_controle(int microinstrucao, int *sc)
{
int RegDst_bit, RegWrite_bit, IsZero_bit, ALUSrcA_bit, ALUSrcB0_bit, ALUSrcB1_bit,
ALUop0_bit, ALUop1_bit, ALUop2_bit, PCSource0_bit, PCSource1_bit, PCWriteCond_bit,
PCWrite_bit, IorD_bit, MemRead_bit, MemWrite_bit, MemtoReg0_bit, MemtoReg1_bit,
IRWrite_bit, ControleSeq0_bit, ControleSeq1_bit;
//Selecionando e posicionando o bit RegDst:
RegDst_bit = microinstrucao & 0x00002000; //aplicando a mscara
RegDst_bit = RegDst_bit >> 13;
//Selecionando e posicionando o bit RegWrite:
RegWrite_bit = microinstrucao & 0x00004000;
RegWrite_bit = RegWrite_bit >> 13;
//Selecionando e posicionando o bit IsZero:
IsZero_bit = microinstrucao & 0x00000004;
//Selecionando e posicionando o bit ALUSrcA:
ALUSrcA_bit = microinstrucao & 0x00020000;
ALUSrcA_bit = ALUSrcA_bit >> 14;
//Selecionando e posicionando o bit ALUSrcB0:
ALUSrcB0_bit = microinstrucao & 0x00008000;
ALUSrcB0_bit = ALUSrcB0_bit >> 11;
//Selecionando e posicionando o bit ALUSrcB1:
ALUSrcB1_bit = microinstrucao & 0x00010000;
ALUSrcB1_bit = ALUSrcB1_bit >> 11;
//Selecionando e posicionando o bit ALUop0:
ALUop0_bit = microinstrucao & 0x00040000;
ALUop0_bit = ALUop0_bit >> 12;
//Selecionando e posicionando o bit ALUop1:
ALUop1_bit = microinstrucao & 0x00080000;
ALUop1_bit = ALUop1_bit >> 12;
//Selecionando e posicionando o bit ALUop2:
ALUop2_bit = microinstrucao & 0x00100000;
ALUop2_bit = ALUop2_bit >> 12;
//Selecionando e posicionando o bit PCSource0:
PCSource0_bit = microinstrucao & 0x00000008;
PCSource0_bit = PCSource0_bit << 6;
//Selecionando e posicionando o bit PCSource1:
PCSource1_bit = microinstrucao & 0x00000010;
PCSource1_bit = PCSource1_bit << 6;
//Selecionando e posicionando o bit PCWriteCond:
PCWriteCond_bit = microinstrucao & 0x00000020;
PCWriteCond_bit = PCWriteCond_bit << 6;
//Selecionando e posicionando o bit PCWrite:
PCWrite_bit = microinstrucao & 0x00000040;
PCWrite_bit = PCWrite_bit << 6;
//Selecionando e posicionando o bit IorD:
IorD_bit = microinstrucao & 0x00000100;
IorD_bit = IorD_bit << 5;
//Selecionando e posicionando o bit MemRead:
MemRead_bit = microinstrucao & 0x00000400;
MemRead_bit = MemRead_bit << 4;
//Selecionando e posicionando o bit MemWrite:
MemWrite_bit = microinstrucao & 0x00000200;
MemWrite_bit = MemWrite_bit << 9;
//Selecionando e posicionando o bit MemtoReg0:
MemtoReg0_bit = microinstrucao & 0x00000800;
MemtoReg0_bit = MemtoReg0_bit << 5;
//Selecionando e posicionando o bit MemtoReg1:
MemtoReg1_bit = microinstrucao & 0x00001000;
MemtoReg1_bit = MemtoReg1_bit << 5;
//Selecionando e posicionando o bit IRWrite:
IRWrite_bit = microinstrucao & 0x00000080;
IRWrite_bit = IRWrite_bit << 11;
//Selecionando e posicionando o bit ControleSeq0:
ControleSeq0_bit = microinstrucao & 0x00000001;
ControleSeq0_bit = ControleSeq0_bit << 19;
//Selecionando e posicionando o bit ControleSeq1:
ControleSeq1_bit = microinstrucao & 0x00000002;
ControleSeq1_bit = ControleSeq1_bit << 19;
//Agrupando os sinais de controle:
*sc = (RegDst_bit | RegWrite_bit | IsZero_bit | ALUSrcA_bit | ALUSrcB0_bit | ALUSrcB1_bit
| ALUop0_bit | ALUop1_bit | ALUop2_bit | PCSource0_bit | PCSource1_bit | PCWriteCond_bit
| PCWrite_bit | IorD_bit | MemRead_bit | MemWrite_bit | MemtoReg0_bit | MemtoReg1_bit
| IRWrite_bit | ControleSeq0_bit | ControleSeq1_bit);
}
/*
Funo auxiliar.
Retorna e extenso de sinal de 16 bits para 32 bits de um valor passado como argumento.
*/
int sign_extend(int value)
{
int sign_bit = ((value & 0x00008000) >> 15);
if(sign_bit == 0)
return value;
else if(sign_bit == 1)
return (value | 0xffff0000);
}
/*
Determina a operao a ser feita pela ULA com base nos sinais de controle ALUop e no cdigo
de funo da instruo armazenada no IR
*/
char alu_control(int ALUop, int function_code)
{
char ula_op;
switch(ALUop)
{
case 0:
ula_op = 0x02;
break;
case 1:
ula_op = 0x06;
break;
case 2:
//tipo-r:
if(function_code == 0x20)//add
ula_op = 0x02;
else if(function_code == 0x22)//sub
ula_op = 0x06;
else if(function_code == 0x2a)//slt
ula_op = 0x07;
else if(function_code == 0x24)//and
ula_op = 0x00;
else if(function_code == 0x25)//or
ula_op = 0x01;
break;
case 3:
ula_op = 0x00;
break;
case 4:
ula_op = 0x01;
break;
case 5:
ula_op = 0x07;
break;
}
return ula_op;
}
/* UC principal
void UnidadeControle(int IR, int *sc);
args de entrada: int IR
args de saida: int *sc */
void UnidadeControle(int IR, int *sc)
{
int micromemoria[10];
int opcode;
int opcodemask = 0xfc000000;
int microinstrucao;
int i;
static int EndCt1, micro_pc;
typedef struct{
int opcode;
int address;
}TABELA;
TABELA despacho1[5], despacho2[2];
despacho1[0].opcode = 0x00;
despacho1[1].opcode = 0x02;
despacho1[2].opcode = 0x04;
despacho1[3].opcode = 0x23;
despacho1[4].opcode = 0x2b;
despacho1[0].address = 6; //Rformat1
despacho1[1].address = 9; //Jump1
despacho1[2].address = 8; //BEQ1
despacho1[3].address = 2; //Mem1
despacho1[4].address = 2; //Mem1
despacho2[0].opcode = 0x23;
despacho2[1].opcode = 0x2b;
despacho2[0].address = 3; //LW2
despacho2[1].address = 5; //SW2
micromemoria[0] = 0x000084c3; //Busca
micromemoria[1] = 0x00018001;
micromemoria[2] = 0x00030002; //Mem1
micromemoria[3] = 0x00000503; //LW2
micromemoria[4] = 0x00004800;
micromemoria[5] = 0x00000300; //SW2
micromemoria[6] = 0x000a0002; //Rformat1
micromemoria[7] = 0x00006000;
micromemoria[8] = 0x00060028; //BEQ1
micromemoria[9] = 0x00000050; //Jump1
//Processamento inicial do IR:
if(IR == -1)
{
EndCt1 = 0;
micro_pc = 0;
}
//Controle do sequenciamento:
switch(EndCt1)
{
case 0:
//Desvio para a microinstruo de Busca:
microinstrucao = micromemoria[0];
obter_sinais_controle(microinstrucao,sc);
EndCt1 = 3;
break;
case 1:
//Despache usando a tabela 1:
opcode = IR & opcodemask;
opcode = opcode >> 26;
for(i = 0; i < 5; i++)
{
if(opcode == despacho1[i].opcode)
{
micro_pc = despacho1[i].address;
break;
}
}
microinstrucao = micromemoria[micro_pc];
obter_sinais_controle(microinstrucao,sc);
EndCt1 = (((*sc) & 0x00180000) >> 19);
break;
case 2:
//Despache usando a tabela 2:
opcode = IR & opcodemask;
opcode = opcode >> 26;
for(i = 0; i < 2; i++)
{
if(opcode == despacho2[i].opcode)
{
micro_pc = despacho2[i].address;
break;
}
}
microinstrucao = micromemoria[micro_pc];
obter_sinais_controle(microinstrucao,sc);
EndCt1 = (((*sc) & 0x00180000) >> 19);
break;
case 3:
//Desvio para a prxima microinstruo sequencialmente:
micro_pc++;
microinstrucao = micromemoria[micro_pc];
obter_sinais_controle(microinstrucao,sc);
EndCt1 = (((*sc) & 0x00180000) >> 19);
break;
}
}
/* Busca da Instrucao
void Busca_Instrucao(int sc, int PC, int ALUOUT, int IR, int A, int B, int *PCnew, int *IRnew, int *MDRnew);
args de entrada: int sc, int PC, int ALUOUT, int IR, int A, int B
args de saida: int *PCnew, int *IRnew, int *MDRnew */
void Busca_Instrucao(int sc, int PC, int ALUOUT, int IR, int A, int B, int *PCnew, int *IRnew, int *MDRnew)
{
int IorD_bit, IRWrite_bit, MemRead_bit,
MemWrite_bit, ALUSrcA_bit, ALUSrcB, PCSource, ALUop;
int mem_address, mem_data, mem_writedata;
int a, b, result_ula, function_code;
char ula_op, zero, overflow;
int value_aux;
//Selecionando os bits de controle:
IorD_bit = ((sc & 0x00002000) >> 13);
IRWrite_bit = ((sc & 0x00040000) >> 18);
MemRead_bit = ((sc & 0x00004000) >> 14);
MemWrite_bit = ((sc & 0x00008000) >> 15);
ALUSrcA_bit = ((sc & 0x00000008) >> 3);
ALUSrcB = ((sc & 0x00000030) >> 4);
PCSource = ((sc & 0x00000600) >> 9);
ALUop = ((sc & 0x000001c0) >> 6);
//Controlando as unidades funcionais:
if(IorD_bit == 0)
mem_address = PC;
else if(IorD_bit == 1)
mem_address = ALUOUT;
mem_writedata = B;
if(MemRead_bit == 1 && MemWrite_bit == 0)
{
mem_data = memoria[mem_address];
if(IRWrite_bit == 1)
*IRnew = mem_data;
else if(IRWrite_bit == 0)
*IRnew = IR;
*MDRnew = mem_data;
}
else
{
if(MemRead_bit == 0 && MemWrite_bit == 1)
{
memoria[mem_address] = mem_writedata;
*IRnew = IR;
}
}
if(ALUSrcA_bit == 0)
a = PC;
else if(ALUSrcA_bit == 1)
a = A;
switch(ALUSrcB)
{
case 0:
b = B;
break;
case 1:
b = 1;/*pela memria ser um vetor de inteiros,temos nesta simulao
em particular o endereamento a palavra*/
break;
case 2:
value_aux = (IR & 0x0000ffff);//value_aux = IR[15..0]
b = sign_extend(value_aux);
break;
case 3:
value_aux = (IR & 0x0000ffff);//value_aux = IR[15..0]
b = ((sign_extend(value_aux)) << 2);
break;
}
function_code = (IR & 0x0000003f);
ula_op = alu_control(ALUop, function_code);
ula(a, b, ula_op, &result_ula, &zero, &overflow);
switch(PCSource)
{
case 0:
*PCnew = result_ula;
break;
case 1:
*PCnew = ALUOUT;
break;
case 2:
value_aux = (IR & 0x03ffffff); //value_aux = IR[25..0]
*PCnew = ((PC & 0xf000000) | (value_aux << 2)); // PC[31..28] : (IR[25..0] << 2)
break;
}
}
/* Decodifica Instrucao, Busca Registradores e Calcula Endereco para beq
void Decodifica_BuscaRegistrador(int sc, int IR, int PC, int A, int B, int *Anew, int *Bnew, int *ALUOUTnew);
args de entrada: int sc, int IR, int PC, int A, int B,
args de saida: int *Anew, int *Bnew, int *ALUOUTnew */
void Decodifica_BuscaRegistrador(int sc, int IR, int PC, int A, int B, int *Anew, int *Bnew, int *ALUOUTnew)
{
int ALUop, ALUSrcA_bit, ALUSrcB;
int read_reg1, read_reg2, value_aux;
int a, b, result_ula, function_code;
char ula_op, zero, overflow;
//Selecionando os bits de controle:
ALUop = ((sc & 0x000001c0) >> 6);
ALUSrcA_bit = ((sc & 0x00000008) >> 3);
ALUSrcB = ((sc & 0x00000030) >> 4);
//Controlando as unidades funcionais:
read_reg1 = ((IR & 0x03e00000) >> 21);
read_reg2 = ((IR & 0x001f0000) >> 16);
*Anew = reg[read_reg1];
*Bnew = reg[read_reg2];
if(ALUSrcA_bit == 0)
a = PC;
else if(ALUSrcA_bit == 1)
a = A;
switch(ALUSrcB)
{
case 0:
b = B;
break;
case 1:
b = 1;
break;
case 2:
value_aux = (IR & 0x0000ffff);//value_aux = IR[15..0]
b = sign_extend(value_aux);
break;
case 3:
value_aux = (IR & 0x0000ffff);//value_aux = IR[15..0]
b = ((sign_extend(value_aux)) << 2);
break;
}
function_code = (IR & 0x0000003f);
ula_op = alu_control(ALUop, function_code);
ula(a, b, ula_op, &result_ula, &zero, &overflow);
*ALUOUTnew = result_ula;
}
/*Executa TipoR, Calcula endereco para lw/sw e efetiva desvio condicional e incondicional
void Execucao_CalcEnd_Desvio(int sc, int A, int B, int IR, int PC, int ALUOUT, int *ALUOUTnew, int *PCnew);
args de entrada: int sc, int A, int B, int IR, int PC, int ALUOUT
args de saida: int *ALUOUTnew, int *PCnew */
void Execucao_CalcEnd_Desvio(int sc, int A, int B, int IR, int PC, int ALUOUT, int *ALUOUTnew, int *PCnew)
{
int ALUop, ALUSrcA_bit, ALUSrcB, RegWrite_bit, RegDst_bit, MemtoReg, PCSource;
int a, b, result_ula, function_code, value_aux, opcode;
char ula_op, zero, overflow;
//Selecionando os bits de controle:
ALUop = ((sc & 0x000001c0) >> 6);
ALUSrcA_bit = ((sc & 0x00000008) >> 3);
ALUSrcB = ((sc & 0x00000030) >> 4);
RegWrite_bit = ((sc & 0x00000002) >> 1);
RegDst_bit = (sc & 0x00000001);
MemtoReg = ((sc & 0x00030000) >> 16);
PCSource = ((sc & 0x00000600) >> 9);
//Controlando as unidades funcionais:
if(ALUSrcA_bit == 0)
a = PC;
else if(ALUSrcA_bit == 1)
a = A;
switch(ALUSrcB)
{
case 0:
b = B;
break;
case 1:
b = 1;
break;
case 2:
value_aux = (IR & 0x0000ffff);//value_aux = IR[15..0]
b = sign_extend(value_aux);
break;
case 3:
value_aux = (IR & 0x0000ffff);//value_aux = IR[15..0]
b = ((sign_extend(value_aux)) << 2);
break;
}
function_code = (IR & 0x0000003f);
ula_op = alu_control(ALUop, function_code);
ula(a, b, ula_op, &result_ula, &zero, &overflow);
*ALUOUTnew = result_ula;
switch(PCSource)
{
case 0:
*PCnew = result_ula;
break;
case 1:
opcode = ((IR & 0xfc000000) >> 26);
if(opcode == 4 && zero == 1) //condio do desvio ondicional
*PCnew = ALUOUT;
else
{
if(opcode == 4 && zero == 0)
{
a = PC;
b = 1;
ALUop = 0;
ula_op = alu_control(ALUop, function_code);
ula(a, b, ula_op, &result_ula, &zero, &overflow);
*PCnew = result_ula;
}
else
*PCnew = ALUOUT;
}
break;
case 2:
value_aux = (IR & 0x03ffffff); //value_aux = IR[25..0]
*PCnew = ((PC & 0xf000000) | (value_aux << 2)); // PC[31..28] : (IR[25..0] << 2)
break;
}
}
/* Escreve no Bco de Regs resultado TiporR, Le memoria em lw e escreve na memoria em sw
void EscreveTipoR_AcessaMemoria(int sc, int B, int IR, int ALUOUT, int PC, int *MDRnew, int *IRnew);
args de entrada: int sc, int B, int IR, int ALUOUT, int PC
args de saida: int *MDRnew, int *IRnew */
void EscreveTipoR_AcessaMemoria(int sc, int B, int IR, int ALUOUT, int PC, int *MDRnew, int *IRnew)
{
int RegWrite_bit, RegDst_bit, MemtoReg, IorD_bit, IRWrite_bit,
MemWrite_bit, MemRead_bit;
int write_register, write_reg_data;
int mem_address, mem_write_data, mem_data;
//Selecionando os bits de controle:
RegWrite_bit = ((sc & 0x00000002) >> 1);
RegDst_bit = (sc & 0x00000001);
MemtoReg = ((sc & 0x00030000) >> 16);
MemRead_bit = ((sc & 0x00004000) >> 14);
MemWrite_bit = ((sc & 0x00008000) >> 15);
IorD_bit = ((sc & 0x00002000) >> 13);
//Controlando as unidades funcionais:
if(RegDst_bit == 0)
write_register = ((IR & 0x001f0000) >> 16);
else if(RegDst_bit == 1)
write_register = ((IR & 0x0000f800) >> 11);
if(IorD_bit == 0)
mem_address = PC;
else if(IorD_bit == 1)
mem_address = ALUOUT;
mem_write_data = B;
if(MemRead_bit == 1 && MemWrite_bit == 0)
{
mem_data = memoria[mem_address];
if(IRWrite_bit == 1)
*IRnew = mem_data;
else if(IRWrite_bit == 0)
*IRnew = IR;
*MDRnew = mem_data;
}
else
{
if(MemRead_bit == 0 && MemWrite_bit == 1)
{
memoria[mem_address] = mem_write_data;
*IRnew = IR;
}
}
if(MemtoReg == 0)
write_reg_data = ALUOUT;
else if(MemtoReg == 1)
write_reg_data = mem_data;
if(RegWrite_bit == 1)
reg[write_register] = write_reg_data;
}
/* Escreve no Bco de Regs o resultado da leitura da memoria feita por lw
void EscreveRefMem(sort int sc, int IR, int MDR, int ALUOUT);
args de entrada: int sc, int IR, int MDR, int ALUOUT
args de saida: nao ha */
void EscreveRefMem(int sc, int IR, int MDR, int ALUOUT)
{
int RegWrite_bit, RegDst_bit, MemtoReg;
int write_register, write_reg_data;
//Selecionando os bits de controle:
RegWrite_bit = ((sc & 0x00000002) >> 1);
RegDst_bit = (sc & 0x00000001);
MemtoReg = ((sc & 0x00030000) >> 16);
//Controlando as unidades funcionais:
if(RegDst_bit == 0)
write_register = ((IR & 0x001f0000) >> 16);
else if(RegDst_bit == 1)
write_register = ((IR & 0x0000f800) >> 11);
if(MemtoReg == 0)
write_reg_data = ALUOUT;
else if(MemtoReg == 1)
write_reg_data = MDR;
if(RegWrite_bit == 1)
reg[write_register] = write_reg_data;
}
|
C
|
#include <string.h>
#include "kdebug.h"
#include "task.h"
#include "printk.h"
#include "ipc.h"
error_t kdebug_run(const char *cmdline, char *buf, size_t len) {
if (strlen(cmdline) == 0) {
// An empty command. Just ignore it.
return OK;
} else if (strcmp(cmdline, "help") == 0) {
INFO("Kernel debugger commands:");
INFO("");
INFO(" ps - List tasks.");
INFO(" q - Quit the emulator.");
INFO("");
} else if (strcmp(cmdline, "ps") == 0) {
task_dump();
} else if (strcmp(cmdline, "q") == 0) {
#ifdef CONFIG_SEMIHOSTING
arch_semihosting_halt();
#endif
PANIC("halted by the kdebug");
} else if (strcmp(cmdline, "_log") == 0) {
if (!len) {
return ERR_TOO_SMALL;
}
int read_len = klog_read(buf, len - 1);
buf[read_len - 1] = '\0';
} else {
WARN("Invalid debugger command: '%s'.", cmdline);
return ERR_NOT_FOUND;
}
return OK;
}
static uint32_t *get_canary_ptr(void) {
vaddr_t sp = (vaddr_t) __builtin_frame_address(0);
return (uint32_t *) ALIGN_DOWN(sp, STACK_SIZE);
}
/// Writes the stack canary at the borrom of the current kernel stack.
void stack_set_canary(void) {
*get_canary_ptr() = STACK_CANARY_VALUE;
}
/// Checks that the kernel stack canary is still alive.
void stack_check(void) {
if (*get_canary_ptr() != STACK_CANARY_VALUE) {
PANIC("the kernel stack has been exhausted");
}
}
|
C
|
#include<stdio.h>
#include<math.h>
void main()
{
typedef struct point
{
int x,y;
}point;
point p1,p2;
float distance;
printf("/nEnter the coordinate of first pt");
scanf("%d %d",&p1.x,&p1.y);
printf("/nEnter the coordinate of second pt");
scanf("%d %d",&p2.x,&p2.y);
distance=sqrt(pow((p1.x-p2.x),2)+pow((p1.y-p2.y),2));
printf("The distance between p1 &p2 = %f",distance);
}
|
C
|
/*Eric Pickup
03-60-254 Assigment #1
Instructions: Write a program that allows the user to store information about
Facebook posts. For each post, the user wants to store the number of likes and
the number of comments the post received. The name of the post owner (account name),
the size of the post (number of chars), and the date of the posting. The date could
be a string or a number in various formats.
When the program executes it should ask the user the following options:
1. Display the stored posts
2. Display the first post with a given attribute value (e.g. post author = John)
3. Display the current total number of stored posts
4. Store the data of a new post
5. Delete a post by one of the following options (date, author)
6. Delete all the stored posts
7. Sort the post based on an attribute (num likes, num comments, date, or post size)
8. Exit
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
struct Facebook {
int numLikes;
int numComments;
char author[20];
int size;
char date[20];
struct Facebook *nextPost;
};
typedef struct Facebook postInfo;
postInfo *addPost (postInfo *postList);
void printPosts (postInfo *postList);
int searchPost (postInfo *postList, int choice);
void printNumPosts();
postInfo *deletePost (postInfo *postList);
postInfo *deleteAllPosts(postInfo * postList);
postInfo *sortPosts(postInfo *postList);
int doesPostExist (postInfo *postList, int attribute);
int errorCatcher (int type, char attribute[20]);
int numPosts = 0;
int main(void) {
postInfo *postList = NULL;
int input = 0;
while (input != 8) {
printf("\n\n~~~~~MENU~~~~~\n");
printf("1. Display the stored posts\n");
printf("2. Search for post\n");
printf("3. Display the current total number of stored posts\n");
printf("4. Store new post\n");
printf("5. Delete a post (by date, author)\n");
printf("6. Delete all posts\n");
printf("7. Sort posts (by # of likes, # of comments, date or size\n");
printf("8. Exit\n");
printf("\n>>> ");
scanf("%d", &input);
if (input == 1) {
printPosts(postList);
} else if (input == 2) {
printf("Enter the attribute you wish to search with from the following list:\n1. Author\n2. Date\n3. Size\n4. Number of likes\n5. Number of comments\n>>>");
int choice;
scanf("%d",&choice);
searchPost(postList,choice);
} else if (input == 3) {
printNumPosts();
} else if (input == 4) {
postList = addPost(postList);
} else if (input == 5) {
postList = deletePost(postList);
} else if (input == 6) {
postList = deleteAllPosts(postList);
} else if (input == 7) {
postList = sortPosts(postList);
}
}
}
void printPosts (postInfo *postList) {
postInfo *tempPostList = postList;
while (tempPostList != NULL) {
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
printf("Author: %s\n",tempPostList->author);
printf("Date: %s\n",tempPostList->date);
printf("Post size: %d character(s)\n",tempPostList->size);
printf("Number of likes: %d\n",tempPostList->numLikes);
printf("Number of comments: %d\n",tempPostList->numComments);
tempPostList = tempPostList->nextPost;
}
}
postInfo *addPost (postInfo *postList) {
postInfo *newPost = (postInfo *) malloc(sizeof(postInfo));
postInfo *tempPostList = postList;
printf("Enter the author's name:\n>>>");
scanf("%s",newPost->author);
printf("Enter the date (DDMMYYYY):\n>>>");
scanf("%s",newPost->date);
if (errorCatcher(1,newPost->date) == 1) {
return postList;
}
printf("Enter the size of the post (# of chars):\n>>>");
char testSize[20];
scanf("%s",testSize);
if (errorCatcher(2,testSize) == 1) {
return postList;
}
newPost->size = atoi(testSize);
printf("Enter number of likes:\n>>>");
char testLikes[20];
scanf("%s",testLikes);
if (errorCatcher(2,testLikes) == 1) {
return postList;
}
newPost->numLikes = atoi(testLikes);
printf("Enter number of comments:\n>>>");
char testComments[20];
scanf("%s", testComments);
if (errorCatcher(2,testComments) == 1) {
return postList;
}
newPost->numComments = atoi(testComments);
printf("\nPost added successfully.\n");
if (postList == NULL) { //If list was empty
newPost->nextPost = NULL;
numPosts++;
return newPost;
}
while (tempPostList->nextPost != NULL) {
tempPostList = tempPostList->nextPost;
}
newPost->nextPost = NULL;
tempPostList->nextPost = newPost;
numPosts++;
return postList;
}
int searchPost (postInfo *postList, int choice) {
int matchFlag = 0;
postInfo *tempPostList = postList;
if (choice == 1) { //Search by name
printf("Enter the author's name:\n>>>");
char searchName[40];
char tempName[40]; //temp name for converting name to uppercase
scanf("%s",searchName);
while (tempPostList != NULL) {
strcpy(tempName,tempPostList->author);
if (strcmp(strupr(searchName),strupr(tempName)) == 0) { //Converts both names to uppercase to make it non-case sensitive
matchFlag = 1;
break;
}
tempPostList = tempPostList->nextPost;
}
} else if (choice == 2) { //Search by date
printf("Enter the date to search for (DDMMYYYY)\n>>>");
char searchDate[20];
scanf("%s",searchDate);
if (errorCatcher(1,searchDate) == 1) {
return 0;
}
while (tempPostList != NULL) {
if (strcmp(searchDate,tempPostList->date) == 0) {
matchFlag = 1;
break;
}
tempPostList = tempPostList->nextPost;
}
} else if (choice == 3) { //Search by size
printf("Enter the size to search for (# of characters):\n>>>");
char searchSize[10];
scanf("%s",searchSize);
if (errorCatcher(2,searchSize) == 1) {
return 0;
}
while (tempPostList != NULL) {
if (atoi(searchSize) == tempPostList->size) {
matchFlag = 1;
break;
}
tempPostList = tempPostList->nextPost;
}
} else if (choice == 4) { //Search by likes
printf("Enter # of likes to search for:\n>>>");
char searchLikes[10];
scanf("%s",searchLikes);
if (errorCatcher(2,searchLikes) == 1) {
return 0;
}
while (tempPostList != NULL) {
if (atoi(searchLikes) == tempPostList->numLikes) {
matchFlag = 1;
break;
}
tempPostList = tempPostList->nextPost;
}
} else if (choice == 5) { //Search by comments
printf("Enter # of comments to search for:\n>>>");
char searchComments[10];
scanf("%s",searchComments);
if (errorCatcher(2,searchComments) == 1) {
return 0;
}
while (tempPostList != NULL) {
if (atoi(searchComments) == tempPostList->numComments) {
matchFlag = 1;
break;
}
tempPostList = tempPostList->nextPost;
}
}
if (matchFlag == 1) {
printf("\n~~~~~~~~FOUND MATCH!~~~~~~~~~\n");
printf("Author: %s\n",tempPostList->author);
printf("Date: %s\n",tempPostList->date);
printf("Post size: %d characters\n",tempPostList->size);
printf("Number of likes: %d\n",tempPostList->numLikes);
printf("Number of comments: %d\n",tempPostList->numComments);
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
return 1;
} else {
printf("NO MATCH FOUND (make sure input is correct format)!\n");
return 0;
}
}
void printNumPosts() {
printf("There are currently %d post(s) stored.\n",numPosts);
}
postInfo * deletePost(postInfo * postList) {
printf("Enter the attribute you wish to delete by from the following list:\n1. Author\n2. Date\n>>>");
int deleteChoice;
scanf("%d", &deleteChoice);
if (deleteChoice == 1) { //DELETE BY AUTHOR
printf("Enter the name of the post's author:\n>>>");
char deleteName[20];
scanf("%s", deleteName);
postInfo *tempPostList = postList;
if (strcmp(tempPostList->author,deleteName) == 0) { //if it's the first element in list
postList = tempPostList->nextPost;
free(tempPostList);
} else {
if (tempPostList->nextPost == NULL) {
printf("ENTRY NOT FOUND IN LIST. RETURNING TO MENU.\n");
return postList;
}
while (strcmp(tempPostList->nextPost->author,deleteName) != 0) {
tempPostList = tempPostList->nextPost;
if (tempPostList -> nextPost == NULL) {
printf("ENTRY NOT FOUND IN LIST. RETURNING TO MENU.");
return postList;
}
}
if (tempPostList->nextPost->nextPost == NULL) { //Deleting from end of list
free(tempPostList->nextPost);
tempPostList->nextPost = NULL;
} else {
free(tempPostList->nextPost);
tempPostList->nextPost = tempPostList->nextPost->nextPost;
}
}
} else if (deleteChoice == 2) { //DELETE BY DATE
printf("Enter the date of the post you would like to delete:\n>>>");
char deleteDate[20];
scanf("%s", deleteDate);
if (errorCatcher(1,deleteDate) == 1) {
return postList;
}
postInfo *tempPostList = postList;
if (strcmp(tempPostList->date,deleteDate) == 0) { //if it's the first element in list
postList = tempPostList->nextPost;
free(tempPostList);
} else {
if (tempPostList->nextPost == NULL) {
printf("ENTRY NOT FOUND IN LIST. RETURNING TO MENU.\n");
return postList;
}
while (strcmp(tempPostList->nextPost->date,deleteDate) != 0) {
tempPostList = tempPostList->nextPost;
if (tempPostList -> nextPost == NULL) {
printf("ENTRY NOT FOUND IN LIST. RETURNING TO MENU.");
return postList;
}
}
if (tempPostList->nextPost->nextPost == NULL) { //Deleting from end of list
free(tempPostList->nextPost);
tempPostList->nextPost = NULL;
} else {
free(tempPostList->nextPost);
tempPostList->nextPost = tempPostList->nextPost->nextPost;
}
}
}
printf("DELETED SUCCESSFULLY.\n");
numPosts--;
return postList;
}
postInfo *deleteAllPosts(postInfo * postList) {
while (postList != NULL) {
postInfo *tempPostList = postList;
postList = postList->nextPost;
free(tempPostList);
}
printf("ALL POSTS SUCCESSFULLY DELETED.");
numPosts = 0;
return postList;
}
postInfo *sortPosts(postInfo *postList) {
printf("Enter the attribute you wish to sort by from the following list:\n1. Date\n2. # Of Likes\n3. # Of Comments\n4. Post size (# of chars)\n>>>");
int choice;
scanf("%d",&choice);
if (choice == 1) { //SORT BY DATE
for (int i = 0; i < numPosts; i++) {
postInfo *current = postList;
postInfo *next = current->nextPost;
postInfo *previous = NULL;
while (next != NULL) {
int lessThan;
char year1[4], year2[4], month1[2], month2[2], day1[2], day2[2];
for (int i = 0; i < 4; i++) {
year1[i] = current->date[i+4];
year2[i] = next->date[i+4];
}
for (int i = 0; i < 2; i++) {
month1[i] = current->date[i+2];
month2[i] = next->date[i+2];
day1[i] = current->date[i];
day2[i] = next->date[i];
}
if (atoi(year1) > atoi(year2)) {
lessThan = 1;
} else if (atoi(year2) > atoi(year1)) {
lessThan = 0;
} else if (atoi(month1) > atoi(month2)) {
lessThan = 1;
} else if (atoi(month2) > atoi(month1)) {
lessThan = 0;
} else if (atoi(day1) < atoi(day2)) {
lessThan = 1;
} else if (atoi(day2) < atoi(day1)) {
lessThan = 0;
} else {
lessThan = 0;
}
if (lessThan == 0) {
if (current == postList) {
postList = next;
} else {
previous->nextPost = next;
}
current->nextPost = next->nextPost;
next->nextPost = current;
previous = next;
next = current->nextPost;
} else {
previous = current;
current = current->nextPost;
next = current->nextPost;
}
}
}
} else if (choice == 2) { //SORT BY LIKES
for (int i = 0; i < numPosts; i++) {
postInfo *current = postList;
postInfo *next = current->nextPost;
postInfo *previous = NULL;
while (next != NULL) {
if (current->numLikes > next->numLikes) {
if (current == postList) {
postList = next;
} else {
previous->nextPost = next;
}
current->nextPost = next->nextPost;
next->nextPost = current;
previous = next;
next = current->nextPost;
} else {
previous = current;
current = current->nextPost;
next = current->nextPost;
}
}
}
} else if (choice == 3) { //SORT BY COMMENTS
for (int i = 0; i < numPosts; i++) {
postInfo *current = postList;
postInfo *next = current->nextPost;
postInfo *previous = NULL;
while (next != NULL) {
if (current->numComments > next->numComments) {
if (current == postList) {
postList = next;
} else {
previous->nextPost = next;
}
current->nextPost = next->nextPost;
next->nextPost = current;
previous = next;
next = current->nextPost;
}
else {
previous = current;
current = current->nextPost;
next = current->nextPost;
}
}
}
} else if (choice == 4) { //SORT BY SIZE
for (int i = 0; i < numPosts; i++) {
postInfo *current = postList;
postInfo *next = current->nextPost;
postInfo *previous = NULL;
while (next != NULL) {
if (current->size > next->size) {
if (current == postList) {
postList = next;
} else {
previous->nextPost = next;
}
current->nextPost = next->nextPost;
next->nextPost = current;
previous = next;
next = current->nextPost;
} else {
previous = current;
current = current->nextPost;
next = current->nextPost;
}
}
}
}
return postList;
}
int errorCatcher (int type, char attribute[20]) {
//1 = Date 2 = Comments, size, likes
if (type == 1) { //Date
if (strlen(attribute) != 8) { //Check if it's < or > 8 characters
printf("ERROR: INCORRECT FORMAT! FORMAT: DDMMYYYY, SHOULD BE 8 CHARACTERS!");
return 1; //Return error
} else {
for (int i = 0; i < 8; i++) { //Check if date only contains digits (no /'s)
if (isdigit(attribute[i]) == 0) {
printf("ERROR: INVALID INPUT (CORRECT FORMAT: DDMMYYYY), DETECTED ALPHABETICAL LETTERS (NUMBERS ONLY!) RETURNING TO MENU\n");
return 1;
}
}
}
return 0;
} else if (type == 2) {
if (atoi(attribute) == 0) {
printf("ERROR: INVALID INPUT (SHOULD BE INTEGER #), DETECTED CHARACTERS! RETURNING TO MENU\n");
return 1;
}
return 0;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int start, finish;
int lastDigit, firstDigit;
printf ("Enter start value: "); scanf("%d", &start);
printf ("Enter finish value: "); scanf("%d", &finish);
for (start; start<=finish; start++)
{
int temp = start;
lastDigit = temp % 10;
while (temp > 0)
{
firstDigit = temp % 10;
temp = temp/10;
}
if ((firstDigit%2==0) && (lastDigit%2==0))
printf ("%d\n", start);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define T 3
#define LEN 20
int main()
{
int legajo[T];
char nombre[T][LEN];
int i;
int j;
int auxEnt;
char auxString[20];
for(i=0; i<T; i++)
{
printf("Ingrese legajo: ");
scanf("%d", &legajo[i]);
printf("Ingrese nombre: ");
fflush(stdin);
gets(nombre[i]);
}
// BURBUJEO- ORDENAMIENTO
for(i=0; i<T-1; i++)
{
for(j=i+1; j<T; j++)
{
if(legajo[i]>legajo[j])
{
auxEnt = legajo[i];
legajo[i] = legajo[j];
legajo[j] = auxEnt;
strcpy(auxString, nombre[i]);
strcpy(nombre[i], nombre[j]);
strcpy(nombre[j], auxString);
}
}
}
for(i=0; i<T; i++)
{
printf("%d\t%s\n", legajo[i], nombre[i]);
}
return 0;
}
|
C
|
#ifndef GPIO_H_
#define GPIO_H_
typedef enum {
GPIO_HIGH,
GPIO_LOW
}gpio_state_t;
typedef enum {
GPIO_OUTPUT,
GPIO_INPUT
}gpio_dir_t;
/** Initializes a pin with direction and initial state
* @parm pinNo BCM pin number
* @parm dir direction of data
* @parm state initial state of the pin
*
* @return 0 on success
* */
uint8_t gpio_init(int pinNo, gpio_dir_t dir, gpio_state_t state);
/** DeInitializes specific pin
* @parm pinNo BCM pin number
*
* @return 0 on success
* */
uint8_t gpio_deinit(int pinNo);
/** Set a pin high
* @parm pinNo BCM pin number
* */
void gpio_setHigh(int pinNo);
/** Sets a pin low
* @parm pinNo BCM pin number
* */
void gpio_setLow(int pinNo);
#endif /* GPIO_H_ */
|
C
|
#include "../api.h"
#include "../behaviour.c"
#include <stdio.h>
#include <assert.h>
void test_getGoalAction()
{
struct Config config = {100., 50., 5.};
struct Ball ball = {1., 0., 0., 0., 0.};
struct Robot robots[12];
robots[0].x = 50.;
robots[0].y = 0.;
robots[0].t = 0.;
robots[0].team = 1;
robots[0].behaviour = GOAL_KEEPER;
struct Action action = getGoalAction(&config, robots, 12, &ball, 0);
assert(action.x == 47.5 && action.y == 0. && action.t == 0.);
robots[0].team = 2;
action = getGoalAction(&config, robots, 12, &ball, 0);
assert(action.x == -47.5 && action.y == 0. && action.t == 0.);
robots[0].team = 1;
ball.y = 20;
action = getGoalAction(&config, robots, 12, &ball, 0);
assert(action.x >= -47.5 && action.y >= 0. && action.t >= 0.);
ball.y = -20;
struct Action action2 = getGoalAction(&config, robots, 12, &ball, 0);
assert(action2.x == action.x && action2.y == -action.y && action2.t == -action.t);
// printf("%f %f %f\n", action.x, action.y, action.t);
}
int main(int argc, char const *argv[])
{
test_getGoalAction();
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
#define MAXOP 100
#define NUMBER '0'
int getop(char []);
void ungets(char []);
void push(double);
double pop(void);
main(int argc, char *argv[])
{
char s[MAXOP];
double op2;
while (--argc > 0)
{
ungets("");
ungets(*++argv);
switch(getop(s)){
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
case '/':
op2 = pop();
if (op2 != 0.0)
push(pop() / op2);
else
printf("error: zero divisor\n");
break;
default:
printf("error: unknown command %s\n",s);
argc = 1;
break;
}
}
printf("\t%.8g\n",pop());
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gguichar <gguichar@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/08/02 23:18:10 by gguichar #+# #+# */
/* Updated: 2020/02/28 10:40:08 by gguichar ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include <unistd.h>
#include "libft.h"
#include "ft_ssl.h"
#include "hash_md5.h"
#include "hash_sha.h"
static t_cmd g_cmds[] = {
{"md5", "MD5", HASH_CMD, md5_stream_init},
{"sha1", "SHA-1", HASH_CMD, sha1_stream_init},
{"sha224", "SHA-224", HASH_CMD, sha224_stream_init},
{"sha256", "SHA-256", HASH_CMD, sha256_stream_init},
{"sha384", "SHA-384", HASH_CMD, sha384_stream_init},
{"sha512", "SHA-512", HASH_CMD, sha512_stream_init},
{"base64", "Base64", CIPHER_CMD, NULL}
};
static void filter_print_cmd(t_cmd_type filter_type)
{
size_t idx;
idx = 0;
while (idx < (sizeof(g_cmds) / sizeof(g_cmds[0])))
{
if (g_cmds[idx].type == filter_type)
ft_dprintf(STDERR_FILENO, "%s\n", g_cmds[idx].id);
idx++;
}
}
static void usage_help(const char *prefix, const char *cmd)
{
ft_dprintf(STDERR_FILENO, "%s: %s: not a valid command\n", prefix, cmd);
ft_dprintf(STDERR_FILENO, "\nStandard commands\nNone\n");
ft_dprintf(STDERR_FILENO, "\nMessage Digest commands\n");
filter_print_cmd(HASH_CMD);
ft_dprintf(STDERR_FILENO, "\nCipher commands\n");
filter_print_cmd(CIPHER_CMD);
ft_dprintf(STDERR_FILENO, "\n");
}
static t_cmd *find_command(const char *cmd_id)
{
size_t idx;
idx = 0;
while (idx < (sizeof(g_cmds) / sizeof(g_cmds[0])))
{
if (ft_strequ(g_cmds[idx].id, cmd_id))
return (&g_cmds[idx]);
idx++;
}
return (0);
}
int exec_command(const char *prefix, int argc, char **argv)
{
int ret;
t_ssl_opts opts;
t_cmd *cmd;
ret = 1;
ft_memset(&opts, 0, sizeof(t_ssl_opts));
opts.prefix = prefix;
cmd = find_command(argv[0]);
if (cmd == NULL)
usage_help(prefix, argv[0]);
else
{
opts.argc = argc;
opts.argv = argv;
if (cmd->type == HASH_CMD)
ret = parse_hash_options(&opts, cmd);
}
return (ret);
}
int main(int argc, char **argv)
{
const char *prefix;
int ret;
prefix = argv[0];
if (argc >= 2)
ret = exec_command(prefix, argc - 1, argv + 1);
else
{
ft_printf("No argument supplied, falling back to interactive mode.\n");
ret = interactive_mode(prefix);
}
return (ret ? EXIT_FAILURE : EXIT_SUCCESS);
}
|
C
|
#ifndef MOON_INS_REFERENCE_H
#define MOON_INS_REFERENCE_H
#include "runtime/class.h"
#include "runtime/thread.h"
#include "runtime/rcp.h"
#include "runtime/oop.h"
#include "interpreter/bytecode_stream.h"
#include "interpreter/bytecode_interpreter.h"
// 引用
// GETSTATIC 178 0xb2 获取指定类的静态域,并将其值压入栈顶
// PUTSTATIC 179 0xb3 为指定的类的静态域赋值
// GETFIELD 180 0xb4 获取指定类的实例域,并将其值压入栈顶
// PUTFIELD 181 0xb5 为指定的类的实例域赋值
// INVOKEVIRTUAL 182 0xb6 调用实例方法
// INVOKESPECIAL 183 0xb7 调用超类构造方法,实例初始化方法,私有方法
// INVOKESTATIC 184 0xb8 调用静态方法
// INVOKEINTERFACE 185 0xb9 调用接口方法
// INVOKEDYNAMIC 186 0xba 调用动态链接方法
// NEW 187 0xbb 创建一个对象,并将其引用值压入栈顶
// NEWARRAY 188 0xbc 创建一个指定原始类型(如int、float、char„„)的数组,并将其引用值压入栈顶
// ANEWARRAY 189 0xbd 创建一个引用型(如类,接口,数组)的数组,并将其引用值压入栈顶
// ARRAYLENGTH 190 0xbe 获得数组的长度值并压入栈顶
// ATHROW 191 0xbf 将栈顶的异常抛出
// CHECKCAST 192 0xc0 检验类型转换,检验未通过将抛出ClassCastException
// INSTANCEOF 193 0xc1 检验对象是否是指定的类的实例,如果是将1压入栈顶,否则将0压入栈顶
// MONITORENTER 194 0xc2 获得对象的monitor,用于同步方法或同步块
// MONITOREXIT 195 0xc3 释放对象的monitor,用于同步方法或同步块
void insm_178(Frame *frame, ByteCodeStream *stream)
{
// GETSTATIC
int16_t filedRefIndex = nextInt16(stream);
IKlass *clazz = frame->method->clazz;
MemberRef *fieldRef = (MemberRef *)getRCPInfo(clazz->constantPool, filedRefIndex)->data;
Field *field = resolveFieldReference(fieldRef);
if (!isClassInit(field->clazz))
{
initClass(field->clazz);
}
char *descriptor = field->descriptor;
uint32_t index = field->slotIndex;
Slots *slots = getStaticVars(field->clazz);
char flag = descriptor[0];
if (flag == 'Z' || flag == 'B' || flag == 'C' || flag == 'S' || flag == 'I')
{
pushInt(frame->operandStack, getSlotInt(slots, index));
}
else if (flag == 'F')
{
pushFloat(frame->operandStack, getSlotFloat(slots, index));
}
else if (flag == 'J')
{
pushLong(frame->operandStack, getSlotLong(slots, index));
}
else if (flag == 'D')
{
pushDouble(frame->operandStack, getSlotDouble(slots, index));
}
else if (flag == 'L')
{
pushRef(frame->operandStack, getSlotRef(slots, index));
}
else
{
}
UPDATE_PC_AND_CONTINUE
}
void insm_180(Frame *frame, ByteCodeStream *stream)
{
// GETFIELD
int16_t filedRefIndex = nextInt16(stream);
IKlass *clazz = frame->method->clazz;
MemberRef *fieldRef = (MemberRef *)getRCPInfo(clazz->constantPool, filedRefIndex)->data;
Field *field = resolveFieldReference(fieldRef);
if (!isClassInit(field->clazz))
{
initClass(field->clazz);
}
char *descriptor = field->descriptor;
uint32_t index = field->slotIndex;
InstanceOOP *oop = (InstanceOOP *)popRef(frame->operandStack);
Slots slots = getInstanceVars(oop);
// TODO
UPDATE_PC_AND_CONTINUE
}
void insm_183(Frame *frame, ByteCodeStream *stream)
{
// INVOKESPECIAL
int16_t methodRefIndex = nextInt16(stream);
IKlass *clazz = frame->method->clazz;
RCP *rcp = clazz->constantPool;
MemberRef *methodRef = (MemberRef *)getRCPInfo(clazz->constantPool, methodRefIndex)->data;
Method *method = resolveMethodReference(methodRef);
if (method->name == "<init>" && clazz != method->clazz)
{
// java.lang.NoSuchMethodError
}
if (isMethodStatic(method))
{
// java.lang.IncompatibleClassChangeError
}
void *ref = getRefFromTop(frame->operandStack, method->argCount - 1);
if (ref == NULL)
{
// java.lang.NullPointerException
}
if (isMethodProtected(method))
{
// java.lang.IllegalAccessError
}
Method *methodToBeInvoked = lookupMethodInClass(clazz, method);
JThread *thread = frame->thread;
Frame *newFrame = thread->createFrame(thread, methodToBeInvoked);
pushFrame(thread, newFrame);
uint32_t argSlotCount = method->argCount;
if (argSlotCount > 0)
{
for (int i = argSlotCount - 1; i >= 0; i--)
{
union Slot *slot = popVar(newFrame->operandStack);
setVar(newFrame->localVars, (uint32_t)i, slot);
}
}
}
void insm_187(Frame *frame, ByteCodeStream *stream)
{
// NEW
int16_t index = nextInt16(stream);
IKlass *clazz = frame->method->clazz;
char *className = ((ClassRef *)getRCPInfo(clazz->constantPool, index)->data)->classname;
IKlass *refClass = resolveClassReference(clazz, className);
if (!isClassInit(refClass))
{
initClass(refClass);
}
InstanceOOP *oop = newObject(refClass);
pushRef(frame->operandStack, oop);
UPDATE_PC_AND_CONTINUE
}
void insm_190(Frame *frame, ByteCodeStream *stream)
{
// ARRAYLENGTH
ArrayOOP *arrayRef = (ArrayOOP *)popRef(frame->operandStack);
if (arrayRef == NULL)
{
// java.lang.NullPointerException
}
pushInt(frame->operandStack, arrayRef->length);
UPDATE_PC_AND_CONTINUE
}
void insm_191(Frame *frame, ByteCodeStream *stream)
{
// ATHROW
void *exceptionRef = popRef(frame->operandStack);
if (exceptionRef == NULL)
{
// java.lang.NullPointerException
}
// TODO
UPDATE_PC_AND_CONTINUE
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
int *iPtr;
char *cPtr;
printf("sizeof iPtr[%p]: %d\n",iPtr,sizeof(iPtr));
printf("sizeof char[%p]: %d\n",cPtr,sizeof(cPtr));
return 0;
}
|
C
|
/*
** my_realloc.c for RT in /partage/code/c/RT/working_dir/part_parse
**
** Made by mathias lang
** Login <lang_m@epitech.net>
**
** Started on Mon Apr 4 16:39:47 2011 mathias lang
** Last update Fri Jun 3 19:47:49 2011 Mathias Lang
*/
#include <strings.h>
#include <stddef.h>
#include "rt.h"
void *my_realloc(char *ptr, int size)
{
char *new;
int i;
i = 0;
new = cx_malloc(size);
bzero(new, size);
if (ptr != NULL)
while (i < size)
{
new[i] = ptr[i];
i++;
}
return (new);
}
|
C
|
#include<stdlib.h>
void foo(int* p) {
}
int main() {
int *i, *j, *k;
i = (int*) malloc(sizeof(int)*5); // escapes
j = (int*) malloc(sizeof(int)*5); // does not escape
k = i;
foo(k);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
const int MAX_CONTRIB = 10;
int Global_sum(int my_contrib, int my_rank, int p, MPI_Comm comm);
int main(int argc, char* argv[]) {
int p, my_rank;
MPI_Comm comm;
int my_contrib;
int sum;
MPI_Init(&argc, &argv);
comm = MPI_COMM_WORLD;
MPI_Comm_size(comm, &p);
MPI_Comm_rank(comm, &my_rank);
srandom(my_rank+1);
my_contrib = random() % MAX_CONTRIB;
printf("Proc %d > my_contrib = %d\n", my_rank, my_contrib);
sum = Global_sum(my_contrib, my_rank, p, comm);
if (my_rank == 0)
printf("Proc %d > global sum = %d\n", my_rank, sum);
MPI_Finalize();
return 0;
}
int Global_sum(int my_contrib, int my_rank, int p, MPI_Comm comm) {
int sum = my_contrib;
int divisor = 2;
int core_diff = 1;
int partner;
int received_value;
while (divisor <= p) {
if(my_rank % divisor == 0){
partner = my_rank + core_diff;
MPI_Recv(&received_value, 1, MPI_INT, partner, 0, comm, MPI_STATUS_IGNORE);
sum += received_value;
}
else if ((my_rank % (divisor/2)) == 0){
partner = my_rank - core_diff;
MPI_Send(&sum, 1, MPI_INT, partner, 0, comm);
}
divisor *= 2;
core_diff *= 2;
}
MPI_Barrier(MPI_COMM_WORLD);
return sum;
}
|
C
|
#include<stdio.h>
int main()
{
int i,n,c;
int a=1,b=0;
printf("enter the numbers:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
c=a+b;
a=b;
b=c;
printf("%d",c);
}
return 0;
}
|
C
|
/*
* File: FunctionElement.h
* Author: alex
*
* Created on 27 June 2014, 18:45
*/
#ifndef FUNCTIONELEMENT_H
#define FUNCTIONELEMENT_H
#ifdef __cplusplus
extern "C" {
#endif
#include "ListOfString.h"
#include <stdio.h>
struct functionElement {
char * NameOfFunction;
ListOfString * LOCs;
struct functionElement *next;
};
typedef struct functionElement FunctionElement;
void freeListOfFunctionElement(FunctionElement ** head);
FunctionElement * searchAnElement(FunctionElement * head, char * name);
void addNewFunction(FunctionElement ** head, char * name);
int addNewLOC(FunctionElement ** head, char * name, char * LOC);
void addNewFunctionElement(FunctionElement ** head, FunctionElement * newElement);
void printListOfFunctions(FILE * fout, FunctionElement * head);
void printAFunctionElement(FILE * fout, FunctionElement * head);
void fixCloseBrackets(ListOfString ** head);
void removeLOCsFromAListOfStringAfterCall(ListOfString ** head, char * nextFunction);
void removeLOCsAfterCallForAList(FunctionElement ** head,
ListOfString * reverseCallGraph);
FunctionElement * readFunctionElemenentListFromFile(char * inputFile, ListOfString * reverseCallGraph);
#ifdef __cplusplus
}
#endif
#endif /* FUNCTIONELEMENT_H */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.