language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/* cdok -- Calcudoku solver/generator
* Copyright (C) 2012 Daniel Beer <dlbeer@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef PRINTER_H_
#define PRINTER_H_
#include <stdio.h>
#include "cdok.h"
/* This structure specifies Unicode characters for the top and bottom
* borders of the puzzle:
*
* start: left corner
* end: right corner
* tee_major: connection with a major vertical grid-line
* tee_minor: connection with a minor vertical grid-line
*/
struct cdok_template_hborder {
uint16_t start;
uint16_t end;
uint16_t tee_major;
uint16_t tee_minor;
};
/* This structure specifies Unicode characters for drawing a puzzle grid:
*
* top: characters for the top border
* bottom: characters for the bottom border
* hline_major: major horizontal gridlines
* hline_minor: minor horizontal gridlines
* vline_major: major vertical gridlines
* vline_minor: minor vertical gridlines
* tee_left_major: connection on left with a major horizontal gridline
* tee_left_minor: connection on left with a minor horizontal gridline
* tee_right_major: connection on right with a major horizontal gridline
* tee_right_minor: connection on right with a minor horizontal gridline
* inners: characters used at the boundary of four cells
*/
struct cdok_template {
struct cdok_template_hborder top;
struct cdok_template_hborder bottom;
uint16_t hline_major;
uint16_t hline_minor;
uint16_t vline_major;
uint16_t vline_minor;
uint16_t tee_left_major;
uint16_t tee_left_minor;
uint16_t tee_right_major;
uint16_t tee_right_minor;
uint16_t inners[16];
};
/* Within the grid, different characters are used to connect gridlines
* depending on whether the lines to the top, left, right or bottom are
* major or minor. This enum gives the appropriate indices into the
* "inners" field of the template for each case.
*
* For example CDOK_TIN_TR is the index of the character used when the
* gridlines to the top and to the right of the character are major, and
* the other two are minor.
*
* Note that not all cases are possible -- it's not possibe for there to
* be only a single major gridline from an inner character.
*/
typedef enum {
CDOK_TIN_0 = 0,
CDOK_TIN_L = 1,
CDOK_TIN_R = 2,
CDOK_TIN_LR = 3,
CDOK_TIN_T = 4,
CDOK_TIN_TL = 5,
CDOK_TIN_TR = 6,
CDOK_TIN_TLR = 7,
CDOK_TIN_B = 8,
CDOK_TIN_BL = 9,
CDOK_TIN_BR = 10,
CDOK_TIN_BLR = 11,
CDOK_TIN_BT = 12,
CDOK_TIN_BTL = 13,
CDOK_TIN_BTR = 14,
CDOK_TIN_BTLR = 15
} cdok_template_inner_t;
/* ASCII template. */
extern const struct cdok_template cdok_template_ascii;
/* Template using Unicode line-drawing characters. */
extern const struct cdok_template cdok_template_unicode;
/* Print a puzzle structure with the given values filled in, using the
* specified template.
*/
void cdok_format_puzzle(const struct cdok_template *templ,
const struct cdok_puzzle *puz,
const uint8_t *values,
FILE *out);
/* Print a puzzle spec that can be read by the parser. */
void cdok_print_puzzle(const struct cdok_puzzle *puz,
const uint8_t *values, FILE *out);
#endif
|
C
|
#include <stdio.h>
#include <stm32f4xx_gpio.h>
#include <stm32f4xx_rcc.h>
#define I2C_TIMEOUT_MAX 0xff
#define MEM_DEVICE_READ_ADDR 0xA0
#define MEM_DEVICE_WRITE_ADDR 0xA1
#define M2402 1
#define M24512 2
void Delay(long i) {
while (i--) { asm ( "nop" ); };
}
void init_GPIO(void) {
GPIO_InitTypeDef GPIO_Output;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
/* Configure PD12, PD13, PD14 and PD15 in output pushpull mode */
GPIO_Output.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;
GPIO_Output.GPIO_Mode = GPIO_Mode_OUT;
GPIO_Output.GPIO_OType = GPIO_OType_PP;
GPIO_Output.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_Output.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOD, &GPIO_Output);
}
void blink(GPIO_TypeDef * port, int pin) {
GPIO_ToggleBits(port, pin);
Delay(0x0000ffff);
GPIO_ToggleBits(port, pin);
Delay(0x0000ffff);
}
int main(void) {
init_GPIO();
while (1) {
blink(GPIOD, GPIO_Pin_12);
blink(GPIOD, GPIO_Pin_13);
blink(GPIOD, GPIO_Pin_14);
blink(GPIOD, GPIO_Pin_15);
}
}
|
C
|
#ifndef _WORK_QUEUE_H_
#define _WORK_QUEUE_H_
/*
*线程池里所有运行和等待的任务都是一个work_t
*由于所有任务都在链表里,所以是一个链表结构
*/
typedef struct work_s
{
/*回调函数,任务运行时会调用此函数,注意也可声明成其它形式*/
void *(*process) (void *arg);
void *arg;/*回调函数的参数*/
struct work_s *next;
} work_t;
/*线程池结构*/
typedef struct work_queue_s
{
pthread_mutex_t queue_lock;
pthread_cond_t queue_ready;
/*链表结构,线程池中所有等待任务*/
work_t *queue_head;
/*是否销毁线程池*/
int shutdown;
pthread_t *threadid;
/*线程池中允许的活动线程数目*/
int max_thread_num;
/*当前等待队列的任务数目*/
int cur_queue_size;
} work_queue_t;
extern work_queue_t *work_queue_init(int max_thread_num);
extern int queue_add_work (work_queue_t *work_queue, void *(*process) (void *arg), void *arg);
extern int work_queue_destroy(work_queue_t *work_queue);
#endif /* _WORK_QUEUE_H_ */
|
C
|
#include "stdio.h"
#include "unistd.h"
#include "stdlib.h"
#include "pthread.h"
#define N 100
#define x 10000000000
long long int contador = 0;
pthread_mutex_t lock_contador = PTHREAD_MUTEX_INITIALIZER;
void* incrementar(void* arg){
int id = *((int *) arg);
printf("Criou uma pthread com id = %d\n", id);
int i;
pthread_mutex_lock(&lock_contador);
for(i = 0 ; i < x ; i++){
contador++;
}
pthread_mutex_unlock(&lock_contador);
}
int main(){
// Podemos inicializar o locker como está ali em cima ou podemos usar:
// pthread_mutex_init(&lock_contador);
pthread_t a[N];
int i;
int* id;
for(i = 0 ; i < N ; i++){
id = (int*) malloc(sizeof(int));
*id = i;
pthread_create(&a[i], NULL, incrementar, (void*) (id));
}
for(i = 0 ; i < N ; i++) {
pthread_join(a[i], NULL);
}
printf("Valor final do contador: %lld\n", contador);
}
|
C
|
#include <iso646.h> // simplified rewrite of the text editor by dwrr on 2304307.024007
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <termios.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
typedef uint64_t nat;
struct word { char* data; nat count; };
static nat m = 0, n = 0, cm = 0, cn = 0, mode = 0;
static struct word* text = NULL;
static bool zero_width(char c) { return (((unsigned char)c) >> 6) == 2; }
static bool stdin_is_empty(void) {
fd_set f; FD_ZERO(&f); FD_SET(0, &f);
struct timeval timeout = {0};
return select(1, &f, 0, 0, &timeout) != 1;
}
static struct termios configure_terminal(void) {
struct termios save = {0};
tcgetattr(0, &save);
struct termios raw = save;
raw.c_oflag &= ~((size_t)OPOST);
raw.c_iflag &= ~((size_t)BRKINT | (size_t)ICRNL | (size_t)INPCK | (size_t)IXON);
raw.c_lflag &= ~((size_t)ECHO | (size_t)ICANON | (size_t)IEXTEN);
tcsetattr(0, TCSAFLUSH, &raw);
return save;
}
static void insert(char c) {
if (cm == m or cn == n) {
text = realloc(text, (n + 1) * sizeof *text);
memmove(text + cn + 1, text + cn, (n - cn) * sizeof *text);
if (cn < n) cn++;
text[cn].data = malloc(m);
text[cn].data[0] = c;
text[cn].count = 1;
n++; cm = 1;
} else if (text[cn].count < m) {
memmove(text[cn].data + cm + 1, text[cn].data + cm, text[cn].count - cm);
text[cn].data[cm++] = c;
text[cn].count++;
} else {
text = realloc(text, (n + 1) * sizeof *text);
memmove(text + cn + 1, text + cn, (n - cn) * sizeof *text);
n++;
text[cn + 1].data = malloc(m);
memmove(text[cn + 1].data, text[cn].data + cm, text[cn].count - cm);
text[cn + 1].count = text[cn].count - cm;
text[cn].data[cm++] = c;
text[cn].count = cm;
}
}
static char delete(void) {
top: if (cm) {
cm--;
char c = text[cn].data[cm];
text[cn].count--;
memmove(text[cn].data + cm, text[cn].data + cm + 1, text[cn].count - cm);
if (text[cn].count) goto r;
n--;
memmove(text + cn, text + cn + 1, (n - cn) * sizeof *text);
text = realloc(text, n * sizeof *text);
if (not n or not cn) goto r;
cn--; cm = text[cn].count;
r: return c;
} else if (cn < n and text[cn].count) {
if (not cn) return 0;
cn--;
cm = text[cn].count;
goto top;
} else return 0;
}
static void move_left(void) {
if (not n) return;
do if (cm) cm--; else if (cn) { cn--; cm = text[cn].count - 1; }
while ( cm < text[cn].count and zero_width(text[cn].data[cm]) or
cm >= text[cn].count and cn + 1 < n and zero_width(text[cn + 1].data[0])
);
}
static void move_right(void) {
if (not n) return;
do if (cm < text[cn].count) cm++; else if (cn < n - 1) { cn++; cm = 1; }
while ( cm < text[cn].count and zero_width(text[cn].data[cm]) or
cm >= text[cn].count and cn + 1 < n and zero_width(text[cn + 1].data[0])
);
}
static void display(nat display_mode) {
static char* screen = NULL;
static nat screen_size = 0, window_rows = 0, window_columns = 0, cursor_column = 0, cursor_row = 0, om = 0, on = 0;
struct winsize window = {0};
ioctl(1, TIOCGWINSZ, &window);
if (not window.ws_row or not window.ws_col) { window.ws_row = 24; window.ws_col = 60; }
if (window.ws_row != window_rows or window.ws_col != window_columns) {
window_rows = window.ws_row;
window_columns = window.ws_col - 1;
screen_size = 32 + (window_rows + 2) * (window_columns * 4 + 5);
screen = realloc(screen, (size_t) screen_size);
}
bool shifted = false;
nat screen_column = 0, screen_row = 0, start = window_columns * 4 + 5, on1 = 0, om1 = 0, i = on, j = om;
int length = snprintf(screen, screen_size, "\033[?25l\033[H");
fill_screen: while (i <= n) {
while (j <= m) {
if (i == cn and j == cm) { cursor_row = screen_row; cursor_column = screen_column; }
if (i >= n or j >= text[i].count) break;
const char c = text[i].data[j];
if (c == 10) { next_char_newline: j++; goto print_newline; }
else if (c == 9) {
do {
if (screen_column >= window_columns) goto next_char_newline; screen_column++;
length += snprintf(screen + length, screen_size, " ");
} while (screen_column % 8);
} else {
if (zero_width(c)) goto print_char;
if (screen_column >= window_columns) goto print_newline; screen_column++;
print_char: length += snprintf(screen + length, screen_size, "%c", c);
}
j++; continue;
print_newline: length += snprintf(screen + length, screen_size, "\033[K");
if (display_mode == 1 or screen_row >= window_rows - 1) goto print_cursor;
length += snprintf(screen + length, screen_size, "\r\n");
screen_row++; screen_column = 0;
if (screen_row == 1) { on1 = i; om1 = j; }
}
i++; j = 0;
}
if (not shifted and cursor_row == window_rows - 1) {
int t = 9; while (screen[t] != 10) t++; screen[t] = 13;
// we can cache the position of the 10 when we save on1 and om1. yay!
cursor_row--; screen_row--; screen_column = 0;
on = on1; om = om1; shifted = true; goto fill_screen;
} else if (not cursor_row) {
}
if (screen_row < window_rows) goto print_newline;
print_cursor: length += snprintf(screen + length, screen_size, "\033[%llu;%lluH\033[?25h", cursor_row + 1, cursor_column + 1);
write(1, screen, (size_t) length);
}
static void interpret_sequence(void) {
char c = 0; read(0, &c, 1);
if (c != '[') return; read(0, &c, 1);
if (c == 'D') move_left();
else if (c == 'C') move_right();
else if (c == 'M') {
read(0, &c, 1);
if (c == 97) { read(0, &c, 1); read(0, &c, 1);
} else if (c == 96) { read(0, &c, 1); read(0, &c, 1);
} else { char str[3] = {0}; read(0, str + 0, 1); read(0, str + 1, 1); }
}
}
int main(int argc, const char** argv) {
m = 10; n = 0; mode = 1;
if (argc == 2) {
FILE* file = fopen(argv[1], "r");
if (not file) {
printf("error: fopen: %s", strerror(errno));
return 0;
}
fseek(file, 0, SEEK_END);
size_t length = (size_t) ftell(file);
char* local_text = malloc(sizeof(char) * length);
fseek(file, 0, SEEK_SET);
fread(local_text, sizeof(char), length, file);
fclose(file);
for (size_t i = 0; i < length; i++) insert(local_text[i]);
cn = 0; cm = 0;
free(local_text);
}
struct termios terminal = configure_terminal();
write(1, "\033[?1049h\033[?1000h\033[7l\033[r", 23);
char c = 0;
loop: display(0);
read(0, &c, 1);
if (c == 27 and stdin_is_empty()) mode = 0;
else if (c == 27) interpret_sequence();
else if (c == 127) while (zero_width(delete()));
else if (c == 13) insert(10);
else insert(c);
if (mode) goto loop;
write(1, "\033[?1049l\033[?1000l\033[7h", 20);
tcsetattr(0, TCSAFLUSH, &terminal);
}
/*
static void debug_display(void) {
printf("\033[H\033[J");
printf("displaying the text { (m=%llu,n=%llu)(cm=%llu,cn=%llu) }: \n", m, n, cm, cn);
for (nat i = 0; i < n; i++) {
printf("%-3llu %c ", i, i == cn ? '*' : ':' );
printf("%-3llu", text[i].count);
if (i and not text[i].count) abort();
for (nat j = 0; j < m; j++) {
putchar(j == cm and i == cn ? '[' : ' ');
if (j < text[i].count)
{ if (((unsigned char)text[i].data[j]) >> 7)
printf("(%02hhx)", (unsigned char) text[i].data[j]);
else printf("%c", text[i].data[j]); }
else printf("-");
putchar(j == cm and i == cn ? ']' : ' ');
}
puts(" | ");
}
puts(".");
printf("(cm=%llu,cn=%llu): ", cm, cn);
}
static void string_display(void) {
printf("\033[H\033[J");
printf("displaying the text { (m=%llu,n=%llu)(cm=%llu,cn=%llu) }: \n", m, n, cm, cn);
for (nat i = 0; i < n; i++) {
if (i and not text[i].count) abort();
for (nat j = 0; j < m; j++)
if (j < text[i].count) printf("%c", text[i].data[j]);
}
puts("");
}
static inline void open_file(const char* given_filename) {
FILE* file = fopen(given_filename, "r");
if (not file) {
sprintf(message, "error: fopen: %s", strerror(errno));
return;
}
fseek(file, 0, SEEK_END);
size_t length = (size_t) ftell(file);
char* text = malloc(sizeof(char) * length);
fseek(file, 0, SEEK_SET);
fread(text, sizeof(char), length, file);
fclose(file);
for (size_t i = 0; i < length; i++) insert(text[i], 0);
free(text);
saved = 1;
autosaved = 1;
mode = 1;
move_top();
// open file 996 this overwrites. these should be strlcpy's!!!!!!!!
// execute 1677
// editor 1812
strlcpy(filename,
given_filename,
sizeof filename);
//strlcpy(location, given_filename, sizeof filename); // todo: seperate out these two things!!!
//sprintf(message, "read %lub", length);
}
// go backwards from on and om at most window_width number of chars, backwards, or until you hit a newline.
// this is the string we want to put before the current screen string.
// prepend a line at the beginning by using the empty space, at the beginning,
// then subtract from start according to how many things you put there.
// remove the last line, by doing length --, until you hit the newline of the second-to-last line.
*/
|
C
|
#include<stdio.h>
int main()
{
int a;
a=2;
{
int a;
a=4;
{
int a;
a=7;
printf("Inner Inner a= %d\n",a);
}
printf("Inner a= %d\n",a);
}
printf("Outer a= %d\n",a);
return 0;
}
|
C
|
#define _POSIX_SOURCE
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
#include <sys/stat.h>
#include <ctype.h>
#include <time.h>
#define PERM 0644
typedef int pipe_t[2];
typedef struct{
int c1; // pid
int c2; // secondo carattere
int c3; // penultimo carattere
} struttura;
int main(int argc,char **argv){
int pid;
int pidFiglio;
int L;
char secondo;
char penultimo;
int nlinea;
int q;
int fd;
int nr;
int status;
int ritorno;
char linea[250];
struttura cur;
pipe_t *piped; // tra padre e figlio
//controllo parametri
if (argc != 3 ){
printf("numero parametri scorretto \n");
exit(1);
}
if ((fd = open(argv[1],O_RDONLY)) <0 ){
printf("errore apertura file \n");
exit(2);
}
L = atoi(argv[2]);
if ( L <= 0 || L > 255 ){
printf("numero non positivo o maggiore di 255 \n");
exit(3);
}
//pipe
piped = malloc( L * sizeof(pipe_t));
if (piped == NULL){
printf("errore allocazione pipe \n");
exit(4);
}
for ( q = 0; q < L ; ++q){
if ( pipe(piped[q]) < 0 ){
printf("errore creazione pipe \n");
exit(5);
}
}
// creazione figli
for (q = 0 ; q < L ; ++q){
if (( pid = fork() ) < 0){
printf("errore creazione figli \n");
exit(6);
}
//codice figlio
if ( pid == 0){
// nel caso di errore nel figlio ritorno -1
//codice figlio
for ( int j = 0; j < L ; ++j){
close(piped[j][0]);
if (q != j){
close(piped[j][1]);
}
}
if ((fd = open(argv[1],O_RDONLY)) <0 ){
printf("errore apertura file \n");
exit(-1);
}
nlinea = 0;
int j = 0;
cur.c1 = getpid();
cur.c2 = 0;
cur.c3 = 0;
while (read(fd,&(linea[j]),1)){
if (linea[j] == '\n'){
++nlinea;
if ( nlinea == q+1){
linea[j+1] = '\0';
secondo = linea[1];
penultimo = linea[j-1];
printf("il figlio di pid %d ha trovato la linea %s \n",cur.c1,linea);
break;
}
j = 0;
}
else{
++j;
}
}
cur.c2 = secondo;
cur.c3 = penultimo;
write(piped[q][1],&cur,sizeof(struttura));
exit(nlinea);
}
}
// codice padre
for ( int j = 0; j < L ; ++j){
close(piped[j][1]);
}
for ( q = 0 ; q < L ; ++q ){
nr = read(piped[q][0],&cur,sizeof(struttura));
if (nr != sizeof(struttura)){
printf("errore in lettura \n");
exit(7);
}
if (cur.c2 == cur.c3){
printf("il figlio di indice %d di pid %d ha travato nella linea %d i caratteri %c e %c uguali (secondo e penultimo) nel file %s \n",q,cur.c1,q+1,cur.c2,cur.c3,argv[1]);
}else printf("il padre non stampa nulla i caratteri sono diversi \n");
}
for( q = 0 ; q < L; ++q){
pidFiglio = wait(&status);
if ( pidFiglio < 0){
printf("errore in wait \n");
exit(8);
}
if ( (status & 0xFF) != 0){
printf ("figlio %d terminato in modo anomalo \n",pidFiglio);
}
else{
status = status >>8;
ritorno = status & 0xFF;
if (ritorno == 255){
printf ( "figlio ha ritornato -1 problemi \n");
}
else
printf ( "figlio %d ha ritornato %d \n",pidFiglio,ritorno);
}
}
exit(0);
}
|
C
|
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char * buf = "This is a test!";
fd = open("./file1", O_RDWR | O_APPEND);
printf("fd = %d\n", fd);
//ssize_t write(int fd, const void *buf, size_t count);
int n_write = write(fd, buf, strlen(buf));
if(n_write != -1){
printf("Write %d byte to file1\n", n_write);
}else{
printf("Write failed!\n");
}
close(fd);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
//#include <unistd.h>
pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
int msg;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
void * c(void *arg)
{
int counter = 0;
while (1)
{
counter++;
pthread_mutex_lock(&mylock);
// 1. release mylock 2. wait for has_product 3. when ok, regain mylock
pthread_cond_wait(&has_product, &mylock);
printf("%s: %d -> %d\n", (char *)arg, counter, msg);
pthread_mutex_unlock(&mylock);
}
}
void * p(void *arg)
{
int counter = 0;
while (1)
{
counter++;
pthread_mutex_lock(&mylock);
msg = rand() % 100;
printf("%s: %d -> %d\n", (char *)arg, counter, msg);
pthread_mutex_unlock(&mylock);
// wake up
pthread_cond_signal(&has_product);
// sleep(1);
}
return NULL;
}
pthread_t pthid;
pthread_t pthid2;
int main(void)
{
pthread_create(&pthid, NULL, p, "produce");
pthread_create(&pthid2, NULL, c, "consume");
pthread_join(pthid, NULL);
pthread_join(pthid2, NULL);
return 0;
}
|
C
|
#include<stdio.h>
double pi=3.14;
void my_fn()
{
pi=3.1416;
}
int main()
{
printf("%lf\n",pi);
my_fn();
printf("%lf\n",pi);
return 0;
}
|
C
|
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <string.h>
#include "outil.h"
#define couleur(param) printf("\033[%sm",param)
#define NOIR "30"
#define ROUGE "31"
#define VERT "32"
#define JAUNE "33"
#define BLEU "34"
#define MAGENTA "35"
#define CYAN "36"
#define BLANC "37"
#define FOND_NOIR "40"
#define FOND_ROUGE "41"
#define FOND_VERT "42"
#define FOND_JAUNE "43"
#define FOND_BLEU "44"
#define FOND_MAGENTA "45"
#define FOND_CYAN "46"
#define FOND_BLANC "47"
#define DEFAUT "0"
/**
* La fonction calcul un prix en fonction d'un code promo
* @param {double} pPrix :
* @param {CodePromo} pCode_promo :
* @return {int} retourn le prix apres REDUC ou SUPPL
*/
double calculPrixCodePromo(double pPrix, CodePromo pCode_promo)
{
if(pCode_promo == REDUC)
{
pPrix = pPrix*(double)(0.80);
return pPrix;
}
else if(pCode_promo == SUPPL)
{
pPrix = pPrix*(double)(1.10);
return pPrix;
}
else
{
return pPrix;
}
}
/**
* La méthode découpe la chaine de caractere à partir d'un délimiteur passé en parametre
* @param {char*} pChaine : Chaine de caractere à traiter
* @param {char} pDelimiteur : Delimiteur à appliquer sur la chaine
* @return {char**} tableau de chaine de caracteres separé par le delimiteur et se finissant par (char*)0
*/
char** diviseur_chaine(char* pChaine, const char pDelimiteur)
{
char** tmpResultat = 0;
size_t tmpCompteur = 0;
char* tmpChaine = pChaine;
char* tmpLigneCourante = 0;
char tmpDelimiteur[2];
size_t tmpId;
char* token;
tmpDelimiteur[0] = pDelimiteur;
tmpDelimiteur[1] = 0;
/*On compte le nombre de chaine séparé par un délimiteur*/
while (*tmpChaine)
{
if (pDelimiteur == *tmpChaine)
{
tmpCompteur++;
tmpLigneCourante = tmpChaine;
}
tmpChaine++;
}
/*Si le pointeur se trouve dans la chaine il reste un mot à prendre en compte*/
tmpCompteur += tmpLigneCourante < (pChaine + strlen(pChaine) - 1);
/*Puis on ajoute un pour le mot 0*/
tmpCompteur++;
/*On alloue la mémoire au tableau resultat celon le nombre de mots*/
tmpResultat = malloc(sizeof(char*) * tmpCompteur);
tmpId = 0;
token = strtok(pChaine, tmpDelimiteur);
/*tant qu'on a des mots on remplit notre tableau*/
while (token)
{
*(tmpResultat + tmpId++) = strdup(token);
token = strtok(0, tmpDelimiteur);
}
/*on ajoute le mot 0*/
*(tmpResultat + tmpId) = 0;
return tmpResultat;
}
/**
* Fonction qui transforme un {horaire} en {char*}
* @param {horaire} pNum, le numero à transformer
* @return {char*} l'horaire transformé
*/
char* transformer_horaire_en_string(horaire pHoraire) {
char* chaine_horaire = (char*) malloc(7*sizeof(char));
/*Concat de l'heure sous forme hh:mm*/
if (pHoraire.heure < 10) {
if (pHoraire.minute < 10)
sprintf(chaine_horaire, "0%d:0%d", pHoraire.heure, pHoraire.minute);
else
sprintf(chaine_horaire, "0%d:%d", pHoraire.heure, pHoraire.minute);
}
else {
if (pHoraire.minute < 10)
sprintf(chaine_horaire, "%d:0%d", pHoraire.heure, pHoraire.minute);
else
sprintf(chaine_horaire, "%d:%d", pHoraire.heure, pHoraire.minute);
}
return chaine_horaire;
}
/**
* La fonction transforme un char* "heure:minute" en int* {heure, minute}
* @param {char*} pHeure :
* @return {int*} pointeur de int contenant les valeur dans pHeure
*/
int* atoiHeure(char* pHeure)
{
char** tmpTableauHoraire;
int* tmpTableauResult;
tmpTableauResult = (int*)malloc(2*sizeof(int));
tmpTableauHoraire = diviseur_chaine(pHeure,':');
tmpTableauResult[0] = atoi(tmpTableauHoraire[0]);
tmpTableauResult[1] = atoi(tmpTableauHoraire[1]);
return tmpTableauResult;
}
/**
* La fonction calcul l'ecart entre 2 horaires differents
* @param {int*} pHeureMin :
* @param {int*} pHeureMax :
* @return {int} retourn la difference convertie en minutes
*/
int calculHeurePtrPtr(int* pHoraireMin, int* pHoraireMax)
{
return 60*(pHoraireMax[0]-pHoraireMin[0]) + (pHoraireMax[1]-pHoraireMin[1]);
}
/**
* La fonction calcul l'ecart entre 2 horaires differents
* @param {int} pHeureMinHeure :
* @param {int} pHeureMinMinute :
* @param {int*} pHeureMax :
* @return {int} retourn la difference convertie en minutes
*/
int calculHeureIntPtr(int pHoraireMinHeure, int pHoraireMinMinute, int* pHoraireMax)
{
return 60*(pHoraireMax[0]-pHoraireMinHeure) + (pHoraireMax[1]-pHoraireMinMinute);
}
void printc(char * pChaine,char* COULEUR){
couleur(COULEUR);
printf("%s",pChaine);
couleur(DEFAUT);
}
void printfc(char * pChaine,char* COULEUR, char* FOND_COULEUR){
couleur(COULEUR);
couleur(FOND_COULEUR);
printf("%s",pChaine);
couleur(DEFAUT);
}
|
C
|
#include "libftprintf.h"
int ft_dec_minus(int width, int precision, long d, int dot)
{
int t;
int len;
len = 0;
t = ft_cast_putnbr(d);
if (d == 0 && dot && !precision)
{
len += ftt_putchar(' ', width);
return (len);
}
if (!precision || precision <= t)
{
len += ftt_putnbr(d);
len += ftt_putchar(' ', width - t);
}
else
{
len += ftt_putchar('0', precision - t);
len += ftt_putnbr(d);
len += ftt_putchar(' ', (width - t - (precision - t)));
}
return (len);
}
int ft_dec_zero(int width, long d, int dot)
{
int t;
int len;
len = 0;
t = ft_cast_putnbr(d);
if (d == 0 && !dot && width)
{
ftt_putchar('0', width);
return (width);
}
len += ftt_putchar('0', width - t);
len += ftt_putnbr(d);
return (len);
}
int ft_dec_neg(int width, int precision, long d)
{
int t;
int len;
d *= -1;
len = 0;
t = ft_cast_putnbr(d);
if (!precision || precision <= t)
len += ftt_putchar(' ', width - t - 1);
else
len += ftt_putchar(' ', (width - t - 1 - (precision - t)));
len += ftt_putchar('-', 1);
len += ftt_putchar('0', precision - t);
len += ftt_putnbr(d);
return (len);
}
int ft_dec_minus_neg(int width, int precision, long d)
{
int t;
int len;
d *= -1;
len = 0;
t = ft_cast_putnbr(d);
if (!precision || precision <= t)
{
len += ftt_putchar('-', 1);
len += ftt_putnbr(d);
len += ftt_putchar(' ', width - t - 1);
}
else
{
len += ftt_putchar('-', 1);
len += ftt_putchar('0', precision - t);
len += ftt_putnbr(d);
len += ftt_putchar(' ', (width - t - 1 - (precision - t)));
}
return (len);
}
int ft_dec_zero_neg(int width, long d)
{
int t;
int len;
d *= -1;
len = 0;
t = ft_cast_putnbr(d);
len += ftt_putchar('-', 1);
len += ftt_putchar('0', width - t - 1);
len += ftt_putnbr(d);
return (len);
}
|
C
|
#include<stdio.h>
#include<conio.h>
#define MAX 5
typedef struct
{
int key;
}element;
int top=-1,item;
element s[MAX];
void push(int,int *);
int pop(int*);
void display(int *);
void main()
{
int ch,f;
clrscr();
do
{
clrscr();
printf("\n\t 1.. Push ");
printf("\n\t 2.. Pop ");
printf("\n\t 3.. Display ");
printf("\n\t 4.. Exit ");
printf("\n Enter Your Choice :");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n Enter An Element :");
scanf("%d",&item);
push(item,&top);
break;
case 2:
f=pop(&top);
if(f==0)
{
printf("\n Stack Is Empty ");
}
else
{
printf("\n The Deleted Item Is : %d",f);
}
break;
case 3:
display(&top);
break;
case 4:
exit(0);
}
getch();
}while(ch!=4);
getch();
}
void push(int item,int *top)
{
if(*top==MAX-1)
{
printf("\n Stack Is Full ");
}
else
{
s[++(*top)].key=item;
printf("\n One Element Is Added ");
}
}
int pop(int *top)
{
if(*top==-1)
{
return(0);
}
else
{
return(s[(*top)--].key);
}
}
void display(int *top)
{
int i;
if(*top<0)
{
printf("\n The Stack Is Empty ");
}
for(i=0;i<=*top;i++)
{
printf("%5d",s[i]);
}
}
|
C
|
# include<stdio.h>
# include<conio.h>
void main()
{
int i,j,x[10],no,last,cnt=0,temp,k;
clrscr();
printf("\n\t :===>How Many No can be Entered:----->");
scanf("%d",&no);
for(i=0;i<no;i++)
{
printf("\n\t Enter the No:----->");
scanf("%d",&x[i]);
}
printf("\n");
printf("\n\t :===>Array Before Bubble:----->");
for(i=0;i<no;i++)
{
printf("%d,",x[i]);
}
printf("\n");
last=no-1;
for(i=0;i<no-1;i++)
{
for(j=0;j<last;j++)
{
if(x[j]>x[j+1])
{
temp=x[j];
x[j]=x[j+1];
x[j+1]=temp;
cnt++;
}
printf("\n\t Pass [%d]:",i+1);
for(k=0;k<no;k++)
{
printf("%d,",x[k]);
}
}
printf("\n");
if(cnt==0)
{
break;
}
else
{
last--;
}
}
printf("\n\t --------:-Bubble Sort-:---------");
printf("\n");
printf("\n\t :===>Array After Sorting:----->");
for(i=0;i<no;i++)
{
printf("%d,",x[i]);
}
getch();
}
|
C
|
#include<stdio.h>
#include<ctype.h>
#pragma warning(disable:4996)
int main()
{
int i = 0;
char str[100];
printf("ȯϰ ڿ ԷϽÿ : ");
gets(str);
for (i = 0; str[i]; i++){
if (islower(str[i]))
str[i] = toupper(str[i]);
else if (isupper(str[i]))
str[i] = tolower(str[i]);
}
puts(str);
}
|
C
|
/// EXERCICIO 2 ///
/*
ALUNO: EDGAR DOS REIS
GRR: 20111758
Contadores:
Modo UP/DOWN
t = 1.5 s
f = 1M hz
div = 8
T' = 8u s
N = 46.875
Modo UP
t = 0.4 s
f = 1M hz
div = 8
T' = 8u s
N = 50.000
Modo UP/DOWN
t = 0.5 s
f = 1M hz
div = 8
T' = 8u s
N = 15.625
*/
#include <msp430g2553.h>
unsigned int x = 0; // variavel para DEBAUNCING
unsigned int flag_button = 0; // flag para acionamento do botão
unsigned int count = 0; // Contador p/ 1.5s
/* Configurar uC */
void Configurar_uC(void)
{
WDTCTL = WDTPW + WDTHOLD; //Desabilita o watchdog
BCSCTL1 = CALBC1_1MHZ; // Configuração do clock para 1MHz
DCOCTL = CALDCO_1MHZ; // Configuração do clock para 1MHz
P1DIR |= 0x41; // seta os leds como saida
P1REN |= 0x08; // Habilita resistor de pullup/down na chave s2
P1OUT |= 0x08; // Define resistor de pull up
/* Configurar interrupção P1.3 */
P1IE = 0x08; // Habilita interrupção do boão p1.3
P1IES = 0x08; // Habilita interrupção na borda de descida
P1IFG = 0x00; // Zera a flag de interrupção da porta 1
/* Configurar Timer0_A */
TA0CTL |= TASSEL_2 + ID_3 + MC_3; // clock= SMCLK, div= /8, MC_3 = Up/Down mode => TACCR0
TA0CCR0 = 46875; // 46875 * 2 (UP/Down) * 2 * 8 us --> 1.5 s em Modo UP/DOWN
TA0CCTL0 |= CCIE; // Habilita captura/comparação com relação a IFG
/* Configurar Timer1_A */
TA1CTL |= TASSEL_2 + ID_3 + MC_1; // clock= SMCLK, div= /8, MC_1 = Up mode => TACCR0
TA1CCR0 = 50000; // 50.000 (UP) * 8 us --> 0.4 s em Modo UP
TA1CCTL0 |= CCIE; // Habilita captura/comparação com relação a IFG
__enable_interrupt(); // Habilitar Interrupções
}
/* PROGRAMA PRINCIPAL */
void main(void)
{
Configurar_uC(); // Configurações
while(1) // Loop Infinito
{
}
}
// Interrupção do P1.3
#pragma vector = PORT1_VECTOR
__interrupt void interr_P1(void)
{
/* DEBAUNCING */
__delay_cycles(5); // delay de 5ms
x = 1; // garante que irá entrar no while
while (x == 1)
if ((P1IN & 0x08) == 0) // testa se o botão p1.3 está pressionado
{
x = 0; // muda estatus de x para sair do while
}
else
{ // se não estiver pressionado volta a conferir
x = 1;
}
__delay_cycles(5); // delay de 5ms
//P1OUT = ~0x41;
flag_button ^= 1; // Inverte flag_pisca
if (flag_button == 1)
{
TA0CTL |= MC_0; // Para Timer
TA0CCR0 = 15625; // 15625 * 2 (UP/Down) * 2 * 8 us --> 0.5 s em Modo UP/DOWN
TA0CTL |= MC_3; // Inicia timer no modo Up/Down
P1OUT &= ~0x41; // Apaga os Leds para nova sequência
}
else
{
TA0CTL |= MC_0; // Para Timer
TA0CCR0 = 46875; // 46875 * 2 (UP/Down) * 2 * 8 us --> 1.5 s em Modo UP/DOWN
TA0CTL |= MC_3; // Inicia timer no modo Up/Down
}
P1IFG = 0x00; // Zera a flag de interrupção da porta 1
}
/* Interrupção do Timer0_A */
#pragma vector = TIMER0_A0_VECTOR
__interrupt void interrupt_0(void)
{
if (flag_button == 0) // Verifica se foi pressionado
{
count++; // Contador para gerar 1.5 s
if (count == 2)
{
P1OUT ^= 0x01; // Inverte LED
count = 0; // Zera contador
}
}
else
{
P1OUT ^= 0x41; // Inverte LED
}
TA0CCTL0 &=~ CCIFG; //Limpar flag de interrupção
P1IFG = 0x00; // Zera a flag de interrupção da porta 0
}
/* Interrupção do Timer1_A */
#pragma vector = TIMER1_A0_VECTOR
__interrupt void interrupt_1(void)
{
if (flag_button == 0) // Verifica se o botão foi pressionado
{
P1OUT ^= 0x40; // Inverte o LED
}
TA1CCTL0 &=~ CCIFG; //Limpar flag de interrupção
P1IFG = 0x00; // Zera a flag de interrupção da porta 1
}
|
C
|
#include<stdio.h>
void main()
{
//unsigned short int x = 65536;
//signed short x = 32768;
unsigned short x = -4;
clrscr();
printf("%d\n", x); // signed
printf("%u\n", x); // unsigned
getch();
}
|
C
|
int main()
{
int n;
int i,j;
printf("\n Enter 5 integers in a single line separated by space (1-30):\n");
for(i=1;i<=5;i++)
{
scanf("%d",&n);
printf("\n%2d ",n);
for(j=1;j<=n;j++)
printf("*");
}
}
|
C
|
/*4. Faa um programa que leia um nmero do tipo float e depois o exiba na tela.*/
#include <stdio.h>
main ()
{
float n1;
printf("Digite um numero:\n");
scanf ("%f",&n1);
printf("%f",n1);
}
|
C
|
#include "goatee_hashmap.h"
#define TOPBIT (1 << 7)
#define POLYNOMIAL 0x9b
#define HMSIZE 256
static unsigned char table8[256];
static int tinit = 0;
void crc8_init() {
int dividend;
unsigned char bit, remainder;
tinit = 1;
/*
* Compute the remainder of each possible dividend.
*/
for (dividend = 0; dividend < 256; dividend++) {
/*
* Start with the dividend followed by zeros.
*/
remainder = dividend;
/*
* Perform modulo-2 division, a bit at a time.
*/
for (bit = 8; bit > 0; --bit) {
/*
* Try to divide the current data bit.
*/
if (remainder & TOPBIT) {
remainder = (remainder << 1) ^ POLYNOMIAL;
} else {
remainder = (remainder << 1);
}
}
/*
* Store the result into the table.
*/
table8[dividend] = remainder;
}
}
unsigned char crc8_block(const unsigned char *bytes, long byteLen) {
long rpos = 0;
unsigned char remainder = 0, data;
/*
* Divide the message by the polynomial, a byte at a time.
*/
for (rpos = 0; rpos < byteLen; ++rpos) {
data = bytes[rpos] ^ remainder;
remainder = table8[data] ^ (remainder << 8);
}
/*
* The final remainder is the CRC.
*/
return remainder;
}
goatee_hashmap *goatee_hashmap_new() {
goatee_hashmap *ret;
goatee_hashmap_entry_list *buckets;
if (!tinit) crc8_init();
/* clear initial values */
ret = calloc(1, sizeof(goatee_hashmap));
buckets = calloc(HMSIZE, sizeof(goatee_hashmap_entry));
if (ret == NULL || buckets == NULL) return NULL;
ret->buckets = buckets;
return ret;
}
void goatee_hashmap_put(goatee_hashmap *in, const char *key, void *value) {
unsigned char crc8;
goatee_hashmap_entry_list *hel;
goatee_hashmap_entry *he;
/* get hash value */
crc8 = crc8_block((const unsigned char *)key, (long)strlen(key));
hel = &in->buckets[crc8];
/* reallocate memory if necessary */
if (hel->vroom < ++(hel->vlen)) {
hel->vroom = (hel->vroom == 0 ? 4 : hel->vroom*2);
he = realloc(hel->values, hel->vroom * sizeof(goatee_hashmap_entry));
if (he == NULL) {
return; /* TODO: Throw exception */
}
hel->values = he;
}
/* jump to end of goatee_hashmap entry list */
he = &hel->values[hel->vlen-1];
he->key = strdup(key);
he->value = value;
/* success */
}
void *goatee_hashmap_get(goatee_hashmap *in, const char *key) {
unsigned char crc8;
goatee_hashmap_entry_list *hel;
goatee_hashmap_entry *he;
int i;
/* get hash value */
crc8 = crc8_block((const unsigned char *)key, (long)strlen(key));
hel = &in->buckets[crc8];
/* loop through all the key/value pairs with that hash */
for (i = 0; i < hel->vlen; i++) {
he = &hel->values[i];
if (!strcmp(key, he->key)) goto found; /* found exact key */
}
return NULL;
/* success */
found:
return he->value;
}
int goatee_hashmap_iterate(goatee_hashmap *in, goatee_hashmap_iterator iter, void *context) {
goatee_hashmap_entry_list *hel;
goatee_hashmap_entry *he;
int i, j;
/* loop through all the buckets */
for (i = 0; i < HMSIZE; i++) {
hel = &in->buckets[i];
/* loop through all the key/value pairs */
for (j = 0; j < hel->vlen; j++) {
he = &hel->values[j];
/* call the function */
if (iter(context, he->key, he->value))
return -1;
}
}
return 0;
}
void goatee_hashmap_empty(goatee_hashmap *in) {
goatee_hashmap_entry_list *hel;
goatee_hashmap_entry *he;
int i, j;
/* loop through all the buckets */
for (i = 0; i < HMSIZE; i++) {
hel = &in->buckets[i];
/* loop through all the key/value pairs */
for (j = 0; j < hel->vlen; j++) {
he = &hel->values[j];
/* free the key */
free(he->key);
}
/* reset the key/value pairs array */
free(hel->values);
hel->values = NULL;
hel->vlen = 0;
hel->vroom = 0;
}
}
void goatee_hashmap_destroy(goatee_hashmap *in) {
/* empty goatee_hashmap */
goatee_hashmap_empty(in);
/* clean up bucket storage */
free(in->buckets);
free(in);
}
|
C
|
#include "holberton.h"
/**
*add - adds two integers
*@a: it is int parameter
*@b: it is int parameter
*Description: This function adds two functions
*Return: return a + b
*/
int add(int a, int b)
{
return (a + b);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
float a, b;
a = atoi(argv[1]);
scanf("%f", &b);
printf("%f\n", b * a);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/**
* 伯努利实验,实验n次,出现k次的概率
* 非递归方式实现,采用二维数组存储已经计算过的值
* 时间复杂度: O(n * k) 空间复杂度: O(n * k)
*
* @param n
* @param k
* @param p
* @return
*/
double binomialArray(int n, int k, double p) {
double array[n + 1][k + 1];
// 初始化数组
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= k; j++) {
array[i][j] = 0;
}
}
array[0][0] = 1.0;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= k; j++) {
if (j > i) {
break;
}
if (i - 1 >= 0) {
array[i][j] += (1.0 - p) * array[i - 1][j];
if (j - 1 >= 0) {
array[i][j] += p * array[i - 1][j - 1];
}
}
}
}
return array[n][k];
}
int main() {
int N, K = 5;
double p = 0.5;
double ret = binomialArray(N, K, p);
printf("结果为:%d\n", ret);
return 0;
}
|
C
|
#include <stdio.h>
#include "avi.h"
#include <string.h>
#define PAD_EVEN(x) ( ((x)+1) & ~1 )
#define strncasecmp(x,y,z) _tcsnicmp(x,y,z)
//static size_t avi_read(int fd, char *buf, size_t len)
//{
// size_t n = 0;
// size_t r = 0;
//
// while (r < len) {
// n = read(fd, buf + r, len - r);
//
// if (n <= 0)
// return r;
// r += n;
// }
//
// return r;
//}
long AVI_video_frames(avi *AVI)
{
return AVI->video_frames;
}
int AVI_video_width(avi *AVI)
{
return AVI->width;
}
int AVI_video_height(avi *AVI)
{
return AVI->height;
}
double AVI_frame_rate(avi *AVI)
{
return AVI->fps;
}
char* AVI_video_compressor(avi *AVI)
{
return AVI->compressor2;
}
static size_t avi_read(FILE * fp, char *buf, size_t len)
{
size_t n = 0;
size_t r = 0;
n = fread(buf, sizeof(char), len, fp);
return n;
}
/* Copy n into dst as a 4 byte, little endian number.
Should also work on big endian machines */
static void long2str(unsigned char *dst, int n)
{
dst[0] = (n) & 0xff;
dst[1] = (n >> 8) & 0xff;
dst[2] = (n >> 16) & 0xff;
dst[3] = (n >> 24) & 0xff;
}
/* Convert a string of 4 or 2 bytes to a number,
also working on big endian machines */
static unsigned long str2ulong(unsigned char *str)
{
return (str[0] | (str[1] << 8) | (str[2] << 16) | (str[3] << 24));
}
static unsigned long str2ushort(unsigned char *str)
{
return (str[0] | (str[1] << 8));
}
static int avi_add_index_entry(avi *AVI, unsigned char *tag, long flags, unsigned long pos, unsigned long len)
{
void *ptr;
if (AVI->n_idx >= AVI->max_idx) {
ptr = realloc((void *)AVI->idx, (AVI->max_idx + 4096) * 16);
if (ptr == 0) {
return -1;
}
AVI->max_idx += 4096;
AVI->idx = (unsigned char((*)[16])) ptr;
}
/* Add index entry */
// fprintf(stderr, "INDEX %s %ld %lu %lu\n", tag, flags, pos, len);
memcpy(AVI->idx[AVI->n_idx], tag, 4);
long2str(AVI->idx[AVI->n_idx] + 4, flags);
long2str(AVI->idx[AVI->n_idx] + 8, pos);
long2str(AVI->idx[AVI->n_idx] + 12, len);
/* Update counter */
AVI->n_idx++;
if (len > AVI->max_len) AVI->max_len = len;
return 0;
}
void main()
{
AVI_open_input_file("D:\\Downloads\\samples\\flame.avi", 1);
getchar();
}
avi *AVI_open_input_file(char *filename, int getIndex) {
avi * AVI = NULL;
AVI = (avi *)malloc(sizeof(avi));
if (AVI == NULL)
{
free(AVI);
return 0;
}
memset((void *)AVI, 0, sizeof(avi));
//
FILE * fp;
AVI->fp = fopen(filename, "rb");
if (!AVI->fp)
{
free(AVI);
return 0;
}
avi_parse_input_file(AVI, getIndex);
}
int avi_parse_input_file(avi *AVI, int getIndex)
{
long i, n, rate, scale, idx_type;
unsigned char * hdrl_data;
long header_offset = 0, hdrl_len = 0;
long nvi, ioff;
int j;
int lasttag = 0;
int vids_strh_seen = 0;
int vids_strf_seen = 0;
int auds_strh_seen = 0;
// int auds_strf_seen = 0;
int num_stream = 0;
char data[256];
if (avi_read(AVI->fp, data, 12) != 12)
return 0;
if (strncasecmp(data, "RIFF", 4) != 0 ||
strncasecmp(data + 8, "AVI ", 4) != 0) return 0;
/* Go through the AVI file and extract the header list,
the start position of the 'movi' list and an optionally
present idx1 tag */
hdrl_data = 0;
while (1)
{
if (avi_read(AVI->fp, data, 8) != 8)
break; /* We assume it's EOF */
n = str2ulong((unsigned char *)data + 4);
n = PAD_EVEN(n);
if (strncasecmp(data, "LIST", 4) == 0)
{
if (avi_read(AVI->fp, data, 4) != 4)
return 0;
n -= 4;
if (strncasecmp(data, "hdrl", 4) == 0)
{
hdrl_len = n;
hdrl_data = (unsigned char *)malloc(n);
if (hdrl_data == 0)
return;
// offset of header
// header_offset = fseek(AVI->fp, 0, SEEK_CUR);
header_offset = ftell(AVI->fp);
if (avi_read(AVI->fp, (char *)hdrl_data, n) != n)
return 0;
}
else if (strncasecmp(data, "movi", 4) == 0)
{
// AVI->movi_start = fseek(AVI->fp, 0, SEEK_CUR);
AVI->movi_start = ftell(AVI->fp);
fseek(AVI->fp, n, SEEK_CUR);
}
else
fseek(AVI->fp, n, SEEK_CUR);
}
else if (strncasecmp(data, "idx1", 4) == 0)
{
/* n must be a multiple of 16, but the reading does not
break if this is not the case */
AVI->n_idx = AVI->max_idx = n / 16;
AVI->idx = (unsigned char((*)[16]))
malloc(n);
if (AVI->idx == 0)
return 0;
if (avi_read(AVI->fp, (char *)AVI->idx, n) != n)
return 0;
}
else
fseek(AVI->fp, n, SEEK_CUR);
}
if (!hdrl_data)
return 0;
if (!AVI->movi_start)
return 0;
/* Interpret the header list */
for (i = 0; i < hdrl_len;)
{
/* List tags are completly ignored */
if (strncasecmp((char *)hdrl_data + i, "LIST", 4) == 0) { i += 12; continue; }
n = str2ulong(hdrl_data + i + 4);
n = PAD_EVEN(n);
/* Interpret the tag and its args */
if (strncasecmp((char *)hdrl_data + i, "strh", 4) == 0)
{
i += 8;
if (strncasecmp((char *)hdrl_data + i, "vids", 4) == 0 && !vids_strh_seen)
{
memcpy(AVI->compressor, hdrl_data + i + 4, 4);
AVI->compressor[4] = 0;
// ThOe
AVI->v_codech_off = header_offset + i + 4;
scale = str2ulong((unsigned char *)hdrl_data + i + 20);
rate = str2ulong(hdrl_data + i + 24);
if (scale != 0) AVI->fps = (double)rate / (double)scale;
AVI->video_frames = str2ulong(hdrl_data + i + 32);
AVI->video_strn = num_stream;
AVI->max_len = 0;
vids_strh_seen = 1;
lasttag = 1; /* vids */
}
else if (strncasecmp((char *)hdrl_data + i, "auds", 4) == 0 && !auds_strh_seen)
{
}
}
else if (strncasecmp((char *)hdrl_data + i, "strf", 4) == 0)
{
i += 8;
if (lasttag == 1)
{
AVI->width = str2ulong(hdrl_data + i + 4);
AVI->height = str2ulong(hdrl_data + i + 8);
vids_strf_seen = 1;
//ThOe
AVI->v_codecf_off = header_offset + i + 16;
memcpy(AVI->compressor2, hdrl_data + i + 16, 4);
AVI->compressor2[4] = 0;
}
lasttag = 0;
}
else
{
i += 8;
lasttag = 0;
}
i += n;
}
free(hdrl_data);
if (!vids_strh_seen || !vids_strf_seen)
return 0;
AVI->video_tag[0] = AVI->video_strn / 10 + '0';
AVI->video_tag[1] = AVI->video_strn % 10 + '0';
AVI->video_tag[2] = 'd';
AVI->video_tag[3] = 'b';
fseek(AVI->fp, AVI->movi_start, SEEK_SET);
/* get index if wanted */
if (!getIndex)
return(0);
/* if the file has an idx1, check if this is relative
to the start of the file or to the start of the movi list */
idx_type = 0;
if (AVI->idx)
{
long pos, len;
/* Search the first videoframe in the idx1 and look where
it is in the file */
for (i = 0; i < AVI->n_idx; i++)
if (strncasecmp((char *)AVI->idx[i], (char *)AVI->video_tag, 3) == 0) break;
if (i >= AVI->n_idx) return 0;
pos = str2ulong(AVI->idx[i] + 8);
len = str2ulong(AVI->idx[i] + 12);
fseek(AVI->fp, pos, SEEK_SET);
if (avi_read(AVI->fp, data, 8) != 8) return 0;
if (strncasecmp((char *)data, (char *)AVI->idx[i], 4) == 0 &&
str2ulong((unsigned char *)data + 4) == len)
{
idx_type = 1; /* Index from start of file */
}
else
{
fseek(AVI->fp, pos + AVI->movi_start - 4, SEEK_SET);
if (avi_read(AVI->fp, data, 8) != 8) return 0;
if (strncasecmp((char *)data, (char *)AVI->idx[i], 4) == 0 && str2ulong((unsigned char *)data + 4) == len)
{
idx_type = 2; /* Index from start of movi list */
}
}
/* idx_type remains 0 if neither of the two tests above succeeds */
}
if (idx_type == 0)
{
/* we must search through the file to get the index */
fseek(AVI->fp, AVI->movi_start, SEEK_SET);
AVI->n_idx = 0;
while (1)
{
if (avi_read(AVI->fp, data, 8) != 8) break;
n = str2ulong((unsigned char *)data + 4);
/* The movi list may contain sub-lists, ignore them */
if (strncasecmp(data, "LIST", 4) == 0)
{
fseek(AVI->fp, 4, SEEK_CUR);
continue;
}
/* Check if we got a tag ##db, ##dc or ##wb */
if (((data[2] == 'd' || data[2] == 'D') &&
(data[3] == 'b' || data[3] == 'B' || data[3] == 'c' || data[3] == 'C'))
|| ((data[2] == 'w' || data[2] == 'W') &&
(data[3] == 'b' || data[3] == 'B')))
{
avi_add_index_entry(AVI, (unsigned char *)data, 0, fseek(AVI->fp, 0, SEEK_CUR) - 8, n);
}
fseek(AVI->fp, PAD_EVEN(n), SEEK_CUR);
}
idx_type = 1;
}
/* Now generate the video index and audio index arrays */
nvi = 0;
for (i = 0; i < AVI->n_idx; i++) {
if (strncasecmp((char *)AVI->idx[i], (char *)AVI->video_tag, 3) == 0) nvi++;
}
AVI->video_frames = nvi;
// fprintf(stderr, "chunks = %ld %d %s\n", AVI->track[0].audio_chunks, AVI->anum, AVI->track[0].audio_tag);
CHUNK * chunk;
if (AVI->video_frames == 0)
return 0;
AVI->video_index = (video_index_entry *)malloc(nvi * sizeof(video_index_entry));
chunk = (CHUNK *)malloc(nvi * sizeof(CHUNK));
if (AVI->video_index == 0 || chunk == 0)
return 0;
nvi = 0;
ioff = idx_type == 1 ? 8 : AVI->movi_start + 4;
for (i = 0; i < AVI->n_idx; i++) {
//video
if (strncasecmp((char *)AVI->idx[i], (char *)AVI->video_tag, 3) == 0) {
AVI->video_index[nvi].key = str2ulong(AVI->idx[i] + 4);
AVI->video_index[nvi].pos = str2ulong(AVI->idx[i] + 8) + ioff;
AVI->video_index[nvi].len = str2ulong(AVI->idx[i] + 12);
/*chunk[nvi].data = (unsigned char *)malloc(chunk[nvi].dwSize * sizeof(unsigned char *));
fseek(AVI->fp, AVI->video_index[nvi].pos, SEEK_SET);
fread(chunk[nvi].data, sizeof(chunk[nvi].data), 1, AVI->fp);*/
fpp * f = get_frame(AVI, AVI->video_index[nvi].key, 0, 0, 0);
nvi++;
}
}
/* Reposition the file */
fseek(AVI->fp, AVI->movi_start, SEEK_SET);
AVI->video_pos = 0;
return(0);
}
fpp * get_frame(avi * cell_file, int frame_num, int cropped, int scaled, int converted)
{
// variable
int dummy;
int width = AVI_video_width(cell_file);
int height = AVI_video_height(cell_file);
int status;
// There are 600 frames in this file (i.e. frame_num = 600 causes an error)
AVI_set_video_position(cell_file, frame_num);
//Read in the frame from the AVI
char* image_buf = (char*)malloc(width * height * sizeof(char));
status = AVI_read_frame(cell_file, image_buf, &dummy);
if (status == -1) {
exit(-1);
}
// The image is read in upside-down, so we need to flip it
fpp* image_chopped;
image_chopped = chop_flip_image(image_buf,
height,
width,
cropped,
scaled,
converted);
// free image buffer
free(image_buf);
// return
return image_chopped;
}
fpp* chop_flip_image(char *image,
int height,
int width,
int cropped,
int scaled,
int converted) {
// fixed dimensions for cropping or not cropping, square vertices starting from initial point in top left corner going down and right
int top;
int bottom;
int left;
int right;
if (cropped == 1) {
top = 0;
bottom = 0;
left = 0;
right = 0;
}
else {
top = 0;
bottom = height - 1;
left = 0;
right = width - 1;
}
// dimensions of new cropped image
int height_new = bottom - top + 1;
int width_new = right - left + 1;
// counters
int i, j;
// allocate memory for cropped/flipped frame
fpp* result = (fpp *)malloc(height_new * width_new * sizeof(fpp));
// crop/flip and scale frame
fpp temp;
if (scaled) {
fpp scale = 1.0 / 255.0;
for (i = 0; i < height_new; i++) { // rows
for (j = 0; j < width_new; j++) { // colums
temp = (fpp)image[((height - 1 - (i + top)) * width) + (j + left)] * scale;
if (temp < 0) {
result[i*width_new + j] = temp + 256;
}
else {
result[i*width_new + j] = temp;
}
}
}
}
else {
for (i = 0; i < height_new; i++) { // rows
for (j = 0; j < width_new; j++) { // colums
temp = (fpp)image[((height - 1 - (i + top)) * width) + (j + left)];
if (temp < 0) {
result[i*width_new + j] = temp + 256;
}
else {
result[i*width_new + j] = temp;
}
}
}
}
// convert storage method (from row-major to column-major)
fpp* result_converted = (fpp *)malloc(height_new * width_new * sizeof(fpp));
if (converted == 1) {
for (i = 0; i < width_new; i++) { // rows
for (j = 0; j < height_new; j++) { // colums
result_converted[i*height_new + j] = result[j*width_new + i];
}
}
}
else {
result_converted = result;
}
free(result);
// return
return result_converted;
}
long AVI_read_frame(avi *AVI, char *vidbuf, int *keyframe)
{
long n;
if (AVI->video_pos < 0 || AVI->video_pos >= AVI->video_frames) return -1;
n = AVI->video_index[AVI->video_pos].len;
*keyframe = (AVI->video_index[AVI->video_pos].key == 0x10) ? 1 : 0;
fseek(AVI->fp, AVI->video_index[AVI->video_pos].pos, SEEK_SET);
if (avi_read(AVI->fp, vidbuf, n) != n)
{
return -1;
}
AVI->video_pos++;
return n;
}
int AVI_set_video_position(avi *AVI, long frame)
{
if (frame < 0) frame = 0;
AVI->video_pos = frame;
return 0;
}
|
C
|
#include <stdio.h>
int main(void) {
float variavel;
variavel = 1000.0;
printf ("%f\n", variavel);
variavel = variavel + 0.00000000000001;
printf ("%f\n", variavel);
}
|
C
|
#include "stdio.h"
int search1(char s[], char c)
{
int i;
int k = 0;
//printf("%d\n", i );
for (i = 0; s[i] != '\0'; i++)
//printf("%d %c\n", i, s[i]);
if (s[i] == c) k++;
return k;
}
int main()
{
char s[] = "alabalk";
char c = '1';
printf("%d\n", search1(s, c));
return 0;
}
|
C
|
/*
* AD9850.h
*
* Created on: 5-okt.-2015
* Author: Robbe
*/
#ifndef STM32DEV_INCLUDE_GENERAL_AD9850_H_
#define STM32DEV_INCLUDE_GENERAL_AD9850_H_
// PINS FROM IC
/*
PIN NO MNEMONIC DESCRIPTION
4 to 1, 28 to 25 D0 to D7 8-Bit Data Input. This is the 8-bit data port for iteratively loading the 32-bit frequency and the 8-bit phase/ control word. D7 = MSB; D0 = LSB. D7 (Pin 25) also serves as the input pin for the 40-bit serial data-word.
5, 24 DGND Digital Ground. These are the ground return leads for the digital circuitry.
6, 23 DVDD Supply Voltage Leads for Digital Circuitry.
7 W_CLK Word Load Clock. This clock is used to load the parallel or serial frequency/phase/control words.
8 FQ_UD Frequency Update. On the rising edge of this clock, the DDS updates to the frequency (or phase) loaded in the data input register; it then resets the pointer to Word 0.
9 CLKIN Reference Clock Input. This may be a continuous CMOS-level pulse train or sine input biased at 1/2 V supply. The rising edge of this clock initiates operation.
10,19 AGND Analog Ground. These leads are the ground return for the analog circuitry (DAC and comparator).
11,18 AVDD Supply Voltage for the Analog Circuitry (DAC and Comparator).
12 RSET DAC’s External RSET Connection. This resistor value sets the DAC full-scale output current. For normal applications (FS IOUT = 10 mA), the value for RSET is 3.9 kΩ connected to ground. The RSET/IOUT relationship is IOUT = 32 (1.248 V/RSET).
13 QOUTB Output Complement. This is the comparator’s complement output.
14 QOUT Output True. This is the comparator’s true output.
15 VINN Inverting Voltage Input. This is the comparator’s negative input.
16 VINP Noninverting Voltage Input. This is the comparator’s positive input.
17 DACBL (NC) DAC Baseline. This is the DAC baseline voltage reference; this lead is internally bypassed and should normally be considered a no connect for optimum performance.
20 IOUTB Complementary Analog Output of the DAC.
21 IOUT Analog Current Output of the DAC.
22 RESET Reset. This is the master reset function; when set high, it clears all registers (except the input register), and the DAC output goes to cosine 0 after additional clock cycles—see Figure 7.
*/
#endif /* STM32DEV_INCLUDE_GENERAL_AD9850_H_ */
|
C
|
/*
* Copyright (C) 2009-2011 by Benedict Paten (benedictpaten@gmail.com)
*
* Released under the MIT license, see LICENSE.txt
*/
/*
* reconcilliation.c
*
* Created on: 31-Mar-2010
* Author: benedictpaten
*/
#include <assert.h>
#include "cactus.h"
#include "commonC.h"
Event *labelAndReturnEvent(struct BinaryTree *blockTree, Event *event) {
assert(event != NULL);
blockTree->label = cactusMisc_nameToString(event_getName(event));
return event;
}
Event *reconcile(struct BinaryTree *blockTree, EventTree *eventTree,
Event *(*getEventFromLeaf)(struct BinaryTree *binaryTree, void *extraArg), void *extraArg) {
if(blockTree->internal) { //internal node
Event *leftChild = reconcile(blockTree->left, eventTree, getEventFromLeaf, extraArg);
Event *rightChild = reconcile(blockTree->right, eventTree, getEventFromLeaf, extraArg);
if(leftChild != NULL) {
if(rightChild != NULL) {
Event *commonAncestor = eventTree_getCommonAncestor(leftChild, rightChild);
assert(commonAncestor != eventTree_getRootEvent(eventTree));
if(commonAncestor == leftChild || commonAncestor == rightChild) {
Event *parentEvent = event_getParent(commonAncestor);
if(event_getChildNumber(parentEvent) != 1 || parentEvent == eventTree_getRootEvent(eventTree)) {
//we need to invent a new event before the parent speciation or root of tree
Event *newEvent = event_construct4(NULL, 0.01, parentEvent, commonAncestor, eventTree);
return labelAndReturnEvent(blockTree, newEvent);
}
else { //there already exists a valid unary event..
return labelAndReturnEvent(blockTree, parentEvent);
}
}
else { //speciation case
return labelAndReturnEvent(blockTree, commonAncestor);
}
}
else {
return leftChild;
}
}
else {
return rightChild;
}
}
else { //leaf case
Event *childEvent = getEventFromLeaf(blockTree, extraArg);
return childEvent;
}
}
|
C
|
/* it's all too easy to start over-complicating this: for example quotations. Here you woul dneed to check the last 2 characters of everyword, not just the last one, i.e "stop!", that adds new layers. */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#ifdef DBG
#define CBUF 2
#define WABUF 1
#define LBUF 2
#else
#define CBUF 12
#define WABUF 20
#define LBUF 32
#endif
typedef unsigned char boole;
typedef enum
{
STRG, /* unknown type, so default to string */
NUMS, /* NUMberS: but does not include currency. So. .Date, time, float or int, i.e. just a sequence of numbers with maybe some special symbils.*/
TMG, /* pos or beg int. i/e not negative, but int all the way .., */
OTH /* anythign nto the above */
} t_t;
typedef struct /* word type */
{
char *w;
t_t t; /* number or not */
unsigned lp1; /* length of word plus one (i.e. includes null char */
} w_c;
typedef struct /* aw_c: array of words container */
{
w_c **aw;
unsigned ab;
unsigned al;
float t0; // principal timing, prob seconds.
char tmg[3]; // three signed integers that are <128 each.
} aw_c;
typedef struct /* aaw_c: array of array of words container */
{
size_t numl; /* number of lines, i.e. rows */
aw_c **aaw; /* an array of pointers to aw_c */
} aaw_c;
/* checking each character can be comptiue-intensive, so I've offloaded off to MACROS */
/* Macro fo GET Leading Char TYPE */
/* so, this refers to the first character: "+-.0123456789" only these are allowed. These is how we infer
* a quantity of some sort ... except for currency */
#define GETLCTYPE(c, typ); \
if(((c) >= 0x30) && ((c) <= 0x39)) { \
typ = NUMS; \
} else { \
typ = STRG; \
}
/* Macro for InWord MODify TYPE */
#define IWMODTYPEIF(c, typ); \
if( ((typ) == NUMS) & ((c == 0x3A) || (c == 0x2E) || (((c) >= 0x30) && ((c) <= 0x39)))) { \
if( ((c == 0x3A) || (c == 0x2E))) \
typ = TMG; \
}
|
C
|
#pragma once
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923
#endif
#ifndef M_PI_4
#define M_PI_4 0.785398163397448309616
#endif
//структура синусов углов Эйлера , для совмещения с классом SMat
struct TSinus
{
double Teta, Gamma, Psi;
}
;
//структура косинусов углов Эйлера , для совмещения с классом SMat
struct TCosinus
{
double Teta, Gamma, Psi;
};
//Структура 3D вектор в любой системе координат
typedef struct SVECTOR
{
double x,y,z;
SVECTOR(){this->x = 0 ; this->y = 0 ;this->z = 0 ; }
SVECTOR(double x , double y , double z){this->x = x ; this->y = y ;this->z = z ; }
//сложение вычитание
SVECTOR operator + (const SVECTOR vec)
{
SVECTOR res(this->x + vec.x , this->y + vec.y , this->z + vec.z);
return res;
}
SVECTOR operator - (const SVECTOR vec)
{
SVECTOR res(this->x - vec.x , this->y - vec.y , this->z - vec.z);
return res;
}
void operator += (const SVECTOR vec)
{
this->x += vec.x;
this->y += vec.y;
this->z += vec.z;
}
void operator -= (const SVECTOR vec)
{
this->x -= vec.x;
this->y -= vec.y;
this->z -= vec.z;
}
//вектор проекции на вектор
SVECTOR Proj(SVECTOR & vec)
{
double len = (this->x * vec.x + this->y * vec.y + this->z * vec.z) / vec.len();
return SVECTOR(vec.x * len , vec.y * len , vec.z * len);
}
double len()
{
return sqrt(x * x + y * y + z * z);
}
//векторное умножение
SVECTOR operator * (const SVECTOR vec)
{
SVECTOR res_(0,0,0);
res_.x = this->y * vec.z - this->z * vec.y;
res_.y = this->z * vec.x - this->x * vec.z;
res_.z = this->x * vec.y - this->y * vec.x;
return res_;
}
//векторное умножение
void operator *= (const SVECTOR vec)
{
SVECTOR res(this->x,this->y,this->z);
res = res * vec;
this->x = res.x;
this->y = res.y;
this->z = res.z;
}
}
SVECTOR;
//Структура 3D вектор в любой системе координат
struct SVec
{
double x,y,z;
SVec(){this->x = 0 ; this->y = 0 ;this->z = 0 ; }
SVec(double x , double y , double z){this->x = x ; this->y = y ;this->z = z ; }
//сложение вычитание
void Init(double x , double y , double z){this->x = x ; this->y = y ;this->z = z ; }
SVec operator + (const SVec &vec)
{
SVec res(this->x + vec.x , this->y + vec.y , this->z + vec.z);
return res;
}
SVec operator - (const SVec &vec)
{
SVec res(this->x - vec.x , this->y - vec.y , this->z - vec.z);
return res;
}
void operator += (const SVec &vec)
{
this->x += vec.x;
this->y += vec.y;
this->z += vec.z;
}
void operator -= (const SVec &vec)
{
this->x -= vec.x;
this->y -= vec.y;
this->z -= vec.z;
}
//вектор проекции на вектор
SVec Proj(SVec* vec)
{
double len1 = (this->x * vec->x + this->y * vec->y + this->z * vec->z) / vec->len();
return SVec(vec->x * len1 , vec->y * len1 , vec->z * len1);
}
double len()
{
return sqrt(x * x + y * y + z * z);
}
//векторное умножение
SVec operator * (const SVec &vec)
{
SVec res_(0,0,0);
res_.x = this->y * vec.z - this->z * vec.y;
res_.y = this->z * vec.x - this->x * vec.z;
res_.z = this->x * vec.y - this->y * vec.x;
return res_;
}
//векторное умножение
void operator *= (const SVec &vec)
{
SVec res(this->x,this->y,this->z);
res = res * vec;
this->x = res.x;
this->y = res.y;
this->z = res.z;
}
SVec norm()
{
double l = len();
if(l == 0) return SVec(0,0,0);
return SVec(x/l,y/l,z/l);
}
}
;
//Структура которая подается на каждом шаге интегрирования
struct TStateVector
{
double X,Y,Z; // координаты вертолета
double Teta,Psi,Gamma; // углы тангажа, рысканья и крена
double Vx,Vy,Vz; // скорости в связанной с.к.
double Wx,Wy,Wz; // угловые скорости
SVec Xg()
{
return SVec(X,Y,Z);
}
SVec EA()
{
return SVec(Teta,Psi,Gamma);
}
SVec Vb()
{
return SVec(Vx,Vy,Vz);
}
SVec Wb()
{
return SVec( Wx,Wy,Wz);
}
}
;
struct SMat
{
double xx, xy, xz;
double yx, yy, yz;
double zx, zy, zz;
SMat()//Инициализация еденичной матрицей
{
xx=yy=zz=(double)1.0;
xy=xz=yx=yz=zx=zy=(double)0.0;
}
~SMat(){}
void Set(TSinus sin, TCosinus cos)//вычисляем матрицу перехода из связной системы координат в земную
{
xx = (double)(cos.Teta * cos.Psi);
yx = (double)(sin.Teta);
zx = (double)(-cos.Teta * sin.Psi);
xy = (double)(-cos.Gamma * sin.Teta * cos.Psi + sin.Gamma * sin.Psi);
yy = (double)(cos.Gamma * cos.Teta);
zy = (double)(cos.Gamma * sin.Teta * sin.Psi + sin.Gamma * cos.Psi);
xz = (double)(sin.Gamma * sin.Teta * cos.Psi + cos.Gamma * sin.Psi);
yz = (double)(-sin.Gamma * cos.Teta);
zz = (double)(-sin.Psi * sin.Teta * sin.Gamma + cos.Psi * cos.Gamma);
}
void SetInv(TSinus sin, TCosinus cos)//вычисляем матрицу перехода из земной системы координат в связную
{
xx = (double)(cos.Teta * cos.Psi);
xy = (double)(sin.Teta);
xz = (double)(-cos.Teta * sin.Psi);
yx = (double)(-cos.Gamma * sin.Teta * cos.Psi + sin.Gamma * sin.Psi);
yy = (double)(cos.Gamma * cos.Teta);
yz = (double)(cos.Gamma * sin.Teta * sin.Psi + sin.Gamma * cos.Psi);
zx = (double)(sin.Gamma * sin.Teta * cos.Psi + cos.Gamma * sin.Psi);
zy = (double)(-sin.Gamma * cos.Teta);
zz = (double)(-sin.Psi * sin.Teta * sin.Gamma + cos.Psi * cos.Gamma);
}
void Set(double Teta,double Psi,double Gamma)
{
TSinus sin_;
TCosinus cos_;
sin_.Teta = (double)sin(Teta);
sin_.Gamma = (double)sin(Gamma);
sin_.Psi = (double)sin(Psi);
cos_.Teta = (double)cos(Teta);
cos_.Gamma = (double)cos(Gamma);
cos_.Psi = (double)cos(Psi);
Set(sin_,cos_);
}
void SetInv(double Teta,double Psi,double Gamma)
{
TSinus sin_;
TCosinus cos_;
sin_.Teta = (double)sin(Teta);
sin_.Gamma = (double)sin(Gamma);
sin_.Psi = (double)sin(Psi);
cos_.Teta = (double)cos(Teta);
cos_.Gamma = (double)cos(Gamma);
cos_.Psi = (double)cos(Psi);
SetInv(sin_,cos_);
}
SVec operator * (const SVec vec)
{
SVec res_(0,0,0);
res_.x = (this->xx) * vec.x + (this->xy) * vec.y + (this->xz) * vec.z;
res_.y = (this->yx) * vec.x + (this->yy) * vec.y + (this->yz) * vec.z;
res_.z = (this->zx) * vec.x + (this->zy) * vec.y + (this->zz) * vec.z;
return res_;
}
} ;
struct SMatrix
{
double xx, xy, xz;
double yx, yy, yz;
double zx, zy, zz;
SMatrix()//Инициализация еденичной матрицей
{
xx=yy=zz=(double)1.0;
xy=xz=yx=yz=zx=zy=(double)0.0;
}
~SMatrix(){}
void Set(TSinus sin, TCosinus cos)//вычисляем матрицу перехода из связной системы координат в земную
{
xx = (double)(cos.Teta * cos.Psi);
yx = (double)(sin.Teta);
zx = (double)(-cos.Teta * sin.Psi);
xy = (double)(-cos.Gamma * sin.Teta * cos.Psi + sin.Gamma * sin.Psi);
yy = (double)(cos.Gamma * cos.Teta);
zy = (double)(cos.Gamma * sin.Teta * sin.Psi + sin.Gamma * cos.Psi);
xz = (double)(sin.Gamma * sin.Teta * cos.Psi + cos.Gamma * sin.Psi);
yz = (double)(-sin.Gamma * cos.Teta);
zz = (double)(-sin.Psi * sin.Teta * sin.Gamma + cos.Psi * cos.Gamma);
}
void SetInv(TSinus sin, TCosinus cos)//вычисляем матрицу перехода из земной системы координат в связную
{
xx = (double)(cos.Teta * cos.Psi);
xy = (double)(sin.Teta);
xz = (double)(-cos.Teta * sin.Psi);
yx = (double)(-cos.Gamma * sin.Teta * cos.Psi + sin.Gamma * sin.Psi);
yy = (double)(cos.Gamma * cos.Teta);
yz = (double)(cos.Gamma * sin.Teta * sin.Psi + sin.Gamma * cos.Psi);
zx = (double)(sin.Gamma * sin.Teta * cos.Psi + cos.Gamma * sin.Psi);
zy = (double)(-sin.Gamma * cos.Teta);
zz = (double)(-sin.Psi * sin.Teta * sin.Gamma + cos.Psi * cos.Gamma);
}
SVECTOR operator * (const SVECTOR vec)
{
SVECTOR res_(0,0,0);
res_.x = this->xx * vec.x + this->xy * vec.y + this->xz * vec.z;
res_.y = this->yx * vec.x + this->yy * vec.y + this->yz * vec.z;
res_.z = this->zx * vec.x + this->zy * vec.y + this->zz * vec.z;
return res_;
}
} ;
|
C
|
/*
* name: Whelpley
* date: 20 Feb 2019
* project: Lab10.6A - PREPROCESSOR DIRECTIVES
*
* Write a C program with preprocessor directives to:
* Combine two string literals
* Wrap those string literals in quotes
* Define a constant buffer size of 64
*
* Define an array:
* Of standard buffer size
* Assign the wrapped string literals to the array
*
* Print the array
*
*/
#define firstStrLit "Hey there"
#define secondStrLit ", Bruvs!"
#define combineStr firstStrLit secondStrLit
#define constBuff 64
#include <stdio.h>
int main() {
const char heyArray[constBuff] = { combineStr };
fprintf(stdout, heyArray);
return 0;
}
|
C
|
#include "holberton.h"
/**
* print_chessboard - prints the chess board
*
* @a: input pointer
*
* Return: return nothing
*/
void print_chessboard(char (*a)[8])
{
int i, j;
i = 0;
j = 0;
while (i < 64)
{
if (i % 8 == 0 && i != 0)
{
j = i;
_putchar('\n');
}
_putchar(a[i / 8][i - j]);
i++;
}
_putchar('\n');
}
|
C
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
/*
Sign a message and verify the signature
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <amcl/utils.h>
#include <amcl/randapi.h>
#include <amcl/bls_BLS381.h>
#include <amcl/pqnist.h>
#define NTHREADS 8
#define MAXSIZE 256
#define G2LEN 4*BFS_BLS381
#define SIGLEN BFS_BLS381+1
int main()
{
int i,rc;
// Seed value for CSPRNG
char seed[NTHREADS][PQNIST_SEED_LENGTH];
// Message to be sent to Bob
char p[NTHREADS][MAXSIZE];
octet P[NTHREADS];
// BLS signature
char s[NTHREADS][SIGLEN];
octet S[NTHREADS];
// Initialise seed
for(i=0; i<NTHREADS; i++)
{
for(int j=0; j<PQNIST_SEED_LENGTH; j++)
{
seed[i][j] = i;
}
}
// Generate BLS keys
// Alice's BLS keys
char BLSsk[NTHREADS][BGS_BLS381];
char BLSpk[NTHREADS][G2LEN];
#pragma omp parallel for
for(i=0; i<NTHREADS; i++)
{
rc = pqnist_bls_keys(seed[i], BLSpk[i], BLSsk[i]);
if (rc)
{
fprintf(stderr, "FAILURE pqnist_keys rc: %d\n", rc);
exit(EXIT_FAILURE);
}
printf("BLS pklen %d pk: ", G2LEN);
amcl_print_hex(BLSpk[i], G2LEN);
printf("BLS sklen %d BLS sk: ", BGS_BLS381);
amcl_print_hex(BLSsk[i], BGS_BLS381);
printf("\n");
}
// Alice
for(i=0; i<NTHREADS; i++)
{
bzero(p[i],sizeof(p[i]));
P[i].max = MAXSIZE;
P[i].len = sprintf(p[i], "Hello Bob! This is a message from Alice %d", i);
P[i].val = p[i];
printf("Alice Plaintext: ");
OCT_output_string(&P[i]);
printf("\n");
}
for(i=0; i<NTHREADS; i++)
{
bzero(s[i],sizeof(s[i]));
S[i].max = SIGLEN;
S[i].len = SIGLEN;
S[i].val = s[i];
}
#pragma omp parallel for
for(i=0; i<NTHREADS; i++)
{
// Alice signs message
rc = pqnist_bls_sign(P[i].val, BLSsk[i], S[i].val);
if(rc)
{
fprintf(stderr, "FAILURE pqnist_bls_sign rc: %d\n", rc);
exit(EXIT_FAILURE);
}
printf("Alice SIGlen %d SIG", S[i].len);
OCT_output(&S[i]);
printf("\n");
}
#pragma omp parallel for
for(i=0; i<NTHREADS; i++)
{
// Bob verifies message
rc = pqnist_bls_verify(P[i].val, BLSpk[i], S[i].val);
if (rc)
{
fprintf(stderr, "FAILURE pqnist_bls_verify rc: %d\n", rc);
exit(EXIT_FAILURE);
}
else
{
printf("Test %d pqnist_bls_verify rc: %d\n", i, rc);
OCT_output_string(&P[i]);
printf("\n");
}
}
// clear memory
for(i=0; i<NTHREADS; i++)
{
OCT_clear(&P[i]);
OCT_clear(&S[i]);
}
printf("SUCCESS\n");
exit(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(void){
struct book
{
char name[50];
int pages;
float price;
};
struct book b,*bptr;
printf("Enter Book's name:\t");
scanf("%s",b.name);
printf("Number of Pages: \t");
scanf("%d",&b.pages);
printf("Enter Price: \t");
scanf("%f",&b.price);
bptr=&b;
printf("\n\n\n");
printf("Book name:\tPages:\tPrice\n");
// printf("\n\nBook Info Using Pointer i.e arrow operator\n\n");
printf("\n%s\t\t%d\t%.2f\tBook Info Using Pointer i.e arrow operator\n",bptr->name,bptr->pages,bptr->price);
// printf("\n\nBook Info Using Pointer i.e *Operator\n\n");
printf("\n%s\t\t%d\t%.2f\tBook Info Using Pointer i.e *Operator\n",(*bptr).name,(*bptr).pages,(*bptr).price);
// printf("\n\nBook Info Using Structure variable i.e dot operator\n\n");
printf("\n%s\t\t%d\t%.2f\tBook Info Using Structure variable i.e dot operator\n",b.name,b.pages,b.price);
printf("\n\n\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/objects.h>
#include <openssl/comp.h>
COMP_CTX *COMP_CTX_new(COMP_METHOD *meth)
{
COMP_CTX *ret;
if ((ret=(COMP_CTX *)OPENSSL_malloc(sizeof(COMP_CTX))) == NULL)
{
/* ZZZZZZZZZZZZZZZZ */
return(NULL);
}
memset(ret,0,sizeof(COMP_CTX));
ret->meth=meth;
if ((ret->meth->init != NULL) && !ret->meth->init(ret))
{
OPENSSL_free(ret);
ret=NULL;
}
return(ret);
}
void COMP_CTX_free(COMP_CTX *ctx)
{
if(ctx == NULL)
return;
if (ctx->meth->finish != NULL)
ctx->meth->finish(ctx);
OPENSSL_free(ctx);
}
int COMP_compress_block(COMP_CTX *ctx, unsigned char *out, int olen,
unsigned char *in, int ilen)
{
int ret;
if (ctx->meth->compress == NULL)
{
/* ZZZZZZZZZZZZZZZZZ */
return(-1);
}
ret=ctx->meth->compress(ctx,out,olen,in,ilen);
if (ret > 0)
{
ctx->compress_in+=ilen;
ctx->compress_out+=ret;
}
return(ret);
}
int COMP_expand_block(COMP_CTX *ctx, unsigned char *out, int olen,
unsigned char *in, int ilen)
{
int ret;
if (ctx->meth->expand == NULL)
{
/* ZZZZZZZZZZZZZZZZZ */
return(-1);
}
ret=ctx->meth->expand(ctx,out,olen,in,ilen);
if (ret > 0)
{
ctx->expand_in+=ilen;
ctx->expand_out+=ret;
}
return(ret);
}
|
C
|
#include <sys/stat.h>
#include <fcntl.h>
#include "../../lib/tlpi_hdr.h"
#define CMD_SIZE 200
#define BUF_SIZE 1024
int main(int argc, char *argv[])
{
int fd;
int j;
int numBlocks;
char shellCmd[CMD_SIZE];
char buf[BUF_SIZE];
if (argc < 2 || strcmp(argv[1], "--help") == 0) {
usageErr("%s temp-file [num-1kb-blocks] \n", argv[0]);
}
numBlocks = argc > 2 ? getInt(argv[2], GN_GT_0, "num-1kb-blocks") : 100000;
// create a file that will be immediately unlinked
fd = open(argv[1], O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
if (fd == -1) {
errExit("open()");
}
// unlink the file that was just created
if (unlink(argv[1]) == -1) {
errExit("unlink()");
}
// write junk to the file (that is unlinked)
for (j = 0; j < numBlocks; j++) {
if (write(fd, buf, BUF_SIZE) != BUF_SIZE) {
fatal("partial/failed write");
}
}
snprintf(shellCmd, CMD_SIZE, "df -k `dirname %s`", argv[1]);
system(shellCmd);
if (close(fd) == -1) {
errExit("close()");
}
printf("********** Closed file descriptor\n");
system(shellCmd);
exit(EXIT_SUCCESS);
}
|
C
|
#include <math.h>
#include "prbs31.h"
#include <stdio.h>
int main () {
// FILE *fp;
// data_t seed;
// seed = 0x02;
int i;
// Generate the expected result
data_t start = SEED;
result_t hw_out=start;
result_t sw_out=start;
for(i = 1;; i++) {
int newbit = (((sw_out >> 30) ^ (sw_out >> 27)) & 1);
sw_out = ((sw_out << 1) | newbit) & 0x7fffffff;
if (sw_out == 75497536) {
// Detects when the cycle repeats
break;
}
// Run the AutoESL matrix multiply block
prbs31(&hw_out);
// Print result vector
printf(" %d",hw_out);
printf(" %d",sw_out);
}
printf("Test done.\n");
return 0;
}
|
C
|
#include<stdio.h>
void main(){
int j = 1,num = 2;
for(int i = 1;i<=4;){
if(j<=4){
printf("%d ",num);
num += 2;
j++;
continue;
}
else{
printf("\n");
i++;
j = 1;
num = 2;
}
}
}
/*shital@sarode:~/Desktop/PPA/Assignments/Assignment-21 August 2020$ ./a.out
2 4 6 8
2 4 6 8
2 4 6 8
2 4 6 8
*/
|
C
|
#include "util.h"
/*
TODO
give exit and return error number some define
to clarify error information
*/
static void report(const char *prefix, const char *err, va_list params)
{
char msg[2014];
vsnprintf(msg,sizeof(msg),err,params);
fprintf(stderr," %s%s\n", prefix, msg);
}
static NORETURN void die_builtin(const char *err, va_list params)
{
report(" Fatal: ", err, params);
exit(128);
}
static void error_builtin(const char *err, va_list params)
{
report(" Error: ", err, params);
}
static void warn_builtin(const char *warn, va_list params)
{
report(" Warning: ", warn, params);
}
static void info_builtin(const char *info, va_list params)
{
report(" Info: ", info, params);
}
void die(const char *err, ...)
{
va_list params;
va_start(params,err);
die_builtin(err, params);
va_end(params);
}
int pr_err(const char *err, ...)
{
va_list params;
va_start(params, err);
error_builtin(err, params);
va_end(params);
return -1;
}
void pr_warning(const char *warn, ...)
{
va_list params;
va_start(params, warn);
warn_builtin(warn, params);
va_end(params);
}
void pr_info(const char *info, ...)
{
va_list params;
va_start(params, info);
info_builtin(info, params);
va_end(params);
}
void die_perror(const char *s)
{
perror(s);
exit(1);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int n, m, a, b;
scanf("%d", &n);
scanf("%d", &m);
a = (n + m) / 2;
b = n - a;
printf("%d\n", a);
printf("%d", b);
}
|
C
|
#include <sqlite3.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include "callback.h"
#include "show_data.h"
#include "user_manager.h"
#include "expense_manager.h"
#include "draw_main.h"
sqlite3 *db;
int main(void) {
int rc = sqlite3_open("ljdata.db", &db);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot open database: %s\n",
sqlite3_errmsg(db));
sqlite3_close(db);
exit(0);
}
system("clear");
printf("%s\n", "════════════════════════════════════════════════════════════════════════════════");
printf("%s\n", " ╔═╗┌─┐┌─┐┌┬┐ ╔═╗┌─┐┬ ┬┌┬┐┌┬┐┌─┐┬─┐");
printf("%s\n", " ║ │ │└─┐ │ ───╚═╗├─┘│ │ │ │ ├┤ ├┬┘");
printf("%s\n", " ╚═╝└─┘└─┘ ┴ ╚═╝┴ ┴─┘┴ ┴ ┴ └─┘┴└─");
printf("%s\n", "════════════════════════════════════════════════════════════════════════════════");
sleep(3);
system("clear");
draw_main();
sqlite3_close(db);
printf("%s\n", "BYE");
system("clear");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include "icy_mem.h"
#include "types.h"
#include "log.h"
#include "mem.h"
#include "array.h"
#include "utils.h"
#ifndef MAP_32BIT
#define MAP_32BIT 0
#endif
static icy_mem * icy_mems = NULL;
static u64 icy_mem_cnt = 0;
icy_mem * get_icy_mem_by_name(const char * name){
for(u64 i = 0; i < icy_mem_cnt; i++){
if(strcmp(icy_mems[i].name, name) == 0)
return icy_mems + i;
}
return NULL;
}
icy_mem * get_icy_mem_by_ptr(const void * ptr){
for(u64 i = 0; i < icy_mem_cnt; i++){
if(icy_mems[i].ptr == ptr)
return icy_mems + i;
}
return NULL;
}
icy_mem * icy_mem_create(const char * name){
return icy_mem_create2(name, false);
}
static const char * data_directory = "data";
void icy_mem_set_data_directory(char * data_dir){
data_directory = data_dir;
}
icy_mem * icy_mem_create2(const char * name, bool only_32bit){
int fd = 0;
u64 size = 0;
if(name != NULL){
ASSERT(name[0] != '/' && name[0] != 0);
mkdir(data_directory, 0777);
{
char * pt = (char * )name;
while(true){
char * slash = strchr(pt, '/');
if(slash == NULL) break;
if(slash != NULL && slash[-1] != '\\'){
size_t size = slash - name;
char s[100];
strcpy(s, name);
s[size] = 0;
char buf[100];
sprintf(buf, "%s/%s", data_directory, s);
mkdir(buf, 0777);
}
pt = slash + 1;
ASSERT(pt[0] != '/' && pt[0] != 0);
}
}
const size_t min_size = 1;
char path[100];
sprintf(path, "%s/%s",data_directory, name);
fd = open(path, O_RDWR | O_CREAT, 0666);
ASSERT(fd >= 0);
size = lseek(fd, 0, SEEK_END);
if(size < min_size){
lseek(fd, 0, SEEK_SET);
ASSERT(0 == ftruncate(fd, min_size));
size = lseek(fd, 0, SEEK_END);
}
lseek(fd, 0, SEEK_SET);
}
int flags = MAP_SHARED;
if(only_32bit)
flags |= MAP_32BIT;
void * ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, flags, fd, 0);
if(flags & MAP_32BIT){
logd("32bit: %p\n", ptr);
}
ASSERT(ptr != NULL);
icy_mem mema = {
.ptr = ptr, .size = size,
.name = (char *) name, .fd = fd,
.only_32bit = only_32bit,
.persisted = true
};
return IRON_CLONE(mema);
}
void icy_mem_free(icy_mem * area){
if(area->persisted == false){
if(area->ptr != NULL)
dealloc(area->ptr);
}else{
munmap(area->ptr, area->size);
}
memset(area, 0, sizeof(*area));
}
icy_mem * icy_mem_create3(){
icy_mem mema = {
.ptr = NULL, .size = 0,
.name = (char *)"", .fd = 0,
.only_32bit = false
};
return iron_clone(&mema, sizeof(mema));
}
void * icy_mem_alloc2(const char * name, size_t min_size, size_t * out_size){
if(min_size == 0)
min_size = 1;
{
icy_mem * area = get_icy_mem_by_name(name);
if(area != NULL){
*out_size = area->size;
return area->ptr;
}
}
mkdir(data_directory, 0777);
char path[100];
sprintf(path, "%s/%s",data_directory, name);
int fd = open(path, O_RDWR | O_CREAT, 0666);
ASSERT(fd >= 0);
u64 size = lseek(fd, 0, SEEK_END);
if(size < min_size){
lseek(fd, 0, SEEK_SET);
ASSERT(0 == ftruncate(fd, min_size));
size = lseek(fd, 0, SEEK_END);
}
lseek(fd, 0, SEEK_SET);
void * ptr = mmap(NULL, size, PROT_READ | PROT_WRITE , MAP_SHARED, fd, 0);
ASSERT(ptr != NULL);
icy_mem mema = {.ptr = ptr, .size = size, .name = fmtstr("%s", name), .fd = fd};
list_push2(icy_mems, icy_mem_cnt, mema);
*out_size = size;
return ptr;
}
void * icy_mem_alloc(const char * name, size_t min_size){
size_t s = 0;
return icy_mem_alloc2(name, min_size, &s);
}
void icy_mem_realloc(icy_mem * area, size_t size){
ASSERT(area != NULL);
if(area->size == size) return;
if(false == area->persisted){
area->ptr = ralloc(area->ptr, area->size = size);
return;
}
int flags = MREMAP_MAYMOVE;
if(area->only_32bit)
flags |= MAP_32BIT;
area->ptr = mremap(area->ptr, area->size, size, flags);
ASSERT(0 == ftruncate(area->fd, size));
area->size = size;
}
|
C
|
#include <setjmp.h>
#include "test.h"
#include "os.h"
enum state_t
{
STATE_ZERO = 0,
STATE_0,
STATE_1,
STATE_2,
STATE_3,
};
enum state_t states[10] = {0};
static int state_num = 0;
static void test_task(void *data)
{
os_task_begin();
states[state_num++] = STATE_1;
os_yield();
states[state_num++] = STATE_2;
os_task_end();
}
static void test_task_exit(void *data)
{
states[state_num++] = STATE_3;
jmp_buf *quit = (jmp_buf *)data;
longjmp(*quit, 0);
}
void test_os(void)
{
jmp_buf quit;
states[state_num++] = STATE_0;
os_init();
os_add_task(test_task, 2, 0);
os_add_task(test_task_exit, 1, &quit);
if (setjmp(quit))
{
int i=0;
TEST_EQ(states[i++], STATE_0);
TEST_EQ(states[i++], STATE_1);
TEST_EQ(states[i++], STATE_2);
TEST_EQ(states[i++], STATE_3);
TEST_EQ(states[i++], STATE_ZERO);
return;
}
os_start();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
#include <time.h>
#define MSG_SIZE 64
#define NB_MSG 20
#define NB_CHANNELS 10
void do_reader(void)
{
int i, v, n;
int ret;
int fd[NB_CHANNELS];
char msg[MSG_SIZE];
char chaname[50];
fd_set set_read;
struct timeval tv;
// open all the channels, receiver side
for (i = 0; i < NB_CHANNELS; i++)
{
snprintf(chaname, 50, "/dev/kbfish%i", i);
fd[i] = open(chaname, O_RDWR | O_CREAT);
if (fd[i] < 0)
{
perror("Reader open");
printf(">>> Error while opening channel %i\n", i);
}
}
printf("I am the reader. I am gonna recv %i messages on %i channels\n",
NB_MSG, NB_CHANNELS);
// while not has received NB_MSG_TO_SEND
n = 0;
while (n < NB_MSG)
{
// select on them
FD_ZERO(&set_read);
tv.tv_sec = 1; // timeout in seconds
tv.tv_usec = 0;
int max = 0;
for (i = 0; i < NB_CHANNELS; i++)
{
FD_SET(fd[i], &set_read);
max = ((fd[i] > max) ? fd[i] : max);
}
/*
for (i = 0; i < NB_CHANNELS; i++)
{
// read the message and print it + the channel from which it comes
ret = read(fd[i], (void*) &v, sizeof(v));
if (ret == -1)
{
perror("read error");
}
else if (ret > 0)
{
printf(">>> %i: %i from %i\n", n, v, i);
n++;
}
}
*/
//select
//printf(">>> %i: select\n", n);
ret = select(max + 1, &set_read, NULL, NULL, &tv);
if (ret)
{
for (i = 0; i < NB_CHANNELS; i++)
{
if (FD_ISSET(fd[i], &set_read))
{
// read the message and print it + the channel from which it comes
ret = read(fd[i], (void*) &v, sizeof(v));
if (ret == -1)
{
perror("read error");
}
else if (ret > 0)
{
printf(">>> %i: %i from %i\n", n, v, i);
n++;
}
else
{
printf(">>> nothing to read\n");
}
}
}
}
}
// close
for (i = 0; i < NB_CHANNELS; i++)
{
close(fd[i]);
}
}
void do_writer(void)
{
int i, v, n;
int ret;
int fd[NB_CHANNELS];
char msg[MSG_SIZE];
char chaname[50];
srand(time(NULL));
// open all the channels in read-only
for (i = 0; i < NB_CHANNELS; i++)
{
snprintf(chaname, 50, "/dev/kbfish%i", i);
fd[i] = open(chaname, O_RDWR);
if (fd[i] < 0)
{
perror("Writer open");
printf("<<< Error while opening channel %i\n", i);
}
}
// while not has received NB_MSG_TO_SEND
for (n = 0; n < NB_MSG; n++)
{
// use random channel
i = rand() % NB_CHANNELS;
// write the message
v = n * i;
printf("<<< %i: %i to %i\n", n, v, i);
ret = write(fd[i], (void*) &v, sizeof(v));
if (ret < 0)
{
perror("write error");
}
// sleep 1
//sleep(1);
}
// close
for (i = 0; i < NB_CHANNELS; i++)
{
close(fd[i]);
}
}
int main(void)
{
#ifdef READER
do_reader();
#endif
#ifdef WRITER
do_writer();
#endif
return 0;
}
|
C
|
#include <stdint.h>
#include <kernel.h>
void ipc_send_packet(uint32_t pid, char* payload, uint32_t len) {
// check for a limit overflow
if (((uint32_t)payload + len) >= (task_table[current_task]->pages * PAGE_SIZE)) {
tty_kputs("\nIPC packet had a bogus length.", 0);
tty_kputs("\nTask terminated.\n", 0);
task_terminate(current_task);
task_scheduler();
}
// check if the pid exists
if ((!task_table[pid]) || (task_table[pid] == EMPTY_PID)) {
tty_kputs("\nIPC packet targeted a non-existent PID.", 0);
tty_kputs("\nTask terminated.\n", 0);
task_terminate(current_task);
task_scheduler();
}
payload += task_table[current_task]->base;
task_table[pid]->ipc_queue = krealloc(task_table[pid]->ipc_queue, (task_table[pid]->ipc_queue_ptr + 1) * sizeof(ipc_packet_t));
task_table[pid]->ipc_queue[task_table[pid]->ipc_queue_ptr].payload = kalloc(len);
kmemcpy(task_table[pid]->ipc_queue[task_table[pid]->ipc_queue_ptr].payload, payload, len);
task_table[pid]->ipc_queue[task_table[pid]->ipc_queue_ptr].length = len;
task_table[pid]->ipc_queue[task_table[pid]->ipc_queue_ptr++].sender = current_task;
if (task_table[pid]->status == KRN_STAT_IPCWAIT_TASK)
task_table[pid]->status = KRN_STAT_ACTIVE_TASK;
return;
}
uint32_t ipc_payload_length(void) {
if (task_table[current_task]->ipc_queue_ptr)
return task_table[current_task]->ipc_queue[0].length;
else
return 0;
}
uint32_t ipc_payload_sender(void) {
if (task_table[current_task]->ipc_queue_ptr)
return task_table[current_task]->ipc_queue[0].sender;
else
return 0;
}
uint32_t ipc_resolve_name(char* server_name) {
// check for a limit overflow
if (((uint32_t)server_name + kstrlen(server_name + task_table[current_task]->base)) >= (task_table[current_task]->pages * PAGE_SIZE)) {
tty_kputs("\nIPC server name resolve request had a bogus length.", 0);
tty_kputs("\nTask terminated.\n", 0);
task_terminate(current_task);
task_scheduler();
}
server_name += task_table[current_task]->base;
// find the server name's PID
uint32_t pid;
for (pid = 0; task_table[pid]; pid++) {
if (task_table[pid] == EMPTY_PID) continue;
if (!kstrcmp(server_name, task_table[pid]->server_name)) return pid;
}
return 0;
}
uint32_t ipc_read_packet(char* payload) {
if (!task_table[current_task]->ipc_queue_ptr) return 0;
// check for a limit overflow
if (((uint32_t)payload + task_table[current_task]->ipc_queue[0].length) >= (task_table[current_task]->pages * PAGE_SIZE)) {
tty_kputs("\nIPC payload length exceeds task limit.", 0);
tty_kputs("\nTask terminated.\n", 0);
task_terminate(current_task);
task_scheduler();
}
payload += task_table[current_task]->base;
kmemcpy(payload, task_table[current_task]->ipc_queue[0].payload, task_table[current_task]->ipc_queue[0].length);
kfree(task_table[current_task]->ipc_queue[0].payload);
uint32_t pid = task_table[current_task]->ipc_queue[0].sender;
// push the queue back
for (uint32_t i = (task_table[current_task]->ipc_queue_ptr - 1); i; i--)
task_table[pid]->ipc_queue[i-1] = task_table[pid]->ipc_queue[i];
// free queue entry
task_table[current_task]->ipc_queue = krealloc(task_table[current_task]->ipc_queue,
--task_table[current_task]->ipc_queue_ptr * sizeof(ipc_packet_t));
return pid;
}
uint32_t get_heap_base(void) {
return task_table[current_task]->heap_base;
}
uint32_t get_heap_size(void) {
return task_table[current_task]->heap_size;
}
int resize_heap(uint32_t heap_size) {
uint32_t heap_pages = heap_size / PAGE_SIZE;
if (heap_size % PAGE_SIZE) heap_pages++;
uint32_t new_ptr = (uint32_t)krealloc((char*)task_table[current_task]->base,
task_table[current_task]->heap_base + heap_pages * PAGE_SIZE);
if (!new_ptr) return -1;
task_table[current_task]->base = new_ptr;
task_table[current_task]->pages = (task_table[current_task]->heap_base / PAGE_SIZE) + heap_pages;
task_table[current_task]->heap_size = heap_size;
/* reload segments */
set_segment(0x3, task_table[current_task]->base, task_table[current_task]->pages);
set_segment(0x4, task_table[current_task]->base, task_table[current_task]->pages);
return 0;
}
void* alloc(uint32_t size) { /*
// search of a big enough, free, heap chunk
heap_chunk_t* heap_chunk = (heap_chunk_t*)task_table[current_task]->heap_begin;
heap_chunk_t* new_chunk;
uint32_t heap_chunk_ptr;
again:
if ((heap_chunk->free) && (heap_chunk->size > (size + sizeof(heap_chunk_t)))) {
// split off a new heap_chunk
new_chunk = (heap_chunk_t*)((uint32_t)heap_chunk + size + sizeof(heap_chunk_t));
new_chunk->free = 1;
new_chunk->size = heap_chunk->size - (size + sizeof(heap_chunk_t));
new_chunk->prev_chunk = (uint32_t)heap_chunk;
new_chunk->prev_chunk -= task_table[current_task]->base;
heap_chunk->free = !heap_chunk->free;
heap_chunk->size = size;
return (void*)(((uint32_t)heap_chunk + sizeof(heap_chunk_t)) - task_table[current_task]->base);
} else {
heap_chunk_ptr = (uint32_t)heap_chunk;
heap_chunk_ptr += heap_chunk->size + sizeof(heap_chunk_t);
if (heap_chunk_ptr >= (task_table[current_task]->base + (task_table[current_task]->pages * 4096)))
return (void*)0; // alloc fail
heap_chunk = (heap_chunk_t*)heap_chunk_ptr;
goto again;
} */
return (void*)0;
}
void free(void* addr) { /*
uint32_t heap_chunk_ptr = (uint32_t)addr;
heap_chunk_ptr += task_table[current_task]->base;
heap_chunk_ptr -= sizeof(heap_chunk_t);
heap_chunk_t* heap_chunk = (heap_chunk_t*)heap_chunk_ptr;
heap_chunk_ptr += heap_chunk->size + sizeof(heap_chunk_t);
heap_chunk_t* next_chunk = (heap_chunk_t*)heap_chunk_ptr;
heap_chunk_t* prev_chunk;
if (heap_chunk->prev_chunk)
prev_chunk = (heap_chunk_t*)(heap_chunk->prev_chunk + task_table[current_task]->base);
else
prev_chunk = (heap_chunk_t*)0;
// flag chunk as free
heap_chunk->free = 1;
// if the next chunk is free as well, fuse the chunks into a single one
if (next_chunk->free)
heap_chunk->size += next_chunk->size + sizeof(heap_chunk_t);
// if the previous chunk is free as well, fuse the chunks into a single one
if (prev_chunk) { // if its not the first chunk
if (prev_chunk->free)
prev_chunk->size += heap_chunk->size + sizeof(heap_chunk_t);
} */
return;
}
void* realloc(void* prev_ptr, uint32_t size) {
return (void*)0;
}
void enter_iowait_status(char* dev, uint64_t loc, uint8_t payload, int type) {
dev += task_table[current_task]->base;
kstrcpy(task_table[current_task]->iowait_dev, dev);
task_table[current_task]->iowait_loc = loc;
task_table[current_task]->status = KRN_STAT_IOWAIT_TASK;
task_table[current_task]->iowait_type = type;
task_table[current_task]->iowait_payload = payload;
return;
}
void enter_vdevwait_status(void) {
task_table[current_task]->status = KRN_STAT_VDEVWAIT_TASK;
return;
}
void enter_ipcwait_status(void) {
if (!task_table[current_task]->ipc_queue_ptr)
task_table[current_task]->status = KRN_STAT_IPCWAIT_TASK;
return;
}
void pwd(char* pwd_dump) {
uint32_t pwd_dump_ptr = (uint32_t)pwd_dump;
pwd_dump_ptr += task_table[current_task]->base;
pwd_dump = (char*)pwd_dump_ptr;
kstrcpy(pwd_dump, task_table[current_task]->pwd);
return;
}
void what_stdin(char* dump) {
dump += task_table[current_task]->base;
kstrcpy(dump, task_table[current_task]->stdin);
return;
}
void what_stdout(char* dump) {
dump += task_table[current_task]->base;
kstrcpy(dump, task_table[current_task]->stdout);
return;
}
void what_stderr(char* dump) {
dump += task_table[current_task]->base;
kstrcpy(dump, task_table[current_task]->stderr);
return;
}
|
C
|
/***********TESTO ESERCIZIO***************
scrivere un programma che legge da stdin una riga alla volta (la riga si considera terminata dal carattere \n).
la lunghezza della riga è arbitraria, non fare ipotesi sulla massima lunghezza di riga.
[in questo esercizio, non occorre immagazzinare l'intera riga].
calcolare la media della lunghezza (=numero di caratteri) delle righe lette che vengono lette da stdin.
dopo ogni riga letta, mostrare la lunghezza della riga e la media "parziale" fino a quel momento.
il programma termina in caso di EOF su stdin.
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int c;
int count_tot = 0; //contatore per il numero totale di caratteri su tutte le righe
int count_current = 0; //contatore per il numero di caratteri su una riga
int n_righe = 0; //contatore per il numero di righe
float media; //media parziale del numero di caratteri su tutte le righe
printf("Inserisci del testo : \n");
while ((c = getchar()) != EOF) {
count_current++;
if(c == '\n'){
n_righe++;
count_tot += count_current;
media = (float)(count_tot) / (float)(n_righe);
printf("\nRiga numero %d, lunghezza = %d caratteri, media parziale di caratteri = %f\n", n_righe, count_current, media);
count_current = 0;
}
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* search_path_t.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sirvin <sirvin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/09/26 21:53:26 by sirvin #+# #+# */
/* Updated: 2020/09/30 17:04:10 by sirvin ### ########.fr */
/* */
/* ************************************************************************** */
#include "../inc/lemin.h"
t_queue *new_t_queue(void)
{
t_queue *tr;
tr = (t_queue *)malloc(sizeof(t_queue));
tr->first = NULL;
tr->last = NULL;
return (tr);
}
void iap(t_queue **tv, int s, int *rp, t_map *m)
{
*tv = new_t_queue();
push(*tv, new_list(s));
get_room_pointers(rp, m);
}
t_list *get_augmenting_path(t_map *map, int start, int end, int *room_pointers)
{
t_list *path;
t_queue *to_visit;
t_list *i;
int room;
t_list *connecting_rooms;
iap(&to_visit, start, room_pointers, map);
while (!is_empty(to_visit))
{
room = pop_to_visit(to_visit);
connecting_rooms = get_connecting_rooms(room, map, end);
i = connecting_rooms;
while (i)
{
if (gfp((int *)i->content) != end || room_pointers[end] == end)
room_pointers[gfp((int *)i->content)] = room;
visit(gfp((int *)i->content), map);
push(to_visit, new_list(gfp((int *)i->content)));
i = i->next;
}
ft_lstdel(&connecting_rooms, &delete_info);
}
path = get_path(map, end, room_pointers);
free(to_visit);
return (path);
}
void get_room_pointers(int *room_pointers, t_map *map)
{
int i;
i = 0;
while (i < map->num_of_rooms)
{
room_pointers[i] = i;
i++;
}
}
int is_empty(t_queue *queue)
{
return (queue->first == NULL);
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <ctype.h>
int p[2];
void
aleatorios (int sig){
int aleatorio;
aleatorio = rand() % 10;
write(p[1], &aleatorio, sizeof(int));
}
int
main (void){
// Variables
pid_t PID;
char buffer[1024];
int N;
// Fin Variables
pipe(p);
PID = fork();
if (PID < 0){ //Error al crear proceso hijo
fprintf(stderr, "Error al crear proceso hijo");
exit(1);
} else if (PID == 0){ // Proceso Hijo
close(p[0]);
signal(SIGUSR1, aleatorios);
for(;;){
pause();
}
close(p[1]);
exit(0);
} else { // Proceso Padre
close(p[1]);
while (fgets(buffer, 1024, stdin) != NULL){
kill(PID, SIGUSR1);
read(p[0], &N, sizeof(int));
printf("El numero aleatorio es: %d \n", N);
}
close(p[0]);
kill(PID, SIGINT);
wait(NULL);
}
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct phy_device {scalar_t__ state; scalar_t__ link; scalar_t__ loopback_enabled; int /*<<< orphan*/ lock; } ;
/* Variables and functions */
scalar_t__ PHY_NOLINK ;
scalar_t__ PHY_RUNNING ;
int /*<<< orphan*/ WARN_ON (int) ;
int /*<<< orphan*/ mutex_is_locked (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ phy_link_down (struct phy_device*,int) ;
int /*<<< orphan*/ phy_link_up (struct phy_device*) ;
int phy_read_status (struct phy_device*) ;
__attribute__((used)) static int phy_check_link_status(struct phy_device *phydev)
{
int err;
WARN_ON(!mutex_is_locked(&phydev->lock));
/* Keep previous state if loopback is enabled because some PHYs
* report that Link is Down when loopback is enabled.
*/
if (phydev->loopback_enabled)
return 0;
err = phy_read_status(phydev);
if (err)
return err;
if (phydev->link && phydev->state != PHY_RUNNING) {
phydev->state = PHY_RUNNING;
phy_link_up(phydev);
} else if (!phydev->link && phydev->state != PHY_NOLINK) {
phydev->state = PHY_NOLINK;
phy_link_down(phydev, true);
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* bubblesort.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kdumarai <kdumarai@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/15 18:26:31 by kdumarai #+# #+# */
/* Updated: 2018/01/15 18:49:12 by kdumarai ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <stdlib.h>
void sort_tab(int *tab, size_t len)
{
unsigned int idx;
int bak;
idx = 1;
while (idx < len)
{
if (tab[idx - 1] > tab[idx])
{
bak = tab[idx];
tab[idx] = tab[idx - 1];
tab[idx - 1] = bak;
idx = 0;
}
idx++;
}
}
void show_tab(int *tab, size_t len)
{
unsigned int idx;
idx = 0;
while (idx < len)
{
printf("tab[%i] = %i\n", idx, tab[idx]);
idx++;
}
}
int main(void)
{
int tab[320];
size_t len;
unsigned int cnt;
cnt = 0;
len = sizeof(tab) / sizeof(int);
while (cnt < len)
tab[cnt++] = arc4random_uniform(100);
puts("unsorted:");
show_tab(tab, len);
puts("\nsorting...");
sort_tab(tab, len);
puts("\nsorted");
show_tab(tab, len);
return (0);
}
|
C
|
#ifndef __LINKED_LIST_H__
#define __LINKED_LIST_H__
typedef struct Node Node;
typedef struct List_t List;
List* create_list(void);
void insert_first(List *list, int val);
void insert_last(List *list, int val);
void insert_after(List *list, Node *node, int val);
void insert_before(List *list, Node *node, int val);
void insert_sorted(List *list, int val);
Node *search(List *list, int key);
Node *mov_to_head_search(List *list, int key);
void reverse_w_val(List *list);
void reverse_w_links(List *list);
void display(List *list);
void display_all(List *list);
void delete_first(List *list);
void delete(List *list, Node *node);
void remove_v(List *list, int val);
void destroy(List *list);
void concatenate(List **dest, List **src);
int is_sorted(List *list);
List* merge(List **list1, List **list2);
#endif
|
C
|
#include "map.h"
#include "tools.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
enum Const
{
Search_mark = 's',
Bad_map = 'B',
};
const scalar Ship_sizes[ Max_ship_size+1] = { 0, 4, 3, 2, 1};
scalar map_set( struct map_t *map, scalar x, scalar y, scalar val);
scalar map_check_ship( struct map_t *map, scalar x, scalar y);
scalar is_ship( scalar current); //0 if false
void map_destroy_ship( struct map_t *map, scalar x, scalar y);
struct map_t *map_new_clone( struct map_t * map);
scalar map_get_ship_size( struct map_t *search_map, scalar i, scalar j);
scalar bad_map_if_ship( struct map_t *search_map, scalar x, scalar y);
struct map_t *map_new( scalar x_size, scalar y_size)
{
struct map_t * new_map = malloc( sizeof( struct map_t));
if( new_map == NULL)
{
return NULL;
}
new_map->ptr = malloc( sizeof( scalar) * x_size*y_size);
if( new_map->ptr == NULL)
{
free( new_map);
return NULL;
}
for( int i = 0; i < x_size*y_size; i++)
{
new_map->ptr[ i] = Empty;
}
new_map->x_size = x_size;
new_map->y_size = y_size;
new_map->ships_count = 0;
return new_map;
}
void map_delete( struct map_t *map)
{
free( map->ptr);
free( map);
}
scalar map_get( struct map_t *map, scalar x, scalar y)
{
if( !( 0 <= x && x < map->x_size))
{
return Out_of_range;
}
if( !( 0 <= y && y < map->y_size))
{
return Out_of_range;
}
return map->ptr[ x + y*map->x_size];
}
scalar map_set( struct map_t *map, scalar x, scalar y, scalar val)
{
if( !( 0 <= x && x < map->x_size))
{
return Out_of_range;
}
if( !( 0 <= y && y < map->y_size))
{
return Out_of_range;
}
return map->ptr[ x + y*map->x_size] = val;
}
int map_dump( struct map_t *map)
{
printf( "Map dump start\n");
printf( "x_size = %d\n", map->x_size);
printf( "y_size = %d\n", map->y_size);
for( int j = 0; j < map->y_size; j++)
{
for( int i = 0; i < map->x_size; i++)
{
printf( "%c ", ( char)map_get( map, i, j));
}
printf( "\n");
}
printf( "Map dump end\n");
return 0;
}
int map_dump_scalar( struct map_t *map)
{
printf( "Map dump start\n");
printf( "x_size = %d\n", map->x_size);
printf( "y_size = %d\n", map->y_size);
for( int j = 0; j < map->y_size; j++)
{
for( int i = 0; i < map->x_size; i++)
{
printf( "%2d ", map_get( map, i, j));
}
printf( "\n");
}
printf( "Map dump end\n");
return 0;
}
scalar map_fire( struct map_t *map, scalar x, scalar y)
{
scalar aim = map_get( map, x, y);
if( ! is_ship( aim))
{
map_set( map, x, y, Hit);
return Hit;
}
if( is_ship( aim) && aim != Destroyed_ship)
{
map_set( map, x, y, Hit_ship);
map_check_ship( map, x, y);
return Hit_ship;
}
return 0;
}
struct map_t *file_to_new_map( const char * filename)
{
FILE *in_file = fopen( filename, "r");
if( in_file == NULL)
{
return NULL;
}
scalar x = 0, y = 0;
fscanf( in_file, "%u\n", &x);
fscanf( in_file, "%u\n", &y);
struct map_t *new_map = map_new( x, y);
for( int j = 0; j < y; j++)
{
for( int i = 0; i < x; i++)
{
char symbol = 0, space = 0;
fscanf( in_file, "%c%c", &symbol, &space);
map_set( new_map, i, j, symbol);
}
}
fclose( in_file);
return new_map;
}
scalar map_check_ship( struct map_t *map, scalar x, scalar y)
{
scalar hit_count = 0;
scalar count = 0;
scalar current = map_get( map, x, y);
if( !is_ship( current))
{
return current;
}
int x0 = x;
current = map_get( map, x0, y);
while( is_ship( current))
{
current = map_get( map, x0, y);
if( current == Hit_ship)
{
hit_count++;
}
if( current == Destroyed_ship)
{
return Destroyed_ship;
}
x0++;
if( is_ship( current))
{
count++;
}
}
x0 = x-1;
current = map_get( map, x0, y);
while( is_ship( current))
{
current = map_get( map, x0, y);
if( current == Hit_ship)
{
hit_count++;
}
if( current == Destroyed_ship)
{
return Destroyed_ship;
}
x0--;
if( is_ship( current))
{
count++;
}
}
int y0 = y+1;
current = map_get( map, x, y0);
while( is_ship( current))
{
current = map_get( map, x, y0);
if( current == Hit_ship)
{
hit_count++;
}
if( current == Destroyed_ship)
{
return Destroyed_ship;
}
y0++;
if( is_ship( current))
{
count++;
}
}
y0 = y-1;
current = map_get( map, x, y0);
while( is_ship( current))
{
current = map_get( map, x, y0);
if( current == Hit_ship)
{
hit_count++;
}
if( current == Destroyed_ship)
{
return Destroyed_ship;
}
y0--;
if( is_ship( current))
{
count++;
}
}
if( count == hit_count)
{
map_destroy_ship( map, x, y);
return Destroyed_ship;
}
if( hit_count != 0)
{
return Hit_ship;
}
return Ship_any;
}
scalar is_ship( scalar current)
{
if( ( Ship_any <= current && current <= Ship_biggest)
|| current == Hit_ship
|| current == Destroyed_ship)
{
return current;
}
return 0;
}
void map_destroy_ship( struct map_t *map, scalar x, scalar y)
{
scalar current = map_get( map, x, y);
if( is_ship( current) && current != Destroyed_ship)
{
map_set( map, x, y, Destroyed_ship);
map_destroy_ship( map, x+1, y);
map_destroy_ship( map, x-1, y);
map_destroy_ship( map, x, y+1);
map_destroy_ship( map, x, y-1);
}
}
struct map_t *map_get_map_for_enemy( struct map_t * map)
{
struct map_t *enemy_map = map_new_clone( map);
if( enemy_map == NULL)
{
return NULL;
}
for( int i = 0; i < enemy_map->x_size; i++)
{
for( int j = 0; j < enemy_map->y_size; j++)
{
scalar current = map_get( enemy_map, i, j);
if( current != Hit
&& current != Destroyed_ship
&& current != Hit_ship)
{
map_set( enemy_map, i, j, Hidden);
}
}
}
return enemy_map;
}
struct map_t *map_update_enemy_map( struct map_t *dst, struct map_t *src)
{
for( int i = 0; i < dst->x_size; i++)
{
for( int j = 0; j < dst->y_size; j++)
{
scalar current = map_get( src, i, j);
if( current != Hit
&& current != Destroyed_ship
&& current != Hit_ship)
{
map_set( dst, i, j, Hidden);
}
else
{
map_set( dst, i, j, current);
}
}
}
return dst;
}
struct map_t *map_new_clone( struct map_t * map)
{
struct map_t *new_map = map_new( map->x_size, map->y_size);
if( new_map == NULL)
{
return NULL;
}
memcpy( new_map->ptr, map->ptr, sizeof( scalar) * map->x_size*map->y_size);
new_map->x_size = map->x_size;
new_map->y_size = map->y_size;
return new_map;
}
scalar map_is_correct( struct map_t *map)
{
scalar is_correct = 1;
struct map_t *search_map = map_new_clone( map);
scalar found_ships[ Max_ship_size+1] = { 0, 0, 0, 0, 0};
for( int i = 0; i < search_map->x_size; i++)
{
for( int j = 0; j < search_map->y_size; j++)
{
scalar current = map_get( search_map, i, j);
if( current == Search_mark )
{
continue;
}
if( is_ship( current))
{
scalar size = map_get_ship_size( search_map, i, j);
if( size == Bad_map)
{
map_delete( search_map);
return 0;
}
if( 0 < size && size <= Max_ship_size)
{
found_ships[ size]++;
}
}
map_set( search_map, i, j, Search_mark);
}
}
map_delete( search_map);
for( int i = 0; i <= Max_ship_size; i++)
{
if( found_ships[ i] != Ship_sizes[ i])
{
printf( "Warning: ships with length %d expected %d, but found %d\n",
i, Ship_sizes[ i], found_ships[ i]);
is_correct = 0;
}
}
return is_correct;
}
scalar map_get_ship_size( struct map_t *search_map, scalar x, scalar y)
{
scalar result = 0;
scalar current = map_get( search_map, x, y);
if( !is_ship( current))
{
return result = 0;
}
if( is_ship( map_get( search_map, x-1, y)))
{
if( bad_map_if_ship( search_map, x, y+1)
|| bad_map_if_ship( search_map, x, y-1))
{
return Bad_map;
}
else
{
map_set( search_map, x, y+1, Search_mark);
map_set( search_map, x, y-1, Search_mark);
}
return result = map_get_ship_size( search_map, x-1, y);
}
else if( is_ship( map_get( search_map, x, y-1)))
{
if( bad_map_if_ship( search_map, x+1, y)
|| bad_map_if_ship( search_map, x-1, y))
{
return Bad_map;
}
else
{
map_set( search_map, x+1, y, Search_mark);
map_set( search_map, x-1, y, Search_mark);
}
return result = map_get_ship_size( search_map, x, y-1);
}
if( is_ship( map_get( search_map, x+1, y)))
{//Horizontal
if( bad_map_if_ship( search_map, x-1, y-1)
|| bad_map_if_ship( search_map, x-1, y)
|| bad_map_if_ship( search_map, x-1, y+1))
{
return Bad_map;
}
scalar offset = 0;
scalar current = map_get( search_map, x, y);
while( is_ship( current))
{
if( bad_map_if_ship( search_map, x+offset, y+1)
|| bad_map_if_ship( search_map, x+offset, y-1))
{
return Bad_map;
}
map_set( search_map, x+offset, y, Search_mark);
offset++;
current = map_get( search_map, x+offset, y);
}
result = offset;
if( bad_map_if_ship( search_map, x+offset, y-1)
|| bad_map_if_ship( search_map, x+offset, y)
|| bad_map_if_ship( search_map, x+offset, y+1))
{
return Bad_map;
}
return result;
}
else if( is_ship( map_get( search_map, x, y+1)))
{//Vertical
if( bad_map_if_ship( search_map, x-1, y-1)
|| bad_map_if_ship( search_map, x, y-1)
|| bad_map_if_ship( search_map, x+1, y-1))
{
return Bad_map;
}
scalar offset = 0;
scalar current = map_get( search_map, x, y);
while( is_ship( current))
{
if( bad_map_if_ship( search_map, x+1, y+offset)
|| bad_map_if_ship( search_map, x-1, y+offset))
{
return Bad_map;
}
map_set( search_map, x, y+offset, Search_mark);
offset++;
current = map_get( search_map, x, y+offset);
}
result = offset;
if( bad_map_if_ship( search_map, x-1, y+offset)
|| bad_map_if_ship( search_map, x, y+offset)
|| bad_map_if_ship( search_map, x+1, y+offset))
{
return Bad_map;
}
return result;
}
else
{//Single
if( bad_map_if_ship( search_map, x-1, y-1)
|| bad_map_if_ship( search_map, x-1, y)
|| bad_map_if_ship( search_map, x-1, y+1)
|| bad_map_if_ship( search_map, x, y-1)
|| bad_map_if_ship( search_map, x, y+1)
|| bad_map_if_ship( search_map, x+1, y-1)
|| bad_map_if_ship( search_map, x+1, y)
|| bad_map_if_ship( search_map, x+1, y+1))
{
return Bad_map;
}
else
{
map_set( search_map, x, y, Search_mark);
return 1;
}
}
return 0;
}
scalar bad_map_if_ship( struct map_t *search_map, scalar x, scalar y)
{
if( is_ship( map_get( search_map, x, y)))
{
return Bad_map;
}
else
{
map_set( search_map, x, y, Search_mark);
return 0;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char s[40], crypt[200], vis[200];
typedef struct node {
char c;
struct node *nxt;
} node;
int main() {
char ch;
int len, i, num;
FILE *in = fopen("in.txt", "r"), *out = fopen("in_crpyt.txt", "w");
node *head = (node*) malloc(sizeof(node)), *cur = head, *tmp, *tmp2;
scanf("%[^\n]", s);
len = strlen(s);
head->c = s[0];
vis[s[0]]=1;
for (i = 1; i < len; i++) {
if (!vis[s[i]]) {
vis[s[i]] = 1;
tmp = (node*) malloc(sizeof(node));
tmp->c = s[i];
cur->nxt = tmp;
cur = tmp;
}
}
for (i = 32; i <= 126; i++) {
if (!vis[i]) {
vis[i] = 1;
tmp = (node*) malloc(sizeof(node));
tmp->c = i;
cur->nxt = tmp;
cur = tmp;
}
}
cur->nxt = head;
tmp2 = cur;
cur = head;
while (cur->nxt != cur) {
num = cur->c;
tmp = cur;
cur = cur->nxt;
tmp2->nxt = cur;
free(tmp);
for (i = 1; i < num; i++) {
cur = cur->nxt;
tmp2 = tmp2->nxt;
}
crypt[num] = cur->c;
}
crypt[cur->c] = s[0];
while ((ch = getc(in)) != EOF) {
if (ch >= 32 && ch <= 126) putc(crypt[ch], out);
else putc(ch, out);
}
fclose(in);
fclose(out);
return 0;
}
|
C
|
/**
**************************************************************
* @file mylib/atimer/s4353737_hal_atimer
* @author George Todorovic - 43537370
* @date 30032020
* @brief Atimer driver files
* REFERENCE: csse3010_mylib_hal_atimer.pdf
***************************************************************
* EXTERNAL FUNCTIONS
***************************************************************
* sxxxxxx_mylib_template_init() - intialise mylib template driver
* sxxxxxx_mylib_template_set() - set mylib template driver
***************************************************************
*/
/* Private define -------------------------------------------- */
#define ON 1
#define OFF 0
/* Includes -------------------------------------------------- */
#include "board.h"
#include "processor_hal.h"
#include "debug_printf.h"
#include "s4353737_hal_atimer.h"
#include "s4353737_hal_joystick.h"
#include "s4353737_hal_lta1000g.h"
#include "s4353737_hal_pwm.h"
#include "s4353737_hal_iss.h"
/* Private variables ----------------------------------------- */
unsigned short ledSeg;
int pinState = S4353737_HAL_JOYSTICK_Z_READ();
//store the pin values for looping
uint16_t pinArrays[10] = {BRD_D16_PIN,
BRD_D17_PIN,
BRD_D18_PIN,
BRD_D19_PIN,
BRD_D20_PIN,
BRD_D21_PIN,
BRD_D22_PIN,
BRD_D23_PIN,
BRD_D24_PIN,
BRD_D25_PIN};
//store the port values for looping
GPIO_TypeDef* portArrays[10] = {BRD_D16_GPIO_PORT,
BRD_D17_GPIO_PORT,
BRD_D18_GPIO_PORT,
BRD_D19_GPIO_PORT,
BRD_D20_GPIO_PORT,
BRD_D21_GPIO_PORT,
BRD_D22_GPIO_PORT,
BRD_D23_GPIO_PORT,
BRD_D24_GPIO_PORT,
BRD_D25_GPIO_PORT};
/* Prototype functions --------------------------------------- */
void init_hardware();
void run_atimer();
void yadc_increment_led();
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin);
void EXTI3_IRQHandler();
int main() {
init_hardware();
uint32_t current_val = 0;
uint32_t next_val = 0;
uint8_t mode = 0;
while(1) {
int xAdcValue = S4353737_HAL_JOYSTICK_X_READ();
run_atimer();
yadc_increment_led();
current_val = S4353737_PWM_DC_GET();
if (mode) {
next_val = (uint32_t)(current_val*1.1);
} else {
next_val = (uint32_t)(current_val*0.9);
}
S4353737_PWM_DC_SET(2*xAdcValue);
if ((next_val > S4353737_HAL_PWM_PULSEPERIOD*20) && (mode == 1)) {
mode = 0;
}
if ((next_val < S4353737_HAL_PWM_PULSEPERIOD) && (mode == 0)) {
mode = 1;
}
}
}
/**
* @brief Increment the upper segment of LED's on the board as the via the value
* returned on the yAdc.
* @param None
* @retval None
*/
void yadc_increment_led() {
int yAdcValue = S4353737_HAL_JOYSTICK_Y_READ();
if(yAdcValue < 2000) {
if(yAdcValue < 50 && yAdcValue > 0) {
ledSeg = 1023;
}
if(yAdcValue < 500 && yAdcValue > 51) {
ledSeg = 511;
}
if(yAdcValue < 760 && yAdcValue > 501) {
ledSeg = 255;
}
if(yAdcValue < 1140 && yAdcValue > 761) {
ledSeg = 127;
}
if(yAdcValue < 1520 && yAdcValue > 1141) {
ledSeg = 63;
}
}
else if(yAdcValue < 2100) {
ledSeg = 31;
}
if(yAdcValue > 2475) {
ledSeg = 63;
}
if(yAdcValue > 2850) {
ledSeg = 127;
}
if(yAdcValue > 3375) {
ledSeg = 255;
}
if(yAdcValue > 4050) {
ledSeg = 511;
}
if(yAdcValue > 4051) {
ledSeg = 1023;
}
s4353737_hal_lta1000g_write(ledSeg);
}
/**
* @brief Initialise driver hardware
* @param None
* @retval None
*/
void init_hardware() {
BRD_init();
s4353737_hal_pwm_init();
s4353737_hal_atimer_init();
s4353737_hal_atimer_init_pin();
s4353737_hal_joystick_init();
s4353737_hal_lta1000g_init();
}
/**
* @brief Waits for user input to display information about the current
* values of the atimer
* @param None
* retval None
*/
void run_atimer() {
char RxChar = debug_getc();
if(RxChar != '\0') {
switch(RxChar) {
case 'f':
s4353737_hal_atimer_timer_pause();
s4353737_hal_atimer_init();
break;
case 'r':
s4353737_hal_atimer_resume();
break;
case 'z':
s4353737_hal_atimer_timer_reset();
break;
case 'c':
debug_printf("atimer tick: %d\n\r", s4353737_hal_atimer_getms()*
s4353737_hal_atimer_clkspeed_get());
break;
case 't':
debug_printf("atimer ms: %d\n\r", s4353737_hal_atimer_getms());
break;
case '+':
s4353737_hal_atimer_period_set(s4353737_hal_atimer_clkspeed_get()/100);
s4353737_hal_atimer_init();
break;
case '-':
s4353737_hal_atimer_period_set(-(s4353737_hal_atimer_clkspeed_get()/100));
s4353737_hal_atimer_init();
break;
case 'i':
s4353737_hal_atimer_period_set(s4353737_hal_get_period()/(s4353737_hal_atimer_clkspeed_get()/1000));
s4353737_hal_atimer_clkspeed_set(1000);
s4353737_hal_atimer_init();
break;
case 'd':
s4353737_hal_atimer_clkspeed_set(-1000);
s4353737_hal_atimer_period_set(s4353737_hal_get_period()/(s4353737_hal_atimer_clkspeed_get()/1000));
s4353737_hal_atimer_init();
break;
}
}
}
/**
* @brief GPIO Interrupt call function. LED lights will switch on or off
depending on their current state.
* @param GPIO_Pin: The pin to be on which an interrupt occurs.
* @retval None
*/
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
if(GPIO_Pin == BRD_A3_PIN) {
unsigned int tempEvent =
s4353737_hal_iss_eventcounter_read(S4353737_HAL_ISS_SOURCE_3);
s4353737_hal_iss_synchroniser(S4353737_HAL_ISS_SOURCE_3);
if(s4353737_hal_iss_eventcounter_read(S4353737_HAL_ISS_SOURCE_3) == 11) {
s4353737_hal_iss_eventcounter_reset(S4353737_HAL_ISS_SOURCE_3);
}
if(s4353737_hal_iss_eventcounter_read(S4353737_HAL_ISS_SOURCE_3)
!= tempEvent) {
if(pinState == ON) {
for(int i = 0; i < 10; i++) {
HAL_GPIO_DeInit(portArrays[i], pinArrays[i]);
pinState = OFF;
}
} else {
s4353737_hal_lta1000g_init();
pinState = ON;
}
}
}
}
/**
* @brief Overrider default mapping of this handler
* @param None
* @retval None
*/
void EXTI3_IRQHandler() {
HAL_GPIO_EXTI_IRQHandler(BRD_A3_PIN);
}
|
C
|
#include "inheritence_defs.h"
const char* getName(Types type)
{
const char* const names[] = { "Plastic", "Metal", "Wood", "Paper", "Other" };
return names[type];
}
void _ZN11PhysicalBoxC1Eddd(PhysicalBox* const this, double l, double w, double h)
{
_ZN3BoxC1Eddd((Box*)this, l, w, h);
this->material.material = OTHER;
printf("Material created, set to %s\n", getName(this->material.material));
printp(this);
}
void _ZN11PhysicalBoxC1EdddN9Materials5TypesE(PhysicalBox* const this,
double l,
double w,
double h, Types t)
{
_ZN3BoxC1Eddd((Box*)this, l, w, h);
this->material.material = t;
printf("Material created, set to %s\n", getName(this->material.material));
printp(this);
}
void _ZN11PhysicalBoxC2EN9Materials5TypesE(PhysicalBox* const this, Types t)
{
_ZN3BoxC1Ed((Box*)this,1);
this->material.material = t;
printf("Material created, set to %s\n", getName(this->material.material));
printp(this);
}
void _ZN11PhysicalBoxD1Ev(PhysicalBox* const this)
{
printf("PhysicalBox dtor, %f x %f x %f, %s; ", this->box.length, this->box.width, this->box.height, getName(this->material.material));
_ZN3BoxD1Ev((Box*)this);
}
void printp(const PhysicalBox* const this)
{
printf("PhysicalBox, made of %s; ", getName(this->material.material));
_ZNK3Box5printEv((Box*)this);
}
/*weight*/
void _ZN9WeightBoxC1Edddd(WeightBox* const this, double l, double w, double h, double wgt)
{
_ZN3BoxC1Eddd((Box*)this, l,w,h);
this->weight = wgt;
_ZNK9WeightBox6printwEv(this);
}
void _ZN9WeightBoxC1ERKS_(WeightBox* const this,const WeightBox* const other)/*cpy ctor*/
{
_ZN3BoxC1Ed((Box*)this,1);
this->weight = other->weight;
_ZNK9WeightBox6printwEv(this);
}
void _ZN9WeightBoxD1Ev(WeightBox* const this)/*dtor*/
{
printf("Destructing WeightBox; ");
_ZNK9WeightBox6printwEv(this);
_ZN3BoxD1Ev((Box*)this);
}
void _ZNK9WeightBox6printwEv(const WeightBox* const this)
{
printf("WeightBox, weight: %f; ", this->weight);
_ZNK3Box5printEv((Box*)this);
}
WeightBox _ZN9WeightBoxaSERKS_(WeightBox* const this, const WeightBox* const other)
{
this->weight = other->weight;
return *this;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** CPE_matchstick_2019
** File description:
** ia_turn.c
*/
#include <stdlib.h>
#include "include/my.h"
int maj_ia(map_t *map)
{
int i = map->first;
for (; map->buffer[map->line_ia][i] != '|'; i--);
for (int j = 0; j != map->nb_ia_rm; j++, i--)
if (map->buffer[map->line_ia][i] == '|')
map->buffer[map->line_ia][i] = ' ';
display_map(map);
return (0);
}
void ia_turn(map_t *map)
{
int pipes = 0;
map->line_ia = rand() % map->line_nb + 1;
map->nb_ia_rm = rand() % map->matches;
while (map->line_ia == 0)
map->line_ia = rand() % map->line_nb + 1;
pipes = pipes_in_line(map, pipes);
while (pipes == 0) {
map->line_ia = rand() % map->line_nb + 1;
pipes = pipes_in_line(map, pipes);
}
while (map->nb_ia_rm > pipes || map->nb_ia_rm == 0)
map->nb_ia_rm = rand() % map->matches;
my_printf("\nAI's turn...\n");
my_printf("AI removed %d ", map->nb_ia_rm);
my_printf("match(es) from line %d\n", map->line_ia);
maj_ia(map);
}
|
C
|
#include "stm32f0xx_rcc.h"
#include "stm32f0xx_gpio.h"
#include "led.h"
#define LED_RCC RCC_AHBPeriph_GPIOC
#define LED_PORT GPIOC
#define LED_PIN GPIO_Pin_13
void led_init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHBPeriphClockCmd(LED_RCC, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
}
void led_on(void)
{
LED_PORT->BSRR = LED_PIN;
}
void led_off(void)
{
LED_PORT->BRR = LED_PIN;
}
void led_toggle(void)
{
if (LED_PORT->ODR & LED_PIN)
LED_PORT->BRR = LED_PIN;
else
LED_PORT->BSRR = LED_PIN;
}
|
C
|
#ifndef _FINDPEAKS_H_
#define _FINDPEAKS_H_
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
/*
* find the peak in an array.
*
* Input
* ------------------------------------------
* data: the data array
* length: the array length
* peaks: the peaks found in the array
* index: the index of the found peaks in the array
* maxnum: the maxinum num of the peaks allowed
*
* Output
* ------------------------------------------
* return the peaks num
*/
int findpeaks(double *data,int length,double *peaks,int *index,int maxnum);
/*
* find the peak in arrays.
*
* Input
* ------------------------------------------
* data: the data array
* length: the array length
* batch: the array number
* peaks: the peaks found in the array
* index: the index of the found peaks in the array
* peaks_num: the peaks num of every array
* maxnum: the maxinum num of the peaks allowed
*/
void findpeaks(double *data,int length,int batch,double *peaks,int *index,int *peaks_num,int maxnum);
#endif
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cs50.h>
#include <ctype.h>
#define ALPHABET_COUNT 26
string encrypt(string text, string key);
bool valid_key(string key);
int main(int argc, char* argv[])
{
if (argc != 2)
{
printf("Include the key as a command-line argument!\n");
return 1;
}
if (!valid_key(argv[1]))
{
printf("Key must be made of only alphebetical charchaters!\n");
return 1;
}
else
{
string keyword = argv[1];
string text = GetString();
string cypher = encrypt(text, keyword);
printf("%s\n", cypher);
free(cypher);
}
return 0;
}
string encrypt(string text, string keyword)
{
/*
encrypts and returns a string using the key as a shift value
*/
// printf("inputs: text=%s , key=%i\n", text, key);
string cypher = malloc(strlen(text) * sizeof(char));
int key_index = 0;
int len_keyword = strlen(keyword);
for (int i = 0; i < strlen(text); i++)
{
if (isalpha(text[i]))
{
char key = keyword[key_index % len_keyword];
// how much to subtract depending on case of a char in a keyword
char offset = isupper(key) ? 'A' : 'a';
// printf("Key is %c\n", key);
if (islower(text[i]))
{
// printf("lower, %c\n", text[i]);
// subtract 'a' to make counting start from 0
// then add it again when encrypting
cypher[i] = (text[i] - 'a' + key - offset) % ALPHABET_COUNT + 'a';
}
else
{
// printf("upper, %c\n", text[i]);
cypher[i] = (text[i] - 'A' + key - offset) % ALPHABET_COUNT + 'A';
}
key_index++;
}
else
{
cypher[i] = text[i];
}
}
return cypher;
}
bool valid_key(string key)
{
/*
takes a key as a string and makes sure it's all digits
*/
for (int i = 0; i < strlen(key); i++)
{
if (!isalpha(key[i]))
{
return false;
}
}
return true;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <sys/timeb.h>
#define R 6371.8
#define TO_RAD(val) (val * (M_PI / 180))
void main(void)
{
struct timeb start, stop;
double elapsed;
int i;
ftime(&start);
for(i=0; i < 1000000000; i++)
{
double lat1 = 58.7530;
double lon1 = 17.0115;
double lat2 = 58.7515;
double lon2 = 16.9857;
double d_lat = TO_RAD(lat2 - lat1);
double d_lon = TO_RAD(lon2 - lon1);
lat1 = TO_RAD(lat1);
lat2 = TO_RAD(lat2);
double a = pow(sin(d_lat / 2), 2) + cos(lat1) * cos(lat2) * pow(sin(d_lon / 2), 2);
double c = 2 * asin(sqrt(a));
double result = R * c;
}
ftime(&stop);
elapsed = ((double) stop.time + ((double) stop.millitm * 0.001)) -
((double) start.time + ((double) start.millitm * 0.001));
printf("%f \n", elapsed);
}
|
C
|
/**
****************************************************************************************
*
* @file airmouse.h
*
* Copyright (C) Shanghai Tropos Microelectronics Co., Ltd. 2018~2020
*
****************************************************************************************
*/
#ifndef AIRMOUSE_H
#define AIRMOUSE_H
/* Include Files
****************************************************************************************
*/
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
/* Macro Definition
****************************************************************************************
*/
#define M_SAMPLE_FREQUENCY (100)//unit: Hz
#define M_ACC_1G_COUNT (4096)//ٶΪ1gʱֵ(1 LSB)the count value when
#define M_GYRO_1DS_COUNT (16)//ٶΪ1/ʱֵ(1 LSB)
#define M_SENSITIVITY (32)//ȣֵԽƶԽ
/* Enum Definition
****************************************************************************************
*/
/* Struct Definition
****************************************************************************************
*/
typedef struct
{
int16_t accX;
int16_t accY;
int16_t accZ;
int16_t gyroX;
int16_t gyroY;
int16_t gyroZ;
}
amSensor_t;
typedef struct
{
int8_t x;
int8_t y;
}
amMouse_t;
typedef struct
{
amSensor_t sensor;
amMouse_t mouse;
}
amAirMouse_t;
/* Function Declaration
****************************************************************************************
*/
/* Global Variable
****************************************************************************************
*/
/* Function Definition
****************************************************************************************
*/
bool airmouseInit(int16_t sFreq, int16_t accGCount, int16_t gyroDsCount, int16_t sen);
void airmouseConversion(amAirMouse_t *amData);
/* Example:
{
bool result;
amAirMouse_t data = {0};
result = airmouseInit(M_SAMPLE_FREQUENCY, M_ACC_1G_COUNT, M_GYRO_1DS_COUNT, M_SENSITIVITY);
if(result == false)
return;
while(SAMPLE_FREQUENCY is reached)
{
data.sensor.accX = accXReal;
data.sensor.accY = accYReal;
data.sensor.accZ = accZReal;
data.sensor.gyroX = gyroXReal;
data.sensor.gyroY = gyroYReal;
data.sensor.gyroZ = gyroZReal;
airmouseConversion(&data);
printf("x=%d, y=%d\r\n", data.mouse.x, data.mouse.y);
}
}
*/
/* Note:
If the direction of X&Y output is wrong, change
the sign and the sequence of sensor's X&Y&Z input, and retry.
*/
#endif
|
C
|
#define F_CPU 16000000UL
#include <inttypes.h>
#include <compat/twi.h>
#include "i2cmaster.h"
/* I2C clock in Hz */
#define SCL_CLOCK 100000L
/*************************************************************************
Initialization of the I2C bus interface. Need to be called only once
*************************************************************************/
void i2c_init(void)
{
/* initialize TWI clock: 100 kHz clock, TWPS = 0 => prescaler = 1 */
TWSR = 0; /* no prescaler */
TWBR = ((F_CPU/SCL_CLOCK)-16)/8; /* must be > 10 for stable operation */
}/* i2c_init */
/*************************************************************************
Issues a start condition and sends address and transfer direction.
return 0 = device accessible, 1= failed to access device
*************************************************************************/
unsigned char i2c_start(unsigned char address)
{
/* COMPLETE CODE steps 1 to 5.1 */
/* Instead of ERROR() -> return 1 */
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
while(!(TWCR & (1 << TWINT)));
if ((TWSR & 0xF8) != 0x08) return 1; //START EN DATASHEET (DUDA)
TWDR=address; //NO SABEMOS COMO (DUDA)
TWCR= (1 << TWINT) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)));
if ((TWSR & 0xF8) != 0x18) return 1; //MTA_SLA_ACK???
return 0;
}/* i2c_start */
/*************************************************************************
Issues a repeated start condition and sends address and transfer direction
Input: address and transfer direction of I2C device
Return: 0 device accessible
1 failed to access device
*************************************************************************/
unsigned char i2c_rep_start(unsigned char address)
{
return i2c_start( address );
}/* i2c_rep_start */
/*************************************************************************
Terminates the data transfer and releases the I2C bus
*************************************************************************/
void i2c_stop(void)
{
/* send stop condition */
/* COMPLETE CODE step 7.2 */
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
// wait until stop condition is executed and bus released
while(TWCR & (1<<TWSTO));
}/* i2c_stop */
/*************************************************************************
Send one byte to I2C device
Input: byte to be transfered
Return: 0 write successful
1 write failed
*************************************************************************/
unsigned char i2c_write( unsigned char data )
{
/* COMPLETE CODE steps 5.2 to 7.1 */
/* Instead of ERROR() -> return 1 */
TWDR = data;
TWCR = (1<<TWINT) | (1<< TWEN);
while (!(TWCR & (1 << TWINT)));
if ((TWSR & 0xF8) != 0x28) return 1;
return 0;
}/* i2c_write */
/*************************************************************************
Read one byte from the I2C device, request more data from device
Return: byte read from I2C device
*************************************************************************/
unsigned char i2c_readAck(void)
{
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA);
while(!(TWCR & (1<<TWINT)));
return TWDR;
}/* i2c_readAck */
/*************************************************************************
Read one byte from the I2C device, read is followed by a stop condition
Return: byte read from I2C device
*************************************************************************/
unsigned char i2c_readNak(void)
{
TWCR = (1<<TWINT) | (1<<TWEN);
while(!(TWCR & (1<<TWINT)));
return TWDR;
}/* i2c_readNak */
|
C
|
#include <stdio.h>
void main(){
int input_number=0;
int input_number_copy=0;
int sum_number=0;
int total=0;
float average=0;
printf(" Է¹ðڽϱ? ex) 3 : ");
scanf("%d", &input_number);
input_number_copy = input_number;
while(0 < input_number){
printf(" Էϼ: ");
scanf("%d", &sum_number);
total = total + sum_number;
printf(" հ %d Դϴ.\n", total);
input_number--;
}
average = (float)total / input_number_copy;
printf(" %f Դϴ", average);
}
|
C
|
/*
* https://www.geeksforgeeks.org/write-a-program-to-reverse-an-array-or-string/
*
* Write a program to reverse an array or string
*
* Given an array (or string), the task is to reverse the array/string
*
* Input : arr[] = {1, 2, 3}
* Output : arr[] = {3, 2, 1}
*
* Input : arr[] = {4, 5, 1, 2}
* Output : arr[] = {2, 1, 5, 4}
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void
rotate(int *array, int n) {
int mid = 0;
int ind = 0;
int tmp = 0;
mid = n / 2;
for(ind=0;ind<mid;ind++) {
tmp = array[ind];
array[ind] = array[n-1-ind];
array[n-1-ind] = tmp;
}
}
void
print(int *array, int n) {
int i = 0;
for(i=0;i<n;i++) {
printf("Index %d = %d\n",i,array[i]);
}
}
int main(int argc, char *arg[]) {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
rotate(arr, sizeof(arr)/sizeof(int));
print(arr, sizeof(arr)/sizeof(int));
}
|
C
|
#include <stdio.h>
#include <string.h>
int x[100], y[100], row[20], column[20];
int main()
{
int count, i, j, dia1, dia2, over, p;
scanf("%d", &count);
while(count--)
{
memset(x, -1, sizeof(x));
memset(y, -1, sizeof(y));
dia1 = dia2 = 1;
for(i=0; i<5; i++)
{
row[i] = column[i] = 0;
for(j=0; j<5; j++)
{
if(i == 2 && j == 2)
{
continue;
}
scanf("%d", &p);
x[p] = i;
y[p] = j;
}
}
row[2] = column[2] = 1;
for(i=0, over=0; i<75; i++)
{
scanf("%d", &p);
if(over)
{
continue;
}
if(x[p] != -1)
{
row[x[p]]++;
column[y[p]]++;
if(x[p] == y[p])
{
dia1++;
}
if(x[p] + y[p] == 4)
{
dia2++;
}
if(row[x[p]] == 5 || column[y[p]] == 5 || dia1 == 5 || dia2 == 5)
{
over = 1;
printf("BINGO after %d numbers announced\n", i+1);
}
}
}
}
return 0;
}
|
C
|
//write a program that displays two dimentional array
#include<stdio.h>
int main()
{
while(1)
{
int i, j;
int A[3][4] = { {3,4,5,6}, {11,12,13,14}, {22,23,24,25} };
for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
printf("%d ", A[i][j]);
}
printf("\n");
}
getch();
}
}
|
C
|
////////////////////////////////////////////////////////////////////////////////
// Main File: division.c
// This File: division.c
// Other Files: sendsig.c, intdate.c
// Semester: CS 354 Fall 2018
//
// Author: Alexandra Yavnilovitch
// Email: yavnilovitch@wisc.edu
// CS Login: yavnilovitch
//////////////////////////// 80 columns wide ///////////////////////////////////
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
void handler_SIGFPE();
void handler_SIGINT();
int counter;
/* The division function prompts the user enters 2 integer values.
* Then a division operation is attempted (first/second). The number of
* successful operations is recorded.
* The function can be terminated in two ways:
* - Interrupt signal (SIGINT) ctrl+C
* - Division by zero (SIGFPE)
*/
int main()
{
// Vars for the numerator (string is converted to int)
int num;
char num_str[100];
// Vars for the denominator (srting is conv. to int)
int denom;
char denom_str[100];
// Var for quotient and remainder
int quot;
int rem;
// Initialize counter for number of successful division operations
counter = 0;
// Sigaction struct to handle division by zero error
struct sigaction sa;
memset (&sa, 0, sizeof(sa));
sa.sa_handler = &handler_SIGFPE;
sa.sa_flags = 0;
// Call the SIGFPE handler if division by zero triggers
if (sigaction(SIGFPE, &sa, NULL) != 0)
{
printf("Error: Binding SIGFPE error");
}
// Sigaction struct to handle INTERRUPT (ctrl+C)
struct sigaction sa_int;
memset (&sa_int, 0, sizeof(sa_int));
sa_int.sa_handler = &handler_SIGINT;
sa_int.sa_flags = 0;
// Call the SIGINT handler when (ctrl+c) or kill() interrupts process.
if (sigaction(SIGINT, &sa_int, NULL) != 0)
{
printf("Error: Binding SIGINT error");
}
// Loop body of division function
// Prompts user for integer values to use in division
// If division by zero does not occur, the result is displayed,
// and the loop continues to iterate
while (1)
{
// Prompt for user inputs (first, second ints)
printf("Enter first integer: ");
if (fgets(num_str, 100, stdin) == NULL)
{
printf("Unable to read user input\n");
exit(0);
}
printf("Enter second integer: ");
if (fgets(denom_str, 100, stdin) == NULL)
{
printf("Unable to read user input\n");
exit(0);
}
// Parse user input for the numerator and the denominator
num = atoi(num_str);
denom = atoi(denom_str);
// Determine the quotient and remainder of the operation
quot = num / denom;
rem = num % denom;
// Print out the results
printf("%d / %d is %d with a remainder of %d\n", num, denom, quot, rem);
counter++;
}
}
/* The SIGFPE handler responds to the division by zero operation.
* Once the handler is triggered, the count of successful division operations
* is printed, and the process is terminated.
*/
void handler_SIGFPE()
{
printf("Error: a division by 0 operation was attempted.\n");
printf("Total number of operations completed successfully: %d\n", counter);
printf("The program will be terminated.\n");
exit(0);
}
/* The SIGINT handler responds to an INTERRUPT (ctrl + C)
* Once the handler is triggered, the count of successful division operations
* is printed, and the process is terminated.
*/
void handler_SIGINT()
{
printf("\nTotal number of operations successfully completed: %d\n", counter);
printf("The program will be terminated.\n");
exit(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define RANDINT(a, b) ((rand() % ((b) - (a))) + (a))
/*
*
* + AA, , ׳
* + ǻ, ڵ, ũν
* ͵
* + , ݶ, ġ佺, , ڱ
*/
/*
*
* struct
*
*/
#ifndef _ITEMINFO_STRUCT
#define _ITEMINFO_STRUCT
typedef struct {
int no;
int x;
int y;
const char* name;
} ItemInfo;
#endif
/*
*
* unique rand
*
*/
int randIndex = 0, *randHistory = NULL;
int contains(int* arr, int len, int target) {
for (int i = 0; i < len; i++) {
if (*(arr + i) == target)
return 1;
}
return 0;
}
void initUniqueRand(int historyLimit) {
if (randHistory != NULL)
free(randHistory);
randHistory = (int*)malloc(sizeof(int) * historyLimit);
randIndex = 0;
}
int uniqueRandIntHelper(int a, int b) {
int r;
while(1) {
r = RANDINT(a, b);
if (!contains(randHistory, randIndex, r)) {
randHistory[randIndex] = r;
randIndex++;
return r;
}
}
}
int uniqueRandInt(int b) {
return uniqueRandIntHelper(0, b);
}
/*
*
* logic about area
*
*/
int area_horizontal_index(int an, int r) {
if (0 < an && an < r)
return an;
else if (r <= an && an < r * 2 - 1)
return r - 1;
else if (r * 2 - 1 <= an && an <= r * 3 - 3)
return r - (an - (r * 2 - 3));
else
return 0;
}
int area_vertical_index(int an, int r) {
if (0 < an && an < r)
return 0;
else if (r <= an && an < r * 2 - 1)
return an - (r - 1);
else if (r * 2 <= an && an <= r * 3 - 2)
return r - 1;
else
return r - 1 - (an - (r * 3 - 3));
}
/*
*
* logic
*
*/
const char* itemNames[] = {
"AA",
"",
"׳",
"ǻ",
"ڵ",
"ũν",
" ͵"
"",
"ݶ",
"",
"ڱ"
};
ItemInfo* placeItems(int width, int height, int** answers) {
//
initUniqueRand(3);
for (int i = 0; i < 3; i++)
answers[0][i] = i;
initUniqueRand(3);
for (int i = 0; i < 3; i++)
answers[1][i] = 3 + i;
srand((unsigned)time(NULL));
// ġġ
ItemInfo* items = (ItemInfo*)malloc(sizeof(ItemInfo) * 10);
int areaWUnit = width / 5,
areaHUnit = height / 5,
itemIndex = 0;
initUniqueRand(4);
for (int i = 0; i < 4; i++) {
int area = uniqueRandInt(16);
int xi = area_horizontal_index(area, 5),
yi = area_vertical_index(area, 5),
x = RANDINT(areaWUnit * i, areaWUnit * (i + 1)),
y = RANDINT(areaHUnit * i, areaHUnit * (i + 1));
items[itemIndex].x = x;
items[itemIndex].y = y;
itemIndex++;
}
initUniqueRand(4);
for (int i = 0; i < 4; i++) {
int area = uniqueRandInt(8);
int xi = area_horizontal_index(area, 3),
yi = area_vertical_index(area, 3),
x = areaWUnit + RANDINT(areaWUnit * i, areaWUnit * (i + 1)),
y = areaHUnit + RANDINT(areaHUnit * i, areaHUnit * (i + 1));
items[itemIndex].x = x;
items[itemIndex].y = y;
itemIndex++;
}
{
int x = areaWUnit + RANDINT(areaWUnit * 2, areaWUnit * 3),
y = areaHUnit + RANDINT(areaHUnit * 2, areaHUnit * 3);
items[itemIndex].x = x;
items[itemIndex].y = y;
itemIndex++;
}
{
int x = RANDINT(0, width),
y = RANDINT(0, height);
items[itemIndex].x = x;
items[itemIndex].y = y;
itemIndex++;
}
// ۹
initUniqueRand(10);
for (int i = 0; i < 10; i++) {
items[i].no = uniqueRandInt(10);
items[i].name = itemNames[items[i].no];
}
return items;
}
|
C
|
#include<stdio.h>
int main(){
int mat[10][10],i,j,k=0,m,n,arri[10],arrj[10];
printf("\nEnter order(m x n) :");
scanf("%d %d",&m,&n);
for(i=0;i<m;i++)
for(j=0;j<n;j++){
scanf("%d",&mat[i][j]);
if(mat[i][j]){
arri[k]=i;
arrj[k++]=j;
}
}
for(i=0;i<k;i++){
for(j=0;j<n;j++)
mat[arri[i]][j]=1;
for(j=0;j<m;j++)
mat[j][arrj[i]]=1;
}
printf("\nMatrix :\n");
for(i=0;i<m;i++){
for(j=0;j<n;j++)
printf("%d\t",mat[i][j]);
printf("\n");
}
printf("\n\n");
return 0;
}
|
C
|
/* File: main08.c
Using generic linked list functions in ll.c
to implement a linked list of integers.
*/
#include <stdio.h>
#include <stdlib.h>
#include "ll.h"
typedef struct int_node {
print_ftype print_func ;
struct int_node *next ;
int data ;
} int_node ;
void print_int_node(int_node *ptr) {
printf("%d ", ptr->data) ;
return ;
}
int_node *new_int_node (int data) {
int_node *ptr ;
ptr = malloc(sizeof(*ptr)) ;
if (ptr == NULL) {
fprintf(stderr, "Could not malloc() in new_int_node()!\n") ;
exit(1) ;
}
ptr->print_func = (print_ftype) &print_int_node ; // Note syntax!!
ptr->data = data ;
ptr->next = NULL ;
return ptr ;
}
int main() {
base_node *list1 ;
int_node *ptr ;
printf("New list1: ") ;
list1 = LL_New() ;
LL_Insert(list1, new_int_node(72)) ;
LL_Insert(list1, new_int_node(94)) ;
LL_Insert(list1, new_int_node(31)) ;
LL_Insert(list1, new_int_node(44)) ;
LL_Insert(list1, new_int_node(57)) ;
LL_Insert(list1, new_int_node(18)) ;
LL_Insert(list1, new_int_node(2)) ;
LL_Print(list1) ;
printf("Remove 1 node: ") ;
LL_Delete(list1) ;
LL_Print(list1) ;
printf("First item: ") ;
ptr = (int_node *) LL_First(list1) ;
printf("%d ", ptr->data) ;
printf("\n") ;
printf("Reverse list: ") ;
base_node *temp_list = LL_New() ;
while( ( ptr = (int_node *) LL_Extract(list1) )) {
LL_Insert(temp_list, ptr) ;
}
LL_Destroy(list1) ;
list1 = temp_list ; //shallow copy
temp_list = NULL ;
LL_Print(list1) ;
LL_Destroy(list1) ;
return 0 ;
}
|
C
|
/***************************************************************
Paul Lewis
File Name: tour.h
Genetic Algorithms and Permutations
Contains struct definitions, libraries, and function prototypes for tour.c
***************************************************************/
#ifndef TOUR_H
#define TOUR_H
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
/*
* A tour struct
*
* @field int *cities, the cities on this tour
* @field double total, the total of the edges on tour
*/
struct tour {
int *cities;
double total;
};
/*
* Function for allocating a new tour
*
* @param int numCities, the number of cities
*
* @return struct tour *, the new tour
*/
struct tour *newTour(int numCities);
/*
* Function to free a tour
*
* @param struct tour *t, the tour to free
*/
void freeTour(struct tour *t);
#endif
|
C
|
#include <stdio.h>
int main(){
int result=0, tmp;
while (scanf("%d", &tmp) != EOF){
if(tmp>0) result++;
else continue;
}
printf("%d", result);
}
|
C
|
/*
* fiwix/fs/fd.c
*
* Copyright 2018-2022, Jordi Sanfeliu. All rights reserved.
* Distributed under the terms of the Fiwix License.
*/
#include <fiwix/errno.h>
#include <fiwix/types.h>
#include <fiwix/fs.h>
#include <fiwix/sleep.h>
#include <fiwix/stdio.h>
#include <fiwix/string.h>
struct fd *fd_table;
static struct resource fd_resource = { 0, 0 };
int get_new_fd(struct inode *i)
{
unsigned int n;
lock_resource(&fd_resource);
for(n = 1; n < NR_OPENS; n++) {
if(fd_table[n].count == 0) {
memset_b(&fd_table[n], 0, sizeof(struct fd));
fd_table[n].inode = i;
fd_table[n].count = 1;
unlock_resource(&fd_resource);
return n;
}
}
unlock_resource(&fd_resource);
return -ENFILE;
}
void release_fd(unsigned int fd)
{
lock_resource(&fd_resource);
fd_table[fd].count = 0;
unlock_resource(&fd_resource);
}
void fd_init(void)
{
memset_b(fd_table, 0, fd_table_size);
}
|
C
|
#include "holberton.h"
/**
* set_bit - Set the value of a bit to 1 at a given index
* @n: unsigned long int
* @index: index, starting from 0 of the bit you want to set
*
* Return: 1 if it worked, or -1 if an error occured
*/
int set_bit(unsigned long int *n, unsigned int index)
{
unsigned long int max = sizeof(unsigned long int) * 8;
if (index > max)
{
return (-1);
}
*n = *n | (1ul << index);
return (1);
}
|
C
|
#include <stdio.h>
#define AL 5
#define MAX 5
int main(){
int i, x, smol, poz;
float nums[AL];
printf("Input the 5 members of the array: ");
for (i = 0; i < AL; i++)
{
scanf("%f", &nums[i]);
}
for (i = 0; i < AL; i++)
{
if (nums[i] < MAX)
{
printf("A[%d] = %.1f\n", i, nums[i]);
}
}
return 0;
}
|
C
|
//-----------------------------------------------------------------------------
// Parsing helper functions
//-----------------------------------------------------------------------------
#include "shared.h"
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "libparse.h"
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
//-----------------------------------------------------------------------------
// Functions
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// parse_trim_trailing_spaces(char *s)
// Trim trailing spaces by writing an end-of-string marker
//-----------------------------------------------------------------------------
void parse_trim_trailing_spaces (char *s)
{
int i;
i = strlen(s) - 1;
while (i >= 0 && isspace((unsigned char)s[i])) // u8 needed because of accentued characters in MEKA.MSG and isspace asserting
s[i--] = EOSTR;
}
//-----------------------------------------------------------------------------
// parse_skip_spaces(char **src)
// Skip all spaces in pointed string
//-----------------------------------------------------------------------------
void parse_skip_spaces(char **src)
{
char c;
while ((c = **src) == ' ' || c == '\t')
(*src) ++;
}
//-----------------------------------------------------------------------------
// Retrieve next word, as delimited by the given set of separators,
// into given location, with maximum length, starting at given pointed string.
// Increase pointed string source.
// If no location is given, automatically allocate result.
//-----------------------------------------------------------------------------
// Note: In case of repeated separators (eg: ",,,,", it doesn't return NULL
// but empty strings. NULL is returned at end of source pointed string.
//-----------------------------------------------------------------------------
char * parse_getword(char *dst, int dst_len, char **src, const char *separators, char comment_char, t_parse_flags flags)
{
char * p;
int inhibit;
char c;
char * dst_write;
// If dst is NULL, we have to allocate ourself
if (dst == NULL)
{
dst_len = 0;
inhibit = FALSE;
for (p = *src; (c = *p) != EOSTR; p++)
{
if (!inhibit)
{
if (strchr (separators, c))
break;
if (c == comment_char)
break;
if (c == '\\')
{
inhibit = TRUE;
continue;
}
}
dst_len++;
inhibit = FALSE;
}
if (dst_len == 0 && (*p == EOSTR || *p == comment_char))
return (NULL);
dst_len++; // for \0 storage
dst = (char*)malloc(sizeof (char) * dst_len);
}
// Copy word until separator or end-of-string is found. Handle \ inhibitor.
dst_write = dst;
inhibit = FALSE;
for (p = *src; (c = *p) != EOSTR; p++)
{
if (!inhibit)
{
if (strchr (separators, c))
break;
if (c == comment_char)
break;
if (c == '\\')
{
inhibit = TRUE;
continue;
}
}
if (dst_write - dst == dst_len)
break;
if (inhibit)
{
if (c == 'n')
c = '\n';
else if (c == 't')
c = '\t';
}
*dst_write++ = c;
inhibit = FALSE;
}
*dst_write = EOSTR;
// Set new source pointer
if (flags & PARSE_FLAGS_DONT_EAT_SEPARATORS)
*src = p;
else
*src = (*p == EOSTR || *p == comment_char) ? p : p + 1;
// Return NULL at end of string
if (dst_write - dst == 0 && (*p == EOSTR || *p == comment_char))
return (NULL);
// Trim trailing spaces
parse_trim_trailing_spaces(dst);
return (dst);
}
char * parse_escape_string(const char *src, const char *escape_chars)
{
char * p;
char * dst;
char c;
int count;
int src_length;
// Default escape characters
if (escape_chars == NULL)
escape_chars = PARSE_ESCAPE_CHARACTERS_DEFAULT;
// Count characters to escape
count = 0;
for (src_length = 0; (c = src[src_length]) != '\0'; src_length++)
{
if (strchr(escape_chars, c) != NULL)
count++;
}
// If none, return NULL
if (count == 0)
return NULL;
dst = (char*)malloc(sizeof(char) * (src_length + count + 1));
p = dst;
while ((c = *src++) != '\0')
{
if (strchr(escape_chars, c) != NULL)
{
*p++ = '\\';
//count--;
}
*p++ = c;
}
*p = '\0';
return (dst);
}
char * parse_unescape_string(const char *src, const char *escape_chars)
{
char * dst;
char * p;
char c;
int src_length;
// Default escape characters
if (escape_chars == NULL)
escape_chars = PARSE_ESCAPE_CHARACTERS_DEFAULT;
// Make it easier, allocate same as source length
src_length = strlen(src);
dst = (char*)malloc(sizeof(char) * (src_length + 1));
p = dst;
// Copy
while ((c = *src++) != '\0')
{
if (strchr(escape_chars, c) != NULL)
{
c = *src++;
if (c == '\0') // FIXME: not exact behavior, but at least we're safe here
break;
}
*p++ = c;
}
*p = '\0';
return (dst);
}
t_tfile * tfile_read(const char *filename)
{
// Open and file
FILE* f;
if ((f = fopen(filename, "rb")) == NULL)
{
meka_errno = MEKA_ERR_FILE_OPEN;
return NULL;
}
// Gets its size
int size;
if (fseek(f, 0, SEEK_END) != 0 || (size = ftell(f)) == -1 || fseek(f, 0, SEEK_SET) != 0)
{
meka_errno = MEKA_ERR_FILE_READ;
return NULL;
}
// Allocate the t_tfile and read file data into to
t_tfile* tf = (t_tfile*)malloc(sizeof (t_tfile));
tf->size = size;
tf->data_raw = (char*)malloc(sizeof (char) * size + 1);
tf->data_lines = NULL;
if (fread(tf->data_raw, sizeof (char), size, f) < (unsigned int)size)
{
meka_errno = MEKA_ERR_FILE_READ;
tfile_free(tf);
return NULL;
}
tf->data_raw[size] = EOSTR;
fclose(f);
// Silently ignore UTF-8 header (for meka.nam)
char* p_cur = tf->data_raw;
if ((u8)p_cur[0] == 0xEF && (u8)p_cur[1] == 0xBB && (u8)p_cur[2] == 0xBF)
p_cur += 3;
// Parse raw data to create the lines list
int lines_count = 0;
char* p_new;
while ((p_new = strchr(p_cur, '\n')) != NULL)
{
*p_new = EOSTR;
StrChomp(p_cur);
list_add_to_end(&tf->data_lines, p_cur);
lines_count++;
p_cur = p_new + 1;
}
// Handle last line case
if (p_cur < tf->data_raw + tf->size)
{
list_add_to_end(&tf->data_lines, p_cur);
lines_count++;
}
tf->data_lines_count = lines_count;
// OK
meka_errno = MEKA_ERR_OK;
return (tf);
}
void tfile_free(t_tfile *tf)
{
list_free_no_elem(&tf->data_lines);
free(tf->data_raw);
free(tf);
}
//-----------------------------------------------------------------------------
|
C
|
#ifndef I386_SLAB_H
#define I386_SLAB_H
#include <mutex.h>
#include <common/types.h>
/*The AK slab allocator is a very simple design:
*A slab entry contains the address (page) of the first
*buffer node. It contains a link to the next page of
*objects, if there is one (denoted by not being null).
*The first_free is the index of the first free object.
*Free objects always contain the relative address to the
*next free object, essentially a large linked list of
*free objects. When full, another page of objects is
*allocated.
*/
typedef struct sbuf {
uint32 num_free_objects;
int32 first_free;
struct sbuf *next;
} sbuf_t;
typedef struct {
mutex_t lock;
uint32 num_objects;
sbuf_t *empty;
sbuf_t *partial;
sbuf_t *full;
uint32 size;
} slab_entry_t;
void init_slabs ();
slab_entry_t * create_slab(int size);
void delete_slab(slab_entry_t *);
void * allocate_from_slab(slab_entry_t *);
void deallocate_from_slab(slab_entry_t *, void *);
void dump_slab_info ();
#endif
|
C
|
/*******************************************************************************
* This file is part of Bombeirb.
* Copyright (C) 2018 by Laurent Réveillère
******************************************************************************/
#include <SDL/SDL_image.h>
#include <assert.h>
#include <player.h>
#include <sprite.h>
#include <window.h>
#include <misc.h>
#include <constant.h>
#include <myfonct.h>
struct player {
int life;
int x, y;
enum direction direction;
int bombs; //nb of bomb that player can put right now
int max_bomb;
int range;
int state; // state=>0 => player est invulneratble ; -1 = vulneratble
int key;
};
struct player* player_init(int bombs) {
struct player* player = malloc(sizeof(*player));
if (!player)
error("Memory error");
player->direction = NORTH;
player->bombs = bombs;
player->max_bomb = bombs;
player->life=3;
player->state=-1;
player->key=0;
return player;
}
void player_free(struct player* player) {
assert(player);
free(player);
}
//fonction link to player->x and player->y
void player_set_position(struct player *player, int x, int y) {
assert(player);
player->x = x;
player->y = y;
}
int player_get_x(struct player* player) {
assert(player != NULL);
return player->x;
}
int player_get_y(struct player* player) {
assert(player != NULL);
return player->y;
}
//fonction link to player->direction
enum direction player_get_direction(struct player* player){
assert(player);
return player->direction;
}
void player_set_current_way(struct player* player, enum direction way) {
assert(player);
player->direction = way;
}
//fonction link to player->nb_bomb
int player_get_nb_bomb(struct player* player) {
assert(player);
return player->bombs;
}
void player_set_nb_bomb(struct player* player,int nb_bomb){
assert(player);
player->bombs = nb_bomb;
}
void player_inc_nb_bomb(struct player* player) {
assert(player);
player->bombs += 1;
}
void player_dec_nb_bomb(struct player* player) {
assert(player);
player->bombs -= 1;
}
//fonction link to player->life
int player_get_life(struct player *player){
assert(player);
return player->life;
}
void player_set_life(struct player* player,int life){
assert(player);
player->life = life;
}
void player_inc_life(struct player* player) {
assert(player);
player->life +=1;
}
void player_dec_life(struct player *player){
assert(player);
player->life -=1;
}
//fonction link to player->range
int player_get_range(struct player* player){
assert(player != NULL);
return player->range;
}
void player_set_range(struct player* player,int range){
assert(player);
player->range = range;
}
void player_inc_range(struct player * player){
assert(player);
player->range += 1;
}
void player_dec_range(struct player * player){
assert(player);
player->range -= 1;
}
//fonction link to player->max_bomb
int player_get_max_bomb(struct player * player){
assert(player);
return player->max_bomb;
}
void player_set_max_bomb(struct player* player,int max_bomb){
assert(player);
player->max_bomb = max_bomb;
}
void player_inc_max_bomb(struct player* player) {
assert(player);
player->max_bomb += 1;
}
void player_dec_max_bomb(struct player* player) {
assert(player);
player->max_bomb -= 1;
}
//fonction link to player->key
int player_get_key(struct player* player){
assert(player);
return player->key;
}
void player_set_key(struct player* player,int key){
assert(player);
player->key = key;
}
void player_inc_key(struct player* player){
assert(player);
player->key += 1;
}
void player_dec_key(struct player* player) {
assert(player);
player -> key -= 1;
}
void player_set_state(struct player* player,unsigned int time){
assert(player);
player->state = time;
}
static int player_move_aux(struct player* player, struct map* map, int x, int y) {
enum direction direction;
direction=player->direction;
if (!map_is_inside(map, x, y))
return 0;
switch (map_get_cell_type(map, x, y)) {
case CELL_SCENERY:
if(map_get_bonus_type(map,x,y)==4) //4 = princess
return 1;
return 0; // Les mouvements du joueur sont limités les éléments de décors
break;
case CELL_BOMB:
return 0;
break;
case CELL_BOX:
return boxe_move(direction,map,x,y);
break;
case CELL_BONUS:
cell_bonus_move(map,player,x,y);
map_set_cell_type(map,x,y,CELL_EMPTY);
break;
case CELL_KEY:
if (player->key <9) {
map_set_cell_type(map,x,y,CELL_EMPTY);
player_inc_key(player);
}
break;
default:
break;
}
// Player has moved
return 1;
}
int player_move(struct player* player, struct map* map) {
int x = player->x;
int y = player->y;
int move = 0;
switch (player->direction) {
case NORTH:
if (player_move_aux(player, map, x, y - 1)) {
player->y--;
move = 1;
}
break;
case SOUTH:
if (player_move_aux(player, map, x, y + 1)) {
player->y++;
move = 1;
}
break;
case WEST:
if (player_move_aux(player, map, x - 1, y)) {
player->x--;
move = 1;
}
break;
case EAST:
if (player_move_aux(player, map, x + 1, y)) {
player->x++;
move = 1;
}
break;
}
return move;
}
void player_update_state(struct map *map,struct player* player) {
int x=player->x;
int y=player->y;
int state=player->state;
enum cell_type cell_type=map_get_cell_type(map,x,y);
if (state < 0) {
switch (cell_type) {
case CELL_MONSTER:
player_dec_life(player);
player->state=SDL_GetTicks();
break;
case CELL_EXPLOSION:
player_dec_life(player);
player->state=SDL_GetTicks();
default:
break;
}
}else{
if((SDL_GetTicks()-state)>2500)
player->state=-1;
}
}
void player_display(struct player* player) {
assert(player);
if (player->state < 0) {
window_display_image(sprite_get_player(player->direction),
player->x * SIZE_BLOC, player->y * SIZE_BLOC);
}else{
if ( ((SDL_GetTicks() - player->state)%300)>150 ) {
window_display_image(sprite_get_player(player->direction),
player->x * SIZE_BLOC, player->y * SIZE_BLOC);
}else{
window_display_image(sprite_get_player2(player->direction),
player->x * SIZE_BLOC, player->y * SIZE_BLOC);
}
}
}
|
C
|
/*******************************************************************************
* Name: pun.c
* Purpose: Prints a bad pun
* Author: shiqf*
*******************************************************************************/
/* 包含了出演标准输入/与输出库的相关信息 */
/* 指令 */
#include <stdio.h>
/*
* 函数分为两类:库函数和程序员自己编写的函数
* main 函数是非常特殊的,不能写成其他名称例如:begin start or MAIN
* main 函数回在程序终止时向操作系统返回一个状态码
*/
int main(void)
{
/* printf 函数有标准库stdio.h头文件指明,\n表示换行 */
printf("To C, or not to C: that is the question.\n");
/* return 有两个作用:使得main函数终止、指出main函数返回值是0 */
return 0;
}
|
C
|
/*
* Problem-5: Program to multiply 2 matrixes
* Ayush Singh 1910990059 24/07/21
* Assignment_1 -> C Foundation
*/
#include <stdio.h>
#include<stdlib.h>
//function to multiply two matrixes
int **multiply_matrix(int row1, int col1, int matrix1[][col1], int row2, int col2, int matrix2[][col2]){
int i, j, k;
int **new_matrix = (int **)calloc(row1, sizeof(int *));
for(i = 0; i < row1; i++){
new_matrix[i] = (int *)calloc(col2, sizeof(int));
for(j = 0; j < col2; j++){
new_matrix[i][j] = 0;
for(k = 0; k < col1; k++){
new_matrix[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return new_matrix;
}
int main(){
int row, col, row1, col1, row2, col2;
printf("Enter dimensions of first matrix: ");
scanf("%d %d", &row1, &col1);
printf("Enter dimensions of second matrix: ");
scanf("%d %d", &row2, &col2);
if(col1 != row2){
printf("Invalid input");
return 0;
}
int matrix1[row1][col1], matrix2[row2][col2];
printf("Enter first matrix: ");
for(row = 0; row < row1; row++){
for(col = 0; col < col1; col++){
scanf("%d ", &matrix1[row][col] );
}
}
printf("Enter second matrix: ");
for(row = 0; row < row2; row++){
for(col = 0; col < col2; col++){
scanf("%d ", &matrix2[row][col] );
}
}
//calling count function
int **new_matrix = multiply_matrix(row1, col1, matrix1, row2, col2, matrix2);
printf("New matrix:\n");
for(row = 0; row < row1; row++){
for(col = 0; col < col2; col++){
printf("%d ",new_matrix[row][col] );
}
printf("\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include "vecs.h"
#include "display.h"
#include "shader.h"
#include "mesh.h"
#include "texture.h"
#include "camera.h"
int main(void)
{
float counter = 0.0f;
SDL_Init(SDL_INIT_EVERYTHING);
struct display *d = display_new(800, 600, "hello world");
GLenum status = glewInit();
if (status != GLEW_OK) {
fprintf(stderr, "Glew failed to initialize: %s\n",
glewGetErrorString(status));
}
struct vertex verticies[] = { vertex_new(-0.5, -0.5, 0,
0.0, 0.0),
vertex_new(0, 0.5, 0,
0.5, 1.0),
vertex_new(0.5, -0.5, 0,
1.0, 0.0) };
struct mesh *m = mesh_new
(verticies, sizeof(verticies)/sizeof(verticies[0]));
struct shader *s = shader_new("./res/basicShader");
struct texture *t = texture_new("./res/bricks.jpg");
struct transform *tr = transform_new(vec3_new(0, 0, 0),
vec3_new(1, 0, 0),
vec3_new(0.5, 0.5, 0.5));
struct camera *cam = camera_new(vec3_new(0, 0, -0.75), 70.0f,
600.0f/800.0f, 0.1f, 1000.0f);
while (!d->is_closed) {
clear(0.0, 0.15, 0.3, 1.0);
/* tr->m_pos.x = sinf(counter); */
/* tr->m_pos.z = counter; */
shader_bind(s);
texture_bind(t, 0);
shader_update(s, tr, cam);
mesh_draw(m);
update(d);
cam->m_position.z = cosf(counter) - 2;
cam->m_position.x = sinf(counter);
/* tr->m_rot.x = counter; */
/* tr->m_rot.y = sinf(counter); */
/* tr->m_scale.x = cosf(counter); */
/* tr->m_scale.y = cosf(counter); */
/* tr->m_scale.z = cosf(counter); */
counter += 0.01f;
}
display_free(d);
shader_free(s);
mesh_free(m);
SDL_Quit();
return 0;
}
|
C
|
/* spike.c - spiking filter design */
#define MAX 10
#define NMAX 10
#define max(a, b) (((a) >= (b)) ? (a) : (b))
#define min(a, b) (((a) <= (b)) ? (a) : (b))
void lev(), corr();
void spike(N, y, M, R, L, E, P, H, eps)
double y[], R[], L[][MAX+1], E[], P[][NMAX+MAX+1], H[][NMAX+MAX+1], eps;
int N, M;
{
int i, j, k, s, t;
corr(N+1, y, y, M, R);
for (k=0; k<=M; k++)
R[k] *= N+1;
R[0] *= 1 + eps;
lev(M, R, L, E);
for (i=0; i<=M; i++)
for (j=0; j<=N+M; j++)
for (H[i][j]=0, s=i; s<=M; s++)
for (t=max(0, j-N); t<=min(j, s); t++)
H[i][j] += L[s][i] * L[s][t] * y[j-t] / E[s];
for (i=0; i<=N+M; i++)
for (j=0; j<=N+M; j++)
for (P[i][j]=0, t=max(0, i-N); t<=min(i, M); t++)
P[i][j] += y[i-t] * H[t][j];
}
|
C
|
#include "utilities.h"
#include <stdio.h>
int main(){
printf("This is Fred's testing area:\n");
double total, average;
for (int i=0; i<10; i++) {
double R=arcRand(0.0,2.0);
printf("%lf\n",R);
total = total + R;
}
average = total/10.0;
printf("average = %lf\n",average);
if (abs(average - 1.0) < 0.25){
printf("WORKING!\n");
}
else {
printf("NOT WORKING!\n");
}
}
|
C
|
#include<stdio.h>
int main(void){
//questao 1
float n1,n2;
char op;
scanf("%f%f%s",&n1,&n2,&op);
switch (op)
{
case '+':
printf("%0.2f",(n1+n2));
break;
case '-':
printf("%0.2f",(n1-n2));
break;
case '*':
printf("%0.2f",(n1*n2));
break;
case '/':
printf("%0.2f",(n1/n2));
break;
default:
break;
}
}
|
C
|
#include <stdio.h>
int main(){
int l,n,range[201][3],i,j,max=0,st,end,sf=0;
scanf("%d %d",&l,&n);
for(i=1;i<=n;i++){
scanf("%d %d",&st,&end);
range[i][0] = st;
range[i][1] = end;
}
for(i = 1; i<=l;i++){
sf = 0;
for(j=1; j<=n;j++){
if(i<range[j][0] || i>=range[j][1]){
continue;
}
sf += 1;
}
if(max<sf){
max = sf;
}
}
printf("%d\n",max);
}
|
C
|
// zhaoyangbu.c
#include <ansi.h>
inherit SKILL;
string *dodge_msg = ({
"$nһݣʹ"YEL"ɽơ"NOR"ܿһС\n",
"$Nһ$nʹ"HIR"ƻơ"NOR"һ$NͷԽ\n",
"$nһãһ"HIC"ƺơ"NOR"ӰӶûˡ\n",
"$nһ㣬һ"HIG"ơ"NOR"ڿն𣬱˿ȥ\n",
"$nʹһ"HIY"ƽơ"NOR"Ʈ˿ȥ\n",
"ֻ$nһɼ磬ڷǡе"HIW"ơ"NOR"\n"
});
int valid_enable(string usage)
{
return (usage=="dodge") || (usage=="move");
}
int valid_learn(object me)
{
if( (int)me->query("max_force") < 0 )
return notify_fail("ûа취\n");
return 1;
}
string query_dodge_msg(string limb)
{
return dodge_msg[random(sizeof(dodge_msg))];
}
int practice_skill(object me)
{
if( (int)me->query("kee") < 100
||(int)me->query("force") < 30 )
return notify_fail("\n");
me->receive_damage("kee", 30);
me->add("force", -3);
return 1;
}
int stage(int level)
{
if( level <20 ) return 1;
else if ( level < 60 ) return 2;
else if ( level < 80 ) return 3;
else if ( level < 140 ) return 4;
else if ( level < 180 ) return 5;
else return 6;
}
string level_description(int level)
{
if ( stage(level) < 1 )
return YEL "ɽơ" NOR;
else if ( stage(level) < 2 )
return HIR "ƻơ" NOR;
else if ( stage(level) < 3 )
return HIC "ƺơ" NOR;
else if ( stage(level) < 4 )
return HIG "ơ" NOR;
else if ( stage(level) < 5 )
return HIY "ƽơ" NOR;
else
return HIW "ơ" NOR;
}
|
C
|
#include "Decoder.h"
void Construct_MsgList()
{
int index=0;
LINK* header = NULL;
LINK* temp = NULL;
for(index=0;index<Msg_No;index++)
{
/* First Node */
if(Msg_List == NULL)
{
temp = (LINK*)malloc(sizeof(LINK));
Msg_List = header = temp;
}
else
{
temp = (LINK*)malloc(sizeof(LINK));
Msg_List->next = temp;
Msg_List= Msg_List->next;
}
temp->Msg_Type = Message_Arr[index];
temp->start_block= File_OffsetList[index];
temp->end_block = File_BlockList[index];
temp->next = NULL;
}
Msg_List = header;
}
void Print_LinkedList()
{
LINK *temp = Msg_List;
while(temp != NULL)
{
printf("%s",temp->Msg_Type);
printf("%d",temp->start_block);
printf("%d",temp->end_block);
temp = temp->next;
}
}
void Free_LinkedList()
{
LINK *temp = Msg_List ,*prev ;
while(temp != NULL)
{
prev = temp;
temp = temp->next;
free(prev);
}
}
void Print_FieldName(char *Field_Name)
{
int i = 0;
char buffer[80];
memset(buffer,'\0',sizeof(buffer));
strcpy(buffer,Field_Name);
printf("\n");
while(buffer[i] != '\0')
{
if(buffer[i] == '_' && buffer[i+1] == '_')
{
printf(" ");
}
else
{
if(buffer[i] == '_')
{
printf(" ");
i++;
}
printf("%c",buffer[i]);
}
i++;
}
printf(" : ");
}
void Scan_Msg()
{
FILE *file_ptr;
char buffer[80];
char *token = 0 , *Mtype = 0 ,*tmp;
int Msg_count = 0 ;
LINK* Node = Msg_List;
file_ptr = fopen(MsgFile_Name,"r");
if(file_ptr == NULL)
{
printf("\n Cannot open the Message File '%s' .Please try again \n" ,MsgFile_Name);
exit(0);
}
while ( !feof(file_ptr))
{
memset(buffer, '\0' ,sizeof(buffer));
if(fgets(buffer,80,file_ptr) == NULL)
{
continue;
}
if(buffer[0] == '\n' || buffer[0] == '/')
continue;
token = strtok_r( buffer, delimiters,&tmp);
Msg_Header = token;
if( strncasecmp(token, CALL_PILOT ,strlen(CALL_PILOT)) == 0 || strncasecmp(token , MERIDIAN_MAIL,strlen(MERIDIAN_MAIL)) == 0)
{
printf(" \n\nMsg %d ", ++Msg_count);
while(token != NULL)
{
if(strcasecmp(token, "O") == 0)
printf(" Outgoing Message Type -");
else
{
if(strcasecmp(token, "I") == 0)
printf(" Incoming Message Type - ");
}
if(strncasecmp(token,"MTYP",4)== 0)
{
Mtype = strtok_r( NULL,delimiters,&tmp);
printf("'%s'",Mtype);
}
if(strncasecmp(token,"TIME",4) == 0)
{
printf(" %s\n ",token);
}
token = strtok_r(NULL,delimiters,&tmp);
}
}
else
{
printf("\nInvalid Message Format\n");
exit(0);
}
Search_MsgType(Mtype, &Node);
Print_Msg(file_ptr,Mtype,&Node);
printf("\n");
}
fclose(file_ptr);
}
void Search_MsgType(char* Mtype,LINK** Node)
{
*Node = Msg_List;
while (*Node != NULL )
{
if( strcasecmp((*Node)->Msg_Type,Mtype) == 0)
{
return ;
}
else
{
*Node = (*Node)->next;
}
}
/* Invalid Message */
printf("\n '%s' Message not recognised \n",Mtype);
exit(0);
}
void Print_Msg( FILE* MsgFile_ptr , char* Mtype , LINK** Node)
{
FILE *RefMsgFile_ptr;
char buffer[80], *token = 0, *tmp;
int cnt = 0,flag = 0, Check_Flag = 0 ,i = 0 ,Len_Flag = 0 , offset = 0;
int calling_DN_len = 0,called_DN_len = 0;
Line_Count = 0;
RefMsgFile_ptr = fopen( REFMSG_FILE , "r");
if(RefMsgFile_ptr == NULL)
{
printf("\n Cannot open the Reference File '%s' .Please try again \n" ,REFMSG_FILE);
exit(0);
}
GoTo_LineNo(RefMsgFile_ptr,Node);
while( Line_Count <= (*Node)->end_block && !feof(MsgFile_ptr))
{
memset(buffer,'\0',sizeof(buffer));
offset = ftell(MsgFile_ptr);
if((fgets(buffer,80, MsgFile_ptr) == NULL || buffer[0] == '/' || buffer[0] == '\n')|| !flag )
{
/* Skip reading the second line of message */
flag = 1;
continue;
}
/* If Decoder is Meridian Mail and Message Type is Call Pilot / Symposium -- give an Invalid Message and exit out of the program */
if((strcasecmp(Decoder_Type,MERIDIAN_MAIL) == 0 )&& (memcmp(buffer,CALL_PILOT,strlen(CALL_PILOT)) == 0))
{
printf(" \n This message is not a Meridian Mail Message Format\n");
exit(0);
}
/* If Decoder is of Call Pilot and message to be decoded is Meridian mail then exit out of the program */
if((strcasecmp(Decoder_Type, CALL_PILOT) == 0) && (memcmp(buffer,MERIDIAN_MAIL,strlen(MERIDIAN_MAIL)) == 0))
{
printf("\n This message is not a Call Pilot /Symposium Message Format\n");
exit(0);
}
/* Replace the header with blank spaces */
memset(buffer,' ',strlen(Msg_Header));
token = strtok_r(buffer,delimiters,&tmp);
if(strcasecmp(token,"O") == 0 || strcasecmp(token,"I") == 0)
{
/* Next Message in the buffer */
fseek(MsgFile_ptr,offset,SEEK_SET);
fclose(RefMsgFile_ptr);
return;
}
while(token != NULL)
{
if(!Check_Flag)
{
Field_Len = Octet = 0;
Param_ID = 0;
Tokenize(RefMsgFile_ptr);
Line_Count++;
}
Check_Flag = 0;
if(Len_Flag)
{
Field_Len = (int) strtol(token,NULL,16);
token = strtok_r(NULL,delimiters,&tmp);
Len_Flag = 0;
}
if(Octet == 2 || Octet == 7 || Octet == 14 || Octet == 18)
{
token = strtok_r(NULL,delimiters,&tmp);
continue;
}
if(called_DN_len != 0)
{
Print_FieldName(Field_Name);
Field_Len = called_DN_len;
called_DN_len = 0;
}
if(Octet == 22)
{
/* token = strtok_r(NULL,delimiters,&tmp);*/
printf("%s" , token);
calling_DN_len = (int) strtol(token,NULL,16);
Tokenize(RefMsgFile_ptr);
token = strtok_r(NULL,delimiters,&tmp);
printf("%s" , token);
Tokenize(RefMsgFile_ptr);
called_DN_len = (int) strtol(token,NULL,16);
Field_Len = calling_DN_len;
token = strtok_r(NULL,delimiters,&tmp);
}
if(Field_Len >= 1 )
{
cnt = 0;
while(token != NULL && cnt < Field_Len)
{
printf("%s" , token);
cnt++;
token = strtok_r(NULL,delimiters,&tmp);
}
if(token == NULL)
{
Check_Flag = 1;
Field_Len = Field_Len - cnt;
break;
}
if(Line_Count >= (*Node)->end_block && token != NULL)
{
rewind(RefMsgFile_ptr);
GoTo_LineNo(RefMsgFile_ptr,Node);
ParamID_Match(RefMsgFile_ptr,token,Node);
Check_Flag = 1;
}
}
else
{
if(Line_Count >= (*Node)->end_block && token != NULL)
{
rewind(RefMsgFile_ptr);
GoTo_LineNo(RefMsgFile_ptr,Node);
ParamID_Match(RefMsgFile_ptr,token,Node);
}
if(Param_ID != 0 && strcasecmp(token ,Param_ID) == 0)
{
Print_FieldName(Field_Name);
token = strtok_r(NULL ,delimiters,&tmp);
if( token != NULL)
{
Field_Len = (int) strtol(token,NULL,16);
token = strtok_r(NULL,delimiters,&tmp);
}
else
{
Len_Flag = 1;
Check_Flag = 1;
Line_Count--;
break;
}
cnt = 0;
while( token != NULL && cnt < Field_Len )
{
printf("%s" , token);
cnt++;
token = strtok_r(NULL,delimiters,&tmp);
}
if(token == NULL)
{
Check_Flag = 1;
Field_Len = Field_Len - cnt;
/* If IEs are not in sequence */
if(Line_Count <= (*Node)->end_block)
{
break;
/*IEs not in sequence */
}
else
{
Line_Count --;
}
}
/* if(Line_Count >= (*Node)->end_block && token != NULL)
{
rewind(RefMsgFile_ptr);
GoTo_LineNo(RefMsgFile_ptr,Node);
ParamID_Match(RefMsgFile_ptr,token,Node);
}*/
}
}
}
}
fclose(RefMsgFile_ptr);
}
void GoTo_LineNo(FILE* RefMsgFile_ptr,LINK** Node)
{
char buffer[80];
memset(buffer,'\0',sizeof(buffer));
Line_Count = 0;
while(Line_Count != (*Node)->start_block)
{
if(fgets(buffer,80,RefMsgFile_ptr) != NULL)
Line_Count++;
}
}
void ParamID_Match(FILE* RefMsgFile_ptr,char* token, LINK** Node)
{
Field_Len = Octet = 0;
Param_ID = 0;
while(Line_Count <= (*Node)->end_block)
{
Match_Flag = 0;
Tokenize(RefMsgFile_ptr);
if( Param_ID && (strcasecmp(token,Param_ID) == 0))
{
Match_Flag = 1;
return;
}
Line_Count++;
}
}
void Tokenize(FILE* RefMsgFile_ptr)
{
char Refbuffer[80];
int cnt = 0;
char *token = 0, *tmp;
memset(Refbuffer,'\0', sizeof(Refbuffer));
memset(Field_Name, '\0', sizeof(Field_Name));
if(fgets(Refbuffer,80,RefMsgFile_ptr) != NULL && Refbuffer[0] != '%')
{
token = strtok_r(Refbuffer,delimiters,&tmp);
while(token != NULL)
{
switch(cnt)
{
case 0:
if(!Match_Flag)
{
Field_Len = 0;
break;
}
if( *token != '-')
{
Field_Len = (int) strtol(token,NULL,16) ;
break;
}
case 1 :
if( *token != '-')
Octet = atoi(token);
break;
case 2:
if(Field_Len == 0)
{
strcpy(Field_Name,token);
}
else
{
if(Octet != 2 && Octet !=7 && Octet !=14 && Octet != 18)
Print_FieldName(token);
}
break;
case 3:
if( *token != '-')
Param_ID = token;
}
cnt++;
token = strtok_r(NULL,delimiters,&tmp);
}
}
}
int main( int argc , char* argv[])
{
if(argc < 3)
{
exit(0);
}
Construct_MsgList();
/* Print_LinkedList();*/
MsgFile_Name = argv[1];
Decoder_Type = argv[2];
Scan_Msg();
Free_LinkedList();
Msg_Header = 0;
MsgFile_Name = 0;
Decoder_Type = 0;
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
/*
* In this problem, there is a sushi bar with 5 open seats. If a customer
* arrives, then two conditions might happen:
*
* 1. If there is an empty seat, then the customer walks in and take a seat.
*
* 2. If all 5 seats are occupied, then the customer must wait for ALL five
* customers to leave before they can enter.
*
*/
#define NUM_CUSTOMERS 23
void* customer_fn(void *arg)
{
// TODO: Add code here!
printf("Customer waiting...\n");
// TODO: Add code here!
printf("Customer eating...\n");
sleep(3);
// TODO: Add code here!
printf("Customer finished eating...\n");
return NULL;
}
int
main(int argc, char **argv)
{
int i;
pthread_t customers[NUM_CUSTOMERS];
srand(time(NULL));
for(i = 0; i < NUM_CUSTOMERS; i++) {
pthread_create(&customers[i], 0, customer_fn, 0);
sleep(rand() % 2);
}
for(i = 0; i < NUM_CUSTOMERS; i++) {
pthread_join(customers[i], 0);
}
}
|
C
|
#ifndef ___CGI_H___
#define ___CGI_H___
/**
@file cgi.h
Macros úteis para gerar CGIs
*/
#include <stdio.h>
/**
* Caminho para as imagens
*/
#define IMAGE_PATH "http://localhost/images/"
/**
\brief Macro para começar o html
*/
#define COMECAR_HTML printf("Content-Type: text/html\n\n")
/**
\brief Macro para abrir um svg
@param tamx O comprimento do svg
@param tamy A altura do svg
*/
#define ABRIR_SVG(tamx, tamy) printf("<svg width=%d height=%d>\n", tamx, tamy)
/**
\brief Macro para fechar um svg
*/
#define FECHAR_SVG printf("</svg>\n")
/**
\brief Macro para criar uma imagem
@param X A coordenada X do canto superior esquerdo
@param Y A coordenada Y do canto superior esquerdo
@param ESCALA A escala da imagem
@param FICHEIRO O caminho para o link do ficheiro
*/
#define IMAGEM(X, Y, ESCALA, FICHEIRO) printf("<image x=%d y=%d width=%d height=%d xlink:href=%s />\n", \
ESCALA * X +2, ESCALA* Y+2, ESCALA, ESCALA, IMAGE_PATH FICHEIRO)
#define IMAGEMATASHURIKEN(X, Y, ESCALA, FICHEIRO) printf("<image id=shuriken x=%d y=%d width=%d height=%d opacity ='0' xlink:href=%s />\n", \
ESCALA * X, ESCALA* Y, ESCALA, ESCALA, IMAGE_PATH FICHEIRO)
#define IMAGEMATAFLAME(X, Y, ESCALA, FICHEIRO, NUMERO) printf("<image id=flame%i x=%d y=%d width=%d height=%d opacity ='0' xlink:href=%s />\n", \
NUMERO, ESCALA * X, ESCALA* Y, ESCALA, ESCALA, IMAGE_PATH FICHEIRO)
#define IMAGEMATARange(X, Y, ESCALA, FICHEIRO, NUMERO) printf("<image id=ranged%i x=%d y=%d width=%d height=%d opacity ='0' xlink:href=%s />\n", \
NUMERO, ESCALA * X, ESCALA* Y, ESCALA, ESCALA, IMAGE_PATH FICHEIRO)
#define IMAGEMT(X, Y, ESCALA, FICHEIRO, OPACIDADE) printf("<image x=%d y=%d width=%d height=%d xlink:href=%s opacity = %f />\n", \
ESCALA * X, ESCALA* Y, ESCALA, ESCALA, IMAGE_PATH FICHEIRO, OPACIDADE)
#define IMAGEMI(X, Y, ESCALA, FICHEIRO, NUMERO) printf("<image id=inimigo%i x=%d y=%d width=%d height=%d xlink:href=%s />\n", \
NUMERO, ESCALA * X, ESCALA* Y, ESCALA, ESCALA, IMAGE_PATH FICHEIRO)
#define IMAGEMJ(X, Y, ESCALA, FICHEIRO) printf("<image id=jog x=%d y=%d width=%d height=%d xlink:href=%s />\n", \
ESCALA * X, ESCALA* Y, ESCALA, ESCALA, IMAGE_PATH FICHEIRO)
/**
\brief Macro para criar um quadrado
@param X A coordenada X do canto superior esquerdo
@param Y A coordenada Y do canto superior esquerdo
@param ESCALA A escala do quadrado
@param COR A cor de preenchimento do quadrado
*/
#define ANIMATEATACAIFLAME(COISA, X,Y,ESCALA) printf("<animateMotion xlink:href= #flame%i dur=%fs begin= %fs fill=freeze path=%cM%i,%i %i,%i %c/>\n<animate xlink:href= #flame%i attributeType='auto' attributeName='opacity' to='0' dur='0.1' begin='0.35s' fill=freeze />\n<animate xlink:href= #flame%i attributeType='auto' attributeName='opacity' to='1' dur='0.001' begin='0s' fill=freeze />\n", \
COISA, 0.1,0.25,'"' , 0,0,X*ESCALA, Y*ESCALA ,'"', COISA,COISA)
#define ANIMATEATACAISETA(COISA, X,Y,ESCALA) printf("<animateMotion xlink:href= #ranged%i dur=%fs begin= %fs fill=freeze path=%cM%i,%i %i,%i %c/>\n<animate xlink:href= #ranged%i attributeType='auto' attributeName='opacity' to='0' dur='0.1' begin='0.35s' fill=freeze />\n<animate xlink:href= #ranged%i attributeType='auto' attributeName='opacity' to='1' dur='0.001' begin='0s' fill=freeze />\n", \
COISA, 0.1,0.25,'"' , 0,0,X*ESCALA, Y*ESCALA ,'"', COISA,COISA)
#define QUADRADO(X, Y, ESCALA, COR) printf("<rect x=%d y=%d width=%d height=%d fill=%s />\n", \
ESCALA * X +2, ESCALA* Y+2, ESCALA, ESCALA, COR)
#define ANIMATESHURIKEN( X,Y,ESCALA) printf("<animateMotion xlink:href= #shuriken dur=%fs begin= %is fill=freeze path=%cM%i,%i %i,%i %c/>\n<animate xlink:href= #shuriken attributeType='auto' attributeName='opacity' to='0' dur='0.1' begin='0.1s' fill=freeze />\n<animate xlink:href= #shuriken attributeType='auto' attributeName='opacity' to='1' dur='0.001' begin='0s' fill=freeze />\n", \
0.1,0,'"', 0,0, X*ESCALA, Y*ESCALA , '"')
#define ANIMATEMOVEI(COISA, X,Y,ESCALA) printf("<animateMotion xlink:href= #inimigo%i dur=%fs begin= %is fill=freeze path=%cM%i,%i %i,%i %c/>\n<animate xlink:href= #shuriken attributeType='auto' attributeName='opacity' to='0' dur='0.001' begin='0.1s' fill=freeze />\n", \
COISA, 0.10,0,'"',X*ESCALA, Y*ESCALA , 0,0, '"')
#define ANIMATEMOVEJOG(X,Y,ESCALA) printf("<animateMotion xlink:href= #jog dur=%fs begin= %is fill=freeze path=%cM%i,%i %i,%i %c/>\n", \
0.25,0,'"',X*ESCALA, Y*ESCALA , 0,0 ,'"')
#define ANIMATEATACAI(COISA, X,Y,ESCALA) printf("<animateMotion xlink:href= #inimigo%i dur=%fs begin= %fs fill=freeze path=%cM%i,%i %i,%i %c/>\n", \
COISA, 0.1,0.1,'"',X*ESCALA/2, Y*ESCALA/2 , 0,0 ,'"')
#define ANIMATEATACAJOG(X,Y,ESCALA) printf("<animateMotion xlink:href= #jog dur=%fs begin= %is fill=freeze path=%cM%i,%i %i,%i %c/>\n", \
0.1,0,'"',X*ESCALA/2, Y*ESCALA/2 , 0,0 ,'"')
#define QUADRADOT(X, Y, ESCALA, COR, OPACIDADE) printf("<rect x=%d y=%d width=%d height=%d fill=%s opacity = %f />\n", \
ESCALA * X +2, ESCALA* Y +2, ESCALA, ESCALA, COR, OPACIDADE)
/**
\brief Macro para abrir um link
@param link O caminho para o link
*/
#define ABRIR_LINK(link) printf("<a xlink:href=%s>\n", link)
/**
\brief Macro para fechar o link
*/
#define FECHAR_LINK printf("</a>\n")
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
int main(int argc,char *argv[]) {
int connsfd;
int porta;
struct sockaddr_in strind;
if(argc!=2)
{
printf("\nINS <IP>\n");
exit(1);
}
printf("\nIns porta\n");
scanf("%d",&porta);
strind.sin_family=AF_INET;
strind.sin_port=htons(porta);
inet_pton(AF_INET,argv[1],&strind.sin_addr,sizeof(strind.sin_addr));
if((connsfd=socket(AF_INET,SOCK_STREAM,0))<0)
{printf("\nImpossibile creare il socket\n");
exit(1);
}
if(connect(connsfd,(struct sockaddr *)&strind,sizeof(strind))<0)
{printf("\nImpossibile connettersi all'end point\n");
exit(1);
}
printf("\nCONNESSO\n");
char buffer[300];
int n;
n=read(connsfd,buffer,299);
printf("\ncar letti %d\n",n);
puts(buffer);
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#define _USE_MATH_DEFINES
/* Numerically Solve throw at an angle*/
const double g = -10.0;
double *make_dynamic_array(size_t slots);
double *init_dynamic_array(double *m, size_t slots);
typedef struct
{
size_t step;
size_t size;
double *t;
double *y;
double *v;
} dimension;
typedef struct
{
dimension x;
dimension y;
} plane;
dimension make_dimension(size_t size);
dimension dimension_resize(dimension d, size_t new_size);
void init_dimension(size_t size, dimension *d);
void free_dimension(dimension d);
/* Vertical axis */
double ver_dydt(double t, double x, double v);
double ver_dvdt(double t, double x, double v);
/* Horizontal axis */
double hor_dydt(double t, double x, double v);
double hor_dvdt(double t, double x, double v);
/* Solvers need to be fed a properly initialised pointer to initialised plane p */
/* Euler solver */
void euler_solve_free_fall(double angle, double time_step, double in_vel, plane *p);
/* 4th Order Runge-Kutta solver*/
void rk_solve_free_fall(double angle, double time_step, double in_vel, plane *p);
/* Analytical Solver for free fall*/
void true_solve_free_fall(double angle, double time_step, double in_vel, plane *p);
/* Export a plane to a .dat file for processing */
void export_plane(char *filename, plane p);
/* Export the values of plane p with error values from the difference of each value from corresponding values on plane e*/
void export_compare(char *filename, plane p, plane e);
int main()
{
plane p,e;
p.x = make_dimension(100000);
p.y = make_dimension(100000);
e.x = make_dimension(100000);
e.y = make_dimension(100000);
/* Test multiple time steps with both methods, generate plottable files */
double time_step;
char *filename = malloc(20*sizeof(char));
for(time_step=0.01; time_step>0.000001; time_step *= 0.1)
{
printf("Generating Euler data files for time step: %f\n", time_step);
true_solve_free_fall(M_PI/4.0, time_step, 1, &e);
euler_solve_free_fall(M_PI/4.0, time_step, 1, &p);
sprintf(filename, "Euler_step:%f.dat", time_step);
export_compare(filename, p, e);
printf("Generating Runge-Kutta data files for time step: %f\n", time_step);
rk_solve_free_fall(M_PI/4.0, time_step, 1, &p);
sprintf(filename, "RungeKutta_step:%f.dat", time_step);
export_compare(filename, p, e);
}
return 0;
}
double *init_dynamic_array(double *m, size_t slots)
{
memset(m,0,slots*sizeof(double));
return m;
}
double *make_dynamic_array(size_t slots)
{
double *m = (double *) malloc(slots*sizeof(double));
m = init_dynamic_array(m, slots);
return m;
}
void init_dimension(size_t size, dimension *d)
{
d->step = 0;
d->size = size;
init_dynamic_array(d->t, size);
init_dynamic_array(d->y, size);
init_dynamic_array(d->v, size);
}
dimension make_dimension(size_t size)
{
dimension d;
d.step = 0;
d.size = size;
d.t = make_dynamic_array(size);
d.y = make_dynamic_array(size);
d.v = make_dynamic_array(size);
return d;
}
dimension dimension_resize(dimension d, size_t new_size)
{
if(d.size == new_size)
return d;
dimension n = make_dimension(new_size);
int i;
if(new_size>d.size)
new_size = d.size;
for(i=0;i<new_size;++i)
{
n.t[i] = d.t[i];
n.y[i] = d.y[i];
n.v[i] = d.v[i];
}
return n;
}
void free_dimension(dimension d)
{
free(d.t);
free(d.y);
free(d.v);
return;
}
double ver_dydt(double t, double x, double v)
{
return v;
}
double ver_dvdt(double t, double x, double v)
{
return g;
}
double hor_dydt(double t, double x, double v)
{
return v;
}
double hor_dvdt(double t, double x, double v)
{
return 0;
}
void euler_solve_free_fall(double angle, double time_step, double in_vel, plane *p)
{
init_dimension(p->x.size, &(p->x));
init_dimension(p->y.size, &(p->y));
p->x.v[0] = in_vel*cos(angle);
p->y.v[0] = in_vel*sin(angle);
int i = 0;
do{
p->y.t[i+1] = p->y.t[i] + time_step;
p->x.t[i+1] = p->y.t[i] + time_step;
p->y.y[i+1] = p->y.y[i] + time_step*ver_dydt(p->y.t[i], p->y.y[i], p->y.v[i]);
p->y.v[i+1] = p->y.v[i] + time_step*ver_dvdt(p->y.t[i], p->y.y[i], p->y.v[i]);
p->x.y[i+1] = p->x.y[i] + time_step*hor_dydt(p->x.t[i], p->x.y[i], p->x.v[i]);
p->x.v[i+1] = p->x.v[i] + time_step*hor_dvdt(p->x.t[i], p->x.y[i], p->x.v[i]);
if(i==p->x.size)
return;
i++;
p->y.step = i;
p->x.step = i;
}while(p->y.y[i] > 0);
return;
}
void rk_solve_free_fall(double angle, double time_step, double in_vel, plane *p)
{
init_dimension(p->x.size, &(p->x));
init_dimension(p->y.size, &(p->y));
p->x.v[0] = in_vel*cos(angle);
p->y.v[0] = in_vel*sin(angle);
double k1,k2,k3,k4,l1,l2,l3,l4;
int i = 0;
do{
/* Time */
p->y.t[i+1] = p->y.t[i] + time_step;
p->x.t[i+1] = p->y.t[i] + time_step;
/* Vertical Position and Velocity */
k1 = time_step*ver_dydt(p->y.t[i], p->y.y[i], p->y.v[i]);
l1 = time_step*ver_dvdt(p->y.t[i], p->y.y[i], p->y.v[i]);
k2 = time_step*ver_dydt(p->y.t[i] + 0.5*time_step, p->y.y[i] + 0.5*k1, p->y.v[i] + 0.5*l1);
l2 = time_step*ver_dvdt(p->y.t[i] + 0.5*time_step, p->y.y[i] + 0.5*k1, p->y.v[i] + 0.5*l1);
k3 = time_step*ver_dydt(p->y.t[i] + 0.5*time_step, p->y.y[i] + 0.5*k2, p->y.v[i] + 0.5*l2);
l3 = time_step*ver_dvdt(p->y.t[i] + 0.5*time_step, p->y.y[i] + 0.5*k2, p->y.v[i] + 0.5*l2);
k4 = time_step*ver_dydt(p->y.t[i] + time_step, p->y.y[i] + k3, p->y.v[i] + l3);
l4 = time_step*ver_dvdt(p->y.t[i] + time_step, p->y.y[i] + k3, p->y.v[i] + l3);
p->y.y[i+1] = p->y.y[i] + (1.0/6.0)*(k1+2*k2+2*k3+k4);
p->y.v[i+1] = p->y.v[i] + (1.0/6.0)*(l1+2*l2+2*l3+l4);
/* Horizontal Position and Velocity */
k1 = time_step*hor_dydt(p->x.t[i], p->x.y[i], p->x.v[i]);
l1 = time_step*hor_dvdt(p->x.t[i], p->x.y[i], p->x.v[i]);
k2 = time_step*hor_dydt(p->x.t[i] + 0.5*time_step, p->x.y[i] + 0.5*k1, p->x.v[i] + 0.5*l1);
l2 = time_step*hor_dvdt(p->x.t[i] + 0.5*time_step, p->x.y[i] + 0.5*k1, p->x.v[i] + 0.5*l1);
k3 = time_step*hor_dydt(p->x.t[i] + 0.5*time_step, p->x.y[i] + 0.5*k2, p->x.v[i] + 0.5*l2);
l3 = time_step*hor_dvdt(p->x.t[i] + 0.5*time_step, p->x.y[i] + 0.5*k2, p->x.v[i] + 0.5*l2);
k4 = time_step*hor_dydt(p->x.t[i] + time_step, p->x.y[i] + k3, p->x.v[i] + l3);
l4 = time_step*hor_dvdt(p->x.t[i] + time_step, p->x.y[i] + k3, p->x.v[i] + l3);
p->x.y[i+1] = p->x.y[i] + (1.0/6.0)*(k1+2*k2+2*k3+k4);
p->x.v[i+1] = p->x.v[i] + (1.0/6.0)*(l1+2*l2+2*l3+l4);
if(i==p->x.size)
return;
i++;
p->y.step = i;
p->x.step = i;
}while(p->y.y[i] > 0);
return;
}
void export_plane(char *filename, plane p)
{
FILE *dat = fopen((const char *) filename, "w");
fprintf(dat, "t x y\n");
int i;
for(i=0;i<p.x.step;++i)
fprintf(dat,"%f %f %f\n", p.x.t[i], p.x.y[i], p.y.y[i]);
fclose(dat);
return;
}
void true_solve_free_fall(double angle, double time_step, double in_vel, plane *p)
{
init_dimension(p->x.size, &(p->x));
init_dimension(p->y.size, &(p->y));
p->x.v[0] = in_vel*cos(angle);
p->y.v[0] = in_vel*sin(angle);
int i=0;
do{
/* Time */
p->y.t[i+1] = p->y.t[i] + time_step;
p->x.t[i+1] = p->y.t[i] + time_step;
/* Vertical Position */
p->y.y[i+1] = p->y.y[0] + p->y.v[0]*p->y.t[i+1] + 0.5*g*pow(p->y.t[i+1],2);
/* Vertical Velocity */
p->y.v[i+1] = p->y.v[0] + g*p->x.t[i+1];
/* Horizontal Position */
p->x.y[i+1] = p->x.y[0] + p->x.v[0]*p->x.t[i+1];
/* Horizontal Velocity */
p->x.v[i+1] = p->x.v[0];
if(i==p->x.size)
return;
i++;
p->y.step = i;
p->x.step = i;
}while(p->y.y[i] > 0);
return;
}
void export_compare(char *filename, plane p, plane e)
{
FILE *dat = fopen((const char *) filename, "w");
fprintf(dat, "t x y xdelta ydelta\n");
int i;
for(i=0;i<p.x.step;++i)
fprintf(dat,"%f %.10f %.10f %.10f %.10f\n", p.x.t[i], p.x.y[i], p.y.y[i], fabs(p.x.y[i] - e.x.y[i]), fabs(p.y.y[i] - e.y.y[i]));
fclose(dat);
return;
}
|
C
|
/*---------------------------------------------------------19910726 RWB-----*/
/* jobser.c -- recv messages passed over the network */
/*--------------------------------------------------------------------------*/
#include <stdio.h>
#include <dos.h>
#include <conio.h>
#include <process.h>
#include <stdlib.h>
#include <string.h>
#include "typdef.h"
#include "msglib.h"
#include "msgapi.h"
/*---------------------------------------------------------------------*/
/* run_command -- run a dos command via command.com */
/*---------------------------------------------------------------------*/
int run_command( char command[] )
{
char args[25][30]; /* allocate space for arguments */
char *argp[25];
int err=0;
word laststart=0;
word parmno=2;
word chn=0;
word endstr=0;
word pn=0;
for (pn=0; pn<25; pn++) argp[pn]=args[pn];
strcpy(args[0],"command.com");
strcpy(args[1],"/c");
while (!endstr)
{
if (command[chn]==0) endstr=1;
if ((command[chn]==' ') || (command[chn]==',') || (endstr))
{
strncpy(args[parmno],command+laststart,chn-laststart);
args[parmno][chn-laststart]=0;
// printf(" Parm %2i: [%s] \n",parmno,args[parmno]);
laststart=chn+1;
parmno++;
}
chn++;
}
argp[parmno]=NULL;
err=spawnvp(P_WAIT,args[0],argp);
return(err);
}
/*--------------------------------------------------------------------------*/
/* try_pipe_all -- try to message pipe to all stations to advertise */
/*--------------------------------------------------------------------------*/
void try_pipe_all(void)
{
int sn=0;
word connection_list[150];
byte result_list[150];
for (sn=0; sn<105; sn++) { connection_list[sn]=sn+1; }
OpenMessagePipe(connection_list,result_list,90);
}
//--------------------------------------------------------------------------
// sit around and wait for messages to come
//--------------------------------------------------------------------------
main(void)
{
#if 0
unsigned int ss[120]={ 0x3132, 0, 0, 0 };
char mm[300]="tester";
unsigned char rr[300];
printf("Return code: %u\n",SendPersonalMessage(mm,ss,rr,1));
return 0;
#else
char mess[400];
int err=0;
word station=0;
char command[200];
union REGS r;
word our_station=0;
byte our_station_byte=0;
r.h.ah=0xDC;
int86(0x21,&r,&r);
our_station_byte=r.h.al;
our_station=r.x.cx;
printf("Station=%02X, (word=%04X)\n",our_station_byte,our_station);
if (!our_station_byte) {
printf("not connected to net -- no station ID.\n");
return 1;
}
delay(0);
printf("Awaiting commands \n");
while (!kbhit())
{
try_pipe_all();
station=recv_message(command);
if (station)
{
printf(" From station [%i] Command: \"%s\" \n",station,command);
err=run_command(command);
printf(" Command Error Level= %i \n",err);
delay(500);
if (station!=our_station_byte) {
sprintf(mess,"JOBSER: \"%s\" complete (%u)",command,err);
broadcast_message(station,mess);
}
}
}
return(0);
#endif
} //main
|
C
|
#include <stdio.h>
#include <string.h>
int N,M;
char input[50][51];
#define MAX(i,j) ((i)>(j))?(i):(j)
int upper(int size,int y,int x);
int lower(int size,int y,int x);
int upper(int size,int y,int x)
{
int i;
int temp;
if(x<0||y>N-1||x>M-1)
return 0;
for(i=0;i<size;i++)
{
if(input[y][x+i]!='#')
return 0;
}
if(temp=upper(size+2,y+1,x-1))
{
return temp;
}
else
{
if(lower(size-2,y+1,x+1))
return size;
}
return 0;
}
int lower(int size,int y,int x)
{
int i;
if(x<0||y>N-1||x>M-1)
return 0;
if(size==1)
{
if(input[y][x]=='#')
return 1;
else
return 0;
}
for(i=0;i<size;i++)
{
if(input[y][x+i]!='#')
return 0;
}
return lower(size-2,y+1,x+1);
}
int main(void)
{
int testcase;
int i,j,temp;
int max;
scanf("%d",&testcase);
while(testcase--)
{
max=0;
scanf("%d",&N);
for(i=0;i<N;i++)
{
scanf("%s",input[i]);
}
M = strlen(input[0]);
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
if(input[i][j]=='#')
{
max=MAX(max,1);
if(temp=upper(3,i+1,j-1))
{
// printf("[y:%d x:%d] size %d \n",i,j,temp);
max = MAX(max,temp);
}
}
}
}
printf("%d\n",max);
}
}
|
C
|
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/version.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <linux/ioctl.h>
#include<linux/proc_fs.h>
#define SET_VALUE _IOW('q', 1, char *)
#define PROC_SET_VALUE _IOW('q', 2, char *)
static dev_t dev;
static struct cdev c_dev;
static struct class *cl;
char value[60]={"\0"};
static int my_open(struct inode *i, struct file *f)
{
printk(KERN_INFO"Driver opened...!!!\n");
return 0;
}
static int my_close(struct inode *i, struct file *f)
{
printk(KERN_INFO"Driver closed...!!!\n");
return 0;
}
static long my_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
{
switch(cmd)
{
case SET_VALUE:
copy_from_user(&value,(char *)arg,sizeof(value));
printk(KERN_INFO"ioctl request processing.......\n");
printk(KERN_INFO"%s\n",value);
break;
case PROC_SET_VALUE:
copy_from_user(&value,(char *)arg,sizeof(value));
printk(KERN_INFO"ioctl request processing.......\n");
printk(KERN_INFO"%s\n",value);
break;
default:
printk(KERN_INFO"Invalid Ioctl request\n");
return -EINVAL;
}
return 0;
}
static struct file_operations my_fops =
{
.owner = THIS_MODULE,
.open = my_open,
.release = my_close,
.unlocked_ioctl = my_ioctl,
};
static int __init query_ioctl_init(void)
{
int ret;
struct device *dev_ret;
if ((ret = alloc_chrdev_region(&dev, 0, 1, "query_ioctl")) < 0)
{
return ret;
}
cdev_init(&c_dev, &my_fops);
if ((ret = cdev_add(&c_dev, dev, 1)) < 0)
{
return ret;
}
if((cl = class_create(THIS_MODULE, "char")) == NULL)
{
printk(KERN_INFO "Cannot create the struct class\n");
cdev_del(&c_dev);
unregister_chrdev_region(dev, 1);
return PTR_ERR(cl);
}
if (IS_ERR(dev_ret = device_create(cl, NULL, dev, NULL, "query")))
{
class_destroy(cl);
cdev_del(&c_dev);
unregister_chrdev_region(dev, 1);
return PTR_ERR(dev_ret);
}
proc_create("my_msg",0666,NULL,&my_fops);
return 0;
}
static void __exit query_ioctl_exit(void)
{
device_destroy(cl, dev);
class_destroy(cl);
cdev_del(&c_dev);
unregister_chrdev_region(dev, 1);
}
module_init(query_ioctl_init);
module_exit(query_ioctl_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Sunil Kumar Sahu");
MODULE_DESCRIPTION("Query ioctl() Char Driver");
|
C
|
/*****************************************************
* cbc.c
This is a simple xor chain encryption program that will encrypt a
file, the filename of which must be provided as a command line
argument, using a simple CBC encryption algorithm. Upon
execution of the program, the user is prompted to enter a
password. If the file is not encrypted, the file will be
overwritten with the encrypted file, and a hash of the password
will be prepended to the begining of the file. If the file is
encrypted, the password is checked against this embedded hash
value before decrypting and overwriting the file.
The target file is cached in RAM; the amount of RAM necessary is
double the size of the file.
*
****************************************************/
#include <stdio.h>
int stringsize(char* string) {
int i = 0;
while ( *(string + i++) != (char) NULL);
return i-1;
}
int clearstring(char* string) {
int i = 0;
if (string == NULL)
return 0;
while ( *(string + i) != (char) NULL) {
*(string + i) = ' ';
i++;
}
return 1;
}
int strip_extra_space( char* p1, char* p2) {
int j;
int i;
char c;
char lastc;
i = 0;
j = 0;
do {
c = *(p1 + i );
if (c == ' ' && lastc == ' ') {
i++;
continue;
}
*(p2 + j) = c;
lastc = c;
j++;
i++;
} while ( c != (char) NULL);
return j;
}
int readfile(char* f, int size, FILE* ifile) {
fseek(ifile,0,SEEK_SET);
fread(f, 1, size, ifile);
*(f + size) = (char) NULL;
fclose(ifile);
return 0;
}
int writefile(char* f, int size, char* filename) {
FILE* ofile;
ofile = fopen(filename,"w");
if (ofile==NULL) {
printf("error writing file\n");
return 1;
} else {
fwrite(f,1, size, ofile);
fclose(ofile);
}
return 0;
}
int stripp(char* p1, char* p2, int psize) { /* take out vowels from the passwd */
int j,i;
char c;
j=0;
for (i=0;i<psize;i++) {
c = *(p1 + i);
if ( c == ' ' || c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
;}
else
*(p2+j++) = c;
}
return j;
}
int getline(char*s , int lim) { /* gets password from keyboard */
char*t;
int c;
int len;
len = lim;
t=s;
while (--lim>1 && (c=getchar()) != EOF && c != '\n')
*s++ = c;
if (c == '\n')
*s++ = c;
else if (lim == 1) {
*s++ = '\n';
fprintf(stderr, "warning, getline too long. splited.\n");
}
*s = '\0';
return s - t;
}
int file_is_encrypted_probably (char* f, int fsize) { /*not implemented */
int i;
int cnt;
char c;
float percent;
cnt = 0;
for (i=0;i<fsize;i++) {
c = *(f + i);
if ((c >= 'a' && c <='z') || (c >= 'A' && c <= 'Z') || (c == ' ') || (c>='1' && c <= '9') || (c=='(') || (c==')') || (c=='*') || (c=='=') || (c==';') || (c=='{') || (c=='}'))
cnt++;
}
percent = (float) ((float)cnt/(float)fsize);
printf("\npercentage=%f",percent);
if (percent >= .666)
return 0;
else
return 1;
}
void fillstring(char* s, int size, char c) {
int i;
for (i=0;i<size;i++)
*(s + i)=c;
return;
}
int decrypt(char* f1, char* f2, int filesize, char* p2, int p2size) {
char c;
char f;
int i;
int j;
char p;
char* constant;
char cons;
constant = (char*) malloc (sizeof(char) * (p2size + 1));
if (constant==NULL)
return 1;
fillstring(constant,p2size,'0');
for (i=0;i<filesize;i++) {
f = *(f1 + i);
j = i % p2size;
p = *(p2 + j);
cons = *(constant + j);
c = p ^ f ^ cons;
*(f2 + i) = c;
*(constant + j) = c;
}
*(f2 + i) = (char) NULL;
free(constant);
return 0;
}
int encrypt(char* f1, char* f2, int filesize, char* p2, int p2size) {
char c;
char f;
int i;
int j;
char p;
char* constant;
char cons;
constant = (char*) malloc (sizeof(char) * (p2size + 1));
if (constant == NULL)
return 1;
fillstring(constant,p2size,'0');
for (i=0;i<filesize;i++) {
f = *(f1 + i);
j = i % p2size;
p = *(p2 + j);
cons = *(constant + j);
c = p ^ f ^ cons;
*(f2 + i) = c;
*(constant + j) = f;
}
*(f2 + i) = (char) NULL;
free(constant);
return 0;
}
int getheaderendpos(char* f, int filesize) { /* used in the event of variable sized headers */
int i;
for (i=0;i<filesize -4;i++)
if (*(f+i)== 0 && (char) *(f+i +1)== 'h' && (char) *(f+ i+2)== 'v' && *(f+ i +3) == 0)
return i+4;
return 0;
}
void writeheader(char* f, long hash) {
long* hashptr;
hashptr = (long*) f;
*hashptr = hash;
f[6] = 0;
f[7] = 'h';
f[8] = 'v';
f[9] = 0;
f[10] = 'x'; /* the 'x' at position 10 means this cbc algorithm was used*/
return;
}
static long hash(const char *key) {
int i=0;
long mask=0x0fffffff;
long hashvalue=0;
int downshift=1 ;
while (*key != '\0')
i=(i<<3)+(*key++ - '0');
hashvalue = (((i*1103515249)>>downshift) & mask);
if (hashvalue < 0) {
hashvalue = 0;
}
return hashvalue;
}
long get_hashfile(char* f)
{
long* hash;
hash = (long*) f;
return *hash;
}
int main(int argc, char** argv) {
FILE* ifile;
char* p1; /* contains password */
char* p2; /* contains stripped password */
char* f1; /* cache of input file */
char* f2; /* cache of file to be written */
char* fileread; /* ptr into string of f1 */
char* filewrite; /* ptr into string of f2 */
int filesize;
int filesizetarget;
int filebegining;
int fileend;
int file_is_encrypted;
int p1size;
int p2size;
int encrypted;
int errchk;
long hashfile;
long hashp2;
int headerend;
int stdhdrsize;
stdhdrsize = 20;
hashfile = 0;
p1 = (char*) NULL;
p2 = (char*) NULL;
f1 = (char*) NULL;
encrypted = 0;
if (argc != 2) {
printf("\nRequires a filename argument to encrypt or decrypt\n");
return 1;
}
ifile = fopen((char*)argv[1],"r");
if (ifile==NULL) {
printf("\nUnable to open file %s\n", argv[1]);
return 1;
}
fseek(ifile,0,SEEK_SET); /* get filesize */
filebegining= ftell(ifile);
fseek(ifile,0,SEEK_END);
fileend = ftell(ifile);
filesize= fileend - filebegining;
p1 = (char*) malloc(sizeof(char)*666);
if (p1 == NULL) {
printf("\nFailed to allocate memory");
return 1;
}
printf("\nEnter Encryption Key:");
getline(p1,666);
if (*p1 == (char) NULL) {
printf("%s","\nRequires encryption key\n");
free(p1);
return 1;
}
p1size = stringsize(p1);
p2 = (char*) malloc (sizeof(char) * (p1size + 1));
if (p2==NULL) {
printf("\nFailed to allocate memory");
free(p1);
return 1;
}
p2size = stripp(p1,p2,p1size);
clearstring(p1);
free(p1);
if (p2size<2) {
printf("Password must contain more consonants\n");
free(p2);
return 1;
}
hashp2 = hash(p2);
f1 = (char*) malloc (sizeof(char) * (filesize + 2 + stdhdrsize));
if (f1==NULL) {
printf("\nFailed to allocate memory");
free(p2);
return 1;
}
f2 = (char*) malloc (sizeof(char) * (filesize + 2 + stdhdrsize));
if (f2==NULL) {
printf("\nFailed to allocate memory");
free(f1);
free(p2);
return 1;
}
readfile(f1,filesize,ifile);
headerend = getheaderendpos(f1, filesize - 1);
if (headerend == 0) {
file_is_encrypted = 0;
fileread = (char*) f1;
filewrite = (char*) (f2 + stdhdrsize);
} else {
file_is_encrypted = 1;
filewrite = f2;
fileread = (char*) (f1 + stdhdrsize);
hashfile = get_hashfile(f1);
if (hashfile != hashp2 ) {
printf("the password is not valid, please try again\n");
clearstring(p2);
free(p2);
free(f1);
free(f2);
return 1;
}
if (f1[10]!='x') {
printf("wrong decryption algorithm\n");
clearstring(p2);
free(p2);
free(f1);
free(f2);
return 1;
}
}
p2size--;
if ( file_is_encrypted) {
printf("\nXOR chain decryption applied to this file: %s\n", argv[1]);
errchk = decrypt(fileread,filewrite,filesize,p2,p2size);
filesizetarget = filesize - stdhdrsize;
} else {
printf("\nXOR chain encryption applied to this file: %s\n", argv[1]);
errchk = encrypt(fileread,filewrite,filesize,p2,p2size);
writeheader(f2,hashp2);
filesizetarget = filesize + stdhdrsize;
}
if (errchk == 0)
writefile(f2,filesizetarget,(char*)argv[1]);
else
printf("\nFailed to allocate memory");
clearstring(p2);
clearstring(f1);
clearstring(f2);
free(p2);
free(f1);
free(f2);
printf("\n");
return 0;
}
|
C
|
/******************************* COPYRIGHT ********************************/
/*
* Copyright (c) 2017 Gregory N. Leonhardt All rights reserved.
*
****************************************************************************/
/******************************** JAVADOC ***********************************/
/**
* The 'file' library provide the ability to open close and delete files
* on the systems file system.
*
* @note
*
****************************************************************************/
/****************************************************************************
* Compiler directives
****************************************************************************/
#define ALLOC_FILE ( "ALLOCATE STORAGE FOR FILE" )
/****************************************************************************
* System Function API
****************************************************************************/
//*******************************************
#include <stdint.h> // Alternative storage types
#include <stdbool.h> // TRUE, FALSE, etc.
#include <stdio.h> // Standard I/O definitions
//*******************************************
#include <string.h> // Functions for managing strings
#include <stdlib.h> // ANSI standard library.
#include <ctype.h> // Determine the type contained
#include <fcntl.h> // Manipulate file descriptor
#include <sys/stat.h> // Get file status
#include <sys/time.h> // gettimeofday()
#include <sys/types.h> // Defines data types used in system source
#include <time.h> // Functions for manipulating date and time
#include <langinfo.h> // Identify items of langinfo data
#include <dirent.h> // Facilitate directory traversing
#include <errno.h> // Defines the integer variable errno
//*******************************************
/****************************************************************************
* Application APIs
****************************************************************************/
//*******************************************
#include <libtools_api.h> // My Tools Library
//*******************************************
#include "file_lib.h" // API for all FILE__* PRIVATE
//*******************************************
/****************************************************************************
* API Enumerations
****************************************************************************/
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
/****************************************************************************
* Private Definitions
****************************************************************************/
//----------------------------------------------------------------------------
#define SYS_CMD_L ( 4096 )
//----------------------------------------------------------------------------
/****************************************************************************
* Private Structures
****************************************************************************/
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
/****************************************************************************
* Private Storage Allocation
****************************************************************************/
//----------------------------------------------------------------------------
/**
* @param bytes_read_last Number of bytes read last count */
float bytes_read_last;
/**
* @param bytes_read_last Total number of bytes read */
float total_bytes_read;
/**
* @param time_now Seconds since the Epoch */
struct timeval time_now;
/**
* @param time_last Seconds since the Epoch */
struct timeval time_last;
//----------------------------------------------------------------------------
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************/
/**
* The file_open_read function is called once for each file. It only
* opens the file and does NOT read any data from it.
*
* @param filename A pointer to a character string containing
* the file name of the input file.
*
* @return file_fp Upon successful completion the file pointer is
* returned else NULL is returned.
*
* @note
*
****************************************************************************/
FILE *
file_open_read(
char * file_name
)
{
/**
* @parm file_fp File pointer */
FILE * file_fp;
/************************************************************************
* Function Initialization
************************************************************************/
/************************************************************************
* File open and verification
************************************************************************/
// Open the input file for read only
file_fp = fopen( file_name, "r");
// Was the file open successful ?
if ( file_fp == NULL)
{
// The file open failed. Change the return code to FAIL
log_write( MID_FATAL, "file_open_read",
"Unable to open file '%s' for read\n",
file_name );
}
else
{
// Log the event
log_write( MID_DEBUG_3, "file_open_read",
"Successfully opened file: '%s' (%p)\n",
file_name, file_fp );
}
/************************************************************************
* Function Exit
************************************************************************/
// DONE!
return( file_fp );
}
/****************************************************************************/
/**
* The file_open_write function is called once for each file. It only
* opens the file and does NOT write any data to it.
*
* @param filename A pointer to a character string containing
* the file name of the input file.
*
* @return file_fp Upon successful completion the file pointer is
* returned else NULL is returned.
*
* @note
*
****************************************************************************/
FILE *
file_open_write(
char * file_name
)
{
/**
* @parm file_fp File pointer */
FILE * file_fp;
/************************************************************************
* Function Initialization
************************************************************************/
/************************************************************************
* File open and verification
************************************************************************/
// Open the input file for read only
file_fp = fopen( file_name, "w");
// Was the file open successful ?
if ( file_fp == NULL)
{
// The file open failed. Change the return code to FAIL
log_write( MID_FATAL, "file_open_write",
"Unable to open file '%s' for write\n",
file_name );
}
else
{
// Log the event
log_write( MID_DEBUG_3, "file_open_write",
"Successfully opened file: '%s' (%p)\n",
file_name, file_fp );
}
/************************************************************************
* Function Exit
************************************************************************/
// DONE!
return( file_fp );
}
/****************************************************************************/
/**
* The file_open_write function is called once for each file. It only
* opens the file and does NOT write any data to it.
*
* @param filename A pointer to a character string containing
* the file name of the input file.
*
* @return file_fp Upon successful completion the file pointer is
* returned else NULL is returned.
*
* @note
*
****************************************************************************/
FILE *
file_open_write_no_dup(
char * file_name,
char * dup_name
)
{
/**
* @parm file_fp File pointer */
FILE * file_fp;
/**
* @param mod_file_name Modified file name */
char mod_file_name[ 1024 ];
/**
* @param dup_count Number of duplicate files */
int dup_count;
/************************************************************************
* Function Initialization
************************************************************************/
// Initialize the file pointer
file_fp = NULL;
// Initialize the duplicate file count
dup_count = 0;
// Is the input file name too large to handle ?
if ( strlen( file_name ) > sizeof( mod_file_name ) )
{
// YES: Not a good thing
log_write( MID_FATAL, "file_open_write_no_dup",
"The file name string is too large.\n" );
}
else
{
// NO: Copy it to the local file name buffer
memset( mod_file_name, '\0', sizeof( mod_file_name ) );
strncpy( mod_file_name, file_name, sizeof( mod_file_name ) );
}
/************************************************************************
* File open and verification
************************************************************************/
do
{
// Is there a currently open file ?
if ( file_fp != NULL )
{
// YES: Close it.
fclose( file_fp );
}
// Test for an existing file
file_fp = fopen( mod_file_name, "r");
// Does it already exist ?
if ( file_fp != NULL )
{
// YES: Will the modified file name fit into the buffer
if ( ( strlen( file_name ) + strlen( dup_name ) + 6 )
> ( sizeof( mod_file_name ) ) )
{
// YES: Not a good thing
log_write( MID_FATAL, "file_open_write_no_dup",
"The modified file name string is too large.\n" );
}
else
{
// NO: Copy it to the local file name buffer
memset( mod_file_name, '\0', sizeof( mod_file_name ) );
snprintf( mod_file_name, sizeof( mod_file_name ),
"%s.%s%04X", file_name, dup_name, ++dup_count );
}
}
} while( file_fp != NULL );
// Now open the file for write
file_fp = file_open_write( mod_file_name );
/************************************************************************
* Function Exit
************************************************************************/
// DONE!
return( file_fp );
}
/****************************************************************************/
/**
* The file_open_append function is called once for each file. It only
* opens the file and does NOT read or write any data from/to it.
*
* @param filename A pointer to a character string containing
* the file name of the input file.
*
* @return file_fp Upon successful completion the file pointer is
* returned else NULL is returned.
*
* @note
*
****************************************************************************/
FILE *
file_open_append(
char * file_name
)
{
/**
* @parm file_fp File pointer */
FILE * file_fp;
/************************************************************************
* Function Initialization
************************************************************************/
/************************************************************************
* File open and verification
************************************************************************/
// Open the input file for read only
file_fp = fopen( file_name, "a");
// Was the file open successful ?
if ( file_fp == NULL)
{
// The file open failed. Change the return code to FAIL
log_write( MID_FATAL, "file_open_append",
"Unable to open file '%s' for append\n",
file_name );
}
else
{
// Log the event
log_write( MID_DEBUG_3, "file_open_append",
"Successfully opened file: '%s' (%p)\n",
file_name, file_fp );
}
/************************************************************************
* Function Exit
************************************************************************/
// DONE!
return( file_fp );
}
/****************************************************************************/
/**
* The file_close function is will close a previously opened file.
*
* @param file_fp Pointer to the previously opened file.
*
* @return void No return information from this function.
*
* @note
*
****************************************************************************/
void
file_close(
FILE * file_fp
)
{
/************************************************************************
* Function Initialization
************************************************************************/
/************************************************************************
* File Close
************************************************************************/
// Close a previously opened file
fclose( file_fp );
log_write( MID_DEBUG_3, "file_close",
"Successfully closed file: (%p)\n",
file_fp );
/************************************************************************
* Function Exit
************************************************************************/
// DONE!
}
/****************************************************************************/
/**
* Read a single line of test from the file.
*
* @param in_buffer_p Pointer to a file previously opened for read.
*
* @return data Pointer to the data read from the file.
* END_OF_FILE at End-Of-File
*
* @note
*
****************************************************************************/
char *
file_read_text(
FILE * file_fp,
enum read_text_options_e options
)
{
/**
* @param in_line Local buffer to store read data */
char in_line[ MAX_LINE_L ];
/**
* @param in_line_p Pointer to the read data buffer */
char * in_line_p;
/**
* @param tmp_data_1_p Pointer to a temporary data buffer */
char * tmp_data_1_p;
/**
* @param tmp_data_2_p Pointer to a temporary data buffer */
char * tmp_data_2_p;
/**
* @param eof_p End-Of-File pointer (NULL == EOF) */
char * eof_p;
/**
* @param eol End-Of-Line flag */
int eol;
/**
* @param found TRUE = found, FALSE = not found */
int found;
/**
* @param bytes_read Total number of bytes read */
float bytes_read;
/************************************************************************
* Function Initialization
************************************************************************/
// Not at End-Of-Line yet.
eol = false;
// Clean the input buffer
memset( in_line, '\0', sizeof( in_line ) );
// Initialize the buffer pointers
in_line_p = NULL;
tmp_data_1_p = NULL;
tmp_data_2_p = NULL;
/************************************************************************
* Read a new line of text
************************************************************************/
// Continue to read until End-Of-Line is reached
while( eol == false )
{
// Read another line of text from the input file
eof_p = fgets( in_line, sizeof( in_line ), file_fp );
// Are we at End-Of-File ?
if ( eof_p == NULL )
{
// YES: Are we at End-Of-File ?
in_line_p = END_OF_FILE;
// We are done here!
break;
}
else
{
// NO: Update the total number of bytes read.
total_bytes_read += strlen( in_line );
// What time is it ?
gettimeofday( &time_now, NULL );
// Is the first time through here ?
if ( time_last.tv_sec == 0 )
{
// YES: Update the last display time
time_last.tv_sec = time_now.tv_sec;
}
// Is it time to display ?
if ( ( time_last.tv_sec + 60 ) <= time_now.tv_sec )
{
// YES: Update the last display time
time_last.tv_sec = time_now.tv_sec;
// Is this the first time ?
if ( bytes_read_last > 0 )
{
// NO: Calculate the transfer rate.
bytes_read = total_bytes_read - bytes_read_last;
// Log the transfer rate
log_write( MID_DEBUG_0, "file_read_text",
"Transfer rate: %3.2f KB/s\n",
( ( bytes_read / 1000 ) / 60 ) );
}
// Save the current count
bytes_read_last = total_bytes_read;
}
// Remove the CR/LF characters (if present)
text_remove_crlf( in_line );
// Remove any trailing whitespace from the end of the line
text_strip_whitespace( in_line );
// Move the read data to a temporary buffer
tmp_data_2_p = text_copy_to_new( in_line );
log_write( MID_DEBUG_1, "file_api.c", "Line: %d\n", __LINE__ );
// Is there already data in the read data buffer ?
if ( tmp_data_1_p == NULL )
{
// NO: Transfer data from the tmp buffer to the read data buffer.
tmp_data_1_p = tmp_data_2_p;
// clear the temporary data pointer
tmp_data_2_p = NULL;
}
else
{
/**
* @param copy_of_p Pointer to a temporary buffer */
char * copy_of_p;
/**
* @param data_l Size (in bytes) of the data */
int data_l;
// YES: Calculate the size needed for the two buffers.
data_l = strlen( tmp_data_1_p ) + strlen( tmp_data_2_p ) + 1;
// Allocate a new buffer for the two lines.
copy_of_p = mem_malloc( data_l );
log_write( MID_DEBUG_1, "file_api.c", "Line: %d\n", __LINE__ );
// Copy the two lines of text to the new buffer
strncpy( copy_of_p, tmp_data_1_p, data_l );
strncat( copy_of_p, tmp_data_2_p, data_l );
// Free the unused data buffer(s)
mem_free( tmp_data_1_p );
mem_free( tmp_data_2_p );
// This is now the new temporary data 1 buffer
tmp_data_1_p = copy_of_p;
}
}
// Does line of data end with an equals sign '=' ?
if ( ( tmp_data_1_p != NULL )
&& ( tmp_data_1_p[ strlen( tmp_data_1_p ) - 1 ] == '=' )
&& ( tmp_data_1_p[ strlen( tmp_data_1_p ) - 2 ] != '=' ) )
{
// YES: Strip off the equals sign
tmp_data_1_p[ strlen( tmp_data_1_p ) - 1 ] = '\0';
}
else
{
// NO: This is the end of the text line
eol = true;
// Set the return data pointer
in_line_p = tmp_data_1_p;
}
}
/********************************************************************
* Change character coding from quoted printable
********************************************************************/
// Are we at End-Of-File "
if ( ( in_line_p != END_OF_FILE )
&& ( in_line_p != NULL ) )
{
// Initialize the search pointer
tmp_data_2_p = in_line_p;
do
{
/**
* @param xlate_char The translated character */
long int xlate_char;
/**
* @param data_l Size (in bytes) of the data */
int data_l;
// Set the found flag to it's default state.
found = false;
// Look for the first character of a quoted printable string
tmp_data_1_p = strchr( tmp_data_2_p, '=' );
// Did we find one ?
if ( tmp_data_1_p != NULL )
{
// Is the format correct ?
if ( ( tmp_data_1_p[ 0 ] == '=' )
&& ( isxdigit( tmp_data_1_p[ 1 ] ) != 0 )
&& ( isxdigit( tmp_data_1_p[ 2 ] ) != 0 ) )
{
/**
* @param in_line Temporary for HEX to ASCII */
char hex_data[ 3 ];
// YES: change the state of the found flag
found = true;
// Clear the buffer and copy the hex data string
memset( hex_data, '\0', sizeof( hex_data ) );
memcpy( hex_data, &tmp_data_1_p[ 1 ], 2 );
// Convert the string to a single character
xlate_char = strtol( hex_data, NULL, 16 );
// Is this x'BD (1/2)
if ( xlate_char == 0xBD )
{
// YES: Write it out
tmp_data_1_p[ 0 ] = '1';
tmp_data_1_p[ 1 ] = '/';
tmp_data_1_p[ 2 ] = '2';
}
// Is this x'BC (1/4)
if ( xlate_char == 0xBC )
{
// YES: Write it out
tmp_data_1_p[ 0 ] = '1';
tmp_data_1_p[ 1 ] = '/';
tmp_data_1_p[ 2 ] = '4';
}
// Is this x'BE (3/4)
if ( xlate_char == 0xBC )
{
// YES: Write it out
tmp_data_1_p[ 0 ] = '3';
tmp_data_1_p[ 1 ] = '/';
tmp_data_1_p[ 2 ] = '4';
}
else
{
// None of the above. write the converted character
tmp_data_1_p[ 0 ] = (char)xlate_char;
// Find the string length of the remaining data
data_l = strlen( &tmp_data_1_p[ 3 ] );
// Is there anything else in the string ?
if ( data_l > 0 )
{
/**
* @param ndx Offset into a buffer */
int ndx;
// @note: I have an interesting problem with the following.
// Both the 'strcpy' and 'memcpy' are corrupting data.
// Before: "B0. Prepare a 9\\" pie pan with cooking spray and flour; set aside. T"
// strcpy: ". Prepare 9\\" p pie pan with cooking spray and flour; set aside. T"
// memcpy: ". Prepare a pie pan with cooking spray and flour; set aside. . T"
// EXPECTED: ". Prepare a 9\\" pie pan with cooking spray and flour; set aside. T"
// YES: Left shift the remainder of the string
for( ndx = 1; tmp_data_1_p[ ndx ] != '\0'; ndx += 1 )
{
tmp_data_1_p[ ndx ] = tmp_data_1_p[ ndx + 2 ];
}
// Set the new search starting pointer
tmp_data_2_p = &tmp_data_1_p[ 1 ];
}
else
{
// NO: Terminate the string here
tmp_data_1_p[ 1 ] = '\0';
}
}
}
}
} while( found == true );
}
// Remove the CR/LF characters (if present)
// @NOTE: The line may have ended with =0D
if ( ( in_line_p != NULL )
&& ( in_line_p != END_OF_FILE ) )
{
text_remove_crlf( in_line_p );
}
/************************************************************************
* Function Exit
************************************************************************/
// DONE!
return( in_line_p );
}
/****************************************************************************/
/**
* Read a single line of test from the file.
*
* @param file_p Pointer to a file previously opened for read.
* @param buffer_p Pointer to a read buffer
* @param size Number of bytes to read.
*
* @return read_data_l The number of bytes received from the
* read. Zero if at End of File.
*
* @note
*
****************************************************************************/
size_t
file_read_data(
FILE * file_fp,
char * buffer_p,
size_t size
)
{
/**
* @param read_data_l Number of bytes read */
size_t read_data_l;
/************************************************************************
* Function Initialization
************************************************************************/
// Clean the input buffer
memset( buffer_p, '\0', size );
/************************************************************************
* Read a new line of text
************************************************************************/
// Read some data from the input file
read_data_l = fread( buffer_p, 1, size, file_fp );
/************************************************************************
* Function Exit
************************************************************************/
// DONE!
return( read_data_l );
}
/****************************************************************************/
/**
* The file_stat function is called once for each file. It only opens the
* file and does NOT read any data from it.
*
* @param full_file_name_p Pointer to the fully qualified file name.
* @param file_name_p Pointer to File name.
*
* @return Upon successful completion PASS is returned
* else FAIL is returned
*
* @note
****************************************************************************/
struct file_info_t *
file_stat(
char * full_file_name_p,
char * file_name_p
)
{
/**
* @param file_rc Return Code */
int file_rc;
/**
* @param statbuf File statistics data */
struct stat statbuf;
/**
* @param tm Time structure */
struct tm * tm;
/**
* @param file_info_p Pointer to file information */
// struct file_info_t file_info;
/**
* @param file_info_p Pointer to file information */
struct file_info_t * file_info_p;
/**
* @parm tmp_char_p Pointer to a character buffer */
char * tmp_char_p;
/**
* @param dir_name Buffer to hold the directory name */
char dir_name[ FILE_NAME_L ];
/************************************************************************
* Function Initialization
************************************************************************/
// Allocate a structure to save the file information
file_info_p = mem_malloc( sizeof( struct file_info_t ) );
log_write( MID_DEBUG_1, "file_api.c", "Line: %d\n", __LINE__ );
/************************************************************************
* Function Body
************************************************************************/
// Copy the full file name to the directory name buffer
strncpy( dir_name, full_file_name_p, sizeof( dir_name ) - 1 );
// Is the last character of the full file name a '/' ?
if ( dir_name[ strlen( dir_name ) - 1 ] == '/' )
{
// YES: Remove it from the string
dir_name[ strlen( dir_name ) - 1 ] = '\0';
}
// Is there a directory in the full file name ?
if ( strrchr( dir_name, '/' ) == NULL )
{
// NO: Just use the full file name
strncpy( file_info_p->file_name, dir_name,
sizeof( file_info_p->file_name ) - 1 );
strncpy( file_info_p->dir_name, ".",
sizeof( file_info_p->dir_name ) - 1 );
}
else
{
// YES: Split the directory path from the file name
tmp_char_p = strrchr( dir_name, '/' );
// NULL terminate the directory path string
tmp_char_p[ 0 ] = '\0';
// Save file name string
strncpy( file_info_p->dir_name, dir_name,
sizeof( file_info_p->dir_name ) - 1 );
// Save file name string
strncpy( file_info_p->file_name, &tmp_char_p[ 1 ],
sizeof( file_info_p->file_name ) - 1 );
}
// Get statistics for the file name
file_rc = stat( full_file_name_p, &statbuf );
// Were we successful at getting the statistics data ?
if ( file_rc != -1 )
{
// YES: File Size
snprintf( file_info_p->file_size, sizeof( file_info_p->file_size ),
"%ld", statbuf.st_size );
// File Creation Time
tm = localtime( &statbuf.st_mtime );
#if 0
strftime( file_info_p->date_time,
sizeof( file_info_p->date_time ),
nl_langinfo( D_T_FMT ),
tm );
#else
strftime( file_info_p->date_time,
sizeof( file_info_p->date_time ),
"%Y/%m/%d %H:%M:%S",
tm );
#endif
}
else
{
// NO: Set the return pointer to NULL to show the failure
mem_free( file_info_p );
file_info_p = NULL;
}
/************************************************************************
* Function Exit
************************************************************************/
// TTFN!
return ( file_info_p );
}
/****************************************************************************/
/**
* Create a recursive list of files in a directory tree.
*
* @param fd_name A directory name.
* @param file_list_p Pointer to a list for the list of files
* @param include_ext_p Pointer to a file extension to include
*
* @return void No return information from this function.
*
* @note
*
****************************************************************************/
void
file_ls(
struct list_base_t * file_list_p,
char * fd_name,
char * include_ext_p
)
{
/**
* @param directory_p Directory pointer */
DIR * directory_p;
/**
* @param entry Directory information structure */
struct dirent * entry;
/**
* @param statbuf File or Directory state data */
struct stat statbuf;
/**
* @param full_file_name Fully qualified file name */
char full_file_name[ MAX_LINE_L ];
/**
* @param file_info_p Pointer to a file information structure */
struct file_info_t * file_info_p;
/**
* @param stat_data_p Pointer to a file statistics structure */
struct file_info_t * stat_data_p;
/************************************************************************
* Function Initialization
************************************************************************/
// Log the progress
log_write( MID_DEBUG_0, "file_next",
"Scanning: '%s'\n",
fd_name );
/************************************************************************
* Function Body
************************************************************************/
// Attempt to open a directory
if ( ( directory_p = opendir( fd_name ) ) == NULL )
{
log_write( MID_FATAL, "file_next",
"File or Directory '%s' does not exist.\n",
fd_name );
}
// Directory:
while( ( entry = readdir( directory_p ) ) != NULL )
{
// Will the full name fit in the buffer ?
if ( ( strlen( fd_name ) + strlen( entry->d_name ) )
< ( sizeof( full_file_name ) - 2 ) )
{
// YES: Expand the name
snprintf( full_file_name, sizeof( full_file_name ),
"%s/%s", fd_name, entry->d_name );
}
else
{
// NO: Error message
log_write( MID_INFO, "file_next",
"Full file name is larger than the allocated buffer\n" );
log_write( MID_FATAL, "file_next",
"%s/%s\n", fd_name, entry->d_name );
}
// Test for a directory or a file name.
lstat( full_file_name, &statbuf );
// Is this a directory ?
if ( S_ISDIR( statbuf.st_mode ) )
{
/****************************************************************
* Exclude these directories
****************************************************************/
// YES: Does the directory name match any of the following ?
if ( ( strcmp( entry->d_name, "." ) == 0 )
|| ( strcmp( entry->d_name, ".." ) == 0 ) )
{
// YES: Exclude it from processing.
continue;
}
// Build a file list for this directory
file_ls( file_list_p, full_file_name, include_ext_p );
}
else
{
// Is there a extension exclude type ?
if ( include_ext_p != NULL )
{
/**
* @param period_p Pointer to the last period */
char * period_p;
/**
* @param extention Buffer to hold file extention */
char extention[ 10 ];
// YES: Locate the start of the file extention
period_p = strrchr( full_file_name, '.' );
// Is there a file extention ?
if ( period_p != NULL )
{
// YES: Copy the file extention to a new buffer
strncpy( extention, ++period_p, sizeof( extention ) );
// Make the file extention all lowercase
text_to_lowercase( extention );
// Compare the file extention to the include extention.
if ( strncmp( include_ext_p, extention, strlen( include_ext_p ) ) != 0 )
{
// NO: This isn't an include file extention
continue;
}
}
}
// NO: Allocate a structure to save the file information
file_info_p = mem_malloc( sizeof( struct file_info_t ) );
log_write( MID_DEBUG_1, "file_api.c", "Line: %d\n", __LINE__ );
// Get the file statics data
stat_data_p = file_stat( full_file_name, entry->d_name );
// Clean th destination buffers
memset( file_info_p->dir_name, '\0', sizeof( file_info_p->dir_name ) );
memset( file_info_p->file_name, '\0', sizeof( file_info_p->file_name ) );
memset( file_info_p->date_time, '\0', sizeof( file_info_p->date_time ) );
memset( file_info_p->file_size, '\0', sizeof( file_info_p->file_size ) );
// Save the file information
strncpy( file_info_p->dir_name,
fd_name,
sizeof( file_info_p->dir_name ) - 1 );
strncpy( file_info_p->file_name,
stat_data_p->file_name,
sizeof( file_info_p->file_name ) - 1 );
strncpy( file_info_p->date_time,
stat_data_p->date_time,
sizeof( file_info_p->date_time ) - 1 );
strncpy( file_info_p->file_size,
stat_data_p->file_size,
sizeof( file_info_p->file_size ) - 1 );
// Add the new file to the list
list_put_last( file_list_p, file_info_p );
}
}
/************************************************************************
* Function Exit
************************************************************************/
// At the end of the directory, close it.
closedir( directory_p );
// DONE!
}
/****************************************************************************/
/**
* Returns a pointer to a text string with the directory path to the
* .LibTools directory.
*
* @param void No information is passed into this function
*
* @return path_p Pointer to the directory path
*
* @note
*
****************************************************************************/
char *
file_path_to_lib(
void
)
{
/**
* @param path_p Pointer to the directory path */
char * path_p;
/**
* @param tmp_p Pointer to a temporary buffer */
char * tmp_p;
/************************************************************************
* Function Exit
************************************************************************/
/************************************************************************
* Function
************************************************************************/
// Allocate storage for the directory path.
path_p = mem_malloc( FILE_NAME_L + 1 );
// Get the home directory path
tmp_p = getenv( "HOME" );
// Did we get it ?
if ( tmp_p != NULL )
{
// YES: Build the full path
snprintf( path_p, FILE_NAME_L,
"%s/%s", tmp_p, LOG_DIR_NAME );
}
else
{
// NO: This is bad.
log_write( MID_FATAL, "file_path_to_lib",
"Environment variable 'HOME' is not set.\n" );
}
/************************************************************************
* Function Exit
************************************************************************/
// DONE!
return( path_p );
}
/****************************************************************************/
/**
* Recursively find and extract all "*.zip" files in the target directory.
*
* @param dir_p Pointer to the starting directory
*
* @return void No information is returned from this function.
*
* @note
*
****************************************************************************/
int
file_unzip(
char * path_p
)
{
/**
* @param unzip_count Number of files UnZipped */
int unzip_count;
/**
* @param found_zip Flag showing a "*.zip" file was found. */
int found_zip;
/**
* @param file_list Pointer to a list of files */
struct list_base_t * file_list_p;
/**
* @param file_info_p Pointer to a file information structure */
struct file_info_t * file_info_p;
/**
* @param file_name Buffer to hold the directory/file name */
char file_name[ ( FILE_NAME_L * 3 ) ];
/**
* @param extract_to Name of the directory to extract into */
char extract_to[ ( FILE_NAME_L * 4 ) ];
/**
* @param saved_dir_name Saved directory name */
char saved_dir_name[ ( FILE_NAME_L * 3 ) ];
/**
* @param tmp_p Temporary data pointer */
char * tmp_p;
/**
* @param command System command buffer */
char command[ SYS_CMD_L ];
/**
* @param extention Buffer to hold file extention */
char extention[ 10 ];
/**
* @param dir_created Directory was created */
int dir_created;
/**
* @param dir_ndx Directory name index */
int dir_ndx;
/************************************************************************
* Function Initialization
************************************************************************/
// Create the file-list
file_list_p = list_new( );
// Reset the number of unzipped files.
unzip_count = 0;
/************************************************************************
* Function
************************************************************************/
// Keep looping until there are no more "*.zip" files
do
{
// Assume that we will NOT find a "*.zip" file
found_zip = false;
// Build the file list
file_ls( file_list_p, path_p, "zip" );
// Scan the list
for( file_info_p = list_get_first( file_list_p );
file_info_p != NULL;
file_info_p = list_get_next( file_list_p, file_info_p ) )
{
// Remove it from the list
list_delete_payload( file_list_p, file_info_p );
// Will the fully qualified file name will fit in the buffer ?
if ( ( ( strlen( file_info_p->dir_name ) )
+ ( strlen( file_info_p->file_name ) ) )
>= ( sizeof( file_name ) ) )
{
// NO: This is bad..
log_write( MID_WARNING, "file_unzip",
"The file name is too big for the buffer provided. \n" );
log_write( MID_FATAL, "file_unzip",
"'%s/%s'\n",
file_info_p->dir_name, file_info_p->file_name );
}
else
{
// YES: build the full file name.
snprintf( file_name, sizeof( file_name ) - 1,
"%s/%s",
file_info_p->dir_name, file_info_p->file_name );
snprintf( extract_to, sizeof( extract_to ) - 1,
"%s/%s",
file_info_p->dir_name, file_info_p->file_name );
}
// Find the file extension
tmp_p = strrchr( extract_to, '.' );
// Is there one ?
if ( tmp_p != NULL )
{
// YES: Is this a "*.zip" file ?
if ( strncasecmp( ++tmp_p, "zip", 3 ) == 0 )
{
// YES: Null terminate at the period
(--tmp_p)[ 0 ] = '\0';
// Save the directory name
strncpy( saved_dir_name, extract_to, sizeof( saved_dir_name ) );
// Initialize the directory index value
dir_ndx = 0;
#if 1
do
{
// Create a directory to extract into.
dir_created = mkdir( extract_to, S_IRWXU | S_IRWXG | S_IRWXO );
// Was the directory creation successful ?
if ( dir_created == 0 )
{
// YES: Log it.
log_write( MID_INFO, "file_unzip",
"Extracting: '%s'\n", file_name );
// Build the unzip command
snprintf( command, sizeof ( command ),
"unzip -q -o \"%s\" -d \"%s\"",
file_name,
extract_to );
// Uncompress the file into the new directory
system( command );
// Finally, delete the zip file.
remove( file_name );
// Change the flag, we extracted a "*.zip" file
found_zip = true;
// Increment the number of files unzipped
unzip_count += 1;
}
else
{
// NO: Does the directory already exist ?
if ( errno == EEXIST )
{
// YES: Increment the index and try again
snprintf( extract_to, sizeof( extract_to ),
"%s_%02d", saved_dir_name, ++dir_ndx );
}
else
{
// NO: Something bad happened.
log_write( MID_FATAL, "file_unzip", "%s\n",
"Unable to create the extraction "
"directory because: %s\n",
strerror( errno ) );
}
}
} while( dir_created != 0 );
#else
// Make a new directory for the uncompressed file(s).
if ( mkdir( extract_to, S_IRWXU | S_IRWXG | S_IRWXO ) == 0 )
{
// YES: Log it.
log_write( MID_INFO, "file_unzip",
"Extracting: '%s'\n", file_name );
// Build the unzip command
snprintf( command, sizeof ( command ),
"unzip -q -o \"%s\" -d \"%s\"",
file_name,
extract_to );
// Uncompress the file into the new directory
system( command );
// Finally, delete the zip file.
remove( file_name );
// Change the flag, we extracted a "*.zip" file
found_zip = true;
// Increment the number of files unzipped
unzip_count += 1;
}
#endif
}
}
// Release storage for the File Information structure
mem_free( file_info_p );
}
} while( found_zip == true );
/************************************************************************
* Function Exit
************************************************************************/
// Create the file-list
list_kill( file_list_p );
// DONE!
return( unzip_count );
}
/****************************************************************************/
/**
* Test if the directory already exists.
*
* @param dir_p Pointer to the starting directory
* @param create When TRUE and the directory does NOT already
* exist, create it.
*
* @return file_rc TRUE when the directory exists, else FALSE.
*
* @note
*
****************************************************************************/
int
file_dir_exist(
char * path_p,
int create
)
{
/**
* @param file_rc Function return code */
int file_rc;
/**
* param directory_p Directory information structure */
DIR * directory_p;
/**
* @param func_rc Function return code */
int func_rc;
/************************************************************************
* Function Initialization
************************************************************************/
// Assume the directory does NOT exist
file_rc = false;
/************************************************************************
* Function
************************************************************************/
// Attempt to open the directory
directory_p = opendir( path_p );
// Does it already exist ?
if ( directory_p )
{
// YES: Directory exists.
closedir( directory_p );
// Set the return code
file_rc = true;
}
else
{
// NO: Should it be created ?
if ( create == true )
{
// YES: Do it!
func_rc = mkdir( path_p, 0766 );
// Success ?
if ( func_rc != -0 )
{
// NO: Let everyone know why.
log_write( MID_FATAL, "file_dir_exist",
"Unable to create directory %s\n%s\n",
path_p, strerror( errno ) );
}
}
}
/************************************************************************
* Function Exit
************************************************************************/
// DONE!
return( file_rc );
}
/****************************************************************************/
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main() {
float valordia = 30;
float taxair= 0.08;
float taxainss= 0.04;
float valorbruto ;
int dias;
printf(" Digite o numero de dias trab:");
scanf("%d",&dias);
valorbruto = (dias *valordia);
printf("o salario bruto e %.2f:", valorbruto);
printf("O salario liquido e: %.2f :",valorbruto - (valorbruto * taxair) - (valorbruto * taxainss));
printf("taxa ir e: %.2f :", valorbruto * taxair );
printf("taxa inss e: %.2f :", valorbruto * taxainss);
return 0;
}
|
C
|
#include"stdio.h"
#include"unistd.h"
#include"fcntl.h"
#include"sys/types.h"
#include"errno.h"
int main()
{
int fd1, fd2, fd3, dup2ret;
char buffer[12];
printf("PID :- %ld\n",(long)getpid());
fd1 = ("read.c",O_RDONLY);
fd2 = ("read.c",O_RDONLY);
fd3 = ("select.c",O_RDONLY);
dup2ret = dup2(fd,19);
if(dup2ret == -1)
{
perror("dup2 error");
return 1;
}
printf("Dup2 return = %d\n",dup2ret);
}
// output of Question no.5 and no. 6:- BAD FILE DESCRIPTOR
|
C
|
// Annie is the talk of the town, who recently won the prize for being the most beautiful woman of her town. Due to her achievement, she has become Dream girl of the youth.
// So, many people in the town are trying to propose her, but She has her own demands and only if the demands are satisfied, she will accept the proposal. She loves two types of chocolates a and b,
//and she wants someone to gift her d chocolates during the act of proposing. You have infinite supply of boxes of chocolates of type a and b, box of type a contains n chocolates whereas box of type b contains m chocolates. You can gift her d chocolates by using boxes of both the types.
// (You cannot use any box partially).
// Now, You have to find the number of ways in which you can impress her.
// Input Format
// The first line of input consists of an integer T denoting the number of test cases. Each test case consists of only one line containing three space separated integers n(Number of chocolates in box of type a), m(Number of chocolates in box of type b) and d.
// Constraints
// 1 ≤ T ≤ 10^5
// 1 ≤a < b ≤ 10^9
// 0 ≤ d ≤ 109
// Output Format
// For each test case, print the answer in a separate line.
// Sample Input
// 3
// 2 3 7
// 4 10 6
// 5 1 5
// Sample Output
// 1
// 0
// 2
// Explanation
// Test case 1:
// 7 chocolates can only be achieved by using 2 boxes of type a and 1 box of type b.
// Test case 2: No combination of boxes exist to satisfy the value of d.
// Test case 3: 5 chocolates can be achieved by using 2 combinations.
// 1) -> 1 box of type a and 0 box of type b.
// 2)-> 0 box of type a and 5 boxes of type b.
#include <stdio.h>
#include <stdlib.h>
int find_ways(int n, int m , int d)
{
int i,remainig,count=0;
i=0;
while (i*n<=d)
{
if((d-i*n)%m==0)
count++;
i++;
}
return count;
}
void main()
{
int t,*m,*n,*d,i;
printf("\nEnter the test case : ");
scanf("%d",&t);
m=(int *)malloc(sizeof(int)*t);
n=(int *)malloc(sizeof(int)*t);
d=(int *)malloc(sizeof(int)*t);
for ( i = 0; i < t; i++)
{
printf("\nEnter the data for test case %d : ",i+1);
scanf("%d%d%d",n+i,m+i,d+i);
}
for ( i = 0; i < t; i++)
{
printf("\nThe number of ways to impress in test case %d is %d ",i+1,find_ways(*(n+i),*(m+i),*(d+i)));
}
}
|
C
|
// Protótipo para o programa de criação de listas invertidas utilizando MPI
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<mpi.h>
typedef struct chave{
char valor[30];
int ordem;
struct chave *prox;
}Chave;
typedef struct chaveiro{
Chave *c;
struct chaveiro *prox;
}Chaveiro;
void tratarDados(char *frase){
char caracteresIgnorados[] = {'?','!','.',','};
int reescrever=0;
int i=0,j;
while(1){
frase[i-reescrever] = frase[i];
for(j=0;j<4;j++){
if(frase[i] == caracteresIgnorados[j]){
reescrever++;
}
}
if(frase[i]=='\0'){break;}
i++;
}
}
Chave *copiar(Chave *original){
if(original == NULL) {return NULL;}
int i=0;
Chave *copia = (Chave*) malloc(sizeof(Chave));
copia -> ordem = original -> ordem;
do{
copia -> valor[i] = original -> valor[i];
i++;
}
while(original->valor[i]!='\0');
copia->prox = copiar(original->prox);
return copia;
}
Chave *separar(char *frase){
Chave *head = (Chave*) malloc(sizeof(Chave));
head -> prox = NULL;
Chave *atual = head;
int ordem = 1;
int i=0,j=0;
do{
if(frase[i] == ' '){
atual -> valor[j]='\0';
atual -> prox = (Chave*) malloc(sizeof(Chave));
atual -> ordem = ordem++;
atual = atual -> prox;
atual -> prox = NULL;
i++;
j=0;
}
atual->valor[j++] = frase[i++];
}
while(frase[i]!='\0');
return head;
}
int comparar(char *val1, char *val2){
int i=-1;
do{
i++;
if(val1[i]!=val2[i])
return 0;
}
while(val1[i]!='\0');
return 1;
}
Chave *entradasUnicas(Chave *chaves,int *numero){
Chave *salvar=chaves;
Chave *atual = NULL;
Chave *eliminar;
int num=0;
while(chaves!=NULL){
if(chaves->valor[0]!='!'){
num++;
atual = chaves -> prox;
while(atual!=NULL){
if(comparar(chaves->valor,atual->valor)){
atual->valor[0]='!';
}
atual = atual->prox;
}
}
chaves = chaves -> prox;
}
chaves = salvar;
while(chaves != NULL && chaves->prox!=NULL){
if(chaves->prox->valor[0]=='!'){
eliminar = chaves ->prox;
if(chaves -> prox != NULL)
chaves -> prox = chaves -> prox -> prox;
else
chaves -> prox = NULL;
free(eliminar);
}
else{
chaves = chaves->prox;
}
}
*numero = num;
return salvar;
}
int *inverterLista(char *texto,char *palavra, int *tam){
int i=0,j=0;
int num=0;
int total;
int atual=1;
int *vetor = (int*) malloc(sizeof(int));
char aux[30];
while(texto[i]!='\0'){
if(texto[i]==palavra[0]){
while(texto[i]!=' ' && texto[i]!='\0'){
aux[j] = texto[i];
i++;
j++;
}
aux[j]='\0';
j=0;
if(comparar(palavra,aux)){
num++;
vetor = realloc(vetor,num*sizeof(int));
vetor[num-1]=atual;
}
}
else{
while(texto[i]!=' '){i++;}
}
atual++;
i++;
}
num++;
vetor = realloc(vetor,num*sizeof(int));
vetor[num-1]=-1;
*tam = num;
return vetor;
}
void imprimir(int *vetor){
int i;
for(i=0;vetor[i]!=-1;i++){
printf("%d ",vetor[i]);
fflush(stdout);
}
}
int main(int argc, char *argv[]){
char frase[1000];
int tamFrase, tamWord;
MPI_Comm parentcomm, intercomm;
MPI_Status st; // estrutura padrão do MPI, não é relevante para esse exemplo mas precisa ser atribuída.
MPI_Init(&argc, &argv);
MPI_Comm_get_parent(&parentcomm); // verifica qual é o comunicador para o processo pai
if(parentcomm == MPI_COMM_NULL){ // se não houver comunicador para o pai, ele é o pai
printf("-----------------\nMaster process.\n-----------------\n"); // exibe que é o processo mestre
fflush(stdout);
Chave *palavras;
int qtde;
//printf("Digite frase: ");
//scanf("%[^\n]",frase);
int siz=0;
FILE *arq = fopen(argv[1], "r");
while(!feof(arq)){
fscanf(arq, "%c", &frase[siz]);
siz++;
}
printf("%s\n", frase);
printf("--------------");
tratarDados(frase);
tamFrase = strlen(frase);
palavras = separar(frase);
Chave *copy = entradasUnicas(copiar(palavras),&qtde);
free(palavras);
int np = qtde; // número de processos que serão criados
printf("\nNumero de processos alocados: %d\n", np);
double start = MPI_Wtime();
// Cria várias instâncias de processos do arquivo invertex.e
// intercomm é o comunicador que o pai utilizará para comunicar-se com os processos filhos.
MPI_Comm_spawn("./invertex.e", MPI_ARGV_NULL, np, MPI_INFO_NULL, 0, MPI_COMM_WORLD, &intercomm, MPI_ERRCODES_IGNORE);
for(int i=0;i<np;i++){
char word[30];
strcpy(word, copy->valor);
tamWord = strlen(word);
printf("\n%s(%d): ",word, tamWord);
fflush(stdout);
MPI_Send(&word, 30, MPI_CHAR,i, 0, intercomm); // passa a palavra
MPI_Send(&tamFrase, 1, MPI_INT, i, 0, intercomm); // passa o tamanho da frase
MPI_Send(&frase, tamFrase, MPI_CHAR, i, 0, intercomm); // passa a frase
int tam, val[30];
MPI_Recv(&tam, 1, MPI_INT, i, 0, intercomm, &st); // recebe o tamanho do vetor
MPI_Recv(&val, tam, MPI_INT, i, 0, intercomm, &st); // recebe o vetor
imprimir(val);
fflush(stdout);
copy = copy->prox;
}
double finish = MPI_Wtime();
printf("\nTempo de execução: %f segundos.\n", finish-start);
} else{ // Caso haja um comunicador para o pai, significa que é um processo filho (escravo)
char word[30];
MPI_Recv(&word, 30, MPI_CHAR, 0,0, parentcomm, &st); // recebe a palavra
MPI_Recv(&tamFrase, 1, MPI_INT, 0, 0, parentcomm, &st); // recebe o tamanho da frase
MPI_Recv(&frase, tamFrase, MPI_CHAR, 0, 0, parentcomm, &st); //recebe a frase
int tam=1;
int *res = inverterLista(frase, word, &tam);
MPI_Send(&tam, 1, MPI_INT, 0, 0, parentcomm); // passa o tamanho do vetor
MPI_Send(res, tam, MPI_INT, 0, 0, parentcomm); // passa o vetor
}
MPI_Finalize();
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.