language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
int main(void)
{
int Ingresso = 1;
int Idade = 22;
if (!Ingresso)
printf("Você não tem ingresso!\n");
if (Idade < 18)
printf("Você é menor de idade!\n");
if (!Ingresso || Idade < 18)
printf("Você não pode entrar!\n");
if (Ingresso && Idade >= 18)
printf("Entrar autorizada!\n");
return(0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_stack.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tayamamo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/02 12:25:12 by tayamamo #+# #+# */
/* Updated: 2021/04/02 13:11:19 by tayamamo ### ########.fr */
/* */
/* ************************************************************************** */
#include "stack.h"
t_stack *ft_stack_init(size_t size)
{
t_stack *new;
new = malloc(sizeof(t_stack));
if (new == NULL)
return (NULL);
new->top = 0;
new->size = size;
new->p_buf = malloc(sizeof(int) * size);
if (new->p_buf == NULL)
return (NULL);
new->p_validator = NULL;
return (new);
}
int ft_stack_push(t_stack *p, int val)
{
if (!ft_validate(p->p_validator, val) || ft_stack_is_full(p))
return (0);
p->p_buf[p->top++] = val;
return (1);
}
int ft_stack_pop(t_stack *p, int *p_ret)
{
if (ft_stack_is_empty(p))
return (0);
*p_ret = p->p_buf[--p->top];
return (1);
}
|
C
|
/******************************************************************************
* FILE: omp_bug2.c
* DESCRIPTION:
* Another OpenMP program with a bug.
* AUTHOR: Blaise Barney
* LAST REVISED: 04/06/05
******************************************************************************/
/******************************************************************************
* Comment:
* There are several bugs in this program.
* (1) tid and i declaration should be moved from top into the section of #pragma omp parallel.
* (2) modifying 'float total' to 'long int total' to solve the float point calculation problem.
* (3) There is a race condition, because two threads try to modify the memory address of total variable at the same time.
* To solve this, I have to add #pragma omp atomic to make it to be an atomic operation.
******************************************************************************/
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
int nthreads; // removing tid and i decalaration
long int total=0; // modifying from float to long int.
/*** Spawn parallel region ***/
#pragma omp parallel
{
/* Obtain thread number */
int tid = omp_get_thread_num(); // declare tid here so that tid will become private in each thread.
/* Only master thread does this */
if (tid == 0) {
nthreads = omp_get_num_threads();
printf("Number of threads = %d\n", nthreads);
}
printf("Thread %d is starting...\n",tid);
#pragma omp barrier
/* do some work */
#pragma omp for schedule(dynamic,10)
for (int i=0; i<1000000; i++){ // declare i here so that i will become private in each thread
#pragma omp atomic // add this line to solve race condition, make 'total = total + i*1.0;' an atomic operation
total = total + i*1.0;
}
printf ("Thread %d is done! Total= %ld\n",tid,total); // modifying from %e to %ld to match long int
} /*** End of parallel region ***/
}
|
C
|
#ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "THNN/generic/LogSigmoid.c"
#else
void THNN_(LogSigmoid_updateOutput)(
THNNState *state,
THTensor *input,
THTensor *output,
THTensor *buffer)
{
THTensor_(resizeAs)(output, input);
THTensor_(resizeAs)(buffer, input);
//Use the LogSumExp trick to make this stable against overflow
TH_TENSOR_APPLY3(scalar_t, output, scalar_t, input, scalar_t, buffer,
scalar_t max_elem = fmax(0, -*input_data);
scalar_t z = exp(-max_elem) + exp(-*input_data - max_elem);
*buffer_data = z;
*output_data = -(max_elem + log(z));
);
}
void THNN_(LogSigmoid_updateGradInput)(
THNNState *state,
THTensor *input,
THTensor *gradOutput,
THTensor *gradInput,
THTensor *buffer)
{
THNN_CHECK_NELEMENT(input, gradOutput);
THTensor_(resizeAs)(gradInput, buffer);
/* deriv of -max(0,-x) - log(e(0 - max(0,-x)) + e(-x - max(0,-x))) is
* -max_deriv - (-max_deriv*e(0-max(0,-x)) + (-1 - max_deriv)*e(-x - max(0,-x)))/z
* where z = e(0 - max(0,-x)) + e(-x - max(0,-x))
* which simplifies to
* -max_deriv - (z-1)/z if x is >= 0 or
* -max_deriv + (z-1)/z if x is < 0
*/
TH_TENSOR_APPLY3(scalar_t, input, scalar_t, gradInput, scalar_t, buffer,
scalar_t z = *buffer_data;
scalar_t max_deriv = 0.0;
scalar_t sign = -1.0;
if (*input_data < 0){
max_deriv = -1.0;
sign = 1.0;
}
*gradInput_data = -max_deriv - sign*((z - 1.0)/ z);
);
THTensor_(cmul)(gradInput, gradOutput, gradInput);
}
#endif
|
C
|
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main() {
int n,tot;
int k,i,s=0;
scanf("%i %i", &n, &k);
int *ar = malloc(sizeof(int) * n);
for(i = 0; i < n; i++){
scanf("%i",&ar[i]);
}
int b;
scanf("%i", &b);
ar[k]=0;
for(i=0;i<n;i++){
s=s+ar[i];
}
i=s/2;
tot=b-i;
if(i==b)
printf("Bon Appetit");
else
printf("%d",tot);
return 0;
}
|
C
|
#include "C:\Keil_v5\ARM\PACK\Keil\TM4C_DFP\1.1.0\Device\Include\TM4C123\TM4C123GH6PM.h"
#include <string.h>
#include <stdlib.h>
char readChar(void);
void printChar(char c);
void printString(char * string);
char* readString(char delimiter);
//void SystemInit();
int main(void)
{
// 1. Enable the UART0 module using the RCGCUART register (see page 344). Receiver Transmitter Run mode clock Gating control
SYSCTL->RCGCUART |= (1<<0);
// 2. Enable the clock to the appropriate GPIO module via the RCGCGPIO register (see page 340).Enabled PORTA
// To find out which GPIO port to enable, refer to Table 23-5 on page 1351.
SYSCTL->RCGCGPIO |= (1<<0);
// 3. Set the GPIO AFSEL bits for the appropriate pins (see page 671). To determine which GPIOs to
// configure, see Table 23-4 on page 1344
GPIOA->AFSEL = (1<<1)|(1<<0);
// 4. Configure the GPIO current level and/or slew rate as specified for the mode selected (see
// page 673 and page 681
// 5. Configure the PMCn fields in the GPIOPCTL register to assign the UART signals to the appropriate
// pins (see page 688 and Table 23-5 on page 1351).PORTF 0,1 Configured to UART.
GPIOA->PCTL = (1<<0)|(1<<4);
GPIOA->DEN = (1<<0)|(1<<1);
UART0->CTL &= ~(1<<0);
// 2. Write the integer portion of the BRD to the UARTIBRD register
UART0->IBRD = 104;
// 3. Write the fractional portion of the BRD to the UARTFBRD register.
UART0->FBRD = 11;
// 4. Write the desired serial parameters to the UARTLCRH register (in this case, a value of 0x0000.0060)
UART0->LCRH = (0x3<<5)|(1<<4); // 8-bit, no parity, 1-stop bit
// 5. Configure the UART clock source by writing to the UARTCC register
UART0->CC = 0x0;
// 6. Optionally, configure the DMA channel (see Micro Direct Memory Access (DMA) on page 585)
// and enable the DMA option(s) in the UARTDMACTL register
// 7. Enable the UART by setting the UARTEN bit in the UARTCTL register.
UART0->CTL = (1<<0)|(1<<8)|(1<<9);
// Configure LED pins
SYSCTL->RCGCGPIO |= (1<<5); // enable clock on PortF
GPIOF->DIR = (1<<1)|(1<<2)|(1<<3); // make LED pins (PF1, PF2, and PF3) outputs
GPIOF->DEN = (1<<1)|(1<<2)|(1<<3); // enable digital function on LED pins
GPIOF->DATA |= ((1<<1)|(1<<2)|(1<<3)); // turn off leds
while(1)
{
printString("Type");
char c = readChar();
printChar(c);
printString("\n\r");
switch(c)
{
case 'r':
GPIOF->DATA = (1<<1);
break;
case 'b':
GPIOF->DATA = (1<<2);
break;
case 'g':
GPIOF->DATA = (1<<3);
break;
default:
GPIOF->DATA &= ~((1<<1)|(1<<2)|(1<<3));
break;
}
}
}
char readChar(void)
{
char c;
while((UART0->FR & (1<<4)) != 0)
{ c = UART0->DR;
return c;}
}
void printChar(char c)
{
while((UART0->FR & (1<<5)) != 0)
{
UART0->DR = c; }
}
void printString(char * string)
{
while(*string!='\n')
{
printChar(*(string++));
}
}
|
C
|
#include <stdio.h>
#include <cs50.h>
int main(void)
{
// TODO: Prompt for start size
int height;
do
{
height = get_int("height of pyramid: ");
}
while (height > 8 || height < 1);
int i;
int j;
int d;
for (i = 0; i < height; i++)
{
for (d = height - 1; d > i; d--)
{
printf(" ");
}
for (j = 0; j <= i; j++)
{
printf("#");
}
printf("\n");
}
}
|
C
|
#include <string.h>
#include "application.h"
struct app_entry_t *new_app_sig(int id, char *sig)
{
struct app_entry_t *entry;
if (strlen(sig) >= MAX_SIG_LENGTH)
return NULL;
entry = (struct app_entry_t *)malloc(sizeof(struct app_entry_t));
if (entry) {
entry->appId = id;
strcpy(entry->regex, sig);
}
return entry;
}
struct element_s *new_sig_element(int id, char *sig)
{
struct element_s *entry;
if (strlen(sig) >= MAX_SIG_LENGTH)
return NULL;
entry = (struct element_s *)malloc(sizeof(struct element_s));
if (entry) {
entry->id = id;
strcpy(entry->match, sig);
}
return entry;
}
|
C
|
#include <stdio.h>
int main()
{
int a[7] = {3, -355, 235, 47, 67, 943, 1222};
int i;
int *ptr;
ptr = a;
for (i = 0; i < 5; i++)
printf("%p\n", ptr[i]);
return 0;
}
|
C
|
#include <stdint.h>
#include <stdio.h>
#include <string.h>
typedef uint8_t u8;
static void hexdump(u8 *ptr, unsigned len, int bytes);
u8 mem[0x20] = { 0, };
int main(void) {
memset(mem, 0xf, sizeof(mem) - 2);
// hexdump(mem, sizeof(mem), 0);
int i;
u8 A = 5;
int carry = 1;
for (i = 0; i < sizeof(mem) - 2; ++i) {
if (!(mem[i] & 1))
A += 8;
if (!(A & 2))
A += 4;
A = (A + mem[i]) & 0xf;
mem[i] = A;
if (!carry)
A += 7;
A = (A + mem[i]) & 0xF;
A = A + mem[i] + carry;
if (A >= 0x10) {
carry = 1;
A -= 0x10;
} else {
carry = 0;
}
mem[i] = (~A) & 0xf;
A = mem[i];
}
hexdump(mem, sizeof(mem), 0);
return 0;
}
static void hexdump(u8 *ptr, unsigned len, int bytes) {
int i;
for (i = 0; i < len; ++i) {
if (bytes)
printf("%02x ", ptr[i]);
else
printf("%x ", ptr[i] & 0xf);
if ((i & 15) == 15)
printf("\n");
}
}
|
C
|
#include <stdio.h>
int main() {
int n = 100;
int *p;
p = &n;
printf("%p\n", p);
printf("%d\n", n);
printf("%d\n", *p);
}
|
C
|
/* chvt.c - change virtual terminal for [k]freebsd
Copyright (C) 2009 Werner Koch
This file is free software; as a special exception the author gives
unlimited permission to copy and/or distribute it, with or without
modifications, as long as this notice is preserved.
This file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, to the extent permitted by law; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/consio.h>
#include <errno.h>
int
main (int argc, char **argv)
{
int fd, screen;
if (argc < 1 || argc > 2)
{
fputs ("Usage: chvt [VTNO]\n", stderr);
return 1;
}
if (argc == 2)
{
screen = atoi (argv[1]);
if (screen < 1 || screen > 11)
{
fprintf (stderr, "chvt: invalid screen numver %d\n", screen);
return 1;
}
}
fd = open ("/dev/ttyv0", O_RDWR, 0);
if (fd == -1)
{
fprintf (stderr, "chvt: error opening terminal: %s\n", strerror (errno));
return 1;
}
if (argc == 2)
{
if (ioctl (fd, VT_ACTIVATE, screen))
{
fprintf (stderr, "chvt: VT_ACTIVATE failed: %s\n", strerror (errno));
return 1;
}
}
else
{
if (ioctl (fd, VT_GETACTIVE, &screen))
{
fprintf (stderr, "chvt: VT_GETACTIVE failed: %s\n", strerror (errno));
return 1;
}
printf ("%d\n", screen);
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a,b,sum;
a=123;
b=456;
//a>b?printf("a"):printf("b");
sum=a+b;
printf("sum is %d\n",sum);
return 0;
}
|
C
|
#include <stdio.h>
int sum_of_natural_numbers(int n)
{
if(n == 0)
return 0;
return n + sum_of_natural_numbers(n - 1);
}
int main()
{
int n;
printf("\nEnter the number : ");
scanf("%d", &n);
printf("\nSum of first %d Natural Numbers is %d\n",n,sum_of_natural_numbers(n));
return 0;
}
|
C
|
#include<stdio.h>
#include<stdbool.h>
void DisplaySchedule(char);
int main()
{
char ch = '\0';
printf("Enter division ");
scanf("%c",&ch);
DisplaySchedule(ch);
return 0;
}
void DisplaySchedule(char c)
{
if(c=='A'||c=='a')
{
printf("Your exam is at 7 AM ");
}
else if(c=='B'||c=='b')
{
printf("Your exam is at 8:30 AM");
}
else if(c=='C'||c=='c')
{
printf("Your exam is at 9:20 AM");
}
else if(c=='D'||c=='d')
{
printf("Your exam is at 10:30 AM ");
}
else
{
printf("No division ");
}
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
char a[105], b[105];
int i;
scanf("%s %s", &a, &b);
for(i=0; i<strlen(a); i++)
{
if(a[i]<95) {a[i]+=32;}
if(b[i]<95) {b[i]+=32;}
}
i = strcmp(a, b);
printf("%d", i);
}
|
C
|
#include<stdio.h>
float celsiusToFahren(int a, int b, int c);
int main()
{
float e;
e = celsiusToFahren(0, 1.8, 32);
return 0;
}
float celsiusToFahren(int a, int b, int c)
{
float e;
e = (float) (a * b) + c;
printf("The result is:%.2f", e);
return e;
}
|
C
|
#include <stdio.h>
void main()
{
int *a1,*a2,*a3;
triangle();
printf("area of triangle= %d",a1);
rectangle();
printf("area of rectangle= %d",a2);
square();
printf("area of square= %d",a3);
}
int triangle()
{
float *l,*b,int *a1;
*a1=(1/2)*l*b;
}
void rectangle()
{
int a=5,b=10,a2;
a2=a*b;
}
/void square()
{
int s=5,a3;
a3=s*s;
}
|
C
|
#ifndef _TTY_H
#define _TTY_H
#include <termios.h>
#define TTY_BUF_SIZE 1024 //队列大小
struct tty_queue {
unsigned long data;//缓冲区中字符行数
unsigned long head;
unsigned long tail;
struct task_struct * proc_list;//该队列中的阻塞进程列表
char buf[TTY_BUF_SIZE];//队列缓冲区
};
/**
* 注意:队列的头是不放数据的
*/
#define INC(a) ((a) = ((a)+1) & (TTY_BUF_SIZE-1))
#define DEC(a) ((a) = ((a)-1) & (TTY_BUF_SIZE-1))
#define EMPTY(a) ((a).head == (a).tail)
#define LEFT(a) (((a).tail-(a).head-1)&(TTY_BUF_SIZE-1))//队列剩余空间大小
#define LAST(a) ((a).buf[(TTY_BUF_SIZE-1)&((a).head-1)])//队列最后一个字符
#define FULL(a) (!LEFT(a))
#define CHARS(a) (((a).head-(a).tail)&(TTY_BUF_SIZE-1))
#define GETCH(queue,c) \
(void)({c=(queue).buf[(queue).tail];INC((queue).tail);})
#define PUTCH(c,queue) \
(void)({(queue).buf[(queue).head]=(c);INC((queue).head);})
#define INTR_CHAR(tty) ((tty)->termios.c_cc[VINTR])
#define QUIT_CHAR(tty) ((tty)->termios.c_cc[VQUIT])
#define ERASE_CHAR(tty) ((tty)->termios.c_cc[VERASE])
#define KILL_CHAR(tty) ((tty)->termios.c_cc[VKILL])
#define EOF_CHAR(tty) ((tty)->termios.c_cc[VEOF])
#define START_CHAR(tty) ((tty)->termios.c_cc[VSTART])
#define STOP_CHAR(tty) ((tty)->termios.c_cc[VSTOP])
#define SUSPEND_CHAR(tty) ((tty)->termios.c_cc[VSUSP])
struct tty_struct {
struct termios termios;//终端IO控制数据结构
int pgrp;//所属进程组
int stopped;//停止标记
void (*write)(struct tty_struct * tty);//写函数指针
struct tty_queue read_q;//读队列
struct tty_queue write_q;//写队列
struct tty_queue secondary;//辅助队列,存放键盘输入 规范熟模式内容
};
extern struct tty_struct tty_table[];
#define INIT_C_CC "\003\034\177\025\004\0\1\0\021\023\032\0\022\017\027\026\0"
void con_init(void);
void tty_init(void);
void con_write(struct tty_struct * tty);
#endif
|
C
|
#include<stdio.h>
void main()
{
int i;
for(i=0;i<=10;i++)
{
printf("saranteja\n");
}
i=1;
while(i<=10)
{
printf("saranteja\n");
i++;
}
i=1;
do
{
printf("saranteja\n");
i++;
}while(i<=10);
}
|
C
|
/* NOTE: program run with ./ReaderWriters ricr ricb roocr roocb wicr wicb woocr woocb nr nw
• ricr is the range parameter for controlling how long readers sleep inside their critical sections
• ricb is the base number of nanoseconds a reader will sleep inside their critical sections
• roocr is the range parameter for controlling how long readers sleep outside their critical sections
• roocb is the base number of nanoseconds a reader will sleep outside their critical sections
• wicr is the range parameter for controlling how long writer s sleep inside their critical sections
• wicb is the base number of nanoseconds a writer will sleep inside their critical sections
• woocr is the range parameter for controlling how long writer s sleep outside their critical sections
• woocb is the base number of nanoseconds a writer will sleep outside their critical sections
• nr is the number of reader threads to create
• nw is the number of writer threads to create
ex: ./ReadersWriters 5 5 5 5 5 5 5 5 5 5
./ReadersWriters 10000 10000 10000 10000 10000 10000 10000 10000 5 5
./ReadersWriters 100 100 100 100 5 5 5 5 3 10
*/
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// these are the globals shared by all threads including main
#define RANGE 1000000000
#define BASE 500000000
int rICrange = RANGE;
int rICbase = BASE;
int rOOCrange = RANGE;
int rOOCbase = BASE;
int wICrange = RANGE;
int wICbase = BASE;
int wOOCrange = RANGE;
int wOOCbase = BASE;
int keepgoing = 1;
int totalReaders = 0;
int totalWriters = 0;
// the global area must include semaphore declarations and declarations
// of any state variables (reader counts, total number of readers and writers
sem_t rw_mutex = 1;
sem_t mutex = 1;
int read_count = 0;
int total_reads = 0;
// Use this to sleep in the threads
void threadSleep(int range, int base) {
struct timespec t;
t.tv_sec = 0;
t.tv_nsec = (rand() % range) + base;
nanosleep(&t, 0);
}
void *readers(void *args) {
int id = *((int *)args);
threadSleep(rOOCrange, rOOCbase);
while (keepgoing) {
// add code for each reader to enter the
// reading area
sem_wait(&mutex);
// the totalReaders variable must be
// incremented just before entering the
// reader area
read_count++;
if (read_count == 1)
sem_wait(&rw_mutex);
sem_post(&mutex);
total_reads++;
printf("Reader %d starting to read\n", id);
threadSleep(rICrange, rICbase);
printf("Reader %d finishing reading\n", id);
wait(mutex);
read_count--;
if (read_count == 0)
sem_post(&rw_mutex);
// add code for each reader to leave the
// reading area
sem_post(&mutex);
threadSleep(rOOCrange, rOOCbase);
}
printf("Reader %d quitting\n", id);
}
void *writers(void *args) {
int id = *((int *)args);
threadSleep(rOOCrange, rOOCbase);
while (keepgoing) {
// add code for each writer to enter
// the writing area
sem_wait(&rw_mutex);
totalWriters++;
printf("Writer %d starting to write\n", id);
threadSleep(wICrange, wICbase);
printf("Writer %d finishing writing\n", id);
// add code for each writer to leave
// the writing area
sem_post(&rw_mutex);
threadSleep(wOOCrange, wOOCbase);
}
printf("Writer %d quitting\n", id);
}
int main(int argc, char **argv) {
int numRThreads = 0;
int numWThreads = 0;
if (argc == 11) {
rICrange = atoi(argv[1]);
rICbase = atoi(argv[2]);
rOOCrange = atoi(argv[3]);
rOOCbase = atoi(argv[4]);
wICrange = atoi(argv[5]);
wICbase = atoi(argv[6]);
wOOCrange = atoi(argv[7]);
wOOCbase = atoi(argv[8]);
numRThreads = atoi(argv[9]);
numWThreads = atoi(argv[10]);
} else {
printf("Usage: %s <reader in critical section sleep range>", argv[0]);
printf("<reader in critical section sleep base> \n\t <reader out of "
"critical section sleep range> ");
printf("<reader out of critical section sleepbase> \n\t <writer in "
"critical section sleep range> ");
printf("<writer in critical section sleep base> \n\t<writer out of "
"critical section sleep range> ");
printf("<writer out of critical section sleep base> \n\t <number of "
"readers> <number of writers>\n");
exit(-1);
}
// declarations for pthread arrays, one for reader threads and
// one for writer threads
// arrays for reader and writer thread identities. As in the
// dining philosopher problem, arrays of int are used
// initialize the binary semaphores used by the readers and writers
// a for loop to create numRThread reader threads
// a for loop to create numWThread writer threads
// these statements wait for the user to type a character and press
// the Enter key. Then, keepgoing will be set to 0, which will cause
// the reader and writer threads to quit
pthread_t pWriters[numWThreads]; // need to change this number
pthread_t pReaders[numRThreads];
int i;
int writerID[numWThreads];
int readerID[numRThreads];
sem_init(&rw_mutex, 0, 1); // initialize semaphores
sem_init(&mutex, 0, 1);
for (i = 0; i < numWThreads; i++) { // create writer threads
writerID[i] = i;
if (pthread_create(&pWriters[i], 0, writers, &writerID[i]) != 0)
perror("Writer Pthread_create error");
}
for (i = 0; i < numRThreads; i++) { // create reader threads
readerID[i] = i;
if (pthread_create(&pReaders[i], 0, readers, &readerID[i]) != 0)
perror("Reader Pthread_create error");
}
char buf[256];
scanf("%s", &buf);
keepgoing = 0;
// two for loops to use pthread_join to wait for the reader
// and writer threads to quit
for (i = 0; i < numWThreads; i++)
pthread_join(pWriters[i], 0);
for (i = 0; i < numRThreads; i++)
pthread_join(pReaders[i], 0);
printf("Total number of reads: %d\nTotal number of writes: %d\n",
total_reads, totalWriters);
return 0;
}
|
C
|
/*
ףһ
2004240205
(궨)
*/
#include<stdio.h>
#define M(a,b) (a>b?a:b)
#define MAX(a,b,c) (M(a,b)>c?M(a,b):c)
int main()
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
printf("%d",MAX(a,b,c));
return 0;
}
|
C
|
/*
CSC D84 - Unit 1 - Search
This file contains stubs for implementing the different search
algorithms covered in the course. Please read the assignment
handout carefully - it describes the game, the data you will
have to handle, and the search functions you must provide.
Once you have read the handout carefully, implement your search
code in the sections below marked with
**************
*** TO DO:
**************
Make sure to add it to your report.txt file - it will be marked!
Have fun!
DO NOT FORGET TO 'valgrind' YOUR CODE - We will check for pointer
management being done properly, and for memory leaks.
Starter code: F.J.E., Jul. 15
Updated: F.J.E., Jan. 18
*/
/**********************************************************************
% COMPLETE THIS TEXT BOX:
%
% 1) Student Name: Ajiteshwar Rai
% 2) Student Name:
%
% 1) Student number: 1003587647
% 2) Student number:
%
% 1) UtorID raiajite
% 2) UtorID
%
% We hereby certify that the work contained here is our own
%
% ___Ajiteshwar Rai___ _____________________
% (sign with your name) (sign with your name)
***********************************************************************/
#include "AI_search.h"
// container to create a stack
struct Container{
int top;
int rear;
int* store;
};
// node for creating linked list for priority queue
struct Node{
int index;
int priority;
struct Node* next;
};
struct Node* createNode(int index, int priority){
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->index = index;
node->priority = priority;
node->next = NULL;
return node;
}
int headIndex(struct Node** head){
return (*head)->index;
}
void popPQueue(struct Node** head){
struct Node* temp = *head;
(*head) = (*head)->next;
free(temp);
}
void pushPQueue(struct Node** head, int index, int priority){
struct Node* start = *head;
struct Node* temp = createNode(index, priority);
// if lower priority than head, make it new head
if(start->priority > priority){
temp->next = start;
*head = temp;
} else {
// keep going until at right location
while(start->next != NULL && start->next->priority <= priority){
start = start->next;
}
temp->next = start->next;
start->next = temp;
}
}
struct Container* createStack(){
struct Container* container = (struct Container*)malloc(sizeof(struct Container));
container->top = -1;
container->store = (int*)malloc(1024 * sizeof(int));
return container;
}
int isEmpty(struct Container* container){
return container->top == -1;
}
int isEmptyPQueue(struct Node** node){
return (*node) == NULL;
}
void pushStack(struct Container* stack, int index){
stack->store[++stack->top] = index;
}
int popStack(struct Container* stack){
if (isEmpty(stack))
return -1;
return stack->store[stack->top--];
}
void freeList(struct Node* head){
// jsut freeing remaining space
struct Node* temp;
while (head != NULL){
temp = head;
head = head->next;
free(temp);
}
}
void search(double gr[graph_size][4], int path[graph_size][2], int visit_order[size_X][size_Y], int cat_loc[10][2], int cats, int cheese_loc[10][2], int cheeses, int mouse_loc[1][2], int mode, int (*heuristic)(int x, int y, int cat_loc[10][2], int cheese_loc[10][2], int mouse_loc[1][2], int cats, int cheeses, double gr[graph_size][4]))
{
/*
This function is the interface between your solution for the assignment and the driver code. The driver code
in AI_search_core_GL will call this function once per frame, and provide the following data
Board and game layout:
The game takes place on a grid of size 32x32, the file board_layout.h specifies the size and defines two
constants 'size_X' and 'size_Y' for the horizontal and vertical size of the board, respectively. For our
purposes, the grid of locations is represented by a graph with one node per grid location, so given
the 32x32 cells, the graph has 1024 nodes.
To create a maze, we connect cell locations in the grid in such a way that a) there is a path from any
grid location to any other grid location (i.e. there are no disconnected subsets of nodes in the graph),
and b) there are loops.
Since each node represents a grid location, each node can be connected to up to 4 neighbours in the
top, right, bottom, and left directions respectively:
node at (i,j-1)
^
|
(node at i-1, j) <- node at (i,j) -> node at (i+1, j)
|
v
node at (i,j+1)
The graph is theredore stored as an adjacency list with size 1024 x 4, with one row per node in the
graph, and 4 columns corresponding to the weight of an edge linking the node with each of its 4
possible neighbours in the order towp, right, bottom, left (clockwise from top).
Since all we care is whether nodes are connected. Weights will be either 0 or 1, if the weight is
1, then the neighbouring nodes are connected, if the weight is 0, they are not. For example, if
graph[i][0] = 0
graph[i][1] = 1
graph[i][2] = 0
graph[i][3] = 1
then node i is connected to the right and left neighbours, but not to top or bottom.
The index in the graph for the node corresponding to grid location (x,y) is
index = x + (y*size_X) or in this case index = x + (y*32)
Conversely, if you have the index and want to figure out the grid location,
x = index % size_X or in this case x = index % 32
y = index / size_Y or in this case y = index / 32
(all of the above are *integer* operations!)
A path is a sequence of (x,y) grid locations. We store it using an array of size
1024 x 2 (since there are 1024 locations, this is the maximum length of any
path that visits locations only once).
Agent locations are coordinate pairs (x,y)
Arguments:
gr[graph_size][4] - This is an adjacency list for the maze
path[graph_size][2] - An initially empty path for your code to fill.
In this case, empty means all entries are initially -1
visit_order[size_X][size_Y] - An array in which your code will store the
*order* in which grid locations were
visited during search. For example, while
doing BFS, the initial location is the
start location, it's visit order is 1.
Then the search would expand the immediate
neighbours of the initial node in some order,
these would get a visit order of 2, 3, 4, and
5 respectively, and so on.
This array will be used to display the search
pattern generated by each search method.
cat_loc[10][2], cats - Location of cats and number of cats (we can have at most 10,
but there can be fewer). Only valid cat locations are 0 to (cats-1)
cheese_loc[10][2], cheeses - Location and number of cheese chunks (again at most 10,
but possibly fewer). Valid locations are 0 to (cheeses-1)
mouse_loc[1][2] - Mouse location - there can be only one!
mode - Search mode selection:
mode = 0 - BFS
mode = 1 - DFS
mode = 2 - A*
(*heuristic)(int x, int y, int cat_loc[10][2], int cheese_loc[10][2], int mouse_loc[10][2], int cats, int cheeses)
- This is a pointer to one of the heuristic functions you will implement, either H_cost()
or H_cost_nokitty(). The driver in AI_search_core_GL will pass the appropriate pointer
depending on what search the user wants to run.
If the mode is 0 or 1, this pointer is NULL
* How to call the heuristic function from within this function : *
- Like any other function:
h = heuristic( x, y, cat_loc, cheese_loc, mouse_loc, cats, cheeses);
Return values:
Your search code will directly update data passed-in as arguments:
- path[graph_size][2] : Your search code will update this array to contain the path from
the mouse to one of the cheese chunks. The order matters, so
path[0][:] must be the mouse's current location, path[1][:]
is the next move for the mouse. Each successive row will contain
the next move toward the cheese, and the path ends at a location
whose coordinates correspond to one of the cheese chunks.
Any entries beyond that must remain set to -1
- visit_order[size_X][size_Y] : Your search code will update this array to contain the
order in which each location in the grid was expanded
during search. This means, when that particular location
was checked for being a goal, and if not a goal, had its
neighbours added as candidates for future expansion (in
whatever order is dictated by the search mode).
Note that since there are 1024 locations, the values in
this array must always be in [0, 1023]. The driver code
will then display search order as a yellow-colored
brightness map where nodes expanded earlier will look
brighter.
* Your code MUST NOT modify the locations or numbers of cats and/or cheeses, the graph,
or the location of the mouse - if you try, the driver code will know it *
That's that, now, implement your solution!
*/
/********************************************************************************************************
*
* TO DO: Implement code to carry out the different types of search depending on the
* mode.
*
* You can do this by writing code within this single function (and being clever about it!)
* Or, you can use this function as a wrapper that calls a different search function
* (BFS, DFS, A*) depending on the mode. Note that in the latter case, you will have
* to inform your A* function somehow of what heuristic it's supposed to use.
*
* Visiting Order: When adding the neighbours of a node to your list of candidates for
* expansion, do so in the order top, right, bottom, left.
*
* NOTE: Your search functions should be smart enough to not choose a path that goes
* through a cat! this is easily done without any heuristics.
*
* How you design your solution is up to you. But:
*
* - Document your implementation by adding concise and clear comments in this file
* - Document your design (how you implemented the solution, and why) in the report
*
********************************************************************************************************/
// changing the mode based on what they enter
if(mode == 0){
bfs_search(gr, path, visit_order, mouse_loc, cheese_loc, cheeses, cats, cat_loc);
} else if(mode == 1){
dfs_search(gr, path, visit_order, mouse_loc, cheese_loc, cheeses, cats, cat_loc);
} else if(mode == 2){
heuristic_search(gr, path, visit_order, mouse_loc, cheese_loc, cat_loc, cheeses, cats, heuristic);
} else {
// don't think I need this but I'll leave it in, who really cares
printf("invalid search mode\n");
}
return;
}
int checkCat(int index, int cats, int cat_loc[10][2]){
// quick funciton that checks whether this current block is a cat
for(int i = 0; i < cats; i++){
// just go through all cats and compare the location with current location
int curr_cat_index = cat_loc[i][0] + (cat_loc[i][1]*32);
if(index == curr_cat_index){
return 0;
}
}
// yeah it returns 1 if there is no cat, but you know what I mean
return 1;
}
void bfs_search(double gr[graph_size][4], int path[graph_size][2], int visit_order[size_X][size_Y], int mouse_loc[1][2], int cheese_loc[10][2], int cheeses, int cats, int cat_loc[10][2]){
// get mouse's current location
int m_loc = mouse_loc[0][0] + (mouse_loc[0][1]*size_X);
// create the queue and add the current mouse location
struct Node* head = createNode(m_loc, 0);
int visited[1024] = {0};
int deep[1024] = {-1};
visited[m_loc] = 0;
deep[m_loc] = 0;
int found_cheese = 0;
int curr_elem;
int visit_num = 0;
// just loop till you go everywhere or you find a cheese
while(isEmptyPQueue(&head) != 1 && found_cheese == 0){
curr_elem = headIndex(&head);
// add when you visit a node
visit_order[curr_elem % size_X][curr_elem / size_Y] = visit_num;
visit_num++;
for(int i = 0; i < cheeses; i++){
// if you found cheese, yippee
if(cheese_loc[i] && curr_elem == (cheese_loc[i][0] + (cheese_loc[i][1]*size_X))){
found_cheese = 1;
}
}
// adding the possible options around it to the queue, checking if there is a cat or its already added
if((gr[curr_elem][0] == 1) && checkCat(curr_elem-32, cats, cat_loc) && (visited[curr_elem-32] == 0)){
pushPQueue(&head, curr_elem-32, head->priority + 1);
visited[curr_elem-32] = curr_elem;
deep[curr_elem-32] = deep[curr_elem]+1;
}
if((gr[curr_elem][1] == 1) && checkCat(curr_elem+1, cats, cat_loc) && (visited[curr_elem+1] == 0)){
pushPQueue(&head, curr_elem+1, head->priority + 1);
visited[curr_elem+1] = curr_elem;
deep[curr_elem+1] = deep[curr_elem]+1;
}
if((gr[curr_elem][2] == 1) && checkCat(curr_elem+32, cats, cat_loc) && (visited[curr_elem+32] == 0)){
pushPQueue(&head, curr_elem+32, head->priority + 1);
visited[curr_elem+32] = curr_elem;
deep[curr_elem+32] = deep[curr_elem]+1;
}
if((gr[curr_elem][3] == 1) && checkCat(curr_elem-1, cats, cat_loc) && (visited[curr_elem-1] == 0)){
pushPQueue(&head, curr_elem-1, head->priority + 1);
visited[curr_elem-1] = curr_elem;
deep[curr_elem-1] = deep[curr_elem]+1;
}
popPQueue(&head);
}
int depth = deep[curr_elem];
// you want the depth so you can create a path by going backwards
while(depth != -1){
// since we saved which node is visited from which, we can jsut follow the trail
path[depth][0] = curr_elem % size_X;
path[depth][1] = curr_elem / size_Y;
depth--;
curr_elem = visited[curr_elem];
}
if(head != NULL){
// free whatever is left in the linked list after we found the cheese
freeList(head);
}
}
void dfs_search(double gr[graph_size][4], int path[graph_size][2], int visit_order[size_X][size_Y], int mouse_loc[1][2], int cheese_loc[10][2], int cheeses, int cats, int cat_loc[10][2]){
// get mouse's current location
int m_loc = mouse_loc[0][0] + (mouse_loc[0][1]*size_X);
// create the queue and add the current mouse location
struct Container* stack = createStack();
pushStack(stack, m_loc);
int visited[1024] = {0};
int deep[1024] = {-1};
visited[m_loc] = 0;
deep[m_loc] = 0;
int prev_visit = m_loc;
int found_cheese = 0;
int curr_elem;
int visit_num = 0;
while(found_cheese == 0){
// this is a little different cuz the stack works easier with arrays than linked list imo
curr_elem = popStack(stack);
visit_order[curr_elem % size_X][curr_elem / size_Y] = visit_num;
visit_num++;
for(int i = 0; i < cheeses; i++){
// mmm finding cheese so we good
if(cheese_loc[i] && curr_elem == (cheese_loc[i][0] + (cheese_loc[i][1]*size_X))){
found_cheese = 1;
}
}
// adding the possible options around it to the stack again checking for cats
if((gr[curr_elem][0] == 1) && checkCat(curr_elem-32, cats, cat_loc) && (visited[curr_elem-32] == 0)){
pushStack(stack, curr_elem-32);
visited[curr_elem-32] = curr_elem;
deep[curr_elem-32] = deep[curr_elem]+1;
}
if((gr[curr_elem][1] == 1) && checkCat(curr_elem+1, cats, cat_loc) && (visited[curr_elem+1] == 0)){
pushStack(stack, curr_elem+1);
visited[curr_elem+1] = curr_elem;
deep[curr_elem+1] = deep[curr_elem]+1;
}
if((gr[curr_elem][2] == 1) && checkCat(curr_elem+32, cats, cat_loc) && (visited[curr_elem+32] == 0)){
pushStack(stack, curr_elem+32);
visited[curr_elem+32] = curr_elem;
deep[curr_elem+32] = deep[curr_elem]+1;
}
if((gr[curr_elem][3] == 1) && checkCat(curr_elem-1, cats, cat_loc) && (visited[curr_elem-1] == 0)){
pushStack(stack, curr_elem-1);
visited[curr_elem-1] = curr_elem;
deep[curr_elem-1] = deep[curr_elem]+1;
}
}
int depth = deep[curr_elem] - 1;
// this is the same as bfs, we get depth and follow backwards since we store predecesor
while(depth != -1){
path[depth][0] = curr_elem % size_X;
path[depth][1] = curr_elem / size_Y;
depth--;
curr_elem = visited[curr_elem];
}
// freeing whatever is in the stack
free(stack->store);
free(stack);
}
void heuristic_search(double gr[graph_size][4], int path[graph_size][2], int visit_order[size_X][size_Y], int mouse_loc[1][2], int cheese_loc[10][2], int cat_loc[10][2], int cheeses, int cats, int (*heuristic)(int x, int y, int cat_loc[10][2], int cheese_loc[10][2], int mouse_loc[1][2], int cats, int cheeses, double gr[graph_size][4])){
// get mouse's current location
int m_loc = mouse_loc[0][0] + (mouse_loc[0][1]*size_X);
// create the queue and add the current mouse location
struct Node* head = createNode(m_loc, 0);
int visited[1024] = {0};
int deep[1024] = {-1};
visited[m_loc] = 0;
deep[m_loc] = 0;
int found_cheese = 0;
int curr_elem;
int visit_num = 0;
// largely the same as bfs but how we use the heuristics that we calculate
while(isEmptyPQueue(&head) != 1 && found_cheese == 0){
curr_elem = headIndex(&head);
visit_order[curr_elem % size_X][curr_elem / size_Y] = visit_num;
visit_num++;
for(int i = 0; i < cheeses; i++){
// found cheese yum leave the loop
if(cheese_loc[i] && curr_elem == (cheese_loc[i][0] + (cheese_loc[i][1]*size_X))){
found_cheese = 1;
}
}
// adding the possible options around it to the queue still checking for ze cats
// but as you can see now we call the heauristic function to switch up the priorities
if((gr[curr_elem][0] == 1) && checkCat(curr_elem-32, cats, cat_loc) && (visited[curr_elem-32] == 0)){
pushPQueue(&head, curr_elem-32, head->priority + 1 + heuristic((curr_elem - 32) % size_X, (curr_elem-32)/size_Y, cat_loc, cheese_loc, mouse_loc, 10, cheeses, gr));
visited[curr_elem-32] = curr_elem;
deep[curr_elem-32] = deep[curr_elem]+1;
}
if((gr[curr_elem][1] == 1) && checkCat(curr_elem+1, cats, cat_loc) && (visited[curr_elem+1] == 0)){
pushPQueue(&head, curr_elem+1, head->priority + 1 + heuristic((curr_elem+1) % size_X, (curr_elem+1)/size_Y, cat_loc, cheese_loc, mouse_loc, 10, cheeses, gr));
visited[curr_elem+1] = curr_elem;
deep[curr_elem+1] = deep[curr_elem]+1;
}
if((gr[curr_elem][2] == 1) && checkCat(curr_elem+32, cats, cat_loc) && (visited[curr_elem+32] == 0)){
pushPQueue(&head, curr_elem+32, head->priority + 1 + heuristic((curr_elem + 32) % size_X, (curr_elem+32)/size_Y, cat_loc, cheese_loc, mouse_loc, 10, cheeses, gr));
visited[curr_elem+32] = curr_elem;
deep[curr_elem+32] = deep[curr_elem]+1;
}
if((gr[curr_elem][3] == 1) && checkCat(curr_elem-1, cats, cat_loc) && (visited[curr_elem-1] == 0)){
pushPQueue(&head, curr_elem-1, head->priority + 1 + heuristic((curr_elem - 1) % size_X, (curr_elem-1)/size_Y, cat_loc, cheese_loc, mouse_loc, 10, cheeses, gr));
visited[curr_elem-1] = curr_elem;
deep[curr_elem-1] = deep[curr_elem]+1;
}
popPQueue(&head);
}
// create path
int depth = deep[curr_elem];
while(depth != -1){
path[depth][0] = curr_elem % size_X;
path[depth][1] = curr_elem / size_Y;
depth--;
curr_elem = visited[curr_elem];
}
if(head != NULL){
freeList(head);
}
}
int H_cost(int x, int y, int cat_loc[10][2], int cheese_loc[10][2], int mouse_loc[1][2], int cats, int cheeses, double gr[graph_size][4])
{
/*
This function computes and returns the heuristic cost for location x,y.
As discussed in lecture, this means estimating the cost of getting from x,y to the goal.
The goal is cheese. Which cheese is up to you.
Whatever you code here, your heuristic must be admissible.
Input arguments:
x,y - Location for which this function will compute a heuristic search cost
cat_loc - Cat locations
cheese_loc - Cheese locations
mouse_loc - Mouse location
cats - # of cats
cheeses - # of cheeses
gr - The graph's adjacency list for the maze
These arguments are as described in the search() function above
*/
// here we find the closest cheese using manhattan distance
int closestX = cheese_loc[0][0];
int closestY = cheese_loc[0][1];
for (int i = 1; i < cheeses; i++){
if(abs(cheese_loc[i][0]+cheese_loc[i][1] - x - y) < abs(closestX+closestY - x - y)){
closestX = cheese_loc[i][0];
closestY = cheese_loc[i][1];
}
}
// return how far the node is from the goal ala manhattan distance
int retVal = abs(closestX+closestY - x - y);
return retVal;
}
int bfsCat(double gr[graph_size][4], int x, int y, int cat_loc[10][2], int cats){
// this is a cool function that returns how many cats can reach a point in x number of steps
int allowed_steps = 5;
int num_cats = 0;
for(int i = 0; i < cats; i++){
// similar to the bfs search but we do not need to keep track of predecesors or visit_order
struct Node* head = createNode(cat_loc[i][0]+(32*cat_loc[i][1]), 0);
int curr_elem;
int iteration = 0;
int visited[1024] = {0};
int not_reached = 1;
while(not_reached && isEmptyPQueue(&head) != 1 && iteration < allowed_steps){
curr_elem = headIndex(&head);
if(curr_elem == (x + (y*size_X))){
// if you find the spot, then increment the number of problem cats
num_cats++;
}
// adding the possible options around it to the queue
if((gr[curr_elem][0] == 1) && (visited[curr_elem-32] == 0)){
pushPQueue(&head, curr_elem-32, head->priority + 1);
visited[curr_elem-32] = curr_elem;
}
if((gr[curr_elem][1] == 1) && (visited[curr_elem+1] == 0)){
pushPQueue(&head, curr_elem+1, head->priority + 1);
visited[curr_elem+1] = curr_elem;
}
if((gr[curr_elem][2] == 1) && (visited[curr_elem+32] == 0)){
pushPQueue(&head, curr_elem+32, head->priority + 1);
visited[curr_elem+32] = curr_elem;
}
if((gr[curr_elem][3] == 1) && (visited[curr_elem-1] == 0)){
pushPQueue(&head, curr_elem-1, head->priority + 1);
visited[curr_elem-1] = curr_elem;
}
popPQueue(&head);
iteration++;
}
// free the rest
if(head != NULL){
freeList(head);
}
}
// return how many cats reach the spot
return num_cats;
}
int H_cost_nokitty(int x, int y, int cat_loc[10][2], int cheese_loc[10][2], int mouse_loc[1][2], int cats, int cheeses, double gr[graph_size][4])
{
/*
This function computes and returns the heuristic cost for location x,y.
As discussed in lecture, this means estimating the cost of getting from x,y to the goal.
The goal is cheese.
However - this time you want your heuristic function to help the mouse avoid being eaten.
Therefore: You have to somehow incorporate knowledge of the cats' locations into your
heuristic cost estimate. How well you do this will determine how well your mouse behaves
and how good it is at escaping kitties.
This heuristic *does not have to* be admissible.
Input arguments have the same meaning as in the H_cost() function above.
*/
// you still wanna go to the closest cheese
int closestX = cheese_loc[0][0];
int closestY = cheese_loc[0][1];
for (int i = 1; i < cheeses; i++){
if(abs(cheese_loc[i][0]+cheese_loc[i][1] - x - y) < abs(closestX+closestY - x - y)){
closestX = cheese_loc[i][0];
closestY = cheese_loc[i][1];
}
}
// but now you also want to avoid places that have a lot of cats able to reach it
int retVal = abs(closestX+closestY - x - y);
int num_cats = bfsCat(gr, x, y, cat_loc, cats) * 1000;
if(num_cats != 0){
retVal += num_cats;
}
return retVal;
}
|
C
|
/*
* MemoryManage.h
*
* Created on: 2020年2月22日
* Author: LuYonglei
*/
#ifndef SRC_MEMORYMANAGE_H_
#define SRC_MEMORYMANAGE_H_
#include <stdlib.h>
#include <stdint.h>
#include "task.h"
/* 字节对齐数 字节对齐掩码
* 8 0x0007
* 4 0x0003
* 2 0x0001
* 1 0x0000
*/
#define BYTE_ALIGNMENT 8 //字节对齐数
#define BYTE_ALIGNMENT_MASK 0x0007 //字节对齐掩码
#define TOTAL_HEAP_SIZE 1000 //堆大小
#define MIN_BLOCK_SIZE 32 //最小内存块大小
#define HEAP_BITS_PER_BYTE 8 //堆中每个字节拥有的位数
//定义内存控制块
typedef struct memory_control_block {
struct memory_control_block *nextUsableBlock; //下一个空闲块的地址
size_t blockSize; //空闲块的大小
} MCB;
void* los_malloc(size_t wantedSize); //动态分配一块内存,内存大小为 wantedSize Bytes
void los_free(void *addressToBeFree); //释放一块动态分配了的内存
size_t los_get_usable_heap_size(void); //获取当前未分配的内存堆大小
size_t los_get_ever_min_usable_heap_size(void); //获取未分配的内存堆的历史最小值
//以下函数为调试系统所用,实际使用中可删除
void OS_MemoryUsableInfo(void); //获取当前系统内存可分配情况
#endif /* SRC_MEMORYMANAGE_H_ */
|
C
|
/**
\file adc1.c
\author G. Icking-Konert
\date 2013-11-22
\version 0.1
\brief implementation of ADC1 functions/macros
implementation of functions for ADC1 measurements in single-shot mode
*/
/*-----------------------------------------------------------------------------
INCLUDE FILES
-----------------------------------------------------------------------------*/
#include <stdint.h>
#include "stm8as.h"
#include "adc1.h"
/*----------------------------------------------------------
FUNCTIONS
----------------------------------------------------------*/
/**
\fn void adc1_init(void)
\brief initialize ADC
initialize ADC1 for single-shot measurements. Default to channel AIN0
*/
void adc1_init() {
// reset channel selection [3:0], no ADC interrupt [5]
ADC1.CSR.byte = 0x00;
// set single shot mode
ADC1.CR1.reg.CONT = 0;
// set ADC clock 1/12*fMaster (<2MHz)
ADC1.CR1.reg.SPSEL = 6;
// right alignment (read DRL, then DRH), no external trigger
ADC1.CR2.reg.ALIGN = 1;
// disable Schmitt trigger only for measurement channels
//ADC1.TDR = 0xFFFF;
// ADC module on
ADC1.CR1.reg.ADON = 1;
} // adc1_init
/**
\fn uint16_t adc1_measure(uint8_t ch)
\brief measure ADC1 channel
\param ch ADC1 channel to query
\return ADC1 value in INC
measure ADC1 channel in single shot mode.
*/
uint16_t adc1_measure(uint8_t ch) {
uint16_t result;
// switch to ADC channel if required. Else skip to avoid AMUX charge injection
if (ADC1.CSR.reg.CH != ch)
ADC1.CSR.reg.CH = ch;
// clear conversion ready flag, start conversion, wait until conversion done
ADC1.CSR.reg.EOC = 0;
ADC1.CR1.reg.ADON = 1; // start conversion
while(!ADC1.CSR.reg.EOC); // wait for "conversion ready" flag
// get ADC result (read low byte first for right alignment!)
result = (uint16_t) (ADC1.DR.byteL);
result += ((uint16_t)(ADC1.DR.byteH)) << 8;
// don't switch to default channel to avoid AMUX charge injection
// return result
return(result);
} // adc1_measure
/*-----------------------------------------------------------------------------
END OF MODULE
-----------------------------------------------------------------------------*/
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include <locale.h>
// 2) Faa uma funo recursiva que calcule e retorne o N-simo termo da sequncia
// Fibonacci. Alguns nmeros desta sequncia so: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89...
void fibonacci(int num){
int x = num;
int vetorAux[x];
int i;
vetorAux[0]= 0;
for(i=1; i<x; i++){
if(i==1 || i==2){ vetorAux[i] = 1;}
else{
vetorAux[i] = vetorAux[i-1] + vetorAux[i-2];}
}
printf("%d\n", vetorAux[x-1]);
}
int main(){
setlocale(LC_ALL, "Portuguese");
int n, i;
do{
printf("Digite a posio do elemento da sequncia de Fibonacci que voc deseja: ");
scanf("%d",&n);
if(n<1){
printf("Digite um valor maior ou igual a 1.\n\n");
}
} while(n<1);
printf("\nO elemento %d da sequncia de Fibonacci : ", n);
fibonacci(n);
getch();
return 0;
}
|
C
|
#include "pcm_alsa.h"
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
//wav 文件头数据结构
#define ID_RIFF 0x46464952
#define ID_WAVE 0x45564157
#define ID_FMT 0x20746d66
#define ID_DATA 0x61746164
#define FORMAT_PCM 1
#define fix_min_max(m, min, max) (m < min ? min : m > max ? max : m)
pthread_mutex_t alsa_cap_mutex;
struct wav_header {
/* RIFF WAVE Chunk */
uint32_t riff_id; /*固定字符串 RIFF*/
uint32_t riff_sz; /**/
uint32_t riff_fmt;
/* Format Chunk */
uint32_t fmt_id;
uint32_t fmt_sz;
uint16_t audio_format;
uint16_t num_channels;
uint32_t sample_rate;
uint32_t byte_rate; /* sample_rate * num_channels * bps / 8 */
uint16_t block_align; /* num_channels * bps / 8 */
uint16_t bits_per_sample;
/* Data Chunk */
uint32_t data_id;
uint32_t data_sz;
};
struct vad_parameter{
int sample_rate; //采样率
int format_type; //采样格式 16bit
int num_channels; //录音通道数量
int chunk_duration_ms; //窗口时间
int chunk_size; //窗口数据量
int chunk_bytes; //窗口bytes数量
int num_window_chunks_start; //开始端点语音窗口数量
int num_window_chunks_end; //结束端点非语音窗口数量
float start_voice_parameter; //开始端点乘积因子
float end_voice_parameter; //结束端点乘积因子
int mute_time; //静音时间
int voice_time; //语音时间
int TE_MIN; //门限最小能量值
int TE_MAX; //门限最大能量值
int TZ_MIN; //门限最小过零率
int TZ_MAX; //门限最大过零率
int TO_MIN; //过零率幅度最大值
int TO_MAX; //过零率幅度最小值
};
typedef struct wav_header WAV_HEADER_T;
typedef struct vad_parameter VAD_PARAMETER_T;
int add_wav_head(int fd, WAV_HEADER_T* hdr, uint32_t totle_size)
{
/* 回到文件头,重新更新音频文件大小 */
lseek(fd, 0, SEEK_SET);
/*填充文件头*/
//RIFF WAVE Chunk
hdr->riff_id = ID_RIFF; //固定格式
hdr->riff_sz = totle_size + 36; //Filelength=totle_size + 44 - 8
hdr->riff_fmt = ID_WAVE;
//Format Chunk
hdr->fmt_id = ID_FMT;
hdr->fmt_sz = 16; //一般为16,如果18要附加信息
hdr->audio_format = FORMAT_PCM; //编码方式:一般为1
hdr->num_channels = 1; //声道数
hdr->sample_rate = 16000; //采样频率
hdr->bits_per_sample = 16; //样本长度
hdr->byte_rate = hdr->sample_rate * hdr->num_channels * hdr->bits_per_sample / 8; //每秒所需的字节数 采样频率×通道数×样本长度
hdr->block_align = hdr->num_channels * hdr->bits_per_sample / 8; //数据块对齐单位(每个采样需要的字节数)
//Data Chunk
hdr->data_id = ID_DATA;
hdr->data_sz = totle_size;
if (write(fd, hdr, sizeof(WAV_HEADER_T)) != sizeof(WAV_HEADER_T)) {
fprintf(stderr, "arec: cannot write header\n");
return -1;
}
fprintf(stderr,"arec: %d ch, %ld hz, %d bit, %s\n",
hdr->num_channels, hdr->sample_rate, hdr->bits_per_sample,
hdr->audio_format == FORMAT_PCM ? "PCM" : "unknown");
return fd;
}
/*******************************************
函数功能:在固定路径下创建文件
参数说明:
返回说明:文件语句柄
********************************************/
int create_and_open_file(const char* path)
{
int fd = -1;
// O_TRUNC: 如果文件存在并以只读或读写打开,则将其长度截短为0
fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0664);
if(fd < 0) {
fprintf(stderr, "arec: cannot open '%d'\n", fd);
return -1;
}
return fd;
}
int write_info_to_file(int fd, short* buf, int frame, int totle_size)
{
int rc = write(fd, buf, 2 * frame);
if (rc != 2 * frame)
fprintf(stderr,
"short write: wrote %d bytes\n", rc);
return totle_size + frame;
}
snd_pcm_t *record_init(u32 rate, u32 channles, u8 sample, const char* dev_name)
{
snd_pcm_t *capture_handle;//会语句柄
capture_handle = record_config_init(rate, channles, sample, CAPTURE_DEVICE);
return capture_handle;
}
int alsa_read_frame(int frame, short *f_buf, snd_pcm_t *capture_handle)
{
int err = -1;
if((err = snd_pcm_readi(capture_handle, f_buf, frame)) != frame) {
if (err == -EPIPE) {
/* EPIPE means overrun */
fprintf(stderr, "overrun occurred\n");
snd_pcm_prepare(capture_handle);
} else if (err < 0) {
fprintf(stderr,
"error from read: %s\n",
snd_strerror(err));
} else {
fprintf(stderr, "short read, read %d frames\n", err);
}
}
return (err);
}
int alsa_read_chunk(int chunk_duration_ms, int sample_rate, short *f_buf, snd_pcm_t *capture_handle)
{
int err = -1;
int per_frames = sample_rate / 1000;
int totle_frames = chunk_duration_ms * per_frames;
int i = 0;
for (i = 0; i < chunk_duration_ms; i++){
err = alsa_read_frame(per_frames, &f_buf[i*per_frames], capture_handle);
}
return err;
}
//录制音频
u32 record(u32 loops)
{
int fd = -1;
int err = -1;
WAV_HEADER_T* hdr = (WAV_HEADER_T *)malloc(sizeof(WAV_HEADER_T));
u32 totle_size = 0; /*记录总量*/
int frame = 2; /* 帧大小 = 量化单位×通道数 / 字节位数 */
short buf[frame];
//buf =(short*)malloc(2*sizeof(short));
int start_sec = 0;
snd_pcm_t *capture_handle;//会语句柄
//初始化声卡配置
capture_handle = record_config_init(16000, 1, 16, CAPTURE_DEVICE);
//录音开始
printf("Ready to capture frame...\n");
//在指定路径打开或创建固定音频文件 0664
fd = create_and_open_file("test.pcm");
printf("Start to record...\n");
//start_sec = get_sec();
while(loops--) //这里到时修正成 后端点检测
{
//bzero(buf,16);
if((err = snd_pcm_readi(capture_handle, buf, frame)) != frame)
{
fprintf(stderr, "read from audio interface failed(%s)\n",
snd_strerror(err));
exit(1);
}
totle_size = write_info_to_file(fd, buf, frame, totle_size);
//printf(" %d : %d", buf[0], buf[1]);
}
printf("tltle_size = %d\n", totle_size);
//加入音频头
fd = add_wav_head(fd, hdr, totle_size);
//关闭文件
snd_pcm_close(capture_handle);
//free(buf);
close(fd);
//printf("Use %d seconds!\n",get_sec()-start_sec);
return totle_size;
}
/***********************************
函数功能:
使用矩形窗口函数计算短时能量
参数说明:
audioFramePtr: 音频帧
win_len: 滑动窗口长度
返回值:
每段帧的能量值
************************************/
int energyPerSampleUseRectangle(short* audio_frame_ptr, int win_len)
{
unsigned int energy_int = 0;
double energy = 0.2f; //保留小数点后两位
short sample;
int i = 0;
for (i = 0; i<win_len; i++){
sample = *(audio_frame_ptr + i);
//energy += sample * sample;
energy_int += abs(sample);
}
energy_int = energy_int / win_len;
//energy = (double)10 * log(energy);
return energy_int;
}
/****************************************
函数功能:
使用矩形窗口函数计算短时过零率
参数说明:
audioFramePtr: 音频帧
win_len: 滑动窗口长度
返回值:
每段帧的过零率
***************************************/
int zeroPointPerSampleUseRectangle(short* audio_frame_ptr, int win_len, int T)
{
int zeroPoint = 0;
short sample = 0;
int i = 0;
for (i = 0; i<win_len-1; i++){
if ((*(audio_frame_ptr + i)) * (*(audio_frame_ptr + i + 1)) < 0 && abs(*(audio_frame_ptr + i) - *(audio_frame_ptr + i + 1)) > T){
zeroPoint++;
}
}
return zeroPoint;
}
int is_speech(int chunk_size, int TZ, int TE, int TO, short *chunk, snd_pcm_t *capture_handle)
{
int energy_int = 0;
int zeroPoint = 0;
int active = 0;
energy_int = energyPerSampleUseRectangle(chunk, chunk_size);
zeroPoint = zeroPointPerSampleUseRectangle(chunk, chunk_size, TO);
active = (energy_int >= TE && zeroPoint >= TZ) ? 1 : 0;
return active;
}
void voice_init(int period, int sample_rate, int *voice_data, snd_pcm_t *capture_handle)
{
int per_frames = sample_rate / 1000;
int totle_frames = period * per_frames;
short f_buf[totle_frames];
int energy_int = 0;
int zeroPoint = 0;
int k = 0;
int i = 0;
for (k = 0; k < 5; k++){
for (i = 0; i < period; i++){
alsa_read_frame(per_frames, &f_buf[i*per_frames], capture_handle);
}
energy_int += energyPerSampleUseRectangle(f_buf, totle_frames);
zeroPoint += zeroPointPerSampleUseRectangle(f_buf, totle_frames, 100);
}
voice_data[0] = energy_int / 5;
voice_data[1] = zeroPoint / 5;
}
int array_sum(char *array, int size)
{
int i = 0;
int sum = 0;
for (i == 0; i < size; i++){
sum += array[i];
}
return sum;
}
int vad(VAD_PARAMETER_T *vad_par, snd_pcm_t *capture_handle)
{
int fd = -1;
int i = 0;
int index = 0;
int active = 0;
int time_start = 0;
int time_totle = 0;
int num_voiced = 0;
int num_unvoiced = 0;
uint32_t totle_size = 0;
int got_a_sentence = 0;
int triggered = 0;
int ring_buffer_index = 0;
int ring_buffer_index_end = 0;
int per_chunk_point = 0;
int voice_data[2];
short chunk[vad_par->chunk_size];
short per_chunk[vad_par->num_window_chunks_start * (vad_par->chunk_size)];
char ring_buffer_flags[vad_par->num_window_chunks_start];
char ring_buffer_flags_end[vad_par->num_window_chunks_end];
WAV_HEADER_T* hdr = (WAV_HEADER_T *)malloc(sizeof(WAV_HEADER_T));
memset(ring_buffer_flags, 0, sizeof(char)*vad_par->num_window_chunks_start);
memset(ring_buffer_flags_end, 0, sizeof(char)*vad_par->num_window_chunks_end);
//在指定路径打开或创建固定音频文件 0664
fd = create_and_open_file("wav/iflytek02.wav");
printf("* recording: \n");
voice_init(vad_par->chunk_duration_ms, vad_par->sample_rate, voice_data, capture_handle);
int TE = fix_min_max(1.5 * voice_data[0], vad_par->TE_MIN, vad_par->TE_MAX);
int TZ = fix_min_max(1.5 * voice_data[1], vad_par->TZ_MIN, vad_par->TZ_MAX);
int TO = fix_min_max(voice_data[0], vad_par->TO_MIN, vad_par->TO_MAX);
printf("voice_data= %d %d\n", voice_data[0], voice_data[1]);
printf("Tez= %d %d %d\n", TE, TZ, TO);
while (!got_a_sentence){
//alsa_read_chunk(CHUNK_DURATION_MS, RATE, chunk, capture_handle);
alsa_read_frame(vad_par->chunk_size, chunk, capture_handle);
active = is_speech(vad_par->chunk_size, TZ, TE, TO, chunk, capture_handle);
index += vad_par->chunk_size;
write(0, active == 1 ? "1" : "_", 1);
time_totle += vad_par->chunk_duration_ms;
if (!triggered){
per_chunk_point = ring_buffer_index * vad_par->chunk_size;
for (i = 0; i < vad_par->chunk_size; i++){
per_chunk[per_chunk_point + i] = chunk[i];
}
}
ring_buffer_flags[ring_buffer_index] = (active == 1 ? 1 : 0);
ring_buffer_index += 1;
ring_buffer_index %= vad_par->num_window_chunks_start;
ring_buffer_flags_end[ring_buffer_index_end] = (active == 1 ? 1 : 0);
ring_buffer_index_end += 1;
ring_buffer_index_end %= vad_par->num_window_chunks_end;
if (!triggered){
num_voiced = array_sum(ring_buffer_flags, vad_par->num_window_chunks_start);
if (num_voiced > vad_par->start_voice_parameter * vad_par->num_window_chunks_start){
time_start = time_totle;
write(0, "OPEN", 4);
totle_size = write_info_to_file(fd, &per_chunk[ring_buffer_index * vad_par->chunk_size], (12 - ring_buffer_index) * (vad_par->chunk_size), totle_size);
totle_size = write_info_to_file(fd, per_chunk, (ring_buffer_index) * (vad_par->chunk_size), totle_size);
triggered = 1;
}
if (time_totle > vad_par->mute_time){
fd = add_wav_head(fd, hdr, totle_size);
free(hdr);
close(fd);
return 0;
}
}else{
num_unvoiced = vad_par->num_window_chunks_end - array_sum(ring_buffer_flags_end, vad_par->num_window_chunks_end);
if ((num_unvoiced > (vad_par->end_voice_parameter * vad_par->num_window_chunks_end)) || (time_totle - time_start > vad_par->voice_time)){
write(0, "CLOSE", 4);
triggered = 0;
got_a_sentence = 1;
}
totle_size = write_info_to_file(fd, chunk, vad_par->chunk_size, totle_size);
}
}
fd = add_wav_head(fd, hdr, totle_size);
free(hdr);
close(fd);
return 1;
}
int alsa_vad(int s_rate, int f_type, int channels, int c_d_ms)
{
int is_get_sentence = 0;
snd_pcm_t *capture_handle;
VAD_PARAMETER_T* vad_par = (VAD_PARAMETER_T *)malloc(sizeof(VAD_PARAMETER_T));
vad_par->sample_rate = s_rate;
vad_par->format_type = f_type;
vad_par->num_channels = channels;
vad_par->chunk_duration_ms = c_d_ms;
vad_par->chunk_size = (int)(c_d_ms * s_rate / 1000);
vad_par->chunk_bytes = vad_par->chunk_size * vad_par->format_type / 8;
vad_par->num_window_chunks_start = 240 / vad_par->chunk_duration_ms;
vad_par->num_window_chunks_end = vad_par->num_window_chunks_start * 5;
vad_par->start_voice_parameter = 0.7; //开始端点乘积因子
vad_par->end_voice_parameter = 0.9; //结束端点乘积因子
vad_par->mute_time = 30000; //静音时间
vad_par->voice_time = 10000; //语音时间
vad_par->TE_MIN = 100; //门限最小能量值
vad_par->TE_MAX = 300; //门限最大能量值
vad_par->TZ_MIN = 10; //门限最小过零率
vad_par->TZ_MAX = 20; //门限最大过零率
vad_par->TO_MIN = 80; //过零率幅度最大值
vad_par->TO_MAX = 200; //过零率幅度最小值
capture_handle = record_config_init(vad_par->sample_rate, vad_par->num_channels, vad_par->format_type, CAPTURE_DEVICE);
is_get_sentence = vad(vad_par, capture_handle);
snd_pcm_close(capture_handle);
return is_get_sentence;
}
void main(void)
{
alsa_vad(16000, 16, 1, 20);
}
|
C
|
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>
int data = 0;
void taska()
{
int i = 0;
for (i=3; i>0; i--)
{
data = data + i;
printf("data = %d\n", data);
sleep(2);
}
return;
}
void taskb()
{
int i = 0;
for (i=7; i>0; i--)
{
data = data + data*i;
sleep(1);
}
return;
}
void main()
{
int i = 0;
pthread_t ta, tb;
pthread_create(&ta, NULL, (void *) taska, 0);
pthread_create(&tb, NULL, (void *) taskb, 0);
pthread_join(ta, NULL);
pthread_join(tb, NULL);
return;
}
|
C
|
#include<stdio.h>
int main()
{
FILE *f1;
char c;
f1 = fopen("input.txt","w"); //input.txt
while( (c=getchar()) !=EOF) //EOF input Ѵ
putc(c,f1);
fclose(f1);
f1=fopen("input.txt", "r"); // о´
while( (c=getc(f1)) !=EOF) //EOF Ͽ ڸ о
printf("%c",c);
fclose(f1);
getchar();
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
enum Color {red, green, blue = 10, yellow}; //给枚举常量的第一个值赋值
enum Color rgby;
printf("red = %d\n", red);
printf("green = %d\n", green);
printf("blue = %d\n", blue);
printf("yellow = %d\n", yellow);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_pythagore.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: semartin <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/04/15 11:56:41 by semartin #+# #+# */
/* Updated: 2016/04/15 11:56:50 by semartin ### ########.fr */
/* */
/* ************************************************************************** */
/*
** ft_color : Deal with the color
** ----------------------------------------------------------------------------
** ft_print_square : Print a sqaure knowing his size, angle and position
** ----------------------------------------------------------------------------
** ft_pythagore_algo : Recursiv function that trace the tree
** ----------------------------------------------------------------------------
** ft_build_pythagore : Call the recusiv function
** ----------------------------------------------------------------------------
** ft_call_pythagore : Trace the tree with the mlx needed fucntion
*/
#include "fract_ol.h"
static int ft_color(double size)
{
if (size == (WIDTH / 7.0))
return (0xFFBB00);
else if (size >= 0.5 * (WIDTH / 7.0))
return (0xFFFF00);
else if (size >= 0.25 * (WIDTH / 7.0))
return (0xCCFF99);
else if (size >= 0.125 * (WIDTH / 7.0))
return (0x99FF33);
else if (size >= 0.0625 * (WIDTH / 7.0))
return (0x66CC66);
else if (size >= 0.03125 * (WIDTH / 7.0))
return (0x009966);
else
return (0x006600);
}
static void ft_print_square(t_env *e, double size, t_complex cdb, double phi)
{
int i;
int j;
int color;
double x;
double y;
i = 0;
color = ft_color(size);
while (i <= size)
{
j = 0;
while (j <= size)
{
x = cdb.x + (cos(phi - M_PI_2) * j) + (cos(phi) * i);
y = cdb.i - (sin(phi - M_PI_2) * j) - (sin(phi) * i);
ft_pixel_put_image(e, x, y, color);
if (size > 10 && i < size - 1 && j < size - 1)
{
ft_pixel_put_image(e, x + 1, y, color);
ft_pixel_put_image(e, x, y + 1, color);
}
j++;
}
i++;
}
}
static void ft_pythagore_algo(t_env *e, double size, t_complex cdb, double phi)
{
t_complex cdb_1;
t_complex cdb_2;
double size_1;
if (size > 1)
{
size_1 = (sqrt(2) / 2) * size;
cdb_1.x = cdb.x + (cos(phi) * size);
cdb_1.i = cdb.i - (sin(phi) * size);
cdb_2.x = cdb_1.x + (cos(phi - M_PI_4) * size_1);
cdb_2.i = cdb_1.i - (sin(phi - M_PI_4) * size_1);
ft_pythagore_algo(e, size_1, cdb_1, phi + M_PI_4);
ft_pythagore_algo(e, size_1, cdb_2, phi - M_PI_4);
ft_print_square(e, size, cdb, phi);
}
}
void ft_build_pythagore(t_env *e)
{
t_complex cdb;
cdb.x = (3.0 / 7.0) * WIDTH;
cdb.i = HIGHT;
ft_pythagore_algo(e, WIDTH / 7.0, cdb, M_PI_2);
}
void ft_call_pythagore(t_env *e)
{
int endian;
e->win = mlx_new_window(e->mlx, WIDTH, HIGHT, "Pythagore");
endian = 1;
e->img = mlx_new_image(e->mlx, WIDTH, HIGHT);
e->data = malloc(sizeof(char*));
e->data = mlx_get_data_addr(e->img, &(e->bpp), &(e->size_line), &endian);
ft_build_pythagore(e);
mlx_expose_hook(e->win, expose_hook, e);
mlx_key_hook(e->win, key_escape, e);
}
|
C
|
/**
* \file abin.c
*/
#include "abin.h"
/*
#define N int
#define F double
typedef struct s_noeud {
N op;
F val;
bool unaire;
struct s_noeud *fg, *fd;
} noeud, *abin;
*/
/**
* \fn abin enraciner(T x, abin g, abin d)
* \brief enraciner deux arbres
* \return la racine
*/
abin enraciner(N op, F val, abin g, abin d)
{
abin n = (abin) malloc(sizeof(noeud));
n->val=val;
n->op=op;
n->fg=g;
n->fd=d;
n->unaire=false;
return n;
}
/**
* \fn abin sag(abin a)
* \return sous arbre gauche
*/
abin sag(abin a)
{
return a->fg;
}
/**
* \fn abin sad(abin a)
* \return sous arbre droit
*/
abin sad(abin a)
{
return a->fd;
}
/**
* \fn T racine(abin a)
* \return val de la racine
*/
N racine(abin a)
{
return a->op;
}
/**
* \fn bool vide(abin a)
* \return true s'il est vide, false sinon
*/
bool vide(abin a)
{
return a==NULL;
}
/**
* \fn abin copier_arbre(abin a)
* \return un nouvel arbre
*/
abin copier_arbre(abin a)
{
if(vide(a))
return NULL;
else
return enraciner(a->op,a->val,copier_arbre(a->fg),copier_arbre(a->fd));
}
/**
* \fn void liberer_arbre(abin a)
* \brief libere l'arbre
*/
void liberer_arbre(abin a)
{
if(a->fg!=NULL)
liberer_arbre(a->fg);
if(a->fd!=NULL)
liberer_arbre(a->fd);
free(a);
return;
}
|
C
|
#include "stdio.h"
int main()
{
char buf[300];
FILE* fin = fopen("task1.txt", "r");
FILE* fout = fopen("result.txt", "w");
for(int i=0; i<5; i++)
{
fgets(buf, 200, fin);
fprintf(fout,"%s",buf);
}
do
{
fscanf(fin, "%154c",buf);
buf[154] = '\0';
fprintf(fout, "%s\n",buf);
}
while( fgets(buf, 300, fin));
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include "chacha20.h"
#include "utils.h"
const int ROUND_1[] = {0, 4, 8, 12};
const int ROUND_2[] = {1, 5, 9, 13};
const int ROUND_3[] = {2, 6, 10, 14};
const int ROUND_4[] = {3, 7, 11, 15};
const int ROUND_5[] = {0, 5, 10, 15};
const int ROUND_6[] = {1, 6, 11, 12};
const int ROUND_7[] = {2, 7, 8, 13};
const int ROUND_8[] = {3, 4, 9, 14};
const uint32_t STARTING_STATE[] = { 0x61707865,
0x3320646e,
0x79622d32,
0x6b206574 };
void
apply_rules(uint32_t *_a, uint32_t *_b, uint32_t *_c, uint32_t *_d)
{
uint32_t a = *_a; uint32_t b = *_b; uint32_t c = *_c; uint32_t d = *_d;
a += b; d ^= a; d = rotate(d, 16);
c += d; b ^= c; b = rotate(b, 12);
a += b; d ^= a; d = rotate(d, 8);
c += d; b ^= c; b = rotate(b, 7);
*_a = a; *_b = b; *_c = c; *_d = d;
}
void
apply_qround(const int *qround, uint32_t *state)
{
apply_rules(&state[qround[0]],
&state[qround[1]],
&state[qround[2]],
&state[qround[3]]);
}
uint32_t
to_uint32(uint8_t a, uint8_t b, uint8_t c, uint8_t d)
{
return (d << 24) | (c << 16) | (b << 8) | a;
}
void
build_block(uint8_t *key,
uint32_t counter,
uint8_t *nonce,
uint32_t *state)
{
state[0] = STARTING_STATE[0];
state[1] = STARTING_STATE[1];
state[2] = STARTING_STATE[2];
state[3] = STARTING_STATE[3];
// TODO: transform key to uint32s in a separate & more intuitive function
state[4] = to_uint32(key[0], key[1], key[2], key[3]);
state[5] = to_uint32(key[4], key[5], key[6], key[7]);
state[6] = to_uint32(key[8], key[9], key[10], key[11]);
state[7] = to_uint32(key[12], key[13], key[14], key[15]);
state[8] = to_uint32(key[16], key[17], key[18], key[19]);
state[9] = to_uint32(key[20], key[21], key[22], key[23]);
state[10] = to_uint32(key[24], key[25], key[26], key[27]);
state[11] = to_uint32(key[28], key[29], key[30], key[31]);
state[12] = counter;
state[13] = to_uint32(nonce[0], nonce[1], nonce[2], nonce[3]);
state[14] = to_uint32(nonce[4], nonce[5], nonce[6], nonce[7]);
state[15] = to_uint32(nonce[8], nonce[9], nonce[10], nonce[11]);
}
void
chacha20_block(uint32_t *state)
{
uint32_t working_state[BLOCK_LENGTH];
for (int i=0; i<BLOCK_LENGTH; i++){
working_state[i] = state[i];
}
for (int i=0; i<NUMBER_ROUNDS; i++) {
apply_qround(ROUND_1, working_state);
apply_qround(ROUND_2, working_state);
apply_qround(ROUND_3, working_state);
apply_qround(ROUND_4, working_state);
apply_qround(ROUND_5, working_state);
apply_qround(ROUND_6, working_state);
apply_qround(ROUND_7, working_state);
apply_qround(ROUND_8, working_state);
}
for (int i=0; i<BLOCK_LENGTH; i++) {
state[i] += working_state[i];
}
}
void
chacha20_block_and_serialize(uint32_t *state, uint8_t *output)
{
chacha20_block(state);
serialize(state, output);
}
void
build_block_and_serialize(uint8_t *key,
uint32_t counter,
uint8_t *nonce,
unsigned char *output)
{
uint32_t *state = malloc(BLOCK_LENGTH*sizeof(uint32_t));
if (!state)
return;
build_block(key, counter, nonce, state);
chacha20_block(state);
serialize(state, output);
free(state);
}
void
chacha20_encrypt(uint8_t *key,
uint32_t starting_counter,
uint8_t *nonce,
unsigned char *plaintext,
uint32_t plaintext_length,
unsigned char *ciphertext)
{
uint32_t counter = starting_counter;
unsigned char *keystream = malloc(BYTE_LENGTH*sizeof(char));
unsigned char *block = malloc(BYTE_LENGTH*sizeof(char));
if (!keystream || !block)
return;
uint32_t i;
for (i=0; i<(plaintext_length/(BYTE_LENGTH-1)); i+=BYTE_LENGTH) {
build_block_and_serialize(key, counter, nonce, keystream);
slice(plaintext, block, i, BYTE_LENGTH);
xor_block(block, keystream, BYTE_LENGTH);
memcpy(ciphertext+i, block, BYTE_LENGTH*sizeof(char));
counter++;
}
int remaining = plaintext_length%64;
build_block_and_serialize(key, counter, nonce, keystream);
slice(plaintext, block, i, i+remaining);
xor_block(block, keystream, remaining);
memcpy(ciphertext+i, block, remaining*sizeof(char));
free(keystream);
free(block);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdint.h>
#include <unistd.h>
#include <byteswap.h>
#include "fileHeader.h"
int printError() { // test
perror("main");
return 0;
}
uint8_t* readFileBackwards(uint32_t size, int sourceFd) {
uint8_t* buffer = malloc(size * sizeof(uint8_t));
uint8_t sample;
for(int i = 1; i <= size; ++i) {
lseek(sourceFd, i * -1, SEEK_END);
if(read(sourceFd, &sample, sizeof(uint8_t)) == -1) {
perror("main");
return NULL;
}
buffer[i - 1] = sample;
}
return buffer;
}
int fileInput() {
int result = -1;
char str[100];
do {
printf("Please enter input path...\n");
scanf("%s", str);
printf("%s\n", str);
result = open(str, O_RDONLY);
perror("main");
} while (result == -1);
return result;
}
int main() {
int fdInput = fileInput();
printf("Reading file...\n");
int fdOutput = open("output.au", O_WRONLY|O_TRUNC|O_CREAT|O_APPEND, 0666);
FileHeader header = getHeaderInformation(fdInput);
uint32_t headerLength = bswap_32(header.length);
printf("offset: 0x%08x\n", bswap_32(header.offset));
printf("encoding: 0x%08x\n", bswap_32(header.encoding));
printf("length: 0x%08x\n", bswap_32(headerLength));
printf("rate: 0x%08x\n", bswap_32(header.samplingRate));
printf("channels: 0x%08x\n", bswap_32(header.audioChannels));
uint32_t arr[] = { header.type, header.offset, header.length, header.encoding, header.samplingRate, header.audioChannels };
int fdResult = write(fdOutput, arr, sizeof(uint32_t) * 6);
if (fdResult == -1) {
printError();
}
printf("Reading file backwards...\n");
uint8_t * buffer = readFileBackwards(headerLength, fdInput);
if (buffer == NULL) {
printError();
}
printf("Writing result...\n");
fdResult = write(fdOutput, buffer, sizeof(uint8_t) * headerLength);
if (fdResult == -1) {
return printError();
}
free(buffer);
return 0;
}
|
C
|
//SPI master
#include <avr/io.h>
#include <util/delay.h>
//SPI initvoid
void SPIMasterInit(void) {
//set MOSI, SCK and SS as output
DDRB |= (1<<PB3)|(1<<PB5)|(1<<PB2);
//set SS to high
PORTB |= (1<<PB2);
//enable master SPI at clock rate Fck/16
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
}
//master send function
void SPIMasterSend(uint8_t data){
//select slave
PORTB &= ~(1<<PB2);
//send data
SPDR=data;
//wait for transmition complete
while (!(SPSR &(1<<SPIF)));
//SS to high
PORTB |= (1<<PB2);
}
int main(void) {
//initialize master SPI
SPIMasterInit();
//initial PWM value
uint8_t pwmval = 0;
while (1) {
SPIMasterSend(pwmval+=5);
_delay_ms(1000);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
#include <math.h>
#define TAM 200
typedef struct dados {
int codigo, ano, status;
float orcamento;
char titulo[40], descricao[100], gerente[50], tipo[30], publico[30];
} base_projetos;
int contador = 0;
int i;
int status;
void cadastrar_projeto(base_projetos proj[TAM]);
void relatorio_projeto(base_projetos proj[TAM]);
void buscar_codigo(base_projetos proj[TAM]);
void aFazer(base_projetos proj[TAM]);
void fazendo(base_projetos proj[TAM]);
void concluidos(base_projetos proj[TAM]);
void verificarStatus(base_projetos proj[TAM], int st);
int main() {
setlocale(LC_ALL, "portuguese");
base_projetos proj[TAM];
int escolha;
system("cls");
do {
system("cls");
printf("===========================================\n");
printf("| MENU | \n");
printf("===========================================\n");
printf("\n>> Escolha uma opcao abaixo:\n");
printf("\n[1] - CADASTRAR UM PROJETO\n");
printf("[2] - LISTAR TODOS OS PROJETOS\n");
printf("\n[3] - LISTAR OS PROJETOS A FAZER\n");
printf("[4] - LISTAR OS PROJETOS EM ANDAMENTO\n");
printf("[5] - LISTAR OS PROJETOS CONCLUDOS\n");
printf("\n[6] - BUSCAR POR CDIGO\n");
printf("[0] - ENCERRAR\n\n");
scanf("%d", &escolha);
fflush(stdin);
switch(escolha) {
case 1:
cadastrar_projeto(proj);
break;
case 2:
relatorio_projeto(proj);
break;
case 3:
aFazer(proj);
break;
case 4:
fazendo(proj);
break;
case 5:
concluidos(proj);
break;
case 6:
buscar_codigo(proj);
break;
case 0:
system("cls");
printf("\nPROGRAMA ENCERRADO\n");
break;
default:
system("cls");
printf("\nOPO INVLIDA!\n");
printf("Aperte ENTER e tente novamente.\n\n");
system("Pause");
break;
}
} while(escolha != 0);
return 0;
}
void cadastrar_projeto(base_projetos proj[TAM]) {
/*int status;*/
if(contador <= TAM) {
system("cls");
printf("===========================================\n");
printf("| CADASTRAR NOVO PROJETO | \n");
printf("===========================================\n");
printf("\nCdigo do projeto: %d \n", contador+1);
proj[contador].codigo = contador+1;
printf("Ttulo: ");
fgets(proj[contador].titulo, 40, stdin);
fflush(stdin);
printf("Descrio: ");
fgets(proj[contador].descricao, 100, stdin);
fflush(stdin);
printf("Ano: ");
scanf("%d", &proj[contador].ano);
fflush(stdin);
printf("Tipo de projeto: ");
fgets(proj[contador].tipo, 30, stdin);
fflush(stdin);
printf("Pblico:");
fgets(proj[contador].publico, 30, stdin);
fflush(stdin);
printf("Gerente de projetos responsvel: ");
fgets(proj[contador].gerente, 50, stdin);
fflush(stdin);
printf("Oramento do projeto: R$ ");
scanf("%f", &proj[contador].orcamento);
fflush(stdin);
printf("Status: \n");
printf(" [1] - A fazer [2] - Em andamento [3] - Concludo \n");
scanf("%d", &status);
fflush(stdin);
switch(status) {
case 1:
proj[contador].status = 1;
break;
case 2:
proj[contador].status = 2;
break;
case 3:
proj[contador].status = 3;;
break;
default:
proj[contador].status = 10;
break;
}
printf("\n");
contador++;
system("Pause");
} else {
printf("> Nmero mximo de cadastros atingido!");
system("Pause");
}
}
void relatorio_projeto(base_projetos proj[TAM]) {
/*int i;*/
system("cls");
if(contador != 0) {
printf("================================================\n");
printf("| TODOS OS PROJETOS | \n");
printf("================================================\n");
for(i=0; i<contador; i++) {
printf("\n");
printf("Cdigo: %d\n", i+1);
printf("Ttulo: %s", proj[i].titulo);
printf("Descrio: %s", proj[i].descricao);
printf("Ano: %d\n", proj[i].ano);
printf("Tipo de projeto: %s", proj[i].tipo);
printf("Pblico: %s", proj[i].publico);
printf("Gerente de projetos responsvel: %s", proj[i].gerente);
printf("Oramento do projeto: R$ %f\n", proj[i].orcamento);
printf("Status: %d\n", proj[i].status);
}
} else {
printf("\n\nLista vazia!\n");
}
system("Pause");
}
void buscar_codigo(base_projetos proj[TAM]) {
int j;
int busca;
int x = 0;
system("cls");
printf("===========================================\n");
printf("| BUSCAR POR CDIGO | \n");
printf("===========================================\n");
printf("\n>> Digite o cdigo que deseja buscar: \n");
scanf ("%d", &busca);
fflush(stdin);
system("cls");
for(j=0; j<contador; j++) {
if(proj[j].codigo == busca) {
printf("\n> Projetos com o cdigo %d: \n", busca);
printf("\n");
printf("Cdigo: %d\n", busca);
printf("Ttulo: %s", proj[j].titulo);
printf("Descrio: %s", proj[j].descricao);
printf("Ano: %d\n", proj[j].ano);
printf("Tipo de projeto: %s", proj[j].tipo);
printf("Pblico: %s", proj[j].publico);
printf("Gerente de projetos responsvel: %s", proj[j].gerente);
printf("Oramento do projeto: R$ %f\n", proj[j].orcamento);
printf("Status: %d\n", proj[j].status);
x += 1;
}
}
if(x == 0) {
printf("\n> Projeto no encontrado com o cdigo %d\n\n", busca);
}
system("Pause");
}
void aFazer(base_projetos proj[TAM]) {
system("cls");
printf("===========================================\n");
printf("| PROJETOS A FAZER | \n");
printf("===========================================\n");
verificarStatus(proj, 1);
}
void fazendo(base_projetos proj[TAM]) {
system("cls");
printf("==========================================\n");
printf("| PROJETOS EM ANDAMENTO | \n");
printf("==========================================\n");
verificarStatus(proj, 2);
}
void concluidos(base_projetos proj[TAM]) {
system("cls");
printf("==========================================\n");
printf("| PROJETOS CONCLUDOS | \n");
printf("==========================================\n");
verificarStatus(proj, 3);
}
void verificarStatus(base_projetos proj[TAM], int st) {
int x = 0;
for(i=0; i<contador; i++) {
if(proj[i].status == st) {
printf("\n");
printf("Cdigo: %d\n", i+1);
printf("Ttulo: %s", proj[i].titulo);
printf("Descrio: %s", proj[i].descricao);
printf("Ano: %d\n", proj[i].ano);
printf("Tipo de projeto: %s", proj[i].tipo);
printf("Pblico: %s", proj[i].publico);
printf("Gerente de projetos responsvel: %s", proj[i].gerente);
printf("Oramento do projeto: R$ %f\n", proj[i].orcamento);
printf("Status: %d\n", proj[i].status);
x += 1;
}
}
if(x == 0) {
printf("\nNo existem projetos com esse status!\n\n");
}
system("Pause");
}
|
C
|
//##########################################################
//## ENSTA Bretagne ##
//## Simplified library code for Dynamixel. ##
//## Inspiration from ROBOTIS 2015.11.02 ##
//##########################################################
#include <stdio.h>
#include <termio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include "dynamixel.h"
#include "r_28_servo.h"
void setMovement(int servo_id,const int angleMin,const int angleMax);//private function
int open_USB2Dyn(const int baudnum,const int deviceIndex){
if( dxl_initialize(deviceIndex, baudnum) == 0 )
{
printf( "Failed to open USB2Dynamixel!\n" );
return 0;
}
else
printf( "Succeed to open USB2Dynamixel!\n" );
return 1;
}
void close_USB2Dyn(){
dxl_terminate();
}
int setAngle(const int servo_id,const int goalPos){
if (goalPos>1023 || goalPos <0)
return ERROR_VALUE_GOAL_POS;
dxl_write_word( servo_id , P_GOAL_POSITION_L, goalPos);
return 1;
}
int setSpeed(const int servo_id,const int speedPos){
if (speedPos>1023 || speedPos <0)
return ERROR_VALUE_GOAL_POS;
dxl_write_word( servo_id , P_MOVING_SPEED_L, speedPos);
return 1;
}
void getPosition(const int servo_id,int *pos,int *CommStatus){
*pos = dxl_read_word( servo_id, P_PRESENT_POSITION_L );
*CommStatus = dxl_get_result();
if(*CommStatus != COMM_RXSUCCESS)
PrintCommStatus(*CommStatus);
}
void isMoving(const int servo_id,int *result,int *CommStatus){
*result = dxl_read_byte( servo_id, P_MOVING);
*CommStatus = dxl_get_result();
if(*CommStatus != COMM_RXSUCCESS)
PrintCommStatus(*CommStatus);
PrintErrorCode();
}
void getOperationType(const int servo_id,int *typeOperation,int *CommStatus){
int cw_val = dxl_read_word( servo_id, P_CW_LIMIT_L);
int ccw_val = dxl_read_word( servo_id, P_CCW_LIMIT_L);
if (cw_val+ccw_val==0)
*typeOperation = WHEEL_TYPE;
else if (cw_val<1024 && ccw_val<1024)
*typeOperation = JOINT_TYPE;
else
*typeOperation = MULTITURN_TYPE;
*CommStatus = dxl_get_result();
if(*CommStatus != COMM_RXSUCCESS)
PrintCommStatus(*CommStatus);
}
void setMovement(int servo_id,const int angleMin,const int angleMax){
int GoalPos[2] = {angleMin,angleMax};
int index =0;
int Moving,CommStatus;
while(1){
// Write goal position
dxl_write_word( servo_id, P_GOAL_POSITION_L, GoalPos[index] );
do
{
// Check moving done
Moving = dxl_read_byte( servo_id, P_MOVING );
CommStatus = dxl_get_result();
if( CommStatus == COMM_RXSUCCESS )
{
if( Moving == 0 )
{
// Change goal position
if( index == 0 )
index = 1;
else
index = 0;
}
}
else
{
PrintCommStatus(CommStatus);
break;
}
}while(Moving == 1);
}
}
// Print communication result
void PrintCommStatus(const int CommStatus)
{
switch(CommStatus)
{
case COMM_TXFAIL:
printf("COMM_TXFAIL: Failed transmit instruction packet!\n");
break;
case COMM_TXERROR:
printf("COMM_TXERROR: Incorrect instruction packet!\n");
break;
case COMM_RXFAIL:
printf("COMM_RXFAIL: Failed get status packet from device!\n");
break;
case COMM_RXWAITING:
printf("COMM_RXWAITING: Now recieving status packet!\n");
break;
case COMM_RXTIMEOUT:
printf("COMM_RXTIMEOUT: There is no status packet!\n");
break;
case COMM_RXCORRUPT:
printf("COMM_RXCORRUPT: Incorrect status packet!\n");
break;
default:
printf("This is unknown error code!\n");
break;
}
}
// Print error bit of status packet
void PrintErrorCode()
{
if(dxl_get_rxpacket_error(ERRBIT_VOLTAGE) == 1)
printf("Input voltage error!\n");
if(dxl_get_rxpacket_error(ERRBIT_ANGLE) == 1)
printf("Angle limit error!\n");
if(dxl_get_rxpacket_error(ERRBIT_OVERHEAT) == 1)
printf("Overheat error!\n");
if(dxl_get_rxpacket_error(ERRBIT_RANGE) == 1)
printf("Out of range error!\n");
if(dxl_get_rxpacket_error(ERRBIT_CHECKSUM) == 1)
printf("Checksum error!\n");
if(dxl_get_rxpacket_error(ERRBIT_OVERLOAD) == 1)
printf("Overload error!\n");
if(dxl_get_rxpacket_error(ERRBIT_INSTRUCTION) == 1)
printf("Instruction code error!\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "z_arv_AVL_ED.h"
#include "fa_impressao.h"
/* inicializa rvore */
int arvAVL_init (char **args) {
TipoArvAVL *defn;
printf("Processando %s ...\n",args[0]);
if (arvAVL != NULL) {
fprintf(stderr, "ED: estrutura jah inicializada - delete-a antes de inicializar\n");
return 3;
} else {
defn = (TipoArvAVL *) malloc(sizeof(TipoArvAVL));
if (defn == NULL) {
fprintf(stderr, "ED: Incapaz de alocar espaco para a estrutura\n");
return 4;
}
arvAVL = defn;
ed_arvAVL_init(arvAVL);
printf("Estrutura criada\n");
return 1;
}
}
/* Busca Elemento na rvore */
int arvAVL_busca (char **args) {
printf("Processando %s ...\n",args[0]);
if (arvAVL == NULL) {
fprintf(stderr, "ED: arv nao inicializada\n");
return 1;
} else {
if (args[1] == NULL) {
fprintf(stderr, "ED: esperado uma chave para busca \n");
return 1;
} else {
int n = toString(args[1]);
TipoRegistro reg;
int i = ed_arvAVL_busca(n,arvAVL->raiz,®);
if (i == 1) printf("Registro encontrado\n");
else printf("Registro nao encontrado\n");
}
return 1;
}
}
/* Insere elemento na rvore */
int arvAVL_insere (char **args) {
TipoRegistro *defn;
printf("Processando %s ...\n",args[0]);
if (arvAVL == NULL) {
fprintf(stderr, "ED: arvore nao inicializada\n");
return 1;
} else {
if (args[1] == NULL) {
fprintf(stderr, "ED: esperado um inteiro para inserir\n");
return 1;
} else {
int n = toString(args[1]);
defn = (TipoRegistro *) malloc(sizeof(TipoRegistro));
if (defn == NULL) {
fprintf(stderr, "ED: Incapaz de alocar espaco para registro\n");
return 2;
} else {
defn -> chave = n;
// Faa implementao
int i = ed_arvAVL_insere(*defn,arvAVL);
if (i==1) printf("Registro Inserido\n");
else printf( "ED: Erro na alocacao do no' na arvore\n" ) ;
}
return 1;
}
}
}
/* Insere vrios elementos na rvore */
int arvAVL_insere_varios (char **args) {
TipoRegistro *defn;
printf("Processando %s ...\n",args[0]);
if (arvAVL == NULL) {
fprintf(stderr, "ED: arv nao inicializada\n");
return 1;
} else {
if (args[1] == NULL) {
fprintf(stderr, "ED: esperado pelo menos um inteiro para insercao\n");
return 1;
};
int j = 1;
while(args[j] != NULL ) {
int n = toString(args[j]);
defn = (TipoRegistro *) malloc(sizeof(TipoRegistro));
if (defn == NULL) {
fprintf(stderr, "ED: Incapaz de alocar espaco para a estrutura\n");
return 2;
} else {
defn -> chave = n;
int i = ed_arvAVL_insere(*defn,arvAVL);
if (i==1) printf("Registro Inserido\n");
else {
printf("ED: erro de alocacao, %d. param em diante nao foi inserido\n",j);
break;
}
}
j++;
}
return 1;
}
}
/* Remove Elemento da rvore */
int arvAVL_remove (char **args) {
printf("Processando %s ...\n",args[0]);
if (arvAVL == NULL) {
fprintf(stderr, "ED: arvore nao inicializada\n");
return 1;
} else {
if (args[1] == NULL) {
fprintf(stderr, "ED: esperado uma chave para remocao \n");
return 1;
} else {
int n = toString(args[1]);
int i = ed_arvAVL_remove(n,arvAVL);
if (i==1) printf("Registro removido\n");
else printf("Registro nao encontrado\n");
}
return 1;
}
}
int arvAVL_altura (char **args)
{
printf("Processando %s ...\n",args[0]);
if (arvAVL == NULL) {
fprintf(stderr, "ED: arvore nao inicializada\n");
return 1;
} else {
int alt = ed_arvAVL_altura(arvAVL->raiz);
printf("Arvore possui altura %d\n", alt);
return 1;
}
}
int arvAVL_emOrd (char **args)
{
printf("Processando %s ...\n",args[0]);
if (arvAVL == NULL) {
fprintf(stderr, "ED: arvore nao inicializada\n");
return 1;
} else {
printf("Percurso em Ordem ===========================\n");
ed_arvAVL_emOrd(arvAVL->raiz);
printf("\n");
return 1;
}
}
int arvAVL_posOrd (char **args)
{
printf("Processando %s ...\n",args[0]);
if (arvAVL == NULL) {
fprintf(stderr, "ED: arvore nao inicializada\n");
return 1;
} else {
printf("Percurso em Pos Ordem ===========================\n");
ed_arvAVL_posOrd(arvAVL->raiz);
printf("\n");
return 1;
}
}
int arvAVL_preOrd (char **args)
{
printf("Processando %s ...\n",args[0]);
if (arvAVL == NULL) {
fprintf(stderr, "ED: arvore nao inicializada\n");
return 1;
} else {
printf("Percurso em Pre' Ordem ===========================\n");
ed_arvAVL_preOrd(arvAVL->raiz);
printf("\n");
return 1;
}
}
int arvAVL_printA(char **args)
{
printf("Processando %s ...\n",args[0]);
if (arvAVL == NULL) {
fprintf(stderr, "ED: arvore nao inicializada\n");
return 1;
} else {
printf("Percurso em Forma A ===========================\n");
ed_arvAVL_emNivel_A(arvAVL->raiz);
printf("\n");
return 1;
}
return 1;
}
int arvAVL_print_nivel_bonito(char **args)
{
printf("Processando %s ...\n",args[0]);
if (arvAVL == NULL) {
fprintf(stderr, "ED: arvore nao inicializada\n");
return 1;
} else {
printf("Percurso em Forma A ===========================\n");
print_nivel(arvAVL->raiz);
printf("\n");
return 1;
}
return 1;
}
|
C
|
/*Accept number from user and
input:7585 5
output:2
input:89765 1
o/p: 0
*/
#include<stdio.h>
int digitfreq(int num,int digit)
{
int dig=0,cnt=0;
if((digit<0)&&(digit>9))
{
return 0;
}
if(num<=0)
{
num=-num;
}
while(num!=0)
{
dig=num%10;
if(dig==digit)
{
cnt++;
}
num=num/10;
}
return cnt ;
}
int main()
{
int ivalue,n,res;
printf("Enter the number");
scanf("%d",&ivalue);
printf("enter the number which we have to find");
scanf("%d",&n);
res=digitfreq(ivalue,n);
printf(" number of given digits %d \n",res);
return 0;
}
|
C
|
#include "message.h"
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
void createNewArray(char** oldMatrix, char** newMatrix, oldMatrixHeight, oldMatrixWidth) {
int newMatrixRowIndex = 0;
int newMatrixColumnIndex = 0;
for(int i = 0 ; i < oldMatrixWidth ; i++, newMatrixRowIndex++) {
newMatrixColumnIndex = 0;
for(int j = oldMatrixHeight - 1; j >= 0; j--, newMatrixColumnIndex++) {
newMatrix[newMatrixRowIndex][newMatrixColumnIndex] = oldMatrix[j][i];
}
}
}
MessageResult messageRotateClockwise(Message message) {
if (message == NULL) {
return MESSAGE_NULL_ARGUMENT;
}
if(message->type == MESSAGE_TEXT) {
return MESSAGE_WRONG_TYPE;
}
int oldMatrixHeight = message->content.image.height;
int oldMatrixWidth = message->content.image.width;
//!!!!!!!!!!!!!!MALLOC NEW MATRIX!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
char **newMatrix = (char**)malloc(sizeof(char)*(oldMatrixHeight)*(oldMatrixWidth));
createNewArray(message->content.image.data, newMatrix, oldMatrixHeight, oldMatrixWidth);
message->content.image.data = newMatrix;
return MESSAGE_SUCCESS;
//do we have to free the memory which we did malloc to?
}
int main() {
return 0;
}
|
C
|
#include "LCD_RG1602A.h"
#include "Delay.h"
#define SET_LCD_E HAL_GPIO_WritePin(LCD_E_GPIO_Port, LCD_E_Pin, GPIO_PIN_SET)
#define RESET_LCD_E HAL_GPIO_WritePin(LCD_E_GPIO_Port, LCD_E_Pin, GPIO_PIN_RESET)
//BORYS
#define SET_LCD_RS HAL_GPIO_WritePin(LCD_RS_GPIO_Port, LCD_RS_Pin, GPIO_PIN_SET)
#define RESET_LCD_RS HAL_GPIO_WritePin(LCD_RS_GPIO_Port, LCD_RS_Pin, GPIO_PIN_RESET)
/*
#define SET_LCD_RS HAL_GPIO_WritePin(LCD_RS_TEMP_GPIO_Port, LCD_RS_TEMP_Pin, GPIO_PIN_SET)
#define RESET_LCD_RS HAL_GPIO_WritePin(LCD_RS_TEMP_GPIO_Port, LCD_RS_TEMP_Pin, GPIO_PIN_RESET)
*/
#ifdef USE_RW
#define SET_LCD_RW HAL_GPIO_WritePin(LCD_RW_GPIO_Port, LCD_RW_Pin, GPIO_PIN_SET)
#define RESET_LCD_RW HAL_GPIO_WritePin(LCD_RW_GPIO_Port, LCD_RW_Pin, GPIO_PIN_RESET)
#endif
/*
*
* INSIDE FUNCTIONS
*
*/
//
// Set data port
//BORYS
extern volatile char argument;
static inline void LCD_SetDataPort(uint8_t data)
{
// argument = data;
#ifdef LCD_4BIT
if(data & (1<<0))
{
HAL_GPIO_WritePin(LCD_D4_GPIO_Port, LCD_D4_Pin, GPIO_PIN_SET);
}
else
{
HAL_GPIO_WritePin(LCD_D4_GPIO_Port, LCD_D4_Pin, GPIO_PIN_RESET);
}
if(data & (1<<1))
{
HAL_GPIO_WritePin(LCD_D5_GPIO_Port, LCD_D5_Pin, GPIO_PIN_SET);
}
else
{
HAL_GPIO_WritePin(LCD_D5_GPIO_Port, LCD_D5_Pin, GPIO_PIN_RESET);
}
if(data & (1<<2))
{
HAL_GPIO_WritePin(LCD_D6_GPIO_Port, LCD_D6_Pin, GPIO_PIN_SET);
}
else
{
HAL_GPIO_WritePin(LCD_D6_GPIO_Port, LCD_D6_Pin, GPIO_PIN_RESET);
}
if(data & (1<<3))
{
HAL_GPIO_WritePin(LCD_D7_GPIO_Port, LCD_D7_Pin, GPIO_PIN_SET);
}
else
{
HAL_GPIO_WritePin(LCD_D7_GPIO_Port, LCD_D7_Pin, GPIO_PIN_RESET);
}
#endif
}
#ifdef USE_RW
static inline uint8_t LCD_GetDataPort()
{
uint8_t result = 0;
#ifdef LCD_4BIT
if(HAL_GPIO_ReadPin(LCD_D4_GPIO_Port, LCD_D4_Pin) == GPIO_PIN_SET) result |= (1<<0);
if(HAL_GPIO_ReadPin(LCD_D5_GPIO_Port, LCD_D5_Pin) == GPIO_PIN_SET) result |= (1<<1);
if(HAL_GPIO_ReadPin(LCD_D6_GPIO_Port, LCD_D6_Pin) == GPIO_PIN_SET) result |= (1<<2);
if(HAL_GPIO_ReadPin(LCD_D7_GPIO_Port, LCD_D7_Pin) == GPIO_PIN_SET) result |= (1<<3);
#endif
argument=result;
return result;
}
#endif
static void LCD_DataOut()
{
GPIO_InitTypeDef GPIO_InitStruct;
#ifdef LCD_4BIT
GPIO_InitStruct.Pin = LCD_D4_Pin|LCD_D5_Pin|LCD_D6_Pin|LCD_D7_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
#endif
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}
static void LCD_DataIn()
{
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = LCD_D4_Pin|LCD_D5_Pin|LCD_D6_Pin|LCD_D7_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}
//
// Write byte to LCD
//
uint8_t LCD_ReadByte(void)
{
uint8_t result = 0;
LCD_DataIn();
SET_LCD_RW;
delay(1,&htim4);
SET_LCD_E;
delay(5,&htim4);
result = (LCD_GetDataPort() << 4);
RESET_LCD_E;
RESET_LCD_RW;
delay(3,&htim4);
RESET_LCD_RW;
SET_LCD_E;
delay(5,&htim4);
result |= LCD_GetDataPort();
RESET_LCD_E;
delay(3,&htim4);
argument=result;
return result;
}
//
// Check Busy Flag
//
uint8_t LCD_CheckBusyFlag()
{
RESET_LCD_RS;
delay(1,&htim4);
return LCD_ReadByte();
}
//
// Write byte to LCD
//
void LCD_WriteByte(uint8_t data)
{
#ifdef USE_RW // There is no need to change GPIO direction if RW is not used
LCD_DataOut();
RESET_LCD_RW;
#endif
#ifdef LCD_4BIT
delay(1,&htim4);
LCD_SetDataPort(data >> 4);
SET_LCD_E;
delay(1,&htim4);
RESET_LCD_E;
delay(2,&htim4);
#endif
LCD_SetDataPort(data);
SET_LCD_E;
delay(1,&htim4);
RESET_LCD_E;
delay(2,&htim4);
/*#ifdef USE_RW
while((LCD_CheckBusyFlag() & (1<<7))); // Wait for data processing
argument=argument;
#else
HAL_Delay(1);
delay(120, &htim4); // Wait for data processing
#endif*/
// HAL_Delay(1);
delay(1200, &htim4); // Wait for data processing
}
//
// Write command to LCD
//
void LCD_WriteCmd(uint8_t cmd)
{
RESET_LCD_RS;
LCD_WriteByte(cmd);
#ifndef USE_RW
delay(1000, &htim4); //<<--- wait for command processing
#endif
}
//
// Write data to LCD
//
void LCD_WriteData(uint8_t data)
{
SET_LCD_RS;
argument=data;
LCD_WriteByte(data);
}
/*
*
* USER FUNCTIONS
*
*/
//
// Write one character to LCD
//
void LCD_Char(unsigned char c)
{
LCD_WriteData(c);
// LCD_WriteData(((c >= 0x80) && (c <= 0x87)) ? (c & 0x07) : c);
}
//
// Write string to LCD
//
void LCD_String(char* str)
{
while(*str)
{
argument=*(str+1);
LCD_Char(*str);
str++;
}
argument=argument;
}
//
// Print integer on LCD
//
void LCD_Int(int value)
{
char buf[LCD_X+1];
sprintf(buf, "%d", value);
LCD_String(buf);
}
//
// Print hexadecimal on LCD
//
void LCD_Hex(int value, uint8_t upper_case)
{
char buf[LCD_X+1];
if(upper_case)
sprintf(buf, "%X", value);
else
sprintf(buf, "%x", value);
LCD_String(buf);
}
//
// Define custom char in LCD CGRAM in 'number' slot
//
void LCD_DefChar(uint8_t number, uint8_t *def_char)
{
uint8_t i, c;
LCD_WriteCmd(64+((number&0x7)*8));
for(i = 0; i < 8; i++)
{
c = *(def_char++);
LCD_WriteData(c);
}
}
//
// Back to home position
//
void LCD_Home(void)
{
LCD_WriteCmd(LCDC_CLS|LCDC_HOME);
}
//
// Control cursor visibility
//
void LCD_Cursor(uint8_t on_off)
{
if(on_off == 0)
LCD_WriteCmd(LCDC_ONOFF|LCDC_DISPLAYON);
else
LCD_WriteCmd(LCDC_ONOFF|LCDC_DISPLAYON|LCDC_CURSORON);
}
//
// Control cursor blinking
//
void LCD_Blink(uint8_t on_off)
{
if(on_off == 0)
LCD_WriteCmd(LCDC_ONOFF|LCDC_DISPLAYON);
else
LCD_WriteCmd(LCDC_ONOFF|LCDC_DISPLAYON|LCDC_CURSORON|LCDC_BLINKON);
}
//
// Set cursor for x-column, y-row
//
void LCD_Locate(uint8_t x, uint8_t y)
{
switch(y)
{
case 0:
y = LCD_LINE1;
break;
#if (LCD_Y>1)
case 1:
y = LCD_LINE2;
break;
#endif
#if (LCD_Y>2)
case 2:
y = LCD_LINE3;
break;
#endif
#if (LCD_Y>3)
case 3:
y = LCD_LINE4;
break;
#endif
}
LCD_WriteCmd((0x80 + y + x));
}
//
// Clear LCD
//
void LCD_Cls(void)
{
LCD_WriteCmd(LCDC_CLS);
}
//
// Initialization
//
void LCD_Init(void)
{
RESET_LCD_RS;
RESET_LCD_E;
#ifdef USE_RW
RESET_LCD_RW;
#endif
LCD_DataOut();
HAL_Delay(45);
/*
// LCD_SetDataPort(LCDC_FUNC|LCDC_FUNC8B);
LCD_SetDataPort(0x03);
// delay(4100, &htim4);
delay(4200, &htim4);
//LCD_SetDataPort(LCDC_FUNC|LCDC_FUNC8B);
LCD_SetDataPort(0x03);
// delay(100, &htim4);
delay(200, &htim4);
#ifdef LCD_4BIT
//LCD_SetDataPort(LCDC_FUNC|LCDC_FUNC4B); //4-byte mode
LCD_SetDataPort(0x2);
delay(100, &htim4);
LCD_WriteCmd(LCDC_FUNC|LCDC_FUNC4B|LCDC_FUNC2L|LCDC_FUNC5x7); // 4-bit, 2 lanes, 5x7 chars
#endif
LCD_WriteCmd(LCDC_ONOFF|LCDC_CURSOROFF); // Cursor off
LCD_WriteCmd(LCDC_ONOFF|LCDC_DISPLAYON); // LCD on
LCD_WriteCmd(LCDC_ENTRY|LCDC_ENTRYR); // Data entry right
LCD_Cls(); // Clear display
delay(4500, &htim4);
*/
LCD_SetDataPort(0x03);
SET_LCD_E;
delay(1, &htim4);
RESET_LCD_E;
delay(5100, &htim4);
LCD_SetDataPort(0x03);
SET_LCD_E;
delay(1, &htim4);
RESET_LCD_E;
delay(180, &htim4);
LCD_SetDataPort(0x03);
SET_LCD_E;
delay(1, &htim4);
RESET_LCD_E;
delay(180, &htim4);
LCD_SetDataPort(0x02);
SET_LCD_E;
delay(1, &htim4);
RESET_LCD_E;
delay(120, &htim4);
LCD_SetDataPort(0x02);
SET_LCD_E;
delay(1, &htim4);
RESET_LCD_E;
delay(10, &htim4);
LCD_SetDataPort(0x08);
SET_LCD_E;
delay(1, &htim4);
RESET_LCD_E;
delay(120, &htim4);
LCD_SetDataPort(0x00);
SET_LCD_E;
delay(1, &htim4);
RESET_LCD_E;
delay(120, &htim4);
LCD_SetDataPort(0x0F);
SET_LCD_E;
delay(1, &htim4);
RESET_LCD_E;
delay(120, &htim4);
LCD_SetDataPort(0x00);
SET_LCD_E;
delay(1, &htim4);
RESET_LCD_E;
delay(120, &htim4);
LCD_SetDataPort(0x06);
SET_LCD_E;
delay(1, &htim4);
RESET_LCD_E;
delay(120, &htim4);
LCD_Cls();
/*
LCD_WriteCmd(LCDC_FUNC|LCDC_FUNC4B|LCDC_FUNC2L|LCDC_FUNC5x7); // 4-bit, 2 lanes, 5x7 chars
// LCD_WriteCmd(LCDC_FUNC|LCDC_FUNC4B|LCDC_FUNC5x7|LCDC_FUNC2L);
LCD_WriteCmd(LCDC_ONOFF|LCDC_CURSOROFF); // Cursor off
LCD_WriteCmd(LCDC_ONOFF|LCDC_DISPLAYON); // LCD on
LCD_WriteCmd(LCDC_ENTRY|LCDC_ENTRYR); // Data entry right
// LCD_WriteCmd(0x02|0x00);
LCD_Cls(); // Clear display
*/
delay(4500, &htim4);
}
|
C
|
#include <linux/init.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/init_task.h>
#include <linux/kernel.h>
MODULE_LICENSE("GPL");
static const char *task_state_array[] = {
"R (running)", /* 0 */
"S (sleeping)", /* 1 */
"D (disk sleep)", /* 2 */
"T (stopped)", /* 4 */
"T (tracing stop)", /* 8 */
"Z (zombie)", /* 16 */
"X (dead)" /* 32 */
};
static inline const char *get_task_state(struct task_struct *tsk)
{
unsigned int state = (tsk->state & TASK_REPORT) | tsk->exit_state;
const char **p = &task_state_array[0];
while (state) {
p++;
state >>= 1;
}
return *p;
}
static int __init listall_init(void)
{
struct task_struct *task;
for_each_process(task) {
if(task->mm == NULL){
printk(KERN_INFO"%-25s%-7d%-25s%-7d%-7d\n",
task->comm,
task->pid,
get_task_state(task),
task->prio,
task->parent->pid
);
}
}
return 0;
}
static void __exit listall_exit(void)
{
printk(KERN_ALERT"goodbye\n");
return 0;
}
module_init(listall_init);
module_exit(listall_exit);
|
C
|
#include <stdio.h>
int main(void) {
int i;
printf("%%d\t%%.2f\t%%x\t%%c\n");
for (i = 0; i < 64; i++) {
printf("%d\t%.2f\t%x\t%c\n", i, i+0.0, i, (char) i+65);
}
}
|
C
|
// cyclically rotate array by one
#include<stdio.h>
int crotate(int a[],int size)
{
int temp,i;
temp=a[size-1];
for(i=size-1;i>=1;i--)
{
a[i]=a[i-1];
}
a[0]=temp;
//printf("test");
return 0;
}
main()
{
int a[20],n,i,ch;
printf("Enter the size of the array:\n");
scanf("%d",&n);
printf("Enter the data:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
do {
printf("Enter your choice:\n");
printf("1.Rotate\n2.display\n3.exit\n");
scanf("%d",&ch);
switch(ch)
{
case 1:{
crotate(a,n);
}
break;
case 2:{
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n");
break;
}
}
}
while(ch==1||ch==2);
}
|
C
|
/*cccp generate
return '\n\tputs("Hello, world!");\n'
*/
#include <stdio.h>
#include <math.h>
int main() {
/*cccp begin*/
puts("Hello, world!");
/*cccp end 61DD0743*/
/*cccp generate
-- Create a sine LUT of length 1000.
return '\n\tputs("Need more generation.");\n'
*/
/*cccp begin*/
puts("Need more generation.");
/*cccp end B4030A83*/
for (int i = 0; i < length; i++) {
printf("%f", sineLUT[i]);
if (i >= length - 1) {
putc('\n', stdout);
}
else {
putc(' ', stdout);
}
}
return 0;
}
|
C
|
/*
*Implement popen() and pclose(). Although these functions are simplified by not requiring the signal handling employed in the implementation of system() (Section 27.7),
* you will need to be careful to correctly bind the pipe ends to file streams in each process, and to ensure that all unused descriptors referring to the pipe ends are closed.
*Since children created by multiple calls to popen() may be running at one time,
* you will need to maintain a data structure that associates the file stream pointers allocated by popen() with the corresponding child process IDs.
*(If using an array for this purpose, the value returned by the fileno() function, which obtains the file descriptor corresponding to a file stream, can be used to index the array.)
*Obtaining the correct process ID from this structure will allow pclose() to select the child upon which to wait.
*This structure will also assist with the SUSv3 requirement that any still-open file streams created by earlier calls to popen() must be closed in the new child process.
*
* $ ./pipes/t_popen
* ++ PID TTY TIME CMD
* ++ 4255 pts/0 00:00:01 bash
* ++ 6916 pts/0 00:00:00 t_popen
* ++ 6917 pts/0 00:00:00 sh
* ++ 6918 pts/0 00:00:00 ps
* 2 4 25
*
*/
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include "tlpi_hdr.h"
#define BUF_SIZE 100
static int arr[10000];
static FILE *
t_popen(const char *command, const char *type)
{
int pfd[2], child_pid; /* Pipe file descriptors */
FILE * stream;
if (pipe(pfd) == -1) /* Create pipe */
errExit("pipe");
if(strcmp(type, "r")==0)
{
char mode = 'r';
stream = fdopen(pfd[0], &mode);
}
else
{
char mode = 'w';
stream = fdopen(pfd[1], &mode);
}
switch (child_pid = fork()) {
case -1:
errExit("fork");
case 0:
if(strcmp(type, "r")==0)
{
if (close(pfd[0]) == -1) /* Read end is unused */
errExit("close");
if (pfd[1] != STDOUT_FILENO) { /* Defensive check */
if (dup2(pfd[1], STDOUT_FILENO) == -1)
errExit("dup2 ");
if (close(pfd[1]) == -1)
errExit("close ");
}
}
else
{
if (close(pfd[1]) == -1) /* Write end is unused */
errExit("close");
if (pfd[0] != STDIN_FILENO) { /* Defensive check */
if (dup2(pfd[0], STDIN_FILENO) == -1)
errExit("dup2 ");
if (close(pfd[0]) == -1)
errExit("close ");
}
}
execl("/bin/sh", "sh", "-c", command, (char *) NULL);
_exit(127); /* We could not exec the shell */
default:
arr[fileno(stream)] = child_pid;
if(strcmp(type, "r")==0)
{
if (close(pfd[1]) == -1) /* Write end is unused */
errExit("close");
}
else
{
if (close(pfd[0]) == -1) /* Read end is unused */
errExit("close");
}
return stream;
}
}
static int
t_pclose(FILE *stream){
int status;
int childPid = arr[fileno(stream)];
fclose(stream);
while (waitpid(childPid, &status, 0) == -1) {
if (errno != EINTR) { /* Error other than EINTR */
status = -1;
break; /* So exit loop */
}
}
return status;
}
int
main(int argc, char *argv[])
{
char res[BUF_SIZE];
FILE *fp = t_popen("ps", "r");
if (fp == NULL) {
errExit("t_popen");
}
while (fgets(res, BUF_SIZE, fp) != NULL) {
printf("++%s", res);
}
int status = t_pclose(fp);
if(status==-1)
errExit("pclose");
fp = t_popen("wc", "w");
char *str = "First line \n Second line\n";
fputs(str,fp);
status = t_pclose(fp);
if(status==-1)
errExit("pclose");
exit(EXIT_SUCCESS);
}
|
C
|
/* */
/* RFF.C : Recursive find file utility */
/* */
/* Programmed By Lee jaekyu */
/* */
#include <stdio.h>
#include <dos.h>
#include <dir.h>
#define ALL_ATTRIB FA_RDONLY|FA_HIDDEN|FA_SYSTEM|FA_LABEL|FA_DIREC|FA_ARCH
void findfile(char *mask)
{
char path[80];
struct ffblk info;
if (findfirst(mask, &info, ALL_ATTRIB) == 0)
{
do
{
getcwd(path, 80);
printf("\n%s%s%s", path,
strlen(path) == 3 ? "" : "\\",
info.ff_name);
} while (findnext(&info) == 0);
}
if (findfirst("*", &info, FA_DIREC) == 0)
{
do
{
if (info.ff_name[0] == '.' || info.ff_attrib != FA_DIREC)
continue;
chdir(info.ff_name);
findfile(mask);
chdir("..");
} while (findnext(&info) == 0);
}
}
int main(int argc, char *argv[])
{
char curpath[30];
if (argc < 2)
{
printf("\nUsage : RFF <file mask>");
return 0;
}
getcwd(curpath, 30);
chdir("\\");
findfile(argv[1]);
chdir(curpath);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h> /* General Utilities */
#include <unistd.h>
#include <sys/file.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#define LOGFILE "log.txt"
/* Gets a lock of the indicated type on the fd which is passed.
The type should be either F_UNLCK, F_RDLCK, or F_WRLCK */
void getlock(int fd, int type) {
struct flock lockinfo;
/* we'll lock the entire file */
lockinfo.l_whence = SEEK_SET;
lockinfo.l_start = 0;
lockinfo.l_len = 0;
/* keep trying until we succeed */
while (1) {
lockinfo.l_type = type;
/* if we get the lock, return immediately */
if (!fcntl(fd, F_SETLK, &lockinfo)) return;
/* find out who holds the conflicting lock */
fcntl(fd, F_GETLK, &lockinfo);
/* we wait for PARENT OR CHID to write their message */
sleep(0.25);
}
}
void Log (char *message)
{
int fd;
fd = open(LOGFILE, O_RDWR | O_APPEND, 0666);
if (fd < 0) {
perror("ERROR : open log file");
exit(0);
}
getlock(fd, F_RDLCK);
if ( write(fd, message, strlen(message)) == EOF ) exit(0);
if ( close(fd) != 0) exit(0);
}
|
C
|
// This file is for Step 2.
// You should do
// Step 2 (A): write seq2
// Step 2 (B): write main to test seq2
// Step 2 (C): write sumSeq2
// Step 2 (D): add test cases to main to test sumSeq2
//
// Be sure to #include any header files you need!
#include <stdio.h>
#include <stdlib.h>
int seq2(int x) {
int y;
if ((x > 0) && ((x % 4) == 2)) {
y = 2 * x;
}
else {
if ((x < 0) && (((-x) % (-4)) == 2)) {
y = 2 * x;
}
else {
y = x * (x + 3) + 1;
}
}
return y;
}
int sumSeq2(int low, int high) {
int s = 0;
if (low >= high) {
return 0;
}
for (int i = low; i <= high - 1; i++) {
s += seq2(i);
}
return s;
}
int main(void) {
int y = seq2(2);
printf("seq2(%d) = %d\n", 2, y);
y = seq2(12);
printf("seq2(%d) = %d\n", 12, y);
y = seq2(13);
printf("seq2(%d) = %d\n", 13, y);
y = seq2(-4);
printf("seq2(%d) = %d\n", -4, y);
y = seq2(-2);
printf("seq2(%d) = %d\n", -2, y);
y = seq2(-6);
printf("seq2(%d) = %d\n", -6, y);
y = sumSeq2(0, 2);
printf("sumSeq2(%d, %d) = %d\n", 0, 2, y);
y = sumSeq2(3, 6);
printf("sumSeq2(%d, %d) = %d\n", 3, 6, y);
y = sumSeq2(9, 7);
printf("sumSeq2(%d, %d) = %d\n", 9, 7, y);
y = sumSeq2(9, 9);
printf("sumSeq2(%d, %d) = %d\n", 9, 9, y);
y = sumSeq2(-4, -1);
printf("sumSeq2(%d, %d) = %d\n", -4, -1, y);
y = sumSeq2(-3, 2);
printf("sumSeq2(%d, %d) = %d\n", -3, 2, y);
return 0;
}
|
C
|
#include "lists.h"
#include <stdlib.h>
#include <stdio.h>
/**
* reverse_listint - main entry, reverse the linked list
* @head: pointer to the head of the node
*
* Return: a pointer to the first node of the reversed list
*/
listint_t *reverse_listint(listint_t **head)
{
listint_t *curr;
listint_t *prev;
prev = NULL;
curr = *head;
while (*head != NULL)
{
*head = (*head)->next;
curr->next = prev;
prev = curr;
curr = *head;
}
*head = prev;
return (*head);
}
|
C
|
#include<stdio.h>
void main() {
//ּ : ؼϰ ڵ տ ۼ
// 1. ڵ忡 ۼ
// 2. ʴ ڵ带
// ּ : ctrl + k + c
// ּ Ű : ctrl + k + u
/*
ּ
ڵ带 ּó ϱ ؼ
ּ ʿϴ.
*/
//̸ ϴ κ
//printf("ǥ\n");
//̸ ϴ κ
//printf("10\n");
}
|
C
|
/*
** EPITECH PROJECT, 2020
** main
** File description:
** main
*/
#include "minishell.h"
void setup_shell(t_shell *mysh, t_env *envi, char **env)
{
remove_jumpline(mysh->buffer);
mysh->clean = clean_str(mysh->buffer, ';');
mysh->opt = my_strtok(mysh->clean, ";");
mysh->args = my_str_to_word_array(mysh->clean);
mysh->env = env;
mysh->envi = envi;
mysh->pwd = init_pwdstruct(mysh);
mysh->redi = init_redi(mysh);
}
void loop_args(char **env, t_shell *mysh)
{
my_getpath(env, mysh);
}
t_shell *init_struct(void)
{
t_shell *mysh = malloc(sizeof(t_shell) * 1);
mysh->args = NULL;
mysh->path = NULL;
mysh->buffer = NULL;
mysh->cmd = NULL;
mysh->opt = NULL;
mysh->env = NULL;
mysh->clean = NULL;
mysh->len = 0;
mysh->exit = 0;
mysh->envi = NULL;
mysh->pwd = NULL;
mysh->redi = NULL;
return (mysh);
}
void shell_loop(char **argv, char **env)
{
t_shell *mysh;
mysh = init_struct();
t_env *envi = env_tolist(env);
while (1){
my_putstr("$> ");
if (getline(&mysh->buffer, &mysh->len, stdin) == -1){
my_printf("exit\n");
exit(mysh->exit);
}
setup_shell(mysh, envi, env);
loop_args(mysh->env, mysh);
my_cmd(mysh);
free(mysh->args);
free(mysh->clean);
}
}
int main(int argc, char **argv, char **env)
{
shell_loop(argv, env);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_print.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kylee <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/12 15:47:15 by kylee #+# #+# */
/* Updated: 2020/02/12 16:25:38 by kylee ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_print.h"
#include "ft_math.h"
#include "ft_valid.h"
#include "ft_utils.h"
/*
** desc: 왼쪽, 왼쪽 대각선, 위의 값을 확인해서 최소값을 찾아주는 함수
** params:
** return:
*/
int ft_min_arr(t_array *arr, int i)
{
int temp;
if (i == 0)
{
temp = arr->array[i];
arr->array[i] = ft_min(arr->array[i], arr->diagonal);
arr->diagonal = temp;
return (0);
}
else
{
temp = arr->array[i];
arr->array[i] = ft_min(arr->array[i], arr->array[i - 1]);
arr->array[i] = ft_min(arr->array[i], arr->diagonal);
arr->diagonal = temp;
}
return (arr->array[i]);
}
int ft_set_num(char *buf, t_map_argu *map_argu, int row)
{
int i;
i = -1;
map_argu->arr->diagonal = 0;
while (++i < map_argu->map->num_col)
{
if (buf[i] == map_argu->map->obstacle_char)
map_argu->arr->array[i] = 0;
else if (buf[i] == map_argu->map->empty_char)
map_argu->arr->array[i] = ft_min_arr(map_argu->arr, i) + 1;
else
return (ft_g_error());
if (map_argu->arr->array[i] > map_argu->res->max_num)
{
map_argu->res->max_num = map_argu->arr->array[i];
map_argu->res->res_row = row;
map_argu->res->res_col = i;
}
}
if (!(buf[i] == '\n' || buf[i] == '\0'))
return (ft_g_error());
return (0);
}
void ft_get_char(char *buf, t_map_con *map, t_res_po *res, int row)
{
int i;
i = 0;
while (i < map->num_col)
{
if (buf[i] == map->obstacle_char)
ft_write_c(map->obstacle_char);
else if (ft_is_box(res, i, row))
ft_write_c(map->full_char);
else
ft_write_c(map->empty_char);
i++;
}
ft_write("\n");
return ;
}
void ft_print_res(char *map_name, t_res_po *res, t_map_con *map)
{
int fd;
char buf[MAX_LEN];
int i;
fd = open(map_name, O_RDONLY);
read(fd, buf, map->num_col_first + 1);
i = 0;
while (i < map->num_row)
{
read(fd, buf, map->num_col + 1);
buf[map->num_col] = '\0';
ft_get_char(buf, map, res, i);
i++;
}
close(fd);
}
|
C
|
/*{{{ includes */
#include "PTMEPT-utils.h"
#include "PTMEPT.h"
#include <MEPT-utils.h>
#include <assert.h>
#include <stdlib.h>
#include <aterm2.h>
#include <string.h>
/*}}} */
static ATermTable lowerCache = NULL;
/*{{{ static PTPT_Tree lookupTree(PT_Tree tree) */
static PT_Tree lookupTree(PTPT_Tree tree)
{
if (lowerCache) {
return PT_TreeFromTerm(ATtableGet(lowerCache, PTPT_TreeToTerm(tree)));
}
return NULL;
}
/*}}} */
/*{{{ static PTPT_Symbol lookupSymbol(PT_Symbol symbol) */
static PT_Symbol lookupSymbol(PTPT_Symbol symbol)
{
if (lowerCache) {
return PT_SymbolFromTerm(ATtableGet(lowerCache, PTPT_SymbolToTerm(symbol)));
}
return NULL;
}
/*}}} */
/*{{{ static PTPT_ATerm lookupATerm(PT_ATerm symbol) */
static ATerm lookupATerm(PTPT_ATerm trm)
{
if (lowerCache) {
return ATtableGet(lowerCache, PTPT_ATermToTerm(trm));
}
return NULL;
}
/*}}} */
/*{{{ static int PTPT_lowerNatCon(PTPT_NatCon val) */
static int PTPT_lowerNatCon(PTPT_NatCon val)
{
char *valStr = PT_yieldTree((PT_Tree) val);
int result = atoi(valStr);
return result;
}
/*}}} */
/*{{{ static int PTPT_lowerIntCon(PTPT_IntCon val) */
static int PTPT_lowerIntCon(PTPT_IntCon val)
{
int result = PTPT_lowerNatCon(PTPT_getIntConNatCon(val));
return PTPT_isIntConNegative(val) ? -result : result;
}
/*}}} */
/*{{{ static double PTPT_lowerRealCon(PTPT_RealCon val) */
static double PTPT_lowerRealCon(PTPT_RealCon val)
{
ATerror("lower: reals not implemented!\n");
return 0.0;
}
/*}}} */
/*{{{ static AFun PTPT_lowerStrCon(PTPT_StrCon string) */
static AFun PTPT_lowerStrCon(PTPT_StrCon string)
{
char *str = PT_yieldTree((PT_Tree) string);
ATerm appl;
AFun fun;
appl = ATparse(str);
fun = ATgetAFun((ATermAppl) appl);
return fun;
}
/*}}} */
/*{{{ static AFun PTPT_lowerIdCon(PTPT_IdCon string) */
static AFun PTPT_lowerIdCon(PTPT_IdCon string)
{
ATerm appl = ATparse(PT_yieldTree((PT_Tree) string));
return ATgetAFun((ATermAppl) appl);
}
/*}}} */
/*{{{ static AFun PTPT_lowerAFun(PTPT_AFun fun, int arity) */
static AFun PTPT_lowerAFun(PTPT_AFun fun, int arity)
{
AFun result = 0;
if (PTPT_isAFunQuoted(fun)) {
result = PTPT_lowerStrCon(PTPT_getAFunStrCon(fun));
}
else if (PTPT_isAFunUnquoted(fun)) {
result = PTPT_lowerIdCon(PTPT_getAFunIdCon(fun));
}
/* put the proper arity in the result */
result = ATmakeAFun(ATgetName(result), arity, ATisQuoted(result));
return result;
}
/*}}} */
ATerm PTPT_lowerATerm(PTPT_ATerm term);
/*{{{ static ATermList PTPT_lowerATermList(PTPT_ATerm listelems) */
static ATermList PTPT_lowerATermList(PTPT_ATerm listelems)
{
ATermList list = ATempty;
PTPT_ATermElems elems = PTPT_getATermElems(listelems);
for (; !PTPT_isATermElemsEmpty(elems);
elems = PTPT_getATermElemsTail(elems)) {
ATerm head = PTPT_lowerATerm(PTPT_getATermElemsHead(elems));
list = ATinsert(list, head);
if (!PTPT_hasATermElemsTail(elems)) {
break;
}
}
return ATreverse(list);
}
/*}}} */
/*{{{ static ATermList PTPT_lowerAnnotations(PTPT_ATermAnnos annos) */
static ATermList PTPT_lowerAnnotations(PTPT_ATermAnnos annos)
{
PTPT_OptLayout e = PTPT_makeOptLayoutAbsent();
PTPT_ATerm list = PTPT_makeATermList(e, (PTPT_ATermElems) annos, e);
return PTPT_lowerATermList(list);
}
/*}}} */
/*{{{ static ATermList PTPT_lowerAnn(PTPT_Ann ann) */
static ATermList PTPT_lowerAnn(PTPT_Annotation ann)
{
return PTPT_lowerAnnotations(PTPT_getAnnotationAnnos(ann));
}
/*}}} */
/*{{{ static PT_ATerm PTPT_lowerATermAppl(ATermAppl appl) */
static ATerm PTPT_lowerATermAppl(PTPT_ATerm appl)
{
ATermList args;
AFun fun;
PTPT_OptLayout e = PTPT_makeOptLayoutAbsent();
/* hack alert, PT_ATermArgs is the same as an ATermList by coincidence */
PTPT_ATerm list = PTPT_makeATermList(e, (PTPT_ATermElems)
PTPT_getATermArgs(appl),
e);
args = (ATermList) PTPT_lowerATermList(list);
fun = PTPT_lowerAFun(PTPT_getATermFun(appl), ATgetLength(args));
return (ATerm) ATmakeApplList(fun, args);
}
/*}}} */
/*{{{ PT_ATerm PTPT_lowerATerm(ATerm term) */
ATerm PTPT_lowerATerm(PTPT_ATerm term)
{
ATerm result = lookupATerm(term);
ATermList ann = NULL;
if (result != NULL) {
return result;
}
if (PTPT_hasATermAnnotation(term)) {
ann = PTPT_lowerAnn(PTPT_getATermAnnotation(term));
}
if (PTPT_isATermList(term)) {
result = (ATerm) PTPT_lowerATermList(term);
}
else if (PTPT_isATermAppl(term)) {
result = PTPT_lowerATermAppl(term);
}
else if (PTPT_isATermFun(term)) {
{
AFun afun = PTPT_lowerAFun(PTPT_getATermFun(term), 0);
result = (ATerm) ATmakeAppl0(afun);
}
}
else if (PTPT_isATermInt(term)) {
PTPT_IntCon intc = PTPT_getATermIntCon(term);
result = (ATerm) ATmakeInt(PTPT_lowerIntCon(intc));
}
else if (PTPT_isATermReal(term)) {
PTPT_RealCon real = PTPT_getATermRealCon(term);
result = (ATerm) ATmakeReal(PTPT_lowerRealCon(real));
}
else if (PTPT_isATermPlaceholder(term)) {
ATerm type = PTPT_lowerATerm(PTPT_getATermType(term));
result = (ATerm) ATmakePlaceholder(type);
}
else {
ATwarning("lower: unsupported ATerm %t\n", term);
assert(ATfalse);
}
return result;
}
/*}}} */
/*{{{ static PT_CharRanges PTPT_lowerCharRanges(PTPT_CharRanges symbols) */
static PT_CharRange PTPT_lowerCharRange(PTPT_CharRange symbol);
static PT_CharRanges PTPT_lowerCharRanges(PTPT_CharRanges symbols)
{
PTPT_CharRangeList ranges = PTPT_getCharRangesList(symbols);
PT_CharRanges list = PT_makeCharRangesEmpty();
for (; !PTPT_isCharRangeListEmpty(ranges);
ranges = PTPT_getCharRangeListTail(ranges)) {
PT_CharRange head =
PTPT_lowerCharRange(PTPT_getCharRangeListHead(ranges));
list = PT_makeCharRangesMany(head, list);
if (!PTPT_hasCharRangeListTail(ranges)) {
break;
}
}
return (PT_CharRanges) ATreverse((ATermList) list);
}
/*}}} */
/*{{{ static PT_Symbols PTPT_lowerSymbols(PTPT_Symbols symbols) */
static PT_Symbol PTPT_lowerSymbol(PTPT_Symbol symbol);
static PT_Symbols PTPT_lowerSymbols(PTPT_Symbols symbols)
{
PTPT_SymbolList elems = PTPT_getSymbolsList(symbols);
PT_Symbols list = PT_makeSymbolsEmpty();
for (; !PTPT_isSymbolListEmpty(elems);
elems = PTPT_getSymbolListTail(elems)) {
PT_Symbol head = PTPT_lowerSymbol(PTPT_getSymbolListHead(elems));
list = PT_makeSymbolsMany(head, list);
if (!PTPT_hasSymbolListTail(elems)) {
break;
}
}
return PT_reverseSymbols(list);
}
/*}}} */
/*{{{ static PT_Attrs PTPT_lowerAttrs(PTPT_Attrs symbols) */
static PT_Attr PTPT_lowerAttr(PTPT_Attr attr);
static PT_Attrs PTPT_lowerAttrs(PTPT_Attrs attrs)
{
PTPT_AttrList list = PTPT_getAttrsList(attrs);
PT_Attrs result = NULL;
for (; PTPT_hasAttrListHead(list); list = PTPT_getAttrListTail(list)) {
PT_Attr head = PTPT_lowerAttr(PTPT_getAttrListHead(list));
if (result == NULL) {
result = PT_makeAttrsSingle(head);
}
else {
result = PT_makeAttrsMany(head, result);
}
if (!PTPT_hasAttrListTail(list)) {
break;
}
}
return PT_reverseAttrs(result);
}
/*}}} */
/*{{{ static PT_Symbol PTPT_lowerSymbol(PTPT_Symbol symbol) */
static PT_Symbol PTPT_lowerSymbol(PTPT_Symbol symbol)
{
PT_Symbol result = lookupSymbol(symbol);
if (result != NULL) {
return result;
}
if (PTPT_isSymbolLit(symbol)) {
AFun lit = PTPT_lowerStrCon(PTPT_getSymbolString(symbol));
result = PT_makeSymbolLit(ATgetName(lit));
}
else if (PTPT_isSymbolCilit(symbol)) {
AFun lit = PTPT_lowerStrCon(PTPT_getSymbolString(symbol));
result = PT_makeSymbolCilit(ATgetName(lit));
}
else if (PTPT_isSymbolCf(symbol)) {
PT_Symbol new = PTPT_lowerSymbol(PTPT_getSymbolSymbol(symbol));
result = PT_makeSymbolCf(new);
}
else if (PTPT_isSymbolLex(symbol)) {
PT_Symbol new = PTPT_lowerSymbol(PTPT_getSymbolSymbol(symbol));
result = PT_makeSymbolLex(new);
}
else if (PTPT_isSymbolEmpty(symbol)) {
result = PT_makeSymbolEmpty();
}
else if (PTPT_isSymbolSeq(symbol)) {
PT_Symbols syms = PTPT_lowerSymbols(PTPT_getSymbolSymbols(symbol));
result
= PT_makeSymbolSeq(syms);
}
else if (PTPT_isSymbolOpt(symbol)) {
PT_Symbol new = PTPT_lowerSymbol(PTPT_getSymbolSymbol(symbol));
result = PT_makeSymbolOpt(new);
}
else if (PTPT_isSymbolAlt(symbol)) {
PT_Symbol lhs = PTPT_lowerSymbol(PTPT_getSymbolLhs(symbol));
PT_Symbol rhs = PTPT_lowerSymbol(PTPT_getSymbolRhs(symbol));
result = PT_makeSymbolAlt(lhs, rhs);
}
else if (PTPT_isSymbolTuple(symbol)) {
PT_Symbol head = PTPT_lowerSymbol(PTPT_getSymbolHead(symbol));
PT_Symbols rest = PTPT_lowerSymbols(PTPT_getSymbolRest(symbol));
result = PT_makeSymbolTuple(head, rest);
}
else if (PTPT_isSymbolSort(symbol)) {
AFun lit = PTPT_lowerStrCon(PTPT_getSymbolString(symbol));
result = PT_makeSymbolSort(ATgetName(lit));
}
else if (PTPT_isSymbolIter(symbol)) {
PT_Symbol new = PTPT_lowerSymbol(PTPT_getSymbolSymbol(symbol));
result = PT_makeSymbolIterPlus(new);
}
else if (PTPT_isSymbolIterStar(symbol)) {
PT_Symbol new = PTPT_lowerSymbol(PTPT_getSymbolSymbol(symbol));
result = PT_makeSymbolIterStar(new);
}
else if (PTPT_isSymbolIterSep(symbol)) {
PT_Symbol sym = PTPT_lowerSymbol(PTPT_getSymbolSymbol(symbol));
PT_Symbol sep = PTPT_lowerSymbol(PTPT_getSymbolSeparator(symbol));
result = PT_makeSymbolIterPlusSep(sym, sep);
}
else if (PTPT_isSymbolIterStarSep(symbol)) {
PT_Symbol sym = PTPT_lowerSymbol(PTPT_getSymbolSymbol(symbol));
PT_Symbol sep = PTPT_lowerSymbol(PTPT_getSymbolSeparator(symbol));
result = PT_makeSymbolIterStarSep(sym, sep);
}
else if (PTPT_isSymbolIterN(symbol)) {
PT_Symbol sym = PTPT_lowerSymbol(PTPT_getSymbolSymbol(symbol));
int num = PTPT_lowerNatCon(PTPT_getSymbolNumber(symbol));
result = PT_makeSymbolIterN(sym, num);
}
else if (PTPT_isSymbolIterSepN(symbol)) {
PT_Symbol sym = PTPT_lowerSymbol(PTPT_getSymbolSymbol(symbol));
PT_Symbol sep = PTPT_lowerSymbol(PTPT_getSymbolSeparator(symbol));
int num = PTPT_lowerNatCon(PTPT_getSymbolNumber(symbol));
result = PT_makeSymbolIterSepN(sym, sep, num);
}
else if (PTPT_isSymbolFunc(symbol)) {
PT_Symbols syms = PTPT_lowerSymbols(PTPT_getSymbolSymbols(symbol));
PT_Symbol sym = PTPT_lowerSymbol(PTPT_getSymbolSymbol(symbol));
result = PT_makeSymbolFunc(syms, sym);
}
else if (PTPT_isSymbolParameterizedSort(symbol)) {
AFun lit = PTPT_lowerStrCon(PTPT_getSymbolSort(symbol));
PT_Symbols syms = PTPT_lowerSymbols(PTPT_getSymbolParameters(symbol));
result = PT_makeSymbolParameterizedSort(ATgetName(lit), syms);
}
else if (PTPT_isSymbolVarsym(symbol)) {
PT_Symbol new = PTPT_lowerSymbol(PTPT_getSymbolSymbol(symbol));
result = PT_makeSymbolVarSym(new);
}
else if (PTPT_isSymbolLayout(symbol)) {
result = PT_makeSymbolLayout();
}
else if (PTPT_isSymbolCharClass(symbol)) {
PT_CharRanges ranges =
PTPT_lowerCharRanges(PTPT_getSymbolCharRanges(symbol));
result = PT_makeSymbolCharClass(ranges);
}
else {
ATwarning("lower: unknown symbol %t\n", symbol);
assert(ATfalse);
}
return result;
}
/*}}} */
/*{{{ static PT_CharRange PTPT_lowerCharRange(PTPT_CharRange range) */
static PT_CharRange PTPT_lowerCharRange(PTPT_CharRange range)
{
PT_CharRange result = NULL;
if (PTPT_isCharRangeCharacter(range)) {
int nat = PTPT_lowerNatCon(PTPT_getCharRangeInteger(range));
result = PT_makeCharRangeCharacter(nat);
}
else if (PTPT_isCharRangeRange(range)) {
int start = PTPT_lowerNatCon(PTPT_getCharRangeStart(range));
int end = PTPT_lowerNatCon(PTPT_getCharRangeEnd(range));
result = PT_makeCharRangeRange(start, end);
}
else {
ATwarning("lower: unknown charrange %t\n", range);
assert(ATfalse);
}
return result;
}
/*}}} */
/*{{{ static PT_Associativity PTPT_lowerAssociativity(PTPT_Associativity assoc) */
static PT_Associativity PTPT_lowerAssociativity(PTPT_Associativity assoc)
{
PT_Associativity result = NULL;
if (PTPT_isAssociativityLeft(assoc)) {
result = PT_makeAssociativityLeft();
}
else if (PTPT_isAssociativityRight(assoc)) {
result = PT_makeAssociativityRight();
}
else if (PTPT_isAssociativityAssoc(assoc)) {
result = PT_makeAssociativityAssoc();
}
else if (PTPT_isAssociativityNonAssoc(assoc)) {
result = PT_makeAssociativityNonAssoc();
}
else {
ATwarning("lower: unknown associativity %t\n", assoc);
assert(ATfalse);
}
return result;
}
/*}}} */
/*{{{ static PT_Attr PTPT_lowerAttr(PTPT_Attr attr) */
static PT_Attr PTPT_lowerAttr(PTPT_Attr attr)
{
PT_Attr result = NULL;
if (PTPT_isAttrAssoc(attr)) {
PT_Associativity assoc =
PTPT_lowerAssociativity(PTPT_getAttrAssociativity(attr));
result = PT_makeAttrAssoc(assoc);
}
else if (PTPT_isAttrTerm(attr)) {
ATerm term = PTPT_lowerATerm(PTPT_getAttrAterm(attr));
result = PT_makeAttrTerm(term);
}
else if (PTPT_isAttrId(attr)) {
AFun id = PTPT_lowerStrCon(PTPT_getAttrModuleName(attr));
result = PT_makeAttrId(ATgetName(id));
}
else if (PTPT_isAttrBracket(attr)) {
result = PT_makeAttrBracket();
}
else if (PTPT_isAttrReject(attr)) {
result = PT_makeAttrReject();
}
else if (PTPT_isAttrPrefer(attr)) {
result = PT_makeAttrPrefer();
}
else if (PTPT_isAttrAvoid(attr)) {
result = PT_makeAttrAvoid();
}
else {
ATwarning("lower: unknown attr %t\n", attr);
assert(ATfalse);
}
return result;
}
/*}}} */
/*{{{ static PT_Attributes PTPT_lowerAttributes(PTPT_Attributes attributes) */
static PT_Attributes PTPT_lowerAttributes(PTPT_Attributes attributes)
{
PT_Attributes result = NULL;
if (PTPT_isAttributesNoAttrs(attributes)) {
result = PT_makeAttributesNoAttrs();
}
else if (PTPT_isAttributesAttrs(attributes)) {
PT_Attrs attrs =
PTPT_lowerAttrs(PTPT_getAttributesAttributes(attributes));
result = PT_makeAttributesAttrs(attrs);
}
else {
ATwarning("lower: unknown attributes: %t\n", attributes);
assert(ATfalse);
}
return result;
}
/*}}} */
/*{{{ static PT_Production PTPT_lowerProd(PTPT_Production prod) */
static PT_Production PTPT_lowerProd(PTPT_Production prod)
{
PT_Production result = NULL;
if (PTPT_isProductionDefault(prod)) {
PT_Symbols lhs;
PT_Symbol rhs;
PT_Attributes attrs;
lhs = PTPT_lowerSymbols(PTPT_getProductionLhs(prod));
rhs = PTPT_lowerSymbol(PTPT_getProductionRhs(prod));
attrs = PTPT_lowerAttributes(PTPT_getProductionAttributes(prod));
result = PT_makeProductionDefault(lhs, rhs, attrs);
}
else if (PTPT_isProductionList(prod)) {
PT_Symbol rhs = PTPT_lowerSymbol(PTPT_getProductionRhs(prod));
result = PT_makeProductionList(rhs);
}
else {
ATwarning("lower: unknown production %t\n", prod);
assert(ATfalse);
}
return result;
}
/*}}} */
PT_Tree PTPT_lowerTree(PTPT_Tree pt);
/*{{{ static PT_Args PTPT_lowerArgs(PTPT_Args args) */
static PT_Args PTPT_lowerArgs(PTPT_Args args)
{
PTPT_TreeList trees = PTPT_getArgsList(args);
PT_Args list = PT_makeArgsEmpty();
for (; !PTPT_isTreeListEmpty(trees); trees = PTPT_getTreeListTail(trees)) {
PT_Tree head = PTPT_lowerTree(PTPT_getTreeListHead(trees));
list = PT_makeArgsMany(head, list);
if (!PTPT_hasTreeListTail(trees)) {
break;
}
}
return PT_reverseArgs(list);
}
/*}}} */
/*{{{ PT_Tree PTPT_lowerTreeCache(PTPT_Tree pt, ATermTable myLowerCache) */
PT_Tree PTPT_lowerTreeCache(PTPT_Tree pt, ATermTable myLowerCache)
{
PT_Tree result = NULL;
lowerCache = myLowerCache;
result = PTPT_lowerTree(pt);
lowerCache = NULL;
return result;
}
/*}}} */
/*{{{ PT_Tree PTPT_lowerTree(PTPT_Tree pt) */
PT_Tree PTPT_lowerTree(PTPT_Tree pt)
{
PT_Tree result = lookupTree(pt);
PTPT_Annotation annos = NULL;
if (result != NULL) {
return result;
}
if (PTPT_isTreeAnnotated(pt)) {
annos = PTPT_getTreeAnnotation(pt);
pt = PTPT_getTreeTree(pt);
assert(!PTPT_isTreeAnnotated(pt)
&& "encountered an illegal nested annotation");
}
if (PTPT_isTreeAmb(pt)) {
PTPT_Args args = PTPT_getTreeArgs(pt);
result = PT_makeTreeAmb(PTPT_lowerArgs(args));
}
else if (PTPT_isTreeAppl(pt)) {
PT_Production prod;
PT_Args args;
prod = PTPT_lowerProd(PTPT_getTreeProd(pt));
args = PTPT_lowerArgs(PTPT_getTreeArgs(pt));
result = PT_makeTreeAppl(prod, args);
}
else if (PTPT_isTreeCycle(pt)) {
PT_Symbol symbol;
int length;
symbol = PTPT_lowerSymbol(PTPT_getTreeSymbol(pt));
length = PTPT_lowerNatCon(PTPT_getTreeLength(pt));
result = PT_makeTreeCycle(symbol,length);
}
else if (PTPT_isTreeChar(pt)) {
PTPT_NatCon val = PTPT_getTreeCharacter(pt);
result = PT_makeTreeChar(PTPT_lowerNatCon(val));
}
else {
ATwarning("lower: unknown term %t\n", pt);
/* In this case we leave the term as-is, which is important
* for bootstrapping purposes. When bootstrapping the ASF-Normalizer,
* we try to lower meta-level variables, which should be left alone.
*/
result = (PT_Tree) pt;
}
if (annos != NULL) {
ATermList atannos = PTPT_lowerAnn(annos);
result = PT_setTreeAnnotations(result, (ATerm) atannos);
}
return result;
}
/*}}} */
/*{{{ PT_ParseTree PTPT_lowerParseTree(PTPT_ParseTree pt) */
PT_ParseTree PTPT_lowerParseTree(PTPT_ParseTree pt)
{
PTPT_Tree tree = PTPT_getParseTreeTop(pt);
PTPT_NatCon ambCnt = PTPT_getParseTreeAmbCnt(pt);
return PT_makeParseTreeTop(PTPT_lowerTree(tree), PTPT_lowerNatCon(ambCnt));
}
/*}}} */
|
C
|
#include <stdlib.h>
#include <stdio.h>
#define SIZE 64
struct mnv{
int tnum;
int raz;
int dnum[SIZE];
};
int main(){
struct mnv num[SIZE];
int i=0, n=0, d=0, vnum;
while(d==0){
num[n].raz=0;
vnum=0;
scanf("%d", &vnum);
num[n].tnum=vnum;
if(vnum==-1){
d=1;
break;
}
while (vnum != 0){
i=num[n].raz;
if (vnum % 2 == 0){
num[n].dnum[i] = 0;
vnum /= 2;
}else{
num[n].dnum[i] = 1;
vnum /= 2;
}
num[n].raz++;
}
num[n].raz-= 1;
n++;
}
int k=0;
for(k;k<n;k++){
printf("%10d = ",num[k].tnum);
for(i=num[k].raz;i>=0;i--){
printf("%d",num[k].dnum[i]);
}
printf("\n");
}
return 0;
}
|
C
|
/*
* Note: git import taken from hellomain.c @ r1821.
*
* Based on Autotool Tutorial by Alexandre Duret-Lutz (updated: May 16, 2010)
*
* "Using GNU Autotools",
* by Alexandre Duret-Lutz
* http://www.lrde.epita.fr/~adl/autotools.html
*
* Tutorial examples based on:
* GNU Autoconf 2.65
* GNU Automake 1.11.1
* GNU Libtool 2.2.6b
* GNU Gettext 0.17
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv)
{
printf("Hello World\n");
printf("This is %s.\n", PACKAGE_STRING);
return (EXIT_SUCCESS);
}
|
C
|
/* author Sijun Li */
#include "pools.h"
void initQ(MqueueDef* const th,int size,uint8_t* data){
th->size = size;
th->data = data;
th->front = th->rear = 0;
}
void pushQ(MqueueDef* const th, uint8_t data){
th->data[th->rear++] = data;
if(th->rear >= th->size)th->rear = 0;
// Discards oldest data;
if(th->rear == th->front)th->front = (th->front+1)%th->size;
}
uint8_t popQ(MqueueDef* const th){
uint8_t rt = th->data[th->front++];
if(th->front >= th->size)th->front = 0;
return rt;
}
int emptyQ(MqueueDef* const th){
return (th->front == th->rear);
}
int sizeQ(MqueueDef* const th){
int tmp = th->rear - th->front;
if(tmp<0)tmp += th->size;
return tmp;
}
|
C
|
//
// Created by CalebBorwick on 2019-11-25.
//
#include "account.h"
#include <stdlib.h>
#include <stdio.h>
account *createAccount(char typ, int dep, int with, int transf, int transa, int transFee, int over, int bal){
account *new = (account *) malloc(sizeof(account));
new->type = typ;
new->deposit = dep;
new->withdraw=with;
new->transfer = transf;
new->transaction = transa;
new->transactionFee = transFee;
new->overdraft = over;
new->balance=bal;
return new;
}
char getType(account *a1){
return a1->type;
}
void setType(account *a1, char typ){
a1->type=typ;
}
int getDeposit(account *a1){
return a1->deposit;
}
void setDeposit(account *a1, int dep){
a1->deposit = dep;
}
int getWithdraw(account *a1) {
return a1->withdraw;
}
void setWithdraw(account *a1, int with){
a1->withdraw=with;
}
int getTransfer(account *a1){
return a1->transfer;
}
void setTransfer(account *a1, int tranf){
a1->transfer=tranf;
}
int getTransaction(account *a1){
return a1->transaction;
}
void setTransaction(account *a1,int transa){
a1->transaction=transa;
}
int getTransactionFee(account *a1){
return a1->transactionFee;
}
void setTransactionFee(account *a1,int fee){
a1->transactionFee=fee;
}
int getOverdraft(account *a1){
return a1->overdraft;
}
void setOverdraft(account *a1,int over){
a1->overdraft=over;
}
int getBalance(account *a1){
return a1->balance;
}
void setBalance(account *a1,int bal){
a1->balance=bal;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#define SIZE 2000000
float xsum(int l, int r, float* tab) {
if(l == r) return tab[l] * tab[l];
int half = (l + r) / 2;
return xsum(l, half, tab) + xsum(half+1, r, tab);
}
int main() {
float e = 1.0 / SIZE;
float * tab = malloc(SIZE * sizeof(float));
int i;
for(i = 0; i < SIZE; i++)
tab[i] = e;
float sum = xsum(0, SIZE, tab);
printf("Liczba początkowa e:\t\t%.48f\nSuma kwadratów liczb z tabeli:\t%.48f\nRóżnica: %.48f\n", e, sum, e-sum);
free(tab);
}
|
C
|
// gcc -o irm1 irm1.c -l bcm2835 -l lirc_client
// sudo ./irm1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <bcm2835.h>
#include <lirc/lirc_client.h>
// LED3 je na DVK512 pločici na P28 što je pin 20 na BCM-u,
// ako se koristi protobord može se
// koristiti isti ovaj pin ili neki drugi
#define PIN 20
int main(int argc, char **argv)
{
struct lirc_config *config;
char *code;
//startuj lirc
if(lirc_init("lirc",1)==-1)
return 1;
if (!bcm2835_init())
return 2;
// Setuj PIN kao izlazni
bcm2835_gpio_fsel(PIN, BCM2835_GPIO_FSEL_OUTP);
//procitaj /etc/lirc/lirc/lircrc/lircd.conf
if(lirc_readconfig(NULL, &config,NULL)==0)
{
//radimo dok je LIRC soket otvoren 0=otvoren -1=zatvoren
while (lirc_nextcode(&code)==0)
{
// if code=NULL ništa nije primljeno-preskoči
if(code==NULL) continue; {
bcm2835_delay(400);
if (strstr(code,"KEY_0")){
printf("KEY0\n");
// iskljuci
bcm2835_gpio_write(PIN, LOW);
bcm2835_delay(500);
}
else if (strstr(code,"KEY_1")){
printf("KEY1\n");
// ukljuci
bcm2835_gpio_write(PIN, HIGH);
bcm2835_delay(500);
}
}
free(code);
}
lirc_freeconfig(config);
}
lirc_deinit();
bcm2835_close();
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int size = 1;
char* fileName;
void* buffer;
FILE* file = NULL;
int bufferLocation = 2;
struct fun {
char *name;
void (*fun)(char *filename, int size, void *mem_buffer);
};
void quit(char *filename, int size, void *mem_buffer) {
fclose(file);
printf("Quit...\n");
exit(0);
}
void memDisplay(char *filename, int size, void *mem_buffer) {
printf("Please enter <address> <length>\n");
char input[20];
fgets(input, 20, stdin);
unsigned char* buf = mem_buffer;
unsigned int offset = 0;
int length;
if (sscanf(input, "%X %d", &offset, &length) != 2) {
printf("Error: wrong format...\n");
}
buf += offset;
while (length > 0) {
int i;
for (i = 0; i < size; i++) {
printf("%02X", *buf++);
}
printf(" ");
length--;
}
printf("\n");
}
void loadToMem(char *filename, int size, void *mem_buffer) {
printf("Please enter <mem-address> <source-file> <location> <length>\n");
char input[20];
fgets(input, 20, stdin);
unsigned int memoryAddress = 0;
char* inputFile = 0;
unsigned int offset;
unsigned int length;
if (sscanf(input, "%X %s %X %d",&memoryAddress, inputFile, &offset, &length) != 4) {
printf("Error: wrong format...\n");
}
FILE* inFile = fopen(fileName, "r+");
printf("Loaded %d units into %p\n", length, memoryAddress);
}
void saveToMem(char *filename, int size, void *mem_buffer) {
exit(0);
}
struct fun menu[] = { {"Mem Display", memDisplay},
{"Load Into Memory", loadToMem},
{"Save Into Memory", saveToMem},
{"Quit", quit}
};
/* ---------------------------------------------------*/
void showMenu() {
printf("\e[2J\e[H"); /*clean the screen*/
printf("\n\n ------------------------------------------------------------------ \n");
printf(" ****Hexedit Plus ****\n");
printf(" ------------------------------------------------------------------ \n\n");
printf("File: %s, buffer location: %p, choose action:\n", fileName, buffer);
/*iteratively print the menu:*/
int sz = sizeof(menu) / sizeof(menu[0]);
int i = 0;
for (i = 0; i < sz; i++)
printf("%d-%s\n", i + 1, menu[i].name);
}
int main (int argc , char* argv[], char* envp[]) {
/*------------- get args: -----------------*/
if (argc == 1) {
printf("Error: No filename received!\n");
exit(1);
}
fileName = argv[1];
if (argc == 3) {
size = atoi(argv[2]);
printf("Size: %d\n", size);
if (!(size == 1 || size == 2 || size == 4)) {
printf("Invalid size!\n");
exit(1);
}
}
/*-----------------------------------------------*/
file = fopen(fileName, "r+");
if (file == NULL) {
printf("Error Opening the file!\n");
exit(1);
}
buffer = (void*)malloc(1024 * 4);
showMenu();
int choice;
scanf("%d%*c", &choice);
choice--;
menu[choice].fun(fileName, size, &buffer);
/*free buffer*/
free(buffer);
/************/
if (file != NULL)
fclose(file);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "intsort.h"
int main(int argc, char *argv[]){
if (argc != 2) {
printf("Expected 2 args, got %d", argc);
}
/* Open the file.*/
FILE *file = fopen(argv[1], "r");
if (!file) {
exit(EXIT_FAILURE);
}
/* Read, sort, and print lines.*/
char *line = NULL;
size_t len = 0;
while (getline(&line, &len, file) != NO_MORE_LINES) {
print_sorted_line(line);
busy_wait();
}
/* Clean up after ourselves.*/
if (line) {
free(line);
}
fclose(file);
exit(EXIT_SUCCESS);
}
void print_sorted_line(char *line) {
static int64 buf[MAX_LINE];
size_t len = parse_int_line(line, buf, MAX_LINE);
recursive_bubble_sort(buf, len);
for (size_t i = 0; i < len; ++i) {
printf("%lld ", buf[i]);
}
putchar('\n');
}
size_t parse_int_line(char *line, int64 *buf, size_t maxsize) {
int64 parsed;
char *prev;
size_t n = 0;
while (*line != '\0') {
if (n >= maxsize){
puts("Integer line too long!");
exit(EXIT_FAILURE);
}
prev = line;
parsed = strtoll(line, &line, 10);
if (!parsed && prev == line) {
break;
}
buf[n] = parsed;
++n;
}
return n;
}
void swap(int64 *a, int64 *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
void recursive_bubble_sort(int64 *arr, int len){
if (len < 2) {
return;
}
for (int i = 0; i + 1 < len; ++i) {
if (arr[i] > arr[i + 1]) {
swap(arr + i, arr + i + 1);
}
}
recursive_bubble_sort(arr, len - 1);
}
volatile int x = 0;
void busy_wait(){
for (int i=0; i < 90000000; ++i){
if (x) {
printf("Someone changed x %d", x);
}
}
}
|
C
|
// This program simulates the flow of heat through a two-dimensional plate.
// The number of grid cells used to model the plate as well as the number of
// iterations to simulate can be specified on the command-line as follows:
// ./heated_plate_sequential <columns> <rows> <iterations>
// For example, to execute with a 500 x 500 grid for 250 iterations, use:
// ./heated_plate_sequential 500 500 250
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <numa.h>
#include <utmpx.h>
#include <sched.h>
// Define the immutable boundary conditions and the inital cell value
#define TOP_BOUNDARY_VALUE 0.0
#define BOTTOM_BOUNDARY_VALUE 100.0
#define LEFT_BOUNDARY_VALUE 0.0
#define RIGHT_BOUNDARY_VALUE 100.0
#define INITIAL_CELL_VALUE 50.0
#define hotSpotRow 4500
#define hotSptCol 6500
#define hotSpotTemp 1000
#define ncols 10000
#define nrows 10000
// Function prototypes
void print_cells(float **cells, int n_x, int n_y);
void initialize_cells(float **cells, int n_x, int n_y);
void create_snapshot(float **cells, int n_x, int n_y, int id, int tc);
float **allocate_cells(int n_x, int n_y);
void die(const char *error);
void *halo(void* a);
typedef struct arg {
int tnum;
float ***cells;
int iterations;
int thread_count;
int iters_per_snap;
} t_arg;
pthread_barrier_t barr;
int main(int argc, char **argv) {
// Record the start time of the program
time_t start_time = time(NULL);
// Extract the input parameters from the command line arguments
// Number of columns in the grid (default = 1,000)
// int num_cols = (argc > 1) ? atoi(argv[1]) : 1000;
// // Number of rows in the grid (default = 1,000)
// int num_rows = (argc > 2) ? atoi(argv[2]) : 1000;
// // Number of iterations to simulate (default = 100)
// int iterations = (argc > 3) ? atoi(argv[3]) : 100;
//number of chunks in x dimension
int thread_count = (argc > 1) ? atoi(argv[1]) : 1;
int iters_per_snap = (argc > 2) ? atoi(argv[2]) : 5000;
// Number of iterations to simulate (default = 100)
int iterations = (argc > 3) ? atoi(argv[3]) : 1000;
float **cells[2];
cells[0] = (float **) malloc((nrows+2)*sizeof(float*));
cells[1] = (float **) malloc((nrows+2)*sizeof(float*));
//set up threads, attrs and the barrier we will need
pthread_t tids[thread_count];
t_arg args[thread_count];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_barrier_init(&barr, NULL, thread_count);
int i;
cpu_set_t cpuset;
//makes the first pthread in tids the main process so that it can be included in the overall count
//I made the thread executing the main method also call halo because I thought pthread_join was implemented
//by basically a loop that continually tested for completion of the other threads, and therefore thought that when creating
//64 threads on 64 cores, the creating thread would be a 65th thread that would take up time-slices on one of the processors
//delaying the thread computing on that core. I now know it suspends execution, but live and learn. This way works too.
tids[0] = pthread_self();
for(i=1; i < thread_count; i++){
args[i].tnum = i;
args[i].cells = cells;
args[i].iterations = iterations;
args[i].thread_count = thread_count;
args[i].iters_per_snap = iters_per_snap;
//create the threads.
pthread_create(&tids[i], &attr, halo, &args[i]);
//set the affinity of the thread to the core numbered the same as the thread.
CPU_ZERO(&cpuset);
CPU_SET(i, &cpuset);
pthread_setaffinity_np(tids[i], sizeof(cpu_set_t), &cpuset);
}
//setting up args for thread 0 as well
args[0].tnum = 0;
args[0].cells = cells;
args[0].iterations = iterations;
args[0].thread_count = thread_count;
args[0].iters_per_snap = iters_per_snap;
printf("threads: %d\n",thread_count);fflush(stdout);
//the mmain funciton calls halo with the correct args.
halo(&args[0]);
//start at one because we know proc 0 has returned from halo if it has reached this point. Join the other threads.
for(i=1; i < thread_count; i++){
pthread_join(tids[i], NULL);
}
// Compute and output the execution time
time_t end_time = time(NULL);
printf("\nExecution time: %d seconds\n", (int) difftime(end_time, start_time));
fflush(stdout);
free(cells[0]); free(cells[1]);
//exit pthreads
pthread_exit(NULL);
}
void *halo(void *a){
t_arg *arg = (t_arg*) a;
int id = arg->tnum;
int iterations = arg->iterations;
float ***cells = arg->cells;
int thread_count = arg->thread_count;
int i, x, y;
int num_cols = ncols;
int num_rows = nrows;
//set the affinity for the main process (thread 0)
if(id == 0){
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(0, &cpuset);
sched_setaffinity(0, sizeof(cpu_set_t), &cpuset);
}
//wait until all threads are on the core they will be pinned to to proceed with allocation of data
//need to do this because the affinity is set after the thread starts, have to wait for them to switch to the right core
while(1){
if(sched_getcpu() == id){
pthread_barrier_wait(&barr);
break;
}
}
if (id == 0){
// Output the simulation parameters
printf("Grid: %dx%d, Iterations: %d\n", num_cols, num_rows, iterations);
fflush(stdout);
}
int rows_each = num_rows / thread_count;
int offsets[thread_count];
offsets[0] = 1; //1 to account for boundary along the top
for(i = 1; i <= thread_count; i++){
//creates a list of the row offsets from 0 of the start point of each of the threads responsibility.
//last element is the boundary row at the bottom, so all access loops can go offsets[id] <= i < offsets[id+1]
//ternary operator tests whether to add one to account for a matrix size not perfectly divisible by the thread count (threads at the beginning have one more row than threads at the end)
offsets[i] = offsets[i-1] + rows_each + (((i-1) < (num_rows % thread_count)) ? 1 : 0);
}
//store these in variables so I don't spend time in array lookups in the loop bodies later
int rowStart = offsets[id];
int rowEnd = offsets[id+1];
//allocate each row the processor is responsible for locally to it
//since this takes place after we make sure every process is on the core it will be pinned
//to for the whole process, we know that memory allocated locally here will stay local to that process.
if(id == 0) {
cells[0][0] = (float *)numa_alloc_local((num_cols+2) * sizeof(float));
cells[1][0] = (float *)numa_alloc_local((num_cols+2) * sizeof(float));
}
if (id == thread_count - 1){
cells[0][num_rows + 1] = (float *)numa_alloc_local((num_cols+2) * sizeof(float));
cells[1][num_rows + 1] = (float *)numa_alloc_local((num_cols+2) * sizeof(float));
}
for(i = rowStart; i < rowEnd; i++){
cells[0][i] = (float *)numa_alloc_local((num_cols+2) * sizeof(float));
cells[1][i] = (float *)numa_alloc_local((num_cols+2)* sizeof(float));
}
//initialize the non-boundary cells
for(y = rowStart; y < rowEnd; y++){
for(x=1; x < num_cols + 1; x++){
cells[0][y][x] = INITIAL_CELL_VALUE;
}
}
//initialize boundary conditions
for(y = rowStart; y < rowEnd; y++){
cells[0][y][0] = cells[1][y][0] = LEFT_BOUNDARY_VALUE;
cells[0][y][num_cols+1] = cells[1][y][num_cols+1] = RIGHT_BOUNDARY_VALUE;
}
if(id==0){
for(x=0; x < num_cols + 2; x++) cells[0][0][x] = cells[1][0][x] = TOP_BOUNDARY_VALUE;
}
if(id == thread_count -1){
for(x=0; x < num_cols + 2; x++) cells[0][num_rows + 1][x] = cells[1][num_rows + 1][x] = BOTTOM_BOUNDARY_VALUE;
}
//barrier so that no threads start until the whole array is allocated
pthread_barrier_wait(&barr);
int cur_cells_index = 0, next_cells_index = 1;
for (i = 0; i < iterations; i++){
for(y = rowStart; y < rowEnd; y++){
for (x = 1; x < num_cols + 1; x++){
// The new value of this cell is the average of the old values of this cell's four neighbors
cells[next_cells_index][y][x] = (cells[cur_cells_index][y][x - 1] +
cells[cur_cells_index][y][x + 1] +
cells[cur_cells_index][y - 1][x] +
cells[cur_cells_index][y + 1][x]) * 0.25;
}
}
// Print the current progress every time you iterate
//took this out to speed things up but mostly cause it's annoying when I'm not testing
// if(id==0){
// printf("Iteration: %d / %d\n", i + 1, iterations);
// fflush(stdout);
// }
//switch the arrays
cur_cells_index = next_cells_index;
next_cells_index = !cur_cells_index;
//sets the hotspot temp with the thread that is responsible for it, and therefore local to it
if(rowStart <= hotSpotRow && rowEnd > hotSpotRow && num_cols >= hotSptCol) {
cells[cur_cells_index][hotSpotRow][hotSptCol] = hotSpotTemp;
}
//only thread 0 calls create snapshot, then that thread accesses the whole array, including non-local portions, and compiles the snap
//not that costly cause in benchmarking runs I only do it once in the whole program
if ((i+1) % arg->iters_per_snap == 0 && id == 0){
int final_cells = (iterations % 2 == 0) ? 0 : 1;
create_snapshot(cells[final_cells], num_cols, num_rows, i+1, thread_count);
}
//wait until all threads have finished the iteration to proceed to the next one
pthread_barrier_wait(&barr);
}
//free each row by the processor that is responsible/local for it
if(id == 0) {
numa_free(cells[0][0],(num_cols+2) * sizeof(float));
numa_free(cells[1][0],(num_cols+2) * sizeof(float));
}
if (id == thread_count - 1){
numa_free(cells[0][num_rows + 1],(num_cols+2) * sizeof(float));
numa_free(cells[1][num_rows + 1],(num_cols+2) * sizeof(float));
}
for(i = rowStart; i < rowEnd; i++){
numa_free(cells[0][i],(num_cols+2) * sizeof(float));
numa_free(cells[1][i],(num_cols+2) * sizeof(float));
}
}
// Allocates and returns a pointer to a 2D array of floats
float **allocate_cells(int cols, int rows) {
float **array = (float **) malloc(rows * sizeof(float *));
if (array == NULL) die("Error allocating array!\n");
array[0] = (float *) malloc(rows * cols * sizeof(float));
if (array[0] == NULL) die("Error allocating array!\n");
int i;
for (i = 1; i < rows; i++) {
array[i] = array[0] + (i * cols);
}
return array;
}
// Sets all of the specified cells to their initial value.
// Assumes the existence of a one-cell thick boundary layer.
void initialize_cells(float **cells, int num_cols, int num_rows) {
int x, y;
for (y = 1; y <= num_rows; y++) {
for (x = 1; x <= num_cols; x++) {
cells[y][x] = INITIAL_CELL_VALUE;
}
}
}
// Creates a snapshot of the current state of the cells in PPM format.
// The plate is scaled down so the image is at most 1,000 x 1,000 pixels.
// This function assumes the existence of a boundary layer, which is not
// included in the snapshot (i.e., it assumes that valid array indices
// are [1..num_rows][1..num_cols]).
void create_snapshot(float **cells, int cols, int rows, int id, int thread_count) {
int scale_x, scale_y;
scale_x = scale_y = 1;
// Figure out if we need to scale down the snapshot (to 1,000 x 1,000)
// and, if so, how much to scale down
if (cols > 1000) {
if ((cols % 1000) == 0) scale_x = cols / 1000;
else {
die("Cannot create snapshot for x-dimensions >1,000 that are not multiples of 1,000!\n");
return;
}
}
if (rows > 1000) {
if ((rows % 1000) == 0) scale_y = rows / 1000;
else {
printf("Cannot create snapshot for y-dimensions >1,000 that are not multiples of 1,000!\n");
return;
}
}
// Open/create the file
char text[255];
sprintf(text, "snapshot.tc%d.%d.ppm",thread_count, id);
FILE *out = fopen(text, "w");
// Make sure the file was created
if (out == NULL) {
printf("Error creating snapshot file!\n");
return;
}
// Write header information to file
// P3 = RGB values in decimal (P6 = RGB values in binary)
fprintf(out, "P3 %d %d 100\n", cols / scale_x, rows / scale_y);
// Precompute the value needed to scale down the cells
float inverse_cells_per_pixel = 1.0 / ((float) scale_x * scale_y);
// Write the values of the cells to the file
int x, y, i, j;
for (y = 1; y <= rows; y += scale_y) {
for (x = 1; x <= cols; x += scale_x) {
float sum = 0.0;
for (j = y; j < y + scale_y; j++) {
for (i = x; i < x + scale_x; i++) {
sum += cells[j][i];
}
}
// Write out the average value of the cells we just visited
int average = (int) (sum * inverse_cells_per_pixel);
if (average > 100)
average = 100;
fprintf(out, "%d 0 %d\t", average, 100 - average);
}
fwrite("\n", sizeof(char), 1, out);
}
// Close the file
fclose(out);
}
// Prints the specified error message and then exits
void die(const char *error) {
printf("%s", error);
exit(1);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* operations.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: slight <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/18 16:38:36 by slight #+# #+# */
/* Updated: 2021/08/18 16:43:15 by slight ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_opers.h"
int plus(int num1, int num2, int *succees)
{
int res;
res = num1 + num2;
*succees = 1;
return (res);
}
int minus(int num1, int num2, int *succees)
{
int res;
res = num1 - num2;
*succees = 1;
return (res);
}
int multiplication(int num1, int num2, int *succees)
{
int res;
res = num1 * num2;
*succees = 1;
return (res);
}
int devision(int num1, int num2, int *succees)
{
int res;
if (num2 == 0)
{
write(2, "Stop : division by zero\n", 24);
*succees = 0;
return (0);
}
res = num1 / num2;
*succees = 1;
return (res);
}
int modulo(int num1, int num2, int *succees)
{
int res;
if (num2 == 0)
{
write(2, "Stop : modulo by zero\n", 22);
*succees = 0;
return (0);
}
res = num1 % num2;
*succees = 1;
return (res);
}
|
C
|
/*
* command.h
*/
#include <stdint.h>
#include <stdio.h>
#ifndef HASHTABLE_COMMAND_H
#define HASHTABLE_COMMAND_H
/**
* A command type.
*/
typedef enum command_type {
UNKNOWN = 0,
INSERT = 1,
DELETE = 2,
FIND = 3,
LIST = 4
} command_type_t;
/**
* A command.
*/
typedef struct command {
// the command type
command_type_t type;
// the command arg
char * arg;
} command_t;
/**
* Pointer to a command.
*/
typedef command_t * command_ptr;
/**
* Read a command.
* @param input the file to read the input from
* @param command pointer where to place the command
* @return 0 on success, 1 otherwise
*/
uint8_t command_read(FILE * input, command_ptr command);
#endif //HASHTABLE_COMMAND_H
|
C
|
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dlfcn.h>
#include "mm.h"
#include "memlib.h"
#ifdef DRIVER
#define malloc mm_malloc
#define free mm_free
#define realloc mm_realloc
#define calloc mm_calloc
#endif
#define WSIZE 4
#define OVERHEAD 8
#define DSIZE 8
#define PACK(size,alloc) ((size)|(alloc))
#define GET(p) (*(size_t *)(p))
#define PUT(p, val) (*(size_t *)(p) = (val))
#define GET_SIZE(p) (GET(p) & ~0x7)
#define GET_ALLOC(p) (GET(p) & 0x1)
#define HDRP(bp) ((char *)(bp) - WSIZE)
#define FTRP(bp) ((char *)(bp) + GET_SIZE(HDRP(bp)) - DSIZE)
#define FLSB(bp) ((char *)(bp) )
#define FLPB(bp) ((char *)(bp) + WSIZE)
#define NEXT_BLKP(bp) ((char *)(bp) + GET_SIZE(((char *)(bp) - WSIZE)))
#define PREV_BLKP(bp) ((char *)(bp) - GET_SIZE(((char *)(bp) - DSIZE)))
#define AD(bp) ( ( (char*)bp - start)/8)
void extend(size _t asize);
void place(void *bp,size_t asize);
void *malloc(size_t size);
static void find_fit(size_t asize);
static void merge(void *bp , size_t size, int state);
static void free(void *bp);
static void merge_case(void *bp,int state);
void *init; //list
void *last; //last
void *start;
int free_count;
//Init
int mm_init(void)
{
start = mem_sbrk(0);
free_count = 0;
init = NULL;
bp = mem_sbrk(DSIZE*4);
PUT(HDRP(bp),PACK(DSIZE*2,1));
PUT(FTRP(bp),PACK(DSIZE*2,1));
bp = NEXT_BLKP(bp);
last = bp;
PUT(HDRP(bp),PACK(DSIZE*2,1));
PUT(FTRP(bp),PACK(DSIZE*2,1));
}
void *malloc(size_t size)
{
while(1)
{
if( free_count ) //exist
{
if ( bp = find_fit(asize) )
return place(bp,asize);
else
extend(asize);
}
else
extend(asize);
}
}
void find_fit(size_t asize)
{
void *bp;
for ( bp = init ; bp != NULL ; bp = GET(FLSB(bp))) )
{
if ( GET_SIZE(HDRP(bp)) >= asize)
return bp;
}
return NULL;
}
void place(void *bp,size_t asize)
{
void *p = GET(FLPB(bp)); //preview free_block
void *n = GET(FLSB(bp)); //next free_block
PUT(HDRP(bp),PACK(asize,0));
PUT(FTRP(bp),PACK(asize,0));
bp = NEXT_BLKP(bp); //split block
if ( p == &prev)
{
PUT(FLSB(bp),prev);
PUT(FLPB(bp),&prev);
prev = bp;
}
else
{
PUT(FLSB(bp),n);
PUT(FLPB(bp),p);
PUT(FLSB(p),bp);
}
if ( n == NULL )
PUT(FLSB(bp),NULL);
else
PUT(FLPB(n),bp);
}
void extend(size _t asize)
{
void *cp;
bp = mem_sbrk(asize);
PUT(HDRP(bp-DSIZE),PACK(asize-DSIZE*2,0));
PUT(FTRP(bp-DSIZE),PACK(asize-DSIZE*2,0));
cp = PREV_BLKP(bp-DSIZE);
bp = NEXT_BLKP(bp-DSIZE);
PUT(HDRP(bp),PACK(DSIZE*2,1)); //dumy block
PUT(FTRP(bp),PACK(DSIZE*2,1)); //dumy block
if ( GET_ALLOC(HDRP(cp)) )
merge(bp,asize,1); //AXA
else
merge(bp,asize,3); //FXA
}
void *realloc(void *oldptr, size_t size)
(
size_t oldsize=GET_SIZE(HDRP(oldptr));
void *newptr;
if ( size <= 0 )
{
free(oldptr);
return 0;
}
if ( oldptr == NULL)
return malloc(size);
if (size == oldsize)
return oldptr;
newptr = malloc(size);
if( size < oldsize)
oldsize = size;
memcpy(newptr,oldptr,oldsize);
free(oldptr);
return newptr;
}
void *calloc(size_t nmemb, size_t size)
{
return NULL;
}
void free(void *bp)
{
void *prev = PREV_BLKP(bp); //prev block
void *next = NEXT_BLKP(bp); //next block
int next_alloc_state = GET_ALLOC(HDRP(next)); //decide block state
int prev_alloc_state = GET_ALLOC(HDRP(prev)); //decide block state
int size = GET_SIZE(HDRP(bp)));
if ( prev_alloc_state && next_alloc_state )
{
merge(bp,size,1);
return ;
}
else if ( prev_alloc_state && !next_alloc_state)
{
merge(bp,size,2);
return ;
}
else if ( !prev_alloc_state && next_alloc_state)
{
merge(bp,size,3);
return ;
}
else if ( !prev_alloc_state && !next_alloc_state)
{
merge(bp,size,4);
return ;
}
}
void merge(void *bp , size_t size, int state)
{
// void *prev_block = PREV_BLKP(bp);
// void *next_block = NEXT_BLKP(bp);
switch (state) //X means current blcok
{
case 1: //AXA
{
PUT(HDRP(bp),PACK(size,0));
PUT(FTRP(bp),PACK(size,0));
merge_case(bp,1);
return;
}
case 2: //AXF
{
PUT(HDRP(bp),PACK(size,0));
PUT(FTRP(bp),PACK(size,0));
merge_case(bp,2);
return ;
}
case 3: //FXA
{
PUT(HDRP(bp),PACK(size,0));
PUT(FTRP(bp),PACK(size,0));
merge_case(bp,3);
return ;
}
case 4: //FXF
{
PUT(HDRP(bp),PACK(size,0));
PUT(FTRP(bp),PACK(size,0));
merge_case(bp,4);
return ;
}
}
}
static void merge_case(void *current_block,int state)
{
void *prev_block = PREV_BLKP(current_block);
void *next_block = NEXT_BLKP(current_block);
int prev_size = GET_SIZE(HDRP(prev_block));
int next_size = GET_SIZE(HDRP(next_block));
int current_size = GET_SIZE(HDRP(current_block));
switch ( state )
{
case 1://AXA
{
PUT(FLPB(current_block),&init);
PUT(FLSB(current_block),init);
if ( free_count )
PUT(FLPB(GET(init)),current_block);
init = current_block;
return ;
}
case 2://AXF
{
PUT(HDRP(current_block),PACK(next_size+current_size,0));
PUT(FTRP(next_block),PACK(next_size+current_size,0));
return ;
}
case 3://FXA
{
PUT(HDRP(prev_block),PACK(prev_size+current_size,0));
PUT(FTRP(current_block),PACK(prev_size+current_size,0));
return ;
}
case 4://FXF
{
PUT(HDRP(prev_block),PACK(prev_size+current_size+next_size,0));
PUT(FTRP(next_block),PACK(prev_size+current_size+next_size,0));
return ;
}
}
}
|
C
|
/*
* xyprintf.h
*
* Created on: Oct 30, 2010
* Author: hammer
*/
#ifndef XYPRINTF_H_
#define XYPRINTF_H_
typedef struct __windowDef {
int x;
int y;
int width;
int height;
} windowDef;
void clearScreen(void);
#define BOLD 1
#define INV 2
#define UNDER 4
/**
* This method prints a formatted string
* \param x The column to print at
* \param y The row to print at
* \param fontFlags The font
* \param format The usual printf - format string
*/
void xyprintf(int x, int y, int fontFlags, char * format, ...);
/**
* This method positions the cursor at the position (x, y) relative to
* the 'window'
*/
void cursorTo(windowDef window, int x, int y);
/**
* This method sets the upper left corner for the subsequent xyprinting and the max length of the
* printed line. Printed lines shorter than 'width' are extended using white space (in the current line
* font)
* Note that a border is painted just outside the window; the caller should take this into consideration
* when allocating the window sizes.
* \param window The current window dimension
*/
void xySetWindow(windowDef window);
/**
* This method blocks until a key is pressed on the keyboard
* \return The value of the pressed key
*/
int getch(void);
/**
* This method initialize the printing stuff
*/
void xyinit(void);
/**
* This method flushes all printing to the console.
*/
void xyflush(void);
#endif /* XYPRINTF_H_ */
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* biggest_pal.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: exam <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/01 12:04:29 by exam #+# #+# */
/* Updated: 2020/02/02 12:17:04 by rjeraldi ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
int ft_strlen(char *str)
{
int strlen;
strlen = 0;
while (*(str + strlen) != '\0')
strlen++;
return (strlen);
}
int isnext(char *str, int start)
{
int i;
int strlen;
strlen = ft_strlen(str);
i = strlen - 1;
while (i > start)
if (str[start] == str[i--])
return (i + 1);
return (0);
}
int getpal(char *str, int i, int j, int pallen)
{
int k;
k = 0;
while (j - k > i + k)
{
if (str[i + k] == str[j - k])
k++;
else
{
k = 0;
j--;
}
}
if (k > 0 && str[i + k] == str[j - k])
{
if (j - i + 1 >= pallen)
return (j - i + 1);
}
return (0);
}
int main(int argc, char **argv)
{
int i;
int j;
int strlen;
int pallen;
int palstart;
if (argc == 2 && !(pallen = 0))
{
if ((strlen = ft_strlen(argv[1])))
ft_putchar(argv[1][0]);
i = 0;
while (i < strlen - 1 && pallen < strlen - i + 1)
{
if ((j = isnext(argv[1], i)))
{
if (getpal(argv[1], i, j, pallen) >= pallen && (palstart = i))
pallen = getpal(argv[1], i, j, pallen);
}
i++;
}
if (pallen > 0)
write(1, argv[1] + palstart, pallen);
}
ft_putchar('\n');
return (0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* format_handler.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akhalid <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/04 05:26:19 by akhalid #+# #+# */
/* Updated: 2020/01/04 07:18:10 by akhalid ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
void format_handler(char *f, int *i, t_args *args, va_list pa)
{
*i += 1;
while (f[*i] && (f[*i] == '.' || f[*i] == '-' || f[*i] == '0' ||
f[*i] == '*' || (f[*i] >= '0' && f[*i] <= '9')))
{
check_flag(f, i, args);
check_width(f, i, args, pa);
check_precision(f, i, args, pa);
}
conversion(f[*i], args);
}
void check_flag(char *f, int *i, t_args *args)
{
while (f[*i] && (f[*i] == '0' || f[*i] == '-'))
{
if (f[*i] == '-')
{
MINUS = 1;
ZERO = 0;
}
if (f[*i] == '0' && MINUS == 0)
ZERO = 1;
*i += 1;
}
}
void check_width(char *f, int *i, t_args *args, va_list pa)
{
while (f[*i] && (f[*i] == '*' || (f[*i] >= '0' && f[*i] <= '9')))
{
if (f[*i] == '*')
{
WIDTH = va_arg(pa, int);
*i += 1;
}
else
while (f[*i] >= '0' && f[*i] <= '9')
{
WIDTH = WIDTH * 10 + f[*i] - '0';
*i += 1;
}
}
}
void check_precision(char *f, int *i, t_args *args, va_list pa)
{
char *ptr;
ptr = f;
PRECISION = 0;
if (f[*i] != '.')
return ;
*i += 1;
IFPREC = 1;
while (f[*i] && (f[*i] == '-' || f[*i] == '*'
|| (f[*i] >= '0' && f[*i] <= '9')))
{
if (f[*i] == '*')
{
STAR = 1;
PRECISION = va_arg(pa, int);
*i += 1;
}
else
{
ptr += *i;
PRECISION = ft_atoi(ptr);
while ((f[*i] != '\0' && f[*i] > 47 && f[*i] < 58) || f[*i] == '-')
*i += 1;
}
}
}
void conversion(char conv, t_args *args)
{
if (conv == 'd' || conv == 's' || conv == 'p' || conv == 'i' || conv == 'u'
|| conv == 'X' || conv == 'x' || conv == 'c' || conv == '%')
CONV = conv;
else
CONV = -1;
}
|
C
|
/*
** my_explode.c for MySlack in /home/nomad/mySlack/client
**
** Made by BARREAU Martin
** Login <[email protected]>
**
** Started on Sun Feb 18 22:34:57 2018 BARREAU Martin
** Last update Sun Feb 18 22:35:32 2018 BARREAU Martin
*/
#include <libmy.h>
#include <stdlib.h>
char **my_explode(char *str, char del)
{
int len;
int i;
int j;
int k;
char tmp;
char **res;
i = j = k = 0;
len = my_strlen(str);
tmp = 0x0;
res = 0x0;
res = (char **) realloc(res, sizeof(char **));
res[0] = (char *) malloc(len * sizeof(char));
while (i < len + 1)
{
tmp = str[i++];
if (tmp == del || tmp == 0x0)
{
res[j][k] = 0x0;
res[j] = (char *) realloc(res[j], k * sizeof(char));
k = 0;
res = (char **) realloc(res, (++j + 1) * sizeof(char **));
res[j] = (char *) malloc(len * sizeof(char));
}
else
res[j][k++] = tmp;
}
res[j] = 0x0;
return (res);
}
|
C
|
/* This set of routines handles the basic terminal IO on a NeXT
* system. These routines are all designed to be called from
* Fortran. Thus ttinit can be called using the Fortran line
* CALL TTINIT()
*/
#include <sys/ioctl.h>
#include <stdio.h>
static struct sgttyb term, saveterm;
ttinit_()
/* Sets the terminal flags to CBREAK and NOECHO mode. This means that
* most things the user types is passed back to the calling program.
*/
{
if ( isatty(0) ) {
int ier;
ier=ioctl(0,TIOCGETP,&term);
saveterm = term;
if (ier==0) {
term.sg_flags |=CBREAK;
term.sg_flags &=~ECHO;
ioctl(0,TIOCSETP,&term);
}
}
return;
}
ttrset_()
/* Reset the terminal flags to state when CSTTY was last called.
*/
{
if ( isatty(0) ) {
ioctl(0,TIOCSETP,&saveterm);
}
return;
}
rdchr_(chr_ptr, chr_len)
char *chr_ptr;
int chr_len;
/* Reads a single byte from the current terminal. The read waits
* until the user types something.
*
* chr_ptr In/Ret The character read
* chr_len Input The Fortran size of the character array
*/
{
return (read(0,chr_ptr,1));
}
cwrite_(chr_ptr, chr_len)
char *chr_ptr;
int chr_len;
/* Write a single character to the terminal.
*
* chr_ptr Input The character to be written
* chr_len Input The Fortran size of the character array
*/
{
return (write(0,chr_ptr,chr_len));
}
cpgsze_(irow_ptr, icol_ptr)
int *irow_ptr;
int *icol_ptr;
/* Return the size of the current window.
*
* irow_ptr Return The number of rows in current window
* icol_ptr Return The number of columns in current window
*/
{
struct winsize actsize;
ioctl(0, TIOCGWINSZ, &actsize);
*irow_ptr=actsize.ws_row;
*icol_ptr=actsize.ws_col;
return;
}
cgtenv_(chr_ptr, cbuf_ptr, chr_len, cbuf_len)
char *chr_ptr, *cbuf_ptr;
int chr_len, cbuf_len;
/* Return the value of an environment variable.
*
* chr_ptr Input The environment variable
* cbuf_ptr Return The translation (blanked filled)
* chr_len Input The Fortran size of chr
* cbuf_len Input The Fortran size of cbuf
*/
{
int i;
char *getenv (), *itmp, *iloc;
itmp= cbuf_ptr;
iloc= getenv(chr_ptr);
for (i=1; i<=cbuf_len; i++) {
if ( iloc==0 ) {
*itmp=' ';
} else if ( *iloc==0 ) {
*itmp=' ';
iloc=0;
} else {
*itmp=*iloc;
iloc++;
}
itmp++;
}
return;
}
#include <sys/time.h>
cgtod_(itime)
struct timeval *itime;
/* Returns the UNIX system time.
*
* itime O An array 2 elements long containing the timeval data
*/
{
gettimeofday(itime, 0);
return;
}
cgruse_(iruse)
struct rusage *iruse;
/* Returns the UNIX system rusage structure.
*
* iruse O An array 18 elements long containing the rusage data
*/
{
getrusage(0, iruse);
return;
}
cloctim_(itzone)
struct tm *itzone;
/* Returns the localtime structure in a Fortran readable array.
*
* itzone O An array 11 elements long containing the localtime data
*/
{
struct timeval tp;
struct tm *localtime();
gettimeofday( &tp, 0);
*itzone= *localtime(&tp.tv_sec);
return;
}
cputs_(chr_ptr, chr_len)
char *chr_ptr;
int *chr_len;
{
FILE *file;
int i;
char *ftoolsoutput;
int stdout_opened = 0;
int tty_opened = 0;
ftoolsoutput = getenv("FTOOLSOUTPUT");
/* if the environment FTOOLSOUTPUT is not defined then open /dev/tty
if FTOOLSOUTPUT is defined and it is stdout then assign file to stdout
else, use the value of FTOOLSOUTPUT as a file name */
if (NULL != ftoolsoutput) {
if (!strcmp("/dev/tty",ftoolsoutput))
tty_opened++;
if (strcmp("stdout",ftoolsoutput)) {
file = fopen(ftoolsoutput,"a+");
} else {
file = stdout;
stdout_opened++;
}
} else {
file = stdout;
stdout_opened++;
}
if (NULL != file) {
for (i=0;i<*chr_len;i++) {
fputc(chr_ptr[i],file);
}
if (tty_opened) {
fputc('\015',file);
fputc('\012',file);
} else {
fputc('\n',file);
}
if (!stdout_opened)
fclose (file);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 1000
#define SEPAR ' '
int split(char *str, char *result[]);
int main()
{
char input[SIZE];
gets(input);
char *result[SIZE];
int n = split(input, result);
int i = 0;
char *p;
for(i = 0; i < n; i++){
printf("\"");
p = result[i];
while(*p != SEPAR){
printf("%c", *p);
p++;
}
printf("\"\n");
}
return 0;
}
int split(char *str, char *result[])
{
int count = 0;
int n = 0;
while(*str != '\0'){
while(*str == SEPAR){
str++;
}
if(*str == '\0') break;
*(result + n) = str;
str++;
n++;
while (*str != SEPAR && *str != '\0') {
str++;
}
}
return n;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jgomes-c <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/28 12:00:00 by jgomes-c #+# #+# */
/* Updated: 2021/06/02 16:25:17 by jgomes-c ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_countwrd(char const *s, char c)
{
int i;
int count;
int w;
w = 0;
i = 0;
count = 0;
while (s[i])
{
if (s[i] == c)
w = 0;
else if (s[i] != c && w == 0)
{
w = 1;
count++;
}
i++;
}
return (count);
}
static char *ft_strndup(const char *s, size_t n)
{
char *str;
str = (char *)malloc(sizeof(char) * n + 1);
if (str == NULL)
return (NULL);
str = ft_memcpy(str, s, n);
str[n] = '\0';
return (str);
}
char **ft_split(char const *s, char c)
{
char **len;
int count;
int i;
int i2;
count = 0;
i = 0;
len = (char **)malloc((ft_countwrd(s, c) + 1) * sizeof(char *));
if (len == NULL)
return (NULL);
while (s[i])
{
while (s[i] == c)
i++;
i2 = i;
while (s[i] && s[i] != c)
i++;
if (i > i2)
len[count++] = ft_strndup(s + i2, i - i2);
}
len[count] = NULL;
return (len);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
double wtime()
{
struct timeval t;
gettimeofday(&t, NULL);
return (double)t.tv_sec + (double)t.tv_usec * 1E-6;
}
int getrand(int min, int max)
{
return (double)rand() / (RAND_MAX + 1.0) * (max - min) + min;
}
void siftDown(int *numbers, int root, int bottom)
{
int maxChild;
int done = 0;
while ((root * 2 <= bottom) && (!done)) {
if (root * 2 == bottom)
maxChild = root * 2;
else if (numbers[root * 2] > numbers[root * 2 + 1])
maxChild = root * 2;
else
maxChild = root * 2 + 1;
if (numbers[root] < numbers[maxChild]) {
int temp = numbers[root];
numbers[root] = numbers[maxChild];
numbers[maxChild] = temp;
root = maxChild;
}
else
done = 1;
}
}
void heapSort(int *numbers, int array_size)
{
for (int i = (array_size / 2) - 1; i >= 0; i--) {
siftDown(numbers, i, array_size);
}
for (int i = array_size - 1; i >= 1; i--) {
int temp = numbers[0];
numbers[0] = numbers[i];
numbers[i] = temp;
siftDown(numbers, 0, i - 1);
}
}
int main()
{
double t;
t = wtime();
int const N = 50000;
int mas[N];
for(int i = 0; i < N; i++)
mas[i] = getrand(1, 100000);
// for (int i = 0; i < N; i++) {
// printf("%d ", mas[i]);
// }
// printf("\n");
heapSort(mas, N);
// for (int i = 0; i < N; i++) {
// printf("%d ", mas[i]);
// }
// printf("\n");
t = wtime() - t;
printf("Elapsed time: %.6f sec.\n", t);
return 0;
}
|
C
|
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
void swap( int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void bubbleSort(int a[], int n)
{
for ( int i = 0; i < n - 1; i++) {
for ( int j = 0; j < n - 1 - i; j++) {
if (a[j] > a[j + 1]) {
swap(&a[j], &a[j + 1]);
}
}
}
}
void selectionSort( int arr[], int n)
{
int min;
for (int i = 0; i < n - 1; i++) {
min = i;
for (int j = i + 1; j < n; j++){
if (arr[j] < arr[min]){
min = j;
swap(&arr[min], &arr[i]);
}
}
}
}
int main()
{
printf("Enter no. of elements in array: ");
long long int n;
scanf("%lld", &n);
printf("Elements of array:\n");
long long int arr[n];
for(int i=0; i<n; i++){
scanf("%lld", &arr[i]);
}
clock_t start2, end2;
long int t2;
start2 = clock();
bubbleSort(arr, n);
end2 = clock();
t2=end2-start2;
printf("total time elapsed for bubble sort: %f\n", (double)t2/(double)CLOCKS_PER_SEC);
clock_t start1, end1;
long int t1;
start1=clock();
selectionSort(arr, n);
end1=clock();
t1=end1-start1;
printf("total time elapsed for selection sort: %f\n", (double)t1/(double)CLOCKS_PER_SEC);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
typedef struct Ponto
{
double x, y;
} Ponto;
//grafo usando matriz
typedef struct Grafo
{
double **adj; //armazena distâncias entre os pontos[i][j]
int n;
} Grafo;
typedef Grafo *p_grafo;
p_grafo criar_grafo(int n)
{
int i, j;
p_grafo g = malloc(sizeof(Grafo));
g->n = n;
g->adj = malloc(n * sizeof(double *));
for (i = 0; i < n; i++)
{
g->adj[i] = malloc(n * sizeof(double));
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
g->adj[i][j] = 0;
}
}
return g;
}
void libera_grafo(p_grafo g)
{
for (int i = 0; i < g->n; i++)
{
free(g->adj[i]);
}
free(g->adj);
free(g);
}
double distancia_euclidiana(Ponto p1, Ponto p2)
{
double diferenca_1 = p1.x - p2.x;
double quadrado_1 = pow(diferenca_1, 2.0);
double diferenca_2 = p1.y - p2.y;
double quadrado_2 = pow(diferenca_2, 2.0);
double distancia = sqrt( quadrado_1 + quadrado_2);
return distancia;
}
int calcula_distancia_e_insere_arestas(p_grafo g, Ponto *pontos)
{
int maior_distancia = 0;
for (int i = 0; i < g->n; i++)
{
for (int j = 0; j < g->n; j++)
{
if (i != j)
{
double x = distancia_euclidiana(pontos[i], pontos[j]);
g->adj[i][j] = x;
if (x > maior_distancia)
{
maior_distancia = ceil(x);
}
}
else
{
g->adj[i][j] = -1;
}
}
}
return maior_distancia;
}
int eh_lugia(const int *categorias, int pos)
{
return categorias[pos];
}
int busca_recur(p_grafo g, int *visitados, int vertice, int tam, const int *categorias)
{
int w;
//se v = fim, econtramos o caminho
if (eh_lugia(categorias, vertice))
{
return 1;
}
//caso contario, marca que visitou
visitados[vertice] = 1;
//percorre vizinhos
for (w = 0; w < g->n; w++)
{
//se a distancia for menor que ou igual ao tamanho atual e o vizinho ainda não foi visitado
if (g->adj[vertice][w] <= tam && g->adj[vertice][w] != -1 && !visitados[w])
{
if (busca_recur(g, visitados, w, tam, categorias))
{
return 1;
}
}
}
return 0;
}
/** Chama busca em profundidade,
* que devolve 1 se há um caminho em que
* maior distancia é menor do que x
* ou 0 se a distância é maior
* */
int existe_caminho(p_grafo g, int ini, int tam, const int *categorias)
{
int encontrou, i, *visitado = malloc(g->n * sizeof(int));
for (i = 0; i < g->n; i++)
{
visitado[i] = 0;
}
encontrou = busca_recur(g, visitado, ini, tam, categorias);
free(visitado);
return encontrou;
}
/** Devolve a menor maior distância
* para a qual a busca em profundidade não falha
* */
int busca_binaria(p_grafo g, int ini, int min, int max, const int *categorias)
{
int tam_atual, retorno;
tam_atual = ceil((min + max) / 2);
retorno = existe_caminho(g, ini, tam_atual, categorias);
//se a diferença entre max e min é 1, é pq não existe menor ou igual ao mínimo, mas ao máx sim
if (max - min == 1)
{
return max;
}
//se passou, pode existir existe caminho menor
if (retorno)
{
return busca_binaria(g, ini, min, tam_atual, categorias);
}
//se não passou, existe caminho maior
else
{
return busca_binaria(g, ini, tam_atual, max, categorias);
}
}
int main()
{
int maior_distancia, retorno;
int i = 0, inicio = -1, menor_distancia = 0;
double componente_x;
//armazena todos os pontos lidos antes de inserir na matriz do grafo
Ponto *pontos = malloc(500 * sizeof(Ponto));
int *categorias = calloc(500, sizeof(int));
//lê entrada
Ponto ponto_inicial;
scanf("%lf %lf ", &(ponto_inicial.x), &(ponto_inicial.y));
scanf("%lf", &componente_x);
do
{
char categoria[10];
pontos[i].x = componente_x;
scanf(" %lf ", &(pontos[i].y));
scanf("%s ", categoria);
//identifica Lugias
if (strcmp(categoria, "Lugia") == 0)
{
categorias[i] = 1;
}
//identifica início
if (inicio == -1)
{
if (ponto_inicial.x == pontos[i].x && ponto_inicial.y == pontos[i].y)
{
inicio = i;
}
}
retorno = scanf("%lf", &componente_x);
i++;
} while (retorno != EOF);
//cria grafo com matriz i x i
p_grafo g = criar_grafo(i);
//calcula distâncias e insere em grafo
maior_distancia = calcula_distancia_e_insere_arestas(g, pontos);
//faz busca binária para achar a menor maior distância entre o início e um lugia
int distancia = busca_binaria(g, inicio, menor_distancia, maior_distancia, categorias);
printf("%d\n", distancia);
libera_grafo(g);
free(pontos);
free(categorias);
return 0;
}
|
C
|
#include <stdio.h>
#include "toBinTestVersion.h"
void toBin(unsigned int x, FILE* file) {
if (x == 0) return;
toBin(x / 2, file);
fprintf(file,"%d", x % 2);
}
void basic(unsigned int m, FILE* file) {
unsigned int number = 3;
int change = 0;
while (number <= m) {
fprintf(file, "%u ", number);
toBin(number, file);
fprintf(file, "\n");
if (number > 1073741824) break;
number <<= 2;
if (change) {
number |= 3;
change--;
continue;
}
change++;
}
}
|
C
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,i=1;
scanf("%d",&n);
printf("I hate");
while(i<n) {
if(i%2){
printf(" that I love");i++;}
else{
printf(" that I hate");i++;}
}
printf(" it");
return 0;
}
|
C
|
#include <stdio.h>
// wasa関数の宣言
void WaSa(int *a, int *b);
int main(void){
int a, b;
printf("2つの整数を入力してください.\n");
scanf("%d", &a);
scanf("%d", &b);
WaSa(&a, &b);
printf("和:%d, 差:%d\n", a, b);
return 0;
}
void WaSa(int *a, int *b){
int tmp_a, tmp_b;
tmp_a = *a;
tmp_b = *b;
*a = tmp_a + tmp_b;
*b = tmp_a - tmp_b;
}
|
C
|
#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#define MAX 9
int main(void)
{
return true;
}
typedef struct
{
string name;
int votes;
}
candidate;
int candidate_count;
candidate candidates[MAX];
bool vote(string name)
{
for (int x = 0; x < candidate_count; x++)
{
if (strcmp(name, candidates[x].name) == 0) //Broteforce check
{
candidates[x].votes += 1;
return true;
}
}
return false;
}
void print_winner(void)
{
int f = 0;
for (int x = 0; x < candidate_count; x++)
{
// printf("%d %d %d\n",f ,name_list[x].vote, f < name_list[x].vote); //Debugger
if (f < candidates[x].votes) // Finds highest
{
f = candidates[x].votes;
}
// printf("%d\n", f); //Debugger
}
for (int x = 0; x < candidate_count; x++)
{
// printf("Equal:%d\nVote:%d\nFlag:%d\n",f == name_list[x].vote, name_list[x].vote, f); //Debugger
if (f == candidates[x].votes) // Prints all of the highest value
{
printf("%s\n", candidates[x].name);
}
}
return;
}
|
C
|
#include<stdio.h>
#include<time.h>
void struct_ex01(){
typedef struct{
char role[20];
char position[4];
}lol_info;
struct lol_champ{
char name[14];
int number;
lol_info info;
struct lol_champ *self_c;
}champ[3], *c, *sc;
c=champ;
;
for(int i=0;i<3;i++){
printf("name:");
gets((c+i)->name);
printf("number:");
scanf("%d",&(c+i)->number);
while(getchar()!='\n');
printf("role:");
gets((c+i)->info.role);
printf("position:");
gets((c+i)->info.position);
(c+i)->self_c=(c+i);
printf("\n");
}
sc=c->self_c;
time_t now = time(NULL);
struct tm *today;
today = localtime(&now);
int year = today->tm_year+1900;
int month = today->tm_mon+1;
int day = today->tm_mday;
for(int i=0;i<3;i++){
printf("champ- %d-%d-%d name:%s number:%d role:%s pos:%s\n",year,month,day,(c+i)->name,(c+i)->number,(c+i)->info.role,(c+i)->info.position);
printf("self-c-%d-%d-%d name:%s number:%d role:%s pos:%s\n",year,month,day,(sc+i)->name,(sc+i)->number,(sc+i)->info.role,(sc+i)->info.position);
}
}
int main(){
struct_ex01();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct sNODE {
int dado;
struct sNODE *esq, *dir;
};
struct sNODE *raiz = NULL;
struct sNODE *inserir(struct sNODE *no, int dado);
struct sNODE *remover(struct sNODE *no, int dado);
void emOrdem(struct sNODE *no);
void preOrdem(struct sNODE *no);
void posOrdem(struct sNODE *no);
struct sNODE *buscar(struct sNODE *no, int dado);
int obter(struct sNODE *no);
struct sNODE *apagar(struct sNODE *no);
int getMax(struct sNODE *no);
int getMin(struct sNODE *no);
void mostrarFolhas(struct sNODE *no);
int distanciaDaRaiz(struct sNODE *no, int dado);
int alturaArvore(struct sNODE *no);
int distanciaEntre(struct sNODE *no, int a, int b);
int main(void) {
raiz = inserir(raiz, 6);
raiz = inserir(raiz, 2);
raiz = inserir(raiz, 8);
raiz = inserir(raiz, 1);
raiz = inserir(raiz, 4);
raiz = inserir(raiz, 3);
raiz = inserir(raiz, 9);
printf("Max: %d \n", getMax(raiz));
printf("Min: %d \n", getMin(raiz));
printf("Folhas: ");
mostrarFolhas(raiz);
printf("\n");
printf("Distancia entre raiz e %d eh %d saltos\n", 4, distanciaDaRaiz(raiz, 4));
printf("Distancia entre raiz e %d eh %d saltos\n", 6, distanciaDaRaiz(raiz, 6));
printf("Distancia entre raiz e %d eh %d saltos\n", 15, distanciaDaRaiz(raiz, 15));
printf("Altura da arvore: %d\n", alturaArvore(raiz));
printf("Distancia entre %d e %d eh %d saltos\n", 4, 3, distanciaEntre(raiz, 4, 3));
printf("Distancia entre %d e %d eh %d saltos\n", 4, 4, distanciaEntre(raiz, 4, 4));
return 0;
}
struct sNODE *inserir(struct sNODE *no, int dado) {
if (!no) {
no = (struct sNODE *) malloc(sizeof(struct sNODE));
no->dado = dado;
no->esq = no->dir = NULL;
} else if (dado < no->dado)
no->esq = inserir(no->esq, dado);
else
no->dir = inserir(no->dir, dado);
return no;
}
struct sNODE *remover(struct sNODE *no, int dado) {
struct sNODE *aux = NULL, *aux2 = NULL;
if (no) {
if (no->dado == dado) {
if (no->esq == no->dir) {
free(no);
return NULL;
} else if (!no->esq) {
aux = no->dir;
free(no);
return aux;
} else if (!no->dir) {
aux = no->esq;
free(no);
return aux;
} else {
aux = aux2 = no->dir;
while (aux->esq)
aux = aux->esq;
aux->esq = no->esq;
free(no);
return aux2;
}
} else {
if (dado < no->dado)
no->esq = remover(no->esq, dado);
else
no->dir = remover(no->dir, dado);
}
}
return no;
}
void emOrdem(struct sNODE *no) {
if (no) {
emOrdem(no->esq);
printf("%d ", no->dado);
emOrdem(no->dir);
}
}
void preOrdem(struct sNODE *no) {
if (no) {
printf("%d ", no->dado);
preOrdem(no->esq);
preOrdem(no->dir);
}
}
void posOrdem(struct sNODE *no) {
if (no) {
posOrdem(no->esq);
posOrdem(no->dir);
printf("%d ", no->dado);
}
}
struct sNODE *buscar(struct sNODE *no, int dado) {
if (no) {
if (no->dado == dado)
return no;
else if (dado < no->dado)
return buscar(no->esq, dado);
else
return buscar(no->dir, dado);
}
return NULL;
}
int obter(struct sNODE *no) {
if (no)
return no->dado;
else {
printf("Nenhum dado para retornar.");
exit(0);
}
}
struct sNODE *apagar(struct sNODE *no) {
if (no) {
no->esq = apagar(no->esq);
no->dir = apagar(no->dir);
free(no);
}
return NULL;
}
int getMax(struct sNODE *no) {
if (!no) {
printf("Nao ha arvore!\n");
exit(1);
} else {
if (no->dir)
return getMax(no->dir);
else
return no->dado;
}
}
int getMin(struct sNODE *no) {
if (!no) {
printf("Nao ha arvore!\n");
exit(1);
} else {
if (no->esq)
return getMax(no->esq);
else
return no->dado;
}
}
void mostrarFolhas(struct sNODE *no) {
if (no) {
mostrarFolhas(no->esq);
if (!no->esq && !no->dir)
printf("%d ", no->dado);
mostrarFolhas(no->dir);
}
}
int distanciaDaRaiz(struct sNODE *no, int dado) {
if (!no)
return -1;
else {
if (dado == no->dado) return 0;
else {
int d = (dado < no->dado ? distanciaDaRaiz(no->esq, dado) : distanciaDaRaiz(no->dir, dado));
if (d == -1) return d;
else return d + 1;
}
}
}
int alturaArvore(struct sNODE *no) {
if (!no)
return -1;
else {
if (no->esq == no->dir)
return 0;
else {
int le = 1 + alturaArvore(no->esq);
int ld = 1 + alturaArvore(no->dir);
if (le > ld)
return le;
return ld;
}
}
}
int distanciaEntre(struct sNODE *no, int a, int b) {
if (a < no->dado && b < no->dado)
return distanciaEntre(no->esq, a, b);
else if (a > no->dado && b > no->dado)
return distanciaEntre(no->dir, a, b);
else
return distanciaDaRaiz(no, a) + distanciaDaRaiz(no, b);
}
|
C
|
/**
* @file battery.c
* @author Peter Magro
* @date August 4th, 2021
* @brief Handles all battery measurement-related functions.
*/
//***********************************************************************************
// Include files
//***********************************************************************************
#include "battery.h"
#include "brd_config.h"
//***********************************************************************************
// defined files
//***********************************************************************************
#define fmin(x, y) ((x < y) ? x : y)
//***********************************************************************************
// Static / Private Variables
//***********************************************************************************
static uint32_t consecutive_low_reads;
//***********************************************************************************
// Private functions
//***********************************************************************************
//***********************************************************************************
// Global functions
//***********************************************************************************
/***************************************************************************//**
* @brief
* Opens the ADC and LETIMER for battery readings.
*
* @details
* ADC is opened with 8x oversampling. LETIMER is opened with 5-second poll period
* and no callbacks.
*
******************************************************************************/
void battery_open(void) {
// open ADC
ADC_OPEN_STRUCT_TypeDef adc_init;
adc_init.em2ClockConfig = adcEm2Disabled; // only enables async clock when necessary
adc_init.ovsRateSel = adcOvsRateSel8; // pretty arbitrary selection here. we don't need a lot of precision.
adc_init.tailgate = false; // tailgating is only necessary when the ADC is running continuously. we're going to poll it with the LETIMER
adc_init.target_freq = ADC_TARGET_FREQ;
adc_init.warmUpMode = adcWarmupNormal; // shut down ADC when not in use
adc_init.channel = ADC_INPUT_BUS;
adc_init.overwrite = true; // overwrite FIFO buffer when full
adc_init.acqTime = adcAcqTime8;
adc_open(BATTERY_ADC, &adc_init);
// open LETIMER to poll ADC
APP_LETIMER_PWM_TypeDef letimer_init;
letimer_init.active_period = BATTERY_POLLING_PERIOD / 2;
letimer_init.comp0_cb = 0; // not using callbacks
letimer_init.comp0_irq_enable = false;
letimer_init.comp1_cb = 0;
letimer_init.comp1_irq_enable = false;
letimer_init.debugRun = false;
letimer_init.enable = false;
letimer_init.out_pin_0_en = false;
letimer_init.out_pin_1_en = false;
letimer_init.out_pin_route0 = PWM_ROUTE_0;
letimer_init.out_pin_route1 = PWM_ROUTE_1;
letimer_init.period = BATTERY_POLLING_PERIOD; // 5 seconds
letimer_init.uf_cb = 0;
letimer_init.uf_irq_enable = true;
letimer_pwm_open(BATTERY_LETIMER, &letimer_init);
}
/***************************************************************************//**
* @brief
* Starts a new conversion, reads the last conversion, and updates
* consecutive_low_reads.
*
* @details
* consecutive_low_reads is incremented for each low read, and reset to 0
* for any high read.
*
******************************************************************************/
void battery_poll() {
adc_start_conversion(BATTERY_ADC);
uint32_t last_read = adc_get_last_read();
if (last_read < BATTERY_LOW_THRESH) {
consecutive_low_reads++;
} else {
consecutive_low_reads = 0;
}
}
/***************************************************************************//**
* @brief
* Returns the battery's "low" state.
*
* @details
* The battery is considered "low" if consecutive_low_reads is greater than
* 5.
*
* @return
* True if the battery level is considered "low".
*
******************************************************************************/
bool battery_check_low() {
if (consecutive_low_reads > BATTERY_LOW_COUNT_THRESH) {
return true;
} else {
return false;
}
}
/***************************************************************************//**
* @brief
* Calculates the battery level.
*
* @details
* Extremely rough estimate - simply a linear percent value between the
* battery's dead voltage and full charge.
*
* @return
* A percent value
*
******************************************************************************/
float battery_get_percent() {
// Calculate the battery percentage
float battery_max = BATTERY_MAX_V * 4095;
float battery_min = BATTERY_MIN_V * 4095;
float percent = 100 * ((float) adc_get_last_read() - (battery_min)) / (battery_max - battery_min);
// Return 100 if the battery is reading >100, else return the percentage
return fmin(percent, 100);
}
/***************************************************************************//**
* @brief
* LETIMER interrupt handler.
*
* @details
* Begins the battery reading sequence.
*
******************************************************************************/
void LETIMER0_IRQHandler(void) {
uint32_t int_flag = LETIMER0->IF & LETIMER0->IEN;
LETIMER0->IFC = int_flag;
if (int_flag & LETIMER_IF_UF) {
battery_poll();
}
}
|
C
|
/*
queue.c
Richard Coffey
ECE 223
Program #3
*/
#include <stdio.h>
#include <stdlib.h>
//#include "list.h"
#include "queue.h"
//#include "sim.h"
//queue is a linked list so should never be full
struct queue_s {
list list;
int numelements;
int maxsize;
};
/* create and initialize a new queue
must be able to hold at least size items
return pointer to the new queue, NULL if error */
//int size is input in main file where queue init is called
//should allocate a queue pointer that has size of
//mallocs a new queue_t, then calls list_init
//int size doesn't really matter,
queue_t *queue_init(int size) {
struct queue_s *queue;
queue = (struct queue_s *)malloc(sizeof(struct queue_s));
if (queue == NULL) {
return(NULL);
}
else {
// queue is valid,initialize the linked list in that queue
queue->list = list_init();
if (queue->list == NULL) {
free(queue);
return (NULL);
}
//set counter variables
//queue->numelements = 0;
//queue->maxsize = size+1;
return(queue);
}
}
/* insert an item into the queue
return 0 if successful, -1 otherwise */
//first in first out queue
//no need to check for max length because it's a linked list
int queue_insert(queue_t *q, customer_t *c) {
//create a temp customer pointer
customer_t *ctemp;
//always put the new customer at the back of the list b/c FIFO
ctemp = list_append(q->list, c);
if (ctemp == NULL) {
return(-1);
}
//add 1 to the customer counter
(q->numelements)++;
//if the customer is successfully added to the back of the queue
return (0);
}
/* return the next item in the queue but do not remove it
return NULL if the queue is empty or on error */
customer_t *queue_peek(queue_t *q) {
//set list to the first element
customer_t *cfirst;
cfirst = list_first(q->list);
if (cfirst == NULL) {
return (NULL);
}
else {
return (cfirst);
}
}
/* remove the next item from the queue
and return it, return NULL if there is an error */
customer_t *queue_remove(queue_t *q) {
//remove first item in the queue according to FIFO
//use list_first to set head to current item
customer_t *cfirst;
customer_t *cremoved;
cfirst = list_first(q->list);
if (cfirst == NULL) {
return (NULL);
}
//removes the current item, and which should be head
//list_remvoe should always hit the "just delete head" case
cremoved = list_remove(q->list);
if (cremoved == NULL) {
return (NULL);
}
(q->numelements)--;
return(cremoved);
}
/* return the number of items in the queue
You can see if queue is empty with this */
int queue_size(queue_t *q) {
return (q->numelements);
}
/* return nono-zero if the queue is full
This may be trivial using a linked implementation */
int queue_full(queue_t *q) {
//will always return 0 since linked list in queue is infinite
return(0);
}
/* free all resourced used by the queue then free
the queue itself */
void queue_finalize(queue_t *q) {
list_finalize(q->list);
free(q);
}
|
C
|
#include <stdio.h>
int main(int argc, char **argv){
int n, q;
int S[100], T[100];
scanf("%d", &n);
for(int i = 0; i < n; ++i){
scanf("%d ", &S[i]);
}
scanf("%d", &q);
for(int i = 0; i < q; ++i){
scanf("%d", &T[i]);
}
int ret = 0;
for(int i = 0; i < q; ++i){
int val = T[i];
for(int j = 0; j < n; ++j){
ret += (S[j] == val);
}
}
printf("%d", ret);
}
|
C
|
#include <stdio.h>
int main(void)
{
int psbit = 0, sbit = 0, rebit, i = 1, j = 0, end = 0, end2 = 0;
int ps[64] = { 0 };
int s[64] = { 0 };
int Ps , S , psbit2, sbit2 , sign = 0;
scanf("%d %d", &Ps, &S);
if(Ps <= 0 && s >0)
{
sign = 1;
}else if (Ps > 0 && s <= 0)
{
sign = 1;
}
//비교
if(Ps <= 0)
{
ps[0] = 0;
Ps *=(-1);
for( ; Ps != 0; Ps = Ps/2 )
{
ps[i] = Ps % 2;
i++;
psbit++;
}
i -= 1;
psbit += 1;
for(psbit2 = 1 ; psbit2 < psbit / 2 ; psbit2++)
{
Ps = ps[i];
ps[i] = ps[psbit2];
ps[psbit2] = Ps;
i--;
}
}else
{
ps[0] = 0;
for( ; Ps != 0; Ps = Ps/2 )
{
ps[i] = Ps % 2;
i++;
psbit++;
}
i -= 1;
psbit += 1;
for(psbit2 = 1 ; psbit2 < psbit / 2 ; psbit2++)
{
Ps = ps[i];
ps[i] = ps[psbit2];
ps[psbit2] = Ps;
i--;
}
}
for (j = 0; j < psbit; j++)//피승수 print
{
printf("%d", ps[j]);
}
printf("\n");
i =1;
j = 0;
if(S <= 0)
{
s[0] = 0;
S *=(-1);
for( ; S != 0; S = S/2 )
{
s[i] = S % 2;
i++;
sbit++;
}
i -= 1;
sbit += 1;
for(sbit2 = 1 ; sbit2 <= sbit / 2 ; sbit2++)
{
S = s[i];
s[i] = s[sbit2];
s[sbit2] = S;
i--;
}
}else
{
s[0] = 0;
for( ; S != 0; S = S/2 )
{
s[i] = S % 2;
i++;
sbit++;
}
i -= 1;
sbit += 1;
for(sbit2 = 1 ; sbit2 <= sbit / 2 ; sbit2++)
{
S = s[i];
s[i] = s[sbit2];
s[sbit2] = S;
i--;
}
}
for (j = 0; j <sbit; j++)//승수 print
{
printf("%d", s[j]);
}
printf("\n");
// 10진수 to 2진수
i = rebit = psbit + sbit;
int re[200] = { 0 };
printf(" ");
for (i -= 1; i >= 0; i--)//연산전 re print
{
printf("%d", re[i]);
}
i = rebit;
printf("\n");
for (sbit -= 1; sbit >= 0; sbit--)//승수 연산 확인
{
if (s[sbit] == 1)
{
printf("+ ");
for (j = 0; j < psbit; j++)//피승수 출력
{
printf("%d", ps[j]);
}
printf("\n");
end2 = end + psbit;
for (j = psbit - 1; j >= 0; j--)//덧셈 연산
{
re[end2] = re[end2] + ps[j];
if (re[end2] == 2)
{
re[end2] = 0;
re[end2 + 1] += 1;
}
else if (re[end2] == 3)
{
re[end2] = 1;
re[end2 + 1] += 1;
}
end2++;
}
i = rebit;
printf(" ");
for (i -= 1; i >= end; i--)//덧셈 결과 출력
{
printf("%d", re[i]);
}
printf("\n");
rebit++; //덧셈결과 shift
end++;
i = rebit;
printf(" ");
for (i -= 1; i >= end; i--)//shift print
{
printf("%d", re[i]);
}
printf("\n");
}
else if (s[sbit] == 0)
{
printf("+ ");
for (j = 0; j < psbit; j++)//피승수 print
{
printf("%d", 0);
}
printf("\n");
rebit++;//연산결과 shift
end++;
i = rebit;
printf(" ");
for (i -= 1; i >= end; i--)//shift print
{
printf("%d", re[i]);
}
printf("\n");
}
}
if (sign != 1)
{
i = rebit;
printf("\n");
printf("결과:");
for (i -= 2; i >= end; i--)//결과 print
{
printf("%d", re[i]);
}
}else if (sign == 1)//두 피연산자의 부호 다를 경우 2의 보수 후 결과 출력
{
i = rebit;
for (i -= 1; i >= end; i--)//1의 보수
{
re[i] = !re[i];
}
i = rebit;
end2 = end;
re[end2] = re[end2] + 1;
for (j = i; j >= end; j--)
{
re[end2];
if (re[end2] == 2)
{
re[end2] = 0;
re[end2 + 1] += 1;
}
else if (re[end2] == 3)
{
re[end2] = 1;
re[end2 + 1] += 1;
}
end2++;
}
printf("\n");
i = rebit;
printf("결과:");
for (i -= 2; i >= end ; i--)//2의 보수 결과 print
{
printf("%d", re[i]);
}
printf("\n");
}
return 0;
}
|
C
|
/* sort.c */
// This program generates sorts the following list of random numbers;
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Utility / debug function only used to check array is sorted
void print_arr(int *arr, int size)
{
printf("[");
int i;
for(i = 0; i < size; i++){
printf("%d, ", arr[i]);
}
printf("]\n");
}
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bubbleSort(int *arr, int size){
int i;
int j;
for(j = 0; j < (size-1); j++){
for(i = 0; i < (size-1); i++){
if(arr[i] > arr[i+1]){
swap(&arr[i], &arr[i+1]);
}
}
}
}
int main(void)
{
int n = 100;
int *arr = malloc(sizeof(int) * n);
srand(time(NULL));
int i;
for(i = 0; i < n; i++){
arr[i] = rand() % 200;
}
printf("Before\n");
print_arr(arr, n);
printf("\n");
bubbleSort(arr, n);
printf("After\n");
print_arr(arr, n);
printf("\n");
free(arr);
return 0;
}
|
C
|
#include "./rendering_resource.h"
#include "../../logger/logger.h"
#include "../../memory/memory.h"
#include "../../vulkan/functions/functions.h"
#include "../../vulkan/tools/tools.h"
void rendering_resource_init_empty(rendering_resource* res) {
res->device = VK_NULL_HANDLE;
res->command_pool = VK_NULL_HANDLE;
res->command_buffer = VK_NULL_HANDLE;
res->finished_render_semaphore = VK_NULL_HANDLE;
res->image_available_semaphore = VK_NULL_HANDLE;
res->fence = VK_NULL_HANDLE;
vk_framebuffer_init_empty(&res->framebuffer);
}
static bool rendering_resource_init_framebuffer_from_swp(rendering_resource*
res, const vk_swapchain* swp, VkRenderPass render_pass, size_t swp_idx)
{
bool status = vk_framebuffer_init_from_swapchain(&res->framebuffer, swp,
render_pass, swp_idx);
ASSERT_LOG_ERROR(status, "Unable to create framebuffers from swapchain");
return true;
}
static bool rendering_resource_init_semaphores(rendering_resource* res) {
const VkSemaphoreCreateInfo sempahore_info = {
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
.pNext = NULL,
.flags = 0
};
CHECK_VK_BOOL(vkCreateSemaphore(res->device, &sempahore_info, NULL,
&res->image_available_semaphore));
CHECK_VK_BOOL(vkCreateSemaphore(res->device, &sempahore_info, NULL,
&res->finished_render_semaphore));
return true;
}
static bool rendering_resource_init_fence(rendering_resource* res) {
const VkFenceCreateInfo fence_info = {
.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
.pNext = NULL,
.flags = VK_FENCE_CREATE_SIGNALED_BIT
};
CHECK_VK_BOOL(vkCreateFence(res->device, &fence_info, NULL, &res->fence));
return true;
}
static bool rendering_resource_init_command_resources(rendering_resource* res,
uint32_t queue_family_index)
{
VkCommandPoolCreateInfo cmd_pool_create_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
.pNext = NULL,
.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT |
VK_COMMAND_POOL_CREATE_TRANSIENT_BIT,
.queueFamilyIndex = queue_family_index
};
CHECK_VK_BOOL(vkCreateCommandPool(res->device, &cmd_pool_create_info, NULL,
&res->command_pool));
VkCommandBufferAllocateInfo command_buffer_allocate_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
.pNext = NULL,
.commandPool = res->command_pool,
.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
.commandBufferCount = 1
};
CHECK_VK_BOOL(vkAllocateCommandBuffers(res->device,
&command_buffer_allocate_info, &res->command_buffer));
return true;
}
bool rendering_resources_init_from_swapchain(rendering_resource** resources,
const gpu_info* gpu, const vk_swapchain* swp, VkRenderPass render_pass,
uint32_t queue_family_index)
{
*resources = NULL;
rendering_resource* ress = mem_alloc(sizeof(rendering_resource) *
swp->image_count);
CHECK_ALLOC_BOOL(ress, "Unable to allocate rendering resources");
bool status = true;
for (size_t i = 0; i < swp->image_count && status; ++i) {
rendering_resource* res = &ress[i];
rendering_resource_init_empty(res);
res->device = gpu->device;
status &= rendering_resource_init_framebuffer_from_swp(res, swp,
render_pass, i) &&
rendering_resource_init_semaphores(res) &&
rendering_resource_init_fence(res) &&
rendering_resource_init_command_resources(res, queue_family_index);
}
*resources = ress;
return true;
}
static inline void rendering_resource_destroy_command_res(rendering_resource*
res)
{
if (res->command_pool) {
vkDestroyCommandPool(res->device, res->command_pool, NULL);
res->command_pool = VK_NULL_HANDLE;
}
}
static inline void rendering_resource_destroy_fence(rendering_resource* res) {
if (res->fence) {
vkDestroyFence(res->device, res->fence, NULL);
}
}
static inline void rendering_resource_destroy_sems(rendering_resource* res) {
if (res->image_available_semaphore) {
vkDestroySemaphore(res->device, res->image_available_semaphore, NULL);
}
if (res->finished_render_semaphore) {
vkDestroySemaphore(res->device, res->finished_render_semaphore, NULL);
}
}
static inline void rendering_resource_destroy_fbs(rendering_resource* res) {
vk_framebuffer_destroy(&res->framebuffer);
vk_framebuffer_init_empty(&res->framebuffer);
}
void rendering_resource_destroy(rendering_resource* res) {
rendering_resource_destroy_command_res(res);
rendering_resource_destroy_fbs(res);
rendering_resource_destroy_sems(res);
rendering_resource_destroy_fence(res);
rendering_resource_init_empty(res);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/**
*main - progrman that multiplies two numbers
*@argc: argument count
*@argv: pointer point to argument string
*Return: 0
*/
int main(int argc, char *argv[])
{
int rest, i;
char *p;
int n;
rest = 0;
if (argc > 1)
{
for (i = 1; argv[i]; i++)
{
n = strtol(argv[i], &p, 10);
if (!*p)
rest += n;
else
{
printf("Error\n");
return (1);
}
}
}
printf("%d\n", rest);
return (0);
}
|
C
|
#include<stdio.h>
/**
* main - function, entry point
* @argc: # of args passed to program.
* @argv: string array args passed to program.
*
* Description: program to print all arguments it receives.
* Return: Always 0
*/
int main(int argc, char *argv[])
{
int count;
for (count = 0; count < argc; count++)
{
printf("%s\n", argv[count]);
}
return (0);
}
|
C
|
#include <ctest.h>
#include <func.h>
CTEST(FUNC_TEST, COMMON){
// Given
/*int a[] = {5,4,3,2};
int b[] = {5,6,7,8};
*/
int a = 5;
int b = 5;
// When
int result;
result = func(a,b);
// Then
//int expected[] = {10,10,10,10};
int expected = 10;
//int i;
//for (i = 0; i < 4; i++){
ASSERT_EQUAL(expected,result);
}
|
C
|
/*
* TCP_Server.c
*
* @date 2015/10/01
* @author Leejewoo
* @email [email protected]
*
* TCP_Socket의 생성과 해당 디스크립터 반환
*/
#include <sys/socket.h> /* for socket(), bind(), and connect() */
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */
#include <unistd.h>
#include <string.h> /* for memset() */
#include <stdio.h> /* for perror() */
#include <stdlib.h> /* for exit() */
#include "ctl.c"
#define MAXPENDING 100 /* Maximum outstanding connection requests */
#define RCVBUFSIZE 32 /* Size of receive buffer */
/*
* @function : ServerSocket을 생성하기 위한 함수 socket->bind->listen까지
* @param: port(해당 포트번호로 Tcp server socket을 생성하기 위한 변수)
* @return: 생성된 소켓의 디스크립터 -1일때는 socket 생성실패, 0일경우는
* bind에러
*/
int CreateTCPServerSocket(unsigned short port)
{
int sock; /* socket to create */
struct sockaddr_in echoServAddr; /* Local address */
/* Create socket for incoming connections */
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
perror("socket() failed\n");
exit(8003);
}
sock_reuse(sock);
/* Construct local address structure */
memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */
echoServAddr.sin_family = AF_INET; /* Internet address family */
echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
echoServAddr.sin_port = htons(port); /* Local port */
/* Bind to the local address */
if (bind(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
{
perror("bind() failed\n");
exit(8003);
}
/* Mark the socket so it will listen for incoming connections */
if (listen(sock, MAXPENDING) < 0)
{
perror("listen() failed\n");
exit(8003);
}
return sock;
}
/*
* @function : CreateTCPServerSocket을 통해 생성된 Serversocket으로 accept하기 위한 함수
* @param: servSock(ServerSocket의 디스크립터)
* @return: 실제로 연결된 client와 1:1로 연결되어 있는 TCP소켓 디스크립터
*/
int AcceptTCPConnection(int servSock)
{
int clntSock; /* Socket descriptor for client */
struct sockaddr_in echoClntAddr; /* Client address */
unsigned int clntLen; /* Length of client address data structure */
/* Set the size of the in-out parameter */
clntLen = sizeof(echoClntAddr);
/* Wait for a client to connect */
if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr,
&clntLen)) < 0)
{
perror("accept() failed\n");
exit(8003);
}
/* clntSock is connected to a client! */
printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr));
return clntSock;
}
/*
* @function : CreateTCPServerSocket와 AccpetTCPConnection을 수행해, 실제 1:1
* 로 client 연결된 소켓의 디스크립터만 가져오기 위한 함수, DOS-project에서는 더 이상의
* TCP server socket이 필요없기때문에, close를 통해, 닫고, 1:1로 연결된 디스크립터만 반환한다.
* @param: port(Server Socket을 열기위한 port number)
* @return: 실제로 연결된 client와 1:1로 연결되어 있는 TCP소켓 디스크립터
*/
int TCP_connect_init(unsigned short port)
{
int serv_sock;
int clnt_sock;
char buf;
serv_sock=CreateTCPServerSocket(port);
clnt_sock=AcceptTCPConnection(serv_sock);
close(serv_sock);
buf=1;
send(clnt_sock,&buf,1,0);
recv(clnt_sock,&buf,1,0);
send(clnt_sock,&buf,1,0);
if(buf!=1)
{
printf("tcp init error\n");
return -1;
}
return clnt_sock;
}
|
C
|
/*
** aff_cases.c for 42sh in /u/all/bereng_p/cu/rendu/SVN/42sh/current
**
** Made by philippe berenguel
** Login <[email protected]>
**
** Started on Sun May 23 16:02:55 2010 philippe berenguel
** Last update Sun May 23 23:23:48 2010 carole cailleux
*/
#include <stdlib.h>
#include "parser.h"
#include "builtins.h"
#include "ergonomy.h"
#include "completion.h"
#include "termcaps.h"
#include "lib_includes/aff.h"
#include "lib_includes/strings.h"
#include "lib_includes/xfunctions.h"
void cd_case(char **tab)
{
int p;
p = 0;
while (tab && tab[p])
{
if (tab[p][my_strlen(tab[p])] == '/')
{
my_putstr(tab[p]);
my_putchar('\n');
}
p++;
}
}
void tilde_case(int *p, int *n, int *t, char **tab)
{
while (*p < 2 && tab[0][*t])
if (tab[0][(*t)++] == '/')
(*p)++;
if (*n >= 1)
*n = 2;
}
void tilde_case_two(char **tab, char *buffer, size_t *curs)
{
int p;
unsigned int c;
int s;
c = curs[0];
s = -1;
if (c == curs[1])
c--;
while (c > 0 && buffer[c] != ' ' && buffer[c] != '\t')
c--;
if (buffer[c] == ' ' || buffer[c] == '\t')
c++;
p = c;
while (buffer[c] && buffer[c] != ' ' && buffer[c] != '\t' && s < 4)
if (buffer[++c] == '/')
s++;
p = c - p + 1;
s = 0;
while (tab[s])
{
my_putstr(&tab[s++][p]);
my_putchar('\n');
}
}
int hidden_files(char *buffer, int *c, int *s, size_t *curs)
{
int p;
p = *c;
while (*c > 0 && buffer[*c] != '.')
(*c)--;
if (buffer[*c + 1] != '/' && (*c > 0 || buffer[*c] == '.'))
{
if (*c == 0 && buffer[*c] != '.')
*s = 2;
else
*s = 0;
if (buffer[p] == ' ' || buffer[p] == '\t')
p--;
while (p > 0 && buffer[p] != ' ' && buffer[p] != '\t')
p--;
if (buffer[p] == ' ' || buffer[p] == '\t')
p++;
*c = p;
return (1);
}
else
{
*c = curs[0];
return (0);
}
}
int no_hidden_files(char *buffer, int *c, int *s)
{
if (*c > 0 && (buffer[*c] == ' ' || buffer[*c] == '\t'))
(*c)--;
while (*c > 0 && buffer[*c] != ' ' && buffer[*c] != '\t')
(*c)--;
if (buffer[*c] == ' ' || buffer[*c] == '\t')
{
(*c)++;
(*s) += 2;
}
return (1);
}
|
C
|
#include<stdio.h>
void strncopy( char *sbuf, char *dbuff, int n)
{
int i;
for( i = 0; i < n; i++)
{
dbuff[i] = sbuf[i];
}
dbuff[n] = '\0';
printf("the destination string is: %s\n", dbuff);
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#define MAX_LINE 1000
int any(char s[], char c)
{
int res = -1;
for (int i = 0; s[i] != '\0'; ++i)
if (s[i] == c)
{
res = i;
break;
}
return res;
}
int any_s(char s1[], char s2[])
{
int res = -1;
for (int i = 0; s2[i] != '\0'; ++i)
{
int resc = any(s1, s2[i]);
if (resc > res)
res = resc;
}
return res;
}
void read_line(char s[])
{
char c;
int i;
for (i = 0; i < MAX_LINE - 1 && (c = getchar()) && c != '\n' && c != EOF; i++)
s[i] = c;
s[i] = '\0';
}
int main()
{
char s1[MAX_LINE];
char s2[MAX_LINE];
read_line(s1);
read_line(s2);
int pos = any_s(s1, s2);
printf("%d\n", pos);
}
|
C
|
/*
From:ITC
7
Resource management defects
7.3
Invalid memory access to already freed area
7.3.2
"using pointer to double,conditional statement if ~else using static variable of function scope"
*/
static int staticflag1=1;
void invalid_memory_access_002 ()
{
double *ptr, *dptr = 0,a;
static int staticflag=10;
if (staticflag == 10)
(ptr= (double*) malloc(10*sizeof(double)));
else
(dptr = (double*) malloc(5*sizeof(double)));
if (staticflag == 10 && ptr!=NULL)
(*(ptr+1) = 10.5);
else
(*(dptr+1) = 5.5) ;
if(staticflag == 10 && ptr!=NULL)
a = *(ptr+1); /*Tool should not detect this line as error*/ /*No ERROR:Invalid memory access to already freed area*/
else
a = *(dptr+1);
printf("%lf",a);
if(staticflag == 10 && ptr!=NULL)
{
free(ptr);
ptr = NULL;
}
else
{
free(dptr);
dptr = NULL;
}
}
|
C
|
#ifndef _STACK_H
#define _STACK_H
#include <stdio.h>
#define MAX_STACK_SIZE 100
typedef struct{
int x;
int y;
}Point;
Point* stack_cur_poit(Point* buf, int* b_size);
void stack_push(Point* buf, int* b_size, Point* dot);
void stack_pop(Point* buf, int* b_size);
#endif
|
C
|
#include<stdio.h>
#include<ctype.h>
int main ()
{
char buff[101];
char *s;
s = buff;
scanf("%s",buff);
while(*s){
*s = toupper(*s);
++s;
}
printf("%s",buff);
}
|
C
|
#include "fft.h"
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
//精度0.000001弧度
void conjugateComplex(int n,complex_S in[],complex_S out[])
{
int i = 0;
for(i=0;i<n;i++)
{
out[i].m_dVirt = -in[i].m_dVirt;
out[i].m_dReal = in[i].m_dReal;
}
}
void absComplex(complex_S f[],double out[],int n)
{
int i = 0;
double t;
for(i=0;i<n;i++)
{
t = f[i].m_dReal * f[i].m_dReal + f[i].m_dVirt * f[i].m_dVirt;
out[i] = sqrt(t);
}
}
void plusComplex(complex_S a,complex_S b,complex_S *c)
{
c->m_dReal = a.m_dReal + b.m_dReal;
c->m_dVirt = a.m_dVirt + b.m_dVirt;
}
void subComplex(complex_S a,complex_S b,complex_S *c)
{
c->m_dReal = a.m_dReal - b.m_dReal;
c->m_dVirt = a.m_dVirt - b.m_dVirt;
}
void mulComplex(complex_S a,complex_S b,complex_S *c)
{
c->m_dReal = a.m_dReal * b.m_dReal - a.m_dVirt * b.m_dVirt;
c->m_dVirt = a.m_dReal * b.m_dVirt + a.m_dVirt * b.m_dReal;
}
void divComplex(complex_S a,complex_S b,complex_S *c)
{
c->m_dReal = (a.m_dReal * b.m_dReal + a.m_dVirt * b.m_dVirt)/(b.m_dReal * b.m_dReal +b.m_dVirt * b.m_dVirt);
c->m_dVirt = (a.m_dVirt * b.m_dReal - a.m_dReal * b.m_dVirt)/(b.m_dReal * b.m_dReal +b.m_dVirt * b.m_dVirt);
}
void printComplex(complex_S* pDst, int n)
{
int i = 0;
for (i = 0; i < n; i++)
{
printf("pDst[%d].m_dReal=%f,pDst[%d].m_dVirt=%f\n",
i, pDst[i].m_dReal, i, pDst[i].m_dVirt);
}
}
static void Wn_i(int n,int i,complex_S *Wn,char flag)
{
Wn->m_dReal = cos(2*PI*i/n);
if(flag == 1)
Wn->m_dVirt = -sin(2*PI*i/n);
else if(flag == 0)
Wn->m_dVirt = -sin(2*PI*i/n);
}
//傅里叶变化
void fft(int N,complex_S f[])
{
complex_S t,wn;//中间变量
int i,j,k,m,n,l,r,M;
int la,lb,lc;
/*----计算分解的级数M=log2(N)----*/
for(i=N,M=1;(i=i/2)!=1;M++);
/*----按照倒位序重新排列原信号----*/
for(i=1,j=N/2;i<=N-2;i++)
{
if(i<j)
{
t=f[j];
f[j]=f[i];
f[i]=t;
}
k=N/2;
while(k<=j)
{
j=j-k;
k=k/2;
}
j=j+k;
}
/*----FFT算法----*/
for(m=1;m<=M;m++)
{
la=pow(2,m); //la=2^m代表第m级每个分组所含节点数
lb=la/2; //lb代表第m级每个分组所含碟形单元数
//同时它也表示每个碟形单元上下节点之间的距离
/*----碟形运算----*/
for(l=1;l<=lb;l++)
{
r=(l-1)*pow(2,M-m);
for(n=l-1;n<N-1;n=n+la) //遍历每个分组,分组总数为N/la
{
lc=n+lb; //n,lc分别代表一个碟形单元的上、下节点编号
Wn_i(N,r,&wn,1);//wn=Wnr
mulComplex(f[lc],wn,&t);//t = f[lc] * wn复数运算
subComplex(f[n],t,&(f[lc]));//f[lc] = f[n] - f[lc] * Wnr
plusComplex(f[n],t,&(f[n]));//f[n] = f[n] + f[lc] * Wnr
}
}
}
}
//傅里叶逆变换
void ifft(int N,complex_S f[])
{
int i=0;
conjugateComplex(N,f,f);
fft(N,f);
conjugateComplex(N,f,f);
for(i=0;i<N;i++)
{
f[i].m_dVirt = (f[i].m_dVirt)/N;
f[i].m_dReal = (f[i].m_dReal)/N;
}
}
int createComplex(double* pSrc, complex_S** pDst, int size)
{
int i = 0;
*pDst = malloc(sizeof(complex_S)*size);
if (NULL == *pDst)
{
printf("malloc complex failed\n");
return -1;
}
//printf("xxxxxxxxxxxxx, *pDst=%p\n", *pDst);
for (i = 0; i < size; i++)
{
(*(*pDst+i)).m_dReal = *(pSrc+i);
(*(*pDst+i)).m_dVirt = 0.0;
}
}
void destroyComplex(complex_S** pDst)
{
free(*pDst);
*pDst = NULL;
}
void getFftAbs(double* pSrc, int size, double* pDst)
{
int i = 0;
double* pTmp = malloc(sizeof(double)*size);
complex_S* pCm = NULL;
createComplex(pSrc, &pCm, size);
fft(size, pCm);
absComplex(pCm, pDst, size);
free(pTmp);
destroyComplex(&pCm);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.