language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include "dataout.h"
uint8_t put_in_string(int16_t number, char letter, uint8_t place)//place is 4 digit spotplus 2 for something else, count from right
{
//
//'place' is the target place for the next character
//
//
char temps[5] = "\0\0\0\0\0";//temporary spot for the number to add to the big string
if (number <= 32767 || number<= -32767)
{
//ultoa
itoa(number, temps, 10); // integer number --> string temps base 10
}
else
{
strcpy(temps,"over");//
}
uint8_t datalen = strlen(temps);//actual legnth of ADC data
if (letter != '\0')//dont put in the letter and the colon if '\0'
{
serialout[place] = letter;
place++;
serialout[place] = ':';
}
else
{
place--;
}
for (uint8_t i=0; i<datalen; i++)
{
place++;
serialout[place] = temps[i];
}
place++;
serialout[place] = ',';
return (place+1);
}
void uart_putch(uint8_t c)
{
//if(c == '\n')
// uart_putc('\r');
/* wait until transmit buffer is empty */
while(!(UCSRA & (1 << UDRE)));
/* send next byte */
UDR = c;
}
void uart_putst(const char* s)
{
while(*s)
uart_putch(*s++);
}
void uart_put16dec(uint16_t d)
{
uint16_t num = 10000;
uint8_t started = 0;
while(num > 0)
{
uint8_t b = d / num;
if(b > 0 || started || num == 1)
{
uart_putch('0' + b);
started = 1;
}
d -= b * num;
num /= 10;
}
}
uint8_t spitout(uint8_t place)
{
serialout[place-1] = '\n';
//uint8_t datalen = strlen(serialout);
//serialout[datalen] = '\n';//replace last char (,) with return
uart_putst(serialout);
for (uint8_t i= 0; i<LINESIZE ;i++)//blank serialout
{
serialout[i] = '\0';
}
return 0;//reset place
}
|
C
|
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <emscripten.h>
// number of circles to create and animate
#define NUM_CIRCLES 200
struct Circle {
int x; // y coord
int y; // x coord
int r; // radius
int cr; // color red
int cg; // color green
int cb; // color blue
};
// circle animation data struct
struct CircleAnimationData {
int x; // y coord
int y; // x coord
int r; // radius
int xv; // x axis velocity
int yv; // y axis velocity
int xd; // x axis direction (1 = fwd, 0 = bkwd)
int yd; // y axis direction (1 = fwd, 0 = bkwd)
};
struct Circle circles[NUM_CIRCLES];
struct CircleAnimationData animationData[NUM_CIRCLES];
int getRand(max){
return (rand() % max);
}
// Init circle data and start render - JS
int main() {
srand(time(NULL));
for(int i = 0; i < NUM_CIRCLES; i++){
int radius = getRand(50);
int x = getRand(1000) + radius;
int y = getRand(1000) + radius;
animationData[i].x = x;
animationData[i].y = y;
animationData[i].r = radius;
animationData[i].xv = getRand(10);
animationData[i].yv = getRand(10);
animationData[i].xd = 1;
animationData[i].yd = 1;
circles[i].x = x;
circles[i].y = y;
circles[i].r = radius;
circles[i].cr = getRand(255);
circles[i].cg = getRand(255);
circles[i].cb = getRand(255);
}
// start js rendering
EM_ASM({render($0, $1);}, NUM_CIRCLES * 6, 6);
};
// Return circles to JS
struct Circle * getCircles(int canvasWidth, int canvasHeight) {
for(int i = 0; i < NUM_CIRCLES; i++){
if((animationData[i].x + animationData[i].r) >= canvasWidth) animationData[i].xd = 0;
if((animationData[i].x - animationData[i].r) <= 0) animationData[i].xd = 1;
if((animationData[i].y - animationData[i].r) <= 0) animationData[i].yd = 1;
if((animationData[i].y + animationData[i].r) >= canvasHeight) animationData[i].yd = 0;
if(animationData[i].xd == 1){
animationData[i].x += animationData[i].xv;
} else {
animationData[i].x -= animationData[i].xv;
}
if(animationData[i].yd == 1){
animationData[i].y += animationData[i].yv;
} else {
animationData[i].y -= animationData[i].yv;
}
circles[i].x = animationData[i].x;
circles[i].y = animationData[i].y;
}
return circles;
};
|
C
|
#include <stdio.h>
int main(void)
{
int n, k; // n : ũ, k : ݺ
int arr[101] = { 0 };
int s, e, u;
int sum = 0;
scanf("%d %d", &n, &k);
for (int i = 1; i <= k; i++)
{
scanf("%d %d %d", &s, &e, &u);
arr[s] = arr[s] + u;
arr[e + 1] = arr[e + 1] - u;
}
for (int i = 1; i <= n; i++)
printf("%d ", arr[i]);
printf("\n");
for (int i = 1; i <= n; i++)
{
sum = 0;
for (int j = 1; j <= i; j++)
sum += arr[j];
printf("%d ", sum);
}
printf("\n");
return 0;
}
|
C
|
/**
* @file bitwise_calculator.c
* @author 260756 ([email protected])
* @brief Functions to perform Bitwise AND, Bitwise OR, Bitwise XOR , Bitwise NOT, Left shift and Right Shift on decimal integers
* @version 0.1
* @date 2021-04-12
*
* @copyright Copyright (c) 2021
*
*/
#include "stdlib.h"
#include<stdio.h>
#include "header.h"
void red_color () {
printf("\033[1;31m");
}
void yellow_color(){
printf("\033[1;33m");
}
void reset_color () {
printf("\033[0m");
}
// function for bitwise AND
void bitwise_and(int a, int b)
{
yellow_color();
printf( "a & b = %d\n",(a & b));
}
// function for bitwise OR
void bitwise_or(int a, int b)
{
yellow_color();
printf( "a | b = %d\n",(a | b));
}
// function for bitwise XOR
void bitwise_xor(int a, int b)
{
yellow_color();
printf( "a ^ b = %d\n",(a ^ b));
}
// function for bitwise NOT
void bitwise_not(int a, int b)
{
yellow_color();
printf( "~a = %d\n",(~a));
printf( "~b = %d\n",(~b));
}
// function for bitwise Left Shift
void bitwise_leftshift(int a, int b)
{
yellow_color();
printf( "a << b = %d\n",(a << b));
}
// function for bitwise Right Shift
void bitwise_rightshift(int a, int b)
{
yellow_color();
printf( "a << b = %d\n",(a << b));
}
/*
* Main Function
*/
error_t bitwise_operations()
{
int a, b, option;
char choice;
do {
red_color();
printf( "\nEnter the value of a and b:\n");
scanf("%d%d",&a,&b);
printf( "\nBITWISE OPERATION:\n");
printf( "1.AND\n");
printf( "2.OR\n");
printf( "3.XOR\n");
printf( "4.NOT\n");
printf( "5.Left Shift\n");
printf( "6.Right Shift\n");
printf( "Select your option:\n");
scanf("%d",&option);
switch (option) {
case 1:
bitwise_and(a, b);
break;
case 2:
bitwise_or(a, b);
break;
case 3:
bitwise_xor(a, b);
break;
case 4:
bitwise_not(a, b);
break;
case 5:
bitwise_leftshift(a, b);
break;
case 6:
bitwise_rightshift(a, b);
break;
defualt:
printf( "Invalid option:\n");
exit(0);
}
printf( "\nDo you want to continue?(y/n)");
scanf("%c",&choice);
} while (choice == 'Y' || choice == 'y');
return SUCCESS;
}
|
C
|
#include<stdio.h>
#include<math.h>
int main(){
int x(int y){ return (1+pow(-1,y))/2;}
for(int i=0;i<12;i++){
printf("%i\n",x(i));
}
return 0;}
|
C
|
#include<stdio.h>
int main()
{
int t;
scanf("%d",&t);
while (t--){
int a[50];
int n,i,j,d=0;
scanf("%d",&n);
for (i=0;i<n;i++)
scanf("%d",&a[i]);
for (i=0;i<n;i++){
int x=0;
for (j=i;j>=0;j--)
if(a[i]<a[j]) x++;
if (x==0) d++;
}
printf("%d\n",d);
}
}
|
C
|
#include "common.h"
int main(int argc, char **argv)
{
double elapsedTime;
int pid;
int psize;
unsigned long long int n;
unsigned long long int low_value, high_value;
unsigned long long int size, proc0_size;
char *marked;
unsigned long long int i, index, first;
unsigned long long int prime;
unsigned long long int count, global_count;
unsigned long long int local_first, local_prime, local_size;
char *local_marked;
/**
* Initialize MPI
*/
MPI_Init(&argc, &argv);
MPI_Barrier(MPI_COMM_WORLD);
elapsedTime = -MPI_Wtime();
MPI_Comm_rank(MPI_COMM_WORLD, &pid);
MPI_Comm_size(MPI_COMM_WORLD, &psize);
if (argc != 2)
{
if (pid == 0)
printf("Command line syntax error.\n");
MPI_Finalize();
exit(1);
}
/**
* Parameters Initialization
*/
n = atoll(argv[1]);
low_value = 2 + BLOCK_LOW(pid, psize, n-1);
high_value = 2 + BLOCK_HIGH(pid, psize, n-1);
// size = BLOCK_SIZE(pid, psize, n-1);
low_value = low_value + (low_value + 1) % 2;
high_value = high_value - (high_value + 1) % 2;
size = (high_value - low_value) / 2 + 1;
local_size = (int)sqrt((double)(n)) - 1;
/**
* process 0 must holds all primes used
*/
proc0_size = (n/2 - 1) / psize;
if ((2 + proc0_size) < (int) sqrt((double) n/2))
{
if (pid == 0)
printf("Too many processes.\n");
MPI_Finalize();
exit(1);
}
/**
* Allocation
*/
marked = (char*) malloc(size);
local_marked = (char *) malloc (local_size);
if (marked == NULL || local_marked == NULL)
{
printf("PID: %d - Cannot allocate enough memory.\n", pid);
MPI_Finalize();
exit(1);
}
/**
* Core Function
*/
local_prime = 2;
for (i = 0; i < local_size; i++)
local_marked[i] = 0;
index = 0;
do
{
local_first = local_prime * local_prime - 2;
for (i = local_first; i < local_size; i += local_prime)
local_marked[i] = 1;
while (local_marked[++index] == 1);
local_prime = 2 + index;
} while (local_prime * local_prime <= n);
for (i = 0; i < size; i++)
marked[i] = 0;
index = 0;
prime = 3;
do
{
if (prime * prime > low_value)
first = (prime * prime - low_value) / 2;
else
{
if ((low_value % prime) == 0)
first = 0;
else
first = (prime - (low_value % prime) + low_value / prime % 2 * prime) / 2;
}
for (i = first; i < size; i += prime)
marked[i] = 1;
while(local_marked[++index] == 1);
prime = index + 2;
} while (prime * prime <= n);
count = 0;
for (i = 0; i < size; i++)
if (marked[i] == 0)
count++;
if (pid == 0)
count++; // 2
if (psize > 1)
MPI_Reduce(&count, &global_count, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
elapsedTime += MPI_Wtime();
/**
* Print the results
*/
if (pid == 0)
printf("The total number of primes: %lld, time: %.6lf s in %d processes.\n", global_count, elapsedTime, psize);
MPI_Finalize();
return 0;
}
|
C
|
#include<stdio.h>
int main(){
int a,b,c,x,n,i;
printf("enter starting limit");
scanf("%d",&a);
printf("enter end limit");
scanf("%d",&b);
n=a;
printf("Prime numbers: ");
while(n<=b)
{
c=0;i=1;
while(i<=n)
{
x=n%i;
if(x==0)
c=c+1;
i++;
}
if(c<=2)
if(n!=0&&n!=1)
printf("%d ",n);
n++;
}
}
|
C
|
/*
* block and recursion algorithm for rotate a array.
*
* ./a.out <sequence> <step>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void shift(char *, int, int, int);
static void swap(char *, char *, int);
int main(int argc, char *argv[])
{
if (argc != 3) {
fputs("./a.out <sequence> <step>\n", stderr);
exit(0);
}
int h = strlen(argv[1]);
int b = atoi(argv[2]) % h;
printf("%s\n", argv[1]);
shift(argv[1], 0, h - 1, b - 1);
printf("%s\n", argv[1]);
return(0);
}
/*
* l: lower bound
* h: higher bound
* b: middle bound
*/
static void shift(char *seq, int l, int h, int b)
{
int l1, l2;
if (!(l >= 0 && b >= l && b <= h))
return;
l1 = b - l + 1;
l2 = h - b;
if (l1 < l2) {
swap(seq + l, seq + h - l1 + 1, l1);
shift(seq, l, h - l1, b);
} else if (l1 > l2) {
swap(seq + l, seq + b + 1, l2);
shift(seq, l + l2, h, b);
} else {
swap(seq + l, seq + b + 1, l1);
}
}
static void swap(char *seq1, char *seq2, int len)
{
char tmp;
while (len-- > 0) {
tmp = *(seq1 + len);
*(seq1 + len) = *(seq2 + len);
*(seq2 + len) = tmp;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* lemin.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bkonjuha <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/29 23:23:43 by bkonjuha #+# #+# */
/* Updated: 2020/09/03 14:40:59 by bkonjuha ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/lemin.h"
static char **get_rooms(t_farm *farm)
{
char *line;
char **strstr;
int i;
i = 0;
line = ft_read_file(STD_IN);
validate_lines(line);
farm->file = line;
strstr = ft_strsplit(line, '\n');
while (is_command_or_comment(strstr[i]))
{
ft_strdel(&strstr[i]);
i++;
}
return (validate_instructions(strstr + i));
}
static void reset_unused_edges(t_farm *farm)
{
int i;
i = -1;
while (farm->rooms[++i])
farm->rooms[i]->visited = 0;
}
static void pathfinder(t_farm *farm)
{
int i;
i = -1;
bfs(farm->source, farm->sink);
reset_unused_edges(farm);
reconstruct_path(farm->sink, farm->source, farm);
reset_unused_edges(farm);
while (bfs(farm->source, farm->sink))
{
reset_unused_edges(farm);
reconstruct_path(farm->sink, farm->source, farm);
reset_unused_edges(farm);
}
if (!farm->paths->set)
ft_errno("No paths found", NULL);
}
static t_option *parse(int ac, char **av)
{
int i;
t_option *op;
i = 0;
op = init_option();
while (++i < ac)
{
if (ft_strequ(av[i], "-i") || ft_strequ(av[i], "--info"))
op->info = 1;
else if (ft_strequ(av[i], "-p") || ft_strequ(av[i], "--paths"))
op->paths = 1;
else if (ft_strequ(av[i], "-e") || ft_strequ(av[i], "--error"))
op->error = 1;
else if (!ft_strequ(av[i], "-i") && !ft_strequ(av[i], "--info")
&& !ft_strequ(av[i], "-e") && !ft_strequ(av[i], "--error")
&& !ft_strequ(av[i], "-p") && !ft_strequ(av[i], "--paths"))
op->help = 1;
}
return (op);
}
int main(int ac, char **av)
{
char **file;
t_farm farm;
farm.op = parse(ac, av);
if (farm.op->help)
{
ft_putstr("Usage:\n./lem-in [-e --error] [-i --info] ");
ft_putendl("[-p --paths] < maps/demo_map");
return (0);
}
else
{
ft_errno(NULL, farm.op);
file = get_rooms(&farm);
if (!ft_isint(farm.ants = ft_atol(file[0])))
ft_errno("Number of ants is out of bounds", NULL);
connect_rooms(file, &farm, read_rooms(file, &farm));
farm.paths = init_comb();
farm.paths->set = NULL;
pathfinder(&farm);
combinations(&farm);
//ft_putendl(farm.file);
send_ants(&farm);
}
return (0);
}
|
C
|
/*
* patchmem(1)
* - Rewritten to use mmap(2) instead of read(2), lseek(2), write(2)
* - syncs PAGE_SIZE at a time
* - Disable your kernel's STRICT_DEVMEM setting.
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/mman.h>
#define PAGE_SIZE getpagesize()
#define ROUND_PAGE(x) ((void *)(((unsigned long)(x)) & ~((unsigned long)(PAGE_SIZE - 1))))
unsigned long value = 0;
unsigned int flataddr, mapaddr, offset;
int rflag = 0, wflag = 0;
int main(int argc, char **argv)
{
int opt;
int fd;
char *mem;
while ((opt = getopt(argc, argv, "f:rw:")) != -1) switch (opt) {
case 'f':
flataddr = strtoul(optarg, NULL, 0);
break;
case 'w':
value = strtoul(optarg, NULL, 0);
wflag++;
break;
case 'r':
rflag++;
break;
}
if (!wflag && !rflag) {
fprintf(stderr, "usage: patchmem [-f flataddr] [-r] (read word)\n");
fprintf(stderr, "usage: patchmem [-f flataddr] [-w <value>]\n");
exit(0);
}
if ((fd = open("/dev/mem", O_RDWR)) < 0) {
perror("open(2)");
exit(1);
}
/*
* Reasons mmap(2) returns EINVAL:
* The first reason is because offset is not on a page boundary, and is what is happening.
* EINVAL We don't like addr, length, or offset (e.g., they are too large, or not aligned on a page boundary).
* EINVAL (since Linux 2.6.12) length was 0.
* EINVAL flags contained neither MAP_PRIVATE or MAP_SHARED, or contained both of these values.
*/
mapaddr = (long)ROUND_PAGE(flataddr);
offset = flataddr - mapaddr;
printf("\n");
printf(" Opened /dev/mem for read and write. Fd=%d\n", fd);
printf(" Calling mmap(2) to map 0x1000 bytes (%d pages) from offset to page: %#x.\n",0x1000/4096,
mapaddr);
printf(" Flataddr = %p, mapaddr = %p, offset = %d (%#x)\n", (void *)flataddr, (void *)mapaddr, offset, offset);
if ((mem =
mmap(NULL,
0x1000,
PROT_READ|PROT_WRITE,
MAP_SHARED,
fd, (off_t)mapaddr)) == MAP_FAILED) {
perror("mmap(2)");
exit(1);
}
printf(" mmap(2) gave address range %p->%p\n", mem, mem+0x1000);
printf(" Index to change in mem is %d (address %p).\n", offset, &mem[offset]);
printf("\n");
(void)mprotect(mem, 0x1000, PROT_READ|PROT_WRITE);
perror("mprotect(2)");
if (rflag) {
printf("%#lx\n", *(unsigned long *)&mem[offset]);
munmap(mem, 0x1000);
close(fd);
exit(0);
}
if (wflag) {
printf("%#lx->", *(unsigned long *)&mem[offset]);
*(unsigned int *)&mem[offset] = value;
fflush(stdout);
printf("%#lx\n", *(unsigned long *)&mem[offset]);
msync(mem, 0x1000, MS_SYNC | MS_INVALIDATE);
perror("msync(2)");
fsync(fd);
munmap(mem, 0x1000);
fsync(fd);
perror("fsync(2)");
exit(0);
}
/*NOTREACHED*/
perror("NOTREACHED reached");
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<ncurses.h>
#include<pthread.h>
#include<time.h>
#include"pbm.h"
#define MORTA 0
#define VIVA 1
#define SUPERLOT 3
#define SOLIDAO 2
#define FPS 3.0
#define CHAR 10
#define MAXTHREADS 5
#define MAX_COL 600
#define MAX_LIN 50
/**
* Estrutura de argumentos de uma thread
*/
typedef struct thread_data_structure {
int id[3]; /** id único */
} data;
/**
* Estrutura da lista de células a serem tratadas
*/
typedef struct ponto {
int i;
int j;
struct ponto *prox;
} Ponto;
/**Variaveis globais (compartilhadas pelas threads)*/
int **matriz; /** matriz com o tabuleiro da posição/geração atual */
int **matriz_prox; /** matriz auxiliar para criar um tabuleiro de próxima geração */
int nlin,ncol; /** número de linhas e colunas do tabuleiro */
int iter=0; /** número de iterações do jogo da vida */
float fps = FPS; /** número de frames por segundo(em tese)*/
float fps_real=0; /** número de frames por segundo real */
Ponto *lista_cel=NULL; /** lista de células a serem tratadas */
pthread_mutex_t mutex_lista; /** mutex da lista de células */
int num_cel=0; /** número de células livres */
pthread_mutex_t mutex_num; /** mutex do número de células livres */
pthread_cond_t cond_num; /** cond do número de células livres */
int sair=0; /** mostra se é pra sair do programa ou não */
/**
* Função que le os parametros iniciais e os atribui à variáveis
* @param argc numero de argumento passados na entrada
* @param argv vetor com os valores dos argumentos passados
*/
void config(int argc, char *argv[]);
/**
* Verifica se uma célula da matriz atual estará viva no próximo turno
*
* @param lin Linha da célula
* @param col Coluna da célula
*/
int valida_celula(int lin, int col);
/**
* Função que conta as células adjacentes a uma célula de posição tabuleiro[linha][coluna].
* A função também trata os casos especiais (se a célula estudada estiver numa borda, por ex.).
*
* @param lin Linha da célula
* @param col Coluna da célula
*/
int conta_celula(int lin, int col);
/**
* Função que a thread vai executar ao ser criada:
* A função verifica se a celula na qual a thread se encontra trabalhando
* deve sobreviver à próxima geração (ser escrita no próximo tabuleiro);
* Nesse caso, ela escreve na posição correspondente do pŕoximo tabuleiro
* o estado da célula (VIVA ou MORTA)
*
* @param threadarg Ponteiro void para a struct de parâmetros para a thread
*/
void *exec_thread(void *threadarg);
/**
* Imprime o tabuleiro atual
*/
void imprime();
/**
* Imprime as somas do tabuleiro atual (debug)
*/
void imprime_soma();
/**
* Processa uma certa área da matriz.
* Divide a imagem recursivamente em quatro partes
*
* @param lin_0 Linha inicial
* @param lin_1 Linha final
* @param col_0 Coluna inicial
* @param col_1 Coluna final
* @param threads Matriz de threads
* @param thread_data Matriz de dados das threads
*/
void processa_area(int lin_0, int lin_1, int col_0, int col_1, pthread_t** threads, data** thread_data);
/**
* Processa a matriz sem usar threads (debug)
*/
void processa_sem_threads();
|
C
|
#include<stdio.h>
#include<conio.h>
int main()
{
int base,pow,i=1,sum=1;
printf("enter the base");
scanf("%d",&base);
printf("enter the pow");
scanf("%d",&pow);
while(i<=pow)
{
sum=sum*base;
}
printf("the power of a number is %d",base);
return 0;
}
|
C
|
#include <stdio.h>
int main(int argc, char** argv) {
int enteros[45];
double flotantes[5];
int* p = enteros + 4;
printf("Tamano del entero: %lu\n", sizeof(int));
printf("Tamano del array enteros: %lu\n", sizeof(enteros));
printf("Tamano del float: %lu\n", sizeof(double));
printf("Tamano del array floats: %lu\n", sizeof(flotantes));
printf("Dir array enteros %lu, %lu\n", enteros, &enteros);
printf("Guido pruebaDir array enteros %lu, %lu\n",
&enteros + 4, enteros + 4 );
}
|
C
|
#include<stdio.h>
//#include<conio.h>
#include<string.h>
struct employee{
int empid;
char name[20];
struct date{
int dd;
int mm;
int yyyy;
}doj;
}emp;
void main(){
emp.empid=101;
strcpy(emp.name,"shayli patil");
emp.doj.dd=18;
emp.doj.mm=9;
emp.doj.yyyy=2017;
printf("\nEmployee no=%d",emp.empid);
printf("\nEmployee name=%s",emp.empid);
printf("\nEmployee date of joining (dd/mm/yyyy)=%d/%d/%d",emp.doj.dd,emp.doj.mm,emp.doj.yyyy);
printf("\nEmploy no=%d",emp.empid);
while(getchar()!="\n");
}
|
C
|
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Hello World\n\n");
for (int i=0; i<argc; i++)
printf("argv[%i] = %s\n",i,argv[i]);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void rotate(char matrix[10][10]){
if(matrix!=NULL){
char rotMatrix[10][10];
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
rotMatrix[j][10-1-i]=matrix[i][j];
}
}
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
matrix[i][j]=rotMatrix[i][j];
}
}
}
}
int main(int argc, char **argv){
if(argc!=2){
fprintf(stderr,"Invalid number of arguments!\n");
return EXIT_FAILURE;
}
FILE *f=fopen(argv[1],"r");
if(f==NULL){
fprintf(stderr,"Invalid input file '%s'\n",argv[1]);
return EXIT_FAILURE;
}
char matrix[10][10]={0};
for(int i=0;i<10;i++){
char temp[12]={0};
if(fgets(temp,12,f)==NULL){
fprintf(stderr,"Error: reading input file '%s'\n",argv[1]);
return EXIT_FAILURE;
}
if(temp[10]=='\n'){
for(int j=0;j<10;j++){
if(temp[j]!='\n'){
matrix[i][j]=temp[j];
}
else{
fprintf(stderr,"Invalid input file '%s' format\n",argv[1]);
return EXIT_FAILURE;
}
}
}
else{
fprintf(stderr,"Invalid input file '%s' format\n",argv[1]);
return EXIT_FAILURE;
}
}
int c=fgetc(f);
if(c!=EOF){
fprintf(stderr,"Input file '%s' is too long\n",argv[1]);
return EXIT_FAILURE;
}
rotate(matrix);
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
fprintf(stdout,"%c",matrix[i][j]);
}
fprintf(stdout,"\n");
}
if(fclose(f)!=0){
fprintf(stderr,"Unable to close file '%s'\n",argv[1]);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
C
|
// prob8-16.(難易度★★★)(並べ替え)
// 長さ10の整数の配列を作成し、各々の中に1から100までの乱数を代入し、その数を大きい順番に並べ替えて表示しなさい。なお、並べ替えの方法としては、以下の方法を用いなさい。
// ① 配列の中から、最大の数を探し出す。
// ② ①で見つけた数と、配列の最初の数を入れ替える。
// ③ 次に、配列の2番目から最後の中でもっとも大きな数を見つけ出す。
// ④ ③で見つけた数と、配列の2番目の数を入れ替える。
// ⑤ これを最後10番目まで繰り返す。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand((unsigned)time(NULL));
int ary[10];
for(int i=0; i<10; i++) {
ary[i] = rand() % 100 + 1;
printf("%d ", ary[i]);
}
printf("\n");
for(int i=0; i<10; i++) {
int max = 0;
for(int j=i; j<10; j++) {
if(max<ary[j]) {
max = ary[j];
}
}
int tmp = ary[i];
ary[i] = max;
int index;
for(int j=i; j<10; j++) {
if(max == ary[j]) {
index = j;
}
}
ary[index] = tmp;
if(i == 9) {
for(int j=0; j<10; j++) {
printf("%d ", ary[j]);
}
printf("\n");
}
}
return 0;
}
|
C
|
/*greedy method of choosing the largest square closer to N will not work
examle:
149=12^2+2^2+1^2=7^2+10^2;
*/
#include<stdio.h>
#include<math.h>
#define INF 15000;
int min_sqr[10002];
int square(int N)
{
double tmp;
int i,ans=INF;
if(min_sqr[N]!=15000)
{
return min_sqr[N];
}
tmp=sqrt(N);
if(floor(tmp)==ceil(tmp))
{
min_sqr[N]=1;
return min_sqr[N];
}
for(i=N/2;i>=1;i--)
{
if(square(i)+square(N-i)<ans) ans=min_sqr[i]+min_sqr[N-i];
}
min_sqr[N]=ans;
return ans;
}
int main()
{
int N,t,i;
for(i=0;i<10002;i++) min_sqr[i]=INF;
scanf("%d",&t);
while(t--)
{
scanf("%d",&N);
printf("%d\n",square(N));
}
return 0;
}
|
C
|
#include "../server.h"
/* windows socket program */
void
startServer(){
WORD wVersionRequested;
WSADATA wsaData;
int ret, nLeft, length;
SOCKET sListen, sServer;
struct sockaddr_in saServer, saClient;
char *ptr;
wVersionRequested = MAKEWORD(2,2);
ret = WSAStartup(wVersionRequested, &wsaData);
if(ret != 0){
printf("WSAStartup() failed!\n");
return;
}
sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sListen == INVALID_SOCKET){
WSACleanup();
printf("socket() faild!\n");
return;
}
saServer.sin_family = AF_INET;
saServer.sin_port = htons(SERVER_PORT);
saServer.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
ret = bind(sListen, (struct sockaddr *)&saServer, sizeof(saServer));
if (ret == SOCKET_ERROR){
printf("bind() faild! code:%d\n", WSAGetLastError());
closesocket(sListen);
WSACleanup();
return;
}
ret = listen(sListen, 5);
if (ret == SOCKET_ERROR){
printf("listen() faild! code:%d\n", WSAGetLastError());
closesocket(sListen);
return;
}
printf("Waiting for client connecting!\n");
printf("Tips: Ctrl+c to quit!\n");
while(1){
length = sizeof(saClient);
sServer = accept(sListen, (struct sockaddr *)&saClient, &length);
if (sServer == INVALID_SOCKET){
printf("accept() faild! code:%d\n", WSAGetLastError());
closesocket(sListen);
WSACleanup();
return;
}
char receiveMessage[5*1024];
nLeft = sizeof(receiveMessage);
ptr = (char *)&receiveMessage;
while(nLeft>0){
ret = recv(sServer, ptr, 5000, 0);
if (ret == SOCKET_ERROR){
printf("recv() failed!\n");
return;
}
if (ret == 0){
printf("Client has closed the connection\n");
break;
}
nLeft -= ret;
ptr += ret;
}
printf("receive message:%s\n", receiveMessage);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsub.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: wharring <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/28 16:17:47 by wharring #+# #+# */
/* Updated: 2019/03/12 17:28:10 by wharring ### ########.fr */
/* */
/* ************************************************************************** */
/*
** Allocates (with malloc(3)) and returns a "fresh" substring from the string
** given as argument. The substring begins at index start and is of size len.
** If start and len aren't refering to a valid substring, the behavior is undef
** If the allocation fails, the function returns NULL.
*/
#include "libft.h"
char *ft_strsub(char const *s, unsigned int start, size_t len)
{
char *sub;
if (s)
{
sub = ft_strnew(len);
if (sub)
ft_memmove(sub, s + start, len);
return (sub);
}
else
return (NULL);
}
|
C
|
#include "rb.h"
#include <stdio.h>
void rb_shownode ( root, level, x, p, private )
Arr *root ;
int level ;
Rb_node *x ;
void (*p)() ;
void *private ;
{
printf ( "\nLevel %2d Rb_node %8x\n", level, (unsigned int)x ) ;
printf ( "\t%s\n", x->red ? "Red" : "Black" ) ;
printf ( "\tLeft: %8x\n", (unsigned int)(x->left) ) ;
printf ( "\tRight: %8x\n", (unsigned int)(x->right) ) ;
p(x->key, x->value, private ) ;
if ( x->left != root->z )
rb_shownode ( root, level+1, x->left, p, private ) ;
if ( x->right != root->z )
rb_shownode ( root, level+1, x->right, p, private ) ;
}
void rb_show ( root, p, private )
Arr *root ;
void (*p)() ;
void *private ;
{
if ( root->head != root->z )
rb_shownode ( root, 0, root->head, p, private ) ;
}
/* $Id: rb_vcg.c,v 1.1.1.1 1997/04/12 04:19:02 danq Exp $ */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <time.h>
int randomRange(int _min, int _max){
int result = 0;
int low_num = 0;
int hi_num = 0;
if(_min < _max){
low_num = _min;
hi_num = _max + 1;
}else{
low_num = _max + 1;
hi_num = _min;
}
result = (rand() % (hi_num - low_num)) + low_num;
return result;
}
int main()
{
srand(time(NULL));
/*
int sizeXMA, sizeYMA;
scanf("%d", &sizeXMA);
scanf("%d", &sizeYMA);
int matrixA[sizeYMA][sizeXMA];
for(int i = 0; i < sizeYMA; i++){
for(int j = 0; j < sizeXMA; j++){
matrixA[i][j] = randomRange(0,9);
}
}
int matrixB[sizeXMA][sizeYMA];
for(int i = 0; i < sizeXMA; i++){
for(int j = 0; j < sizeYMA; j++){
matrixB[i][j] = matrixA[j][i];
}
}
printf("MATRIZ A \n");
for(int i = 0; i < sizeYMA; i++){
for(int j = 0; j < sizeXMA; j++){
printf("%d", matrixA[i][j]);
}
printf("\n");
}
printf("\n MATRIZ B \n");
for(int i = 0; i < sizeXMA; i++){
for(int j = 0; j < sizeYMA; j++){
printf("%d", matrixB[i][j]);
}
printf("\n");
}
*/
//Exercicio 3
int numX;
int result = 3;
scanf("%d", &numX);
for(int i = 1; i <= numX; i++){
for(int x = 1; x <= i; x++){
result 3= result * numX;
}
}
printf("\n Result: %d", result);
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/time.h>
#include <time.h>
// Init counter, seconds, microseconds.
static int c = 0;
double ms = 0;
int seconds;
// A handler for info printing.
void handler(int code) {
fprintf(stderr, "Caught signal: %d\n", code);
printf("Reads: %d, Seconds: %d\n", c, seconds);
exit(1);
}
int main(int argc, char ** argv) {
// Open file
FILE * f = fopen(argv[1], "rb");
// check if file cannot open
if (f == NULL) {
perror("fopen");
exit(1);
}
// argc cannot be 3
if (argc != 3) {
printf("Wrong input");
exit(1);
}
// Init variables
seconds = strtol(argv[2], NULL, 10);
int x;
int count;
// set timer
struct itimerval value;
value.it_value.tv_sec = seconds;
value.it_value.tv_usec = 0;
value.it_interval.tv_usec = 0;
value.it_interval.tv_sec = 0;
// check error
if (setitimer(ITIMER_REAL, &value, NULL)) {
perror("setitimer");
exit(1);
}
// set sigaction
struct sigaction newact;
newact.sa_handler = handler;
newact.sa_flags = 0;
sigemptyset(&newact.sa_mask);
sigaction(SIGALRM, &newact, NULL);
signal(SIGALRM, handler);
for (;;) {
x = random() % 100;
fseek(f, sizeof(int)*x, SEEK_SET);
fread(&count, sizeof(int), 1, f);
printf("Number: %d\n", count);
c++;
}
fclose(f);
return 0;
}
|
C
|
#include <stdlib.h>
#include "tournament.h"
#include "game.h"
#include "player.h"
struct tournament_t
{
int id;
int max_games_per_player;
const char* location;
bool finished;
int tournament_winner_id;
int num_different_players;
Map game_list;
};
/*make a copy of tournament_location and put it in tour_to_create->location */
Tournament tournamentCreate(int tournament_id, const char* tournament_location, int max_games_per_player)
{
if(tournament_id <= 0 || tournament_location == NULL || max_games_per_player <= 0)
{
return NULL;
}
Tournament tour_to_create = malloc(sizeof(*tour_to_create));
if(tour_to_create == NULL)
{
return NULL;
}
tour_to_create->finished = false;
tour_to_create->id = tournament_id;
tour_to_create->location = tournament_location;
tour_to_create->max_games_per_player = max_games_per_player;
tour_to_create->tournament_winner_id = PLAYER_INVALID_ID;
tour_to_create->game_list = NULL;
tour_to_create->num_different_players = 0;
return tour_to_create;
}
void tournamentDestroy(Tournament tournament)
{
free(tournament);
}
/* ********************** */
/* ******** SET ********* */
/* ********************** */
void tournamentSetId(Tournament tournament, int id)
{
if(tournament == NULL || id <= 0)
{
return;
}
tournament->id = id;
}
void tournamentSetMaxGames(Tournament tournament, int max_games_per_player)
{
if(tournament == NULL || max_games_per_player <= 0)
{
return;
}
tournament->max_games_per_player = max_games_per_player;
}
void tournamentSetLocation(Tournament tournament, char* location)
{
if(tournament == NULL || location == NULL)
{
return;
}
tournament->location = location;
}
void tournamentSetFinishedState(Tournament tournament, bool finished)
{
if(tournament == NULL)
{
return;
}
tournament->finished = finished;
}
void tournamentSetWinnderId(Tournament tournament, int winner_id)
{
if(tournament == NULL || winner_id <= 0)
{
return;
}
tournament->tournament_winner_id = winner_id;
}
void tournamentSetNumDiffPlayers(Tournament tournament, int num_of_players)
{
if(tournament == NULL || num_of_players < 0)
{
return;
}
tournament->num_different_players = num_of_players;
}
void tournamentSetGameList(Tournament tournament, Map games)
{
if(tournament == NULL || games == NULL)
{
return;
}
tournament->game_list = games;
}
/* ********************** */
/* ******** GET ********* */
/* ********************** */
int tournamentGetId(Tournament tournament)
{
if(tournament == NULL)
{
return TOURNAMENT_NULL_ARGUMENT;
}
return tournament->id;
}
int tournamentGetMaxGames(Tournament tournament)
{
if(tournament == NULL)
{
return TOURNAMENT_NULL_ARGUMENT;
}
return tournament->max_games_per_player;
}
const char* tournamentGetLocation(Tournament tournament)
{
if(tournament == NULL)
{
return NULL;
}
return tournament->location;
}
bool tournamentGetFinishedState(Tournament tournament)
{
if(tournament == NULL)
{
return false;
}
return tournament->finished;
}
Map tournamentGetGames(Tournament tournament)
{
if(tournament == NULL)
{
return NULL;
}
return tournament->game_list;
}
int tournamentGetWinnderId(Tournament tournament)
{
if(tournament == NULL)
{
return TOURNAMENT_NULL_ARGUMENT;
}
return tournament->tournament_winner_id;
}
int tournamentGetGamesPlayed(Tournament tournament)
{
if(tournament == NULL)
{
return TOURNAMENT_NULL_ARGUMENT;
}
if(tournament->game_list == NULL)
{
return 0;
}
return mapGetSize(tournament->game_list);
}
int tournamentGetNumDiffPlayers(Tournament tournament)
{
if(tournament == NULL)
{
return TOURNAMENT_NULL_ARGUMENT;
}
return tournament->num_different_players;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
void func(int tedad,int ragham){
int i,j,k=0,no=0,number,lower,upper,voroodi,m;
float kfloat,tedadfloat;
upper=pow(10,ragham)-1;
lower=pow(10,ragham-1);
int x[tedad];
srand(time(0));
for (m=1;m<=5;m++){
for (i=0;i<tedad;i++){
x[i]=(rand()%(upper - lower + 1)) + lower;
printf("%d ",x[i]);
}
printf("\n");
for (j=0;j<tedad;j++){
scanf("%d",&voroodi);
for (i=0;i<tedad;i++){
if (x[i]==voroodi){
printf("Correct :) :D\n");
k++;
break;
}
}
for (i=0;i<tedad;i++){
if (x[i]!=voroodi){
no++;
}
}
if (no!=(tedad-1)){
printf("Incorrect :( :P\n");
}
no=0;
}
kfloat=k;
tedadfloat=tedad;
if (k==tedad){
printf("1\n");
}
if (k==0){
printf("0\n");
}
if (k>0&&k<tedad){
printf("%f\n",(kfloat/tedadfloat));
}
k=0;
}
printf("1)Continue\n");
printf("2)Increase numbers\n");
printf("3)Increase digits\n");
printf("4)End\n");
}
int main(){
int i,tedad,ragham,pressnumber;
scanf("%d",&tedad);
scanf("%d",&ragham);
func(tedad,ragham);
scanf("%d",&pressnumber);
while (pressnumber!=4){
if (pressnumber==1){
func(tedad,ragham);
}
if (pressnumber==2){
tedad=tedad+1;
func(tedad,ragham);
}
if (pressnumber==3){
ragham=ragham+1;
func(tedad,ragham);
}
scanf("%d",&pressnumber);
}
if (pressnumber==4){
return 0;
}
}
|
C
|
#include <unistd.h>
int ft_strlen(char *str)
{
int i;
i = 0;
while (str[i])
i++;
return (i);
}
void print_word(char *str)
{
while (*str != ' ' && *str)
write (1, str++, 1);
write (1, "\n", 1);
}
int main(int argc, char **argv)
{
int len;
if (argc == 2)
{
len = ft_strlen(argv[1]);
while (--len >= 0)
if (argv[1][len] != ' ' && (argv[1][len - 1] == ' ' || len == 0))
print_word(&argv[1][len]);
}
else
write (1, "\n", 1);
return (0);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#define UID 0
#define GID 0
#define R "\e[31m"
#define G "\e[32m"
#define Y "\e[33m"
#define N "\e[39m"
#define LR "\e[91m"
#define LG "\e[92m"
// Maximum 8 hexadecimal digits for KEY
#define KEY 0x0
// NX bit on, Canary enabled
void penetrate()
{
int target;
fprintf(stdout, "Enter a number to get hint : ");
fscanf(stdin, "%d", &target);
if(target == KEY)
{
fprintf(stdout, G "> You made it!" N "\n");
if(setregid(GID, GID))
{
perror(R "> setgid failed." N);
exit(1);
}
if(setreuid(UID, UID))
{
perror(R "> setuid failed." N);
exit(1);
}
fprintf(stdout, Y "> Entering sh...\n");
system("/bin/sh");
fprintf(stdout, N);
}
else
{
fprintf(stdout, R "> Nah... Try again." N "\n");
}
}
int main()
{
penetrate();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int fibbo(int n);
int main()
{
int n ;
scanf("%d",&n);
for(int i = 0 ; i <= n ; i++)
{
printf("%d \t" ,fibbo(i));
}
return 0;
}
int fibbo(int n)
{
if( n == 0)
{
return 0;
}
if( n == 1)
{
return 1;
}
return (fibbo(n-1) + fibbo(n-2));
}
|
C
|
#include <stdio.h>
struct person {
char name[20];
char pID[20];
struct person* frnd;
};
int main(void)
{
struct person man1 = {"Mr. Lee", "820204-0000512"};
struct person man2 = {"Mr. Lee's Friend", "820000-0000101"};
man1.frnd = &man2;
printf("[Mr. Lee]\n");
printf("name : %s \n", man1.name);
printf("pID : %s \n", man1.pID);
printf("[His Friend]\n");
printf("name : %s \n", man1.frnd->name);
printf("pID : %s \n", man1.frnd->pID);
return 0;
}
|
C
|
/* CS 370
Project #2
Gerardo Gomez-Martinez
September 16, 2014
Program acts as a Linux terminal shell. It prints a prompt containing the current working
directory and waits for user input. It accepts commands from the user and executes until
the user exits the shell. Also accepts the chnage directory command and chnages the
directory accordingly. It also keeps a history of the last 10 commands executed and lets
the user cycle through them using the arrow keys.
*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <termios.h>
#include <stdbool.h>
#include <stdlib.h>
void printPrompt();
int main()
{
int pid; /* Process ID of parent and child processes */
int pipeid; /* Process ID used for pipe communication */
int status; /* Status flag of child process */
int i, j, k; /* Loop control variables */
int h = 0; /* Position to store last command entered on history array */
int histAr; /* Position of current cycle on history array */
int arPress = 0; /* Number of arrow presses */
int er; /* If an error was encountered in current call */
int items = 0; /* Number of items in history array */
int bytesRead; /* Number of bytes read on read() call*/
int fd[2]; /* File descriptors for pipe communication */
char *buffer = (char *)calloc(256, sizeof(char)); /* Input buffer */
char *inpt = (char *)calloc(256, sizeof(char)); /* Current command being executed */
char *command[20]; /* Tokenized command being executed */
char *pipecmd[20]; /* Tokenized second command to use in pipe */
char *history[10]; /* Array to hold commands history */
char *token; /* Tokens of current command */
char *erMsg; /* Error message for perror() call */
char *des = (char *)calloc(2, sizeof(char));
bool ext = false; /* If the user has exited the shell */
bool brk; /* If the user has entered the command */
bool piping; /* If the pipe operator is in the command */
struct termios origConfig; /* Original termios configuration */
struct termios newConfig; /* Modified termios configuration */
setbuf(stdout, NULL);
/* Get original termios configuration */
tcgetattr(0, &origConfig);
newConfig = origConfig;
/* Adjust the new configuration */
newConfig.c_lflag &= ~(ICANON|ECHO);
newConfig.c_cc[VMIN] = 5;
newConfig.c_cc[VTIME] = 1;
/* Set the new configuration */
tcsetattr(0, TCSANOW, &newConfig);
/* Allocate space for the history array */
for (j = 0; j<10; j++)
{
history[j] = (char *)calloc(256, sizeof(char));
}
while (!ext)
{
printPrompt();
brk = false;
piping = false;
j = 0;
k = 0;
while (!brk)
{
/* Reads input from the user and process it */
bytesRead = read(0, buffer, 10);
if (bytesRead == 1)
{
/* If user presses enter break */
if (buffer[0] == '\n')
{
printf("%c", buffer[0]);
inpt[j] = '\n';
brk = true;
}
/* User enters backspace or delete */
else if (buffer[0] == 127 || buffer[0] == 8)
{
if (j > 0)
{
printf("%c%c%c", '\b', ' ', '\b');
j--;
inpt[j] = '\b';
}
}
else
{
printf("%c", buffer[0]);
inpt[j] = buffer[0];
j++;
}
}
else if (bytesRead == 2)
{
if (buffer[0] != '\n' && buffer[1] != '\n')
{
printf("%c%c", buffer[0], buffer[1]);
inpt[j] = buffer[0];
j++;
inpt[j] = buffer[1];
j++;
}
else if (buffer[0] == '\n')
{
brk = true;
}
else
{
printf("%c%c", buffer[0], buffer[1]);
inpt[j] = buffer[0];
j++;
brk = true;
}
}
else
{
/* Arrow pressed */
if (bytesRead == 3)
{
if(buffer[0] == 27 && buffer[1] == 91 && buffer[2] == 65)
{
/* Up arrow */
if (arPress < items)
{
arPress++;
for(k = 0; k < j; k++)
{
printf("%c%c%c", '\b', ' ', '\b');
}
histAr--;
if (histAr < 0)
histAr = 9;
printf("%s", history[histAr]);
strcpy(inpt, history[histAr]);
j = strlen(history[histAr]);
}
}
if(buffer[0] == 27 && buffer[1] == 91 && buffer[2] == 66)
{
/* Down arrow */
if (arPress > 0)
{
arPress--;
for(k = 0; k < j; k++)
{
printf("%c%c%c", '\b', ' ', '\b');
}
histAr++;
if (histAr > 9)
histAr = 0;
if (arPress == 0)
{
inpt[0] = '\n';
j = 0;
}
else
{
printf("%s", history[histAr]);
strcpy(inpt, history[histAr]);
j = strlen(history[histAr]);
}
}
}
}
}
}
/* If command has been input executes it */
if(inpt[0] != '\n')
{
strtok(inpt, "\n");
/* Adds command to history array */
strcpy(history[h%10], inpt);
histAr = (h%10)+1;
arPress = 0;
h++;
items++;
if (items > 10)
items = 10;
token = strtok(inpt, " \n");
i = 0;
while (token != NULL && i < 19)
{
if (token[0] == '|')
{
piping = true;
k = 0;
}
else if (piping)
{
pipecmd[k] = token;
k++;
}
else
{
command[i] = token;
i++;
}
token = strtok(NULL, " \n");
}
command[i] = NULL;
pipecmd[k] = NULL;
/* If change directory command chnage the current working directory */
if (strcmp(command[0], "cd") == 0)
{
er = chdir(command[1]);
if (er < 0)
{
perror("cd");
}
}
/* If command is exit asks the user if he's sure and executes accordingly */
else if (strcmp(command[0], "exit") == 0)
{
printf("Are you sure you want to exit (Y/N)? ");
bytesRead = read(0, des, 1);
printf("%c\n", des[0]);
if (des[0] == 'Y' || des[0] == 'y')
ext = true;
else
{
while (!(des[0] == 'N'|| des[0] == 'n' || des[0] == 'Y' || des[0] == 'y'))
{
printf("Invalid command, please try again.\n");
printf("Are you sure you want to exit (Y/N)? ");
bytesRead = read(0, des, 1);
printf("%c\n", des[0]);
if (des[0] == 'Y' || des[0] == 'y')
ext = true;
}
}
}
else
{
pid = fork();
if (pid == 0)
{
if (piping)
{
pipe(fd);
pipeid = fork();
if (pipeid == 0)
{
/* Child pipe process */
close(1);
dup(fd[1]);
close(fd[0]);
execvp(command[0], command);
exit(0);
}
else
{
/* Parent pipe process */
close(0);
dup(fd[0]);
close(fd[1]);
er = execvp(pipecmd[0], pipecmd);
if (er < 0)
{
perror(pipecmd[0]);
}
}
exit(0);
}
else
{
er = execvp(command[0], command);
if (er < 0)
{
perror(command[0]);
}
exit(0);
}
}
else
{
waitpid(pid, &status, WUNTRACED);
}
}
}
}
/* Restore the original termios configuration */
tcsetattr(0, TCSANOW, &origConfig);
free(buffer);
return(0);
}
/* Prints the prompt containing the current working directory */
void printPrompt()
{
char buffer[100];
getcwd(buffer, sizeof(buffer));
printf("%s>", buffer);
}
|
C
|
#include<math.h>
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
#define N 256
int main(){
char str[N];
int i;
printf("Digite a frase :");
fgets(str,N,stdin);
for(i=0; i<strlen(str); i++){
if(str[i]<78&&str[i]>65)
{
str[i]=(str[i]+13);
}
else
{
if((str[i]>78 && str[i]<90))
str[i]=(str[i]-13);
}
if(str[i]>97 && str[i]<110)
{
str[i]=(str[i]+13);
}
else
{
if((str[i]>110 && str[i]<123))
str[i]=(str[i]-13);
}
}
str[i-1]= '\0';
printf("%s\n", str);
return EXIT_SUCCESS;
}
|
C
|
/*
** EPITECH PROJECT, 2018
** my put number
** File description:
** display number give on parameter
*/
int my_put_hexa_adress(int nb);
void my_putchar(char c);
int my_putstr(char const *str);
int tour = 0;
int nb_special_hexa_adress(long nb)
{
tour = 1;
my_put_hexa_adress(nb / 16);
my_put_hexa_adress(nb % 16);
}
void print_hexa(int nb)
{
if (nb <= 9)
my_putchar(nb + 48);
else if (nb == 10)
my_putchar('a');
else if (nb == 11)
my_putchar('b');
else if (nb == 12)
my_putchar('c');
else if (nb == 13)
my_putchar('d');
else if (nb == 14)
my_putchar('e');
else if (nb == 15)
my_putchar('f');
else {
nb_special_hexa_adress(nb);
}
}
int my_put_hexa_adress(int nb)
{
int special = 0;
if (tour == 0)
my_putstr("0x");
if (nb == -2147483648) {
special = 1;
nb = -214748364;
}
if (nb < 0) {
my_putchar('-');
nb = -nb;
}
print_hexa(nb);
if (special == 1) {
my_putchar(56);
}
}
|
C
|
#ifndef _LED_H_
#define _LED_H_
/**
\file led.h
\brief
\author tyranno
\warning
\date 2012/10/10
*/
/*Revision history ******************************************
*
* Author :
* Dept :
* Revision Date :
* Version :
*
*/
#ifdef __cplusplus
extern "C"
{
#endif
typedef enum
{
LED_RSSI,
LED_STATE,
LED_MAX
}led_type;
typedef enum
{
LED_COL_0=0, //led off
LED_COL_1=1, //orange
LED_COL_2=2, //blue
LED_COL_3=3, //violet
LED_COL_MAX
}led_color_type;
/**
\fn int led_color(led_type t, led_color_type c)
\brief On/Off Led
\param id : control id
\param c : color
\return 0 : No Error, Other : error
\date 2012/10/10
\author tyranno
\version 1
*/
extern int led_color(led_type t, led_color_type c);
/**
\fn int led_aquire_control()
\brief aquire led control to handle led
\param t : led type(RSSI, STATE)
\param ctl : 0:shared, 1:exclusive
\return -1 : error Other: Control id
\date 2012/10/10
\author tyranno
\version 1
*/
extern int led_set_exclusive(led_type t, int ctl);
/**
int main()
{
//set led exclusive mode (other process doesn't control led)
//if process quit, other proesses are able to handle led
led_set_exclusive(LED_RSSI, 1);
//Set RSSI led to red
led_onoff(LED_RSSI, LED_1);
return 0;
}
*/
#ifdef __cplusplus
}
#endif
#endif//_LED_H_
|
C
|
#define EXPORT_OPS
#include "interpreter.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include <inttypes.h>
int daily_run_bytecode(DailyOp* operations) {
#if defined(_MSC_VER) || defined(DAILY_USE_SWITCH)
#define OP_SWITCH while (true) switch (operation->operation)
#define OP_CASE(op) case op:
#define OP_NEXT operation++; break
#else
static void *opcodes[] = {
#define X_OP(op) &&op,
DAILY_OPS
#undef X_OP
};
#define OP_SWITCH operation--; OP_NEXT; if (false)
#define OP_CASE(op) op:
#define OP_NEXT goto *opcodes[(++operation)->operation]
#endif
#define CHECK_POINTER(pointer, size) if (pointer < stack || pointer - size > stack_pointer) return 2
#define CHECK_PARAMETER(parameter, size) CHECK_POINTER(stack_pointer - parameter, size)
#define GET_PARAMETER(parameter, size) stack_pointer[1 - (size) - (parameter)]
#define GET_PARAMETER_AS(parameter, type) *(type*)&GET_PARAMETER(parameter, sizeof(type))
DailyOp* operation = &operations[0];
unsigned char* stack = 0;
unsigned char* stack_pointer = 0;
long stack_size_available = 0;
OP_SWITCH {
OP_CASE(DailyOpNil) {
free(stack);
stack_size_available = 0;
stack = NULL;
stack_pointer = NULL;
return 0;
}
OP_CASE(DailyOpError) {
printf("ERROR %d\n", operation->param1);
free(stack);
stack_size_available = 0;
stack = NULL;
stack_pointer = NULL;
return 1;
}
OP_CASE(DailyOpAlloc) {
if (stack_size_available < operation->param1) {
int pointer_offset = stack_pointer - stack;
stack_size_available = (operation->param1 + stack_size_available) * 2;
stack = realloc(stack, pointer_offset + stack_size_available + 1);
stack_pointer = stack + pointer_offset;
}
memset(stack_pointer + 1, operation->param2, operation->param1);
stack_size_available -= operation->param1;
stack_pointer += operation->param1;
OP_NEXT;
}
OP_CASE(DailyOpDealloc) {
stack_pointer -= operation->param1;
stack_size_available += operation->param1;
CHECK_POINTER(stack_pointer, 0);
OP_NEXT;
}
OP_CASE(DailyOpSet) {
CHECK_PARAMETER(operation->param1, 1);
GET_PARAMETER(operation->param1, 1) = operation->param2;
OP_NEXT;
}
OP_CASE(DailyOpCopy) {
CHECK_PARAMETER(operation->param1, operation->param3);
CHECK_PARAMETER(operation->param2, operation->param3);
memcpy(&GET_PARAMETER(operation->param1, operation->param3), &GET_PARAMETER(operation->param2, operation->param3), operation->param3);
OP_NEXT;
}
OP_CASE(DailyOpDebug) {
printf("---- DEBUG -----\n");
printf("Stack: %ld used, %ld allocated\n", stack_pointer - stack, (stack_pointer - stack) + stack_size_available);
printf("Stack values:\n");
for (long i = 0; i < (stack_pointer - stack); i++) {
printf("\t%5ld: %02x %3d\n", i, stack_pointer[-i], stack_pointer[-i]);
}
OP_NEXT;
}
#define MATH_OP(op, operator, type) \
OP_CASE(op) { \
CHECK_PARAMETER(operation->param1, sizeof(type)); \
CHECK_PARAMETER(operation->param2, sizeof(type)); \
CHECK_PARAMETER(operation->param3, sizeof(type)); \
GET_PARAMETER_AS(operation->param1, type) = \
GET_PARAMETER_AS(operation->param2, type) \
operator \
GET_PARAMETER_AS(operation->param3, type); \
OP_NEXT; \
}
#define MATH_OPS(name, type) \
MATH_OP(DailyOp##name##Add, +, type) \
MATH_OP(DailyOp##name##Subtract, -, type) \
MATH_OP(DailyOp##name##Multiply, *, type) \
MATH_OP(DailyOp##name##Divide, /, type) \
MATH_OP(DailyOp##name##Modulo, %, type)
MATH_OPS(Int16, int16_t)
MATH_OPS(Int32, int32_t)
#undef MATH_OPS
#undef MATH_OP
}
#undef CHECK_POINTER
#undef CHECK_PARAMETER
}
|
C
|
#include<stdio.h>
#include<time.h>
int a[10][10];
int count=-1,n;
int reach[50],pos[50];
void read_matrix()
{
int i,j;
printf("Enter the adjacency matrix(enter 0/1)\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i!=j)
{
printf("%d,%d:",i,j);
scanf("%d",&a[i][j]);
}
}
void dfs(int v)
{
int u;
reach[++count]=v;
u=adjacent(v);
while(u)
{
if(checkreach(u)==0)
dfs(u);
u=adjacent(v);
}
}
int adjacent(int i)
{
int j;
for(j=pos[i]+1;j<=n;j++)
if(a[i][j]==1)
{
pos[i]=j;
return j;
}
pos[i]=n+1;
return 0;
}
int checkreach(int u)
{
int i;
for(i=1;i<=count;i++)
if(reach[i]==u)
return 1;
return 0;
}
void main()
{ char choice;
int v,i;
double clk;
clock_t starttime,endtime;
srand(time(0));
printf("\nHELLO FROM DIGITAL MAPS\n\n");
printf("Would you like too see the connectivity between cities? Y/N:\n");
scanf("%c",&choice);
if(choice=='n'||choice=='N')
return 0;
printf("Enter the number of islands: \n");
scanf("%d",&n);
for(i=1;i<=count;i++)
pos[i]=0;
printf("Enter the matrix representation of islands reachable:\n");
read_matrix();
printf("Enter the starting island: \n");
scanf("%d",&v);
starttime=clock();
dfs(v);
endtime=clock();
clk=(double)(endtime-starttime)/CLOCKS_PER_SEC;
printf("Islands reachable from the given island are...\n");
for(i=0;i<count;i++)
printf("%d\t",reach[i]);
printf("\nThe run time is %f\n",clk);
}
|
C
|
/*This time let us consider the situation in the movie "Live and Let Die" in which James Bond, the world's most famous spy, was captured by a group of drug dealers. He was sent to a small piece of land at the center of a lake filled with crocodiles.
There he performed the most daring action to escape -- he jumped onto the head of the nearest crocodile!
Before the animal realized what was happening, James jumped again onto the next big head... Finally he reached the bank before the last crocodile could bite him (actually the stunt man was caught by the big mouth and barely escaped with his extra thick boot).
Assume that the lake is a 100 by 100 square one.
Assume that the center of the lake is at (0,0) and the northeast corner at (50,50).
The central island is a disk centered at (0,0) with the diameter of 15.
A number of crocodiles are in the lake at various positions.
Given the coordinates of each crocodile and the distance that James could jump, you must tell him whether or not he can escape.
Input Specification:
Each input file contains one test case. Each case starts with a line containing two positive integers N (≤100), the number of crocodiles, and D, the maximum distance that James could jump. Then N lines follow, each containing the (x,y) location of a crocodile. Note that no two crocodiles are staying at the same position.
Output Specification:
For each test case, print in a line "Yes" if James can escape, or "No" if not.
Sample Input 1:
14 20
25 -15
-25 28
8 49
29 15
-35 -2
5 28
27 -29
-8 -28
-20 -35
-25 -20
-13 29
-30 15
-35 40
12 12
Sample Output 1:
Yes
Sample Input 2:
4 13
-12 12
12 12
-12 -12
12 -12
Sample Output 2:
No
code:
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#define Max 100
typedef struct Point{
int x, y;
}Position;
bool DFS(Position Lake[], int i, int N,int D);
bool FisrtJump(int x, int y, int D);
bool IsSafe(int x, int y, int D);
bool Jump(int i, int j, int x, int y, int D);
int Visited[Max] = { false };
int main(){
Position Lake[Max];
int N, D;
scanf("%d %d", &N, &D);
int i;
for (i = 0; i < N; i++){//读入所有顶点,没有边
scanf("%d %d", &Lake[i].x, &Lake[i].y);
}
bool answer = false;
for (i = 0; i < N; i++){
if (!Visited[i] && FisrtJump(Lake[i].x, Lake[i].y,D)){
answer = DFS(Lake,i,N,D);
if (answer ) break;
}
}
if (answer ) printf("Yes\n");
else printf("No\n");
return 0;
}
bool FisrtJump(int x, int y, int D){
double distance;
distance = sqrt(pow(x , 2) + pow(y , 2));
if ((distance - 7.5) <= D) return true;
else return false;
}
bool IsSafe(int x, int y, int D){
if ((x <= -(50 - D) || x >= (50 - D)) || (y <= -(50 - D) || y >= (50 - D)))
return true;
else return false;
}
bool Jump(int i, int j, int x, int y, int D){
double distance;
distance = sqrt(pow(x - i, 2) + pow(y - j, 2));
if (distance <= D) return true;
else return false;
}
bool DFS(Position Lake[], int i, int N,int D){
bool answer = false;
Visited[i] = true;
if (IsSafe(Lake[i].x, Lake[i].y, D)) answer = true;
else{
int cnt;
for (cnt = 0; cnt < N; cnt++){
if (!Visited[cnt] && Jump(Lake[i].x, Lake[i].y, Lake[cnt].x, Lake[cnt].y, D)){
answer = DFS(Lake, cnt, N, D);
if (answer ) break;
}
}
}
return answer;
}
|
C
|
#include <stdio.h>
#include <omp.h>
#define SIZE 1000
int A [SIZE][SIZE];
int B [SIZE][SIZE];
int C [SIZE][SIZE];
int D [SIZE][SIZE];
int R [SIZE][SIZE];
void populate(int A[SIZE][SIZE])
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
A[i][j] = 1;
}
}
}
int main(){
populate(A);
populate(B);
populate(C);
populate(D);
omp_set_num_threads(2);
#pragma omp
{
int i,j;
#pragma parallel for num_threads(2) shared (A,B,C,D) private(i,j)
for (i = 0; i < SIZE; i ++)
{
for (j = 0; j < SIZE; j++)
{
A[i][j] = A[i][j]*B[i][j];
C[i][j] = C[i][j]*D[i][j];
//printf("%d ", A[i][j]);
//printf("%d \n", C[i][j]);
}
}
int k, l;
#pragma parallel for shared (A,C,R) private(k,l)
for (k = 0; k < SIZE; k ++)
{
for (l = 0; l < SIZE; l++)
{
R[k][l] = A[k][l] + C[k][l];
printf("%d", R[k][l]);
}
}
}
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int arr[9] = { 1,2,3,4,5,6,7,8,9 };
for (int i = 8; i >= 0; i--)
{
printf("%2d",arr[i]);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
/**
* How a FTP client application works
* First a socket is created
* Then the client establishes a connection to the server
* In a connection-oriented protocol, the first connection that the client makes to server is a control connection which must be persistent
* In this case, in the control connection, the client needs to authenticate itself with the server for the control connection to be established
*
*/
if (argc != 3)
{
printf("Error: Please only provide address and port as 2 arguments\n");
return -1;
}
u_int32_t ip;
if (strcmp(argv[1], "127.0.0.1") == 0)
ip = INADDR_LOOPBACK;
else
{
printf("Error: Only support localhost connection at 127.0.0.1\n");
return -1;
}
int port = atoi(argv[2]);
// Create a socket and set address family, port number and address
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0)
{
perror("Socket: ");
return (-1);
}
struct sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port);
server_address.sin_addr.s_addr = htonl(ip);
// The client makes connection the server
if (connect(server_fd, (struct sockaddr *)&server_address, sizeof(server_address)) < 0)
{
perror("Connect :");
return -1;
}
char message[100];
while (1)
{
printf("ftp> ");
//gets(message); //not safe
fgets(message, 100, stdin); //more safe but has no \n at the end,
message[strcspn(message, "\n")] = 0; //lets add it
if (strncmp(message, "!CD ", 4) == 0) // '!CD' command
{
char dir[100];
strncpy(dir, &message[4], sizeof(message) - 4);
if (chdir(dir) == -1)
{
printf("Directory does not exist\n");
}
}
else if (strncmp(message, "!PWD", 4) == 0) // '!PWD' command
{
system("pwd");
}
else if (strncmp(message, "!LS", 3) == 0) // '!LS' command
{
system("ls");
}
else if (strncmp(message, "USER ", 5) == 0 || strncmp(message, "PASS ", 5) == 0 || strncmp(message, "PWD", 3) == 0 || strncmp(message, "LS", 2) == 0 || strncmp(message, "CD ", 3) == 0)
{ // valid server commands
send(server_fd, message, strlen(message), 0);
memset(message, 0, sizeof(message));
recv(server_fd, message, sizeof(message) - 1, 0);
printf("%s\n", message);
}
else if (strncmp(message, "PUT ", 4) == 0)
{
char file_name[100];
char file_content[500];
FILE *file;
char line[100];
strncpy(file_name, &message[4], sizeof(message) - 4); // get file_name from PUT command
if (!(file = fopen(file_name, "r")))
{
printf("File not found\n");
}
else
{
send(server_fd, message, strlen(message), 0); // send PUT command to server
memset(message, 0, sizeof(message));
recv(server_fd, message, sizeof(message) - 1, 0); // wait for confirmation message from server
// printf("%s\n", message);
if (strcmp(message, "Authenticate first") == 0)
{
printf("%s\n", message);
}
else
{
memset(file_content, 0, sizeof(file_content));
while (fgets(line, sizeof(line), file) != NULL) // read each line of file
{
strcat(file_content, line);
memset(line, 0, sizeof(line));
}
// open new TCP connection to send file
int port = atoi(message);
int server_sd = socket(AF_INET, SOCK_STREAM, 0);
if (server_sd < 0)
{
perror("Socket: ");
return (-1);
}
struct sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port); // new port for the new TCP connection
server_address.sin_addr.s_addr = htonl(ip);
if (connect(server_sd, (struct sockaddr *)&server_address, sizeof(server_address)) < 0)
{
perror("Connect :");
return -1;
}
send(server_sd, file_content, strlen(file_content), 0); // send file_content to server through the new TCP connection
fclose(file);
close(server_sd); // close the TCP connection for file transfer
memset(message, 0, sizeof(message));
recv(server_fd, message, sizeof(message) - 1, 0); // wait for confirmation message from server
printf("%s\n", message);
}
}
}
else if (strncmp(message, "GET ", 4) == 0)
{
char file_name[100];
char file_content[500];
FILE *file;
strncpy(file_name, &message[4], sizeof(message) - 4); // get file_name from GET command
send(server_fd, message, strlen(message), 0);
memset(message, 0, sizeof(message));
recv(server_fd, message, sizeof(message) - 1, 0); // wait for confirmation message from server
if (strcmp(message, "Authenticate first") == 0 || strcmp(message, "File not found") == 0)
{
printf("%s\n", message);
}
else
{
// open new TCP connection to send file
int port = atoi(message);
int server_sd = socket(AF_INET, SOCK_STREAM, 0);
if (server_sd < 0)
{
perror("Socket: ");
return (-1);
}
struct sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port); // new port for the new TCP connection
server_address.sin_addr.s_addr = htonl(ip);
if (connect(server_sd, (struct sockaddr *)&server_address, sizeof(server_address)) < 0)
{
perror("Connect :");
return -1;
}
recv(server_sd, file_content, sizeof(file_content) - 1, 0); // wait to receive file content from server
file = fopen(file_name, "w"); // open a new file to write to
fputs(file_content, file);
memset(file_name, 0, sizeof(file_name));
memset(file_content, 0, sizeof(file_content));
fclose(file);
close(server_sd);
printf("GET file successful\n");
}
}
else if (strncmp(message, "QUIT", 4) == 0)
{ // terminate connection and close socket
send(server_fd, message, strlen(message), 0);
close(server_fd);
printf("Connection terminated\nSocket closed\n");
break;
}
else
{
printf("Invalid FTP command\n");
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <contiki.h>
#include <dev/button-sensor.h>
#include <dev/leds.h>
PROCESS(timer_process, "timer process");
AUTOSTART_PROCESSES(&timer_process);
PROCESS_THREAD(timer_process,ev,data)
{
PROCESS_BEGIN();
SENSORS_ACTIVATE(button_sensor);
leds_off(LEDS_GREEN);
leds_on(LEDS_RED);
printf("hello world\n");
while(1){
static struct etimer et;
static uint32_t seconds = 5;
PROCESS_WAIT_EVENT();
if(ev == sensors_event && data == &button_sensor){
etimer_set(&et,CLOCK_SECOND*seconds);
printf("button pressed\n");
}
if(etimer_expired(&et)){
leds_toggle(LEDS_GREEN);
leds_toggle(LEDS_RED);
printf("timer expired\n");
}
}
PROCESS_END();
}
|
C
|
#include <stdio.h>
#include <assert.h>
#include "p2.h"
/*
* Test program for a circular doubly linked list.
*/
int main ( ) {
node * head = 0;
add_to_front('O', &head);
print_list(head);
add_to_front('S', &head);
print_list(head);
add_to_front('C', &head);
print_list(head);
add_to_back('f', &head);
add_to_back('u', &head);
add_to_back('n', &head);
print_list(head);
assert(index_of('f', head) == 3 );
empty(&head);
print_list(head);
add_to_back('1', &head);
print_list(head);
remove_first(&head);
print_list(head);
add_to_back('0', &head);
print_list(head);
remove_last(&head);
print_list(head);
int i;
for ( i = 0; i < 5; i=i+2 ) {
add_to_front (i+'A', &head);
add_to_back (i+1+'A', &head);
}
print_list(head);
assert(num_of_nodes(head) == 6);
assert(index_of('A', head) == 2);
assert(index_of('D', head) == 4);
for ( i = 0; i < 5; i=i+2 ) {
remove_first(&head);
remove_last(&head);
}
print_list(head);
printf("\n\nExamine the output above to determine correctness of your code. \n"
"You should make sure to thoroughly test your"
" code even when the above output seems reasonable.\n\n" );
return 0;
}
|
C
|
/*
* io.c
*
* Created: 06.09.2019 10:13:09
* Author: Ole Sivert
*/
#include <avr/io.h>
#include "io.h"
#include "adc.h"
#include "../compact_math.h"
/* Returns the value of the given button */
uint8_t get_button(uint8_t button) {
uint8_t i = PINB;
return (i >> button) & 1;
}
/* Method to read the current status of buttons, sliders and joystick into the given controllerInput struct.
Sets all values in the struct, including flags to test if the value has been changed.
Returns 1 if any value has been changed since last read */
uint8_t read_controller_status(controller_input_t *buffer) {
uint8_t changes = 0;
uint8_t js_button = !get_button(JOYSTICK_BUTTON);
uint8_t button_one = get_button(BUTTON_1);
uint8_t button_two = get_button(BUTTON_2);
if (buffer->joystick_button != js_button) {
changes = 1;
buffer->joystick_button = js_button;
buffer->joystick_button_changed = 1;
} else {
buffer->joystick_button_changed = 0;
}
if (buffer->button_one_value != button_one) {
changes = 1;
buffer->button_one_value = button_one;
buffer->button_one_changed = 1;
} else {
buffer->button_one_changed = 0;
}
if (buffer->button_two_value != button_two) {
changes = 1;
buffer->button_two_value = button_two;
buffer->button_two_changed = 1;
} else {
buffer->button_two_changed = 0;
}
int8_t joystick_x = get_joystick_value(JOYSTICK_X);
if (joystick_x != buffer->joystick_x) {
changes = 1;
buffer->joystick_x = joystick_x;
}
int8_t joystick_y = get_joystick_value(JOYSTICK_Y);
if (joystick_y != buffer->joystick_y) {
changes = 1;
buffer->joystick_y = joystick_y;
}
int8_t joystick_trigger = 0;
if (buffer->joystick_y > 40) joystick_trigger = 1;
else if (buffer->joystick_y < -40) joystick_trigger = -1;
if (buffer->joystick_trigger_last != joystick_trigger && joystick_trigger != 0) {
changes = 1;
buffer->joystick_trigger = joystick_trigger;
} else {
if (buffer->joystick_trigger != 0) {
changes = 1;
}
buffer->joystick_trigger = 0;
}
buffer->joystick_trigger_last = joystick_trigger;
uint8_t slider_one = get_slider_value(SLIDER_1);
uint8_t slider_two = get_slider_value(SLIDER_2);
if (abs_diff(buffer->slider_one_value, slider_one) > 5) {
changes = 1;
buffer->slider_one_value = slider_one;
}
if (abs_diff(buffer->slider_two_value, slider_two) > 5) {
changes = 1;
buffer->slider_two_value = slider_two;
}
return changes;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rotation.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jtrancos <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/26 13:09:15 by jtrancos #+# #+# */
/* Updated: 2021/01/27 10:34:05 by jtrancos ### ########.fr */
/* */
/* ************************************************************************** */
#include "../cub3d.h"
void rotation_right(t_data *data)
{
float old_dir_x;
float old_plane_x;
old_dir_x = data->player.dir_x;
old_plane_x = data->player.plane_x;
data->player.dir_x = data->player.dir_x * cos(-data->player.rotation) -
data->player.dir_y * sin(-data->player.rotation);
data->player.dir_y = old_dir_x * sin(-data->player.rotation) +
data->player.dir_y * cos(-data->player.rotation);
data->player.plane_x = data->player.plane_x * cos(-data->player.rotation) -
data->player.plane_y * sin(-data->player.rotation);
data->player.plane_y = old_plane_x * sin(-data->player.rotation) +
data->player.plane_y * cos(-data->player.rotation);
}
void rotation_left(t_data *data)
{
float old_dir_x;
float old_plane_x;
old_dir_x = data->player.dir_x;
old_plane_x = data->player.plane_x;
data->player.dir_x = data->player.dir_x * cos(data->player.rotation) -
data->player.dir_y * sin(data->player.rotation);
data->player.dir_y = old_dir_x * sin(data->player.rotation) +
data->player.dir_y * cos(data->player.rotation);
data->player.plane_x = data->player.plane_x * cos(data->player.rotation) -
data->player.plane_y * sin(data->player.rotation);
data->player.plane_y = old_plane_x * sin(data->player.rotation) +
data->player.plane_y * cos(data->player.rotation);
}
|
C
|
#ifndef __TVECTOR_ELEMENT_H__
#define __TVECTOR_ELEMENT_H__
/** \file TVectorElement.h
* \brief Definice typu Basic VectorElement a implementace API
* \author Petyovský
* \version 2021
* $Id: TVectorElement.h 1023 2021-02-08 09:42:15Z petyovsky $
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "check.h"
/** \defgroup TVectorElement 1. VectorElement
* \brief Definice datového typu VectorElement a jeho funkcí
* \{
*/
typedef int TVectorElement; ///< Definice typu VectorElement
#define TVECTOR_ELEMENT_FRMSTR "%d" ///< Definice formátovacího řetězce pro souborové operace s typem VectorElement
/** \brief Porovnání dvou elementů
* \details Provede trojcestné porovnání hodnot dvou elementů, předaných pomocí ukazatelů.
* \param[in] aLeft Ukazatel na levou porovnávanou hodnotu (tzv. LHS - Left Hand Side)
* \param[in] aRight Ukazatel na pravou porovnávanou hodnotu (tzv. RHS - Right Hand Side)
* \retval -1 Pokud (LHS < RHS)
* \retval 0 Pokud (LHS = RHS)
* \retval +1 Pokud (LHS > RHS)
* \attention Funkce ověřuje platnost obou ukazatelů \b pouze při překladu v režimu `Debug`, kdy pomocí `assert` hlásí běhovou chybu!
*/
static inline int vector_element_comparator(const TVectorElement *aLeft, const TVectorElement *aRight)
{
assert(aLeft);
assert(aRight);
if(*aLeft == *aRight)
return 0;
if(*aLeft < *aRight)
return -1;
return 1;
}
/** \brief Načtení elementu ze souboru
* \details Načte hodnotu elementu z předem otevřeného souboru.
* \param[in,out] aElement Ukazatel na místo v paměti určené pro načtení hodnoty
* \param[in,out] aInputFile Ukazatel na soubor otevřený v módu pro čtení
* \return \c true pokud byla hodnota elementu ze souboru úspěšně načtena
* \attention Funkce ověřuje platnost obou ukazatelů \b pouze při překladu v režimu `Debug`, kdy pomocí `assert` hlásí běhovou chybu!
*/
static inline bool vector_element_load_file(TVectorElement *aElement, FILE *aInputFile)
{
assert(aElement);
assert(aInputFile);
return fscanf(aInputFile, TVECTOR_ELEMENT_FRMSTR, aElement) == 1;
}
/** \brief Uložení elementu do souboru
* \details Uloží hodnotu elementu do předem otevřeného souboru.
* \param[in] aElement Hodnota elementu určená pro uložení do souboru
* \param[in,out] aOutputFile Ukazatel na soubor otevřený v módu pro zápis
* \return \c true pokud byla hodnota elementu do souboru úspěšně uložena
* \attention Funkce ověřuje platnost ukazatele \p aOutputFile \b pouze při překladu v režimu `Debug`, kdy pomocí `assert` hlásí běhovou chybu!
*/
static inline bool vector_element_store_file(TVectorElement aElement, FILE *aOutputFile)
{
assert(aOutputFile);
return fprintf(aOutputFile, TVECTOR_ELEMENT_FRMSTR " ", aElement) >= 0;
}
/** \brief Vrací nový element s náhodnou hodnotou
* \details Vytváří a vrací nový element inicializovaný pomocí náhodné hodnoty.
* \return Nový element obsahujicí náhodnou hodnotu
*/
static inline TVectorElement vector_element_random_value(void)
{
return (TVectorElement) { (TVectorElement)rand() };
}
/** \} TVectorElement */
#endif /* __TVECTOR_ELEMENT_H__ */
|
C
|
#include <stdlib.h>
#include <stdbool.h>
#include "cval.h"
#include "util.h"
cval *_make_map_(int len)
{
cval *cval = alloc(cval);
_set_type(cval, t_map);
_zero(&(cval->v_map));
_init_map(&(cval->v_map), len);
return cval;
}
void _init_map(map *m, int len)
{
m->len = m->factor = len;
if (len <= 0)
{
len = m->factor = 7;
}
m->base = calloc(len, sizeof(struct mapentry *));
checkMem(m->base);
memset(m->base, 0, len * sizeof(struct mapentry *));
}
void mapSet(map *m, cval *k, cval *v)
{
if (m->len > 2 * m->factor)
{
int newFactor = m->factor * 2 + 1;
//todo
}
//todo P(k)P(v)
unsigned h = hash(k);
int index = h % m->factor;
mapentry *head = m->base[index];
mapentry *e = _makeMapEntry(k, v);
if (head == NULL)
{
m->base[index] = e;
}
else
{
//search
mapentry *tail = _linklist_tail(head);
tail->next = e;
}
}
mapentry *_makeMapEntry(cval *key, cval *value)
{
mapentry *e = alloc(mapentry);
e->key = key;
e->value = value;
return e;
}
mapentry *_linklist_tail(mapentry *head)
{
notNull(head);
mapentry *tail = head;
for (;head; head = head->next)
tail = head;
return tail;
}
unsigned hash(cval *v)
{
switch (type(v))
{
case t_int:
return v->v_int;
case t_float:
return _hash_float(v->v_float);
case t_byte:
return _hash_byte(v->v_byte);
case t_bool:
return _hash_bool(v->v_bool);
case t_str:
return _hash_str(v->v_str);
case t_array:
error("array can not be hashed");
case t_slice:
error("slice can not be hashed");
case t_map:
error("map can not be hashed");
default:
shouldNotHere();
}
}
unsigned _hash_float(float v)
{
unsigned a;
memcpy(&a, &v, sizeof(a));
return a;
}
unsigned _hash_byte(byte v)
{
return v;
}
unsigned _hash_bool(bool v)
{
return v;
}
unsigned _hash_str(str v)
{
const int p = 31;
const int m = 1e9 + 9;
long long hash_value = 0;
long long p_pow = 1;
_Generic((v),
array
: arrayLen(v),
slice
: sliceLen(v),
map
: mapLen(v));
for (int i = 0; i < len(v); i++)
{
char c = v.base->v_array.base[i];
hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m;
p_pow = (p_pow * p) % m;
}
return hash_value;
}
|
C
|
/*
** SkyShaders.c
**
** Functions that shade rays that enter the sky.
**
** 18 Aug 1992 - Created - J. Terrell
*/
#include "headers/tracer.h"
/* skyshader_simple() ; simple single color background */
void skyshader_simple(struct Ray *ray)
{
ray->ci[0] = gl_env->BackDropColor[0];
ray->ci[1] = gl_env->BackDropColor[1];
ray->ci[2] = gl_env->BackDropColor[2];
}
/* skyshader_gradient() ; simple color gradient */
void skyshader_gradient(struct Ray *ray)
{
float length,zenith,horiz;
length = 1.0 / MDOT(ray->d,ray->d);
zenith = (ray->d[1] * ray->d[1]) * length;
horiz = (ray->d[0] * ray->d[0] + ray->d[2] * ray->d[2]) * length;
if(ray->d[1] > 0.0) {
ray->ci[0] = gl_env->ZenithColor[0] * zenith + gl_env->HorizonColor[0] * horiz;
ray->ci[1] = gl_env->ZenithColor[1] * zenith + gl_env->HorizonColor[1] * horiz;
ray->ci[2] = gl_env->ZenithColor[2] * zenith + gl_env->HorizonColor[2] * horiz;
}
else {
ray->ci[0] = gl_env->AZenithColor[0] * zenith + gl_env->HorizonColor[0] * horiz;
ray->ci[1] = gl_env->AZenithColor[1] * zenith + gl_env->HorizonColor[1] * horiz;
ray->ci[2] = gl_env->AZenithColor[2] * zenith + gl_env->HorizonColor[2] * horiz;
}
}
/* skyshader_environmentmap() ; Spherical environment map. */
void skyshader_environmentmap(struct Ray *ray)
{
im_ProcessEnvironmentMap(&gl_env->EnvironmentMap,ray);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <termios.h>
int pid; //mufide lal control -c
void init()
{
printf("\n\n\n\n******************"
"************************");
printf("\n\n\n\t****Welcome to ourshell****");
printf("\n\n\n\n*******************"
"***********************");
printf("\n");
}
// Method to change directory
int changeDirectory(char* args[])
{
// If only cd
if (args[1] == NULL)//iza ketb cd wl args 1 = null y3n cd wenter bekhdo home
{
chdir(getenv("HOME"));
return 1;
}
else
{
if (chdir(args[1]) == -1)
{
printf(" %s: no such directory\n", args[1]);
return -1;
}
else
return 1;
}
return 0;
}
void fPipe(char *command[])
{
int p[2];
pipe (p);
int pid;
char *pa[2];
int pp,status;
pid=fork();
if(pid == 0)
{
pa[0]=command[0];
pa[1]=NULL;
pp=dup(1);
close(1);
close(p[0]);
dup2(p[1],1);
execvp(command[0],pa);
}
else
{
wait(NULL);
pid=fork();
if(!pid)
{
pa[0]=command[2];
pa[1]=NULL;
close(0);
close(p[1]);
dup(p[0]);
if(execvp(command[2],pa)==-1)
printf("command not identified");
}
else
{
close(p[1]);
close(p[0]);
wait(NULL);
}
}
fflush(stdout);
}
void fPipe1(char * args[], char* inputFile, char* outputFile, int option)
{
int status;//kermel 23mel wait
int fileDescriptor; //kermel huwe byft7 fi lfileee
FILE *f;
pid=fork();//krmel leben huwe bdo ysht8l she8l msshh lbay
if(pid==0)//bel child
{
// >
if (option == 0){//y3ne eno yktob be aleb lfile ( o_trunk st3mlta kreml mrat lma kena nktobb eb3t > w7de y3melappend fa searched and found that hay admn)
fileDescriptor = open(outputFile, O_CREAT | O_TRUNC | O_WRONLY ); /// ftht lfile ana 3m ektb bl outputfile ,mode o_creat , otrunnc,o_wrony
close(1); //sakrt lsheshe
dup(fileDescriptor); // 7atet filedescreptor be aleb lsheshe y3ne 3m yktop fiiiii
if (execvp(args[0],args)==-1)
{//iza keteb command 8alat
printf("%s Command not found \n",args[0]);
kill(getpid(),SIGTERM); //be2toul haleee krmel lexit ma atlitlo ma fwta
}
close(fileDescriptor);
exit(1);
}
else if (option == 1){ // < > 3m tu2ra mn fil wtkbon be file tene
fileDescriptor = open(inputFile, O_RDONLY); //awal step ino ou2ra mn file fa fat7too ismo inout file wl mode readonly
if(fileDescriptor != -1)
{
dup2(fileDescriptor, STDIN_FILENO);
fileDescriptor = open(outputFile, O_CREAT | O_TRUNC | O_WRONLY);
dup2(fileDescriptor, STDOUT_FILENO);
if (execvp(args[0],args)==-1)// 3mlt exec
{
printf("%s Command not found \n",args[0]);
kill(getpid(),SIGTERM);
}
}
else
printf("No File Name %s \n",inputFile);
close(fileDescriptor);
exit(1);
}
else if (option == 2){// >> append zid 3l file
fileDescriptor = open(outputFile, O_CREAT | O_APPEND | O_WRONLY ); // o_append o_write only iza ma fi shi bktob
close(1);
dup(fileDescriptor);
if (execvp(args[0],args)==-1)
{
printf("%s Command not found \n",args[0]);
kill(getpid(),SIGTERM);
}
close(fileDescriptor);
exit(1);
}
else if (option == 3){// < sort mn file bou3rd 3l sheshe
fileDescriptor = open(inputFile, O_RDONLY);
if(fileDescriptor != -1)
{
close(0);// skrna lkeyboard
dup(fileDescriptor);
if (execvp(args[0],args)==-1)
{
printf("%s Command not found \n",args[0]);
kill(getpid(),SIGTERM);
}
}
else
printf("No File Name %s \n",inputFile);
close(fileDescriptor);
exit(1);
}
}
wait(&status);// krmelll bayo lhye lshelll yntrooooo lken 5las she8elll
}
void fExec(char **args,int bg)
{
int status;
int n,m;
pid=fork();
if(pid==0)
{
if (execvp(args[0],args)==-1)
{
printf("%s Command not found \n",args[0]);
kill(getpid(),SIGTERM);
}
}
if(bg==0)// keremelo ma keteb & so ana motara ontro
wait(&status);
}
void fExec1(char **args,char * args1)
{
int status;
int n,m;
char * temp[10];
temp[0]=args1;
temp[1]=NULL;
pid=fork();
if(pid==0)
{
if (execvp(args[0],args)==-1)
{
printf("%s Command not found \n",args[0]);
kill(getpid(),SIGTERM);
}
}
else{
pid=fork();
if(pid==0)
{
if (execvp(temp[0],temp)==-1)
{
printf("%s Command not found \n",args[0]);
kill(getpid(),SIGTERM);
}
}
}
//parent
wait(&status);
wait(&status);
}
int Handler(char * args[]){
int i=0;
int j=0;
int f;
int s;
int bg=0; // test of &
char *args1[30];
while ( args[j] != NULL) //mst3mla bs b pipe t3il l < w 3yleta wl &
{
if ( (strcmp(args[j],">") == 0) || (strcmp(args[j],"<") == 0) || (strcmp(args[j],">>") == 0) || (strcmp(args[j],"&") == 0)){
j++;
break;
}
args1[j] = args[j];
j++;
}
args1[j]=NULL;// awal command la abel l carac special eza kenet mawjude
if(strcmp(args[0],"exit") == 0)
{
printf("\n\n\n\n******************"
"************************");
printf("\n\n\n\t****Bye Bye****");
printf("\n\n\n\n*******************"
"***********************");
printf("\n");
exit(0);
}
else if (strcmp(args[0],"clear") == 0)
system("clear");
else if (strcmp(args[0],"cd") == 0)
changeDirectory(args);
else
{
while (args[i] != NULL )//i=0
{
if (strcmp(args[i],"&") == 0)
{
if( args[i+1] != NULL )
{//iza keteb and wb3da shi bt3ml execute ll tnen<3
fExec1(args1,args[i+1]);
return 1;
}
else
{
bg=1;
}
}
else if (strcmp(args[i],"|") == 0)
{
fPipe(args);
return 1;
}
else if (strcmp(args[i],"<") == 0)
{
if (args[i+1] != NULL && args[i+2]== NULL )
{
//args1 m2sam fi awal tu2sime , args i+1 keteb lfile lbde ektob menooo wll null l2no 3m 2u22ra mnn file iza 3m bektob b3tiya value
fPipe1(args1,args[i+1],NULL,3);//null l2no ma bde ektob be mahal hon 3m jib mn l args i+1... le 3 hye option ino tu2r wt3ml execute
return 1;
}
else if(args[i+1] != NULL && strcmp(args[i+2],">")==0 && args[i+3]!=NULL )
{
//a args1<b args i+1>c args i+3
fPipe1(args1,args[i+1],args[i+3],1);
return 1;
}
else
{
printf("Not enough input arguments\n");
return -1;
}
}
else if (strcmp(args[i],">") == 0)//hon 3m bektob be fileee
{
if (args[i+1] == NULL)
{
printf("Not enough input arguments\n");//lakbar msln ketbe akbr bala esem lfile
return -1;
}
fPipe1(args1,NULL,args[i+1],0);// option 0 l null l2no mfi inputtt
return 1;
}
else if (strcmp(args[i],">>") == 0)//bziddd 3lyhonn
{
if (args[i+1] == NULL){
printf("Not enough input arguments\n");
return -1;
}
fPipe1(args1,NULL,args[i+1],2);
return 1;
}
i++;
}
//bkun khalas kel l loop w ma le2a charactere special
fExec(args1,bg);// akbr aaz8r aw 3moud or & bikun already nb3t 3l fct le2elo
}
return 1;
}
void signalInt(int pid)
{
int i;
i=kill(pid,SIGTERM);// fiya value knt m3tito yeee mn l maain iza msln de8re 3melet ctr c mn awal ma ftht lshell so ta ma y3tin error
//bikun by deafult 3tito -10
if(i == 0)
{
printf("the child dead");// iza n2tl lwlad
}
else// ma n2tl iza ma ktbe shi w3mlt ctr c
{
printf("\t continue");
printDir();
printf(">>>>>>");
fflush(stdout);
}
}
void printDir()
{
char cwd[1024];
getcwd(cwd, sizeof(cwd));
printf("\nDir: %s", cwd);
}
int main(int argc, char *argv[], char ** envp)
{
char line[1024]; //lal input line
char * tokens[256];// 3m hot fi ltou2sim
int numTokens;
pid = -10; // initalisation
init();// lprompt
signal(SIGINT,signalInt);//control c handler
while(1)
{
printDir();
printf(">>>>>>");
// We empty the line buffer
memset ( line, '\0', 1024);
// We wait for user input
fgets(line, 1024, stdin);
//new line
if((tokens[0] = strtok(line," \n\t")) == NULL)
continue;
numTokens = 1;
while((tokens[numTokens] = strtok(NULL, " \n\t")) != NULL)
numTokens++;
Handler(tokens);
}
exit(0);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct process
{
int pid ;
int at ;
int bt ;
int wt ;
int ct ;
int tat ;
};
int findWaitingTime(struct process *A , int n)
{
int sum = 0 ;
for(int i = 0 ; i < n ; i++)
{
A[i].wt = A[i].tat - A[i].bt ;
sum = sum + A[i].wt;
}
return sum;
}
void findCompletionTime(struct process *A , int n)
{
A[0].ct = A[0].bt;
for(int i = 1 ; i < n ; i++)
{
if(A[i-1].ct < A[i].at)
{
A[i].ct = A[i].at + A[i].bt;
continue;
}
A[i].ct = A[i-1].ct + A[i].bt;
}
}
int findTurnAroundTime(struct process *A , int n)
{
int sum = 0;
for(int i = 0 ; i < n ; i++)
{
A[i].tat = A[i].ct - A[i].at;
sum = sum + A[i].tat;
}
return sum;
}
void sort_by_ArrivalTime(struct process *A , int n)
{
for(int i = 0 ; i < n ; i++)
{
int pos = i ;
for(int j = i+1 ; j < n ; j++)
{
if(A[pos].at > A[j].at)
pos = j ;
}
struct process v = A[pos];
A[pos] = A[i];
A[i] = v;
}
}
void findAvgTime(struct process *A , int n)
{
findCompletionTime(A ,n);
int tot_tat = findTurnAroundTime(A,n);
int tot_wt = findWaitingTime(A,n);
printf("\nAverage waiting time : %f" , (float)tot_wt/n );
printf("\nAverage turnaround time : %f" , (float)tot_tat/n );
}
void display(struct process *A , int n)
{
printf("\nProcess ID\tArrival Time\tBurst Time\tCompletion Time\tTurnaround Time\tWaiting Time");
for(int i = 0 ; i<n ; i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d" , A[i].pid, A[i].at , A[i].bt , A[i].ct , A[i].tat , A[i].wt);
}
int main()
{
//int n = 0 ;
// printf("\nEnter the number of processes : ");
// scanf("%d" , &n);
// struct process proc[n] ;
// for(int i = 0 ; i<n ; i++)
// {
// printf("\nEnter the arrival time and burst time for process id %d: " , (i+1));
// proc[i].pid = i+1;
// scanf("%d %d" , &proc[i].at , &proc[i].bt);
// proc[i].wt=0;
// proc[i].ct = 0 ;
// proc[i].tat = 0;
// }
struct process proc[] = {{1,0,4,0,0,0},{2,1,3,0,0,0},{3,2,1,0,0,0},{4,3,2,0,0,0},{5,11,5,0,0,0}};
int n = sizeof proc / sizeof proc[0];
printf("\nInitial State");
display(proc,n);
sort_by_ArrivalTime(proc,n);
printf("\nAfter execution");
findAvgTime(proc,n);
display(proc,n);
}
|
C
|
/*
* Program to implement basic operations on stack
* Compilation: stack_program.c
* Exicution: ./a.out
*
* @Sahil Bhatiwal (1910990683) , 2- 08- 2021
* Assignment: Day2_coding_Assignment (Quesiton 1);
*
*/
#include<stdio.h>
//push(insertion ) function
void push(int arr[], int *top) {
int n;
printf("Enter the number: ");
scanf("%d",&n);
arr[++ (*top)] = n;
printf("%d pushed to the array\n",n);
}
//pop(deletion) function
void pop(int *top) {
-- *top;
printf("value poped\n");
}
//peek function which prints the value at top
void peek(int arr[], int top) {
printf("%d\n",arr[top]);
}
//is_empty function checks if the array is empty or not
void is_empty(int top) {
if(top == -1){
printf("Stack is empty\n");
}
else {
printf("Stack is not empty\n");
}
}
//is_full function checks if the array is full or not
void is_full(int top,int size) {
if(top == size - 1) {
printf("Stack is full\n");
}
else {
printf("Stack is not full\n");
}
}
int main() {
int querry = 0, size = 0;
printf("Enter the size of array: ");
scanf("%d",&size);
int arr[size];
int top = -1;
while(querry != 7)
{
printf("\n\nEnter:\n1 push\n2 pop\n3 peek\n4 Is empty\n5 Is full");
printf("\n6 Print complexity for each program\n7 Exit\n Enter the querry:");
scanf("%d",&querry);
printf("\n\n");
if( querry == 1) {
if(top < size-1) {
push(arr, &top);
}
else {
printf("StackOverflow\n");
}
}
else if( querry == 2) {
if(top > -1) {
pop(&top);
}
else {
printf("StackUnderflow\n");
}
}
else if( querry == 3) {
peek(arr, top);
}
else if( querry == 4) {
is_empty(top);
}
else if( querry == 5) {
is_full(top, size);
}
else if( querry == 6) {
printf("Complexity of push is O(1)\n");
printf("Complexity of pop is O(1)\n");
printf("Complexity of peek is O(1)\n");
printf("Complexity of is_empty is O(1)\n");
printf("Complexity of is_full is O(1)\n\n");
}
else if( querry == 7) {
printf("Exit command exicuted\n");
}
else {
printf("Please enter a valid querry");
}
}
return 0;
}
|
C
|
/*
* segmentize.c
*
* Created on: 10 aug 2012
* Author: Wolftower
*
* Description
* This library implements a function that segments
* chromosome/substring files into smaller chunks
*/
#include "segmentize.h"
void seq2chunks(char* sequence, char* seqHeader, char* outputDir, const char* nopathFile, int offset, int* chunkIndex){
int windowSize = 200;
int stepSize = 20;
int currentStep = 0;
int windowsPerChunk = 50000;
int windowIndex;
char window[203];
int breakSwitch = 0;
int seqLen = strlen(sequence);
int nucIndex;
FILE *chunk = NULL;
for (windowIndex = 0; windowIndex * stepSize < seqLen; windowIndex++) {
int windowStart = windowIndex * stepSize;
//Create new chunk
if (windowIndex % windowsPerChunk == 0) {
*chunkIndex = *chunkIndex + 1;
char indexBuffer[10];
char chunkName[100];
sprintf(indexBuffer, "%d", *chunkIndex);
strcpy(chunkName, outputDir);
strcat(chunkName, nopathFile);
strcat(chunkName, "_chunk");
strcat(chunkName, indexBuffer);
strcat(chunkName, ".txt");
if (chunk != NULL) {
fclose(chunk);
}
if (!(chunk = fopen(chunkName, "wt"))) {
printf("GenoScan error: Unable to write '%s' chunk\n", chunkName);
exit(EXIT_FAILURE);
}
}
//Reset window
strcpy(window, "");
//Copy nucleotides from sequence
int windowStop;
if (seqLen - windowStart < windowSize){
windowStop = seqLen - windowStart;
breakSwitch = 1;
}
else {
windowStop = windowSize;
}
for (nucIndex = 0; nucIndex < windowStop; nucIndex++) {
window[nucIndex] = sequence[windowStart + nucIndex];
}
window[nucIndex] = '\n';
window[nucIndex+1] = '\n';
window[nucIndex+2] = '\0';
//Create header
char header[200];
char nucStart[100];
char nucEnd[100];
int headerStart = windowStart + offset;
int headerEnd = windowStart + offset + nucIndex;
sprintf(nucStart, "%d", headerStart);
sprintf(nucEnd, "%d", headerEnd);
strcpy(header, seqHeader);
strcat(header, " | pos ");
strcat(header, nucStart);
strcat(header, "-");
strcat(header, nucEnd);
strcat(header, "\n");
//Write to file
fwrite(header, sizeof(char), strlen(header), chunk);
fwrite(window, sizeof(char), strlen(window), chunk);
if (breakSwitch) {
break;
}
}
fclose(chunk);
}
int segmentize(int* filterFlags, char* manifest, char* outputDir, int VERBOSE) {
FILE *inputFile;
int numFiles = 0;
char line[200];
char fileArray[100][100];
if (!(inputFile = fopen(manifest, "rt"))) {
printf("GenoScan error: Input manifest '%s' could not be read\n", manifest);
exit(EXIT_FAILURE);
}
//Read input file
while (fgets(line, sizeof(line), inputFile) != NULL) {
int len = strlen(line);
if(line[len-1] == '\n'){
strncpy(fileArray[numFiles], line, len-1);
fileArray[numFiles][len-1] = '\0';
}
else{
strcpy(fileArray[numFiles], line);
}
numFiles++;
}
numFiles = numFiles / 2;
fclose(inputFile);
//Read sequence files
int file;
int fileCounter = -1;
int seqMemory = 280000000;
char* sequence = malloc(seqMemory * sizeof(char));
for (file = 0; file < numFiles * 2; file+=2) {
strcpy(sequence, "");
fileCounter++;
char seqfile[100];
char nopathFile[100];
strcpy(seqfile, fileArray[file]);
strcpy(nopathFile, fileArray[file+1]);
int fileIndex = fileCounter + 1;
if (VERBOSE) {
printf(" Segmentizing file %d/%d\r", fileIndex, numFiles);
}
fflush(stdout);
char buffer[200];
int nucIndex;
FILE *fp;
char fileHeader[200];
//Open sequence file
if (!(fp = fopen(seqfile, "rt"))){
printf("GenoScan error: Unable to read input sequence file '%s'\n", seqfile);
exit(EXIT_FAILURE);
}
//Segmentize chromosome sequence
int chunkIndex = 0;
if(!filterFlags[fileCounter]){
fgets(line, sizeof(line), fp);
strncpy(fileHeader, line, strlen(line) - 1);
fileHeader[strlen(line) - 1] = '\0';
int nucRead = 0;
while(fgets(line, sizeof(line), fp) != NULL){
int length = strlen(line);
strcpy(buffer, line);
int nucBuffer = 0;
for (nucIndex = 0; nucIndex < length; nucIndex++) {
if (buffer[nucIndex] != '\n') {
sequence[nucRead + nucIndex] = buffer[nucIndex];
nucBuffer++;
}
}
nucRead += nucBuffer;
}
seq2chunks(sequence, fileHeader, outputDir, nopathFile, 1, &chunkIndex);
}
//Segmentize substring sequences
else{
while(fgets(line, sizeof(line), fp) != NULL){
strncpy(fileHeader, line, strlen(line) - 1);
fileHeader[strlen(line) - 1] = '\0';
int subStart;
fgets(line, sizeof(line), fp);
subStart = atoi(line);
fgets(line, sizeof(line), fp);
fgets(sequence, seqMemory, fp);
seq2chunks(sequence, fileHeader, outputDir, nopathFile, subStart, &chunkIndex);
strcpy(sequence, "");
}
}
fclose(fp);
}
//Free sequnce memory
free(sequence);
if(VERBOSE){
printf("\n");
}
return 1;
}
|
C
|
#include <stdio.h>
#include <string.h>
char code[10];
void putcode();
int main()
{
#ifndef ONLINE_JUDGE
freopen("11223_O dah dah dah!_01.inp","r",stdin);
#endif
int t, i;
char c, l;
scanf(" %d ",&t);
for(i=1; i<=t; ++i)
{
if(i>1) putchar('\n');
printf("Message #%d\n", i);
l = 0;
while((c=getchar())!='\n')
if(c=='.' || c=='-') code[l++] = c;
else if(l>0) l=code[l]=0, putcode();
else putchar(' ');
l=code[l]=0, putcode();
putchar('\n');
}
return 0;
}
void putcode()
{
if(!strcmp(code, ".-")) putchar('A');
else if(!strcmp(code, "-...")) putchar('B');
else if(!strcmp(code, "-.-.")) putchar('C');
else if(!strcmp(code, "-..")) putchar('D');
else if(!strcmp(code, ".")) putchar('E');
else if(!strcmp(code, "..-.")) putchar('F');
else if(!strcmp(code, "--.")) putchar('G');
else if(!strcmp(code, "....")) putchar('H');
else if(!strcmp(code, "..")) putchar('I');
else if(!strcmp(code, ".---")) putchar('J');
else if(!strcmp(code, "-.-")) putchar('K');
else if(!strcmp(code, ".-..")) putchar('L');
else if(!strcmp(code, "--")) putchar('M');
else if(!strcmp(code, "-.")) putchar('N');
else if(!strcmp(code, "---")) putchar('O');
else if(!strcmp(code, ".--.")) putchar('P');
else if(!strcmp(code, "--.-")) putchar('Q');
else if(!strcmp(code, ".-.")) putchar('R');
else if(!strcmp(code, "...")) putchar('S');
else if(!strcmp(code, "-")) putchar('T');
else if(!strcmp(code, "..-")) putchar('U');
else if(!strcmp(code, "...-")) putchar('V');
else if(!strcmp(code, ".--")) putchar('W');
else if(!strcmp(code, "-..-")) putchar('X');
else if(!strcmp(code, "-.--")) putchar('Y');
else if(!strcmp(code, "--..")) putchar('Z');
else if(!strcmp(code, "-----")) putchar('0');
else if(!strcmp(code, ".----")) putchar('1');
else if(!strcmp(code, "..---")) putchar('2');
else if(!strcmp(code, "...--")) putchar('3');
else if(!strcmp(code, "....-")) putchar('4');
else if(!strcmp(code, ".....")) putchar('5');
else if(!strcmp(code, "-....")) putchar('6');
else if(!strcmp(code, "--...")) putchar('7');
else if(!strcmp(code, "---..")) putchar('8');
else if(!strcmp(code, "----.")) putchar('9');
else if(!strcmp(code, ".-.-.-")) putchar('.');
else if(!strcmp(code, "--..--")) putchar(',');
else if(!strcmp(code, "..--..")) putchar('\?');
else if(!strcmp(code, ".----.")) putchar('\'');
else if(!strcmp(code, "-.-.--")) putchar('!');
else if(!strcmp(code, "-..-.")) putchar('/');
else if(!strcmp(code, "-.--.")) putchar('(');
else if(!strcmp(code, "-.--.-")) putchar(')');
else if(!strcmp(code, ".-...")) putchar('&');
else if(!strcmp(code, "---...")) putchar(':');
else if(!strcmp(code, "-.-.-.")) putchar(';');
else if(!strcmp(code, "-...-")) putchar('=');
else if(!strcmp(code, ".-.-.")) putchar('+');
else if(!strcmp(code, "-....-")) putchar('-');
else if(!strcmp(code, "..--.-")) putchar('_');
else if(!strcmp(code, ".-..-.")) putchar('\"');
else if(!strcmp(code, ".--.-.")) putchar('@');
return;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int sayi;
printf("Hello world!\n");
printf("Merhaba canim\n");
printf("heycorversenebor");
printf("sayi syle bana\n");
scanf("%d",&sayi);
printf("girdiginiz sayiyi begendim.\n");
return 0;
}
|
C
|
/* See LICENSE file for copyright and license terms. */
/* file.h: dealing with entire files. */
#ifndef EPAI_FILE_H
#define EPAI_FILE_H
/* to be used for byte buffers; text strings should use regular char type */
typedef unsigned char epai_byte_t;
typedef enum {
EPAI_ENDIAN_NATIVE,
EPAI_ENDIAN_LITTLE,
EPAI_ENDIAN_BIG
} epai_endian_t;
typedef struct {
epai_endian_t endian;
int version;
int num_sections;
/* Pointers to all sections in their actual file order. */
epai_section_t** sections;
} epai_file_t;
/* free file struct */
extern void epai_file_free(epai_file_t*);
/* create new file struct */
extern epai_error_t epai_file_new(epai_file_t**, epai_endian_t);
/* add a section to a file */
extern epai_error_t epai_file_add_section(epai_file_t*, epai_section_t*);
/* validate a file structure */
extern epai_error_t epai_file_validate_struct(epai_file_t*);
#endif /* EPAI_FILE_H */
|
C
|
/* Comentario de
varias lineas */
// Esto es un comentario de un a linea
int x;
int y;
char c;
void mult(){
int z;
x = 2;
y = 3;
z = x * y;
printf("El resultado es %d", z);
}
char x;
void rest(){
int z;
x = 2;
y = 3;
z = x - y;
printf("El resultado es %d", z);
}
|
C
|
#include "ft_library.h"
char * ft_strjoin(char const *s1, char const *s2){
int s1_len = ft_strlen(s1);
int s2_len = ft_strlen(s1);
char * join_str = (char *)malloc((s1_len + s2_len +1) * sizeof(char));
if (join_str == NULL)
return NULL;
ft_strcpy(join_str, s1);
ft_strcpy(&join_str[s1_len], s2);
return join_str;
}
|
C
|
struct Rectangle{
int length;
int breadth;
};
int main(){
struct Rectangle r; /*declaration*/
struct Rectangle r={10,5}; /*initialization*/
r.length = 15;
r.breadth = 10;
printf("Area of Rectangle is %d", r.length*r.breadth);
struct Rectangle *p=&r;
/*Two ways of accessing*/
(*p).length = 20;
p->length = 21;
}
|
C
|
// Example from Cousot Habwachs POPL 1978
// Heap sort, where array operations are abstracted away
// to get a non-deterministic scalar program
// expected results: with polyhedra, no assertion failure
int L,R,I,J;
int N = rand(1,100000); // array size
L = N/2 + 1;
R = N;
if (L >= 2) {
L = L - 1;
// model the assignment "K = TAB[L]"
assert(1 <= L && L <= N);
}
else {
// model the assignments "K = TAB[R]; TAB[R] = TAB[1]"
assert(1 <= R && R <= N);
assert(1 <= 1 && 1 <= N);
R = R - 1;
}
while (R >= 2) {
I = L;
J = 2*I;
while (J <= R && rand(0,1)==0) {
if (J <= R-1) {
// model the comparison "TAB[J] < TAB[J+1]"
assert(1 <= J && J <= N);
assert(1 <= (J+1) && (J+1) <= N);
if (rand(0,1)==0) { J = J + 1; }
}
// model the comparison "K < TAB[J]"
assert(1 <= J && J <= N);
if (rand(0,1)==0) {
// model the assignment "TAB[I] = TAB[J]"
assert(1 <= I && I <= N);
assert(1 <= J && J <= N);
I = J;
J = 2*J;
}
}
// model the assignment "TAB[I] = K"
assert(1 <= I && I <= N);
if (L >= 2) {
L = L - 1;
// model the assignment "K = TAB[L]"
assert(1 <= L && L <= N);
}
else {
// model the assignments "K = TAB[R]; TAB[R] = TAB[1]"
assert(1 <= R && R <= N);
assert(1 <= 1 && 1 <= N);
R = R - 1;
}
// model the assignment "TAB[1] = K"
assert(1 <= 1 && 1 <= N);
}
|
C
|
#include "barrier.h"
#include "qsim_magic.h"
#include <stdatomic.h>
#include <stdlib.h>
#define KB(x) ((x) << 10)
#define MB(x) (KB(x) << 10)
#define size MB(16)
#define QSIM_ENABLE 1
#define CACHE_LINE_SIZE 64
int main()
{
unsigned long max_idx = size / sizeof(atomic_int);
atomic_int *array;
array = (atomic_int*)malloc(size);
#if QSIM_ENABLE
qsim_magic_enable();
#endif
for (int i = 0; i < 1; i++)
for (unsigned long j = 0; j < max_idx; j+= CACHE_LINE_SIZE / sizeof(atomic_int))
atomic_store_explicit(array+j, j*i, memory_order_seq_cst);
#if QSIM_ENABLE
qsim_magic_disable();
#endif
}
|
C
|
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
int main()
{
int fd = open ("data.txt", O_RDWR | O_CREAT | O_TRUNC, 0666);
if (fd == -1)
{
perror ("open");
exit (EXIT_FAILURE);
}
struct flock lock;
lock.l_type = F_WRLCK; //定义锁操作的类型为加写锁
lock.l_whence = SEEK_CUR; //定义锁区偏移起点为文件当前位置
lock.l_start = 10; //定义锁区从文件头开始计算的偏移 10 个字节
lock.l_len = 0; //定义锁区字节长度到文件结尾,即仅文件开头的 10 个字节不加锁
lock.l_pid = -1; //定义加锁进程标识为自动设置
if (fcntl (fd, F_SETLK, &lock) == -1) //F_SETLK 为非阻塞模式,是指进程遇锁,立即以错误返回,并设错误码为EAGAIN
{
if (errno != EAGAIN)
{
perror ("fcntl");
exit (EXIT_FAILURE);
}
printf ("暂时不能加锁,稍后再试...\n");
}
if (close (fd) == -1)
{
perror ("close");
exit (EXIT_FAILURE);
}
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_4__ TYPE_1__ ;
/* Type definitions */
struct ledger_entry {scalar_t__ le_debit; scalar_t__ le_credit; int le_flags; } ;
typedef TYPE_1__* ledger_t ;
typedef scalar_t__ ledger_amount_t ;
typedef int /*<<< orphan*/ kern_return_t ;
struct TYPE_4__ {struct ledger_entry* l_entries; } ;
/* Variables and functions */
int /*<<< orphan*/ ENTRY_VALID (TYPE_1__*,int) ;
int /*<<< orphan*/ KERN_INVALID_VALUE ;
int /*<<< orphan*/ KERN_SUCCESS ;
int LF_TRACK_CREDIT_ONLY ;
int /*<<< orphan*/ OSCompareAndSwap64 (scalar_t__,scalar_t__,scalar_t__*) ;
int /*<<< orphan*/ assert (int) ;
int /*<<< orphan*/ current_thread () ;
int /*<<< orphan*/ lprintf (char*) ;
kern_return_t
ledger_zero_balance(ledger_t ledger, int entry)
{
struct ledger_entry *le;
ledger_amount_t debit, credit;
if (!ENTRY_VALID(ledger, entry))
return (KERN_INVALID_VALUE);
le = &ledger->l_entries[entry];
top:
debit = le->le_debit;
credit = le->le_credit;
if (le->le_flags & LF_TRACK_CREDIT_ONLY) {
assert(le->le_debit == 0);
if (!OSCompareAndSwap64(credit, 0, &le->le_credit)) {
goto top;
}
lprintf(("%p zeroed %lld->%lld\n", current_thread(), le->le_credit, 0));
} else if (credit > debit) {
if (!OSCompareAndSwap64(debit, credit, &le->le_debit))
goto top;
lprintf(("%p zeroed %lld->%lld\n", current_thread(), le->le_debit, le->le_credit));
} else if (credit < debit) {
if (!OSCompareAndSwap64(credit, debit, &le->le_credit))
goto top;
lprintf(("%p zeroed %lld->%lld\n", current_thread(), le->le_credit, le->le_debit));
}
return (KERN_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define NUM 6
void Multiple(int arr[],int);/* Multiple()쫬ŧi */
int main()
{
int i,array[NUM]={ 57,48,38,46,25,17 };
/* ŧiõ_}Cl */
printf("IsMultiple()e,}Ce: ");
for(i=0;i<NUM;i++) /* LX}Ce */
printf("%d ",array[i]);
printf("\n");
Multiple(array,NUM); /* IsMultiple() */
printf("IsMultiple(),}Ce: ");
for(i=0;i<NUM;i++) /* LX}Ce */
printf("%d ",array[i]);
printf("\n");
return 0;
}
void Multiple(int arr[],int n1)/* wqMultiple()ƥD */
{
int i;
for(i=0;i<n1;i++)
arr[i]*=2; /* CӰ}C*2 */
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main (int argc, char **argv)
{
const char *prog_name = argv[0];
if (argc < 2) {
fprintf(stderr, "Please input a file name: %s <filename>\n", prog_name);
return EXIT_FAILURE;
}
const char *file = argv[1];
if (!file) {
fprintf(stderr, "file is a null pointer.\n");
return EXIT_FAILURE;
}
int fd = open(file, O_RDONLY);
if (fd < 0) {
fprintf(stderr, "failed to open(%s): %s\n", file, strerror(errno));
return EXIT_FAILURE;
}
off_t seek_off = lseek(fd, 10, SEEK_CUR);
printf("lseek(fd, 10, SEEK_CUR) = %ld\n", seek_off);
seek_off = lseek(fd, 10, SEEK_CUR);
printf("lseek(fd, 10, SEEK_CUR) = %ld\n", seek_off);
seek_off = lseek(fd, 10, SEEK_CUR);
printf("lseek(fd, 10, SEEK_CUR) = %ld\n", seek_off);
seek_off = lseek(fd, -50, SEEK_CUR);
printf("lseek(fd, -50, SEEK_CUR) = %ld\n", seek_off);
seek_off = lseek(fd, 1000000, SEEK_DATA);
printf("lseek(fd, 1000000, SEEK_DATA) = %ld\n", seek_off);
seek_off = lseek(fd, 100, SEEK_DATA);
printf("lseek(fd, 100, SEEK_DATA) = %ld\n", seek_off);
seek_off = lseek(fd, 0, SEEK_DATA);
printf("lseek(fd, 0, SEEK_DATA) = %ld\n", seek_off);
char buf[20];
ssize_t nr = read(fd, buf, 20);
printf("read(fd, buf, 20) = %ld\n", nr);
// This line will print out some garbage value at the end.
// Because the char buffer buf dose not end with specify '/0'.
printf("%s\n", buf);
return EXIT_SUCCESS;
}
|
C
|
/*PBL4 Q1*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int field[50][50], w, h;
// 迭 ġ Ž
int vx[4] = { -1,1,0,0 }; // x
int vy[4] = { 0,0,-1,1 }; // y ,Ʒ
void dfs(int x, int y) {
int nextX, nextY;
field[x][y] = 0; //湮 Ϸ
for (int i= 0; i < 4; i++) {
nextX = x + vx[i];
nextY = y + vy[i];
if (nextX >= 0 && nextX < w && nextY >= 0 && nextY < h)
if (field[nextX][nextY] == 1)
dfs(nextX, nextY);
}
}
int main() {
int n;
scanf("%d", &n); // Ʈ ̽
int num,x,y, cnt;
for (int i = 0; i < n; i++) {
scanf("%d %d %d", &w, &h, &num); // ,,߰
for(int i=0;i<num;i++) {
scanf("%d %d", &x, &y);
field[x][y] = 1;
}//迭 Է = ġ Է
cnt = 0;
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
if (field[i][j] == 1) {
dfs(i, j);
cnt++;
}
}
}// Ȯ = ϱ
printf(" : %d\n", cnt);
}
return 0;
}
|
C
|
#include <sys/param.h>
#include "hfsp.h"
#ifndef _HFSP_UNICODE_H_
#define _HFSP_UNICODE_H_
int hfsp_unicode_cmp(struct hfsp_unistr * lstrp, struct hfsp_unistr * rstrp);
/*
* Fold case folding of unicode char.
* ch: The unicode char to fold.
* return: The value folded.
*/
u_int16_t hfsp_foldcase(u_int16_t ch);
/*
* Copy a hfsp_unistr from one to an other.
* This function assumed that the unistr are allocated.
* srcp: Source hfsp_unistr from where to copy.
* dstp: Destination hfsp_unistr to copy to.
*/
void hfsp_unicode_copy(struct hfsp_unistr * srcp, struct hfsp_unistr * dstp);
#endif /* _HFSP_UNICODE_H_ */
|
C
|
#include <stdio.h>
#include "ft_putnbr_base.c"
int main()
{
int nb20 = 456;
int min_int = -2147483648;
ft_putnbr_base(min_int, "0123456789");
printf("\n");
ft_putnbr_base(4, "01");
printf("\n");
ft_putnbr_base(nb20, "ABCD");
printf("\n");
ft_putnbr_base(-nb20, "ABCD");
printf("\n");
ft_putnbr_base(nb20, "abcde");
printf("\n");
ft_putnbr_base(nb20, "qwerty");
printf("\n");
ft_putnbr_base(nb20, "abc+te");
printf("\n");
ft_putnbr_base(nb20, "012345678-");
printf("\n");
ft_putnbr_base(nb20, "abc+te");
printf("\n");
ft_putnbr_base(nb20, "abcee");
printf("\n");
ft_putnbr_base(-131744, "0123456789ABCDEF");
printf("\n");
ft_putnbr_base(908, "0123456789");
printf("\n");
ft_putnbr_base(0, "0123456789");
return (0);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "ft_strcmp.c"
int strcmp2(const char *p1, const char *p2)
{
const unsigned char *s1 = (const unsigned char *) p1;
const unsigned char *s2 = (const unsigned char *) p2;
unsigned char c1, c2;
do
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0')
return c1 - c2;
}
while (c1 == c2);
return c1 - c2;
}
int main()
{
// char x[] = "Alaind\x1\x5\x10\x15";
char x1[] = "qwrtyuijk.hvb;";
char x2[] = "qwrtyuijk.hv";
// char myCharValues[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,34,35,36,37,38,39,40,41,42,43,44,127};
// int myIntValues[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,34,35,36,37,38,39,40,41,42,43,44,127};
// char z[] = "hiMarteu\nrdeoir";
// ft_putstr_non_printable(x);
// ft_putstr_non_printable(myValues);
// printf("%u\n", ft_putstr_non_printable(x));
// printf("%s\n", x);
// printf("%s\n", z);
// printf("%lu\n", strlcpy(x, z, 5));
// printf("%s\n", x);
// printf("%s\n", z);
printf("%d\n", ft_strcmp(x1, x2));
printf("%s\n", x1);
printf("%s\n", x2);
printf("%d\n", strcmp(x1, x2));
printf("%s\n", x1);
printf("%s\n", x2);
printf("%d\n", strcmp2(x1, x2));
printf("%s\n", x1);
printf("%s\n", x2);
}
|
C
|
#include <stdio.h>
#include <math.h>
#include "source.h"
void draw_triangle(unsigned int size)
{
for(int i = 1; i <= size; ++i) {
for(int j = size; j > i; --j) {
printf(".");
}
for(int j = 0; j < i; ++j) {
printf("#");
}
printf("\n");
}
}
|
C
|
#include<stdio.h>
int sortarray(int s[],int n);
int main()
{
int a[5],i,n;
n=sizeof(a)/4;
printf("number of elements:%d\n",n);
for(i=0;i<n;i++)
{
printf("Enter elements:");
scanf("%d",&a[i]);
}
printf("\n Sorting of array:");
sortarray(a,n);
return 0;
}
int sortarray(int s[],int n)
{
int i,temp,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(s[i]>s[j])
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
for(i=0;i<n;i++)
{
printf("%d \t",s[i]);
}
return 0;
}
|
C
|
#define ex2
#include<stdio.h>
#include<locale.h>
#include<math.h>
/*1. Gere e exiba cada uma das seqncias abaixo com uma quantidade k de termos determinados
pelo usurio.
a. 3, 6, 9, 12, 15,...
b. 1/4, 1/8, 1/12, 1/16, 1/20,... */
#ifdef ex1
int main()
{
setlocale(LC_ALL, "portuguese");
//variveis do nmero de termos, contador, tabuada do 3 e frao de mltiplos de 4
int numt, cont, tab3, frc4;
printf("Digite a quantidade de termos que iro aparecer das sequncias: ");
scanf("%i", &numt);
for(cont = 0, tab3 = 3; numt != cont; cont++, tab3 += 3){
if(numt - 1 == cont){
printf("%i.", tab3);
}else{
printf("%i, ", tab3);
}
}
printf("\n\n");
for(cont = 0, frc4 = 4; numt != cont; cont++, frc4 += 4){
if(numt - 1 == cont){
printf("1/%i.", frc4);
}else{
printf("1/%i, ", frc4);
}
}
printf("\n");
return 0;
}
#endif // ex1
/*2. Gere e exiba cada uma das seqncias abaixo com uma quantidade k de termos determinados
pelo usurio.
a) 2/5, 4/10, 6/15, 8/20, 10/25, 12/30,...
b) 4/8, 1, 36/24, 2, 100/40, 144/48,... */
#ifdef ex2
int main()
{
setlocale(LC_ALL, "portuguese");
int numt, cont, tab2, tab5, tab8;
printf("Digite a quantidade de termos que iro aparecer das sequncias: ");
scanf("%i", &numt);
for(cont = 0, tab2 = 2, tab5 = 5; numt != cont; cont++, tab2 += 2, tab5 += 5){
if(numt - 1 == cont){
printf("%i/%i.", tab2, tab5);
}else{
printf("%i/%i, ", tab2, tab5);
}
}
printf("\n\n");
for(cont= 0, tab2 = 2, tab8 = 8; numt != cont; cont++, tab2 += 2, tab8 += 8){
if((tab2*tab2)%tab8 == 0) {
if(numt - 1 == cont){
printf("%i.", (tab2*tab2)/tab8);
}else{
printf("%i, ", (tab2*tab2)/tab8);
}
}else{
if(numt - 1 == cont){
printf("%i/%i.", tab2*tab2, tab8);
}else{
printf("%i/%i, ", tab2*tab2, tab8);
}
}
}
return 0;
}
#endif // ex2
/*3. Receba a quantidade de idades de K indivduos. K representa essa quantidade e deve ser
digitada pelo usurio. A varivel Idade armazena cada uma das K idades digitadas. Calcule e
mostre a somatria dessas idades. */
#ifdef ex3
int main()
{
setlocale(LC_ALL,"portuguese");
int numt, cont, idade, somaid;
printf("Digite a quantidade de idade de pessoas que gostaria de somar: ");
scanf("%i", &numt);
printf("Agora digite as idades destas pessoas\n");
for (cont = 0, idade = 0, somaid = 0; cont != numt; cont++){
if(cont == 0){
printf("Digite uma idade: ");
scanf("%i", &idade);
somaid += idade;
}else{
printf("Digite outra idade: ");
scanf("%i", &idade);
somaid += idade;
}
if(cont == numt - 1){
printf("A soma das idades que voc digitou : %i", somaid);
}
}
return 0;
}
#endif // ex3
/*4. Calcule e mostre a mdia dos K primeiros pares e mltiplos de cinco.
OBS: K representa a quantidade de nmeros pares solicitados via teclado pelo usurio.
Os nmeros pares devero ser gerados pelo programador.2, 4, 6, 8, 10,...*/
#ifdef ex4
int main()
{
setlocale(LC_ALL, "portuguese");
int k, soma, i;
printf("Digite a quantidade de nmeros pares e mltiplos de 5 que devero ter sua mdia calculada: ");
scanf("%i", &k);
for (i = 1, soma = 0; i != 2*k+1; i++){
if(cont%2 == 0){
printf("%i ", i);
if(cont%5 == 0){
soma = soma + i;}
}
}
printf("A mdia dos nmeros pares e mltiplos de 5 de: %f", soma/)
}
#endif // ex4
/*5. Receba K nmeros. Exiba a quantidade de nmeros pares negativos e quantas vezes o nmero
zero foi digitado.
OBS1: K representa a quantidade de nmeros digitados pelo usurio.
OBS2: A varivel Num representa cada nmero digitado pelo usurio. */
#ifdef ex5
int main()
{
setlocale(LC_ALL, "portuguese");
int k,
}
#endif // ex5
|
C
|
static void insert(Node** root,Node* node)
{
while(1)
{
if(*root == NULL)
{
*root = node;
return;
}
else
{
if((*root)->data > node->data)
{
*root = &(*root)->left;
}
else
{
*root = &(*root)->right;
}
}
}
}
|
C
|
#ifndef _MATRIX_H_
typedef struct vector{
int size;
float* data;
} Vector;
typedef struct matrix{
int row;
int column;
float** data;
} Matrix;
void print_compile_info();
void initialize_vector(Vector* vector, int size);
void free_vector(Vector *vector);
void print_vector(Vector *vector);
void copy_vector_from_array(Vector *vector, float* array);
void copy_vector(Vector *copy, Vector *org);
void row_vector_to_matrix(Matrix *dst, Vector *org);
void column_vector_to_matrix(Matrix *dst, Vector *org);
float vector_get(Vector *a, int n);
void vector_add(Vector *ans, Vector *a, Vector *b);
void vector_sub(Vector *ans, Vector *a, Vector *b);
float vector_dot(Vector *a, Vector *b);
void initialize_matrix(Matrix* matrix, int row, int column);
void free_matrix(Matrix* matrix);
void print_matrix(Matrix* matrix);
void copy_matrix_from_array(Matrix* matrix, float* array);
void copy_matrix(Matrix* copy, Matrix* org);
float matrix_get(Matrix* a, int n, int m);
void matrix_dot(Matrix* ans, Matrix* a, Matrix* b);
float matrix_determinant(Matrix* a);
void matrix_transpose(Matrix* ans, Matrix* a);
void matrix_cMul(Matrix* ans, Matrix* a, float c);
void matrix_inverse(Matrix* ans, Matrix* a);
void matrix_add(Matrix* ans, Matrix* a, Matrix* b);
void matrix_sub(Matrix* ans, Matrix* a, Matrix* b);
void matrix_hadamard_product(Matrix *ans, Matrix *a, Matrix *b);
float matrix_trace(Matrix* a);
int matrix_rank(Matrix* a);
void matrix_eigenvalues(Vector* eigenvalues, Matrix* a);
float matrix_max(Matrix* a);
float matrix_min(Matrix* a);
void matrix_exp(Matrix* ans, Matrix *a);
float matrix_sum(Matrix* a);
void make_identity_matrix(Matrix* matrix);
void make_upper_triangular_matrix(Matrix* matrix);
void make_lower_triangular_matrix(Matrix* matrix);
void matrix_fill(Matrix* matrix, float num);
int matrix_convolution_output_height(Matrix* a, Matrix* kernel, int padding, int stride);
int matrix_convolution_output_width(Matrix* a, Matrix* kernel, int padding, int stride);
void matrix_convolution(Matrix* ans, Matrix* a, Matrix* kernel, int padding, int stride);
#endif
|
C
|
#include <stdio.h>
#include "../hdr/color.h"
#include "../hdr/display.h"
#include "../hdr/displayTest.h"
#include "../hdr/window.h"
#include "../hdr/video.h"
#define MODE_OFF 0
#define MODE_WHEEL_VIDEO 1
#define MODE_SIDE_TRAIN_VIDEO 2
#define MODE_SOUL_TRAIN_VIDEO 3
#define MODE_SOUL_TRAIN_1_VIDEO 4
#define MODE_PLANET_VIDEO 5
#define MODE_PLANET_TRAIN_VIDEO 6
#define MODE_PLANET_TRAIN_2_VIDEO 7
uint8_t inDisplayTestMode = MODE_OFF;
void startNextVideo()
{
inDisplayTestMode++;
if (inDisplayTestMode > MODE_PLANET_TRAIN_2_VIDEO)
{
inDisplayTestMode = MODE_WHEEL_VIDEO;
}
switch (inDisplayTestMode)
{
case MODE_WHEEL_VIDEO:
return startWheelVideo();
case MODE_SIDE_TRAIN_VIDEO:
return startTrainSideVideo();
case MODE_SOUL_TRAIN_VIDEO:
return startSoulTrainVideo();
case MODE_SOUL_TRAIN_1_VIDEO:
return startSideSoulTrain1Video();
case MODE_PLANET_VIDEO:
return startPlanetVideo();
case MODE_PLANET_TRAIN_VIDEO:
return startPlanetTrainVideo();
case MODE_PLANET_TRAIN_2_VIDEO:
return startPlanetTrain2Video();
}
}
void displayTestOpen()
{
clearDmd();
refreshDmd();
inDisplayTestMode = MODE_OFF;
startNextVideo();
}
void displayTestExit()
{
inDisplayTestMode = MODE_OFF;
}
char *getNextImage()
{
switch (inDisplayTestMode)
{
case MODE_WHEEL_VIDEO:
return getNextWheelFrame();
case MODE_SIDE_TRAIN_VIDEO:
return getNextTrainSideFrame();
case MODE_SOUL_TRAIN_VIDEO:
return getNextSoulTrainFrame();
case MODE_SOUL_TRAIN_1_VIDEO:
return getNextSideSoulTrain1Frame();
case MODE_PLANET_VIDEO:
return getNextPlanetFrame();
case MODE_PLANET_TRAIN_VIDEO:
return getNextPlanetTrainFrame();
case MODE_PLANET_TRAIN_2_VIDEO:
return getNextPlanetTrain2Frame();
}
}
void displayTestTick(uint8_t tick)
{
if (inDisplayTestMode != MODE_OFF)
{
if (tick % 2 == 0)
{
showImage(getNextImage());
}
}
}
void displayTestEnter()
{
startNextVideo();
}
|
C
|
/** @file faux.h
* @brief Additional usefull data types and base functions.
*/
#ifndef _faux_types_h
#define _faux_types_h
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/uio.h>
/**
* A standard boolean type. The possible values are
* BOOL_FALSE and BOOL_TRUE.
*/
typedef enum {
BOOL_FALSE = 0,
BOOL_TRUE = 1
} bool_t;
/**
* A tri-state boolean. The possible values are
* TRI_FALSE, TRI_TRUE, TRI_UNDEFINED.
*/
typedef enum {
TRI_UNDEFINED = -1,
TRI_FALSE = 0,
TRI_TRUE = 1
} tri_t;
/** @def C_DECL_BEGIN
* This macro can be used instead standard preprocessor
* directive like this:
* @code
* #ifdef __cplusplus
* extern "C" {
* #endif
*
* int foobar(void);
*
* #ifdef __cplusplus
* }
* #endif
* @endcode
* It make linker to use C-style linking for functions.
* Use C_DECL_BEGIN before functions declaration and C_DECL_END
* after declaration:
* @code
* C_DECL_BEGIN
*
* int foobar(void);
*
* C_DECL_END
* @endcode
*/
/** @def C_DECL_END
* See the macro C_DECL_BEGIN.
* @sa C_DECL_BEGIN
*/
#ifdef __cplusplus
#define C_DECL_BEGIN extern "C" {
#define C_DECL_END }
#else
#define C_DECL_BEGIN
#define C_DECL_END
#endif
C_DECL_BEGIN
// Memory
void faux_free(void *ptr);
void *faux_malloc(size_t size);
void faux_bzero(void *ptr, size_t size);
void *faux_zmalloc(size_t size);
// I/O
ssize_t faux_write(int fd, const void *buf, size_t n);
ssize_t faux_read(int fd, void *buf, size_t n);
ssize_t faux_write_block(int fd, const void *buf, size_t n);
size_t faux_read_block(int fd, void *buf, size_t n);
ssize_t faux_read_whole_file(const char *path, void **data);
// Filesystem
ssize_t faux_filesize(const char *path);
bool_t faux_isdir(const char *path);
int faux_rm(const char *path);
char *faux_expand_tilde(const char *path);
C_DECL_END
#endif /* _faux_types_h */
|
C
|
#include "unamelib.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/utsname.h>
struct utsname systemInfo;
char *systemName()
{
if (systemInfo.sysname != NULL)
return systemInfo.sysname;
else
{
fprintf(stderr, "Error to return systemName\n");
return 1;
}
}
char *systemNodeName()
{
if (systemInfo.nodename != NULL)
return systemInfo.nodename;
else
{
fprintf(stderr, "Error to return systemNodeName\n");
return 1;
}
}
char *systemRelease()
{
if (systemInfo.release != NULL)
return systemInfo.release;
else
{
fprintf(stderr, "Error to return release\n");
return 1;
}
}
char *systemVersion()
{
if (systemInfo.version != NULL)
return systemInfo.version;
else
{
fprintf(stderr, "Error to return version\n");
return 1;
}
}
char *systemMachine()
{
if (systemInfo.machine != NULL)
return systemInfo.machine;
else
{
fprintf(stderr, "Error to return machine\n");
return 1;
}
}
_init()
{
printf("Unamelib connected\n");
if( uname( &systemInfo ) == -1 )
{
fprintf(stderr, "Error to load uname\n");
return 1;
}
}
_fini()
{
printf("Unamelib disconected\n");
}
|
C
|
#include "SN76489.h"
void SN_Init(GPIO_TypeDef * port)
{
_port = port;
}
void SN_WriteDataPins(char data)
{
//WE = PA09:0x100
GPIOA->ODR |= 0x100; //WE HIGH
Databus.PORT = _port->ODR;
Databus.bytes[0] = data;
_port->ODR = Databus.PORT;
GPIOA->ODR &= ~(0x100); //WE HIGH
Delay(14); //Delay 14 microseconds
GPIOA->ODR |= 0x100; //WE HIGH
}
void SN_Reset()
{
SN_WriteDataPins(0x9F);
SN_WriteDataPins(0xBF);
SN_WriteDataPins(0xDF);
SN_WriteDataPins(0xFF);
}
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
int n,ang;
while(scanf("%d",&n)!=EOF)
{
for(n=3; n<=100; n++)
ang=((n-2)*180);
printf("%d\n",ang);
}
return 0;
}
|
C
|
// Link of the problem (language PT-BR): http://br.spoj.com/problems/COFRE/
// (Name of the problem) COFRE - Cofrinhos da Vó Vitória
#include<stdio.h>
int main(void){
int N, J, Z, dif = 0, test = 1;
scanf("%d", &N);
while (N != 0){
printf("Teste %d\n", test++);
for (int i = 0; i < N; i++){
scanf("%d%d", &J, &Z);
dif += J - Z;
printf("%d\n", dif);
}
dif = 0;
scanf("%d", &N);
}
}
|
C
|
/* hello.c
*
* Copyright (c) 2016 U.S. Army Research Laboratory. All rights reserved.
* Copyright (c) 2019 Brown Deer Technology, LLC. All rights reserved.
*
* This file is part of the ARL OpenSHMEM Reference Implementation software
* package. For license information, see the LICENSE file in the top level
* directory of the distribution.
*/
/*
* "Hello, World" of OpenSHMEM
*/
#include <stdio.h>
#include <string.h>
#include <shmem.h>
int main(int argc, char* argv[])
{
int err = 0;
int major, minor;
char name[SHMEM_MAX_NAME_LEN];
// Starts/Initializes SHMEM/OpenSHMEM
// Some implementations use the deprecated start_pes(0)
shmem_init();
// Fetch the number or processes
// Some implementations use the deprecated num_pes()
int n_pes = shmem_n_pes();
// Assign my process ID to me
int me = shmem_my_pe();
// Query
shmem_info_get_name(name);
shmem_info_get_version(&major, &minor);
if (me == 0) {
printf("# API : %s (%d.%d)\n", name, major, minor);
printf("# HEADER: %s (%d.%d)\n", SHMEM_VENDOR_STRING,
SHMEM_MAJOR_VERSION, SHMEM_MINOR_VERSION);
}
// Global barrier
shmem_barrier_all();
// Comparing shmem.h header values and API values
if (strncmp(name, SHMEM_VENDOR_STRING, SHMEM_MAX_NAME_LEN)) {
printf("# %d: ERROR: vendor name mismatch\n", me);
err++;
}
if (major != SHMEM_MAJOR_VERSION) {
printf("# %d: ERROR: major version mismatch\n", me);
err++;
}
if (minor != SHMEM_MINOR_VERSION) {
printf("# %d: ERROR: minor version mismatch\n", me);
err++;
}
printf("Hello, World from %d of %d\n", me, n_pes);
return(err);
}
|
C
|
/**
*pat-bl-1014
*2016-11-13
*C version 1.0
*未AC前出错3处
*坑点:要仔细读题,到底是大写还是小写,是英文字符还是字符,是判断字符还是判断下标位置,以及判断的边界在哪里,都要搞清楚
*/
#include<stdio.h>
int main()
{
char str[4][70];
char arrayDay[8][10] = {"zero", "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"};
int day;
int hh, mm;
int i, j;
for(i = 0;i < 4;i++)
{
scanf("%s", str[i]);
}
i = 0;
while(1)//判断是星期几
{
if(str[0][i] <= 'G' && str[0][i] >= 'A')//出错3:边界问题,应该<='G',而不是<='Z'
{
if(str[0][i] == str[1][i])
{
day = str[0][i] - 'A' + 1;
break;
}
}
i++;
}
while(1)//判断是一天中的几点
{
i++;//出错1:忘记跳出上一个循环要++
if(str[0][i] == str[1][i])
{
if((str[0][i] <= 'N')&&(str[0][i] >= 'A'))
{
hh = str[0][i] - 'A' + 10;
//printf("%c, %d\n", str[0][i], hh);
break;
}
if((str[0][i] <= '9')&&(str[0][i] >= '0'))
{
hh = str[0][i] - '0';
break;
}
}
}
i = 0;
while(1)//判断是第几分钟
{
if(str[2][i] == str[3][i])
{
if((str[2][i] <= 'z' && str[2][i] >= 'a') || (str[2][i] <= 'Z' && str[2][i] >= 'A'))
{
mm = i;
break;
}
}
i++;
}
//output:出错2:格式控制
printf("%s %02d:%02d\n", arrayDay[day], hh, mm);
}
|
C
|
/*Christien Hotchkiss
* CS 344
* OTP
* otp_enc_d.c
* This is the daemon for the encryption program. It listens for oncoming connections with otp_enc. It reads in the length of key and message as well as the character arrays key and message. Then, it uses modulo % 27 to encrypt a plaintext file and outputs the result back to otp_enc by sending it */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
void error(const char *msg) { perror(msg); exit(1); } // Error function used for reporting issues
//setting up the server is code adopted for class lectures
int main(int argc, char *argv[])
{
int listenSocketFD, establishedConnectionFD, portNumber, charsRead;
socklen_t sizeOfClientInfo;
char buffer[256];
struct sockaddr_in serverAddress, clientAddress;
if (argc < 2) { fprintf(stderr,"USAGE: %s port\n", argv[0]); exit(1); } // Check usage & args
// Set up the address struct for this process (the server)
memset((char *)&serverAddress, '\0', sizeof(serverAddress)); // Clear out the address struct
portNumber = atoi(argv[1]); // Get the port number, convert to an integer from a string
serverAddress.sin_family = AF_INET; // Create a network-capable socket
serverAddress.sin_port = htons(portNumber); // Store the port number
serverAddress.sin_addr.s_addr = INADDR_ANY; // Any address is allowed for connection to this process
// Set up the socket
listenSocketFD = socket(AF_INET, SOCK_STREAM, 0); // Create the socket
if (listenSocketFD < 0) error("ERROR opening socket");
// Enable the socket to begin listening
if (bind(listenSocketFD, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) // Connect socket to port
error("ERROR on binding");
listen(listenSocketFD, 5); // Flip the socket on - it can now receive up to 5 connections
// Accept a connection, blocking if one is not available until one connects
sizeOfClientInfo = sizeof(clientAddress); // Get the size of the address for the client that will connect
//create infinite loop to accept oncoming connections. Blocks until one is able to connect
while (1){
//initialize variables
int lengthOfMessage = 0;
int lengthOfKey = 0;
//arrays to store sent and received data
char * myKey;
char * myMessage;
char * tmpBuffer;
char * cipherText;
char cipher;
int i;
int characterValue;
int characterValue2;
int sum =0 ;
//variables used in the while loop of recv statements to account for plaintext4
int totalReceived = 0;
int lengthReceived = 0;
establishedConnectionFD = accept(listenSocketFD, (struct sockaddr *)&clientAddress, &sizeOfClientInfo); // Accept
if (establishedConnectionFD < 0) error("ERROR on accept");
if (establishedConnectionFD >= 0){
//use key and message. need to fork the process
pid_t spawnPid = fork();
if (spawnPid < 0){
perror("Hull Breach!");
exit(1);
}
//child process
if (spawnPid == 0){
//send an Encrypt message back to otp_enc. This ensures that otp_enc canot connect to otp_dec_d and vice versa
charsRead = send(establishedConnectionFD, "Encrypt", 8, 0);
if (charsRead < 0) error("ERROR writing to socket");
//receive the length of the message from otp_enc
charsRead = recv(establishedConnectionFD, &lengthOfMessage, sizeof(int), 0);
//allocate new memory for message and then receive the length of the key from otp_enc
myMessage = malloc(lengthOfMessage);
charsRead = recv(establishedConnectionFD, &lengthOfKey, sizeof(int), 0);
//printf(" Received Length of Message: %d\n", lengthOfMessage);
//printf("Received Length of Key: %d\n", lengthOfKey);
//allocate memory for key and cipherText (which is same length as message) and initialize these arrays to NULL
myKey = malloc(lengthOfKey);
cipherText = malloc(lengthOfMessage);
for(i = 0; i<lengthOfMessage; i++){
myMessage[i] = '\0';
// myKey[i] = '\0';
cipherText[i] = '\0';
}
for (i = 0; i<lengthOfKey; i++)
myKey[i] = '\0';
//lengthOfKey = lengthOfMessage;
//use a while loop to receive information. This is mainly for plaintext4 but works for all sizes.
totalReceived = 0;
lengthReceived = lengthOfMessage-1;
//necesarry to restore myMessage pointer after while loop increments it
tmpBuffer = myMessage;
//continue looping until characters received is equal to the expected amount (specified by lengthReceived)
while(totalReceived < lengthReceived){
//receive the message sent by otp_enc. This will be the text file to be encrypted
charsRead = recv(establishedConnectionFD, myMessage, lengthReceived-totalReceived, 0);
if (charsRead < 0) error("ERROR reading from socket");
totalReceived = totalReceived + charsRead;
//increment myMesage pointer so next time through loop adds onto myMessage character aray
if (totalReceived < lengthReceived)
myMessage = myMessage + charsRead;
}
myMessage = tmpBuffer;
//charsRead = recv(establishedConnectionFD, myMessage, lengthOfMessage-1, 0);
//if (charsRead < 0) error("ERROR reading from soket");
//printf("Encryption received message with %d characters. Length of message according to variable: %d\n", strlen(myMessage), lengthOfMessage-1);
//printf("received message is: %s\n", myMessage);
//The following while loop is identical to the one above it.
//Instead of populating the message array, it populates the key arary, which is sent from otp_enc.
totalReceived = 0;
lengthReceived = lengthOfKey - 1;
tmpBuffer = myKey;
while(totalReceived < lengthReceived){
charsRead = recv(establishedConnectionFD, myKey, lengthReceived-totalReceived, 0);
if (charsRead < 0) error("ERROR reading from socket");
totalReceived = totalReceived + charsRead;
if (totalReceived < lengthReceived)
myKey = myKey + charsRead;
}
myKey = tmpBuffer;
// charsRead = recv(establishedConnectionFD, myKey, lengthOfKey-1, 0);
// if (charsRead < 0) error("ERROR reading from sokcet");
//printf("received key is: %s\n", myKey);
//do the encryption
for (i = 0; i<lengthOfMessage; i++){
//off set is only 6 for space because its ascii value is 32
if (myMessage[i] == ' ')
characterValue = myMessage[i] - 6;
//otherwise offset is 65 because A = 65 and we are generating random numbers between 0 and 26
else
characterValue = myMessage[i] - 65;
//do the same with myKey
if (myKey[i] == ' ')
characterValue2 = myKey[i] - 6;
else
characterValue2 = myKey[i] - 65;
//printf("characterValue :%d, characterValue2: %d\n", characterValue, characterValue2);
sum = characterValue + characterValue2;
//mod27 and store result in cipherText
sum = sum % 27;
if (sum == 26)
cipher = sum + 6;
else
cipher = sum + 65;
// printf("sum: %d\n", sum);
// printf("cipher: %c\n", cipher);
cipherText[i] = cipher;
}
//free dynamically allocated char arrays
free(myMessage);
free(myKey);
//end the encryption
//printf("server is sending: %s\n", cipherText);
//send encrypted message otp_enc_d
charsRead = send(establishedConnectionFD, cipherText, lengthOfMessage, 0);
if (charsRead < 0) error("ERROR writing to scoket");
free(cipherText);
close(establishedConnectionFD); //close existing socket which is connected to the client
close(listenSocketFD); //close listening socket
exit(0);
}
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
void printTitle(char a[]);
void stringToCaps(char a[]);
int main(){
int userHand, computerHand;
char userHandString[10], computerHandString[10];
int result;
int keepAsking;
char keepPlaying = 'Y';
/*Start randomizer*/
srand(time(NULL));
while(keepPlaying == 'Y' || keepPlaying == 'y'){
/*Generate computer's hand*/
computerHand = rand() % 3;
switch(computerHand){
case 0:
strcpy(computerHandString, "ROCK");
break;
case 1:
strcpy(computerHandString, "PAPER");
break;
case 2:
strcpy(computerHandString, "SCISSORS");
break;
default:
break;
}
/*Game*/
printTitle("ROCK, PAPER, SCISSORS BY ZABE");
do{
printf("\nRock, paper or scissors?: ");
scanf("%s", userHandString);
stringToCaps(userHandString);
keepAsking = 0;
if(strcmp(userHandString, "ROCK") == 0)
userHand = 0;
else if(strcmp(userHandString, "PAPER") == 0)
userHand = 1;
else if(strcmp(userHandString, "SCISSORS") == 0)
userHand = 2;
else
keepAsking = 1;
}while(keepAsking == 1);
printf("\n\nYour hand: %s", userHandString);
printf("\nComputer's hand: %s\n\n", computerHandString);
result = userHand - computerHand;
if(result < 0)
result += 3;
switch(result){
case 0:
printf("It's a draw, gg\n\n");
break;
case 1:
printf("YOU WON YAY!\n\n");
break;
case 2:
printf("Oh, you lost. GG EZ NOOB\n\n");
break;
default:
break;
}
do{
printf("Do you want to keep playing? [Y/N]: ");
fflush(stdin);
scanf("%c",&keepPlaying);
}while(keepPlaying != 'y' && keepPlaying != 'Y'&& keepPlaying != 'n' && keepPlaying != 'N');
system("@cls||clear");
}
printTitle("Thanks for playing! UwU");
clock_t start_time = clock();
while (clock() < start_time + 1600);
return 0;
}
void printTitle(char a[]){
int j = 0;
printf("%c%c",176,177);
for(int i = 0; i <= strlen(a)+7; i++)
printf("%c",178);
printf("%c%c\n",177,176);
printf("%c%c%c%c%c ",176,177,178,177,176);
while(a[j]!='\0'){
printf("%c",a[j]);
j++;
}
printf(" %c%c%c%c%c\n",176,177,178,177,176);
printf("%c%c",176,177);
for(int i = 0; i <= strlen(a)+7; i++)
printf("%c",178);
printf("%c%c\n",177,176);
}
void stringToCaps(char a[]){
for(int i = 0; i < strlen(a); i++)
if(a[i] > 96 && a[i] < 123)
a[i] -= 32;
}
|
C
|
#include <stdio.h>
#define N 10
int main(void) {
int a[N];
printf("Enter %d fucking numbers: ", N);
for (int i = 0; i < N; i++)
if (scanf("%d", &a[i]) <= 0) return 1;
printf("In reverse, these fucking numbers are:");
for (int i = N-1; i >= 0; i--)
printf(" %d", a[i]);
putchar('\n');
return 0;
}
|
C
|
/**
* Joseph Okonoboh
* Lab 4, SUMMER 2015 CECS 424
*
* driver.c
*/
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "animal.h"
#define MAX_CHAR_PER_LINE 1024
#define DOG 1
#define CAT 2
#define LION 3
#define INVALID 0
static char line[MAX_CHAR_PER_LINE];
int empty_string(char* string);
long int get_age();
long int get_animal_type();
long int get_lives();
double get_weight();
void print_animal(Animal* a);
int main() {
Animal* a;
Cat* c;
Dog* d;
Lion* l;
long int type = get_animal_type();
if(type == DOG) {
d = (Dog*) malloc(sizeof(Dog));
Construct_Dog(d);
d->weight = get_weight();
a = (Animal*) d;
} else if(type == CAT) {
c = (Cat*) malloc(sizeof(Cat));
Construct_Cat(c);
c->numberOfLives = get_lives();
a = (Animal*) c;
} else { /* lion */
l = (Lion*) malloc(sizeof(Lion));
Construct_Lion(l);
l->numberOfLives = get_lives();
l->weight = get_weight();
a = (Animal*) l;
}
a->age = get_age();
print_animal(a);
free(a);
return EXIT_SUCCESS;
}
int empty_string(char* string) {
while(*string) {
if(!isspace(*string++)) {
return 0;
}
}
return 1;
}
long int get_age() {
long int age;
char* next_char;
do {
printf("Enter the age of this animal (must be at least 1): ");
fgets(line, MAX_CHAR_PER_LINE, stdin);
age = strtol(line, &next_char, 10);
if(age < 1 || !empty_string(next_char)) {
age = INVALID;
printf("\n\tError: invalid input...\n\n");
}
} while(age < 1);
return age;
}
long int get_animal_type() {
long int type;
char* next_char;
do {
printf("Enter %d for dog, %d for cat, and %d for lion: ", DOG, CAT, LION);
fgets(line, MAX_CHAR_PER_LINE, stdin);
type = strtol(line, &next_char, 10);
if((type != DOG && type != CAT && type != LION) ||
!empty_string(next_char)) {
type = INVALID;
printf("\n\tError: invalid input...\n\n");
}
} while(type != DOG && type != CAT && type != LION);
return type;
}
long int get_lives() {
long int lives;
char* next_char;
do {
printf("Enter number of lives (1 <= lives <= 9): ");
fgets(line, MAX_CHAR_PER_LINE, stdin);
lives = strtol(line, &next_char, 10);
if(lives < MIN_CAT_LIVES || lives > MAX_CAT_LIVES ||
!empty_string(next_char)) {
lives = INVALID;
printf("\n\tError: invalid input...\n\n");
}
} while(lives < MIN_CAT_LIVES || lives > MAX_CAT_LIVES);
return lives;
}
double get_weight() {
double weight = 0.0;
char* next_char;
do {
printf("Enter weight (must be positive): ");
fgets(line, MAX_CHAR_PER_LINE, stdin);
weight = strtod(line, &next_char);
if(weight <= 0.0 || !empty_string(next_char)) {
printf("\n\tError: invalid input...\n\n");
weight = 0.0;
}
} while(weight <= 0.0);
return weight;
}
void print_animal(Animal* a) {
printf("Animal says: \"");
((void (*)(Animal*)) a->vtable[0])(a);
printf("\"\n");
printf("This animal costs: $%.2f.\n",
((double (*)(Animal*)) a->vtable[1])(a));
}
|
C
|
/*
============================================================================
Name : LongestCollatzSequence.c
Author : rightmirem
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int count = 1;
int longestStartingNum = 0;
int longestCount = 0;
long long num = 0;
int i;
//13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
for (i = 999999; i > 1; i--) {
num = i;
while (num > 1) {
if (num%2 == 0){ num /= 2; }
else {num = (num*3+1); }
count += 1;
// printf("(%d)%d\n", count, num);
}
if (count > longestCount) {
longestCount = count;
longestStartingNum = i;
}
printf("%d = %d terms\n", i, count);
count = 1;
}
printf("Longest Count %d:%d\n", longestStartingNum, longestCount);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node*next;
};
struct node*insert(struct node*start,int x)
{
struct node*p = start,*temp = (struct node*)malloc(sizeof(struct node));
temp->data = x;
temp->next = NULL;
if(start == NULL)
start = temp;
else
{
p = start;
while(p->next != NULL)
p = p->next;
p->next = temp;
}
return(start);
}
void display(struct node*start)
{
struct node*p = start;
while(p!=NULL)
{
printf("%d\n",p->data);
p = p->next;
}
}
void printmax(struct node*start,struct node*p)
{
if(p == NULL)
return;
struct node*q = p->next;
int max;
if(q!=NULL)
max = q->data;
while(q!=NULL)
{
if(q->data >= max)
max = q->data;
q = q->next;
}
q = p;
while(q!=NULL&& q->next!=NULL)
{
if(q->next->data == max)
{
q->next = q->next->next;
break;
}
q = q->next;
if(q == NULL)
break;
}
printf("\n");
q = p->next;
printmax(start,q);
return;
}
int main()
{
int n,i,x;
struct node*start = NULL,*p;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&x);
start = insert(start,x);
}
p = start;
printmax(start,p);
display(start);
return(0);
}
|
C
|
/* -------------------------------------------------------------------------*/
/* Guardar y visualizar imgenes, A. Lpez */
/* -------------------------------------------------------------------------*/
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#define anchoVentana 640 /* ancho de la ventana */
#define altoVentana 480 /* alto de la ventana */
#define posicionVentanaX 50 /* pos. X de la esquina sup-izq de la ventana */
#define posicionVentanaY 50 /* pos. Y de la esquina sup-izq de la ventana */
double aspecto; /* relacin ancho/alto de la ventana */
GLubyte *pixeles;
/* Funcin que establece la proyeccin -------------------------------------*/
void proyeccion (void) {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0f, 640.0f, 0.0f, 480.0f);
}
/* Rutina asociada a eventos de ventana ------------------------------------*/
void eventoVentana (GLsizei ancho, GLsizei alto) {
glViewport (0, 0, ancho, alto);
aspecto= (GLdouble) ancho/alto;
proyeccion();
}
/* Rutina asociada a eventos de teclado ------------------------------------*/
void eventoTeclado (unsigned char tecla, int x, int y) {
switch (tecla) {
case 27: exit (0); break;
case 'q': exit (0); break;
case 'Q': exit (0); break;
}
}
/* Rutina de dibujo de la escena -------------------------------------------*/
void Dibuja (void) {
FILE *fichero;
int ancho, alto;
glClearColor (0,0,0,0);
glClear (GL_COLOR_BUFFER_BIT);
glBegin (GL_LINES);
glVertex2i(0,0);
glVertex2i(640,480);
glVertex2i(640,0);
glVertex2i(0,480);
glEnd();
glRecti(270, 190, 370, 290);
/* que la alineacin sea mltiplo de 1 */
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
/* transferio la imagen a memoria */
glReadPixels (0, 0, 640, 480, GL_RGB, GL_UNSIGNED_BYTE, pixeles);
glClear (GL_COLOR_BUFFER_BIT); /* borro la ventana */
/* transfiero la imagen a la ventana */
glRasterPos2i (0, 0);
glDrawPixels (640, 480, GL_RGB, GL_UNSIGNED_BYTE, pixeles);
glFlush();
}
/* Establece las funciones que atienden los distintos eventos --------------*/
void asociaEventos (void) {
glutKeyboardFunc (eventoTeclado);
glutReshapeFunc (eventoVentana);
}
/* Abre la ventana de la aplicacin ----------------------------------------*/
void abreVentana (int numParametros, char **listaParametros) {
glutInit (&numParametros, listaParametros);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (anchoVentana, altoVentana);
glutInitWindowPosition (posicionVentanaX, posicionVentanaY);
glutCreateWindow (listaParametros[0]);
}
/* Programa principal ------------------------------------------------------*/
int main (int numParametros, char **listaParametros) {
pixeles = (GLubyte *) calloc (sizeof (GLubyte), 640*480*3);
/* crea la ventana de la aplicacin*/
abreVentana (numParametros, listaParametros);
/* asocia funciones a eventos de ventana, teclado o ratn*/
asociaEventos ();
/* asocia la rutina de dibujo */
glutDisplayFunc (Dibuja);
/* bucle a la espera de eventos */
glutMainLoop();
}
|
C
|
#include<stdio.h>
void main()
{
int a,n,i;
printf("enter a,n values");
scanf("%d%d",&a,&n);
for(i=0;i<=n;i++)
{
if(i%2==0)
{
printf("%d",i);
}
}
}
|
C
|
#ifndef CS_2413_BANG_H
#define CS_2413_BANG_H
#include "dice.h"
#include "players.h"
#include "friendliness.h"
#define NUM_DICE 5
typedef enum {noExit, outlawWin, renegadeWin, deputyWin} GameOver;
/**
* The main function to run the game
* @authors Anamol Acharya, Jonathon Surles, and Shree Shrestha
*/
void bang();
/**
* Reroll a random number of dice in the provided array
* @author Anamol Acharya
* @param dice The array of dice
*/
void reroll(Dice *dice);
/**
* Check if the game is over. If so, return the win condition that was met.
* @param players The array of all players who started the game
* @param numPlayers The number of players at the beginning of the game
* @return The win condition that was met
*/
GameOver checkEnd(Player *players, int numPlayers);
/**
* Check if the player at the given seat has died. If they have, remove them from the table
* @param player The player at the table
* @param friendliness The friendliness graph to update if death happened
* @return True if the player died, false if they are still alive
*/
bool checkDeath(Seat player, Graph friendliness, int alivePlayers);
#endif //CS_2413_BANG_H
|
C
|
#include <GL/glut.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "funkcije.h"
#include "image.h"
#define TIMER_INTERVAL 20
#define TIMER_ID 0
#define PI 3.14159265359
#define TEXTUREFILE1 "textures/quad_texture.bmp"
#define TEXTUREFILE2 "textures/act_quad_texture.bmp"
static void on_display();
static void on_reshape(int width, int height);
static void on_keyboard(unsigned char key, int x, int y);
static void on_keyboard2(int key, int x, int y);
static void on_timer(int id);
//pomocne funkcije
static void initialize_textures();
static void draw_square2(float x_coord, float z_coord, int activated);
static void animate_player();
void postavi_nivo(int lvl);
//globalne promenljive za animaciju
float animation_parameter = 0;
int animation_ongoing = 0;
//imena tekstura
static GLuint tex_names[2];
//smer kretanja igraca koji je u pocetku u smeru z ose
int direction = 2;
//da li je pozitivan smer, u pocetku jeste pa je jednak 1
//tj da li inkrementiramo ili dekrementiramo kretanjeq
int positive_dir = 1;
//smerovi kretanja pre nego sto smo stisnuli taster
int last_dir =2;
int last_pos_dir=1;
//brzina kretanja igraca
float vel_incr = 0.02;
int main(int argc, char **argv)
{
/* Inicijalizuje se GLUT. */
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
/* Kreira se prozor. */
glutInitWindowSize(800, 800);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
/* Registruju se callback funkcije */
glutDisplayFunc(on_display);
glutReshapeFunc(on_reshape);
glutKeyboardFunc(on_keyboard);
glutSpecialFunc(on_keyboard2);
glutIdleFunc(glutPostRedisplay);
/* Obavlja se OpenGL inicijalizacija. */
glutSetKeyRepeat(GLUT_KEY_REPEAT_OFF),
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
//postavlja se osvetljenje
float light_position[] = {-1, 1, 1, 0};
float light_ambient[] = {.3f, .3f, .3f, 1};
float light_diffuse[] = {.7f, .7f, .7f, 1};
float light_specular[] = {.7f, .7f, .7f, 1};
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glClearColor(0.1,1,1,1);
initialize_textures();
glEnable(GL_NORMALIZE);
glEnable(GL_CULL_FACE);
//pozivamo jer obrcemo smer x ose
glFrontFace(GL_CW);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);
glutMainLoop();
return 0;
}
//funkcije za kontrolu kretanja i pokretanje igrice
void on_keyboard(unsigned char key, int x, int y) {
switch(key) {
case 'g':
case 'G':
if(!animation_ongoing){
animation_ongoing=1;
glutTimerFunc(TIMER_INTERVAL,on_timer,TIMER_ID);
}
break;
case ' ':
if(animation_ongoing){
animation_ongoing=0;
glutTimerFunc(TIMER_INTERVAL,on_timer,TIMER_ID);
}
break;
case 27:
glDeleteTextures(1, tex_names);
exit(0);
break;
glutPostRedisplay();
}
}
void on_keyboard2(int key, int x, int y){
switch(key){
case GLUT_KEY_UP :
if(animation_ongoing){
last_dir=direction;
last_pos_dir=positive_dir;
positive_dir=1;
direction=2;
//animation_parameter+= vel_incr;
glutPostRedisplay();
}
break;
case GLUT_KEY_RIGHT :
if(animation_ongoing){
last_dir=direction;
last_pos_dir=positive_dir;
positive_dir=1;
direction=0;
//animation_parameter= vel_incr;
glutPostRedisplay();
}
break;
case GLUT_KEY_DOWN :
if(animation_ongoing){
last_dir=direction;
last_pos_dir=positive_dir;
positive_dir=0;
direction=2;
//animation_parameter= vel_incr;
glutPostRedisplay();
}
break;
case GLUT_KEY_LEFT :
if(animation_ongoing){
last_dir=direction;
last_pos_dir=positive_dir;
positive_dir=0;
direction=0;
//animation_parameter= vel_incr;
glutPostRedisplay();
}
break;
}
}
//timer i funkcija za ponovno iscrtavanje prozora
void on_timer(int id) {
if (id == TIMER_ID) {
if(!fail_condition)
animation_parameter+=vel_incr;
}
glutPostRedisplay();
if (animation_ongoing){
glutTimerFunc(TIMER_INTERVAL,on_timer, TIMER_ID);
}
}
void on_reshape(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(30, (float) width/height, 1, 1000);
}
//funkcija za iscrtavanje
void on_display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//obrcemo x osu
//https://stackoverflow.com/questions/28632150/opengl-how-to-invert-x-axis
glScalef (-1.0, 1.0, 1.0);
//kamera se pomera sa igracem
gluLookAt(position[0], position[1]+5, position[2]-5,
position[0], position[1], position[2],
0, 1, 0);
//draw_grid();
glPushMatrix();
//iscrtavanje kvadrata po nivoima
postavi_nivo(NIVO);
glPopMatrix();
glPushMatrix();
if(!fail_condition){
fail_condition_check(NIVO);
}
//ako animacija traje pomeramo igraca
if (animation_ongoing && !fail_condition){
//u zavisnosti od smera umanjujemo ili povecavamo
if(positive_dir)
position[direction] += vel_incr;
else
position[direction] -= vel_incr;
} else if (fail_condition){
//idemo malo napred, pa propadamo, ala Pera Kojot
if(fail_animation_parameter<=0.5){
if(positive_dir)
position[direction] += vel_incr;
else
position[direction] -= vel_incr;
fail_animation_parameter += vel_incr;
} else {
//propadanje po y osi
if(fail_animation_parameter<=2.5){
position[1] -= vel_incr;
fail_animation_parameter += vel_incr;
} else {
//dosli smo do kraja animacije propadanja i izlazimo iz programa
glDeleteTextures(2, tex_names);
exit(EXIT_FAILURE);
}
}
}
//pomeramo igraca
glTranslatef(position[0],position[1],position[2]);
//lopta tj. igrac koji se krece po kvadratima
//pomocu promenljivih pravimo vektore
//
int vector_old[2];
int vector_new[2];
if(direction==0)
if(positive_dir==1){
vector_new[0]=-1;
vector_new[1]=0;
}
else {
vector_new[0]=1;
vector_new[1]=0;
}
else
if(positive_dir==1){
vector_new[0]=0;
vector_new[1]=-1;
}
else {
vector_new[0]=0;
vector_new[1]=1;
}
if(last_dir==0)
if(positive_dir==1){
vector_old[0]=-1;
vector_old[1]=0;
}
else {
vector_old[0]=1;
vector_old[1]=0;
}
else
if(last_pos_dir==1){
vector_old[0]=0;
vector_old[1]=-1;
}
else {
vector_old[0]=0;
vector_old[1]=1;
}
double dot = vector_old[0]*vector_new[1] + vector_old[0]*vector_old[1];
double det = vector_old[0]*vector_new[1] - vector_old[1]*vector_new[0];
//ako idemo u istom smeru i dalje nema potrebe rotirati
glPushMatrix();
if(!(last_dir==direction && last_pos_dir==positive_dir)){
if(last_dir==direction){
if(direction==2)
glRotatef(180,0,1,0);
else
glRotatef(270 ,0,1,0);
}
else
glRotatef((2*atan2(det,dot)*180/M_PI)+90,0,1,0);
}
animate_player();
glPopMatrix();
//proveravamo koliko nam je ostalo kvadrata na nivou
int num_of_sq = 0;
if(!fail_condition){
num_of_sq=get_number_of_sq(NIVO);
}
//ako smo ostali sa samo jednim kvadratom onda prelazimo na sledeci nivo
if(!fail_condition){
if(num_of_sq==1){
if(NIVO==MAX_LEVEL){
glDeleteTextures(2, tex_names);
exit(EXIT_SUCCESS);
}
NIVO+=1;
set_zeroes();
set_current_level(NIVO);
set_player_position(NIVO);
}
}
glPopMatrix();
// stampamo tekst
print_level_info();
glBindTexture(GL_TEXTURE_2D, 0);
glutSwapBuffers();
}
//Pomocna funkcija koja ucitava teksture
//kod za rad sa teksturama preuzet sa sedmog casa Racunarske grafike
void initialize_textures(){
Image* image;
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV,
GL_TEXTURE_ENV_MODE,
GL_REPLACE);
image = image_init(0, 0);
image_read(image, TEXTUREFILE1);
glGenTextures(2, tex_names);
glBindTexture(GL_TEXTURE_2D, tex_names[0]);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
image->width, image->height, 0,
GL_RGB, GL_UNSIGNED_BYTE, image->pixels);
image_read(image, TEXTUREFILE2);
glBindTexture(GL_TEXTURE_2D, tex_names[1]);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
image->width, image->height, 0,
GL_RGB, GL_UNSIGNED_BYTE, image->pixels);
glBindTexture(GL_TEXTURE_2D, 0);
image_done(image);
}
//Pomocna funkcija za iscrtavanje kvadrata, activated ima vrednost 0 ili 1 u zavisnosti od toga da li je kvadrat aktivan , tj igrac stoji na njemu ili ne
void draw_square2(float x_coord, float z_coord, int activated){
glPushMatrix();
glTranslatef(x_coord,0,z_coord);
glColor3f(0,0,0);
glBindTexture(GL_TEXTURE_2D, tex_names[activated]);
glBegin(GL_QUADS);
glNormal3f(0,1,0);
glTexCoord2f(0, 0);
glVertex3f(0.5,0,0.5);
glTexCoord2f(0, 1);
glVertex3f(0.5,0,-0.5);
glTexCoord2f(1, 1);
glVertex3f(-0.5,0,-0.5);
glTexCoord2f(1, 0);
glVertex3f(-0.5,0,0.5);
glEnd();
postavi_boje(0,0,0,1);
/* Iskljucujemo aktivnu teksturu */
glBindTexture(GL_TEXTURE_2D, 0);
glPushMatrix();
glTranslatef(0,0.005,0);
glBegin(GL_LINE_STRIP);
glVertex3f(0.5,0,0.5);
glVertex3f(0.5,0,-0.5);
glVertex3f(-0.5,0,-0.5);
glVertex3f(-0.5,0,0.5);
glEnd();
glPopMatrix();
glPopMatrix();
}
//pomocna funkcija za iscrtavanje igraca
void animate_player(){
postavi_boje(0.3,0.3,0.9,1.0);
//ravan za presecanje kupe kako bi napravili torzo
double clip_plane[] = {0,1,0,-0.05};
glPushMatrix();
//glava
glPushMatrix();
glScalef(0.7,1,0.7);
glTranslatef(0,0.35,0);
glutSolidSphere(0.05,32,32);
glPopMatrix();
//torzo
glPushMatrix();
glTranslatef(0,0.1,0);
glClipPlane(GL_CLIP_PLANE0, clip_plane);
glEnable(GL_CLIP_PLANE0);
glPushMatrix();
glTranslatef(0,0.2,0);
glRotatef(90,1,0,0);
glScalef(1,0.3,1);
glutSolidCone(0.1, 0.3, 64, 64);
glPopMatrix();
glDisable(GL_CLIP_PLANE0);
glPopMatrix();
//noge
glPushMatrix();
glTranslatef(0,0.2,0);
glRotatef(-10*sin(6*animation_parameter),1,0,0);
glTranslatef(0,-0.2,0);
glTranslatef(-0.02,0.02,0);
glScalef(0.03,0.3,0.03);
glutSolidSphere(0.5,32,32);
glPopMatrix();
glPushMatrix();
glTranslatef(0,0.2,0);
glRotatef(10*sin(6*animation_parameter),1,0,0);
glTranslatef(0,-0.2,0);
glTranslatef(0.02,0.02,0);
glScalef(0.03,0.3,0.03);
glutSolidSphere(0.5,32,32);
glPopMatrix();
//ruke
glPushMatrix();
glTranslatef(0,0.27,0);
glRotatef(-8*sin(5*animation_parameter),1,0,0);
glTranslatef(0,-0.27,0);
glTranslatef(0.09,0.2,0);
glScalef(0.03,0.2,0.03);
glutSolidSphere(0.5,32,32);
glPopMatrix();
glPushMatrix();
glTranslatef(0,0.27,0);
glRotatef(8*sin(5*animation_parameter),1,0,0);
glTranslatef(0,-0.27,0);
glTranslatef(-0.09,0.2,0);
glScalef(0.03,0.2,0.03);
glutSolidSphere(0.5,32,32);
glPopMatrix();
glPopMatrix();
}
// pomocna funkcija za postavljanje nivoa, takodje postavlja neaktivne kvadrate
void postavi_nivo(int lvl){
int i=0,j=0;
int mati=nivo_dimenzije[lvl-1][0];
int matj=nivo_dimenzije[lvl-1][1];
while(i<mati){
j=0;
while(j<matj){
//ako nije obrisan, iscrtavamo kvadrat
if(curr_lvl_kv[i][j]){
//provera da li je igrac i dalje na kvadratu ako nije onda ga brisemo, takodje proveravamo da li je igrac presao na neki drugi kvadrat
if(curr_lvl_akt[i][j]){
if(provera(i+0.5,j+0.5)){
draw_square2(0.5+i,0.5+j, 1);
} else {
curr_lvl_kv[i][j]=0;
curr_lvl_akt[i][j]=0;
}
} else {
if(provera(i+0.5,j+0.5))
curr_lvl_akt[i][j]=1;
draw_square2(0.5+i,0.5+j,0);
}
}
j+=1;
}
i+=1;
}
}
|
C
|
#include<stdlib.h>
void merge(long src1[], long src2[], long dest[], long n){
long i1 = 0;
long i2 = 0;
long id = 0;
while(i1 < n || i2 < n){
long min = src1[i1] > src2[i2] ? src2[i2] : src1[i1];
i1++;
i2++;
i1 = src1[i1-1] > src2[i2-1] ? i1 - 1 : i1;
i2 = src1[i1-1] > src2[i2-1] ? i2 : i2 - 1;
dest[id++] = min;
}
while(i1 < n)
dest[id++] = src1[i1++];
while(i2 < n)
dest[id++] = src2[i2++];
}
|
C
|
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <stdlib.h>
#include <mpi.h>
#define MASTER 0
#define OUTPUT_NUM 10
void SequentialSort(void);
void CompareLow(int bit);
void CompareHigh(int bit);
int ComparisonFunc(const void* a, const void* b);
int min ( int a, int b ) { return a < b ? a : b; }
void OutputAll();
clock_t timer_init;
clock_t timer_start;
clock_t timer_end;
int process_rank;
int num_processes;
int* array;
int* one_before_array;
int array_size;
int main(int argc, char* argv[]) {
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_processes);
MPI_Comm_rank(MPI_COMM_WORLD, &process_rank);
MPI_Barrier(MPI_COMM_WORLD); // For time measurement
if(process_rank == MASTER)
timer_init = clock();
// Store the array with one more integer in front, so we can easily transmit the size of data to be sent too
int num_elements = atoi(argv[1]);
array_size = num_elements / num_processes;
array = (int*) malloc((array_size) * sizeof(int)); // For some reason there seem to be some out of array accesses
// Generate random data in master and send out to all processes
if(process_rank == MASTER) {
srand(time(NULL));
int* tmparray = (int*)malloc(num_elements * sizeof(int));
for(int i = 0; i < num_elements; i++) {
tmparray[i] = rand() % num_elements;
// Already copy over own elements
if(i < array_size)
array[i] = tmparray[i];
}
for(int i = 1; i < num_processes; i++) {
MPI_Send(
&tmparray[i*array_size],
array_size,
MPI_INT,
i,
0,
MPI_COMM_WORLD
);
}
free(tmparray);
}
else {
MPI_Recv(
&array[0],
array_size,
MPI_INT,
MASTER,
0,
MPI_COMM_WORLD,
MPI_STATUS_IGNORE
);
}
MPI_Barrier(MPI_COMM_WORLD); // For time measurement
if (process_rank == MASTER) {
printf("Number of Processes spawned: %d\n", num_processes);
timer_start = clock();
}
qsort(array, array_size, sizeof(int), ComparisonFunc);
int dimensions = (int)(log2(num_processes)); // Number of i-blocks
for (int i = 0; i < dimensions; i++) {
for (int j = i; j >= 0; j--) {
// i identifies the window (blue/green box in .pdf), j the iteration within this.
// j also represents the distance to send the data to, 0->1, 1->2, 2->4, 3->8 etc (this is used in the compare functions)
// The actual high/low distro is magic to me
if (((process_rank >> (i + 1)) % 2 == 0 &&
(process_rank >> j) % 2 == 0) ||
((process_rank >> (i + 1)) % 2 != 0 &&
(process_rank >> j) % 2 != 0)) {
CompareLow(j);
} else {
CompareHigh(j);
}
}
}
MPI_Barrier(MPI_COMM_WORLD); // Replace with MPI-Gather if you actually want to distribute data
//OutputAll();
free(array);
MPI_Finalize();
if (process_rank == MASTER) {
timer_end = clock();
printf("Time Elapsed (Sec): %f, time since init: %f\n",
(double)(timer_end - timer_start) / CLOCKS_PER_SEC,
(double)(timer_end - timer_init) / CLOCKS_PER_SEC);
}
return 0;
}
void OutputAll() {
for(int i = 0; i < num_processes; i++) {
MPI_Barrier(MPI_COMM_WORLD);
if (i == process_rank) {
printf("Process %d: ", i);
for (int j = 0; j < min(OUTPUT_NUM, array_size); j++) {
printf("%d ",array[j]);
}
printf("\n");
}
}
}
int ComparisonFunc(const void* a, const void* b) {
return ( *(int*)a - *(int*)b );
}
// This one is a low-element
void CompareLow(int j) {
// Send everything to the other process, that one sorts it and sends it back
// TODO optimize by sending only what's between the medians
// the high party could send it's median,
// if their median is higher, send upper half and receive their lower half
// if our median is higher, also send all array elements below the middle that are still higher than their median and wait for them to send back their lower half afterwards
MPI_Send(
&array[0],
array_size,
MPI_INT,
process_rank ^ (1 << j),
0,
MPI_COMM_WORLD
);
MPI_Recv(
&array[0],
array_size,
MPI_INT,
process_rank ^ (1 << j),
0,
MPI_COMM_WORLD,
MPI_STATUS_IGNORE
);
return;
}
void CompareHigh(int j) {
// Receive the data from the other partner, sort it, send it back
int* buffer = (int*)malloc(array_size * 2 * sizeof(int));
MPI_Recv(
&buffer[0],
array_size*2,
MPI_INT,
process_rank ^ (1 << j),
0,
MPI_COMM_WORLD,
MPI_STATUS_IGNORE
);
// Copy over our part of the array
for(int i=0; i< array_size; i++) {
buffer[array_size + i] = array[i];
}
// Sort everything
qsort(buffer, array_size*2, sizeof(int), ComparisonFunc);
MPI_Send(
&buffer[0],
array_size,
MPI_INT,
process_rank ^ (1 << j),
0,
MPI_COMM_WORLD
);
// Copy back the buffer
for(int i=0; i<array_size; i++) {
array[i] = buffer[i + array_size];
}
free(buffer);
return;
}
|
C
|
/* this contains the public definitions for the player module */
#pragma once
enum playerType {
human, computer, inactive
};
#define Player1 1
#define Player2 2
#define Player3 3
#define Player4 4
#define noPlayer -1
#define playerError -1
#define maxNumberOfPlayers 4
#define GetFirstCity(_league) (GetNextCity((_league), -1))
short AddPlayer(enum playerType type);
void DestroyPlayerInfo(void);
void DropPlayer(short league);
short GetCurrentPlayer(void);
short GetFirstActivePlayer(void);
short GetLastActivePlayer(void);
short GetNextActivePlayer(short which);
short GetNextCity(short league, short city);
short GetNumberOfHumanPlayers(void);
short GetNumberOfPlayers(void);
enum playerType GetPlayerStatus(short league);
void InitPlayerInfo(void);
void RestorePlayerInfo(void);
void SavePlayerInfo(void);
void SetPlayerStatus(short league, enum playerType status);
Boolean SetCurrentPlayer(short player);
|
C
|
#include <iostream>
#include "PackedForest.h"
#include "TreeNode.h"
#include "LabelSpan.h"
#include <string>
//#include "LiBE.h"
using namespace std;
using namespace __gnu_cxx;
using namespace mtrule;
////////////////////////////////////////////////////////////////
// Packed Forest.
////////////////////////////////////////////////////////////////
template<class T>
PackedForest<T>:: ~PackedForest()
{
}
#if 0
template<class T>
ORNode<T>* PackedForest<T>::
addNode(const ANDNode<T> & andNode)
{
typename T::Signature sig = andNode.data.getSig(); //
// andNode sholuld have assignment.
ORNode<T>* pnode;
if(pnode = m_index[sig]){
pnode->push_back(andNode);
} else {
ORNode<T> orNode;
orNode.id=m_nodes.size();
m_nodes.push_back(orNode);
m_nodes.back().push_back(andNode);
m_index[sig] = &m_nodes.back();
pnode = & m_nodes.back();
}
return pnode;
}
#endif
//! Ands an AND node into the packed forest. Automatically add and ID,
//! if the corresponding OR node doesnt exist.
template<class T>
ORNode<T>* PackedForest<T>::
addNodeBySig(const ANDNode<T> & andNode)
{
//cerr<<"Adding and node:"<<andNode.data.getSig()<<endl;
ostringstream ost;
ost<<andNode.data.getSig();
typename hash_map<string, ORNode<T>*>::const_iterator it1;
it1 = m_indexBySig.find(ost.str());
if(it1 != m_indexBySig.end()){
typename list<ANDNode<T> >::const_iterator it2;
for(it2 = it1->second->begin(); it2 != it1->second->end(); ++it2){
if(*it2 == andNode){ break; }
}
if(it2 == it1->second->end()){
it1->second->push_back(andNode);
it1->second->back().setType(ForestNode::AND);
}
return it1->second;
} else {
// create a new OR node, and then put this and node in.
ORNode<T> n;
m_nodes.push_back(n);
m_nodes.back().id = m_nodes.size() + 1;
m_nodes.back().push_back(andNode);
m_indexBySig[ost.str()] = &m_nodes.back();
m_nodes.back().setType(ForestNode::OR);
return &(m_nodes.back());
}
}
//! Ands an AND node into the packed forest. Automatically add and ID,
//! if the corresponding OR node doesnt exist.
template<class T>
ORNode<T>* PackedForest<T>::
addNodeById(const ANDNode<T> & andNode, int id)
{
//cerr<<"Adding and node:"<<andNode.data.getSig()<<endl;
ostringstream ost;
ost<<andNode.data.getSig();
ORNode<T>* pOR = const_cast<ORNode<T>*>(getORNode(id));
if(pOR){
typename list<ANDNode<T> >::const_iterator it2;
pOR->push_back(andNode);
pOR->back().setType(ForestNode::AND);
return pOR;
} else {
// create a new OR node, and then put this and node in.
ORNode<T> n;
m_nodes.push_back(n);
m_nodes.back().id = id;
m_nodes.back().push_back(andNode);
m_nodes.back().setType(ForestNode::OR);
m_nodes.back().back().setType(ForestNode::AND);
return &(m_nodes.back());
}
}
template<class T>
const ORNode<T>* PackedForest<T>::
getNode(const string sig) const
{
typename hash_map<string, ORNode<T>*>::const_iterator it1;
it1 = m_indexBySig.find(sig);
if(it1 != m_indexBySig.end()){
return it1->second;
} else { return NULL; }
}
//! Get an ORNode pointer via an ORNode id.
template<class T>
const ORNode<T>* PackedForest<T>:: getORNode(int id) const {
typename list<ORNode<T> >::const_iterator itlist;
for(itlist = m_nodes.begin(); itlist != m_nodes.end(); ++itlist){
if((*itlist).id == id){return &(*itlist);}
}
return NULL;
}
template<class T>
istream& PackedForest<T>::get(istream& in)
{
if(in.peek() == '0') { m_root = NULL; return in; }
ORNode<T>* orNode;
try{
orNode = read_an_OR_node(in, 0);
setAsRoot(orNode);
} catch (ForestFormatError& e) {
setAsRoot(NULL);
return in;
}
computeSpans();
orNode->copyUp();
// also create the signature map here.
return in;
}
// or-node is of form
// form1: (#id (NN ...) ... (NN ...), or
// form2: (#id)
// form3 (#id leaf)
// the latter node refers to anther node in the shared forest.
template<class T>
ORNode<T>*PackedForest<T>::read_an_OR_node(istream& in, int height)
{
char ch;
while(in.peek() == ' '){ in>>ws;}
if(in.eof()){ return NULL; }
// we come to (
in>>ch;
if(ch != '('){
cerr<<"Expected (, but got "<<ch<<endl;
throw ForestFormatError();
return NULL;
}
// we come to #
in>>ch;
if(ch != '#'){
cerr<<"Expected #, but got "<<ch<<endl;
throw ForestFormatError();
return NULL;
}
// or node id.
int nodeID;
in >> nodeID;
while(in.peek() == ' '){ in>>ws;}
// if this or node stores just a id ..., i.e., (#4)
if(in.peek() == ')'){
in>>ch;
return const_cast<ORNode<T>*>(getORNode(nodeID));
} else {
ORNode<T>* porNode = NULL;
// (#4 (NN...) (NN ...))
// form3 (#id leaf)
while(in.peek() != ')'){
ANDNode<T>* pandNode=read_an_AND_node(in, height);
porNode = addNodeById(*pandNode, nodeID);
porNode->id = nodeID;
delete pandNode;
while(in.peek() == ' '){ in>>ws; }
}
// read the )
in>>ch;
return porNode;
}
}
// an and node is of form
// (label #1(children)).
template<class T>
ANDNode<T>*PackedForest<T>::read_an_AND_node(istream& in, int height)
{
char ch;
ANDNode<T>* andNode = new ANDNode<T>;
while(in.peek() == ' '){in>>ws;}
if(in.eof()){ return NULL; }
// not a leaf
if(in.peek() == '('){
in >> ch;
// read the label.
in >> andNode->data.getSig().label;
while(in.peek() == ' '){in>>ws;}
while(in.peek() != ')'){
try {
andNode->push_back(read_an_OR_node(in, height+1));
} catch (ForestFormatError& e){
throw e;
return NULL;
}
while(in.peek() == ' '){in>>ws;}
}
while(in.peek() == ' '){in>>ws;}
in >> ch;
} else {
// leaf
string label = "";
while(in.peek() != ')'){
in>>ch;
label += ch;
}
//in >>ch;
// if the label is '-RRB-' or '-LRB-', we change it into ')' or '('
// sliently. that is, internally, it is always the round bracketes
// themselves. on disk, it will be -RRB- or -LRB-.
// Wei Wang Wed Feb 21 12:22:02 PST 2007
//if(label == "-RRB-") { label = ")";}
//if(label == "-LRB-") { label = "(";}
string::size_type pos;
while((pos=label.find("-RRB-")) != string::npos){
label.replace(pos, 5, ")");
}
while((pos=label.find("-LRB-")) != string::npos){
label.replace(pos, 5, "(");
}
andNode->data.getSig().label = label;
andNode->data.getSig().isInternal = false;
}
return andNode;
}
template<class T>
void PackedForest<T>::
writeNode(ostream& o, const ORNode<T>* node, set<int>& writtenOut) const
{
//cout<<"OR: "<<node->is_extraction_node()<<endl;
if(writtenOut.find(node->id) != writtenOut.end()){
o<<" (#"<<node->id<<")";
} else {
o<<" (#"<<node->id<<"";
// o<<" " <<node->type()<<" ";
typename list<ANDNode<T> > :: const_iterator it;
for(it = node->begin(); it != node->end(); ++it){
writeNode(o, &(*it), writtenOut);
}
o<<")";
writtenOut.insert(node->id);
}
}
template<class T>
void PackedForest<T>::
writeNode(ostream& o, const ANDNode<T>* node, set<int>& writtenOut) const
{
// cout<<"AND: "<<node->is_extraction_node()<<endl;
if(node->size()){
// internal node.
o<<" ("<<node->data.getSig().label<<" ";
//o<<"--" <<node->get_span().first<<"-"<< node->get_span().second<<" ";
// o<<"::"<<node->is_extraction_node()<<" ";
typename list<ORNode<T>*>::const_iterator it;
for(it = node->begin(); it != node->end(); ++it){
writeNode(o, *it, writtenOut);
}
o<<")";
} else {
// leaf
string label = node->data.getSig().label;
// Wei Wang Wed Feb 21 12:06:16 PST 2007
//if(label == ")") { label = "-RRB-"; }
//else if(label == "("){ label = "-LRB-"; }
// replace every ')' (or '(') occurence with '-RRB-' or '-LRB-'.
string::size_type pos;
while((pos=label.find(")")) != string::npos){
label.replace(pos, 1, "-RRB-");
}
while((pos=label.find("(")) != string::npos){
label.replace(pos, 1, "-LRB-");
}
o<<" "<<label;
}
}
template<class T>
ostream& PackedForest<T>:: put(ostream& out) const
{
set<int> orNodeIDs;
if(m_root){
writeNode(out, m_root, orNodeIDs);
} else {
out<<"0"<<endl;
}
return out;
}
template<class T>
void PackedForest<T>:: changeToNextRoot()
{
if(getRoot()){
if(getRoot()->size()){
setAsRoot(*(getRoot()->begin()->begin()));
}
}
}
template<class T>
void PackedForest<T>::cutLeaves()
{
if(!m_root) { return;}
set<mtrule::TreeNode*> nodes;
set<mtrule::TreeNode*> doneNodes;
cutLeavesOfSubForest(getRoot(), nodes, doneNodes);
for(typename set<mtrule::TreeNode*>::iterator it = nodes.begin();
it != nodes.end(); ++it) {
ANDNode<T>* andNode = static_cast<ANDNode<T>*>(*it);
string word = (*andNode->begin())->begin()->data.getSig().label;
andNode->set_word(word);
andNode->get_subtrees().clear();
andNode->clear();
}
}
template<class T>
void PackedForest<T>::cutLeavesOfSubForest(mtrule::TreeNode* node, set<mtrule::TreeNode*>& nodes, set<mtrule::TreeNode*> & doneNodes)
{
if(doneNodes.find(node) != doneNodes.end()){
return;
}
if(node) {
if(node->type() == ForestNode::AND){
ANDNode<T>* andNode = dynamic_cast<ANDNode<T>*>(node);
assert(andNode);
if(andNode->size() == 1 && (*andNode->begin())->size() == 1 &&
(*andNode->begin())->begin()->size() == 0){
nodes.insert(andNode);
#if 0
string word = (*andNode->begin())->begin()->data.getSig().label;
andNode->set_word(word);
andNode->get_subtrees().clear();
andNode->clear();
#endif
// return;
}
for(typename list<ORNode<T>*>::iterator it = andNode->begin(); it != andNode->end();
++it){
cutLeavesOfSubForest(*it, nodes, doneNodes);
}
} else if(node->type() == ForestNode::OR){
ORNode<T>* orNode = dynamic_cast<ORNode<T>*>(node);
assert(orNode);
for(typename list<ANDNode<T> >::iterator it = orNode->begin(); it != orNode->end();
++it){
cutLeavesOfSubForest(&(*it), nodes, doneNodes);
}
} else {
// cout<<"ERROR: "<<node->get_cat()<<" "<<node->type()<<" span: "<<node->get_span().first<<"-"<<node->get_span().second<<endl;
}
}
doneNodes.insert(node);
}
|
C
|
#include "../ostypes.h"
#include "io.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
static FILE *fd;
extern int byteCount;
void openOutput() {
fd = fopen(OUTPUTFILE, "wb");
if (!fd) {
char cwd[1024];
perror("failed to open file for writing");
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working dir: %s\n", cwd);
} else {
perror("getcwd() error");
}
exit(1);
}
}
void openInput() {
fd = fopen(OUTPUTFILE, "rb");
if (!fd) {
char cwd[1024];
perror("failed to open file for reading");
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working dir: %s\n", cwd);
} else {
perror("getcwd() error");
}
exit(1);
}
}
void closeIO(void) {
if (fclose(fd)) {
perror("failed to close file");
exit(1);
}
}
void dumpByte(unsigned char b) {
unsigned char buf[1];
buf[0] = b;
if (fwrite(buf, 1, 1, fd) != 1) {
perror("failed to write to file");
exit(1);
}
byteCount++;
}
unsigned char readByte() {
unsigned char buf[1];
while (1) {
int res = fread(buf, 1, 1, fd);
if (res == -1) {
perror("failed to read from file");
exit(1);
} else {
byteCount++;
return buf[0];
}
}
return -1;
}
void* _malloc_(int size) {
return malloc(size);
}
|
C
|
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/wait.h>
#include <time.h>
#include "consoleUtils.h"
int main(int argc, char *argv[])
{
//int max_process_num = readNumber(argc, argv);
int max_process_num = 5;
int cur_process_num = 0;
pid_t pid = 0;
int fd[2] = {0};
int message = 0;
int status = 0;
while (1)
{
if (cur_process_num < max_process_num)
{
if (pipe(fd) < 0)
{
printf("Can\'t create pipe\n");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == 0)
break;
close(fd[0]);
write(fd[1], &message, sizeof(int));
//Increment current number of active processes
cur_process_num++;
//Increment message
message++;
}
// Track errors
pid = waitpid(-1, &status, WNOHANG);
if (pid != 0)
{
while (WEXITSTATUS(status))
{
pipe(fd);
pid = fork();
if (pid == 0)
{
close(fd[1]);
unsigned int msg = 0;
read(fd[0], &msg, sizeof(int));
// Msg as seed
srand(msg);
// Sleep ..zzzz..
unsigned int sec = rand() % 6u + 7u;
sleep(sec);
status = rand() % 2;
pid_t child_pid = getpid();
printf("PID = %d msg = %d status = %d\n", child_pid, msg, status);
return status;
}
close(fd[0]);
write(fd[1], &message, sizeof(int));
}
cur_process_num--;
}
}
close(fd[1]);
unsigned int msg = 0;
read(fd[0], &msg, sizeof(int));
// Msg as seed
srand(msg);
// Sleep ..zzzz..
unsigned int sec = rand() % 6u + 7u;
sleep(sec);
status = rand() % 2;
pid_t child_pid = getpid();
printf("PID = %d msg = %d status = %d\n", child_pid, msg, status);
return status;
}
|
C
|
/*
* Autonroutines.c
*
* Created on: Nov 28, 2014
* Author: Kyle Medeiros and Wenheng Lu
*/
#include "main.h"
#define FORWARD 0
#define BACKWARD 1
#define LEFT 0
#define RIGHT 1
#define UP 0
#define DOWN 1
#define BW 0
#define FW 1
void Autonroutines(int Routine){
if (Routine == 1){ //First Auton Routine, Red Autoloader
drivePID (500, 500, FORWARD, 127);
lift (1000, 127);
lift (1000, -127);
liftP (AUTOLOADER, 1000, 50);
/*
while (digitalRead (3)== HIGH){
}
turnPID (62, 1500,LEFT, 127);
while (digitalRead (3)== HIGH){
}
drivePID (300, 500, BACKWARD, 127);
drivePID (100, 100, FORWARD, 127);
while (digitalRead (3)== HIGH){
}
lift (400, 127);
drivePID (500, 1000, FORWARD, 127);
turnPID (52, 1000, LEFT, 127);
while (digitalRead (3)== HIGH){
}
drivePID (200, 500, BACKWARD, 127);
while (digitalRead (3)== HIGH){
}
liftP (GROUND, 1000, 0);
drivePID (300, 500, FORWARD, 127);
*/
}//End of Red Skyrise Autonomous
else if (Routine == 2){ //Second Auton , Blue
}
else if (Routine == 3){ //Third Auton Routine, Red Post
//Starting orientation: Robot is facing (and lined up with) the cube by the medium post. Preload is placed such that
//it is touching the "cheater post" and the rear of the lift.
liftP (POSTL, 2000, -120); //Cheater Cube, 3 points
drivePID (1000, 300, BACKWARD, 127);
liftP (POSTL, 1000, -500);
drivePID (900, 500, FORWARD, 127);
/*
drivePID (500, 1000, FORWARD, 127); //Drive to get 1st cube
drivePID (100, 600, BACKWARD, 127); //Slightly back up
turnPID (400, 500, LEFT, 127);
liftP (GROUND, 2000, 0); //Pick up a cube
lift (500, -127);
liftP (POSTM, 2600, 0);
while (digitalRead (3)== HIGH){
}
turnPID (90, 1000, LEFT, 127);
drivePID (400, 1000, FORWARD, 127);
turnPID (90, 1000, RIGHT, 127);
drivePID (500, 1100, FORWARD, 127);
turnPID (90, 1000, RIGHT, 127);
drivePID (1000, 1700, FORWARD, 127);
while (digitalRead (3)== HIGH){
}
drivePID (1, 1700, FORWARD, 127);
liftP (POSTM, 500, -90);
liftP (POSTM ,500, 0);
turnPID (180, 2000, RIGHT, 127);
drivePID (400, 1000, FORWARD, 127);
//Position to intake a second cube
while (digitalRead (3)== HIGH){
}
drivePID (500, 3000, FORWARD, 127); //Drive to cube
turnPID (180, 3000, RIGHT, 127); //Turn around to face Medium Post
*/
/* drivePID (1000, 3000, FORWARD, 127);
liftP (POSTM, 1000, -100); //Press intake down onto post to score cubes (5 points)
liftP (POSTM, 1000, 0); //Raise lift
//Point total: 8
*/
}
else if (Routine == 4){ //Fourth Auton Routine, Blue Post
}
else if (Routine == 5){ //Fifth Auton Routine, Programming Skills (Primary)
Autonroutines (1); // Run Red autonomous
while (digitalRead (3)== HIGH){
}
//Pick up the cube to the left of the starting tile
lift (550, -120);
drivePID (400, 1000, FORWARD, 127 );
lift (100, 127);
lift (100, -127);
lift (500, 127);
//Turn to face Skyrise
turnPID (160, 1500, RIGHT, 127);
//Score a second cube
lift (1300, 127);
drivePID (460, 1000, FORWARD, 127); //Forward was originally 400.
lift (800, -127);
drivePID (400, 1000, BACKWARD, 127);
while (digitalRead (3)== HIGH){
}
lift (800, -127);
drivePID (800, 1500, FORWARD, 127);
lift (1700, 127);
turnPID (130, 1500, RIGHT, 127);
drivePID (500, 1000, FORWARD, 127);
lift (400, -127);
drivePID (800, 1000, BACKWARD, 127);
//Score a third cube
}
else if (Routine == 6){ //Sixth Auton Routine, Programming Skills (Backup)
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/wait.h>
#define MENSAGEM_MAX 80
#define CHAVE 8180
int main ( int argc, char *argv[]){
int segmento, i;
char *mensagem;
// aloca a memória compartilhada
segmento = shmget (IPC_PRIVATE, MENSAGEM_MAX*sizeof(char), IPC_CREAT | S_IRUSR |S_IWUSR);// associa a memória compartilhada ao processo
mensagem = (char*) shmat (segmento, 0, 0);// comparar o retorno com -1
printf("%d\n", segmento);
if(segmento<0)printf("erro\n");
scanf(" %[^\n]", mensagem);
printf("%s\n", mensagem);
for(i=90;i>5;i--){
printf("%d\n", i);
sleep(1);
}
printf("SEU TEMPO ESTÁ ACABANDO!\n");
for(i=5;i>0;i--){
printf("%d\n", i);
sleep(1);
}
printf("VAI EXPLODIR!!\n");
printf("%s\n", mensagem);
// libera a memória compartilhada do processo
shmdt(mensagem);
// libera a memória compartilhada
//shmctl(segmento, IPC_RMID, 0);
return 0;
}
|
C
|
#include "uart.h"
#include <avr/io.h>
#include <stdio.h>
#include <util/setbaud.h>
#ifdef __cplusplus
extern "C" {
#endif
void uart_init() {
UBRR3H = UBRRH_VALUE;
UBRR3L = UBRRL_VALUE;
#if USE_2X
UCSR3A |= _BV(U2X3);
#else
UCSR3A &= ~(_BV(U2X3));
#endif
UCSR3C = _BV(UCSZ31) | _BV(UCSZ30);
UCSR3B = _BV(RXEN3) | _BV(TXEN3);
}
int uart_putchar(char c) {
if (c == '\n') {
uart_putchar('\r');
}
loop_until_bit_is_set(UCSR3A, UDRE3);
UDR3 = c;
return 0;
}
int uart_getchar() {
loop_until_bit_is_set(UCSR3A, RXC3);
return UDR3;
}
void uart_puts(const char *text) {
const char *ptr = text;
for (;;) {
char c = *ptr;
if (c == 0) {
break;
}
uart_putchar(c);
++ptr;
}
}
void uart_putu32(uint32_t x) {
char buffer[12] = {0};
snprintf(buffer, sizeof(buffer), "%u", x);
uart_puts(buffer);
}
void uart_putd32(int32_t x) {
char buffer[13] = {0};
snprintf(buffer, sizeof(buffer), "%d", x);
uart_puts(buffer);
}
void uart_putu8b(uint8_t x) {
char buffer[9] = {0};
for (int index = 7; index >= 0; --index) {
uint8_t bit = (x >> index) & 1;
if (bit) {
buffer[7 - index] = '1';
} else {
buffer[7 - index] = '0';
}
}
uart_puts(buffer);
}
void uart_putu16b(uint16_t x) {
char buffer[17] = {0};
for (int index = 15; index >= 0; --index) {
uint8_t bit = (x >> index) & 1;
if (bit) {
buffer[15 - index] = '1';
} else {
buffer[15 - index] = '0';
}
}
uart_puts(buffer);
}
void uart_putu32x(uint32_t x) {
char buffer[12] = {0};
snprintf(buffer, sizeof(buffer), "%x", x);
uart_puts(buffer);
}
void uart_putf32(float x) {
char buffer[64] = {0};
snprintf(buffer, sizeof(buffer), "%f", x);
uart_puts(buffer);
}
#ifdef __cplusplus
}
#endif
|
C
|
#include <stdio.h>
typedef struct node
{
int data;
struct node *next; //定义我自己??
} NODE, *NODEPTR; //此时NODE 是 未完成类型 即 编译器不能确定它的内存大小
//若内部 struct node *p; 就不是未完成类型了,因为 指针大小是固定的
//这时候此结构包含两个成员 一个整形和一个指针
void traverse(NODEPTR head)//遍历链表
{
NODEPTR p = head;
while (p != NULL)
{
printf("%d\n", p->data);
p = p->next;
}
// for ( ; p!=NULL;p=p->next)
// {
// printf("%d\n",p->data);
// }for循环也一样的效果
}
int main()
{
NODE a = {1, NULL}, b = {2, NULL}, c = {3, NULL};
a.next = &b; //a的指针成员指向b
b.next = &c; //b的指针成员指向c 这是个 链表
NODEPTR head, p;
head = &a; //头指针 指向链表的头
traverse(head);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.