language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/pid.h>
#include <linux/kthread.h>
#include <linux/kernel.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/printk.h>
#include <linux/jiffies.h>
#include <linux/kmod.h>
#include <linux/fs.h>
#include <linux/init.h>
MODULE_LICENSE("GPL");
struct wait_opts { enum pid_type wo_type; //It is defined in ‘/include/linux/pid.h’.
int wo_flags; //Wait options. (0, WNOHANG, WEXITED, etc.)
struct pid *wo_pid; //Kernel's internal notion of a process identifier. “Find_get_pid()”
struct siginfo __user *wo_info; //Singal information.
int __user *wo_stat; // Child process’s termination status
struct rusage __user *wo_rusage; //Resource usage
wait_queue_t child_wait; //Task wait queue
int notask_error ;};
/* extern functions */
extern long _do_fork(unsigned long clone_flags,
unsigned long stack_start,
unsigned long stack_size,
int __user *parent_tidptr,
int __user *child_tidptr,
unsigned long tls);
extern int do_execve(struct filename *filename,
const char __user *const __user *__argv,
const char __user *const __user *__envp);
extern long do_wait(struct wait_opts *wo);
extern struct filename *getname(const char __user * filename);
/* signal-name transform*/
char* SIG_NAME(int sig)
{
switch (sig)
{
case 1:
return "SIGHUP";
break;
case 2:
return "SIGINT";
break;
case 131:
return "SIGQUIT";
break;
case 132:
return "SIGILL";
break;
case 133:
return "SIGTRAP";
break;
case 134:
return "SIGABRT";
break;
case 135:
return "SIGBUS";
break;
case 136:
return "SIGFPE";
break;
case 9:
return "SIGKILL";
break;
case 139:
return "SIGSEGV";
break;
case 13:
return "SIGPIPE";
break;
case 14:
return "SIGALRM";
break;
case 15:
return "SIGTERM";
break;
case 4991:
return "SIGSTOP";
break;
default:
return "normal";
break;
}
return "ERROR";
}
/* implement wait function*/
void my_wait(pid_t pid, int* status)
{
struct wait_opts wo;
struct pid *wo_pid=NULL;
enum pid_type type;
int aa;
type=PIDTYPE_PID;
wo_pid=find_get_pid(pid);
wo.wo_type=type;
wo.wo_pid=wo_pid;
wo.wo_flags= WUNTRACED | WEXITED;
wo.wo_info=NULL;
wo.wo_stat=(int __user*)status;
wo.wo_rusage=NULL;
aa=do_wait(&wo);
put_pid(wo_pid);// decrease the count and free memory
}
/* implement exec function*/
void my_exec(void)
{
int result;
/* executable path*/
const char path[]= "/home/zz/Desktop/source/program2/normal";
const char *const argv[]={path,NULL,NULL};
const char *const envp[]={"HOME=/","PATH=/sbin:/user/sbin:/bin:/usr/bin",NULL};
struct filename * my_filename;
printk("[program2] : Child process pid = %d\n",(int)current->pid);
printk("[program2] : Child process\n");
my_filename=getname(path);
result=do_execve(my_filename,argv,envp);
/* if exec success*/
if(!result)
return;
/* if exec failure*/
do_exit(result);
}
/* implement fork function*/
int my_fork(void *argc){
int pid;
int status=0;
int i;
int sig;
char* sigName;
struct k_sigaction *k_action;
printk("[program2] : module_init kthread start");
/* set default sigaction for current process*/
k_action = ¤t->sighand->action[0];
for(i=0;i<_NSIG;i++){
k_action->sa.sa_handler = SIG_DFL;
k_action->sa.sa_flags = 0;
k_action->sa.sa_restorer = NULL;
sigemptyset(&k_action->sa.sa_mask);
k_action++;
}
/* fork a process using do_fork */
/* Print out the process id for both parent and child process*/
printk("[program2] : Parent process pid = %d\n",(int)current->pid);
if((pid=_do_fork(SIGCHLD,(unsigned long)&my_exec,0,NULL,NULL,0))==0) // child process
{
printk("[program2] : exec error");
do_exit(0);
}
/* wait until child process terminates */
my_wait(pid,&status);
sig=status;
sigName=SIG_NAME(sig);
if(sigName[0]!='n')
printk("[program2] : get %s signal\n",sigName);
else
printk("[program2] : normal termination\n");
printk("[program2] : child process terminated");
printk("[program2] : The return signal is %d",sig);
do_exit(0);
}
static int __init program2_init(void){
struct task_struct *task;
printk("[program2] : Module_init\n");
/* create a kernel thread to run my_fork */
printk("[program2] : Module_init create kthread start\n");
task=kthread_create(&my_fork,NULL,"MyThread");
if(!IS_ERR(task)){
wake_up_process(task);
}
return 0;
}
static void __exit program2_exit(void){
printk("[program2] : Module_exit\n");
}
module_init(program2_init);
module_exit(program2_exit);
|
C
|
#ifndef __FUNCTIONS_H__
#define __FUNCTIONS_H__
struct functions
{
bool sw1 = 0, sw2 = 0, sw3 = 0, sw4 = 0,
sw5 = 0, sw6 = 0, sw7 = 0, not1 = 0,
not2 = 0, not3 = 0, not4 = 0, and1 = 0,
and2 = 0, and3 = 0, and4 = 0, or1 = 0,
or2 = 0, or3 = 0, or4 = 0, or5 = 0,
moved = 0, moved1 = 0, moved2 = 0, moved3 = 0;
bool NOT(bool _sw)
{
if (_sw == false)
return true;
else
return false;
}
bool AND(bool _sw1, bool _sw2)
{
if (_sw1 == true && _sw2 == true)
return true;
else
return false;
}
bool OR(bool _sw1, bool _sw2)
{
if (_sw1 == true || _sw2 == true)
return true;
else
return false;
}
};
struct IntCoin
{
int IntCoins = 0;
};
#endif
|
C
|
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() functions
return subSum(root,0);
}
private:
int subSum(TreeNode*root,int value)
{
if(root==NULL)
return value;
else if(root->right&&root->left)
return subSum(root->left,10*value+root->val)+subSum(root->right,10*value+root->val);
else if(root->right)
return subSum(root->right,10*value+root->val);
else if(root->left)
return subSum(root->left,10*value+root->val);
else
return value*10+root->val;
}
};
|
C
|
// BOA-TEST 1
// simple malloc
#include <stdlib.h>
int main() {
char *p, *q, *r;
int i = 4;
p = (char*)malloc(i);
p[4] = 'a';
q = (char*)malloc(i + 1);
q[4] = 'b';
r = (char*)malloc(i - 1);
r[4] = 'c';
return 0;
}
|
C
|
//Q 3. write a program to send a message "end term practical" from parent process to child process.
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
int fd[2],n;
char buffer[100];
pid_t p;
pipe(fd);
p=fork();
if(p>0)
{
close(fd[0]);
printf("Passing value to child\n");
write(fd[1],"End term practical\n",20);
sleep(1);
}
else
{
close(fd[1]);
n=read(fd[0],buffer,100);
write(1,buffer,n);
}
}
|
C
|
#include "config.h"
#include <avr/io.h>
#include <avr/interrupt.h>
#include "spi.h"
/*Initalize SPI on PORTB
Parameters:
uint8_t master: if true, initalizes in master mode. Otherwise initalizes in slave mode
*/
void SPI_init(uint8_t master){
/*Set the GPIO input/outputs*/
if(master){
DDRB = (1<<PB2) | (1<<PB1);
} else {
DDRB = (1<<PB3);
}
//Enable SPI. SCK = FCPU/128
SPCR = (1<<SPE) | (1<<SPR1) | (1<<SPR0);
if(master){
SPCR |= (1<<MSTR); //Enable master mode
}
}
/*Writes one byte to the SPI bus
Parameters:
uint8_t b: the byte to write
*/
void SPI_write(uint8_t b){
SPDR = b;
while(!(SPSR & (1<<SPIF))); //Wait for write to complete
}
/*Reads one byte from the SPI bus and returns it*/
uint8_t SPI_read(){
while(!(SPSR & (1<<SPIF))); //Wait for receive to complete
return SPDR;
}
/*Simultaniously reads and writes one byte on the SPI bus.
The received byte is returned
Parameters:
uint8_t b: the byte to transmit
*/
uint8_t SPI_rw(uint8_t b){
SPDR = b;
while(!(SPSR & (1<<SPIF))); //Wait for transaction to complete
return SPDR;
}
|
C
|
#include<stdio.h>
int main()
{
char arr[8][8];
int c=0;
int len;
scanf("%d",&len);
char temp[len];
char temp2;
gets(temp);
while(c<8)
{
gets(temp2);
arr=temp2;
}
puts(arr);
return 0;
}
|
C
|
#include "io_multiplexer.h"
#include "caps_transmitter.h"
#include "demultiplexer.h"
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
int ioToCapsA[2], ioToCapsB1[2], capsB1ToCapsB2[2], capsAToDemux[2], capsB2ToDemux[2], back[2], r;
if (pipe(ioToCapsA) || pipe(ioToCapsB1) || pipe(capsB1ToCapsB2) || pipe(capsAToDemux) || pipe(capsB2ToDemux) || pipe(back))
{
perror("pipe");
return -1;
}
if (fork() == 0) //child to io
{
close(ioToCapsA[0]);
close(ioToCapsB1[0]);
close(back[1]);
r = io(back[0], ioToCapsA[1], ioToCapsB1[1]);
close(back[0]);
close(ioToCapsB1[1]);
close(ioToCapsA[1]);
return r;
}
//parent
close(ioToCapsB1[1]); //close writing signal
close(ioToCapsA[1]);
if(fork() == 0) //child caps A
{
close(ioToCapsA[1]);
close(capsAToDemux[0]);
r = caps(ioToCapsA[0], capsAToDemux[1], "A");
close(ioToCapsA[0]);
close(capsAToDemux[1]);
return r;
}
if (fork() == 0) //child caps b1
{
if (fork() == 0) //child caps b2
{
close(capsB1ToCapsB2[1]);
close(capsB2ToDemux[0]);
r = caps(capsB1ToCapsB2[0], capsB2ToDemux[1], "B2");
close(capsB1ToCapsB2[0]);
close(capsB2ToDemux[1]);
return r;
}
close(ioToCapsB1[1]);
close(capsB1ToCapsB2[0]);
r = caps(ioToCapsB1[0], capsB1ToCapsB2[1], "B1");
close(ioToCapsB1[0]);
close(capsB1ToCapsB2[1]);
wait(NULL);
return r;
}
//parent demux
close(capsB1ToCapsB2[1]); //close writing signal
close(capsAToDemux[1]);
close(capsB2ToDemux[1]);
close(back[0]);
r = demux(capsAToDemux[0], capsB2ToDemux[0], back[1]);
close(capsAToDemux[0]);
close(capsB2ToDemux[0]);
close(back[1]);
wait(NULL);
wait(NULL);
wait(NULL);
return r;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* dsp_and.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: oevtushe <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/18 14:39:30 by oevtushe #+# #+# */
/* Updated: 2018/09/22 18:39:34 by oevtushe ### ########.fr */
/* */
/* ************************************************************************** */
#include "op.h"
void print_and(t_carriage *carriage, t_vm *vm)
{
print_pnum(carriage->num_car);
printf("and %d %d r%hhu\n", vm->args.arg1.value, vm->args.arg2.value,
(unsigned char)vm->args.arg3.readed);
}
static void do_and(t_carriage *carriage, t_vm *vm)
{
unsigned int and;
init_args(carriage, vm->map, &vm->args);
and = vm->args.arg1.value & vm->args.arg2.value;
carriage->reg[vm->args.arg3.readed] = and;
carriage->carry = and ? 0 : 1;
}
/*
** name: and
** args: T_REG | T_DIR | T_IND, T_REG | T_IND | T_DIR, T_REG
** opcode: 6
** cycles: 6
** ACB: yes
** modifies carry
**
** Description:
** Apply an AND operation over the first two arguments and
** store the resultin a registry, which is the third argument
*/
int dsp_and(t_carriage *carriage, t_vm *vm)
{
unsigned char acb;
int res;
res = 0;
acb = vm->map[(carriage->pc + 1) % MEM_SIZE];
ft_memset(&vm->args, 0, sizeof(t_args));
vm->args.shift = 1;
if ((acb & ARG_MASK1) || (acb & ARG_MASK2) || (acb & ARG_MASK3))
{
read_args_from_map(carriage->pc, vm->map, &vm->args,
(t_reader){read_int_from_map, read_short_from_map});
if (vm->args.arg1.type == T_IND)
vm->args.arg1.readed %= IDX_MOD;
if (vm->args.arg2.type == T_IND)
vm->args.arg2.readed %= IDX_MOD;
if (validate_args(&vm->args, &vm->ops[5].pargs))
{
do_and(carriage, vm);
res = 1;
}
vm->args.shift += vm->args.arg1.size + vm->args.arg2.size
+ vm->args.arg3.size;
}
return (res);
}
|
C
|
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include "helpers.h"
#include <math.h>
#include <ctype.h>
#include <cs50.h>
#include "bmp.h"
int main(int argc, char *argv[])
{
// Define allowable filters
char *filters = "bgrs";
// Get filter flag and check validity
char filter = getopt(argc, argv, filters);
if (filter == '?')
{
fprintf(stderr, "Invalid filter.\n");
return 1;
}
// Ensure only one filter
if (getopt(argc, argv, filters) != -1)
{
fprintf(stderr, "Only one filter allowed.\n");
return 2;
}
// Ensure proper usage
if (argc != optind + 2)
{
fprintf(stderr, "Usage: filter [flag] infile outfile\n");
return 3;
}
// Remember filenames
char *infile = argv[optind];
char *outfile = argv[optind + 1];
// Open input file
FILE *inptr = fopen(infile, "r");
if (inptr == NULL)
{
fprintf(stderr, "Could not open %s.\n", infile);
return 4;
}
// Open output file
FILE *outptr = fopen(outfile, "w");
if (outptr == NULL)
{
fclose(inptr);
fprintf(stderr, "Could not create %s.\n", outfile);
return 5;
}
// Read infile's BITMAPFILEHEADER
BITMAPFILEHEADER bf;
fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);
// Read infile's BITMAPINFOHEADER
BITMAPINFOHEADER bi;
fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);
// Ensure infile is (likely) a 24-bit uncompressed BMP 4.0
if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
bi.biBitCount != 24 || bi.biCompression != 0)
{
fclose(outptr);
fclose(inptr);
fprintf(stderr, "Unsupported file format.\n");
return 6;
}
int height = abs(bi.biHeight);
int width = bi.biWidth;
// Allocate memory for image
RGBTRIPLE(*image)[width] = calloc(height, width * sizeof(RGBTRIPLE));
if (image == NULL)
{
fprintf(stderr, "Not enough memory to store image.\n");
fclose(outptr);
fclose(inptr);
return 7;
}
// Determine padding for scanlines
int padding = (4 - (width * sizeof(RGBTRIPLE)) % 4) % 4;
// Iterate over infile's scanlines
for (int i = 0; i < height; i++)
{
// Read row into pixel array
fread(image[i], sizeof(RGBTRIPLE), width, inptr);
// Skip over padding
fseek(inptr, padding, SEEK_CUR);
}
// Filter image
switch (filter)
{
// Blur
case 'b':
blur(height, width, image);
break;
// Grayscale
case 'g':
grayscale(height, width, image);
break;
// Reflection
case 'r':
reflect(height, width, image);
break;
// Sepia
case 's':
sepia(height, width, image);
break;
}
// Write outfile's BITMAPFILEHEADER
fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr);
// Write outfile's BITMAPINFOHEADER
fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, outptr);
// Write new pixels to outfile
for (int i = 0; i < height; i++)
{
// Write row to outfile
fwrite(image[i], sizeof(RGBTRIPLE), width, outptr);
// Write padding at end of row
for (int k = 0; k < padding; k++)
{
fputc(0x00, outptr);
}
}
// Free memory for image
free(image);
// Close infile
fclose(inptr);
// Close outfile
fclose(outptr);
return 0;
}
// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
//get each pixels 3 color values
RGBTRIPLE color = image[i][j];
// add all 3 color values together then divide them to find average
int average = round((color.rgbtBlue + color.rgbtGreen + color.rgbtRed) / 3.0);
// initalize the value 255 if average is over 255
if (average > 255)
{
average = 255;
}
//update each array in RGBTRIPLE with the average
image[i][j].rgbtBlue = image[i][j].rgbtGreen = image[i][j].rgbtRed = average;
}
}
return; //RGBTRIPLE updated values
}
// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
RGBTRIPLE color = image[i][j];
int originalRed = color.rgbtRed;
int originalGreen = color.rgbtGreen;
int originalBlue = color.rgbtBlue;
//makes sepia color tone
int sepiaRed = round(.393 * originalRed + .769 * originalGreen + .189 * originalBlue);
int sepiaGreen = round(.349 * originalRed + .686 * originalGreen + .168 * originalBlue);
int sepiaBlue = round(.272 * originalRed + .534 * originalGreen + .131 * originalBlue);
//caps values at 255
if (sepiaRed > 255)
{
sepiaRed = 255;
}
if (sepiaGreen > 255)
{
sepiaGreen = 255;
}
if (sepiaBlue > 255)
{
sepiaBlue = 255;
}
//initialize the new values to its respected value
image[i][j].rgbtBlue = sepiaBlue;
image[i][j].rgbtGreen = sepiaGreen;
image[i][j].rgbtRed = sepiaRed;
}
}
return;
}
//putting the values in color 1 into a temp variable so that i can initalize color 2 into 1
void swap(RGBTRIPLE *color1, RGBTRIPLE *color2)
{
RGBTRIPLE temp = *color1;
*color1 = *color2;
*color2 = temp;
}
// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width / 2; j++)
{
swap(&image[i][j], &image[i][width - 1 - j]);
}
}
return;
}
RGBTRIPLE blur_pixel(int i, int j, int height, int width, RGBTRIPLE image[height][width])
{
int pixel_counter = 0;
int blue = 0;
int red = 0;
int green = 0;
// loop to get all surrounding pixels
for (int di = -1; di < 2; di++)
{
for (int dj = -1; dj < 2; dj++)
{
//make a new i and j so that you can make the if statement for the color calculations
int new_i = i + di;
int new_j = j + dj;
if (new_i >= 0 && new_i < height && new_j >= 0 && new_j < width)
{
//increment a counter based off of the amount of vailid pixels
//add up all the color channels for each pixel
blue += image[new_i][new_j].rgbtBlue;
red += image[new_i][new_j].rgbtRed;
green += image[new_i][new_j].rgbtGreen;
}
}
}
RGBTRIPLE new_pixel;
new_pixel.rgbtBlue = round((float)blue / pixel_counter);
new_pixel.rgbtRed = round((float)red / pixel_counter);
new_pixel.rgbtGreen = round((float)green / pixel_counter);
return new_pixel;
}
// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
RGBTRIPLE new_image[height][width];
//interate over image
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
new_image[i][j] = blur_pixel(i, j, height, width, image);
}
}
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
image[i][j] = new_image[i][j];
}
}
return;
}
|
C
|
//BINARY TREE data structure
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
char *question; //question, this is not a string literal
struct node *no; //no
struct node *yes; //yes
}node;
//take the question string
int yes_no(char *question)
{
char ans[3];
printf("please answer the following question(y/n): %s\n", question);
fgets(ans, 3, stdin);
return ans[0] == 'y';
}
node* create(char *info) //take question
{
node *i = malloc(sizeof(node));
i->question = strdup(info);
i->no = NULL;
i->yes = NULL;
return i;
}
void release(node *rel) //release the node
{
if(rel){
if(rel->question)
free(rel->question);
if(rel->no)
free(rel->no);
if(rel->yes)
free(rel->yes);
}
free(rel); //don't forget to release rel itself
}
//basic structure defined
int main() {
char question[80];
char suspect[20];
node *start_node = create("Does suspect have a mustache");
start_node->no = create("Loretta Barnsworth");
start_node->yes = create("Vinny the Spoon");
node *current;
do {
current = start_node;
while (1) {
if (yes_no(current->question)) {
if (current->yes) { //run through the suspect list
current = current->yes;
}
else { //if there is no continuation of suspect list, then suspect is identified
printf("SUSPECT IDENTIFIED\n");
break;
}
}
else if (current->no) {
current = current->no;
}
//if yes_no is not identified
else {
/* Make the yes-node the new suspect name */
printf("Who's the suspect? ");
fgets(suspect, 20, stdin);
node *yes_node = create(suspect);
current->yes = yes_node;
/* Make the no-node a copy of this question */
node *no_node = create(current->question);
current->no = no_node;
/* Then replace this question with the new question */
printf("Give me a question that is TRUE for %s but not for %s? ", suspect, current->question);
fgets(question, 80, stdin);
//free(current->question);
current->question = strdup(question);
break;
}
}
}
while(yes_no("Run again"));
release(start_node);
//release(current);
return 0;
}
//if suspect y, else if suspect n, else new suspect ... is the process
//the program builds a tree of suspects
// - records data using a binary tree
// allows each piece of data to conect to two other pieces of data
//HOW TO TRACK MEMORY LEAKS?
//one tool used on the LINUX operating system is called
// - valgrind //only works in LINUX
// it monitor the pieces of data that are allocated space on the heap
// works by creating its own fake version of malloc()
// when the program wants to allocate some heap memory
// valgrind will intercept the call & runs its own version
// will take note of which piece of code is calling it and which peice of meomory is allocated
// when ends, will report data left on the heap & where the code is created
//to maximize valgrind
//make sure the executable contains debug information
// - debug information
// is the extra data that gets packed into the xecutable when it is compiled
// things like the line number in the source file that a particular piece of code was compiled from
//if the debug info is present
//valgrind will be able to provide more details about the source of memory leak
//to add debug info into the executable
//recompile the source with the -g switch
// --> gcc -g spies.c -o spies
// tells the compiler to record the line numbers against the code it compiles
// --> valgrind --leak-check=full ./try
|
C
|
/*
*
* VerdictVector.cpp contains implementation of Vector operations
*
* Copyright (C) 2003 Sandia National Laboratories <cubit@sandia.gov>
*
* This file is part of VERDICT
*
* This copy of VERDICT is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* VERDICT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <math.h>
#include "verdict.h"
#include "VerdictVector.h"
#include <float.h>
const double TWO_VERDICT_PI = 2.0 * VERDICT_PI;
VerdictVector &VerdictVector::length(const double new_length)
{
double length = this->length();
xVal *= new_length / length;
yVal *= new_length / length;
zVal *= new_length / length;
return *this;
}
double VerdictVector::distance_between(const VerdictVector& test_vector)
{
double x = xVal - test_vector.x();
double y = yVal - test_vector.y();
double z = zVal - test_vector.z();
return(sqrt(x*x + y*y + z*z));
}
/*
void VerdictVector::print_me()
{
PRINT_INFO("X: %f\n",xVal);
PRINT_INFO("Y: %f\n",yVal);
PRINT_INFO("Z: %f\n",zVal);
}
*/
double VerdictVector::interior_angle(const VerdictVector &otherVector)
{
double cosAngle=0., angleRad=0., len1=0., len2=0.;
if (((len1 = this->length()) > 0) && ((len2 = otherVector.length()) > 0))
cosAngle = (*this % otherVector)/(len1 * len2);
else
{
assert(len1 > 0);
assert(len2 > 0);
}
if ((cosAngle > 1.0) && (cosAngle < 1.0001))
{
cosAngle = 1.0;
angleRad = acos(cosAngle);
}
else if (cosAngle < -1.0 && cosAngle > -1.0001)
{
cosAngle = -1.0;
angleRad = acos(cosAngle);
}
else if (cosAngle >= -1.0 && cosAngle <= 1.0)
angleRad = acos(cosAngle);
else
{
assert(cosAngle < 1.0001 && cosAngle > -1.0001);
}
return( (angleRad * 180.) / VERDICT_PI );
}
// Interpolate between two vectors.
// Returns (1-param)*v1 + param*v2
VerdictVector interpolate(const double param, const VerdictVector &v1,
const VerdictVector &v2)
{
VerdictVector temp = (1.0 - param) * v1;
temp += param * v2;
return temp;
}
void VerdictVector::xy_to_rtheta()
{
//careful about overwriting
double r_ = length();
double theta_ = atan2( y(), x() );
if (theta_ < 0.0)
theta_ += TWO_VERDICT_PI;
r( r_ );
theta( theta_ );
}
void VerdictVector::rtheta_to_xy()
{
//careful about overwriting
double x_ = r() * cos( theta() );
double y_ = r() * sin( theta() );
x( x_ );
y( y_ );
}
void VerdictVector::rotate(double angle, double )
{
xy_to_rtheta();
theta() += angle;
rtheta_to_xy();
}
void VerdictVector::blow_out(double gamma, double rmin)
{
// if gamma == 1, then
// map on a circle : r'^2 = sqrt( 1 - (1-r)^2 )
// if gamma ==0, then map back to itself
// in between, linearly interpolate
xy_to_rtheta();
// r() = sqrt( (2. - r()) * r() ) * gamma + r() * (1-gamma);
assert(gamma > 0.0);
// the following limits should really be roundoff-based
if (r() > rmin*1.001 && r() < 1.001) {
r() = rmin + pow(r(), gamma) * (1.0 - rmin);
}
rtheta_to_xy();
}
void VerdictVector::reflect_about_xaxis(double, double )
{
yVal = -yVal;
}
void VerdictVector::scale_angle(double gamma, double )
{
const double r_factor = 0.3;
const double theta_factor = 0.6;
xy_to_rtheta();
// if neary 2pi, treat as zero
// some near zero stuff strays due to roundoff
if (theta() > TWO_VERDICT_PI - 0.02)
theta() = 0;
// the above screws up on big sheets - need to overhaul at the sheet level
if ( gamma < 1 )
{
//squeeze together points of short radius so that
//long chords won't cross them
theta() += (VERDICT_PI-theta())*(1-gamma)*theta_factor*(1-r());
//push away from center of circle, again so long chords won't cross
r( (r_factor + r()) / (1 + r_factor) );
//scale angle by gamma
theta() *= gamma;
}
else
{
//scale angle by gamma, making sure points nearly 2pi are treated as zero
double new_theta = theta() * gamma;
if ( new_theta < 2.5 * VERDICT_PI || r() < 0.2)
theta( new_theta );
}
rtheta_to_xy();
}
double VerdictVector::vector_angle_quick(const VerdictVector& vec1,
const VerdictVector& vec2)
{
//- compute the angle between two vectors in the plane defined by this vector
// build yAxis and xAxis such that xAxis is the projection of
// vec1 onto the normal plane of this vector
// NOTE: vec1 and vec2 are Vectors from the vertex of the angle along
// the two sides of the angle.
// The angle returned is the right-handed angle around this vector
// from vec1 to vec2.
// NOTE: vector_angle_quick gives exactly the same answer as vector_angle below
// providing this vector is normalized. It does so with two fewer
// cross-product evaluations and two fewer vector normalizations.
// This can be a substantial time savings if the function is called
// a significant number of times (e.g Hexer) ... (jrh 11/28/94)
// NOTE: vector_angle() is much more robust. Do not use vector_angle_quick()
// unless you are very sure of the safety of your input vectors.
VerdictVector ry = (*this) * vec1;
VerdictVector rx = ry * (*this);
double x = vec2 % rx;
double y = vec2 % ry;
double angle;
assert(x != 0.0 || y != 0.0);
angle = atan2(y, x);
if (angle < 0.0)
{
angle += TWO_VERDICT_PI;
}
return angle;
}
VerdictVector vectorRotate(const double angle,
const VerdictVector &normalAxis,
const VerdictVector &referenceAxis)
{
// A new coordinate system is created with the xy plane corresponding
// to the plane normal to the normal axis, and the x axis corresponding to
// the projection of the reference axis onto the normal plane. The normal
// plane is the tangent plane at the root point. A unit vector is
// constructed along the local x axis and then rotated by the given
// ccw angle to form the new point. The new point, then is a unit
// distance from the global origin in the tangent plane.
double x, y;
// project a unit distance from root along reference axis
VerdictVector yAxis = normalAxis * referenceAxis;
VerdictVector xAxis = yAxis * normalAxis;
yAxis.normalize();
xAxis.normalize();
x = cos(angle);
y = sin(angle);
xAxis *= x;
yAxis *= y;
return VerdictVector(xAxis + yAxis);
}
double VerdictVector::vector_angle(const VerdictVector &vector1,
const VerdictVector &vector2) const
{
// This routine does not assume that any of the input vectors are of unit
// length. This routine does not normalize the input vectors.
// Special cases:
// If the normal vector is zero length:
// If a new one can be computed from vectors 1 & 2:
// the normal is replaced with the vector cross product
// else the two vectors are colinear and zero or 2PI is returned.
// If the normal is colinear with either (or both) vectors
// a new one is computed with the cross products
// (and checked again).
// Check for zero length normal vector
VerdictVector normal = *this;
double normal_lensq = normal.length_squared();
double len_tol = 0.0000001;
if( normal_lensq <= len_tol )
{
// null normal - make it the normal to the plane defined by vector1
// and vector2. If still null, the vectors are colinear so check
// for zero or 180 angle.
normal = vector1 * vector2;
normal_lensq = normal.length_squared();
if( normal_lensq <= len_tol )
{
double cosine = vector1 % vector2;
if( cosine > 0.0 ) return 0.0;
else return VERDICT_PI;
}
}
//Trap for normal vector colinear to one of the other vectors. If so,
//use a normal defined by the two vectors.
double dot_tol = 0.985;
double dot = vector1 % normal;
if( dot * dot >= vector1.length_squared() * normal_lensq * dot_tol )
{
normal = vector1 * vector2;
normal_lensq = normal.length_squared();
//Still problems if all three vectors were colinear
if( normal_lensq <= len_tol )
{
double cosine = vector1 % vector2;
if( cosine >= 0.0 ) return 0.0;
else return VERDICT_PI;
}
}
else
{
//The normal and vector1 are not colinear, now check for vector2
dot = vector2 % normal;
if( dot * dot >= vector2.length_squared() * normal_lensq * dot_tol )
{
normal = vector1 * vector2;
}
}
// Assume a plane such that the normal vector is the plane's normal.
// Create yAxis perpendicular to both the normal and vector1. yAxis is
// now in the plane. Create xAxis as the perpendicular to both yAxis and
// the normal. xAxis is in the plane and is the projection of vector1
// into the plane.
normal.normalize();
VerdictVector yAxis = normal;
yAxis *= vector1;
double y = vector2 % yAxis;
// yAxis memory slot will now be used for xAxis
yAxis *= normal;
double x = vector2 % yAxis;
// assert(x != 0.0 || y != 0.0);
if( x == 0.0 && y == 0.0 )
{
return 0.0;
}
double angle = atan2(y, x);
if (angle < 0.0)
{
angle += TWO_VERDICT_PI;
}
return angle;
}
bool VerdictVector::within_tolerance( const VerdictVector &vectorPtr2,
double tolerance) const
{
if (( fabs (this->x() - vectorPtr2.x()) < tolerance) &&
( fabs (this->y() - vectorPtr2.y()) < tolerance) &&
( fabs (this->z() - vectorPtr2.z()) < tolerance)
)
{
return true;
}
return false;
}
void VerdictVector::orthogonal_vectors( VerdictVector &vector2,
VerdictVector &vector3 )
{
double x[3];
unsigned short i=0;
unsigned short imin=0;
double rmin = 1.0E20;
unsigned short iperm1[3];
unsigned short iperm2[3];
unsigned short cont_flag = 1;
double vec1[3], vec2[3];
double rmag;
// Copy the input vector and normalize it
VerdictVector vector1 = *this;
vector1.normalize();
// Initialize perm flags
iperm1[0] = 1; iperm1[1] = 2; iperm1[2] = 0;
iperm2[0] = 2; iperm2[1] = 0; iperm2[2] = 1;
// Get into the array format we can work with
vector1.get_xyz( vec1 );
while (i<3 && cont_flag )
{
if (fabs(vec1[i]) < 1e-6)
{
vec2[i] = 1.0;
vec2[iperm1[i]] = 0.0;
vec2[iperm2[i]] = 0.0;
cont_flag = 0;
}
if (fabs(vec1[i]) < rmin)
{
imin = i;
rmin = fabs(vec1[i]);
}
++i;
}
if (cont_flag)
{
x[imin] = 1.0;
x[iperm1[imin]] = 0.0;
x[iperm2[imin]] = 0.0;
// Determine cross product
vec2[0] = vec1[1] * x[2] - vec1[2] * x[1];
vec2[1] = vec1[2] * x[0] - vec1[0] * x[2];
vec2[2] = vec1[0] * x[1] - vec1[1] * x[0];
// Unitize
rmag = sqrt(vec2[0]*vec2[0] + vec2[1]*vec2[1] + vec2[2]*vec2[2]);
vec2[0] /= rmag;
vec2[1] /= rmag;
vec2[2] /= rmag;
}
// Copy 1st orthogonal vector into VerdictVector vector2
vector2.set( vec2 );
// Cross vectors to determine last orthogonal vector
vector3 = vector1 * vector2;
return;
}
//- Find next point from this point using a direction and distance
void VerdictVector::next_point( const VerdictVector &direction,
double distance, VerdictVector& out_point )
{
VerdictVector my_direction = direction;
my_direction.normalize();
// Determine next point in space
out_point.x( xVal + (distance * my_direction.x()) );
out_point.y( yVal + (distance * my_direction.y()) );
out_point.z( zVal + (distance * my_direction.z()) );
return;
}
VerdictVector::VerdictVector(const double xyz[3])
: xVal(xyz[0]), yVal(xyz[1]), zVal(xyz[2])
{}
|
C
|
#include<stdio.h>
void main()
{
char a ;
printf("Cienijamais lietotaj! Ludzu ievadit vienu burtu:");
scanf("%c", &a);
printf("Cienijamais, lietotaj! Tu esi ievadijis simbolu %c\n", a);
printf("Cienijamais, lietotaj! Tu esi ievadijis simbolu, kura dec kods ir: %d\n", a);
printf("Cienijamais, lietotaj! Tu esi ievadijis simbolu, kura hex kods ir: 0x%x\n", a);
printf("Cienijamais, lietotaj! Tu esi ievadijis simbolu, kura oct kods ir: %o\n", a);
printf("P.s. ka reals skaitlis: %f\n", a);
int b ;
printf("Cienijamais lietotaj! Ludzu ievadit vienu burtu!\n");
scanf("%d", &b);
printf("Cienijamais, lietotaj! Tu esi ievadijis simbolu %c\n", b);
printf("Cienijamais, lietotaj! Tu esi ievadijis simbolu, kura dec kods ir: %d\n", b);
printf("Cienijamais, lietotaj! Tu esi ievadijis simbolu, kura hex kods ir: 0x%x\n",b);
printf("Cienijamais, lietotaj! Tu esi ievadijis simbolu, kura oct kods ir: %o\n", b);
printf("P.s. ka reals skaitlis: %f\n", b);
double c ;
printf("Cienijamais lietotaj! Ludzu ievadit vienu burtu!\n");
scanf("%lf", &c);
printf("Cienijamais, lietotaj! Tu esi ievadijis simbolu %c\n", c);
printf("Cienijamais, lietotaj! Tu esi ievadijis simbolu, kura dec kods ir: %d\n", c);
printf("Cienijamais, lietotaj! Tu esi ievadijis simbolu, kura hex kods ir: ox%x\n", c);
printf("Cienijamais, lietotaj! Tu esi ievadijis simbolu, kura oct kods ir: %o\n", c);
printf("P.s. ka reals skaitlis: %f\n", c);
}
|
C
|
//****************** ( Animation Construction Kit 3D ) **********************
// Ray Casting Routines
// CopyRight (c) 1993 Author: Lary Myers
//***************************************************************************
#include <stdlib.h>
#include <stdio.h>
//#include <dos.h>
//#include <mem.h>
//#include <io.h>
//#include <fcntl.h>
#include <time.h>
#include <string.h>
//#include <sys\stat.h>
#include "ACK3D.H"
#include "ACKENG.H"
#include "ACKEXT.H"
#ifndef UINT
#define UINT unsigned int
#endif
extern short ViewAngle;
//**************************************************************************
//
//**************************************************************************
short ObjectExist(UCHAR onum)
{
short i;
short result = 0;
if (!FoundObjectCount)
return(result);
for (i = 0; i < FoundObjectCount; i++)
{
if (ObjectsSeen[i] == onum)
return(1);
}
return(result);
}
extern int32_t x_xPos,x_yPos,x_xNext,x_yNext;
extern int32_t y_xPos,y_yPos,y_xNext,y_yNext;
//*************************************************************************
//
//*************************************************************************
void xRaySetup(void)
{
x_yNext = yNextTable[ViewAngle]; // PreCalc'd value of BITMAP_WIDTH * Tan(angle)
if (ViewAngle > INT_ANGLE_270 || ViewAngle < INT_ANGLE_90)
{
x_xPos = xBegGlobal + BITMAP_WIDTH; // Looking to the right
x_xNext = BITMAP_WIDTH; // Positive direction
}
else
{
x_xPos = xBegGlobal; // Looking to the left
x_xNext = -BITMAP_WIDTH; // Negative direction
x_yNext = -x_yNext;
}
// Calculate the Y coordinate for the current square
x_yPos = (((int32_t)x_xPos - (int32_t)xPglobal) * LongTanTable[ViewAngle]) + yPglobalHI;
}
//**************************************************************************
//
//**************************************************************************
UINT xRayCast(void)
{
UINT Color;
// short i,j,mx,my;
// short TablePosn;
short MapPosn;
// short xBeg;
// short BitmapColumn;
// short xCenter,yCenter,xAdj;
// short ObjPosn;
// short oBegX,oBegY;
int32_t xd,yd,sy;
int32_t ObjDist;
while (1)
{
if (x_xPos < 0 || x_xPos > GRID_XMAX ||
x_yPos < 0 || x_yPos > GRID_YMAXLONG)
break;
//************* Fixed point Y/64 * 64 X / 64 **********
MapPosn = ((x_yPos >> FP_SHIFT) & 0xFFC0) + (x_xPos >> 6);
if ((Color = ObjGrid[MapPosn]) != 0)
{
Color &= 0xFF; //MEH RGH. NOT 0x7F like he had! That only allows 127 objects!!!
if (!ObjectExist(Color))
ObjectsSeen[FoundObjectCount++] = Color;
}
// Check to see if a wall is being struck by the ray
if ((Color = xGridGlobal[MapPosn]) != 0)
{
xMapPosn = MapPosn; // Hold onto the map location
iLastX = x_xPos;
LastY1 = x_yPos;
if ((Color & (DOOR_TYPE_SLIDE+DOOR_TYPE_SPLIT)))// Is this a door? //MEH NOT ((Color & 0xFF) == DOOR_XCODE) as he had before!
{
yd = ((x_yPos >> FP_SHIFT) & GRID_MASK); // Get the left side
xd = yd + BITMAP_WIDTH; // And the right side
ObjDist = (x_yPos + (x_yNext >> 1)) >> FP_SHIFT; // Calc door distance
if (ObjDist < yd || ObjDist > xd) // Is door visible?
{
x_xPos += x_xNext; // Nope, continue casting
x_yPos += x_yNext; // the ray as before
continue;
}
LastY1 = x_yPos + (x_yNext >> 1); // Adjust the X,Y values so
iLastX += (x_xNext >> 1); // the door is halfway in sq.
}
if (Color & DOOR_TYPE_SECRET)
{
if (xSecretColumn != 0)
{
sy = xSecretColumn * LongTanTable[ViewAngle];
ObjDist = (x_yPos + sy) >> FP_SHIFT;
yd = ((x_yPos >> FP_SHIFT) & GRID_MASK); // Get the left side
xd = yd + BITMAP_WIDTH; // And the right side
if (ObjDist < yd || ObjDist > xd) // Is door visible?
{
x_xPos += x_xNext; // Nope, continue casting
x_yPos += x_yNext; // the ray as before
continue;
}
LastY1 = x_yPos + sy;
iLastX += xSecretColumn;
}
}
return(Color);
}
x_xPos += x_xNext; // Next X coordinate (fixed at 64 or -64)
x_yPos += x_yNext; // Next calculated Y coord for a delta of X
}
return(0); // Return that no wall was found
}
//*************************************************************************
//
//*************************************************************************
UINT OldxRay(void)
{
UINT Color;
// short i,j,mx,my;
// short TablePosn;
short MapPosn;
// short xBeg;
int32_t xPos,xNext;
// short BitmapColumn;
// short xCenter,yCenter,xAdj;
// short ObjPosn;
// short oBegX,oBegY;
int32_t yPos;
int32_t yNext;
int32_t xd,yd,sy;
int32_t ObjDist;
yNext = yNextTable[ViewAngle]; // PreCalc'd value of BITMAP_WIDTH * Tan(angle)
if (ViewAngle > INT_ANGLE_270 || ViewAngle < INT_ANGLE_90)
{
xPos = xBegGlobal + BITMAP_WIDTH; // Looking to the right
xNext = BITMAP_WIDTH; // Positive direction
}
else
{
xPos = xBegGlobal; // Looking to the left
xNext = -BITMAP_WIDTH; // Negative direction
yNext = -yNext;
}
// Calculate the Y coordinate for the current square
yPos = (((int32_t)xPos - (int32_t)xPglobal) * LongTanTable[ViewAngle]) + yPglobalHI;
while (1)
{
if (xPos < 0 || xPos > GRID_XMAX ||
yPos < 0 || yPos > GRID_YMAXLONG)
break;
//************* Fixed point Y/64 * 64 X / 64 ***********
MapPosn = ((yPos >> FP_SHIFT) & 0xFFC0) + (xPos >> 6);
if ((Color = ObjGrid[MapPosn]) != 0)
{
Color &= 0xFF;
if (!ObjectExist(Color))
ObjectsSeen[FoundObjectCount++] = Color;
}
// Check to see if a wall is being struck by the ray
if ((Color & 0xFF) != 0)
{
xMapPosn = MapPosn; // Hold onto the map location
iLastX = xPos;
LastY1 = yPos;
if ((Color >> 8) == DOOR_XCODE) // Is this a door?
{
yd = ((yPos >> FP_SHIFT) & GRID_MASK); // Get the left side
xd = yd + BITMAP_WIDTH; // And the right side
ObjDist = (yPos + (yNext >> 1)) >> FP_SHIFT; // Calc door distance
if (ObjDist < yd || ObjDist > xd) // Is door visible?
{
xPos += xNext; // Nope, continue casting
yPos += yNext; // the ray as before
continue;
}
LastY1 = yPos + (yNext >> 1); // Adjust the X,Y values so
iLastX += (xNext >> 1); // the door is halfway in sq.
}
if (Color & DOOR_TYPE_SECRET)
{
if (xSecretColumn != 0)
{
sy = xSecretColumn * LongTanTable[ViewAngle];
ObjDist = (yPos + sy) >> FP_SHIFT;
yd = ((yPos >> FP_SHIFT) & GRID_MASK); // Get the left side
xd = yd + BITMAP_WIDTH; // And the right side
if (ObjDist < yd || ObjDist > xd) // Is door visible?
{
xPos += xNext; // Nope, continue casting
yPos += yNext; // the ray as before
continue;
}
LastY1 = yPos + sy;
iLastX += xSecretColumn;
}
}
return(Color);
}
xPos += xNext; // Next X coordinate (fixed at 64 or -64)
yPos += yNext; // Next calculated Y coord for a delta of X
}
return(0); // Return that no wall was found
}
//*************************************************************************
//
//*************************************************************************
void yRaySetup(void)
{
y_xNext = xNextTable[ViewAngle]; // Pre-calc'd value of BITMAP_WIDTH / tan(angle)
if (ViewAngle < INT_ANGLE_180)
{
y_yPos = yBegGlobal + BITMAP_WIDTH; // Looking down
y_yNext = BITMAP_WIDTH; // Positive direction
}
else
{
y_yPos = yBegGlobal; // Looking up
y_yNext = -BITMAP_WIDTH; // Negative direction
y_xNext = -y_xNext;
}
// Calculate the X coordinate for the current square
y_xPos = (((int32_t)y_yPos - (int32_t)yPglobal) * LongInvTanTable[ViewAngle]) + xPglobalHI;
}
//*************************************************************************
//
//*************************************************************************
UINT yRayCast(void)
{
UINT Color;
// short i,j,mx,my;
short MapPosn;
// short yBeg;
// short BitmapColumn;
// short xCenter,yCenter,yAdj;
// short ObjPosn;
// short oBegX;
int32_t xd,yd,ObjDist,sx;
while (1)
{
if (y_xPos < 0 || y_xPos > GRID_XMAXLONG ||
y_yPos < 0 || y_yPos > GRID_YMAX)
break;
//********** Y/64 * 64 Fixed point and /64 *****
MapPosn = (y_yPos & 0xFFC0) + (y_xPos >> (FP_SHIFT+6));
if ((Color = ObjGrid[MapPosn]) != 0)
{
Color &= 0xFF;
if (!ObjectExist(Color))
ObjectsSeen[FoundObjectCount++] = Color;
}
// Check for a wall being struck
if ((Color = yGridGlobal[MapPosn]) != 0)
{
yMapPosn = MapPosn; // Hold onto map position
LastX1 = y_xPos;
iLastY = y_yPos;
if ((Color & (DOOR_TYPE_SLIDE+DOOR_TYPE_SPLIT)))// Is this a door? //MEH NOT ((Color & 0xFF) == DOOR_YCODE) as he had before!
{
yd = ((y_xPos >> FP_SHIFT) & GRID_MASK); // Calc top side of square
xd = yd + BITMAP_WIDTH; // And bottom side of square
ObjDist = (y_xPos + (y_xNext >> 1)) >> FP_SHIFT;
if (ObjDist < yd || ObjDist > xd) // Is door visible?
{
y_xPos += y_xNext; // No, continue on with ray cast
y_yPos += y_yNext;
continue;
}
LastX1 = y_xPos + (y_xNext >> 1); // Adjust coordinates so door is
iLastY += (y_yNext >> 1); // Halfway into wall
}
if (Color & DOOR_TYPE_SECRET)
{
if (ySecretColumn != 0)
{
sx = ySecretColumn * LongInvTanTable[ViewAngle];
ObjDist = (y_xPos + sx) >> FP_SHIFT;
yd = ((y_xPos >> FP_SHIFT) & GRID_MASK); // Get the top side
xd = yd + BITMAP_WIDTH; // And the bottom side
if (ObjDist < yd || ObjDist > xd) // Is door visible?
{
y_xPos += y_xNext; // Nope, continue casting
y_yPos += y_yNext; // the ray as before
continue;
}
LastX1 = y_xPos + sx;
iLastY += ySecretColumn;
}
}
return(Color);
}
y_xPos += y_xNext; // Next calculated X value for delta Y
y_yPos += y_yNext; // Next fixed value of 64 or -64
}
return(0); // Return here if no Y wall is found
}
//*************************************************************************
//
//*************************************************************************
UINT OldyRay(void)
{
UINT Color;
// short i,j,mx,my;
short MapPosn;
// short yBeg;
int32_t yPos,yNext;
// short BitmapColumn;
// short xCenter,yCenter,yAdj;
// short ObjPosn;
// short oBegX;
int32_t xPos;
int32_t xNext;
int32_t xd,yd,ObjDist,sx;
xNext = xNextTable[ViewAngle]; // Pre-calc'd value of BITMAP_WIDTH / tan(angle)
if (ViewAngle < INT_ANGLE_180)
{
yPos = yBegGlobal + BITMAP_WIDTH; /* Looking down */
yNext = BITMAP_WIDTH; /* Positive direction */
}
else
{
yPos = yBegGlobal; /* Looking up */
yNext = -BITMAP_WIDTH; /* Negative direction */
xNext = -xNext;
}
/* Calculate the X coordinate for the current square */
xPos = (((int32_t)yPos - (int32_t)yPglobal) * LongInvTanTable[ViewAngle]) + xPglobalHI;
while (1)
{
if (xPos < 0 || xPos > GRID_XMAXLONG ||
yPos < 0 || yPos > GRID_YMAX)
break;
/*********** Y/64 * 64 Fixed point and /64 ******/
// MapPosn = ((yPos / BITMAP_WIDTH) * GRID_WIDTH) + (xPos >> (FP_SHIFT+BITMAP_SHIFT));
// MapPosn = ((yPos & GRID_MASK) >> 1) + (xPos >> (FP_SHIFT+BITMAP_SHIFT));
MapPosn = (yPos & 0xFFC0) + (xPos >> (FP_SHIFT+6));
if ((Color = ObjGrid[MapPosn]) != 0)
{
Color &= 0xFF;
if (!ObjectExist(Color))
ObjectsSeen[FoundObjectCount++] = Color;
}
/** Check for a wall being struck **/
if ((Color = yGridGlobal[MapPosn]) != 0)
{
yMapPosn = MapPosn; /* Hold onto map position */
LastX1 = xPos;
iLastY = yPos;
if ((Color & 0xFF) == DOOR_YCODE) /* Is this a door? */
{
yd = ((xPos >> FP_SHIFT) & GRID_MASK); /* Calc top side of square */
xd = yd + BITMAP_WIDTH; /* And bottom side of square */
ObjDist = (xPos + (xNext >> 1)) >> FP_SHIFT;
if (ObjDist < yd || ObjDist > xd) /* Is door visible? */
{
xPos += xNext; /* No, continue on with ray cast */
yPos += yNext;
continue;
}
LastX1 = xPos + (xNext >> 1); /* Adjust coordinates so door is */
iLastY += (yNext >> 1); /* Halfway into wall */
}
if (Color & DOOR_TYPE_SECRET)
{
if (ySecretColumn != 0)
{
sx = ySecretColumn * LongInvTanTable[ViewAngle];
ObjDist = (xPos + sx) >> FP_SHIFT;
yd = ((xPos >> FP_SHIFT) & GRID_MASK); /* Get the top side */
xd = yd + BITMAP_WIDTH; /* And the bottom side */
if (ObjDist < yd || ObjDist > xd) /* Is door visible? */
{
xPos += xNext; /* Nope, continue casting */
yPos += yNext; /* the ray as before */
continue;
}
LastX1 = xPos + sx;
iLastY += ySecretColumn;
}
}
return(Color);
}
xPos += xNext; /* Next calculated X value for delta Y */
yPos += yNext; /* Next fixed value of 64 or -64 */
}
return(0); /* Return here if no Y wall is found */
}
/****************************************************************************
** **
****************************************************************************/
UINT xRayMulti(UINT MinDist,short MinHeight)
{
UINT Color;
// short i,j,mx,my;
// short TablePosn;
short MapPosn;
// short xBeg;
int32_t xPos,xNext;
// short BitmapColumn;
// short xCenter,yCenter,xAdj;
// short ObjPosn;
// short oBegX,oBegY;
int32_t yPos;
int32_t yNext;
int32_t xd,yd;
// int32_t ObjDist;
yNext = yNextTable[ViewAngle]; /* PreCalc'd value of BITMAP_WIDTH * Tan(angle) */
if (ViewAngle > INT_ANGLE_270 || ViewAngle < INT_ANGLE_90)
{
xPos = xBegGlobal + BITMAP_WIDTH; /* Looking to the right */
xNext = BITMAP_WIDTH; /* Positive direction */
}
else
{
xPos = xBegGlobal; /* Looking to the left */
xNext = -BITMAP_WIDTH; /* Negative direction */
yNext = -yNext;
}
/* Calculate the Y coordinate for the current square */
yPos = (((int32_t)xPos - (int32_t)xPglobal) * LongTanTable[ViewAngle]) + yPglobalHI;
while (1)
{
if (xPos < 0 || xPos > GRID_XMAX ||
yPos < 0 || yPos > GRID_YMAXLONG)
break;
/************** Fixed point Y/64 * 64 X / 64 ***********/
MapPosn = ((yPos >> FP_SHIFT) & 0xFFC0) + (xPos >> 6);
/* Check to see if a wall is being struck by the ray */
if ((Color = xGridGlobal[MapPosn]) & WALL_TYPE_MULTI)
{
if ((Color & 0xFF) > MinHeight)
{
xd = xPos - xPglobal;
yd = InvCosTable[ViewAngle] >> 4;
if (MinDist < ((xd * yd) >> 10))
{
xMapPosn = MapPosn; /* Hold onto the map location */
iLastX = xPos;
LastY1 = yPos;
return(Color);
}
}
}
xPos += xNext; /* Next X coordinate (fixed at 64 or -64) */
yPos += yNext; /* Next calculated Y coord for a delta of X */
}
return(0); /* Return that no wall was found */
}
/****************************************************************************
** **
****************************************************************************/
UINT yRayMulti(UINT MinDist,short MinHeight)
{
UINT Color;
// short i,j,mx,my;
short MapPosn;
// short yBeg;
int32_t yPos,yNext;
// short BitmapColumn;
// short xCenter,yCenter,yAdj;
// short ObjPosn;
// short oBegX;
int32_t xPos;
int32_t xNext;
int32_t xd,yd;
xNext = xNextTable[ViewAngle]; /* Pre-calc'd value of BITMAP_WIDTH / tan(angle) */
if (ViewAngle < INT_ANGLE_180)
{
yPos = yBegGlobal + BITMAP_WIDTH; /* Looking down */
yNext = BITMAP_WIDTH; /* Positive direction */
}
else
{
yPos = yBegGlobal; /* Looking up */
yNext = -BITMAP_WIDTH; /* Negative direction */
xNext = -xNext;
}
/* Calculate the X coordinate for the current square */
xPos = (((int32_t)yPos - (int32_t)yPglobal) * LongInvTanTable[ViewAngle]) + xPglobalHI;
while (1)
{
if (xPos < 0 || xPos > GRID_XMAXLONG ||
yPos < 0 || yPos > GRID_YMAX)
break;
/*********** Y/64 * 64 Fixed point and /64 ******/
MapPosn = (yPos & 0xFFC0) + (xPos >> (FP_SHIFT+6));
/** Check for a wall being struck **/
if ((Color = yGridGlobal[MapPosn]) & WALL_TYPE_MULTI)
{
if ((Color & 0xFF) > MinHeight)
{
xd = yPos - yPglobal;
yd = InvCosTable[ViewAngle] >> 4;
if (MinDist < ((xd * yd) >> 10))
{
yMapPosn = MapPosn; /* Hold onto the map location */
LastX1 = xPos;
iLastY = yPos;
return(Color);
}
}
}
xPos += xNext; /* Next calculated X value for delta Y */
yPos += yNext; /* Next fixed value of 64 or -64 */
}
return(0); /* Return here if no Y wall is found */
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//gcc generateMatrix.c -lgomp -fopenmp -O2 -o generateMatrix
//./generateMatrix NAME X Y
int main(int argc, char* argv[]) {
if(argc < 4) {
perror("Too few agruments");
return 1;
}
char *filename = argv[1];
int m = atoi(argv[2]);
int n = atoi(argv[3]);
int i, j;
FILE *f = fopen(filename, "w");
if(f == NULL) {
perror("Error opening file\n");
}
srand( time(NULL) );
for(i=1; i<=m; i++) {
for(j=1; j<=n; j++) {
fprintf(f, "%d ", rand() % 100);
if(j == n) fprintf(f, "\n\r");
}
}
fclose(f);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
////////////////EXERCICIO 4
int Eprimo(int x)// verifica se primo
{
int i;
if(x == 2)
{
return 1;
}
for(i=2;i<(x/2)+2;i++)
{
if(x%i == 0)
{
return 0;
}
}
return 1;
}
int mostraPrimo(int x)
{
int y, contador = 0, primo1 = 0,primo2 = 0;
if(x == 2)
{
printf("3 e 5 s%co os primos posteriores\nN%co existem primos anteriores\n",198,198);
return 0 ;
}
if(x == 3)
{
printf("5 e 7 s%co os primos posteriores\nApenas 2 %c primo anterior\n",198,130);
return 0;
}
if(x == 5)
{
printf("7 e 11 s%co os primos posteriores\n2 e 3 s%co primos anteriores\n",198,198);
return 0;
}//// o algortmo para encontrar primos anteriores no funicona para 2, 3 e 5
y = x + 2;
while(contador != 2)
{
if(Eprimo(y) && primo1 == 0)
{
primo1 = y;
contador += 1;
y += 2;
}
else if(Eprimo(y))
{
primo2 = y;
contador += 1;
}
y+= 2;
}
printf("\n%d e %d s%co os primos posteriores",primo1,primo2,198);
///////////////////////////////////////////////////////////////////////// acima posteriores, abaixo anteriores
y = x - 2;
primo1 = 0;
primo2 = 0;
contador = 0;
while(contador != 2)
{
if(Eprimo(y) && primo1 == 0)
{
primo1 = y;
contador += 1;
y -= 2;
}
else if(Eprimo(y))
{
primo2 = y;
contador += 1;
}
y-= 2;
}
printf("\n%d e %d s%co os primos anteriores",primo2,primo1,198);
return 0;
}
int main()
{
int d, contador = 0;
while(contador == 0)
{
printf("Digite um n%cmero primo: ",163);
fflush(stdin);
scanf("%d",&d);
if(Eprimo(d))
{
mostraPrimo(d);
contador +=1;
}
else
{
printf("O n%cmero n%co %c primo\n",163, 198, 130);
}
}
return 0;
}
|
C
|
#include "solution.h"
#include <stdio.h>
#include <stdlib.h>
void testcase1()
{
printf("testcase1\n");
int returnSize = 0;
int *indices = findSubstring("barfoofoobarthefoobarman", (char *[]){"foo", "bar", "the"}, 3, &returnSize);
fflush(stdout);
free(indices);
}
void testcase2()
{
printf("testcase2\n");
int returnSize = 0;
int *indices = findSubstring("aaa", (char *[]){"a", "a"}, 2, &returnSize);
fflush(stdout);
free(indices);
}
void testcase3()
{
printf("testcase3\n");
int returnSize = 0;
int *indices = findSubstring("barfoo", (char *[]){"foo", "bar"}, 2, &returnSize);
fflush(stdout);
free(indices);
}
void testcase4()
{
printf("testcase4\n");
int returnSize = 0;
int *indices = findSubstring("aa", (char *[]){"aaa", "aaaa"}, 2, &returnSize);
fflush(stdout);
free(indices);
}
void testcase5()
{
printf("testcase5\n");
int returnSize = 0;
int *indices = findSubstring("aaaaaaaaaaaa", (char *[]){"a", "a", "a", "a", "a"}, 5, &returnSize);
fflush(stdout);
free(indices);
}
int main(int argc, char *argv[])
{
testcase1();
testcase2();
testcase3();
testcase4();
testcase5();
return 0;
}
|
C
|
#include <stdio.h>
int gcd(int p, int q) { if (p == 0) return q; return gcd(q%p, p); }
int main()
{
int a, b;
scanf("%d %d", &a, &b);
int gcd_ab = gcd(a, b);
printf("%d\n", gcd_ab);
printf("%d\n", a * b / gcd_ab);
}
|
C
|
#include <stdio.h>
int fibonacci (int n){//função que calcula a soma de um número com o anterior recursivamente
if (n < 2){
return 1;
}
else{
return fibonacci (n-1) + fibonacci (n-2);
}
}
int main(void) {
int num;
scanf ("%d", &num);
for (int i=0; i < num;i++){
printf ("%d ", fibonacci(i));
}
return 0;
}
|
C
|
#ifndef TEXTURE_POOL_H_
#define TEXTURE_POOL_H_
#include <SDL2/SDL.h>
#include "texture.h"
#define NUM_INITIAL_TEXTURES_IN_TEXTUREPOOL 1
typedef struct textureContainerT
{
textureT *texture; //pointer to the texture data
char *name; //name of the texture
}textureContainerT;
typedef struct texturePoolT
{
int numTextures; //number of textures
int maxTextures; //current max number of textures
textureContainerT *textures; //pointer to the textures
}texturePoolT;
texturePoolT *texturePoolNewTexturePool();
void texturePoolAddTextureToTexturePool(texturePoolT *texturePool,char *filename);
void texturePoolRemoveTextureFromPool(texturePoolT *texturePool,char *filename);
textureT *texturePoolGetTextureFromPool(texturePoolT *texturePool,char *filename);
void texturePoolFreeTexturePool(texturePoolT *texturePool);
#endif // TEXTURE_POOL_H_
|
C
|
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int SBP, gender, age, risk, stp;
do
{
printf("Systolic blood pressure: ");
scanf("%d", &SBP);
}
while(SBP <= 0);
printf("Gender (0 for Male, 1 for Female): ");
scanf("%d", &gender);
printf("Age: ");
scanf("%d", &age);
printf("Presence of Sinus Tachycardia (0 for absent, 1 for present): ");
scanf("%d", &stp);
printf("\n Age: %d \n", age);
printf("\n PST: %d \n",stp);
printf("\n SBP: %d \n", SBP);
printf("\n Gender: %d \n", gender);
printf("\n Age: %d \n", age);
if(SBP > 91)
{
if(gender == 1)
{
printf("\n %d \n", age);
if(age > 55)
{
if(stp)
{
risk = 5;
}
else
{
risk = 4;
}
}
else
{
risk = 3;
}
}
else
{
if(age > 63)
{
if(stp)
{
risk = 5;
}
else
{
risk = 4;
}
}
else
{
risk = 2;
}
}
}
else
{
risk = 1;
}
printf("Risk Level: %d", risk);
}
|
C
|
#include "unity/unity_fixture.h"
#include "test_common.h"
#include "nmpps.h"
TEST_GROUP(tests_threshold_gt);
TEST_SETUP(tests_threshold_gt){};
TEST_TEAR_DOWN(tests_threshold_gt){}
/// nmppsThreshold_GT_16s
TEST(tests_threshold_gt, test_nmppsThreshold_GT_16s_null_ptr){
nmpps16s a;
TEST_ASSERT_EQUAL(nmppsStsNullPtrErr, nmppsThreshold_GT_16s(NULL, &a, 1, 1));
TEST_ASSERT_EQUAL(nmppsStsNullPtrErr, nmppsThreshold_GT_16s(&a, NULL, 1, 1));
}
TEST(tests_threshold_gt, test_nmppsThreshold_GT_16s_err_size){
nmpps16s a;
TEST_ASSERT_EQUAL(nmppsStsSizeErr, nmppsThreshold_GT_16s(&a, &a, 0, 1));
TEST_ASSERT_EQUAL(nmppsStsSizeErr, nmppsThreshold_GT_16s(&a, &a, -1, 1));
}
TEST(tests_threshold_gt, test_nmppsThreshold_GT_16s){
int i = 0;
nmpps16s src[150] __attribute__ ((aligned (2)));
nmpps16s dst[150] __attribute__ ((aligned (2)));
nmpps16s etalon[150] __attribute__ ((aligned (2)));
/// Четное количество элементов, < 32
init_vector_value_16s(dst, 0, 150);
init_vector_value_16s(src, 0, 150);
init_vector_value_16s(etalon, 0, 150);
for(i = 0; i < 10; i++){
src[i] = i;
etalon[i] = i;
}
for(; i < 20; i++){
src[i] = i + 38;
etalon[i] = 38;
}
src[20] = 37; etalon[20] = 37;
src[21] = 123; etalon[21] = 38;
src[22] = 38; etalon[22] = 38;
src[23] = 0; etalon[23] = 0;
src[24] = 39; etalon[24] = 38;
src[25] = 1; etalon[25] = 1;
src[26] = 100; etalon[26] = 38;
src[27] = -3; etalon[27] = -3;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_16s(src, dst, 28, 38));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL(etalon[i], dst[i]);
}
/// Нечетное количество элементов, < 32
init_vector_value_16s(dst, 0, 150);
init_vector_value_16s(src, 0, 150);
init_vector_value_16s(etalon, 0, 150);
for(i = 0; i < 10; i++){
src[i] = i;
etalon[i] = i;
}
for(; i < 20; i++){
src[i] = i + 38;
etalon[i] = 38;
}
src[20] = 37; etalon[20] = 37;
src[21] = 123; etalon[21] = 38;
src[22] = 38; etalon[22] = 38;
src[23] = 0; etalon[23] = 0;
src[24] = 39; etalon[24] = 38;
src[25] = 1; etalon[25] = 1;
src[26] = -3; etalon[26] = -3;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_16s(src, dst, 27, 38));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL(etalon[i], dst[i]);
}
/// Кратно 32
init_vector_value_16s(dst, 0, 150);
init_vector_value_16s(src, 0, 150);
init_vector_value_16s(etalon, 0, 150);
for(i = 0; i < 10; i++){
src[i] = -i;
etalon[i] = -i;
}
for(; i < 120; i++){
src[i] = i + 38;
etalon[i] = 38;
}
src[120] = 37; etalon[120] = 37;
src[121] = 123; etalon[121] = 38;
src[122] = 38; etalon[122] = 38;
src[123] = 0; etalon[123] = 0;
src[124] = 39; etalon[124] = 38;
src[125] = 1; etalon[125] = 1;
src[126] = -3; etalon[126] = -3;
src[127] = -38; etalon[127] = -38;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_16s(src, dst, 128, 38));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL(etalon[i], dst[i]);
}
/// больше 32, кратно 2
init_vector_value_16s(dst, 0, 150);
init_vector_value_16s(src, 0, 150);
init_vector_value_16s(etalon, 0, 150);
for(i = 0; i < 10; i++){
src[i] = -i;
etalon[i] = -i;
}
for(; i < 148; i++){
src[i] = i + 38;
etalon[i] = 38;
}
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_16s(src, dst, 148, 38));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL(etalon[i], dst[i]);
}
/// больше 32, кратно 2
init_vector_value_16s(dst, 0, 150);
init_vector_value_16s(src, 0, 150);
init_vector_value_16s(etalon, 0, 150);
for(i = 0; i < 10; i++){
src[i] = -i;
etalon[i] = -i;
}
for(; i < 148; i++){
src[i] = i + 38;
etalon[i] = 38;
}
src[148] = -123; etalon[148] = -123;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_16s(src, dst, 149, 38));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL(etalon[i], dst[i]);
}
/// 1
init_vector_value_16s(dst, 0, 150);
init_vector_value_16s(src, 0, 150);
init_vector_value_16s(etalon, 0, 150);
src[0] = -39; etalon[0] = -123;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_16s(src, dst, 1, -123));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL(etalon[i], dst[i]);
}
}
/// nmppsThreshold_GT_32s
TEST(tests_threshold_gt, test_nmppsThreshold_GT_32s_null_ptr){
nmpps32s a;
TEST_ASSERT_EQUAL(nmppsStsNullPtrErr, nmppsThreshold_GT_32s(NULL, &a, 1, 1));
TEST_ASSERT_EQUAL(nmppsStsNullPtrErr, nmppsThreshold_GT_32s(&a, NULL, 1, 1));
}
TEST(tests_threshold_gt, test_nmppsThreshold_GT_32s_err_size){
nmpps32s a;
TEST_ASSERT_EQUAL(nmppsStsSizeErr, nmppsThreshold_GT_32s(&a, &a, 0, 1));
TEST_ASSERT_EQUAL(nmppsStsSizeErr, nmppsThreshold_GT_32s(&a, &a, -1, 1));
}
TEST(tests_threshold_gt, test_nmppsThreshold_GT_32s){
int i = 0;
nmpps32s src[150] __attribute__ ((aligned (2)));
nmpps32s dst[150] __attribute__ ((aligned (2)));
nmpps32s etalon[150] __attribute__ ((aligned (2)));
/// Четное количество элементов, < 32
init_vector_value_32s(dst, 0, 150);
init_vector_value_32s(src, 0, 150);
init_vector_value_32s(etalon, 0, 150);
for(i = 0; i < 10; i++){
src[i] = i;
etalon[i] = i;
}
for(; i < 20; i++){
src[i] = i + 38;
etalon[i] = 38;
}
src[20] = 37; etalon[20] = 37;
src[21] = 123; etalon[21] = 38;
src[22] = 38; etalon[22] = 38;
src[23] = 0; etalon[23] = 0;
src[24] = 39; etalon[24] = 38;
src[25] = 1; etalon[25] = 1;
src[26] = 100; etalon[26] = 38;
src[27] = -3; etalon[27] = -3;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_32s(src, dst, 28, 38));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL(etalon[i], dst[i]);
}
/// Нечетное количество элементов, < 32
init_vector_value_32s(dst, 0, 150);
init_vector_value_32s(src, 0, 150);
init_vector_value_32s(etalon, 0, 150);
for(i = 0; i < 10; i++){
src[i] = i;
etalon[i] = i;
}
for(; i < 20; i++){
src[i] = i + 38;
etalon[i] = 38;
}
src[20] = 37; etalon[20] = 37;
src[21] = 123; etalon[21] = 38;
src[22] = 38; etalon[22] = 38;
src[23] = 0; etalon[23] = 0;
src[24] = 39; etalon[24] = 38;
src[25] = 1; etalon[25] = 1;
src[26] = -3; etalon[26] = -3;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_32s(src, dst, 27, 38));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL(etalon[i], dst[i]);
}
/// Кратно 32
init_vector_value_32s(dst, 0, 150);
init_vector_value_32s(src, 0, 150);
init_vector_value_32s(etalon, 0, 150);
for(i = 0; i < 10; i++){
src[i] = -i;
etalon[i] = -i;
}
for(; i < 120; i++){
src[i] = i + 38;
etalon[i] = 38;
}
src[120] = 37; etalon[120] = 37;
src[121] = 123; etalon[121] = 38;
src[122] = 38; etalon[122] = 38;
src[123] = 0; etalon[123] = 0;
src[124] = 39; etalon[124] = 38;
src[125] = 1; etalon[125] = 1;
src[126] = -3; etalon[126] = -3;
src[127] = -38; etalon[127] = -38;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_32s(src, dst, 128, 38));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL(etalon[i], dst[i]);
}
/// больше 32, кратно 2
init_vector_value_32s(dst, 0, 150);
init_vector_value_32s(src, 0, 150);
init_vector_value_32s(etalon, 0, 150);
for(i = 0; i < 10; i++){
src[i] = -i;
etalon[i] = -i;
}
for(; i < 148; i++){
src[i] = i + 38;
etalon[i] = 38;
}
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_32s(src, dst, 148, 38));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL(etalon[i], dst[i]);
}
/// больше 32, кратно 2
init_vector_value_32s(dst, 0, 150);
init_vector_value_32s(src, 0, 150);
init_vector_value_32s(etalon, 0, 150);
for(i = 0; i < 10; i++){
src[i] = -i;
etalon[i] = -38;
}
for(; i < 148; i++){
src[i] = i - 1111;
etalon[i] = i - 1111;
}
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_32s(src, dst, 148, -38));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL(etalon[i], dst[i]);
}
/// больше 32, кратно 2
init_vector_value_32s(dst, 0, 150);
init_vector_value_32s(src, 0, 150);
init_vector_value_32s(etalon, 0, 150);
for(i = 0; i < 10; i++){
src[i] = -i;
etalon[i] = -i;
}
for(; i < 148; i++){
src[i] = i + 38;
etalon[i] = 38;
}
src[148] = -123; etalon[148] = -123;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_32s(src, dst, 149, 38));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL(etalon[i], dst[i]);
}
/// 1
init_vector_value_32s(dst, 0, 150);
init_vector_value_32s(src, 0, 150);
init_vector_value_32s(etalon, 0, 150);
src[0] = -123; etalon[0] = -123;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_32s(src, dst, 1, -7));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL(etalon[i], dst[i]);
}
}
/// nmppsThreshold_GT_32f
TEST(tests_threshold_gt, test_nmppsThreshold_GT_32f_null_ptr){
nmpps32f a;
TEST_ASSERT_EQUAL(nmppsStsNullPtrErr, nmppsThreshold_GT_32f(NULL, &a, 1, 1));
TEST_ASSERT_EQUAL(nmppsStsNullPtrErr, nmppsThreshold_GT_32f(&a, NULL, 1, 1));
}
TEST(tests_threshold_gt, test_nmppsThreshold_GT_32f_err_size){
nmpps32f a;
TEST_ASSERT_EQUAL(nmppsStsSizeErr, nmppsThreshold_GT_32f(&a, &a, 0, 1));
TEST_ASSERT_EQUAL(nmppsStsSizeErr, nmppsThreshold_GT_32f(&a, &a, -1, 1));
}
TEST(tests_threshold_gt, test_nmppsThreshold_GT_32f){
int i = 0;
nmpps32f src[150] __attribute__ ((aligned (2)));
nmpps32f dst[150] __attribute__ ((aligned (2)));
nmpps32f etalon[150] __attribute__ ((aligned (2)));
/// Четное количество элементов, < 32
init_vector_value_32f(dst, 0.0, 150);
init_vector_value_32f(src, 0.0, 150);
init_vector_value_32f(etalon, 0.0, 150);
for(i = 0; i < 10; i++){
src[i] = i / 3;
etalon[i] = -27.5;
}
for(; i < 20; i++){
src[i] = i - 138.1;
etalon[i] = i - 138.1;
}
src[20] = -31.1; etalon[20] = -31.1;
src[21] = 11234.356; etalon[21] = -27.5;
src[22] = 38.0; etalon[22] = -27.5;
src[23] = -1234.111; etalon[23] = -1234.111;
src[24] = 39.0; etalon[24] = -27.5;
src[25] = 0; etalon[25] = -27.5;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_32f(src, dst, 26, -27.5));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL_FLOAT(etalon[i], dst[i]);
}
/// Нечетное количество элементов, < 32
init_vector_value_32f(dst, 0.0, 150);
init_vector_value_32f(src, 0.0, 150);
init_vector_value_32f(etalon, 0.0, 150);
for(i = 0; i < 10; i++){
src[i] = i * 2.3;
etalon[i] = i * 2.3;
}
for(; i < 20; i++){
src[i] = i + 38.0;
etalon[i] = 38.0;
}
src[20] = 37.0; etalon[20] = 37.0;
src[21] = 123.0; etalon[21] = 38.0;
src[22] = 38.0; etalon[22] = 38.0;
src[23] = 0.0; etalon[23] = 0.0;
src[24] = 39.0; etalon[24] = 38.0;
src[25] = 1.0; etalon[25] = 1.0;
src[26] = -3.0; etalon[26] = -3.0;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_32f(src, dst, 27, 38.0));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL_FLOAT(etalon[i], dst[i]);
}
/// Кратно 32
init_vector_value_32f(dst, 0.0, 150);
init_vector_value_32f(src, 0.0, 150);
init_vector_value_32f(etalon, 0.0, 150);
for(i = 0; i < 10; i++){
src[i] = -i;
etalon[i] = -i;
}
for(; i < 120; i++){
src[i] = i + 38.0;
etalon[i] = 38.0;
}
src[120] = 37.0; etalon[120] = 37.0;
src[121] = 123.0; etalon[121] = 38.0;
src[122] = 38.0; etalon[122] = 38.0;
src[123] = 0.0; etalon[123] = 0.0;
src[124] = 39.0; etalon[124] = 38.0;
src[125] = 1.0; etalon[125] = 1.0;
src[126] = -3.0; etalon[126] = -3.0;
src[127] = -38.0; etalon[127] = -38.0;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_32f(src, dst, 128, 38.0));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL_FLOAT(etalon[i], dst[i]);
}
/// больше 32, кратно 2
init_vector_value_32f(dst, 0.0, 150);
init_vector_value_32f(src, 0.0, 150);
init_vector_value_32f(etalon, 0.0, 150);
for(i = 0; i < 10; i++){
src[i] = -i;
etalon[i] = -i;
}
for(; i < 148; i++){
src[i] = i + 38.0;
etalon[i] = 38.0;
}
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_32f(src, dst, 148, 38.0));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL_FLOAT(etalon[i], dst[i]);
}
/// больше 32, кратно 2
init_vector_value_32f(dst, 0.0, 150);
init_vector_value_32f(src, 0.0, 150);
init_vector_value_32f(etalon, 0.0, 150);
for(i = 0; i < 10; i++){
src[i] = -i;
etalon[i] = -i;
}
for(; i < 148; i++){
src[i] = i + 38.0;
etalon[i] = 38.0;
}
src[148] = -123.0; etalon[148] = -123.0;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_32f(src, dst, 149, 38.0));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL_FLOAT(etalon[i], dst[i]);
}
/// 1
init_vector_value_32f(dst, 0.0, 150);
init_vector_value_32f(src, 0.0, 150);
init_vector_value_32f(etalon, 0.0, 150);
src[0] = -123.0; etalon[0] = -123.0;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_32f(src, dst, 1, 4533535.0));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL_FLOAT(etalon[i], dst[i]);
}
}
/// nmppsThreshold_GT_64f
TEST(tests_threshold_gt, test_nmppsThreshold_GT_64f_null_ptr){
nmpps64f a;
TEST_ASSERT_EQUAL(nmppsStsNullPtrErr, nmppsThreshold_GT_64f(NULL, &a, 1, 1));
TEST_ASSERT_EQUAL(nmppsStsNullPtrErr, nmppsThreshold_GT_64f(&a, NULL, 1, 1));
}
TEST(tests_threshold_gt, test_nmppsThreshold_GT_64f_err_size){
nmpps64f a;
TEST_ASSERT_EQUAL(nmppsStsSizeErr, nmppsThreshold_GT_64f(&a, &a, 0, 1));
TEST_ASSERT_EQUAL(nmppsStsSizeErr, nmppsThreshold_GT_64f(&a, &a, -1, 1));
}
TEST(tests_threshold_gt, test_nmppsThreshold_GT_64f){
int i = 0;
nmpps64f src[150] __attribute__ ((aligned (2)));
nmpps64f dst[150] __attribute__ ((aligned (2)));
nmpps64f etalon[150] __attribute__ ((aligned (2)));
/// Четное количество элементов, < 32
init_vector_value_64f(dst, 0.0, 150);
init_vector_value_64f(src, 0.0, 150);
init_vector_value_64f(etalon, 0.0, 150);
for(i = 0; i < 10; i++){
src[i] = i / 3;
etalon[i] = -27.5;
}
for(; i < 20; i++){
src[i] = i - 138.1;
etalon[i] = i - 138.1;
}
src[20] = -31.1; etalon[20] = -31.1;
src[21] = 11234.356; etalon[21] = -27.5;
src[22] = 38.0; etalon[22] = -27.5;
src[23] = -1234.111; etalon[23] = -1234.111;
src[24] = 39.0; etalon[24] = -27.5;
src[25] = 0; etalon[25] = -27.5;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_64f(src, dst, 26, -27.5));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL_FLOAT(etalon[i], dst[i]);
}
/// Нечетное количество элементов, < 32
init_vector_value_64f(dst, 0.0, 150);
init_vector_value_64f(src, 0.0, 150);
init_vector_value_64f(etalon, 0.0, 150);
for(i = 0; i < 10; i++){
src[i] = i * 2.3;
etalon[i] = i * 2.3;
}
for(; i < 20; i++){
src[i] = i + 38.0;
etalon[i] = 38.0;
}
src[20] = 37.0; etalon[20] = 37.0;
src[21] = 123.0; etalon[21] = 38.0;
src[22] = 38.0; etalon[22] = 38.0;
src[23] = 0.0; etalon[23] = 0.0;
src[24] = 39.0; etalon[24] = 38.0;
src[25] = 1.0; etalon[25] = 1.0;
src[26] = -3.0; etalon[26] = -3.0;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_64f(src, dst, 27, 38.0));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL_FLOAT(etalon[i], dst[i]);
}
/// Кратно 32
init_vector_value_64f(dst, 0.0, 150);
init_vector_value_64f(src, 0.0, 150);
init_vector_value_64f(etalon, 0.0, 150);
for(i = 0; i < 10; i++){
src[i] = -i;
etalon[i] = -i;
}
for(; i < 120; i++){
src[i] = i + 38.0;
etalon[i] = 38.0;
}
src[120] = 37.0; etalon[120] = 37.0;
src[121] = 123.0; etalon[121] = 38.0;
src[122] = 38.0; etalon[122] = 38.0;
src[123] = 0.0; etalon[123] = 0.0;
src[124] = 39.0; etalon[124] = 38.0;
src[125] = 1.0; etalon[125] = 1.0;
src[126] = -3.0; etalon[126] = -3.0;
src[127] = -38.0; etalon[127] = -38.0;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_64f(src, dst, 128, 38.0));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL_FLOAT(etalon[i], dst[i]);
}
/// больше 32, кратно 2
init_vector_value_64f(dst, 0.0, 150);
init_vector_value_64f(src, 0.0, 150);
init_vector_value_64f(etalon, 0.0, 150);
for(i = 0; i < 10; i++){
src[i] = -i;
etalon[i] = -i;
}
for(; i < 148; i++){
src[i] = i + 38.0;
etalon[i] = 38.0;
}
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_64f(src, dst, 148, 38.0));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL_FLOAT(etalon[i], dst[i]);
}
/// больше 32, кратно 2
init_vector_value_64f(dst, 0.0, 150);
init_vector_value_64f(src, 0.0, 150);
init_vector_value_64f(etalon, 0.0, 150);
for(i = 0; i < 10; i++){
src[i] = -i;
etalon[i] = -i;
}
for(; i < 148; i++){
src[i] = i + 38.0;
etalon[i] = 38.0;
}
src[148] = -123.0; etalon[148] = -123.0;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_64f(src, dst, 149, 38.0));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL_FLOAT(etalon[i], dst[i]);
}
/// 1
init_vector_value_64f(dst, 0.0, 150);
init_vector_value_64f(src, 0.0, 150);
init_vector_value_64f(etalon, 0.0, 150);
src[0] = -123.0; etalon[0] = -123.0;
TEST_ASSERT_EQUAL(nmppsStsNoErr, nmppsThreshold_GT_64f(src, dst, 1, 4533535.0));
for(i = 0; i < 150;i++){
TEST_ASSERT_EQUAL_FLOAT(etalon[i], dst[i]);
}
}
TEST_GROUP_RUNNER(tests_threshold_gt){
RUN_TEST_CASE(tests_threshold_gt, test_nmppsThreshold_GT_16s_null_ptr);
RUN_TEST_CASE(tests_threshold_gt, test_nmppsThreshold_GT_16s_err_size);
RUN_TEST_CASE(tests_threshold_gt, test_nmppsThreshold_GT_16s);
RUN_TEST_CASE(tests_threshold_gt, test_nmppsThreshold_GT_32s_null_ptr);
RUN_TEST_CASE(tests_threshold_gt, test_nmppsThreshold_GT_32s_err_size);
RUN_TEST_CASE(tests_threshold_gt, test_nmppsThreshold_GT_32s);
RUN_TEST_CASE(tests_threshold_gt, test_nmppsThreshold_GT_32f_null_ptr);
RUN_TEST_CASE(tests_threshold_gt, test_nmppsThreshold_GT_32f_err_size);
RUN_TEST_CASE(tests_threshold_gt, test_nmppsThreshold_GT_32f);
RUN_TEST_CASE(tests_threshold_gt, test_nmppsThreshold_GT_64f_null_ptr);
RUN_TEST_CASE(tests_threshold_gt, test_nmppsThreshold_GT_64f_err_size);
RUN_TEST_CASE(tests_threshold_gt, test_nmppsThreshold_GT_64f);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "3-calc.h"
/**
* main - return result of desired calculation from command line options
* @argc: number of command line arguments
* @argv: array of command line arguments
*
* Return: EXIT_SUCCESS on success, 98 for wrong number of arugments,
* 99 for invalid operation, 99 for division/modulus by 0.
*/
int main(int argc, char *argv[])
{
int num1, num2, result;
int (*op_func)(int, int);
char *operator;
if (argc != 4)
{
puts("Error");
exit(98);
}
operator = argv[2];
num1 = atoi(argv[1]);
num2 = atoi(argv[3]);
if ((operator[0] == '/' || operator[0] == '%') && num2 == 0)
{
puts("Error");
exit(100);
}
op_func = get_op_func(operator);
if (op_func == NULL)
{
puts("Error");
exit(99);
}
result = op_func(num1, num2);
printf("%d\n", result);
exit(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
void read_arr(int*,int);
void print_arr(int*,int);
int ret_max(int*,int);
int main()
{
// array declaration
int arr[10], arr_size,max;
printf("Enter the number of elements \n");
scanf("%d", &arr_size);
printf("Enter the elements\n");
read_arr(arr, arr_size);
printf("The array elements are\n");
print_arr(arr, arr_size);
printf("\nThe maximum element in the arrays is %d\n",ret_max(arr, arr_size));
return 0;
}
void read_arr(int *arr,int arr_size)
{
for(int i=0;i<arr_size;i++)
{
scanf("%d",&arr[i]);
}
}
void print_arr(int *arr,int arr_size)
{
for(int i=0;i<arr_size;i++)
{
printf("%d\t",arr[i]);
}
}
int ret_max(int *arr,int arr_size)
{
int max=arr[0],n;
for (int i = 1; i < n; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include <stdbool.h>
#include <math.h>
#define MAX 50
typedef struct node
{
int label;
bool isVisited;
struct node *next;
} Vertex;
typedef struct List{
Vertex *head, *tail;
} List;
FILE *inputFile, *outputFile; // FILE handles for input and output files
List *adjList[MAX]; // the adjaceny LIST array
bool isVisited[MAX] = {false}; // a boolean array marking the visit-status of a vertex i
int vertexCount; // total number of vertices in the graph
// ***************ADJ-LIST FUNCTIONS******************************
// create a new vertex node
Vertex *newVertex(int label){
Vertex *node;
node = (Vertex*)malloc(sizeof(Vertex));
node->label = label;
node->isVisited = false;
node->next = NULL;
return node;
}
// initialize an adj list
void initAdjList(){
int i = 0;
for(;i <vertexCount; i++){
adjList[i] = (List*) malloc(sizeof(List));
adjList[i]->head = newVertex(-1);
adjList[i]->tail = newVertex(-1);
adjList[i]->head->next = adjList[i]->tail;
}
}
// add undirected edge to adj list
void addUndirectedEdge( int source, int destination){
Vertex *v = newVertex(destination);
v->next = adjList[source]->head->next;
adjList[source]->head->next = v;
Vertex *v2 = newVertex(source);
v2->next = adjList[destination]->head->next;
adjList[destination]->head->next = v2;
}
// vanilla LL traversal
void traverse(List *L){
Vertex *temp = L->head->next;
fprintf(outputFile, "[HEAD]->");
while(temp != L->tail){
fprintf(outputFile, "%d ->", temp->label);
temp = temp->next;
}
fprintf(outputFile, "[TAIL]\n");
}
// display entire adj list
void traverseAdjList(){
int i = 0;
for(; i<vertexCount; i++){
fprintf(outputFile, "%d ", i);
traverse(adjList[i]);
}
}
// ***************GRAPH FUNCTIONS******************************
// vanilla DFS util fn on ADJ list
void DFSUtil(int vertexIndex) {
// marking the current vertex as visited
isVisited[vertexIndex] = true;
Vertex *temp = adjList[vertexIndex]->head->next;
while(temp != adjList[vertexIndex]->tail){
if ( isVisited[temp->label] == false)
DFSUtil(temp->label); // recursive calling DFS-util
temp = temp->next;
}
}
// calculate number of connected components
int numOfConnectedComponents(){
int connectedComponentCount = 0;
int i = 0;
for(; i<vertexCount; i++){
if (isVisited[i] == false){
DFSUtil(i);
connectedComponentCount++;
}
}
return connectedComponentCount;
}
void buildGraphFromFile(FILE *f){
int v1, v2;
fscanf(f, "%d", &vertexCount);
fprintf(outputFile, "Total vertices = %d\n", vertexCount);
fprintf(outputFile, "\n\n");
initAdjList();
while(fscanf(f, "%d", &v1) == 1) {
if (fscanf(f, "%d", &v2) == 1){
if (
(v1 < 0 || v1 >= vertexCount) ||
(v2 < 0 || v2 >= vertexCount)
)
fprintf(outputFile, "Invalid vertex %d and %d skipping...\n", v1, v2);
else{
addUndirectedEdge(v1, v2);
fprintf(outputFile, "Added undirected edge btn %d and %d\n", v1, v2);
}
}
}
fprintf(outputFile, "\n\n");
fprintf(outputFile, "the adj list representation of the graph is as \n");
traverseAdjList();
fprintf(outputFile, "\n\n");
}
main(){
inputFile = fopen("connected-component-input-file.txt", "r");
outputFile = fopen("connected-component-output-file.txt", "w");
buildGraphFromFile(inputFile);
fprintf(outputFile, "Total number of connected components = %d\n", numOfConnectedComponents());
fclose(inputFile);
fclose(outputFile);
}
|
C
|
/*
* string.h
*
* Created on: 15 may. 2021
* Author: Yesid
*/
#ifndef DATAVALIDATION_CHARSTRING_H_
#define DATAVALIDATION_CHARSTRING_H_
#include <string.h>
#include <ctype.h>
/**
* @brief converts a character string to uppercase
*
* @param charStringEntered, character string
* @return, returns the uppercase character string or Null if the pointer does not point to any address
*/
char* stringToUpper(char *charStringEntered);
/**
* @brief converts a character string to lowercase
*
* @param charStringEntered, character string
* @return, returns the lowercase character string or Null if the pointer does not point to any address
*/
char* stringToLower(char *charStringEntered);
/**
* @brief detects if there is a symbol or number in the character entered
*
* @param character, character entered
* @return,0 if it is correct or -1 if there is an error
*/
int isSymbol_Number(char character);
#endif /* DATAVALIDATION_CHARSTRING_H_ */
|
C
|
#include <stdlib.h>
#include "sorting.h"
#include <stdio.h>
//load file function
long *Load_File(char *Filename, int *Size) {
if(Filename == NULL) {
fprintf(stdout, "\nNo filename specified.");
return NULL;
}
long *array = NULL;
int i = 0;
long int num = 0;
FILE *fptr = NULL;
//check to see if file opens
fptr = fopen(Filename, "r");
if(fptr == NULL) {
fprintf(stdout, "Error reading input file.");
return NULL;
}
//put file data into array
fscanf(fptr, "%d", Size);
array = malloc((*Size)*(sizeof(long)));
while(fscanf(fptr,"%li", &num) == 1) {
array[i] = num;
i++;
}
fclose(fptr);
return array;
}
//save file function
int Save_File(char *Filename, long *Array, int Size) {
if(Filename == NULL) {
fprintf(stdout, "\nNo output filename specified");
return -1;
}
if(Array == NULL) {
fprintf(stdout, "\nNo Array");
return -1;
}
FILE *fptr = NULL;
int i = 0;
int count = 0; //total number of numbers saved to file
//create file to write data into
fptr = fopen(Filename, "w");
if(fptr == NULL) {
fprintf(stdout, "\nCannot write to file");
return count;
}
//write data into file
while(Size != 0) {
fprintf(fptr, "%li", Array[i]);
fprintf(fptr, "\n");
count++;
i++;
Size--;
}
fclose(fptr);
return count;
}
//Shell Sort algorithm
void Shell_Insertion_Sort(long *Array, int Size, double *N_Comp, double *N_Move) {
//check to see if input array is null
if(Array == NULL) {
return;
}
if(Size == 0) {
fprintf(stdout, "\nArray Size is 0, please input array with elements in it.");
return;
}
int *seq1 = NULL;
int p2 = 0;
int p3 = 0;
int a2 = 0;
int a3 = 0;
int counter = 0;//tracks the last index of seq1
int gap = 0;
int i = 0;
int check = 0;
int comp = 0;
int move = 0;
long int temp = 0;
int k = 0;
int j = 0;
//check to see if array is already sorted
for(i = 0; (i < (Size - 1)) && (check == 0); i++) {
if(Array[i] > Array[i+1]) {
check = 1;
}
comp++;
}
if(check == 0) {
*N_Comp = comp;
*N_Move = move;
return;
}
//generate seq1
i = 0;
seq1 = (int*)malloc(sizeof(int)*Size);
if(seq1 == NULL) {
fprintf(stdout, "\nCannot generate seq1.");
return;
}
seq1[i] = 1;
i++;
while(seq1[i - 1] < Size) {
//printf("%d, ", seq1[i-1]);
if((seq1[p2] * 2) == (seq1[i - 1])) {
p2++;
}
if((seq1[p3] * 3) == (seq1[i - 1])) {
p3++;
}
a2 = seq1[p2] * 2;
a3 = seq1[p3] * 3;
if(a2 < a3) {
p2++;
seq1[i] = a2;
}
else {
p3++;
seq1[i] = a3;
}
if(seq1[i] > Size) {
break;
}
i++;
counter = i;
}
//iterate through seq1 in descending order
for(i = (counter - 1);i >= 0; i--) {
gap = seq1[i];
//printf("%d, ", i);
//shell sort algorithm
for(j = gap; j < Size; j++) {
temp = Array[j];
k = j;
move++;
while((k >= gap) && (Array[k-gap] > temp)) {
Array[k] = Array[k-gap];
k = k - gap;
comp++;
move++;
}
Array[k] = temp;
move++;
}
}
*N_Move = move;
*N_Comp = comp;
free(seq1);
}
//Bubble Sort Algorithm
void Improved_Bubble_Sort(long *Array, int Size, double *N_Comp, double *N_Move) {
//check to see if input array is null
if(Array == NULL) {
fprintf(stdout, "\n No input array.");
return;
}
if(Size == 0) {
fprintf(stdout, "\n Size is 0 please input array with values.");
return;
}
int move = 0;
int comp = 0;
int check = 0;
int i = 0;
//check to see if array is already sorted
for(i = 0; (i < (Size - 1)) && (check == 0); i++) {
if(Array[i] > Array[i + 1]) {
check = 1;
}
comp++;
}
if(check == 0) {
*N_Move = move;
*N_Comp = comp;
return;
}
int power = 2;//exponent for seq2 generator
int* seq2 = NULL;
int temp = 0;
int gap = 0;
int counter = 0;//holds the last index of seq2
int j = 0;
int k = 0;
int prev = Size / 1.3;
//genearte seq2 in the {N/1.3, N/(1.3)^2,...1} format
i = 0;
seq2 = (int*)malloc(sizeof(int)*Size);
if(seq2 == NULL) {
fprintf(stdout, "\nCannot allocate space for seq2");
}
seq2[i] = (int)(Size / 1.3);
while(seq2[i] != 1) {
//temp = (int)(Size / pow(1.3, power));
temp = (int)(prev / 1.3);
if((temp == 9) || (temp == 10)) {
temp = 11;
}
i++;
seq2[i] = temp;
prev = temp;
power++;
}
counter = i;
//improved bubble sort algo using seq1 for gap
for(i = 0; i < (counter + 1); i++) {
//getting the values of seq2
gap = seq2[i];
//printf("%d, ", gap);
//improved bubble sort algo
for(j = 0, k = gap; k < Size; j++, k++) {
if(Array[j] > Array[k]) {
temp = Array[k];
Array[k] = Array[j];
Array[j] = temp;
move = move + 3;
}
comp++;
}
}
//gurrantees sorting
k = 1;
int flag = 0;
for(j = 0; k < Size; j++) {
if(Array[j] > Array[k]) {
temp = Array[k];
Array[k] = Array[j];
Array[j] = temp;
move += 3;
flag = 1;
}
comp++;
k++;
}
for(i = 0; i < (Size - 1); i++) {
if(Array[i] > Array[i+1]) {
flag = 1;
break;
}
}
if(flag == 1) {
k = 1;
for(j = 0; k < Size; j++) {
if(Array[j] > Array[k]) {
temp = Array[k];
Array[k] = Array[j];
Array[j] = temp;
flag = 2;
move += 3;
}
k++;
}
comp++;
}
if(flag == 2) {
k = 1;
for(j = 0; k < Size; j++, k++) {
if(Array[j] > Array[k]) {
temp = Array[k];
Array[k] = Array[j];
Array[j] = temp;
move +=3;
}
}
comp++;
}
free(seq2);
*N_Move = move;
*N_Comp = comp;
}
void Save_Seq1(char *Filename, int Size) {
if(Filename == NULL) {
fprintf(stdout, "\nNo filename given.");
return;
}
FILE *fptr = NULL;
int i = 0;
int counter = 0;
int p2 = 0;
int p3 = 0;
int a2 = 0;
int a3 = 0;
int *seq1 = NULL;
fptr = fopen(Filename, "w");
if(fptr == NULL) {
fprintf(stdout, "\nCannot Open file.");
return;
}
i = 0;
seq1 = (int*)malloc(sizeof(int)*Size);
if(seq1 == NULL) {
fprintf(stdout, "\nCannot generate seq1.");
return;
}
seq1[i] = 1;
i++;
while(seq1[i - 1] < Size) {
//printf("%d, ", seq1[i-1]);
if((seq1[p2] * 2) == (seq1[i - 1])) {
p2++;
}
if((seq1[p3] * 3) == (seq1[i - 1])) {
p3++;
}
a2 = seq1[p2] * 2;
a3 = seq1[p3] * 3;
if(a2 < a3) {
p2++;
seq1[i] = a2;
}
else {
p3++;
seq1[i] = a3;
}
if(seq1[i] > Size) {
break;
}
i++;
counter = i;
}
while(counter != 0) {
fprintf(fptr, "%d", seq1[counter]);
fprintf(fptr, "\n");
counter--;
}
fprintf(fptr, "%d", seq1[counter]);
fclose(fptr);
free(seq1);
}
void Save_Seq2(char *Filename, int Size) {
if(Filename == NULL) {
fprintf(stdout, "\nNo filename to write too.");
return;
}
FILE *fptr = NULL;
int *seq2 = NULL;
int i = 0;
fptr = fopen(Filename, "w");
if(fptr == NULL) {
fprintf(stdout, "\nCannot Open file.");
return;
}
i = 0;
seq2 = (int*)malloc(sizeof(int)*Size);
if(seq2 == NULL) {
fprintf(stdout, "\nCannot generate seq1.");
return;
}
int temp = 0;
int counter = 0;//holds the last index of seq2
int prev = Size / 1.3;
//genearte seq2 in the {N/1.3, N/(1.3)^2,...1} format
i = 0;
seq2[i] = (int)(Size / 1.3);
while(seq2[i] != 1) {
temp = (int)(prev / 1.3);
if((temp == 9) || (temp == 10)) {
temp = 11;
}
i++;
seq2[i] = temp;
prev = temp;
}
counter = i;
for(i = 0; i < (counter + 1); i++) {
fprintf(fptr, "%d", seq2[i]);
fprintf(fptr, "\n");
}
fclose(fptr);
free(seq2);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct SBTNode
{
int data, size;
struct SBTNode *lchild, *rchild, *father;
} SBTNode;
#define ERROR 0
#define OK 1
void init_NIL();
SBTNode* init(int data, int size, SBTNode *father);
SBTNode * left_rotate(SBTNode * node);
SBTNode * right_rotate(SBTNode * node);
SBTNode* insert_tree(SBTNode *node, int data);
int delete_tree(SBTNode *node, int data);
SBTNode* search(SBTNode *node, int data);
SBTNode* predecessor(SBTNode *node);
SBTNode* successor(SBTNode *node);
SBTNode * maintain(SBTNode * node, int flag);
void remove_node(SBTNode *delete_node);
SBTNode* add_node(SBTNode *node, int data);
void clear(SBTNode *node);
void output(SBTNode *node);
|
C
|
#include<stdio.h>
int factoril(int);
int main(){
int a,fact;
for(a=1;a<=10;a++){
fact=factoril(a);
printf("factoril of %d = %d\n",a,fact);
}
}
factoril(int n){
int result;
if (n==0)
return 1;
else
result=n*factoril(n-1);
return result;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
typedef struct no{
int codigo;
char nome[30];
struct no * next;
}no;
struct no *ptr, *A, *I, *conferir;
int main()
{
setlocale(LC_ALL, "portuguese");
system("color 6");
int i, opcao, pessoas;
ptr = NULL;
A = NULL;
while(opcao != 3)
{
system("cls");
printf("1 - Cadastrar\n");
printf("2 - Exibir\n");
printf("3 - Pesquisar por nome\n");
printf("4 - Sair\n");
printf("SELECIONE UMA OPO: "); scanf("%d", &opcao);
switch(opcao)
{
case 1:
{
printf("Digite a quantidade de pessoas que deseja cadastrar: "); scanf("%d", &pessoas);
for(i=0; i<pessoas; i++)
{
printf("\tCadastro de num %d\n",i+1);
if(A == NULL){
ptr =(no*) malloc(sizeof(no));
printf("informe o Codigo. . ."); scanf("%d", &ptr ->codigo);
printf("informe o nome. . ."); scanf("%s", &ptr->nome);
A =ptr;
I = ptr;
}else{
ptr = (no*)malloc(sizeof(no));
printf("informe o codigo. . . "); scanf("%d", &ptr ->codigo);
printf("informe o nome. . . "); scanf("%s", &ptr->nome);
A->next = ptr;
ptr->next =NULL;
A=ptr;
}
}
break;
}
case 2:
{
ptr = I;
do{
printf("\n\nCodigo %d\t", ptr->codigo);
printf("Nome %s", ptr->nome);
ptr=ptr->next;
}while(ptr!=NULL);
break;
}
case 3:
{
ptr = I;
conferir =(no*) malloc(sizeof(no));
printf("Digite o nome a ser pesquisado: "); scanf("%s", &conferir->nome);
do{
if(strcmp(ptr->nome,conferir->nome) == 0)
{
printf("\n\nCodigo %d\t", ptr->codigo);
printf("Nome %s", ptr->nome);
}
ptr=ptr->next;
}while(ptr!=NULL);
break;
}
case 4:{
default:
break;
}
}
}
}
|
C
|
#include "holberton.h"
/**
* reverse_array - reverses an array
* @a: a pointer
* @n: the number of elements in the array
*
* Return: Nothing
*/
void reverse_array(int *a, int n)
{
int start = 0;
int holder;
while (start < n)
{
holder = a[n - 1];
a[n - 1] = a[start];
a[start] = holder;
start++;
n--;
}
}
|
C
|
#include "upcr.h" /* MUST come first */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <umalloc.h>
int _sizes[] = { 3, 1024, 100000, 1024, 42000, 350, 100, 80,
3,3,3,3,3,3,3,3,3,3,3,3,3,50,
2049, 4097, 9, 33, 9, 33, 9, 78934, 38496 };
/* Other size test arrays which may be interesting */
/*
int _sizes[] = { 1024, 100000, 1024, 3 };
int _sizes[] = { 7, 120546, 32165, 150, 7, 4097, 150, 7, 150, 7 };
int _sizes[] = { 150, 7, 4097, 150, 7, 150, 7, 7, 120546, 32165 };
*/
#define HEAP_SIZE (1024*1024) /* Must be larger than the sum of all _sizes in size[] */
#define SIZES_ITERS (1000000)
#define SIZES_NUM (sizeof _sizes / sizeof _sizes[0])
#define UMALLOC_PAGESIZE 4096
int verbose = 0;
void
sizes_test(umalloc_heap_t *pheap, int heapsize, int iters)
{
int i, j, start, k;
void *allocs[SIZES_NUM];
uintptr_t totsz = 0;
for (i = 0; i < iters; i++) {
/* Allocate from size array in jumbled order */
start = i % SIZES_NUM;
for (j = 0; j < SIZES_NUM; j++) {
k = (start + j) % SIZES_NUM;
totsz += _sizes[k];
allocs[j] = umalloc(pheap, _sizes[k]);
if (verbose)
printf(">>>> malloc(%d) = %p\n", _sizes[k], allocs[j]);
if (allocs[j] == NULL) {
fprintf(stderr, "ERROR Ran out of memory after %d allocations "
"(heapsize=%d,alloc'd=%lu,requested=%d)\n",
j, heapsize, (unsigned long)totsz, _sizes[k]);
abort();
}
}
/* Deallocate from size array in order */
for (j = 0; j < SIZES_NUM; j++) {
k = (start + j) % SIZES_NUM;
if (verbose)
printf("\n>>>> free(%p,%d)\n", allocs[j], _sizes[k]);
ufree(pheap, allocs[j]);
}
totsz = 0;
}
return;
}
void
twoheap_sizes_test(umalloc_heap_t *upheap, umalloc_heap_t *downheap, int iters, unsigned int seed)
{
unsigned short rand_state[3];
void *allocs[SIZES_NUM*2];
int allocwhich[SIZES_NUM*2];
int which;
int i, j, k;
int start;
umalloc_heap_t *heapptr[2];
const char *heapname[] = { "growup ", "growdown" };
heapptr[0] = upheap;
heapptr[1] = downheap;
memset(rand_state, 0, 3*sizeof(short));
memcpy(rand_state, &seed, MIN(sizeof(seed), 3*sizeof(short)));
for (i = 0; i < iters; i++) {
int allocnum[2] = { 0, 0 };
int sz;
uintptr_t totsz[2] = { 0, 0 };
start = i % SIZES_NUM;
for (j = 0; j < SIZES_NUM*2; j++) {
/* what size are we allocating */
k = (start + j) % SIZES_NUM;
sz = _sizes[k];
/* find out what heap we will be allocating from */
which = nrand48(rand_state) % 2;
/* switch heap if we are out of allocations on one of them */
if (allocnum[which] >= SIZES_NUM)
which = 1 - which;
allocwhich[j] = which;
totsz[which] += sz;
allocs[j] = umalloc(heapptr[which], sz);
if (allocs[j] == NULL) {
fprintf(stderr, "ERROR Unable to allocate %d bytes for %s heap "
"(alloc'd %s=%lu, %s=%lu bytes).\n",
sz, heapname[which], heapname[which],
(unsigned long) totsz[which], heapname[1-which],
(unsigned long) totsz[1-which]);
abort();
}
allocnum[which]++;
}
for (j = 0; j < SIZES_NUM*2; j++) {
ufree(heapptr[allocwhich[j]], allocs[j]);
}
}
}
void
limit_test(umalloc_heap_t *pheap, int heapsize)
{
char *test1, *test2, *test3;
test1 = umalloc(pheap, heapsize/4);
if (!test1) {
fprintf(stderr, "> ERROR umalloc fails to allocate 1/4 the heap!\n");
exit(-1);
}
printf("> Allocated 1/4 the heap: got addr=%p\n", test1);
test2 = umalloc(pheap, heapsize/4);
if (!test2) {
fprintf(stderr, "ERROR umalloc fails to allocate 1/2 the heap!\n");
exit(-1);
}
printf("> Allocated 1/4 the heap: got addr=%p\n", test2);
test3 = umalloc(pheap, heapsize/2 + 1);
if (test3) {
fprintf(stderr, "ERROR umalloc should have failed!\n");
exit(-1);
}
printf("> Failed to allocate 100%%+1 of the heap (good)\n");
/* If we free previous allocations, should work now */
ufree(pheap, test1);
ufree(pheap, test2);
test3 = umalloc(pheap, heapsize/2 + 1);
if (!test3) {
fprintf(stderr, "> ERROR Alloc should have worked after ufree!\n");
exit(-1);
}
printf("> Got 1/2 of heap after ufree; addr=%p\n", test3);
test1 = umalloc(pheap, heapsize/2);
if (test1) {
fprintf(stderr, "> ERROR umalloc should have failed!\n");
exit(-1);
}
printf("> Failed to allocate 100%%+ again (good)\n");
/* Should work after we double heap size */
umalloc_provide_pages(pheap, heapsize);
test2 = umalloc(pheap, heapsize/2);
if (!test2) {
fprintf(stderr, "> ERROR umalloc should have worked after provide_pages!\n");
exit(-1);
}
printf("> Allocation of 100%%+ of orig. heap OK after doubling heap size\n");
/* Free heaps before continuing */
ufree(pheap, test1);
ufree(pheap, test2);
}
int user_main(int argc, char **argv)
{ UPCR_BEGIN_FUNCTION();
int id = upcr_mythread();
umalloc_heap_t *pheap_down, *pheap_up;
size_t twoheapsz = HEAP_SIZE*2;
char * area;
int iters = SIZES_ITERS;
unsigned long seed;
int heapsize = sizeof(char) * 2 * twoheapsz;
if (argc > 1) iters = atoi(argv[1]);
seed = id + ((argc > 2) ? atoi(argv[2]) : time(NULL));
/* umalloc requires that this area be aligned to a 4096 byte
boundary */
area = (char *)UPCRI_ALIGNUP(malloc(heapsize + UMALLOC_PAGESIZE), UMALLOC_PAGESIZE);
if (!area) {
fprintf(stderr, "ERROR Malloc failed!\n");
exit(-1);
}
printf("Got heap area at addr=%p-%p of size %lu\n",
area, area + (2*twoheapsz) - 1, (unsigned long)twoheapsz * 2);
/* Sanity test, pretty average test since there is usually some waste in
* every heap allocator */
{
size_t totsz = 0;
int i;
for (i = 0; i < SIZES_NUM; i++)
totsz += _sizes[i];
if (totsz > HEAP_SIZE) {
fprintf(stderr,
"ERROR fatal test parameters: sum of sizes larger than heapsize\n");
return 1;
}
}
pheap_up = umalloc_makeheap(area, HEAP_SIZE, UMALLOC_HEAP_GROWS_UP);
pheap_down = umalloc_makeheap(area+2*twoheapsz-1, HEAP_SIZE, UMALLOC_HEAP_GROWS_DOWN);
printf("\n%i: Running limit test on growup heap\n", id); fflush(stdout);
limit_test(pheap_up, HEAP_SIZE);
printf("\n%i: Running limit test on growdown heap\n", id); fflush(stdout);
limit_test(pheap_down, HEAP_SIZE);
printf("\n%i: Running sizes test on growup heap with %d iterations\n", id, iters); fflush(stdout);
sizes_test(pheap_up, HEAP_SIZE, iters);
printf("\n%i: Running sizes test on growdown heap with %d iterations\n", id, iters); fflush(stdout);
sizes_test(pheap_down, HEAP_SIZE, iters);
printf("\n%i: Running two-heap concurrent sizes test with %d iterations (seed %lu)\n", id, iters, seed); fflush(stdout);
twoheap_sizes_test(pheap_up, pheap_down, iters, seed);
printf("%i: All tests passed\n", id); fflush(stdout);
printf("done.\n");
return 0;
}
#ifdef __BERKELEY_UPC_RUNTIME__
/* strings for upcc configuration consistency checks */
/* UPC Runtime specification expected: 3.0 */
GASNETT_IDENT(UPCRI_IdentString_foo_upc_1053613370_GASNetConfig_gen,
"$GASNetConfig: (foo.upc.w2c.c) " GASNET_CONFIG_STRING " $");
GASNETT_IDENT(UPCRI_IdentString_foo_upc_1053613370_UPCRConfig_gen,
"$UPCRConfig: (foo.upc.w2c.c) " UPCR_CONFIG_STRING UPCRI_THREADCONFIG_STR " $");
GASNETT_IDENT(UPCRI_IdentString_foo_upc_1053613370_GASNetConfig_obj,
"$GASNetConfig: (foo.o) " GASNET_CONFIG_STRING " $");
GASNETT_IDENT(UPCRI_IdentString_foo_upc_1053613370_UPCRConfig_obj,
"$UPCRConfig: (foo.o) " UPCR_CONFIG_STRING UPCRI_THREADCONFIG_STR " $");
GASNETT_IDENT(UPCRI_IdentString_foo_upc_1053613370_translator,
"$UPCTranslator: (foo.o) [written by hand for upcr interface] $");
#else
/* not using upcc - simulate it */
#include "commonlink.c"
#endif
|
C
|
void dp_putchar(char c);
void colle(int x, int y)
{
int col;
int row;
col = 1;
while (col <= y)
{
row = 1;
while (row <= x)
{
if ((col == 1) && ((row == 1) || (row == x)))
dp_putchar('A');
else if ((col == y) && ((row == 1) || (row == x)))
dp_putchar('C');
else if ((row > 1) && (row < x) && (col > 1) && (col < y))
dp_putchar(' ');
else
dp_putchar('B');
row++;
}
dp_putchar('\n');
col++;
}
}
|
C
|
/* Program to display the address
of variables and pointers*/
#include <stdio.h>
int main()
{
float input1=1.1;
float input2=2.2;
float *ptr1;
float *ptr2;
//a)
printf("%p \n %p \n", &input1, &input2);
printf("%p \n %p \n", &ptr1, &ptr2);
//b)
ptr1=&input1;
ptr2=&input2;
//c)
printf("%f \n",*ptr1);
printf("%f \n",*ptr2);
//d)
printf("%f \n",*(&ptr1) );
printf("%f \n",*(&ptr2) );
getchar();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define BIAS 0x80
#define BUFSIZE 80
#define DATANUM 1000
int main(int argc, char **argv) {
int tm1[DATANUM] = {}, tm2, amp1[DATANUM], amp2, dif, n, m, sum1 = 0, sum2 = 0;
char buf[BUFSIZE];
FILE *fp1, *fp2;
if (argc != 3) {
fprintf(stderr, "Usage: %s <file1> <file2>\n", argv[0]);
return EXIT_FAILURE;
}
fp1 = fopen(argv[1], "r");
fp2 = fopen(argv[2], "r");
for (n = 0; n <= DATANUM; n++) {
if (fgets(buf, sizeof(buf), fp1) == NULL) break;
if (buf[0] == '#') continue;
tm1[n] = atoi(strtok(buf, ","));
amp1[n] = atof(strtok(NULL, "\r\n\0"));
sum1 += (amp1[n] - BIAS) * (amp1[n] - BIAS);
}
fclose(fp1);
for (n = 0; n <= DATANUM; n++) {
if (fgets(buf, sizeof(buf), fp2) == NULL) break;
if (buf[0] == '#') continue;
tm2 = atoi(strtok(buf, ","));
amp2 = atoi(strtok(NULL, "\r\n\0"));
sum2 += (amp2 - amp1[n]) * (amp2 - amp1[n]);
}
fclose(fp2);
printf("SNR[dB]: %f\n", 10 * log10(sum1 / (double)sum2));
return EXIT_SUCCESS;
}
|
C
|
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include "mem.h"
/**
Reset the shell buffer
*/
void shell_reset_buffer() {
index_buffer = 0;
memory_set(shell_buffer, sizeof(shell_buffer), 0);
}
/**
Prints command prompt at the shell
*/
void shell_print() {
terminal_color = vga_entry_color(VGA_COLOR_LIGHT_GREY, VGA_COLOR_BLACK);
terminal_writestring(terminalprompt);
terminal_color = vga_entry_color(VGA_COLOR_LIGHT_BLUE, VGA_COLOR_BLACK);
}
/**
Handle method for keys
*/
static inline void shell_handle_key(int32_t keycode, char ch) {
if(keycode > 0 && ch > 2 && index_buffer + 1 < 200 && ch != '\n') {
terminal_putchar(ch);
shell_buffer[index_buffer] = ch;
index_buffer++;
}
if(ch == '\n') {
terminal_putchar('\n');
shell_print();
shell_reset_buffer();
}
}
|
C
|
#include "thing.h"
int main(void) {
DATA_TYPE1 data_buff1[DATA_NUM1];
int i;
int tcp_sock_bool;
int tcp_sock_double;
fd_set fds;
struct timeval time_val;
struct sockaddr_in saddr_in;
struct in_addr in_a;
for(i = 0; i < DATA_NUM1; i++) data_buff1[i] = false;
saddr_in.sin_family = AF_INET;
saddr_in.sin_port = htons(PORT);
inet_aton(IP_ADDR, &in_a);
saddr_in.sin_addr = in_a;
// PF_INET --> IPv4 протоколы Интернет
// SOCK_STREM -->
// Обеспечивает создание двусторонних надежных и последовательных потоков байтов,
// поддерживающих соединения.
// Может также поддерживаться механизм внепоточных данных.
tcp_sock_bool = socket(PF_INET, SOCK_STREAM, 0);
if(connect(tcp_sock_bool, (struct sockaddr *)&saddr_in, sizeof(saddr_in)) != -1) {
FD_ZERO(&fds);
FD_SET(tcp_sock_bool, &fds);
time_val.tv_sec = TIV_SEC;
time_val.tv_usec = 0;
if(select(tcp_sock_bool + 1, NULL, &fds, NULL, &time_val) > 0) {
i = write(tcp_sock_bool, data_buff1, sizeof(DATA_TYPE1) * DATA_NUM1);
printf("Number of send bytes = %d\n", i);
}
}
else perror("Connection to server failed");
shutdown(tcp_sock_bool, 2);
close(tcp_sock_bool);
return 0;
}
|
C
|
//----------------------------------------------------------------------------
// 프로그램명 : PHan_Lib.c
//
// 만든이 : Cho Han Cheol
//
// 날 짜 : 2006.9.18
//
// 최종 수정 : 2003.9.18
//
// MPU_Type :
//
// 파일명 : PHan_Lib.c
//----------------------------------------------------------------------------
/*
*/
//----- 헤더파일 열기
//
#ifndef LIB_INCLUDE
#define PHAN_LIB_LOCAL
#define PHANFONT_LOCAL
#define PHANFONTENG_LOCAL
#include "PHan_Lib.h"
#include "PHanFont.h"
#include "PHanFontEng.h"
#include <stdio.h>
#endif
//----------------------------------------------------------------------------
//
// TITLE : PHan_CnvCodeWan2Johab
//
// WORK :
//
//----------------------------------------------------------------------------
U16 PHan_CnvCodeWan2Johab(U16 WanCode)
{
int index;
U16 hcode, lcode;
hcode = (WanCode >> 8) & 0xFF;
lcode = WanCode & 0x0ff;
index = (hcode - 0x0B0) * 94 + (lcode - 0x0A1);
return wWanToJohabTable[index];
}
//----------------------------------------------------------------------------
//
// TITLE : PHan_FontLoad
//
// WORK :
//
//----------------------------------------------------------------------------
/*----------------------------------------------------------------------*/
/* 한글 일반 폰트(24x24)를 bTemp1Font[72]에 LOAD한다. */
/*----------------------------------------------------------------------*/
U16 PHan_FontLoad( char *HanCode, PHAN_FONT_OBJ *FontPtr ) /* 한글 일반 폰트 생성 */
{
//static declaration 은 속도를 높이기 위한것임.
static U16 uChosung, uJoongsung, uJongsung, uChoType, uJooType,uJonType;
// 버퍼 초기화
memset(FontPtr->FontBuffer, 0x00, 32);
FontPtr->Code_Type = PHAN_NULL_CODE;
// 한글코드인지 감별
//
if( !HanCode[0] || HanCode[0] == 0x0A ) // 문자열 마지막
{
FontPtr->Code_Type = PHAN_END_CODE;
FontPtr->Size_Char = 1;
return PHAN_END_CODE;
}
else if( HanCode[0] & 0x80 ) // 한글 코드인경우
{
U16 utf16;
U32 char_code;
char_code = (HanCode[0]<<16) | (HanCode[1]<<8) | (HanCode[2]<<0);
//utf16 = (HanCode[0] & 0x0f) << 12 | (HanCode[1] & 0x3f) << 6 | HanCode[2] & 0x3f;
if (char_code >= 0xEAB080 && char_code <= 0xED9FB0)
//if (utf16 >= 0xAC00 && utf16 <= 0xD7FF)
{
FontPtr->Code_Type = PHAN_HANGUL_CODE;
FontPtr->Size_Char = 3;
PHan_UniFontLoad( HanCode, FontPtr );
}
else
{
FontPtr->Code_Type = PHAN_HANGUL_CODE;
FontPtr->Size_Char = 2;
PHan_HanFontLoad( HanCode, FontPtr );
}
return PHAN_HANGUL_CODE;
}
else // 영문 코드
{
FontPtr->Code_Type = PHAN_ENG_CODE;
FontPtr->Size_Char = 1;
PHan_EngFontLoad( HanCode, FontPtr );
return PHAN_ENG_CODE;
}
return FontPtr->Code_Type;
}
//----------------------------------------------------------------------------
//
// TITLE : PHan_FontLoad
//
// WORK :
//
//----------------------------------------------------------------------------
void PHan_HanFontLoad( char *HanCode, PHAN_FONT_OBJ *FontPtr ) /* 한글 일반 폰트 생성 */
{
U16 i;
U16 wHanCode;
//static declaration 은 속도를 높이기 위한것임.
static U16 uChosung, uJoongsung, uJongsung, uChoType, uJooType,uJonType;
wHanCode = (U16)HanCode[0]<<8 | (U16)HanCode[1] & 0x00FF;
//printf("%x %x %x\n", HanCode[0], HanCode[1], HanCode[2] );
wHanCode = PHan_CnvCodeWan2Johab(wHanCode);
//printf("a %x \n", wHanCode );
//seperate phoneme code
uChosung = (wHanCode>>10)&0x001F;//Chosung code
uJoongsung = (wHanCode>>5) &0x001F;//Joongsung code
uJongsung = wHanCode & 0x001F; //Jongsung code
//make font index
uChosung = ChoIdxTbl[uChosung]; //Chosung index
uJoongsung = JooIdxTbl[uJoongsung]; //Joongsung index
uJongsung = JonIdxTbl[uJongsung]; //Jongsung index
//decide a character type (몇번째 벌을 사용할지 결정)
uChoType = uJongsung ? ChoTypeCaseJongYes[uJoongsung]:ChoTypeCaseJongNo [uJoongsung];
//'ㄱ'(1) 이나 'ㅋ'(16) 인경우는
uJooType = ((uChosung == 0 || uChosung == 1 ||uChosung == 16 ) ? 0: 1) + (uJongsung ? 2: 0);
uJonType = JonType[uJoongsung];
for(i = 0; i<32; i++)
{
FontPtr->FontBuffer[i] = K_font[uChoType*20+uChosung][i];
FontPtr->FontBuffer[i] |= K_font[160 + uJooType*22+uJoongsung][i];
}
//combine Jongsung
if(uJongsung)
{
for(i = 0; i < 32; i++) FontPtr->FontBuffer[i] |= K_font[248 + uJonType*28+uJongsung][i];
}
}
//----------------------------------------------------------------------------
//
// TITLE : PHan_UniFontLoad
//
// WORK :
//
//----------------------------------------------------------------------------
void PHan_UniFontLoad( char *HanCode, PHAN_FONT_OBJ *FontPtr ) /* 한글 일반 폰트 생성 */
{
U16 i;
U16 utf16;
//static declaration 은 속도를 높이기 위한것임.
static U16 uChosung, uJoongsung, uJongsung, uChoType, uJooType,uJonType;
utf16 = (HanCode[0] & 0x0f) << 12 | (HanCode[1] & 0x3f) << 6 | HanCode[2] & 0x3f;
//seperate phoneme code
utf16 -= 0xac00;
uJongsung = utf16 % 28;
utf16 /= 28;
uJoongsung = utf16 % 21;
uChosung = utf16 / 21;
//make font index
uChosung = UniChoIdxTbl[uChosung]; //Chosung index
uJoongsung = UniJooIdxTbl[uJoongsung]; //Joongsung index
uJongsung = UniJonIdxTbl[uJongsung]; //Jongsung index
//decide a character type (몇번째 벌을 사용할지 결정)
uChoType = uJongsung ? ChoTypeCaseJongYes[uJoongsung]:ChoTypeCaseJongNo [uJoongsung];
//'ㄱ'(1) 이나 'ㅋ'(16) 인경우는
uJooType = ((uChosung == 0 || uChosung == 1 ||uChosung == 16 ) ? 0: 1) + (uJongsung ? 2: 0);
uJonType = JonType[uJoongsung];
for(i = 0; i<32; i++)
{
FontPtr->FontBuffer[i] = K_font[uChoType*20+uChosung][i];
FontPtr->FontBuffer[i] |= K_font[160 + uJooType*22+uJoongsung][i];
}
//combine Jongsung
if(uJongsung)
{
for(i = 0; i < 32; i++) FontPtr->FontBuffer[i] |= K_font[248 + uJonType*28+uJongsung][i];
}
}
//----------------------------------------------------------------------------
//
// TITLE : PHan_EngFontLoad
//
// WORK :
//
//----------------------------------------------------------------------------
void PHan_EngFontLoad( char *HanCode, PHAN_FONT_OBJ *FontPtr )
{
U16 i;
char EngCode;
EngCode = *HanCode;
EngCode -= 0x20; // FONT는 스페이스 부터 시작한다.
for ( i = 0 ; i < 16 ; i++ )
{
FontPtr->FontBuffer[ i ] = wEngFon[EngCode][i];
}
}
/*----------------------------------------------------------------------*/
/* bTemp1Font[72]에 조합한 한글 일반 폰트를 */
/* Line Image Buffer로 전송한다. */
/*----------------------------------------------------------------------*/
void PHan_MoveHanFont( char *ImageBuffer, PHAN_FONT_OBJ *FontPtr, int Xpos)
{
int i, j;
for ( j = 0 ; j < 2 ; j++ ) // 16 x 16 (2 Bytes)
{
ImageBuffer[ Xpos*2 + j ] = FontPtr->FontBuffer[i*2 +j];
}
}
void PHan_DisHanFont(PHAN_FONT_OBJ *FontPtr)
{
U16 i, j, Loop;
U16 FontSize = FontPtr->Size_Char;
for ( i = 0 ; i < 16 ; i++ ) // 16 Lines per Font/Char
{
for ( j = 0 ; j < FontSize ; j++ ) // 16 x 16 (2 Bytes)
{
for( Loop=0; Loop<8; Loop++ )
{
if( FontPtr->FontBuffer[i*FontSize +j] & (0x80>>Loop)) printf("*");
else printf(" ");
}
}
printf(" - \n");
//printf("%x\n",FontPtr->FontBuffer[i]);
}
}
|
C
|
/*
Libreria de numeros aleatorios usando shuffling.
Generadores congruentes lineales usados:
- rand() implementacion gcc
- ??
*/
#include <stdlib.h>
#include <time.h>
#include <cmath>
#define K 10000
#define M1 RAND_MAX
#define M2 RAND_MAX
#include "Generador.cpp"
using namespace std;
int i = 0;
int numbers[K];
Generador generador;
int rand_2(){
return generador.getNextNum();
}
void init_rand(char *nombreArchivo){
srand(time(NULL));
for(int j=0;j<K;j++)
numbers[j]=rand();
generador.iniciar(nombreArchivo, false);
}
double getRandNumber(){
int Yi = rand_2();
int j = ceil(K*Yi/M2);
int Zi = numbers[j];
numbers[j]=rand();
return ((double) Zi)/((double)M1);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int * take_input(int * size)
{
printf("Enter number of elements\n");
int n;
scanf("%d",&n);
int * retarr=(int*)malloc(sizeof(int)*n);
printf("Enter elements in sorted order\n");
for(int i=0;i<n;i++)
scanf("%d",&retarr[i]);
*size=n;
return(retarr);
}
int recur_bsearch(int * arr,int low,int high,int srch)
{
if(low<=high)
{
int mid=low+(high-low)/2;
int ret1=0,ret2=0;
if(arr[mid]==srch)
{
return 1;
}
else if(arr[mid]>srch)
{
ret1=recur_bsearch(arr,low,mid-1,srch);
}
else
{
ret2=recur_bsearch(arr,mid+1,high,srch);
}
if(ret1||ret2)
{
return 1;
}
}
return 0;
}
void b_search(int * arr,int size)
{
printf("Enter element to search\n");
int srch;
scanf("%d",&srch);
int found=recur_bsearch(arr,0,size-1,srch);
if(found)
printf("isPresent\n");
else
printf("isNotPresent");
}
int main()
{
int size=0;
int *arr=take_input(&size);
b_search(arr,size);
return 0;
}
|
C
|
#include <stdio.h>
int main(void) {
int hours, overtime;
float pay,total, overpay, total2;
char line[100];
printf("How many hours have worked the employee?\n");
fgets(line, sizeof(line), stdin);
sscanf(line,"%d", &hours);
printf("How much you pay per hour in dollars?(just write the number)\n");
fgets(line, sizeof(line), stdin);
sscanf(line,"%f", &pay);
total = hours * pay;
if (hours>40) {
overtime= hours-40;
overpay= overtime*1.5*pay;
total= (hours-overtime) * pay + overpay;
}
printf("The weekly payment of the employee is %f dollars \n",total);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#define D_S_MAIN 1
#define D_S 1
#if D_S
void clrscr(void);
#endif
static char daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 30, 30, 31, 30, 31}
};
int day_of_year (int year, int month, int day) {
int i, leap;
char (* ppday)[13] = daytab;
if (year < 0 || 1 > month || month > 12) return -1;
leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
if (1 > day || day > *(month + *(ppday+leap))) return -1;
for (i = 1; i < month; i++)
day += *(i + *(ppday+leap)) /*daytab[leap][i]*/;
return day;
}
int month_day (int year, int yearday, int* pmonth, int* pday) {
int i, leap;
char (* pt);
if (!pmonth || pday == NULL) return -1;
if (year < 0 || 1 > yearday || yearday > 366) return -1;
leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
pt = daytab[leap];
for (i = 1; yearday > *(pt + i); i++)
yearday -= *++pt;
*pmonth = i;
*pday = yearday;
return 0;
}
#if D_S_MAIN
int main() {
int y, m, d, dy = 138;
#if D_S
clrscr();
#endif
y = 1986;
m = 5;
d = 4;
printf("%s\n", &daytab[0][1]);
printf("The day of %04d-%02d-%02d\n is the %dth day of the year.\n",
y, m, d, day_of_year(y, m, d));
if (month_day(y, dy, &m, &d) == -1) return 1;
printf("The %dth day of the year %d is %04d-%02d-%02d.\n",
dy, y, y, m, d);
return 0;
}
#endif
|
C
|
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
void init_arr(int arr[][2]) //arr[][2]
{
int i, j;
srand(time(NULL));
for(i = 0; i < 3; i++)
{
for(j=0;j<2;j++)
{
arr[i][j] = rand() % 5 +1;
}
}
}
void print_arr(int arr[][2])//arr[3][2]
{
int i, j;
for(i = 0; i<3;i++)
{
for( j = 0; j <2; j++)
{
printf("arr[%d][%d] = %d\n ",i ,j, arr[i][j]);
}
}
}
void print_addr(int arr[][2]) //arr[][2]
{
int i , j;
printf("arr addr = 0x%x\n", arr);
for(i = 0; i<3;i++)
{
for( j = 0; j <2; j++)
{
printf("arr[%d][%d] = 0x%x\n ",i ,j, &arr[i][j]);
}
}
}
int main(void)
{
int arr[3][2] = {0};
init_arr(arr);
print_arr(arr);
print_addr(arr);
return 0;
}
|
C
|
//Description: Find Surface_Area and Volume of Cylinder
//Date: 23/09/2021
//Author : Shubham Lodha
#include<stdio.h>
#define Pi 3.14
void Cyclinder(int h,int r)
{
int ans=0;
ans=(2*Pi*r*r)+(2*r*h*Pi);
printf("Surface Area of Cyclinder is %d/n",ans);
ans=Pi*r*r*h;
printf("Volume of Cyclinder is %d/n",ans);
}
int main()
{
int h=0,r=0;
printf("Enter Height of Cylinder:");
scanf("%d",&h);
printf("Enter Radius of Cylinder:");
scanf("%d",&r);
Cyclinder(h,r);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_putnbr_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ahan <ahan@student.42seoul.kr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/05 16:25:08 by ahan #+# #+# */
/* Updated: 2020/12/05 18:29:03 by ahan ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
int chk_error_base(char *base)
{
char *chkbase;
int i_chk;
chkbase = base;
if (*base == 0 || *(base + 1) == 0)
return (0);
while (*chkbase)
{
if (*chkbase == '+' || *chkbase == '-' || *chkbase <= 32)
return (0);
i_chk = 1;
while (*(chkbase + i_chk))
{
if (*(chkbase + i_chk) == *chkbase)
return (0);
i_chk++;
}
chkbase++;
}
return (1);
}
int ft_strlen(char *str)
{
char *ptr;
int i;
ptr = str;
i = 0;
while (*ptr != 0)
{
i++;
ptr++;
}
return (i);
}
void ft_putnbr_base(int nbr, char *base)
{
unsigned int lbase;
unsigned int nbr_unsign;
if (chk_error_base(base))
{
if (nbr < 0)
{
write(1, "-", 1);
nbr_unsign = (unsigned int)(-1 * nbr);
}
else
nbr_unsign = (unsigned int)nbr;
lbase = ft_strlen(base);
if (nbr_unsign >= lbase)
{
ft_putnbr_base(nbr_unsign / lbase, base);
ft_putnbr_base(nbr_unsign % lbase, base);
}
else
{
write(1, base + nbr_unsign, 1);
}
}
}
|
C
|
#include<stdio.h>
void Display(int iNo)
{
int i=1;
/*while(i<=10)
{
printf("table %d*%d\n",iNo,i,iNo*i);
i++;
}*/
if(iNo<0)
{
iNo=-iNo;
}
for(i=1;i<=10;i++)
{
printf("%d\n",iNo*i);
}
}
int main()
{
int iValue=0;
printf("enter number");
scanf("%d",&iValue);
Display(iValue);
return 0;
}
|
C
|
#include<stdlib.h>
#include<stdio.h>
#include <time.h>
#include<pthread.h>
void * watek_klient (void * arg);
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
int l_kf;
main(){
pthread_t *tab_klient;
int *tab_klient_id;
int l_kl, l_kr, i;
printf("\nLiczba klientow: "); scanf("%d", &l_kl);
printf("\nLiczba kufli: "); scanf("%d", &l_kf);
//printf("\nLiczba kranow: "); scanf("%d", &l_kr);
l_kr = 1;
tab_klient = (pthread_t *) malloc(l_kl*sizeof(pthread_t));
tab_klient_id = (int *) malloc(l_kl*sizeof(int));
for(i=0;i<l_kl;i++) tab_klient_id[i]=i;
printf("\nOtwieramy pub (simple)!\n");
printf("\nLiczba wolnych kufli %d\n", l_kf);
for(i=0;i<l_kl;i++){
pthread_create(&tab_klient[i], NULL, watek_klient, &tab_klient_id[i]);
}
for(i=0;i<l_kl;i++){
pthread_join( tab_klient[i], NULL);
}
printf("\nZamykamy pub!\n");
}
void * watek_klient (void * arg_wsk){
int moj_id = * ((int *)arg_wsk);
int i, j=0;
int ile_musze_wypic = 2;
printf("\nKlient %d, wchodzę do pubu\n", moj_id);
for(i=0; i<ile_musze_wypic; i++){
int sucess = 0;
do{
pthread_mutex_lock(&mutex);
if(l_kf > 0){
sucess = 1;
l_kf--;
printf("\nKlient %d, wybieram kufel %d\n", moj_id);
j;
printf("\nKlient %d, nalewam z kranu %d\n", moj_id, j);
usleep(300);
pthread_mutex_unlock(&mutex);
}else{
printf("Klient %d, brak wolnych kufli\n", moj_id);
pthread_mutex_unlock(&mutex);
usleep(200);
}
}while(!sucess);
printf("\nKlient %d, pije\n", moj_id);
nanosleep((struct timespec[]){{0, 5000000L}}, NULL);
pthread_mutex_lock(&mutex);
printf("\nKlient %d, odkladam kufel\n", moj_id);
l_kf++;
pthread_mutex_unlock(&mutex);
printf("\nAktualnie kufli:%d\n", l_kf);
}
printf("\nKlient %d, wychodzę z pubu\n", moj_id);
return(NULL);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* usage.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jwhirlpo <jwhirlpo@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/28 20:47:24 by jwhirlpo #+# #+# */
/* Updated: 2021/07/28 20:48:20 by jwhirlpo ### ########.fr */
/* */
/* ************************************************************************** */
#include "philoph.h"
int ph_err_ret(char *str, t_couisine *table)
{
(void)table;
printf("%s", str);
return (1);
}
int ph_creat(t_couisine *table, int k)
{
t_phl *buf;
if (!table->phs)
{
table->phs = malloc(sizeof(t_phl));
table->phs->ind = k;
table->phs->next = NULL;
table->phs->table = table;
table->if_ded = -1;
}
else
{
buf = table->phs;
while (buf->next)
buf = buf->next;
buf->next = malloc(sizeof(t_phl));
buf->next->ind = k;
buf->next->table = table;
buf->next->next = NULL;
}
return (1);
}
int ph_fork_init(t_couisine *table)
{
int i;
t_phl *buf;
i = 0;
buf = table->phs;
table->forks = malloc(sizeof(pthread_mutex_t) * table->nu_ph);
if (!table->forks)
return (0);
while (i < table->nu_ph)
if (pthread_mutex_init(&table->forks[i++], NULL))
return (0);
while (buf->next)
{
buf->left = &table->forks[buf->ind - 1];
buf->right = &table->forks[buf->ind];
buf = buf->next;
}
buf->left = &table->forks[buf->ind - 1];
buf->right = &table->forks[0];
return (1);
}
void ph_post(char *str, t_phl *philo)
{
pthread_mutex_lock(philo->table->post);
if (philo->table->if_ded == -1)
printf("%zu %d %s\n", ph_time(philo->table, 2), philo->ind, str);
pthread_mutex_unlock(philo->table->post);
}
void *ph_pasta(void *phil)
{
t_phl *philo;
philo = (t_phl *)phil;
philo->le = ph_time(philo->table, 1);
if (philo->ind % 2 == 0)
upgrade_usleep(0.005);
philo->et = 0;
while (philo->table->if_ded != -2)
{
pthread_mutex_lock(philo->left);
ph_post("has taken a fork", philo);
pthread_mutex_lock(philo->right);
philo->le = ph_time(philo->table, 1);
ph_post("has taken a fork", philo);
ph_post("is eating", philo);
philo->et++;
upgrade_usleep(philo->table->tte);
pthread_mutex_unlock(philo->left);
pthread_mutex_unlock(philo->right);
ph_post("is sleeping", philo);
upgrade_usleep(philo->table->tts);
ph_post("is thinking", philo);
}
return (0);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#define _MAX_A 1000
#define _MAX_B 4000
#include<stdio.h>
#include<malloc.h>
int main () {
int x=0, y=0;
int a, b, c;
//freopen("input.dat", "r", stdin);
while (1) {
scanf("%d %d", &a, &b);
if (a == 0 && b == 0) break;
if ((a == 0) && (b == 0)) break;
if ((a > _MAX_A) || (a < 0) || (b > _MAX_B) || (b < 0)) {
printf("INPUT ERROR!\n");
continue;
}
c = (b - 2 * a);
x = (b - 2 * a) / 2;
y = a - x;
if (((c % 2) != 0 ) || (x < 0)||(y < 0) ){
printf("%d\n", x = 0);
continue;
}
printf("%d %d\n", x, y);
}
}
|
C
|
// Convert raw values from ADC counts to physical units
// ADC values used here are averages, max or min
// Wiring: PSP thermopile(white A- black B+)
// Wiring: PIR thermopile(black A- black C+) ; case thermistor( white D black E) ; dome thermistor (green F red G)
// Calibration constants need to be measured beforehand
double V3ref = 3300.3; // mV measured at Aref pin coming from U4 (precision V ref)
double V165ref = 1651.2; // mV measured from voltage divider on U4 to rise v_pir voltage at half-Vref
double V5ref = 5001.1; // mV measured from U3 used to measure case and dome RTDs
double Rdiv_dome = 10.0033; // kohm measured on Rb1
double Rdiv_case = 10.0038; // kohm measured on Ra1
double cal_dome = 1.003812; // calibration constant for dome for R measured correction
double cal_case = 1.005318;
double c1 = 0.0010295, c2 = 0.0002391, c3 = 0.0000001568; // RTD to temperature logarithmic constants
double theta = 5.6704E-8 ; // Stefan-Boltzmann constant W.m-2.K-4
double k = 3.5 ; // dome-case adjustment 3.5 or 4 according to PIR documentation
double max_adc = 4095.0; // adc counts according to resolution used
struct pir{ int a2,a3,a4; };
// A1 - PSP radiometer thermopile voltage - range 0-15 mV
// Amp gain measured:
// Vin <= 4mV -> Vout=VA1 = 203.12 x Vin + 11.284 & Vin > 4mV -> Vout=VA1 = 201.88 x Vin + 18.181 w/ Vin=VBA=V_PSP in mV
int short_irradiance(double adc_val){
double k_psp = 8.26E-6 ; // psp constant in V/Wm-2
double v_psp; // value determined as input coming from psp
double vread = adc_val * V3ref / max_adc ; // value read in mV
if(vread <= 700.0 ) v_psp = (vread - 12.901)/204.64;
else v_psp = (vread - 5.4963)/205.54;
int swi = v_psp / (k_psp * 1000) ; // short-wave irradiance in Wm-2 - final value as INT
return swi;
}
// A2 - PIR radiometer thermopile - range -2.5 to +2.5 mV
// Amp gain measured: Vout - V165ref = 564.93 x Vin + 90.916 in mV
double net_long(double adc_val){
double k_pir = 2.81E-6 ; // PIR constant in V/W.m-2
double v_pir;
double vread = adc_val * V3ref / max_adc ;
if(vread <= 1365.0) v_pir = ((vread - 1642.7)/563.15)-0.03;
else if((vread > 1365.0) && (vread <= 1632.0)) v_pir = ((vread - 1640.9)/554.78)-0.03;
else if(vread > 1632.0 && vread <= 1911.0) v_pir = (vread - 1621.5)/580.49;
else v_pir = (vread - 1628.6)/565.83;
double lwi = v_pir / (k_pir * 1000.0); // net long wave irradiance in Wm-2
return lwi;
}
// RTD measurement
double rtd(double adc_val, double rdiv, double cal){
double vdiv = adc_val * V3ref / ( max_adc * 1000.0); // voltage divider output read in V
double rtd = rdiv * cal * 1000.0 / ( V5ref/vdiv - 1); // resistance measured in ohms
return rtd;
}
// Temperature from RTD in Kelvin
double temp(double rtd){
return 1/( c1 + c2 * log(rtd*1000.0) + c3 * pow((log(rtd*1000.0)),3));
}
// Incoming long-wave irradiance
// A2: pir thermopile, A3: dome RTD, A4: case RTD
double long_irradiance(pir adc){
double net = net_long(adc.a2); // irradiance in Wm-2
double rtd_dome = rtd(adc.a3,Rdiv_dome,cal_dome); // rtd in ohm
double rtd_case = rtd(adc.a4,Rdiv_case,cal_case);
double td = temp(rtd_dome); // dome temperature in Kelvin
double tc = temp(rtd_case);
double lwi_in = net + theta * pow(tc,4) - k * theta * ( pow(td,4) - pow(tc,4));
return lwi_in;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ps_set_ft.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: marrodri <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/01 20:39:43 by marrodri #+# #+# */
/* Updated: 2019/10/01 20:39:45 by marrodri ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
void stb_flag(t_app **app, t_list *st_b)
{
//set the stack_b checker, if the stack b is now sorted, don't do anything
if(st_b)
{
(*app)->sort_stb_flag[0] = ch_rb_stb(st_b); //rb
(*app)->sort_stb_flag[1] = ch_rrb_stb(st_b); //rrb
(*app)->sort_stb_flag[2] = ch_next_hi_elem(st_b, *app); //sb
}
}
// REVAMP THIS
void sta_flag(t_app **app, t_list *st_a)
{
// search for any misplaced number
//if a misplace number is founded, put to the second position from the top,
//then swap the values
//same for stack b
//incase for both equal go to rra
//sa, use this after rotating, check the next one is lower than the current
(*app)->sort_sta_flag[0] = ch_ra_sta(st_a);
(*app)->sort_sta_flag[1] = ch_rra_sta(st_a);
(*app)->sort_sta_flag[2] = ch_next_low_elem(st_a);
}
void saInstrCheck(t_app **app)
{
if((*app)->sort_sta_flag[2])
{
(*app)->sort_sta_flag[0] = 0;
(*app)->sort_sta_flag[1] = 0;
}
if((*app)->sort_stb_flag[2])
{
(*app)->sort_stb_flag[0] = 0;
(*app)->sort_stb_flag[1] = 0;
}
}
//remodify this one
void rotInstrCheck(t_app **app)
{
if((*app)->sort_sta_flag[0] >= (*app)->sort_sta_flag[1] &&
(*app)->sort_sta_flag[1] > 0)
{
(*app)->sort_sta_flag[0] = 0;
}
else if ((*app)->sort_sta_flag[0] < (*app)->sort_sta_flag[1] &&
(*app)->sort_sta_flag[0] > 0)
{
(*app)->sort_sta_flag[1] = 0;
}
if((*app)->sort_stb_flag[0] >= (*app)->sort_stb_flag[1] &&
(*app)->sort_stb_flag[1] > 0)
{
(*app)->sort_stb_flag[0] = 0;
}
else if((*app)->sort_stb_flag[0] < (*app)->sort_stb_flag[1] &&
(*app)->sort_stb_flag[0] > 0)
{
(*app)->sort_stb_flag[1] = 0;
}
}
void bothInstrCheck(t_app **app)
{
int i;
i = 0;
while(i < 4)
{
if((*app)->sort_sta_flag[i] > (*app)->sort_stb_flag[i]
&& (*app)->sort_stb_flag[i] > 0)
{
(*app)->sort_sta_flag[i] = (*app)->sort_stb_flag[i];
}
else if((*app)->sort_sta_flag[i] < (*app)->sort_stb_flag[i]
&& (*app)->sort_sta_flag[i] > 0)
{
(*app)->sort_stb_flag[i] = (*app)->sort_sta_flag[i];
}
i++;
}
}
void set_sort_flag(t_app **app, t_list *st_a, t_list *st_b)
{
//if stack a has only 10 chunks, then sort the stack a properly
if (stARotSort(*app, st_a))
{
setSortedInst(app, st_a, st_b);
rotInstrCheck(app);
}
else
{
sta_flag(app, st_a);
stb_flag(app, st_b);
if((*app)->deb_flag)
{
ft_printf("======PRE INSTRUCTIONS==========\n");
print_inst(*app);
}
saInstrCheck(app);
rotInstrCheck(app);
// bothInstrCheck(app);
}
if((*app)->deb_flag)
{
ft_printf("++++++++FINAL INSTRUCTIONS+++++\n");
print_inst(*app);
}
return ;
}
|
C
|
#include "dk_tool.h"
void subtractedmatrix(int n, int matrixC[n][n], int matrixA[n][n], int matrixB[n][n])
{
int i = 0, j = 0;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
matrixC[i][j] = 0;
matrixC[i][j] = matrixA[i][j] - matrixB[i][j]; //vidnimannya matric
}
}
}
|
C
|
/*
** ops.c for bistro in /home/chapui_s/travaux/bistro
**
** Made by chapui_s
** Login <chapui_s@epitech.net>
**
** Started on Mon Oct 28 23:05:48 2013 chapui_s
** Last update Sun Nov 10 22:54:48 2013 lowik_denel
*/
#include <stdlib.h>
#include "header.h"
#include "bistromathique.h"
int prior_ops(char op_pile, char op_cur, char *ops)
{
if ((op_cur == ops[OP_MULT_IDX] || op_cur == ops[OP_DIV_IDX]
|| op_cur == ops[OP_MOD_IDX]) && (op_pile == ops[OP_PLUS_IDX]
|| op_pile == ops[OP_SUB_IDX]))
return (1);
return (0);
}
int test_if_zero(char *nb, char *base, char op, t_board *board)
{
if (*nb == base[0] || *nb == board->ops[OP_NEG_IDX])
{
while (*(nb + 1) == base[0])
nb = nb + 1;
}
if (nb[0] == base[0] && nb[1] == '\0')
{
if (op == board->ops[OP_MOD_IDX])
my_putstr("Error: Modulo by zero");
else
my_putstr("Error: Divide by zero");
return (1);
}
return (0);
}
char *do_op(char *nb1, char op, char *nb2, t_board *board)
{
char *result;
result = NULL;
if (op == board->ops[OP_PLUS_IDX])
result = inf_add(nb2, nb1, board->base, board->ops[OP_NEG_IDX]);
else if (op == board->ops[OP_MULT_IDX])
result = inf_mult(nb1, nb2, board->base, board->ops[OP_NEG_IDX]);
else if (op == board->ops[OP_SUB_IDX])
result = inf_sub(nb2, nb1, board->base, board->ops[OP_NEG_IDX]);
else if (op == board->ops[OP_DIV_IDX])
{
if (test_if_zero(nb1, board->base, op, board))
return (NULL);
result = inf_div(nb2, nb1, board->base, board->ops[OP_NEG_IDX]);
}
else if (op == board->ops[OP_MOD_IDX])
{
if (test_if_zero(nb1, board->base, op, board))
return (NULL);
result = inf_mod(nb2, nb1, board->base, board->ops[OP_NEG_IDX]);
}
else if (op == -1)
result = inf_mult("-1", nb1, board->base, board->ops[OP_NEG_IDX]);
return (result);
}
void *manage_ops(char op, t_board *board)
{
void *test_malloc;
if (board->pile_ops == NULL)
test_malloc = add_begin_ops(&(board->pile_ops), op);
else if (board->pile_ops->op == board->ops[OP_OPEN_PARENT_IDX])
test_malloc = add_begin_ops(&(board->pile_ops), op);
else if (prior_ops(board->pile_ops->op, op, board->ops) == 1)
test_malloc = add_begin_ops(&(board->pile_ops), op);
else
{
while (board->pile_ops
&& board->pile_ops->op == board->ops[OP_OPEN_PARENT_IDX])
rm_first_ops(&(board->pile_ops));
if (board->pile_calc->next)
{
test_malloc = little_calc(board);
if (test_malloc == NULL)
return (NULL);
}
test_malloc = add_begin_ops(&(board->pile_ops), op);
}
if (test_malloc == NULL)
return (NULL);
return ("1");
}
void *manage_close_parent(t_board *board)
{
void *test_malloc;
while (board->pile_ops
&& (board->pile_ops->op != board->ops[OP_OPEN_PARENT_IDX])
&& (board->pile_calc->next))
{
test_malloc = little_calc(board);
if (test_malloc == NULL)
return (NULL);
}
if (board->pile_ops->op != -1)
board->pile_ops = rm_first_ops(&(board->pile_ops));
return ("1");
}
|
C
|
#include <signal.h> /* traitement des signaux */
#include <stdio.h> /*entrées sorties */
#include <unistd.h> /*primitives de base */
int nbrecus = 0;
int nbalarm = 0;
void affsig(int signal_num) {
printf("Recpetion du dignal %d\n", signal_num);
nbrecus++;
}
void actif(int signal_num, siginfo_t *info, void *uap) {
printf("Processud de pid %d : Reception du signal %d (SIGALRM), émetteur : %d\n",
getpid(), signal_num, info->si_pid);
if (info->si_pid == 0) {
/* les SIGALRM programmés sont envoyés par le scheduler (processus 0) */
alarm(3);
nbalarm++;
} else {
nbrecus++;
}
}
int main(void) {
struct sigaction mon_action;
struct sigaction mon_action0;
int ret, i;
mon_action0.sa_handler = affsig;
for (i = 1; i <= NSIG; i++) {
ret = sigaction(i, &mon_action0, NULL);
}
mon_action.sa_sigaction = actif;
mon_action.sa_flags = SA_SIGINFO;
ret = sigaction(SIGALRM, &mon_action, NULL);
alarm(3);
while ((nbrecus != 5) && (nbalarm != 9)) {
pause();
}
printf("reçus : %d, alarm : %d\n", nbrecus, nbalarm);
return 0;
}
|
C
|
#include <stdio.h>
void rev(char *l, char *r);
int main(int argc, char *argv[]) {
char buf[] = "the world will go on forever";
char *end, *x, *y;
// Reverse the whole sentence first..
for (end = buf; *end; end++)
;
rev(buf, end - 1);
// Now swap each word within sentence...
x = buf - 1;
y = buf;
while (x++ < end) {
if (*x == '\0' || *x == ' ') {
rev(y, x - 1);
y = x + 1;
}
}
// Now print the final string....
printf("%s\n", buf);
return (0);
}
// Function to reverse a string in place...
void rev(char *l, char *r) {
char t;
while (l < r) {
t = *l;
*l++ = *r;
*r-- = t;
}
}
|
C
|
#include <stdio.h>
#include "Deque.h"
void main(void) {
Deque dq;
DqueueInit(&dq);
DQAddFirst(&dq, 1);
DQAddFirst(&dq, 2);
DQAddFirst(&dq, 3);
DQAddFirst(&dq, 4);
DQAddFirst(&dq, 5);
while (!DQIsEmpty(&dq))
{
printf("%d\n", DQRemoveFirst(&dq));
}
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include "timer.h"
int main() {
struct timespec* start = timer_start();
sleep(1);
printf("Timer %.9lf\n", timer_end(start));
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
void hantei(int a,int b);
int win,lose,draw;
int main(void){
int my_hand,pc_hand;
char buf[10];
char word[10];
char yn[10];
win = lose = draw = 0;
srand((unsigned)time(NULL));
while(1){
pc_hand = rand()%3;
printf("..........................\n");
printf("Paper-Rock-Scissors\n");
printf("Your choice? <Rock: 0, Scissors: 1,Paper: 2>:");
fgets(buf,sizeof(buf),stdin);
sscanf(buf,"%d",&my_hand);
hantei(my_hand,pc_hand);
printf("My hand : %d,PC hand : %d",my_hand,pc_hand);
printf("Win %d,Lose %d,Draw %d\n",win,lose,draw);
printf("Continue?<Yes...y,No...n>:");
fgets(buf,sizeof(buf),stdin);
sscanf(buf,"%s",yn);
if(strcmp(yn,"n")==0)break;
}
return 0;
}
void hantei(int m_h,int p_h){
if(m_h < 0 || m_h > 2)return;
if(m_h==p_h){
draw++;
return;
}
if(m_h==2){
if(p_h==0)
win++;
else
lose++;
return;
}
if(m_h < p_h){
lose++;
} else {
win++;
}
return;
}
|
C
|
#include<stdio.h>
int main(){
int cases;
int W,diff,x,y;
char close;
scanf("%d",&cases);
while(cases--){
scanf("%d",&W);
close=1;
scanf("%d%d",&x,&y);
diff=x-y;
while(--W){
scanf("%d%d",&x,&y);
if(x-y!=diff) close=0;
}
if(close) puts("yes");
else puts("no");
if(cases) puts("");
}
return 0;
}
|
C
|
#ifndef LIST_H
#define LIST_H
#include "thread.h"
#include <sys/queue.h>
#define FOR_EACH(E, L) for (E = L->cqh_first; E != (void*)L; E = E->pointers.cqe_next)
struct thread_s;
typedef struct list_s list_t;
typedef struct thread_s *element_t;
CIRCLEQ_HEAD(list_s, thread_s);
/*
* Alloue et initialise une liste
*/
list_t *new_list();
/*
* Indique si la liste est vide
*/
int is_empty(list_t *l);
/*
* Retourne le premier élément dont l'adresse est égale à data ou NULL
*/
int is_in_list(list_t *l, element_t el);
/*
* Retourne le premier élément de la liste
*/
element_t get_head(list_t *l);
/*
* Insère un élément en début de liste
*/
void insert_in_list_head(list_t *l, element_t e);
/*
* Copie et insère un nouvel élément en fin de liste
*/
void insert_in_list_tail(list_t *l, element_t e);
/*
* Retire un élément de la liste et, si free_method est non nulle, libère sa mémoire
*/
void remove_from_list(list_t *l, element_t e, void(free_method)(element_t));
/*
* Libère une liste et, si free_method est non nulle, ses éléments
*/
void free_list(list_t *l, void(free_method)(element_t));
#endif
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
//int main()
//{
// int a = 10;
// int* p = &a;//ָ
// return 0;
//}
//int main()
//{
// /*printf("%d\n", sizeof(char*));
// printf("%d\n", sizeof(int*));
// printf("%d\n", sizeof(short*));
// printf("%d\n", sizeof(double*));*/
// int a = 0x11223344;
// int* pa = &a;
// char* pc = &a;
// printf("%p\n", pa);
// printf("%p\n", pa + 1);
// printf("%p\n", pc);
// printf("%p\n", pc + 1);
// return 0;
//}
//int main()
//{
// int arr[10] = { 0 };
// int* p = &arr;
// int i = 0;
// for (i = 0;i < 10;i++)
// {
// *(p + i) = 1;
// }
// return 0;
//}
//int main()
//{
// int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
// int sz = sizeof(arr) / sizeof(arr[0]);
// int i = 0;
// int* p = arr;
// /*for (i = 0;i < sz;i++)
// {
// printf("%d ", *p);
// p++;
// }*/
// for (i = 0;i < 5;i++)
// {
// printf("%d ", *p);
// p+=2;
// }
// return 0;
//}
//int main()
//{
// int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
// int sz = sizeof(arr) / sizeof(arr[0]);
// int i = 0;
// int* p = &arr[9];
// for (i = 0;i < 5;i++)
// {
// printf("%d ", *p);
// p -= 2;
// }
// return 0;
//}
//int main()
//{
// char ch[5] = { 0 };
// int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
// printf("%d\n", &arr[9] - &arr[0]);//ָָָмԪظ
// printf("%d\n", &arr[0] - &arr[9]);//-9
// //printf("%d\n", &arr[9] - &ch[0]);//err ӡchar *int *Ͳ
// return 0;
//}
//int my_strlen(char* arr)
//{
// char* start = arr;
// char* end = arr;
// while (*end != '\0')
// {
// end++;
// }
// return end - start;
//}
//int main()
//{
// char arr[] = "hello" ;
// int len = my_strlen(arr);
// printf("%d\n", len);
// return 0;
//}
//int main()
//{
// int a = 10;
// int* pa = &a;
// int** ppa = &pa;//ppaǶָ
// **ppa = 20;
// printf("%d\n", **ppa);
// printf("%d\n", a);
//
// //int*** pppa = &ppa;//ָ
// //...
// return 0;
//}
//ָ - - ָ
//ָ - ָ
int main()
{
int a = 10;
int b = 20;
int c = 30;
//int* pa = &a;
//int* pb = &b;
//int* pc = &c;
// -
//ַ - ַ
//ָ - ָ
//int arr1[10];
int* arr2[3] = { &a, &b, &c };//ָ
int i = 0;
for (i = 0;i < 3;i++)
{
printf("%d ", *(arr2[i]) );
}
return 0;
}
|
C
|
#include <stdio.h>
/* Ϣ */
char* errmsg[] = {
/* 0 */ "No error",
/* 1 */ "ʱʼС",
/* 2 */ "ʱֱСڵ",
/* 3 */ "ʱСڵ",
/* 4 */ "ʱСڵ",
/* 5 */ "ʱӹٶСڵ",
/* 6 */ "ʱµٶСڵ",
/* 7 */ "ʱ̧Сڵ",
/* 8 */ "ʱȫ߶Сڵ",
/* 9 */ "ӹʱӹСڵ",
/* 10 */ "ӹʱӹС",
/* 11 */ "ӹʱֱСڵ",
/* 12 */ "ӹʱǶСڵ",
/* 13 */ "ӹʱٶСڵ",
/* 14 */ "ӹʱȫ߶Сڵ",
/* 15 */ "ǼӹʱӹСڵ",
/* 16 */ "ǼӹʱֱСڵ",
/* 17 */ "ǼӹʱٶСڵ",
/* 18 */ "Ǽӹʱȫ߶Сڵ",
/* 19 */ "ӹʱ뾶Сڵ",
/* 20 */ "ʱ״뾶",
/* 21 */ "ӹʱ״뾶",
/* 22 */ "Ǽӹʱ״뾶",
/* 23 */ "ʱڵֱ",
/* 24 */ "ʱʼȴ",
/* 25 */ "ӹʱʼǶȲ0~90ȷΧ",
};
/* ȫֱ */
long errno = 0;
/* ӡϢ */
void perr()
{
if (errno > 0)
{
printf("Error: %s\n", errmsg[errno]);
getchar();
exit();
}
}
|
C
|
#include <curses.h>
#include <stdlib.h>
void fire();
int width, height;
WINDOW *wnd;
int main() {
// main initialization (FIRST LINE!)
wnd = initscr();
// do not echo text back when a key is typed
noecho();
// getch() times out after 150ms
timeout(150);
// turn off cursor display
curs_set(0);
// enable CTRL + C
cbreak();
// turn on colors
start_color();
// init color pairs (cannot change 0)
init_pair(1, COLOR_BLACK, COLOR_WHITE);
init_pair(2, COLOR_BLACK, COLOR_YELLOW);
init_pair(3, COLOR_BLACK, COLOR_RED);
char keyboard = 0;
// loop until ESC (ASCII 27) is pressed
while (keyboard != 27) {
// grab window width and height as it is changed
getmaxyx(wnd, height, width);
// clear screen should be BEFORE drawing
clear();
// draw fire at col 0, row height-1 width, at 15 characters high
fire(0, height - 1, width, 15);
// grab the user input
// should be BELOW drawing otherwise there will be a flicker!
keyboard = getch();
// refresh the screen, should be last line in loop
refresh();
}
// ALWAYS INCLUDE
endwin();
return 0;
}
void fire(int x, int y, int w, int h) {
int i, j, rn;
// draw fire base
for (i = 0; i < w; i++) {
// determine a random height for flame column
rn = (rand() % h) + 3;
// draw column
for (j = 0; j < rn; j++) {
// bottom of the flame should be all 3 colors
// middle of flame should be yellow and red
// top should be red
if (j > rn * 0.5)
attron(COLOR_PAIR(3)); // draw red if 50% up column
else if (j > rn * 0.2)
attron(COLOR_PAIR(2)); // draw yellow at 20%
else
attron(COLOR_PAIR(1)); // else draw white
// embers, draw gaps in flame
if (rand() % (j + 1) < h * 0.4) // if the column is 40% up, small chance
// to disconnect flame
mvprintw(y - j, x + i, " ");
}
}
return;
}
|
C
|
/*Program to calculate power of a value*/
#include<stdio.h>
#include<conio.h>
main()
{
int x,y;
long pow,power();
scanf("%d%d",&x,&y);
pow=power(x,y);
printf("%d to the power %d=%d",x,y,pow);
getch();
}
long power(int x,int y)
{
int i;
long p=1;
for (i=1;i<=y;i++)
p=p*x;
return (p);
}
|
C
|
#include <stdio.h>
double f(double x){
double ret;
ret = 4.0 / (x*x + 1.0);
return ret;
}
|
C
|
#include <string.h>
#include<unistd.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
char *ma_function(char *to_find, char *src, int *a, int *b, int *p)
{
if(to_find[*b] == '\0')
{
while(src[*p])
{
ft_putchar(src[*p]);
*p= *p + 1; //increment pointeur
}
return (src[*a]);
}
}
char *ft_strstr (char *src, char *to_find)
{
int a;
int b;
int p;
a = 0;
b = 0;
p = 0;
if (to_find[0] == '\0')
return (str);
while(src[a] && to_find[b])
{
/*
** scr[a] = *(src + a) -> scr[a] est d'avantage apprecié car sinon
** il risque de ne pas compiler.
*/
if((src[a] != '\0') && (src[a] == to_find[b]))
{
p = a;
while(src[p + b] == to_find[b])
{
b++;
}
ma_function(to_find,src, &a, &b, &p);
b = 0;
}
a++;
}
return 0;
}
int main() {
char *src = "bhcbdspapaKHKpapaiDSK";
char *to_find = "papai";
*ft_strstr (src, to_find);
return 0;
}
|
C
|
#include <stdio.h>
int main() {
int t, _t;
scanf("%d", &t);
for ( _t = 0; _t < t; ++_t ) {
int a, b, k;
scanf("%d %d %d", &a, &b, &k);
int c = 0;
int i, j;
for ( i = 0; i < a; ++i )
for ( j = 0; j < b; ++j )
if ( (i & j) < k )
++c;
printf("Case #%d: %d\n", _t+1, c);
}
return 0;
}
|
C
|
#include <pthread.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <pthread.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <signal.h>
#include "data_structs_defs.h"
#define UNIX_MODE 0
#define NET_MODE 1
#define DEBUGPRINT 1
struct sockaddr_un unixSockStruct;
struct sockaddr_in netSockStruct;
bool iCanLive=true;
void signalHldr(int iSig)
{
iCanLive=false;
}
uint32_t parseIPV4string(char* ipAddress) {
char ipbytes[4];
sscanf(ipAddress, "%uhh.%uhh.%uhh.%uhh", &ipbytes[3], &ipbytes[2], &ipbytes[1], &ipbytes[0]);
return ipbytes[0] | ipbytes[1] << 8 | ipbytes[2] << 16 | ipbytes[3] << 24;
}
void live(char* sMyName, int mySockFd);
void initUnix(char* sMyName,char* sUnixSocketName)
{
printf("Activating client with name '%s' and unix socket name '%s'\n",sMyName,sUnixSocketName);
int mySockFd=socket(AF_UNIX,SOCK_DGRAM ,0);
if(mySockFd<0) {perror("error on creating my socket(unix) "); exit(-1);}
unixSockStruct.sun_family=AF_UNIX;
strcpy(unixSockStruct.sun_path,sUnixSocketName);
int iRet=connect(mySockFd,(struct sockaddr*)&unixSockStruct,sizeof(struct sockaddr_un));
printf("connetion Accepted\n");
if(iRet<0) {perror("error on connect on unix socket ");exit(-1);}
live(sMyName,mySockFd);
}
void initNet(char* sMyName, char* sIpAdress,short iPort)
{
printf("Activating client with name '%s' and ip: %s and port: %d\n",sMyName,sIpAdress,iPort);
struct in_addr targetAddres;
if(inet_aton(sIpAdress,&targetAddres)==0) {printf("fail on getting ip Addres from string literal(%s)\n",sIpAdress); exit(-1);}
if(iPort<1024)
{
printf("specify port ABOVE 1024\n");
exit(-1);
}
netSockStruct.sin_family=AF_INET;
netSockStruct.sin_port=htons(iPort);
netSockStruct.sin_addr=targetAddres;
int mySockFd=socket(AF_INET,SOCK_DGRAM,0);
if(mySockFd<0) {perror("error on creating my socket(net) "); exit(-1);}
if(connect(mySockFd,(struct sockaddr*)&netSockStruct,sizeof(struct sockaddr_in))<0) {perror("error on connect on net socket ");exit(-1);}
live(sMyName,mySockFd);
}
void live(char* sMyName, int mySockFd)
{
message msg;
msg.m_iClientId=0;
msg.m_length=strlen(sMyName);
msg.m_operationId=0;
msg.m_type=I_LIVE;
strcpy(msg.m_message,sMyName);
int iRet;
printf("trying to send welcom message\n");
iRet=write(mySockFd,&msg,sizeof(message));
if(iRet<0) {perror("fail on sending welcome message, exting ");exit(-1);}
printf("trying to read ACCepred/Denied message\n");
iRet=read(mySockFd,&msg,sizeof(message));
printf("succesfully read welcomeMessage\n");
if(iRet<0) {perror("fail on reading accept/denied, exting ");exit(-1);}
if(msg.m_type==DECLINED)
{
printf("i was declined :( :( :( \n");
if(close(mySockFd)<0) {perror("error on close");}
exit(-1);
}
printf("i was accepted ^^\n");
while (iCanLive)
{
iRet=read(mySockFd,&msg,sizeof(message));
if(msg.m_type!=OPERATOR_ADD &&msg.m_type!=OPERATOR_DIV &&msg.m_type!=OPERATOR_MUL &&msg.m_type!=OPERATOR_SUB &&msg.m_type!=I_LIVE &&msg.m_type!=POKE &&msg.m_type!=ACCEPTED &&msg.m_type!=DECLINED &&msg.m_type!=ANSWER &&msg.m_type!=LOGOUT)
{
#ifdef DEBUGPRINT
printf("got unexcpected message of type:%d, ignoring...\n",msg.m_type);
continue;
#endif // DEBUGPRINT
}
if(iRet<0)
{
//if(errno==EINTR) break;
perror("fail on reading causal message, exting ");
exit(-1);
}
if(msg.m_type==POKE)
{
iRet=write(mySockFd,&msg,sizeof(message)); // re send message
if(iRet<0) {perror("fail on sending welcome message, exting ");exit(-1);}
continue;
}
if(msg.m_type!=OPERATOR_ADD && msg.m_type!=OPERATOR_SUB && msg.m_type!=OPERATOR_MUL && msg.m_type!=OPERATOR_DIV )
{
#ifdef DEBUGPRINT
printf("unexcpected message type :%d\n",msg.m_type);
#endif // DEBUGPRINT
continue;
}
if(msg.m_length!=sizeof(double)*2)
{
#ifdef DEBUGPRINT
printf("unexcpcted messega with operator type(%d), and invalid length %d (should be %d)\n",msg.m_type,msg.m_length,sizeof(double)*2);
#endif // DEBUGPRINT
continue;
}
double args[2];
double* dP=(double*) msg.m_message;
args[0]=*dP;
args[1]=*(dP+1);
double out;
switch(msg.m_type)
{
case OPERATOR_ADD:
out=args[1]+args[0];
break;
case OPERATOR_SUB:
out=args[0]-args[1];
break;
case OPERATOR_MUL:
out=args[0]*args[1];
break;
case OPERATOR_DIV:
if(args[1]==0) {out=0;break;}
out=args[0]/args[1];
break;
default:
printf("in default statment, where it cannot be\n");
}
*((double *)msg.m_message)=out;
#ifdef DEBUGPRINT_
printf("tried to inser out into message with outcome %f\n",msg.m_message);
#endif // DEBUGPRINT
msg.m_length=sizeof(double);
msg.m_type=ANSWER;
iRet=write(mySockFd,&msg,sizeof(message)); // re send message
if(iRet<0) {perror("fail on sending ANSWER message, exting ");exit(-1);}
}
clearMessage(&msg);
msg.m_type=LOGOUT;
int iErrors=0;
if(write(mySockFd,&msg,sizeof(message))<0) {perror("fail on sending logout");iErrors++;}
if(close(mySockFd)<0) {perror("error on close");iErrors++;}
if(iErrors==0)
{
printf("logged out succesfuly\n");
}
}
/*
./client name local /tmp/hue.sock
./client name net 192.0.0.0 3876
*/
void printParseError(const char* errmsg)
{
printf("[%s]Error on run info should look like\n./client name local /tmp/hue.sock\nor\n./client name net 127.0.0.1 3876\n",errmsg);
exit(-1);
}
int main(int args, char* argv[])
{
printf("DTGRAM VERSION ");
byte type;
signal(SIGINT,signalHldr);
if(args==4)
{
type=UNIX_MODE;
if(argv[2][0]!='l')
{
printParseError("3 arguments given, yet type not local");
}
if(strlen(argv[3])>=MAX_UNIX_SOCKET_NAME_LEN-1)
{
printParseError("unix socket name too long");
}
}
else if(args==5)
{
type=NET_MODE;
if(argv[2][0]!='n')
{
printParseError("4 arguments given, yet type not net");
}
}
else
{
printParseError("invalid number of arguments");
}
if(strlen(argv[1])>=MAX_CLIENT_NAME_LEN-1)
{
printParseError("Client name too long");
}
if(type==NET_MODE)
{
initNet(argv[1],argv[3],atoi(argv[4]));
}
if(type==UNIX_MODE)
{
initUnix(argv[1],argv[3]);
}
printf("Hello world!\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#define MAX_SIZE 10
#define bound pow(2.0, 127)
#define ZERO 1e-9 /* X is considered to be 0 if |X|<ZERO */
void swap(double *a, double *b)
{
double temp = *a;
*a = *b;
*b = temp;
}
int JudgeMatrix(int n,double a[][MAX_SIZE])
{
double b[MAX_SIZE][MAX_SIZE];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
b[i][j] = a[i][j];
for (int i = 0; i < n; i++)
{
int flag = -1;
for (int j = i; j < n; j++)
{
if (fabs(b[j][i]) > ZERO)
{
flag = j;
break;
}
}
if (flag == -1)
return 0;
else
{
for (int j = 0; j < n; j++)
swap(&b[i][j], &b[flag][j]);
}
for (int j = i + 1; j < n; j++)
for (int k = n - 1; k >= 0; k--)
{
b[j][k] -= b[i][k] * b[j][i] / b[i][i];
}
}
return 1;
}
void TransMatrix(int n, double a[][MAX_SIZE], double b[])
{
for (int i = 0; i < n; i++)
{
double maxRow = fabs(a[i][i]);
int flag = i;
for (int j = i; j < n; j++)
{
if (fabs(a[j][i]) > maxRow)
{
maxRow = fabs(a[j][i]);
flag = j;
}
}
if (maxRow>ZERO&&flag > i)
{
for (int j = 0; j < n; j++)
{
swap(&a[i][j], &a[flag][j]);
}
swap(&b[i], &b[flag]);
}
else if (maxRow < ZERO)
{
maxRow = fabs(a[0][i]);
flag = 0;
for (int j = 0; j < i; j++)
{
if (fabs(a[j][i]) > maxRow)
{
maxRow = fabs(a[j][i]);
flag = j;
}
}
if (maxRow>ZERO)
{
for (int j = 0; j < n; j++)
{
a[i][j] += a[flag][j];
}
b[i] += b[flag];
}
}
}
}
int Jacobi(int n, double a[][MAX_SIZE], double b[], double x[], double TOL, int MAXN)
{
if (JudgeMatrix(n, a) == 0)
return -1;
TransMatrix(n, a, b);
double y[MAX_SIZE] = { 0 };
int k = 1;
while (k <= MAXN)
{
for (int i = 0; i < n; i++)
{
y[i] = b[i]/a[i][i];
for (int j = 0; j < n; j++)
{
if (j != i)
{
y[i] -= x[j] * a[i][j]/a[i][i];
}
}
if (fabs(y[i]) > bound)
return -2;
}
//judge if this method has succeed
double max = 0;
for (int i = 0; i < n; i++)
{
if (fabs(y[i] - x[i])>max)
max = fabs(y[i] - x[i]);
}
if (max < TOL)
{
return k;
}
for (int i = 0; i < n; i++)
x[i] = y[i];
k++;
}
return 0;
}
int Gauss_Seidel(int n, double a[][MAX_SIZE], double b[], double x[], double TOL, int MAXN)
{
if (JudgeMatrix(n, a) == 0)
return -1;
TransMatrix(n, a, b);
int k = 1;
while (k <= MAXN)
{
double max = 0;
for (int i = 0; i < n; i++)
{
double sum = 0;
for (int j = 0; j < n; j++)
{
if (j != i)
{
sum += a[i][j] * x[j];
}
}
double temp = (b[i] - sum) / a[i][i];
if (fabs(temp - x[i])>max)
max = fabs(temp - x[i]);
x[i] = temp;
if (fabs(x[i]) > bound)
return -2;
}
if (max < TOL)
return k;
k++;
}
return 0;
}
int main()
{
freopen("1.in", "r", stdin);
freopen("1.out", "w", stdout);
int n, MAXN, i, j, k;
double a[MAX_SIZE][MAX_SIZE], b[MAX_SIZE], x[MAX_SIZE];
double TOL;
scanf("%d", &n);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
scanf("%lf", &a[i][j]);
scanf("%lf", &b[i]);
}
scanf("%lf %d", &TOL, &MAXN);
printf("Result of Jacobi method:\n");
for (i = 0; i < n; i++)
x[i] = 0.0;
k = Jacobi(n, a, b, x, TOL, MAXN);
switch (k) {
case -2:
printf("No convergence.\n");
break;
case -1:
printf("Matrix has a zero column. No unique solution exists.\n");
break;
case 0:
printf("Maximum number of iterations exceeded.\n");
break;
default:
printf("no_iteration = %d\n", k);
for (j = 0; j < n; j++)
printf("%.8f\n", x[j]);
break;
}
printf("Result of Gauss-Seidel method:\n");
for (i = 0; i < n; i++)
x[i] = 0.0;
k = Gauss_Seidel(n, a, b, x, TOL, MAXN);
switch (k) {
case -2:
printf("No convergence.\n");
break;
case -1:
printf("Matrix has a zero column. No unique solution exists.\n");
break;
case 0:
printf("Maximum number of iterations exceeded.\n");
break;
default:
printf("no_iteration = %d\n", k);
for (j = 0; j < n; j++)
printf("%.8f\n", x[j]);
break;
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct student
{
int roll;
char name[20];
int yr;
}stud[100];
int main()
{
int i,n,r,y,j=0,k;
printf("Enter number of students");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nInformation about student %d\n",i);
printf("Enter roll number = ");
scanf("%d",&stud[i].roll);
printf("Enter year of admission = ");
scanf("%d",&stud[i].yr);
printf("Enter the name of the student = ");
scanf("%s",stud[i].name);
}
printf("\nNow we are going to draw the info\n");
printf("Enter the roll no.");
scanf("%d",&r);
printf("Enter year of admission");
scanf("%d",&y);
for(i=1;i<=n;i++)
{
if(r==stud[i].roll && y==stud[i].yr)
{
++j;
for(k=0;k<j;k++)
{
printf("Name of the student = %s",stud[i].name);
}
}
}
return 0;
}
|
C
|
/*
============================================================================
Name : estrutura_exe_02.c
Grupo : Eduardo Ferreira, Caroline e Edvar
Description : exerccio 02
============================================================================
Agora faa os exerccios abaixo onde cada programa deve executar os seguintes passos:
1 - Declarar o tipo abstrato de dados;
2 - Criar uma varivel do tipo abstrato de dados;
3 - Ler os dados do teclado e preencher os campos da varivel;
4 - Exibir na tela os campos preenchidos da varivel do tipo abstrato de dados.
Construir um programa em Linguagem C que implemente uma estrutura pedido( struct pedido ), permitindo o cadastro e exibio
com os seguintes campos:
Pedido
nome-cliente
telefone
endereco ( deve ser declarado um tipo abstrato para endereco )
logradouro
numero
bairro
complemento
itens[10] ( Item deve ser declarado um tipo abstrato para item contendo os campos sabor,
tamanho e quantidade )
sabor
tamanho
quantidade
pagamento ( deve ser declarado um tipo abstrato para pagamento contendo os campos forma
de pagamento e valor do pedido )
forma de pagamento
valor-pedido
*/
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i, qtd;
struct pedido {
char nome[50];
unsigned long int telefone;
struct endereco {
char logradouro[80], bairro[20], complemento[20];
unsigned int numero;
}add;
struct itens {
char sabor[50];
unsigned int tamanho, quantidade;
}its[10];
struct pagamento {
char formapgto[50];
unsigned int valor;
}pgto;
}P;
puts ("Cadastro de Pedidos");
puts ("Escreva seu nome ____________:");
gets(P.nome);
//getchar();
puts ("Escreva seu endereco:");
puts ("Rua _________________________:");
scanf("%s",P.add.logradouro);
getchar();
puts ("Numero ______________________:");
scanf("%d", &P.add.numero);
getchar();
puts ("complemento _________________:");
// scanf("%s",P.add.complemento);
// getchar();
gets (P.add.complemento);
puts ("bairro ______________________:");
scanf("%s",P.add.bairro);
getchar();
puts ("Escolha quantos itens _______:");
scanf("%d", &qtd);
for(i=0;i<qtd;i++){
puts ("Escreva o sabor desejado_____:");
scanf("%s", P.its[i].sabor);
puts ("Escreva o comprimento desejado___:");
scanf("%d",&P.its[i].tamanho);
puts ("Escreva a quantidade desejada:");
scanf("%d", &P.its[i].quantidade);
}
puts ("Escreva a forma de pagamento_:");
scanf("%s", P.pgto.formapgto);
getchar();
puts ("Escreva o valor total________:");
scanf("%d", &P.pgto.valor);
getchar();
puts ("\n\nCadastro Realizado com sucesso!\n");
printf ("Nome: %s\n",P.nome);
printf ("Rua: %s\n",P.add.logradouro);
printf ("Complemento: %s\n", P.add.complemento);
printf ("Numero %d\n", P.add.numero);
printf ("Bairro: %s\n",P.add.bairro);
for(i=0;i<qtd;i++){
printf("Sabor: %s\n", P.its[i].sabor);
printf("Tamanho: %d\n", P.its[i].tamanho);
printf("Quantidade: %d\n", P.its[i].quantidade);
}
printf("Forma de pagamento : %s", P.pgto.formapgto);
printf("Valor total: %d\n", P.pgto.valor);
puts("Muito Obrigado!");
return 0;
}
|
C
|
#include <stdio.h>
#include<string.h>
int printRepeat(char a,int size);
int printWithSpace(char column[],int size);
int findMaxLength(char name[][10]);
int main()
{
char name[][10]={"abvnnc","xyz","ws"};
char age[][3]={"10","9","13"};
char place[][10]={"abvnnc","xyz","ws"};
int max= findMaxLength(name);
int maxPlace = findMaxLength(place);
int columnSize[3] = { max + 2 , 5, maxPlace + 2 };
char colum[][10]={"name","age", "place"};
int tableWidth = max + 2 + 5 + maxPlace + 3;
int size=3;
int len=strlen(name[2]);
int count=0;
int i, j;
for (i = 0; i < size + 4; i++)
{
int len=strlen(name[count]);
if(!(i==0 || i==2 || i==size+3))
{
printf("|");
}
else
{
printf(" ");
}
for (j = 0; j < 3; j++)
{
if(i==0 || i==2 || i==size+3)
{
printRepeat("_", columnSize[j]+1);
}
else if(i == 1)
{
printWithSpace(colum[j], columnSize[j]);
printf("|");
}
else
{
// printf("%s",name[i]);
if( j ==0 )
{
printWithSpace(name[i-3], columnSize[j]);
}
if(j == 1)
{
printWithSpace(age[i-3], columnSize[j]);
}
if(j == 2)
{
printWithSpace(place[i-3], columnSize[j]);
}
printf("|");
}
}
printf("\n");
}
return 0;
}
int printRepeat(char a,int size)
{
int s;
for(s=0;s<size;s++)
{
printf("_");
}
return 0;
}
int printWithSpace(char column[],int size)
{
int j;
int len=strlen(column);
printf("%s",column);
for(j=0;j<size-len; j++)
{
printf(" ");
}
return 0;
}
int findMaxLength(char name[][10])
{
int max=0, i;
for (i = 0; i < 3; i++)
{
int len=strlen(name[i]);
if(max<len)
{
max=len;
}
}
if(max<4){
max=4;
}
return max;
}
|
C
|
#include<stdio.h>
int nzd(int n, int m);
int main() {
int n, m;
printf("Unesite broj n i m:\n");
scanf("%d%d", &n, &m);
printf("NZD je:%d\n", nzd(n, m));
return 0;
}
int nzd(int n, int m) {
if (n % m == 0)
return m;
else
nzd(m, n % m);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* test.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: evgenkarlson <RTFM@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/14 12:33:14 by evgenkarlson #+# #+# */
/* Updated: 2020/11/19 17:52:21 by evgenkarlson ### ########.fr */
/* */
/* ************************************************************************** */
/* ************************************************************************** */
/* команда для компиляции и одновременного запуска */
/* */
/* gcc -Wall -Werror -Wextra test.c && chmod +x ./a.out && ./a.out */
/* ************************************************************************** */
#include <unistd.h>
#include <stdlib.h>
#include "ft_btree.h"
void ft_putchar(char c)
{
write(1, &c, 1);
}
/* ************************************************************************** */
void ft_putstr(char *str)
{
int i;
i = 0;
while (*(str + i))
i++;
write(1, str, i);
}
/* ************************************************************************** */
t_btree *btree_create_node(void *item)
{
t_btree *tree;
if ((tree = (t_btree *)malloc(sizeof(t_btree))))
{
tree->left = ((void *)0);
tree->right = ((void *)0);
tree->item = item;
}
return (tree);
}
/* ************************************************************************** */
void btree_apply_infix(t_btree *root, void (*applyf)(void *))
{
if (root)
{
if (root->left)
btree_apply_infix(root->left, applyf);
(*applyf)(root->item);
if (root->right)
btree_apply_infix(root->right, applyf);
}
}
int main(void)
{
t_btree *tree_temp;
tree_temp = btree_create_node("root \n");
tree_temp->left = btree_create_node("\t one children \n");
tree_temp->right = btree_create_node("\t two children \n");
tree_temp->left->left = btree_create_node("\t\t\t one grand-children from one children \n");
tree_temp->left->right = btree_create_node("\t\t\t two grand-children from one children \n");
tree_temp->right->left = btree_create_node("\t\t\t one grand-children from two children \n");
tree_temp->right->right = btree_create_node("\t\t\t two grand-children from two children \n");
btree_apply_infix(tree_temp, (void *)&ft_putstr);
return (0);
}
/* ************************************************************************** */
/* ************************************************************************** */
|
C
|
#include "graphics.h"
void drawMenu(ALLEGRO_FONT*title_font, ALLEGRO_FONT*font, unsigned char r, unsigned char g, unsigned char b, int choice, int width, int height) {
enum { START, RANKING, HELP, EXIT };
al_draw_text(title_font, al_map_rgb(255, 255, 255), width / 2, height / 2 - 300, ALLEGRO_ALIGN_CENTER, "SNAKE");
switch (choice)
{
case START:
al_draw_text(font, al_map_rgb(r, g, b), width / 2, height / 2 - 100, ALLEGRO_ALIGN_CENTER, "START");
al_draw_text(font, al_map_rgb(255, 255, 255), width / 2, height / 2, ALLEGRO_ALIGN_CENTER, "RANKING");
al_draw_text(font, al_map_rgb(255, 255, 255), width / 2, height / 2 + 100, ALLEGRO_ALIGN_CENTER, "HELP");
al_draw_text(font, al_map_rgb(255, 255, 255), width / 2, height / 2 + 200, ALLEGRO_ALIGN_CENTER, "EXIT");
break;
case RANKING:
al_draw_text(font, al_map_rgb(255, 255, 255), width / 2, height / 2 - 100, ALLEGRO_ALIGN_CENTER, "START");
al_draw_text(font, al_map_rgb(r, g, b), width / 2, height / 2, ALLEGRO_ALIGN_CENTER, "RANKING");
al_draw_text(font, al_map_rgb(255, 255, 255), width / 2, height / 2 + 100, ALLEGRO_ALIGN_CENTER, "HELP");
al_draw_text(font, al_map_rgb(255, 255, 255), width / 2, height / 2 + 200, ALLEGRO_ALIGN_CENTER, "EXIT");
break;
case HELP:
al_draw_text(font, al_map_rgb(255, 255, 255), width / 2, height / 2 - 100, ALLEGRO_ALIGN_CENTER, "START");
al_draw_text(font, al_map_rgb(255, 255, 255), width / 2, height / 2, ALLEGRO_ALIGN_CENTER, "RANKING");
al_draw_text(font, al_map_rgb(r, g, b), width / 2, height / 2 + 100, ALLEGRO_ALIGN_CENTER, "HELP");
al_draw_text(font, al_map_rgb(255, 255, 255), width / 2, height / 2 + 200, ALLEGRO_ALIGN_CENTER, "EXIT");
break;
case EXIT:
al_draw_text(font, al_map_rgb(255, 255, 255), width / 2, height / 2 - 100, ALLEGRO_ALIGN_CENTER, "START");
al_draw_text(font, al_map_rgb(255, 255, 255), width / 2, height / 2, ALLEGRO_ALIGN_CENTER, "RANKING");
al_draw_text(font, al_map_rgb(255, 255, 255), width / 2, height / 2 + 100, ALLEGRO_ALIGN_CENTER, "HELP");
al_draw_text(font, al_map_rgb(r, g, b), width / 2, height / 2 + 200, ALLEGRO_ALIGN_CENTER, "EXIT");
break;
default:
break;
}
}
void drawRanking(ALLEGRO_FONT* medium_font, ALLEGRO_FONT* small_font,struct ranking_record* records,int records_number,int window_width)
{
al_draw_text(medium_font, al_map_rgb(255, 255, 255), window_width / 2, 50, ALLEGRO_ALIGN_CENTER, "RANKING");
if (records)
{
if (records_number >= 10)
{
for (int i = 0; i < 10; ++i)
{
al_draw_textf(small_font, al_map_rgb(255, 255, 255), window_width / 2 - 150, 150 + (i * 50), ALLEGRO_ALIGN_LEFT, "%02d. ", i + 1);
al_draw_textf(small_font, al_map_rgb(255, 255, 255), window_width / 2 - 110, 150 + (i * 50), ALLEGRO_ALIGN_LEFT, "%c %c %c", records[i].name[0], records[i].name[1], records[i].name[2]);
al_draw_textf(small_font, al_map_rgb(255, 255, 255), window_width / 2 + 120, 150 + (i * 50), ALLEGRO_ALIGN_RIGHT, "%d", records[i].score);
}
}
else
{
for (int i = 0; i < records_number; ++i)
{
al_draw_textf(small_font, al_map_rgb(255, 255, 255), window_width / 2 - 150, 150 + (i * 50), ALLEGRO_ALIGN_LEFT, "%02d. ", i + 1);
al_draw_textf(small_font, al_map_rgb(255, 255, 255), window_width / 2 - 110, 150 + (i * 50), ALLEGRO_ALIGN_LEFT, "%c %c %c", records[i].name[0], records[i].name[1], records[i].name[2]);
al_draw_textf(small_font, al_map_rgb(255, 255, 255), window_width / 2 + 120, 150 + (i * 50), ALLEGRO_ALIGN_RIGHT, "%d", records[i].score);
}
for (int i = records_number; i < 10; ++i)
{
al_draw_textf(small_font, al_map_rgb(255, 255, 255), window_width / 2 - 150, 150 + (i * 50), ALLEGRO_ALIGN_LEFT, "%02d. ", i + 1);
al_draw_text(small_font, al_map_rgb(255, 255, 255), window_width / 2 - 110, 150 + (i * 50), ALLEGRO_ALIGN_LEFT, "----");
al_draw_text(small_font, al_map_rgb(255, 255, 255), window_width / 2 + 120, 150 + (i * 50), ALLEGRO_ALIGN_RIGHT, "-");
}
}
}
else
{
for (int i = 0; i < 10; ++i)
{
al_draw_textf(small_font, al_map_rgb(255, 255, 255), window_width / 2 - 150, 150 + (i * 50), ALLEGRO_ALIGN_LEFT, "%02d. ", i + 1);
al_draw_text(small_font, al_map_rgb(255, 255, 255), window_width / 2 - 110, 150 + (i * 50), ALLEGRO_ALIGN_LEFT, "----");
al_draw_text(small_font, al_map_rgb(255, 255, 255), window_width / 2 + 100, 150 + (i * 50), ALLEGRO_ALIGN_LEFT, "-----");
}
}
al_draw_text(small_font, al_map_rgb(255, 255, 255), window_width / 2, 700, ALLEGRO_ALIGN_CENTER, "press ESC / ENTER to exit to main menu");
}
void drawGameOver(ALLEGRO_FONT* title_font,ALLEGRO_FONT* medium_font, ALLEGRO_FONT* small_font,struct ranking_record player,int menu_choice,int window_width,int window_height,unsigned char r, unsigned char g, unsigned char b)
{
al_draw_filled_rectangle(20, 20, window_width - 20, window_height - 20, al_premul_rgba(0, 0, 0, 200));
al_draw_text(title_font, al_map_rgb(255, 255, 255), window_width / 2, window_height / 2 - 300, ALLEGRO_ALIGN_CENTER, "YOU DIED");
al_draw_text(medium_font, al_map_rgb(255, 255, 255), window_width / 2, window_height / 2 - 100, ALLEGRO_ALIGN_CENTER, "YOUR SCORE:");
al_draw_textf(medium_font, al_map_rgb(255, 255, 255), window_width / 2, window_height / 2, ALLEGRO_ALIGN_CENTER, "%d", player.score);
al_draw_textf(medium_font, al_map_rgb(255, 255, 255), window_width / 2, window_height / 2, ALLEGRO_ALIGN_CENTER, "%d", player.score);
if (menu_choice == 0)
{
al_draw_filled_triangle(window_width / 2 + 80, window_height / 2 + 115, window_width / 2 + 90, window_height / 2 + 125, window_width / 2 + 80, window_height / 2 + 135, al_map_rgb(255, 255, 255));
al_draw_filled_triangle(window_width / 2 - 50, window_height / 2 + 90, window_width / 2 - 45, window_height / 2 + 80, window_width / 2 - 40, window_height / 2 + 90, al_map_rgb(r, g, b));
al_draw_filled_triangle(window_width / 2 - 50, window_height / 2 + 160, window_width / 2 - 45, window_height / 2 + 170, window_width / 2 - 40, window_height / 2 + 160, al_map_rgb(r, g, b));
al_draw_filled_triangle(window_width / 2 - 5, window_height / 2 + 90, window_width / 2, window_height / 2 + 80, window_width / 2 + 5, window_height / 2 + 90, al_map_rgb(255, 255, 255));
al_draw_filled_triangle(window_width / 2 - 5, window_height / 2 + 160, window_width / 2, window_height / 2 + 170, window_width / 2 + 5, window_height / 2 + 160, al_map_rgb(255, 255, 255));
al_draw_filled_triangle(window_width / 2 + 50, window_height / 2 + 90, window_width / 2 + 45, window_height / 2 + 80, window_width / 2 + 40, window_height / 2 + 90, al_map_rgb(255, 255, 255));
al_draw_filled_triangle(window_width / 2 + 50, window_height / 2 + 160, window_width / 2 + 45, window_height / 2 + 170, window_width / 2 + 40, window_height / 2 + 160, al_map_rgb(255, 255, 255));
al_draw_textf(medium_font, al_map_rgb(r, g, b), window_width / 2 - 45, window_height / 2 + 100, ALLEGRO_ALIGN_CENTER, "%c", player.name[0]);
al_draw_textf(medium_font, al_map_rgb(255, 255, 255), window_width / 2, window_height / 2 + 100, ALLEGRO_ALIGN_CENTER, "%c", player.name[1]);
al_draw_textf(medium_font, al_map_rgb(255, 255, 255), window_width / 2 + 45, window_height / 2 + 100, ALLEGRO_ALIGN_CENTER, "%c", player.name[2]);
}
else if (menu_choice == 1)
{
al_draw_filled_triangle(window_width / 2 - 80, window_height / 2 + 115, window_width / 2 - 90, window_height / 2 + 125, window_width / 2 - 80, window_height / 2 + 135, al_map_rgb(255, 255, 255));
al_draw_filled_triangle(window_width / 2 + 80, window_height / 2 + 115, window_width / 2 + 90, window_height / 2 + 125, window_width / 2 + 80, window_height / 2 + 135, al_map_rgb(255, 255, 255));
al_draw_filled_triangle(window_width / 2 - 50, window_height / 2 + 90, window_width / 2 - 45, window_height / 2 + 80, window_width / 2 - 40, window_height / 2 + 90, al_map_rgb(255, 255, 255));
al_draw_filled_triangle(window_width / 2 - 50, window_height / 2 + 160, window_width / 2 - 45, window_height / 2 + 170, window_width / 2 - 40, window_height / 2 + 160, al_map_rgb(255, 255, 255));
al_draw_filled_triangle(window_width / 2 - 5, window_height / 2 + 90, window_width / 2, window_height / 2 + 80, window_width / 2 + 5, window_height / 2 + 90, al_map_rgb(r, g, b));
al_draw_filled_triangle(window_width / 2 - 5, window_height / 2 + 160, window_width / 2, window_height / 2 + 170, window_width / 2 + 5, window_height / 2 + 160, al_map_rgb(r, g, b));
al_draw_filled_triangle(window_width / 2 + 50, window_height / 2 + 90, window_width / 2 + 45, window_height / 2 + 80, window_width / 2 + 40, window_height / 2 + 90, al_map_rgb(255, 255, 255));
al_draw_filled_triangle(window_width / 2 + 50, window_height / 2 + 160, window_width / 2 + 45, window_height / 2 + 170, window_width / 2 + 40, window_height / 2 + 160, al_map_rgb(255, 255, 255));
al_draw_textf(medium_font, al_map_rgb(255, 255, 255), window_width / 2 - 45, window_height / 2 + 100, ALLEGRO_ALIGN_CENTER, "%c", player.name[0]);
al_draw_textf(medium_font, al_map_rgb(r, g, b), window_width / 2, window_height / 2 + 100, ALLEGRO_ALIGN_CENTER, "%c", player.name[1]);
al_draw_textf(medium_font, al_map_rgb(255, 255, 255), window_width / 2 + 45, window_height / 2 + 100, ALLEGRO_ALIGN_CENTER, "%c", player.name[2]);
}
else if (menu_choice == 2)
{
al_draw_filled_triangle(window_width / 2 - 80, window_height / 2 + 115, window_width / 2 - 90, window_height / 2 + 125, window_width / 2 - 80, window_height / 2 + 135, al_map_rgb(255, 255, 255));
al_draw_filled_triangle(window_width / 2 - 50, window_height / 2 + 90, window_width / 2 - 45, window_height / 2 + 80, window_width / 2 - 40, window_height / 2 + 90, al_map_rgb(255, 255, 255));
al_draw_filled_triangle(window_width / 2 - 50, window_height / 2 + 160, window_width / 2 - 45, window_height / 2 + 170, window_width / 2 - 40, window_height / 2 + 160, al_map_rgb(255, 255, 255));
al_draw_filled_triangle(window_width / 2 - 5, window_height / 2 + 90, window_width / 2, window_height / 2 + 80, window_width / 2 + 5, window_height / 2 + 90, al_map_rgb(255, 255, 255));
al_draw_filled_triangle(window_width / 2 - 5, window_height / 2 + 160, window_width / 2, window_height / 2 + 170, window_width / 2 + 5, window_height / 2 + 160, al_map_rgb(255, 255, 255));
al_draw_filled_triangle(window_width / 2 + 50, window_height / 2 + 90, window_width / 2 + 45, window_height / 2 + 80, window_width / 2 + 40, window_height / 2 + 90, al_map_rgb(r, g, b));
al_draw_filled_triangle(window_width / 2 + 50, window_height / 2 + 160, window_width / 2 + 45, window_height / 2 + 170, window_width / 2 + 40, window_height / 2 + 160, al_map_rgb(r, g, b));
al_draw_textf(medium_font, al_map_rgb(255, 255, 255), window_width / 2 - 45, window_height / 2 + 100, ALLEGRO_ALIGN_CENTER, "%c", player.name[0]);
al_draw_textf(medium_font, al_map_rgb(255, 255, 255), window_width / 2, window_height / 2 + 100, ALLEGRO_ALIGN_CENTER, "%c", player.name[1]);
al_draw_textf(medium_font, al_map_rgb(r, g, b), window_width / 2 + 45, window_height / 2 + 100, ALLEGRO_ALIGN_CENTER, "%c", player.name[2]);
}
al_draw_text(small_font, al_map_rgb(255, 255, 255), window_width / 2, window_height / 2 + 250, ALLEGRO_ALIGN_CENTER, "press ENTER to confirm");
}
void drawHelp(ALLEGRO_FONT* font, ALLEGRO_FONT* big_font,unsigned char r, unsigned char g, unsigned char b)
{
al_draw_text(big_font, al_map_rgb(255, 255, 255), 400, 100, ALLEGRO_ALIGN_CENTER, "HELP");
al_draw_filled_circle(250, 200, 5, al_map_rgb(181, 230, 29));
al_draw_text(font, al_map_rgb(255, 255, 255), 300, 200-9, ALLEGRO_ALIGN_LEFT, "- small food - gives +1 snake length");
al_draw_filled_rounded_rectangle(240, 240, 260, 260, 3, 3, al_map_rgb(0, 162, 232));
al_draw_text(font, al_map_rgb(255, 255, 255), 300, 250 - 9, ALLEGRO_ALIGN_LEFT, "- big food - gives +2 snake length");
al_draw_filled_triangle(250 - 10, 300 - 5, 250, 300 + 10, 250 + 10, 300 - 5, al_map_rgb(r, g, b));
al_draw_filled_triangle(250 - 10, 300 + 5, 250, 300 - 10, 250 + 10, 300 + 5, al_map_rgb(r, g, b));
al_draw_text(font, al_map_rgb(255, 255, 255), 300, 300 - 9, ALLEGRO_ALIGN_LEFT, "- random bonus");
al_draw_filled_rectangle(250 - 10, 350 - 10, 250 + 10, 350 + 10, al_map_rgb(255, 255, 255));
al_draw_text(font, al_map_rgb(255, 255, 255), 300, 350 - 9, ALLEGRO_ALIGN_LEFT, "- obstacle - do not try to eat it");
al_draw_filled_triangle(250 - 10, 400, 250, 400 + 10, 250 + 10, 400, al_premul_rgba(24, 240, 180, r));
al_draw_filled_triangle(250 - 10, 400, 250, 400 - 10, 250 + 10, 400, al_premul_rgba(24, 240, 180, r));
al_draw_text(font, al_map_rgb(255, 255, 255), 300, 400 - 9, ALLEGRO_ALIGN_LEFT, "- bonus - lets you go through walls");
al_draw_filled_rectangle(250 - (b / 20 + 2), 450 - (b / 20 + 2), 250 + (b / 20 + 2), 450 + (b / 20 + 2), al_map_rgb(250, 65, 20));
al_draw_text(font, al_map_rgb(255, 255, 255), 300, 450 - 9, ALLEGRO_ALIGN_LEFT, "- \"negative bonus\" - spawns obstacle");
al_draw_filled_circle(250, 500, b / 45.0, al_map_rgb(181, 230, 29));
al_draw_filled_circle(250 - 5, 500 - 5, b / 45.0, al_map_rgb(0, 162, 232));
al_draw_filled_circle(250 - 5, 500 + 5, b / 45.0, al_map_rgb(181, 230, 29));
al_draw_filled_circle(250 + 5, 500 + 5, b / 45.0, al_map_rgb(0, 162, 232));
al_draw_filled_circle(250 + 5, 500 - 5, b / 45.0, al_map_rgb(181, 230, 29));
al_draw_text(font, al_map_rgb(255, 255, 255), 300, 500 - 9, ALLEGRO_ALIGN_LEFT, "- food bonus - speeds you up for");
al_draw_text(font, al_map_rgb(255, 255, 255), 300, 530 - 9, ALLEGRO_ALIGN_LEFT, "a while and spawns lots of food");
al_draw_text(font, al_map_rgb(255, 255, 255), 400, 650, ALLEGRO_ALIGN_CENTER, "press ESC to return");
}
void drawPause(ALLEGRO_FONT* medium_font, ALLEGRO_FONT* small_font,struct fifo_pointers fifo, int window_width,int window_height,int speed_x,int speed_y)
{
al_draw_filled_rectangle(20, 20, window_width - 20, window_height - 20, al_premul_rgba(0, 0, 0, 200));
if (speed_y == -20)
al_draw_filled_triangle(fifo.head->x - 9, fifo.head->y - 11, fifo.head->x, fifo.head->y - 20, fifo.head->x + 9, fifo.head->y - 11, al_map_rgb(34, 177, 76));
else if (speed_x == 20)
al_draw_filled_triangle(fifo.head->x + 11, fifo.head->y - 9, fifo.head->x + 20, fifo.head->y, fifo.head->x + 11, fifo.head->y + 9, al_map_rgb(34, 177, 76));
else if (speed_y == 20)
al_draw_filled_triangle(fifo.head->x - 9, fifo.head->y + 11, fifo.head->x, fifo.head->y + 20, fifo.head->x + 9, fifo.head->y + 11, al_map_rgb(34, 177, 76));
else if (speed_x == -20)
al_draw_filled_triangle(fifo.head->x - 11, fifo.head->y - 9, fifo.head->x - 20, fifo.head->y, fifo.head->x - 11, fifo.head->y + 9, al_map_rgb(34, 177, 76));
al_draw_text(medium_font, al_map_rgb(255, 255, 255), window_width / 2, window_height / 2 - 100, ALLEGRO_ALIGN_CENTER, "PAUSE");
al_draw_text(small_font, al_map_rgb(255, 255, 255), window_width / 2, window_height / 2 + 100, ALLEGRO_ALIGN_CENTER, "ESC to exit to main menu");
al_draw_text(small_font, al_map_rgb(255, 255, 255), window_width / 2, window_height / 2 + 200, ALLEGRO_ALIGN_CENTER, "P/ENTER to resume");
}
void drawInGameScore(ALLEGRO_FONT* medium_font,int** collision_array,struct ranking_record player, int window_width,int window_height,int* alpha)
{
if (checkScoreCollision(collision_array))
{
if (*alpha > 100)*alpha -= 10;
al_draw_text(medium_font, al_premul_rgba(255, 255, 255, *alpha), window_width - 150, 30, ALLEGRO_ALIGN_RIGHT, "SCORE:");
al_draw_textf(medium_font, al_premul_rgba(255, 255, 255, *alpha), window_width - 30, 30, ALLEGRO_ALIGN_RIGHT, "%d", player.score);
}
else
{
if (*alpha < 255)*alpha += 10;
if (*alpha > 255)*alpha = 255;
al_draw_text(medium_font, al_premul_rgba(255, 255, 255, *alpha), window_width - 150, 30, ALLEGRO_ALIGN_RIGHT, "SCORE:");
al_draw_textf(medium_font, al_premul_rgba(255, 255, 255, *alpha), window_width - 30, 30, ALLEGRO_ALIGN_RIGHT, "%d", player.score);
}
}
void drawSnake(struct fifo_pointers fifo)
{
while (fifo.head) {
al_draw_filled_rectangle(fifo.head->x - 9, fifo.head->y - 9, fifo.head->x + 9, fifo.head->y + 9, al_map_rgb(34, 177, 76));
fifo.head = fifo.head->next;
}
}
void drawSmallFood(struct list_node *small_food, float food_radius)
{
while (small_food)
{
al_draw_filled_circle(small_food->x, small_food->y, food_radius, al_map_rgb(181, 230, 29));
small_food=small_food->next;
}
}
void drawBigFood(struct list_node *big_food, float rect_rounding_radius)
{
while (big_food)
{
al_draw_filled_rounded_rectangle(big_food->x - 10, big_food->y - 10, big_food->x + 10, big_food->y + 10, rect_rounding_radius, rect_rounding_radius, al_map_rgb(0, 162, 232));
big_food = big_food->next;
}
}
void drawRandomBonus(struct list_node *random_bonus, unsigned char r, unsigned char g, unsigned char b)
{
while (random_bonus)
{
al_draw_filled_triangle(random_bonus->x - 10, random_bonus->y - 5, random_bonus->x, random_bonus->y + 10, random_bonus->x + 10, random_bonus->y - 5, al_map_rgb(r, g, b));
al_draw_filled_triangle(random_bonus->x - 10, random_bonus->y + 5, random_bonus->x, random_bonus->y - 10, random_bonus->x + 10, random_bonus->y + 5, al_map_rgb(r, g, b));
random_bonus = random_bonus->next;
}
}
void drawObstacle(struct list_node *obstacle)
{
while (obstacle)
{
al_draw_filled_rectangle(obstacle->x - 10, obstacle->y - 10, obstacle->x + 10, obstacle->y + 10, al_map_rgb(255, 255, 255));
obstacle = obstacle->next;
}
}
void drawWallsBonus(struct list_node *diamond,unsigned char alpha)
{
while (diamond)
{
al_draw_filled_triangle(diamond->x - 10, diamond->y, diamond->x, diamond->y + 10, diamond->x + 10, diamond->y, al_premul_rgba(24,240,180,alpha));
al_draw_filled_triangle(diamond->x - 10, diamond->y, diamond->x, diamond->y - 10, diamond->x + 10, diamond->y, al_premul_rgba(24, 240, 180, alpha));
diamond = diamond->next;
}
}
void drawNegativeBonus(struct list_node *negative_bonus, unsigned char size)
{
while (negative_bonus)
{
al_draw_filled_rectangle(negative_bonus->x - (size / 20 + 2), negative_bonus->y - (size / 20 + 2), negative_bonus->x + (size / 20 + 2), negative_bonus->y + (size / 20 + 2), al_map_rgb(250, 65, 20));
negative_bonus = negative_bonus->next;
}
}
void drawFoodSpawnBonus(struct list_node *food_spawn, unsigned char size)
{
while (food_spawn)
{
al_draw_filled_circle(food_spawn->x, food_spawn->y, size/45.0, al_map_rgb(181, 230, 29));
al_draw_filled_circle(food_spawn->x - 5, food_spawn->y - 5, size/45.0, al_map_rgb(0, 162, 232));
al_draw_filled_circle(food_spawn->x - 5, food_spawn->y + 5, size / 45.0, al_map_rgb(181, 230, 29));
al_draw_filled_circle(food_spawn->x + 5, food_spawn->y + 5,size/45.0, al_map_rgb(0, 162, 232));
al_draw_filled_circle(food_spawn->x + 5, food_spawn->y - 5, size / 45.0, al_map_rgb(181, 230, 29));
food_spawn = food_spawn->next;
}
}
void drawBonusTimer(ALLEGRO_FONT* font, bool walls_bonus_effect,int walls_bonus_effect_timer,bool negative_effect,int negative_effect_timer,bool food_spawn_bonus_effect, int food_spawn_bonus_effect_timer,int window_width,int window_height)
{
if (walls_bonus_effect)
{
al_draw_textf(font, al_premul_rgba(24, 240, 180, 150), window_width / 2, window_height / 2 - 30, ALLEGRO_ALIGN_CENTER, "%d", walls_bonus_effect_timer / 60);
}
else if (negative_effect)
{
al_draw_textf(font, al_premul_rgba(250, 65, 20, 150), window_width / 2, window_height / 2 - 30, ALLEGRO_ALIGN_CENTER, "%d", negative_effect_timer / 60);
}
else if (food_spawn_bonus_effect)
{
al_draw_textf(font, al_premul_rgba(40, 180, 80, 150), window_width / 2, window_height / 2 - 30, ALLEGRO_ALIGN_CENTER, "%d", food_spawn_bonus_effect_timer / 60);
}
}
void animateRainbowColorChange(struct color_flags *color_flag, unsigned char *r, unsigned char *g, unsigned char *b)
{
if (color_flag->r == 0) (*r) += 5;
if (color_flag->r == 1) (*r) -= 5;
if (color_flag->g == 0) (*g) += 5;
if (color_flag->g == 1) (*g) -= 5;
if (color_flag->b == 0) (*b) += 5;
if (color_flag->b == 1) (*b) -= 5;
if ((*r) >= 255) color_flag->r = 1;
if ((*r) <= 100) color_flag->r = 0;
if ((*g) >= 255) color_flag->g = 1;
if ((*g) <= 50) color_flag->g = 0;
if ((*b) >= 150) color_flag->b = 1;
if ((*b) <= 100) color_flag->b = 0;
}
void animateFoodSizeChange(float *radius, int *flag, int max_value, int min_value, float change_value)
{
if (*flag == 0) *radius += change_value;
if (*flag == 1) *radius -= change_value;
if (*radius >= max_value) { *flag = 1; *radius = max_value; }
if (*radius <= min_value) { *flag = 0; *radius = min_value; }
}
|
C
|
#ifndef __menubar_h__
#define __menubar_h__
#include <stdint.h>
typedef enum
{
mitEntry,
mitSeparator,
mitSubMenu, // FIXME: segment into MainMenu/SubMenu so that orientation is automagic?
} MenuItemType_t;
typedef struct MenuItem
{
const char *text;
int width;
int checked; // Only for mitEntry
int expanded; // Only for mitSubMenu
struct MenuItem *child_menu; // Only for mitSubMenu
int key_accelerator;
void (*on_select)(struct MenuItem *menu);
MenuItemType_t type;
struct MenuItem *next; // Next MenuItem after this (forms a linked list)
} MenuItem_t;
typedef struct
{
int visible;
int init;
MenuItem_t *menu;
MenuItem_t *highlighted;
} MenuBar_t;
#include "display.h"
struct Display; // Forward declaration
void menubar_init(MenuBar_t *menubar, MenuItem_t *menu);
void menubar_destroy(MenuBar_t *menubar);
void menubar_deselect(MenuBar_t *menubar);
void menubar_draw(struct Display *display, MenuBar_t *menubar, DisplayPixel_t *origin);
int menubar_mousedown(struct Display *display, MenuBar_t *menubar, int x, int y);
int menubar_mousemove(struct Display *display, MenuBar_t *menubar, int x, int y);
int menubar_key_accelerator(MenuBar_t *menubar, int key);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
void bubblesort(int dizi[], int size) {
int i, j, temp;
for (i = 0; i < size; i++) {
for (j = 0; j < size - i - 1; j++) {
if (dizi[j + 1] < dizi[j]) {
temp = dizi[j + 1];
dizi[j + 1] = dizi[j];
dizi[j] = temp;
}
}
}
}
void printing(int dizi[], int size) {
for (int i = 0; i < size; i++) {
printf("%d\n", dizi[i]);
}
}
int main() {
int dizi[] = { 9,8,7,6,5,4,3,2,1 };
int size = sizeof(dizi) / sizeof(dizi[1]);
bubblesort(dizi, size);
printing(dizi, size);
system("pause");
}
|
C
|
#include "get_next_line.h"
int main()
{
char *line;
int fd;
fd = open("txt", O_RDONLY);
line = NULL;
while ((get_next_line(fd, &line)) > 0)
{
printf("linea: %s\n", line);
free(line);
line = NULL;
}
free(line);
system("leaks a.out");
line = NULL;
}
|
C
|
#ifndef BSTREE_H
#define BSTREE_H
#include <stdlib.h>
#include <string.h>
struct _bstree_node {
struct _bstree_node *left;
struct _bstree_node *right;
char key[0];
};
struct _bstree {
struct _bstree_node *root;
size_t size;
size_t element_size;
int (*compare)(const void*, const void*);
};
typedef struct _bstree BSTREE;
#define bstree_size(B) ((B)->size)
void bstree_init(BSTREE *t, size_t element_size, int (*compare)(const void*, const void*));
void bstree_destroy(BSTREE *t);
void bstree_clear(BSTREE *t);
int bstree_remove(BSTREE *t, const void *key);
const void *bstree_insert(BSTREE *t, const void *key);
const void *bstree_find(BSTREE *t, const void *key);
void bstree_iterate(BSTREE *t, void (*callback)(const void *key));
#endif
|
C
|
#include "stm32f10x.h"
#include "stm32f10x_usart.h"
#include "usart.h"
#include "misc.h"
#include "stdio.h"
#include "string.h"
/*
USARTGPIO
*/
void USART2_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* GPIOAʱӡAFIOʱӣUSART2ʱ */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
/* USART2 TX PA2 */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* USART2 RX PA3 */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* USART */
USART_DeInit(USART2);
USART_InitStructure.USART_BaudRate = 57600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART2, &USART_InitStructure);
/* ʹUSART2շж */
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
USART_ITConfig(USART2, USART_IT_TXE, ENABLE);
// -YJ- ж
USART_ITConfig(USART2, USART_IT_IDLE, ENABLE); // һ֡ʱᴥжϣǼУ??
/* ʹUSART2 */
USART_Cmd(USART2, ENABLE);
/* ɱ־ */
USART_ClearFlag(USART2, USART_FLAG_TC);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
/* Enable the USART2 Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn; //ж
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void USART3_Configuration( void )
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* GPIOAʱӡAFIOʱӣUSART2ʱ */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE); // PB
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
/* USART3 TX PB10 */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
/* USART3 RX PB11 */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
/* USART */
USART_DeInit(USART3);
USART_InitStructure.USART_BaudRate = 57600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART3, &USART_InitStructure);
/* ʹUSART3շж */
USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
USART_ITConfig(USART3, USART_IT_TXE, ENABLE);
// -YJ- ж
USART_ITConfig(USART3, USART_IT_IDLE, ENABLE); // һ֡ʱᴥжϣǼУ??
/* ʹUSART3 */
USART_Cmd(USART3, ENABLE);
/* ɱ־ */
USART_ClearFlag(USART3, USART_FLAG_TC);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
/* Enable the USART2 Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn; //ж
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
/*
ڷͺ
*/
void USART_Send(USART_TypeDef* USARTx, uint8_t *Dat,uint16_t len)
{
uint16_t i;
for(i=0;i<len;i++)
{
USART_SendData(USARTx, Dat[i]);
while(USART_GetFlagStatus(USARTx, USART_FLAG_TC)==RESET);
}
}
/*
ڷַ
*/
void USART_STR(USART_TypeDef* USARTx,char *str)
{
uint8_t len,i;
len=strlen(str);
for(i=0;i<len;i++)
{
USART_SendData(USARTx, str[i]);
while(USART_GetFlagStatus(USARTx, USART_FLAG_TC)==RESET);
}
}
|
C
|
#include "stattest_gaus.h"
#include <math.h>
using namespace std;
void stattest_gaus::set_data(vector<double> data)
{
if (data.size() != m_nbins)
{
cout << "Error, wrong size for data vector" << endl;
return;
}
m_data = data;
}
void stattest_gaus::set_data_stat(vector<double> data_stat)
{
if (data_stat.size() != m_nbins)
{
cout << "Error, wrong size for data_stat vector" << endl;
return;
}
m_data_stat = data_stat;
}
void stattest_gaus::set_pred(vector<double> pred)
{
if (pred.size() != m_nbins)
{
cout << "Error, wrong size for pred vector" << endl;
return;
}
m_pred = pred;
}
void stattest_gaus::set_systs(vector< vector<double> > systs)
{
// set the systematics vector
if (systs.size() != m_nsyst)
{
cout << "Error, wrong size for systs vector" << endl;
return;
}
for (int i=0; i<systs.size(); i++)
if (systs[i].size() != m_nbins)
{
cout << "Error, wrong size for systs vector" << endl;
return;
}
m_systs = systs;
// set the covariance matrix from there
// cov = diag(m_data_stat^2) + sum_k ^t(fk) fk
for (int i=0; i<m_nbins; i++)
for (int j=0; j<m_nbins; j++)
{
if(i==j) m_cov[i][j] = pow(m_datastat[i],2);
for (int k=0; k<m_nsyst; k++)
{
m_cov[i][j] += m_systs[k][i]*m_systs[k][j];
}
}
// invert the covariance matrix and store it
TMatrixDSym tm_cov(m_nbins), tm_invcov(m_nbins);
for (int i=0; i<m_nbins; i++)
for (int j=0; j<m_nbins; j++)
tm_cov[i][j] = m_cov[i][j];
tm_invconv = tm_cov.Invert();
for (int i=0; i<m_nbins; i++)
for (int j=0; j<m_nbins; j++)
m_invcov[i][j] = tm_invcov[i][j];
}
double stattest_gaus::chi2(double *pulls)
{
double val=0;
// effect of systs
vector<double> data_mod; data_mod = m_data;
if (pulls != NULL)
{
for (int j=0; j<m_nbins; j++)
{
double fact=0.;
for (int i=0; i<m_nsyst; i++)
fact+=m_systs[i][j]*pulls[i];
data_mod[j]*=(1+fact);
}
}
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
val += (data_mod[i]-m_pred[i])*m_invcov[i][j]*(data_mod[j]-m_pred[j]);
if (pulls != NULL)
for (int i=0; i<m_nsysts; i++)
val += pow(pulls[i],2);
return val;
}
|
C
|
/*
* GROUP NUMBER : 16
* GANDHI ATITH NIKESHKUMAR : 2017A7PS0062P
* BURHAN BOXWALLA : 2017A7PS0097P
* KESHAV SHARMA : 2017A7PS0140P
* SHRAY MATHUR : 2017A7PS1180P
* RAJ SANJAY SHAH : 2017A7PS1181P
*/
#include "lexer.h"
#include "parser.h"
#include "ast.h"
#include "symbolTable.h"
#include "assembler.h"
int line_count;
int buf_count;
int DFA_state;
int Printst;
int no_of_terminals;
int factor_nt;
int factor_t;
int SynxErr = 0;
int LexErr = 0;
int SemErr = 0;
int symind = 0;
int op3 = 0;
int asop = 0;
int numAST = 0;
int numParseTree = 0;
extern int switch_label;
extern int while_label;
extern int for_label;
extern int relationalop_label;
extern int logicalop_label;
extern int floatnum;
extern int func_space;
extern int boolprint;
extern int intarrprint;
extern int boolarrprint;
extern int realarrprint;
extern int boolelemprint;
extern int getbool;
extern int getintarr;
extern int getboolarr;
extern int getrealarr;
void menuOptions(int option, FILE* sourceFile, char* filename, char* asmfile)
{
line_count = 1;
DFA_state = Start;
switch(option)
{
case 1:
printf("\n\nLIST OF TOKENS\n");
printf("*************************************************************************************\n");
Token_Print(sourceFile);
return;
case 2:
fclose(sourceFile);
char x='$';
sourceFile = fopen(filename, "a");
fputc(x,sourceFile);
fclose(sourceFile);
sourceFile = fopen(filename, "r");
printf("\n\nPARSING THE INPUT\n\n");
printf("*************************************************************************************\n");
parseInputSourceCode(sourceFile, T);
printf("\nPrinting the Parse Tree in the In-Order Traversal : Left Child, Parent, Remaining Children\n\n");
printf("\n %-30s %-20s %-20s %-20s %-40s %-20s %-30s \n", "CURRENT NODE LEXEME", "LINE NUMBER", "TOKEN NAME", "VALUE OF NUMBER", "PARENT NODE SYMBOL", "IS LEAF", "NODE SYMBOL");
for(int i=0; i<200; i++)
printf("_");
printf("\n");
printParseTree(p->root);
printf("\n\nPARSE TREE CONSTRUCTED\n\n");
if(SynxErr!=0 || LexErr!=0)
{
printf("\033[01;31m%d Syntactic Errors Found and %d Lexical Errors Found\n\033[0m", SynxErr, LexErr);
SynxErr = 0;
LexErr = 0;
}
else
printf("\033[1;32mNo Syntactic and Lexical Errors Found\n\033[0m\n\n");
fclose(sourceFile);
FILE* InputFile = fopen(filename, "r+");
fseek(InputFile, -1, SEEK_END);
int position=ftello(InputFile);
ftruncate(fileno(InputFile),position);
fclose(InputFile);
return;
case 3:
fclose(sourceFile);
x='$';
sourceFile = fopen(filename, "a");
fputc(x,sourceFile);
fclose(sourceFile);
sourceFile = fopen(filename, "r");
printf("\nPARSING THE INPUT\n");
printf("*************************************************************************************\n\n");
parseInputSourceCode(sourceFile, T);
fclose(sourceFile);
FILE* IpFile = fopen(filename, "r+");
fseek(IpFile, -1, SEEK_END);
int postion=ftello(IpFile);
ftruncate(fileno(IpFile),postion);
fclose(IpFile);
if(SynxErr!=0 || LexErr!=0)
{
printf("\033[01;31m%d Syntactic Errors Found and %d Lexical Errors Found\n\033[0m\n", SynxErr, LexErr);
SynxErr = 0;
LexErr = 0;
return;
}
else
printf("\033[1;32mNo Syntactic and Lexical Errors Found\n\033[0m\n");
printf("\nAST CREATION\n\n");
printf("*************************************************************************************\n\n");
asttreee = ast_creation(p);
printf("ABSTRACT SYNTAX TREE CONSTRUCTED\n");
printf("\nPrinting the Abstract Syntax Tree in the Pre-Order Traversal : Parent, Left Child, Remaining Children\n\n");
printf("\n %-30s %-20s %-20s %-20s %-40s %-20s %-30s \n", "CURRENT NODE LEXEME", "LINE NUMBER", "TOKEN NAME", "VALUE OF NUMBER", "PARENT NODE SYMBOL", "IS LEAF", "NODE SYMBOL");
for(int i=0; i<200; i++)
printf("_");
printf("\n");
PrintAST(asttreee->root);
printf("\nABSTRACT SYNTAX TREE CONSTRUCTED\n\n");
return;
case 4:
fclose(sourceFile);
x='$';
sourceFile = fopen(filename, "a");
fputc(x,sourceFile);
fclose(sourceFile);
int sizeastnode = sizeof(ast_node);
int sizeparsenode = sizeof(node);
sourceFile = fopen(filename, "r");
printf("\nPARSING THE INPUT\n");
printf("*************************************************************************************\n\n");
parseInputSourceCode(sourceFile, T);
fclose(sourceFile);
FILE* IpFile1 = fopen(filename, "r+");
fseek(IpFile1, -1, SEEK_END);
int postion1 = ftello(IpFile1);
ftruncate(fileno(IpFile1), postion1);
sizeastnode -= 26;
fclose(IpFile1);
if(SynxErr!=0 || LexErr!=0)
{
printf("\033[01;31m%d Syntactic Errors Found and %d Lexical Errors Found\n\033[0m\n", SynxErr, LexErr);
SynxErr = 0;
LexErr = 0;
return;
}
else
printf("\033[1;32mNo Syntactic and Lexical Errors Found\n\033[0m\n");
printf("\nAST CREATION\n\n");
printf("*************************************************************************************\n\n");
asttreee = ast_creation(p);
printf("\nABSTRACT SYNTAX TREE CONSTRUCTED\n\n");
CountParseTree(p->root);
CountAST(asttreee->root);
int parsesize = sizeparsenode*numParseTree;
int astsize = sizeastnode*numAST;
printf("\nNumber of Parse Tree Nodes = %d\t\tAllocated Memory for Parse Tree Nodes = %d bytes\n", numParseTree, parsesize);
printf("Number of Abstract Syntax Tree Nodes = %d\tAllocated Memory for Abstract Syntax Tree Nodes = %d bytes\n",numAST, astsize);
printf("Compression percentage : %lf\n\n", (((double)parsesize - astsize)/parsesize)*100.0);
numAST = 0;
numParseTree = 0;
return;
case 5:
fclose(sourceFile);
x='$';
sourceFile = fopen(filename, "a");
fputc(x,sourceFile);
fclose(sourceFile);
sourceFile = fopen(filename, "r");
printf("\nPARSING THE INPUT\n");
printf("*************************************************************************************\n\n");
parseInputSourceCode(sourceFile, T);
fclose(sourceFile);
FILE* IpFile2 = fopen(filename, "r+");
fseek(IpFile2, -1, SEEK_END);
int postion2 = ftello(IpFile2);
ftruncate(fileno(IpFile2),postion2);
fclose(IpFile2);
if(SynxErr!=0 || LexErr!=0)
{
printf("\033[01;31m%d Syntactic Errors Found and %d Lexical Errors Found\n\033[0m\n", SynxErr, LexErr);
SynxErr = 0;
LexErr = 0;
return;
}
else
printf("\033[1;32mNo Syntactic and Lexical Errors Found\n\033[0m\n");
printf("\nAST CREATION\n\n");
printf("*************************************************************************************\n\n");
asttreee = ast_creation(p);
printf("\nABSTRACT SYNTAX TREE CONSTRUCTED\n\n");
printf("PERFORMING SEMANTIC ANALYSIS OF THE SOURCE CODE\n\n");
st_node* root = create_st(asttreee);
if(SemErr!=0)
{
printf(RED"%d Semantic Errors Found\n"RESET, SemErr);
SemErr = 0;
}
else
printf(GREEN"No Semantic Errors Found\n"RESET);
printf("\nPRINTING THE SYMBOL TABLE\n");
printf("************************************************************************************\n\n");
printSymbolTable(root);
symind = 0;
return;
case 6:
fclose(sourceFile);
x='$';
sourceFile = fopen(filename, "a");
fputc(x,sourceFile);
fclose(sourceFile);
sourceFile = fopen(filename, "r");
printf("\nPARSING THE INPUT\n");
printf("*************************************************************************************\n\n");
parseInputSourceCode(sourceFile, T);
fclose(sourceFile);
FILE* IpFile3 = fopen(filename, "r+");
fseek(IpFile3, -1, SEEK_END);
int postion3 = ftello(IpFile3);
ftruncate(fileno(IpFile3), postion3);
fclose(IpFile3);
if(SynxErr!=0 || LexErr!=0)
{
printf("\033[01;31m%d Syntactic Errors Found and %d Lexical Errors Found\n\033[0m\n", SynxErr, LexErr);
SynxErr = 0;
LexErr = 0;
return;
}
else
printf("\033[1;32mNo Syntactic and Lexical Errors Found\n\033[0m\n");
printf("\nAST CREATION\n\n");
printf("*************************************************************************************\n\n");
asttreee = ast_creation(p);
printf("\nABSTRACT SYNTAX TREE CONSTRUCTED\n\n");
printf("\nPERFORMING SEMANTIC ANALYSIS OF THE SOURCE CODE\n\n\n");
st_node* root2 = create_st(asttreee);
if(SemErr!=0)
{
printf(RED"%d Semantic Errors Found\n"RESET, SemErr);
SemErr = 0;
}
else
printf(GREEN"No Semantic Errors Found\n"RESET);
printf("\n");
print_activation_record(root2);
printf("\n");
return;
case 7:
fclose(sourceFile);
x='$';
sourceFile = fopen(filename, "a");
fputc(x,sourceFile);
fclose(sourceFile);
sourceFile = fopen(filename, "r");
printf("\nPARSING THE INPUT\n");
printf("*************************************************************************************\n\n");
parseInputSourceCode(sourceFile, T);
fclose(sourceFile);
FILE* IpFile12 = fopen(filename, "r+");
fseek(IpFile12, -1, SEEK_END);
int postion12 = ftello(IpFile12);
ftruncate(fileno(IpFile12), postion12);
fclose(IpFile12);
if(SynxErr!=0 || LexErr!=0)
{
printf("\033[01;31m%d Syntactic Errors Found and %d Lexical Errors Found\n\033[0m\n", SynxErr, LexErr);
SynxErr = 0;
LexErr = 0;
return;
}
else
printf("\033[1;32mNo Syntactic and Lexical Errors Found\n\033[0m\n");
printf("\nAST CREATION\n\n");
printf("*************************************************************************************\n\n");
asttreee = ast_creation(p);
printf("\nABSTRACT SYNTAX TREE CONSTRUCTED\n\n\n");
printf("PERFORMING SEMANTIC ANALYSIS OF THE SOURCE CODE\n\n\n");
st_node* root12 = create_st(asttreee);
if(SemErr!=0)
{
printf(RED"%d Semantic Errors Found\n"RESET, SemErr);
SemErr = 0;
}
else
printf(GREEN"No Semantic Errors Found\n"RESET);
printArray(root12);
return;
case 8:
fclose(sourceFile);
x='$';
sourceFile = fopen(filename, "a");
fputc(x,sourceFile);
fclose(sourceFile);
clock_t start_time, end_time;
double total_CPU_time, total_CPU_time_in_seconds;
start_time = clock();
sourceFile = fopen(filename, "r");
printf("\nPARSING THE INPUT\n");
printf("*************************************************************************************\n\n");
parseInputSourceCode(sourceFile, T);
fclose(sourceFile);
FILE* IpFile4 = fopen(filename, "r+");
fseek(IpFile4, -1, SEEK_END);
int position4 = ftello(IpFile4);
ftruncate(fileno(IpFile4), position4);
fclose(IpFile4);
if(SynxErr!=0 || LexErr!=0)
{
printf("\033[01;31m%d Syntactic Errors Found and %d Lexical Errors Found\n\033[0m\n", SynxErr, LexErr);
SynxErr = 0;
LexErr = 0;
return;
}
else
printf("\033[1;32mNo Syntactic and Lexical Errors Found\n\033[0m\n");
printf("\nAST CREATION\n\n");
printf("*************************************************************************************\n\n");
asttreee = ast_creation(p);
printf("\nABSTRACT SYNTAX TREE CONSTRUCTED\n\n\n");
printf("PERFORMING SEMANTIC ANALYSIS OF THE SOURCE CODE\n\n\n");
st_node* root3 = create_st(asttreee);
if(SemErr!=0)
{
printf(RED"%d Semantic Errors Found\n"RESET, SemErr);
SemErr = 0;
}
else
printf(GREEN"No Semantic Errors Found\n"RESET);
end_time = clock();
total_CPU_time = (double) (end_time - start_time);
total_CPU_time_in_seconds = total_CPU_time / CLOCKS_PER_SEC;
printf("\n\nTOTAL CPU TIME : %lf Clock Ticks\t\tTOTAL CPU TIME IN SECONDS: %lf s\n\n", total_CPU_time, total_CPU_time_in_seconds);
return;
case 9:
fclose(sourceFile);
x='$';
sourceFile = fopen(filename, "a");
fputc(x,sourceFile);
fclose(sourceFile);
start_time = clock();
sourceFile = fopen(filename, "r");
printf("\nPARSING THE INPUT\n");
printf("*************************************************************************************\n\n");
parseInputSourceCode(sourceFile, T);
fclose(sourceFile);
FILE* IpFile5 = fopen(filename, "r+");
fseek(IpFile5, -1, SEEK_END);
int position5 = ftello(IpFile5);
ftruncate(fileno(IpFile5), position5);
fclose(IpFile5);
if(SynxErr!=0 || LexErr!=0)
{
printf("\033[01;31m%d Syntactic Errors Found and %d Lexical Errors Found\n\033[0m\n", SynxErr, LexErr);
SynxErr = 0;
LexErr = 0;
return;
}
else
printf("\033[1;32mNo Syntactic and Lexical Errors Found\n\033[0m\n");
printf("\nAST CREATION\n\n");
printf("*************************************************************************************\n\n");
asttreee = ast_creation(p);
printf("\nABSTRACT SYNTAX TREE CONSTRUCTED\n\n\n");
printf("PERFORMING SEMANTIC ANALYSIS OF THE SOURCE CODE\n\n\n");
st_node* root4 = create_st(asttreee);
if(SemErr!=0)
{
printf(RED"%d Semantic Errors Found\n"RESET, SemErr);
SemErr = 0;
return;
}
else
printf(GREEN"No Semantic Errors Found\n"RESET);
CodeGenStart(asttreee, root4, asmfile);
printf(GREEN"\n\nCode Compiles Successfully..........\n\n"RESET);
printf("\nGenerated the NASM Assembly Level Code of your Program in file %s\n\n", asmfile);
end_time = clock();
total_CPU_time = (double) (end_time - start_time);
total_CPU_time_in_seconds = total_CPU_time / CLOCKS_PER_SEC;
printf("\n\nTOTAL CPU TIME : %lf Clock Ticks\t\tTOTAL CPU TIME IN SECONDS: %lf s\n\n", total_CPU_time, total_CPU_time_in_seconds);
return;
default:
printf("\n\nPLEASE ENTER A VALID OPTION BETWEEN 0 AND 9\n");
return;
}
return;
}
int main(int argc, char* argv[])
{
line_count = 1;
buf_count = 0;
DFA_state = Start;
Printst = Initial;
no_of_terminals = 0;
factor_nt = 317;
factor_t = 127;
//FIRST MESSAGE
printf("\nLEVEL 4 Compiler: Symbol Table / Type Checking / Semantic Rules Modules Work / Handled Static and Dynamic Arrays in Type Checking and Code Generation\n");
ht = initialize_hash_table();
ast_ht = ast_initialization();
parser();
int incorrect_attempts = 0;
char filename[30];
char* correctfile;
char *asmfile;
if(argv[2]==NULL || argv[1]==NULL)
asmfile = "code.asm";
else
asmfile = argv[2];
do{
if(incorrect_attempts>0)
{
printf("\n*************************** ERROR Opening the Source file (FILE NOT FOUND/ FILE NAME MORE THAN 30 CHARACTERS) ***************************\n\n\n");
printf("Try Different Name: ");
scanf("%s", filename);
sourceCode = fopen(filename, "r");
incorrect_attempts++;
}
else
{
sourceCode = fopen(argv[1], "r");
incorrect_attempts++;
}
}while(sourceCode==NULL || strlen(filename)>30);
incorrect_attempts--;
if(incorrect_attempts==0)
correctfile = argv[1];
else
correctfile = filename;
printf("\n******************* OPENED FILE \"%s\"*******************\n\n", correctfile);
fclose(sourceCode);
int option;
do{
printf("\n*************************************************************************************");
printf("\nMAIN MENU\n\n");
printf("0 -> EXIT\n");
printf("1 -> Printing the token list generated by the Lexer\n");
printf("2 -> Parsing the input by the Parser and produce Parse Tree\n");
printf("3 -> Creating the Abstract Syntax Tree\n");
printf("4 -> Calculating the Compression Percentage\n");
printf("5 -> Printing the Symbol Table\n");
printf("6 -> Printing the Activation Record Size (Stack Size) for each Function\n");
printf("7 -> Listing all the Static and Dynamic Arrays\n");
printf("8 -> Verifying the Semantic Correctness and Calculating Compile Time\n");
printf("9 -> Generating the Assembly Code (LINUX Based NASM v2.14.02)\n\n");
printf("Select an option: ");
scanf("%d", &option);
sourceCode = fopen(correctfile, "r");
if(option==0)
break;
menuOptions(option, sourceCode, correctfile, asmfile);
}while(1);
fclose(sourceCode);
printExitMsg();
return 0;
}
|
C
|
/*
* Name: Matthew Toro
* Class: CS344 Operating Systems
* Assignment: Program 4
* Due Date: 8/18/2017
* Description: Daemon that receives plain text from client, encrypts it, and sends it back
* */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
int main(int argc, char* argv[])
{
// set up the server information, borrowed from server.c from lecture
struct sockaddr_in serverAddress;
memset((char*)&serverAddress, '\0', sizeof(serverAddress));
int portNum = atoi(argv[1]);
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(portNum);
serverAddress.sin_addr.s_addr = INADDR_ANY;
// create the socket
int listenSocketFD = socket(AF_INET, SOCK_STREAM, 0);
if (listenSocketFD < 0)
{
fprintf(stderr, "Error: error opening socket");
exit(2);
}
// bind the socket
if (bind(listenSocketFD, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0)
{
fprintf(stderr, "Error: error on binding");
exit(2);
}
// begin listening
listen(listenSocketFD, 5);
// start the infinite loop here
while(1)
{
// accept a connection,
// if not valid, we send a message to stderr,
// else we fork off a child with a copy of the file descriptor
struct sockaddr_in clientAddress;
socklen_t sizeOfClientInfo = sizeof(clientAddress);
int establishedConnectionFD = accept(listenSocketFD, (struct sockaddr *)&clientAddress, &sizeOfClientInfo);
if (establishedConnectionFD < 0)
{
fprintf(stderr, "Error: error on accept");
}
else
{
// else fork off here
pid_t spawnPid = -5;
int childPID_actual;
int childExitMethod = -5;
spawnPid = fork();
switch (spawnPid)
{
case -1:
{
fprintf(stderr, "ERROR: fork failed\n");
close(establishedConnectionFD);
break;
}
case 0:
{
// begin fork child code
// recv message from client
char completeMessage[150000], readBuffer[10];
memset(completeMessage, '\0', sizeof(completeMessage));
int charsRead;
// i use a terminating sequence of "@@" to know when the message ends
while (strstr(completeMessage, "@@") == NULL)
{
memset(readBuffer, '\0', sizeof(readBuffer));
charsRead = recv(establishedConnectionFD, readBuffer, sizeof(readBuffer) - 1, 0);
if (charsRead < 0)
{
fprintf(stderr, "error reading from socket");
break ;
}
strcat(completeMessage, readBuffer);
}
int terminalLocation = strstr(completeMessage, "@@") - completeMessage;
completeMessage[terminalLocation] = '\0';
// tokenize the message on '\n'
// this lets me parse the message for relevant data
// the first token is whether the code is 'e' or not
// if it is 'e' we continue, else we send a rejection message back to the client
char * token = strtok(completeMessage, "\n");
if (token[0] == 'e')
{
// the second token is the plain text
token = strtok(NULL, "\n");
char * plainTextStr = malloc(strlen(token) * sizeof(char));
memset(plainTextStr, '\0', sizeof(plainTextStr));
strcpy(plainTextStr, token);
// the third token is key
token = strtok(NULL, "\n");
char * keyStr = malloc(strlen(token) * sizeof(char));
memset(keyStr, '\0', sizeof(keyStr));
strcpy(keyStr, token);
// set up variables for the encryption algorithm
// i add 5 characters to the cipher text for a code 'e-' and a terminating sequence '@@\n'
char * cipherText = malloc(((int) strlen(plainTextStr) + 5) * sizeof(char));
memset(cipherText, '\0', sizeof(cipherText));
strcpy(cipherText, "e-");
char letters[27] = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char merge[2];
// begin the loop
int i;
for (i = 0; i < strlen(plainTextStr); i++)
{
int plainTextIndex, keyIndex, trueIndex;
// if a space, set to 0; else, subtract 64 from ascii value
if (plainTextStr[i] == 32)
plainTextIndex = 0;
else if (plainTextStr[i] >= 65 && plainTextStr[i] <= 90)
plainTextIndex = plainTextStr[i] - 64;
// do the same here with the key
if (keyStr[i] == 32)
keyIndex = 0;
else if (keyStr[i] >= 65 && keyStr[i] <= 90)
keyIndex = keyStr[i] - 64;
// if the combined indices are greater than 26, mod it;
// else just use the sum
if (plainTextIndex + keyIndex > 26)
trueIndex = (plainTextIndex + keyIndex) % 27;
else
trueIndex = plainTextIndex + keyIndex;
memset(merge, '\0', sizeof(merge));
merge[0] = letters[trueIndex];
strcat(cipherText, merge);
}
// cat the terminating sequence
strcat(cipherText, "@@\0");
// right here we want to send a message back to the client
// this message tells the client we have finished recv and encrypting
// now the client can move on to recv
char go[3];
memset(go, '\0', sizeof(go));
strcpy(go, "go");
send(establishedConnectionFD, go, sizeof(go), 0);
// set up the loop to send the cipher text to the client
int totalBytes = strlen(plainTextStr) + 5;
int currentBytes = 0;
int leftoverBytes = totalBytes;
while(currentBytes < totalBytes)
{
charsRead = send(establishedConnectionFD, cipherText + currentBytes, leftoverBytes, 0);
if (charsRead < 0)
{
fprintf(stderr, "Server: error writing to socket\n");
break;
}
currentBytes += (int) charsRead;
leftoverBytes -= (int) charsRead;
}
// so I was running into a weird bug where the connection would fail in the client
// it turns out I was closing this socket before it was finished sending, so I now I force it to wait
// and then close
int checkSend = -5;
do
{
ioctl(establishedConnectionFD, TIOCOUTQ, &checkSend);
} while (checkSend > 0);
close(establishedConnectionFD);
// exit the child
exit(0);
}
else
{
// if the message receied from the client is anything but a 'e' then I send wrong program error message
char errMsg[19];
memset(errMsg, '\0', sizeof(errMsg));
strcpy(errMsg, "w-Wrong Program@@\n");
int totalBytes = strlen(errMsg);
int currentBytes = 0;
int leftoverBytes = totalBytes;
int charsRead;
while(currentBytes < totalBytes)
{
charsRead = send(establishedConnectionFD, errMsg + currentBytes, leftoverBytes, 0);
if (charsRead < 0)
{
fprintf(stderr, "Server: error writing to socket\n");
break;
}
currentBytes += (int) charsRead;
leftoverBytes -= (int) charsRead;
}
close(establishedConnectionFD);
exit(1);
}
break;
}
default:
{
// parent skips here
// close parent file descriptor
// waitpid nohang so we don't end up with lots of zombies
close(establishedConnectionFD);
childPID_actual = waitpid(-1, &childExitMethod, WNOHANG);
break;
}
}
}
}
close(listenSocketFD);
return 0;
}
|
C
|
/*
* simple_sink.c
*
* Created on: 7 Sep 2016
* Author: Raluca Diaconu
*/
#include <endpoint.h>
#include <middleware.h>
#include <load_mw_config.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
void print_callback(MESSAGE *msg)
{
ENDPOINT *ep = msg->ep;
/* parsing the message and extracting the values */
JSON* elem_msg = msg->_msg_json;
int value = json_get_int(elem_msg, "value");
char* datetime = json_get_str(elem_msg, "datetime");
/* process the extracted values */
printf("Sink ep handler:\n "
"\t-- number: %d \n "
"\t-- string: %s\n", value, datetime);
}
int main(int argc, char* argv[])
{
char *mw_cfg_path = NULL;
char *src_addr = NULL;
if (argc < 3) {
printf("Usage: ./simple_req [mw_cfg_path] addr\n"
"\tmw_cfg_path is the path to the config file for the middleware;\n"
"\t default mw_cfg.json\n"
"\tsink_addr is the address of the response component\n");
mw_cfg_path = "mw_cfg.json";
src_addr = argv[1];
}
else
{
mw_cfg_path = argv[2];
src_addr = argv[1];
}
/* load and apply configuration */
int load_cfg_result = load_mw_config(mw_cfg_path);
printf("Loading configuration: %s\n", load_cfg_result==0?"ok":"error");
printf("\tApp log level: %d\n", config_get_app_log_lvl());
/* start core */
char* app_name = mw_init("request_cpt", config_get_core_log_lvl(), 1);
printf("Initialising core: %s\n", app_name!=NULL?"ok":"error");
printf("\tApp name: %s\n", app_name);
/* load coms modules for the core */
config_load_com_libs();
//printf("Load coms module result: %s\n", load_cfg_result==0?"ok":"error");
/* load access modules for the core */
load_cfg_result = mw_load_access_module(
"/Users/admin/dev/middleware/build/lib/libmoduleaclplain.so",
"/Users/admin/dev/middleware/modules/access_modules/plain/aclplain.cfg.json");
printf("Loading access module: %s\n", load_cfg_result==0?"ok":"error");
/* Declare and register endpoints */
ENDPOINT* ep_req = endpoint_new_req_file(
"ep_req",
"example req endpoint",
"example_schemata/datetime_value.json", /* request schemata */
"example_schemata/datetime_value.json", /* response schemata */
&print_callback);
/* build the query */
Array* ep_query_array = array_new(ELEM_TYPE_STR);
array_add(ep_query_array, "ep_name = 'ep_response'");
JSON* ep_query_json = json_new(NULL);
json_set_array(ep_query_json, NULL, ep_query_array);
char* ep_query_str = json_to_str(ep_query_json);
char* cpt_query_str = "";
printf("\n\nQuery string: *%s*\n\n", ep_query_str);
/* map according to the query */
int map_result = endpoint_map_to(ep_req, src_addr, ep_query_str, cpt_query_str);
printf("Map result: %d \n", map_result);
time_t rawtime;
struct tm* timeinfo;
JSON* msg_json;
char* message;
char* msgid;
int i = 0;
while (i < 1000)
{
i++;
sleep(3);
time ( &rawtime );
timeinfo = localtime ( &rawtime );
msg_json = json_new(NULL);
json_set_int(msg_json, "value", rand() % 10);
json_set_str(msg_json, "datetime", asctime(timeinfo));
message = json_to_str(msg_json);
msgid = endpoint_send_request(ep_req, message);
printf("Request %s: \n%s\n", msgid, message);
free(message);
free(msgid);
json_free(msg_json);
}
return 0;
}
|
C
|
#define DR 0x00
#define FR 0x18
#define RXFE 0x10
#define TXFF 0x20
typedef struct uart{
char *base;
int n;
}UART;
UART uart[4];
int uart_init()
{
int i; UART *up;
for (i=0; i<4; i++){
up = &uart[i];
up->base = (char *)(0x101F1000 + i*0x1000);
up->n = i;
}
uart[3].base = (char *)(0x10009000); // uart3 at 0x10009000
}
int ugetc(UART *up)
{
while (*(up->base + FR) & RXFE);
return *(up->base + DR);
}
int uputc(UART *up, char c)
{
while(*(up->base + FR) & TXFF);
*(up->base + DR) = c;
}
int ugets(UART *up, char *s)
{
while ((*s = (char)ugetc(up)) != '\r'){
uputc(up, *s);
s++;
}
*s = 0;
}
int uprints(UART *up, char *s)
{
while(*s)
uputc(up, *s++);
}
/** WRITE YOUR uprintf(UART *up, char *fmt, . . .) for formatted print **/
|
C
|
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
int main(){
int fd[2];
char b[25]="Hello World",b1[25];
fd[0] = open("./file.txt",O_CREAT | O_RDWR);
fd[1] = open("./file2.txt",O_CREAT | O_RDWR);
write(fd[0],b,strlen(b));
lseek(fd[0],6,SEEK_SET);
int value = read(fd[0],b1,10);
printf("%d",value);
write(fd[1],b1,strlen(b1));
close(fd[0]);
close(fd[1]);
return 0;
}
|
C
|
#include "diff.h"
#include "abs_max.h"
#include "abs_min.h"
#include <stdlib.h>
int diff(int *A, int N){
int diff;
int max=abs_max(A, N);
int min=abs_min(A, N);
int d=max-min;
return d;
}
|
C
|
#include <stdio.h>
#include <string.h>
void main (void)
{
char str1[10] = "First"
char str2[10] = "Second"
char str3[20];
strcpy(str3, str1);
strcpy(str3, str2);
printf("%s + %s = %s\n", str1, str2, str3);
}
|
C
|
#define MAX 512
#include "rozciaganie.h"
void rozciaganie(int obraz_pgm[][MAX],int *wymx,int *wymy,int *szarosci)
{
int Lmax=1,Lmin=*szarosci;
//szukanie najwiekszego elementu
for(int i=0;i<*wymy;i++){
for(int j=0;j<*wymx;j++){
if(obraz_pgm[i][j]>=Lmax)
Lmax=obraz_pgm[i][j];
}
}
//szukanie najmniejszego elementu
for(int i=0;i<*wymy;i++){
for(int j=0;j<*wymx;j++){
if(obraz_pgm[i][j]<=Lmin)
Lmin=obraz_pgm[i][j];
}
}
//uzupelnianie tablicy nowymi wartosciami
for(int i=0;i<*wymy;i++){
for(int j=0;j<*wymx;j++){
obraz_pgm[i][j]=(obraz_pgm[i][j]-Lmin)*(*szarosci)/(Lmax-Lmin);
}
}
}
|
C
|
/***
-----------------------------------------------------------------------------
PG7233
-----------------------------------------------------------------------------
Package name : main
Description : Rising Force Fighters
Authors : David Altuve & Leonardo Cabrera
Email : 19-91255@usb.ve / 20-91371@usb.ve
Version : 01.00
Revision : 00
Date : 7/18/2021
-----------------------------------------------------------------------------
* This main module executes the routines for the game Rising Force Fighters
***/
/* Standard libraries */
#include <stdio.h>
#include "lcd.h"
/* Local libraries */
#include "functions.h"
#include "menu.h"
void main()
{
//System and LCD initialization
SYSTEM_Initialize();
LCD_Initialize();
//Sprite creation
unsigned char Pattern1 [ ] = {0x0E,0x08,0x1C,0x1F,0x1C,0x08,0x0E,0x00}; //xwing
unsigned char Pattern2 [ ] = {0x00,0x0A,0x11,0x15,0x15,0x11,0x0A,0x00}; //Tie Fighter
unsigned char Pattern3 [ ] = {0x00,0x00,0x0E,0x1F,0x0E,0x00,0x00,0x00}; //Bullet
unsigned char Pattern4 [ ] = {0x00,0x00,0x0A,0x1F,0x1F,0x0E,0x04,0x00}; //full heart
unsigned char Pattern5 [ ] = {0x0E,0x02,0x07,0x1F,0x07,0x02,0x0E,0x00}; //reversed xwing
unsigned char Pattern8 [ ] = {0x00,0x1F,0x1F,0x1F,0x1F,0x0E,0x04,0x00}; //full shield
/*Character storage into LCD's memory*/
createCustomCharacter(Pattern1,1);
createCustomCharacter(Pattern2,0);
createCustomCharacter(Pattern3,2);
createCustomCharacter(Pattern4,3);
createCustomCharacter(Pattern5,4);
createCustomCharacter(Pattern8,7);
//LCD PRINTING
//idleScreen();
welcomeScreen();
printMenu();
// Enable the Global Interrupts
INTERRUPT_GlobalInterruptEnable();
// disable player 2 buttons
disableButton(true);
while (1)
{
}
}
|
C
|
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/*Estructuras*/
//Tipos de escenario
typedef struct bajoCoste{
char* nombre;
char* zona;
}bajoCoste;
typedef struct estandar{
char* nombre;
}estandar;
typedef struct deLujo{
char* nombre;
int visitas;
}deLujo;
//Escenario
typedef struct escenario{
char* nombre;
void* categoria;
}escenario;
//Recuerdos
typedef struct recuerdo{
char* descripcion;
escenario* Escenario;
}recuerdo;
typedef struct nodo_recuerdo{
recuerdo Recuerdo;
struct nodo_recuerdo* siguiente;
}nodo_recuerdo;
//Anfitriones
typedef struct anfitrion{
char* nombre;
int energia;
float procesamiento;
nodo_recuerdo* recuerdos;
}anfitrion;
typedef struct nodo_anfitrion{
anfitrion anfitrion;
struct nodo_anfitrion* siguiente;
}nodo_anfitrion;
//Huespedes
typedef struct huesped huesped;
typedef struct nodo_huesped nodo_huesped;
struct huesped{
char* nombre;
int energia;
int minutosRestantes;
nodo_anfitrion* anfitriones;
nodo_huesped* huespedes;
};
struct nodo_huesped{
huesped huesped;
nodo_huesped* siguiente;
};
//Tramas
typedef struct trama{
nodo_huesped* huespedes;
nodo_anfitrion* anfitriones;
escenario* escenario;
}trama;
/*Funciones*/
//Funciones para inicializar las estructuras
bajoCoste* inicializarTipoBajoCoste(char*);
estandar* inicializarTipoEstandar();
deLujo* inicializarTipoDeLujo(int);
anfitrion* inicializarAnfitrion(char*, int, float, nodo_recuerdo*);
huesped* inicializarHuesped(char*, int, int, nodo_anfitrion*, nodo_huesped*);
recuerdo* inicializarRecuerdo(char*, escenario*);
escenario* inicializarEscenario(char*, void*);
//Funciones para agregar elementos a las listas
nodo_anfitrion* agregarAnfitrionALista(anfitrion*, nodo_anfitrion*);
nodo_huesped* agregarHuespedALista(huesped*, nodo_huesped*);
nodo_recuerdo* agregarRecuerdoALista(recuerdo*, nodo_recuerdo*);
//Funciones para mostrar
void mostrarAnfitriones(nodo_anfitrion*);
void mostrarAnfitrion(anfitrion*);
void mostrarHuesped(huesped*);
void mostrarEscenario(escenario*);
void mostrarRecuerdos(nodo_recuerdo*);
//Funciones relacionadas al enunciado del parcial
float felicidadDeAnfitrion(anfitrion*);
float rebeldiaDeAnfitrion(anfitrion*);
float mapearFelicidadAnfitriones(nodo_anfitrion*);
float mapearFelicidadHuespedes(nodo_huesped*);
int nivelDeFama(escenario*);
int emotividad(recuerdo*);
int felicidadDeHuesped(huesped*);
double rebeldiaHuesped(huesped*);
escenario* evolucionarEscenario(escenario*);
void conocerEscenarioAnfitrion(anfitrion*, escenario*);
void conocerEscenarioHuesped(huesped*, escenario*);
anfitrion anfitrionMasFeliz(nodo_anfitrion*);
huesped huespedMasFeliz(nodo_huesped*);
float complejidad(trama);
bool huespedEsRebelde(huesped*);
bool anfitrionEsRebelde(anfitrion*);
bool todosAnfitrionesRebeldes(nodo_anfitrion* Anfitriones);
bool todosHuespedesRebeldes(nodo_huesped*);
bool esPicante(trama);
void matarAnfitrionesRebeldes(nodo_anfitrion*);
void renovar(trama);
//Funciones de utilidad
char* strconcat(char*, char*);
float ini_felicidadAnfitrion(anfitrion);
float ini_felicidadHuesped(huesped);
|
C
|
#include <stdio.h>
#include <windows.h>
void version1(DWORD pid, int process_num) {
int j;
for (j=1; j <= 10; j++)
fprintf(stderr, "[Process #%d] \t ID: %d \t Value: %d\n", process_num, pid, j);
}
void version2(DWORD pid, int process_num) {
int j;
for (j=1; j <= 10; j++) {
fprintf(stderr, "[Process #%d] \t ID: %d \t Value: %d\n", process_num, pid, j);
Sleep(1);
}
}
void version3(DWORD pid, int process_num) {
char *values = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10";
fprintf(stderr, "[Process #%d] \t ID: %d \t Values:\n%s\n", process_num, pid, values);
Sleep(1);
}
void version4(DWORD pid, int process_num) {
char *output;
char *values = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10";
sprintf(output, "[Process #%d] \t ID: %d \t Values:\n%s\n", process_num, pid, values);
fputs(output, stderr);
Sleep(1);
}
void version5(DWORD pid, int process_num) {
char output[256];
char *values = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10";
int output_length;
memset(output, '\0', 256);
sprintf(output, "[Process #%d] \t ID: %d \t Values:\n%s\n", process_num, pid, values);
WriteFile(GetStdHandle(STD_ERROR_HANDLE), &output, strlen(output), NULL, NULL);
Sleep(1);
}
int main(int argc, char *argv[]) {
// Selects which implementation to run based on the first argument
int version = atoi(argv[1]);
int iteration = atoi(argv[2])+1;
DWORD pid = GetCurrentProcessId();
if (version == 1)
version1(pid, iteration);
else if (version == 2)
version2(pid, iteration);
else if (version == 3)
version3(pid, iteration);
else if (version == 4)
version4(pid, iteration);
else if (version == 5)
version5(pid, iteration);
return 0;
}
|
C
|
// File Name: switching_led
// Author: R.venkatesan
# include <reg51.h>
# include <stdio.h>
sbit led_blink =P1^0 ; // led pin connected on port1^0
sbit switch_led=P1^1; // switch connected on port 1^1
void main()
{
switch_led=1; // pullup input pin
while(1) // while loop for contiue woking on program endless
{
if(switch_led==1) // check the input occur if is true led on
{
led_blink=1;
}
else // if is flase led off
{
led_blink=0;
}
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* render_projection_1.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: romanbtt <marvin@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/23 21:16:01 by romanbtt #+# #+# */
/* Updated: 2021/01/30 17:15:14 by romanbtt ### ########.fr */
/* */
/* ************************************************************************** */
#include "cub3d.h"
/*
** This function choose which texture need to be load depending on where
** the ray is facing and if the hit was vertical or not.
*/
static void select_texture(t_texture *text, t_ray *ray)
{
if (ray->isray_up && !ray->hit_vert)
text->curr = text->no;
else if (ray->isray_down && !ray->hit_vert)
text->curr = text->so;
else if (ray->isray_right && ray->hit_vert)
text->curr = text->ea;
else if (ray->isray_left && ray->hit_vert)
text->curr = text->we;
}
/*
** This function calculate the height of the wall and where it begins
** and where it stops. Perp_dist is calculated to get rid of the fisheye
** effect that happens.
** Top_strp is where the wall begins. It is calculated with the height
** resolution / 2 - the height of a wall / 2.
** Btm_strp is where the wall stops. It is calculated with the height
** resolution / 2 + the height of a wall / 2.
*/
static void calc_wall_height(t_struct *cub, t_wall *wall, int col)
{
wall->perp_dist = cub->ray[col].dist * cos(cub->ray[col].ray_angle -
cub->player.rot_angle);
wall->proj_wall_height = (cub->map.tile_size / wall->perp_dist) *
wall->dist_proj_plane;
wall->top_strp = (cub->map.height / 2) - (int)(wall->proj_wall_height / 2);
if (wall->top_strp < 0)
wall->top_strp = 0;
wall->btm_strp = (cub->map.height / 2) + (int)(wall->proj_wall_height / 2);
if (wall->btm_strp > cub->map.height)
wall->btm_strp = cub->map.height;
}
/*
** This function handle the print projection of the wall, ceiling, and floor.
** For each ray until the width resolution is reach we call :
** The engine function that calculates the height of the wall.
** Print_ceiling that will display the ceiling color.
** Select_texture that will choose which texture to load.
** Print_wall that will display the wall with texture.
** Print_floor that will display the floor color.
** Then col is incremented by one.
*/
void render_projection(t_struct *cub)
{
int col;
t_wall wall;
col = 0;
wall.dist_proj_plane = (cub->map.width / 2) / tan(FOV / 2);
while (col < cub->map.width)
{
calc_wall_height(cub, &wall, col);
print_ceiling(cub, &wall, col);
select_texture(&cub->text, &cub->ray[col]);
print_wall(cub, &wall, col);
print_floor(cub, &wall, col);
col++;
}
}
|
C
|
#include "stdio.h"
int main() {
/*Leia 100 valores inteiros. Apresente então o maior valor lido e a posição dentre os 100 valores lidos. */
int valor, pos, maior = 0;
for(int i = 0; i < 100; i++){
scanf("%i", &valor);
if(valor > maior) {
maior = valor;
pos = i + 1;
}
}
printf("\nMaior: %i\nPosição: %i", maior, pos);
}
|
C
|
#include "fonctions.h"
void afficher_entete()
{
system("clear");
printf(JAUNE);
printf("\t\t\t =======================\n");
printf("\t\t\t == Shell ==\n");
printf("\t\t\t =======================\n\n" FIN);
printf(" Entrez une commande (ou help pour afficher l'aide) : \n\n");
printf(BLEU " $ " FIN);
}
void afficher_help(char* cmd)
{
int existe = 0;
printf("\n");
if(strcmp(cmd, "lire") == 0 || strcmp(cmd, "ALL") == 0)
{
existe = 1;
printf("\n");
printf(JAUNE " lire\n");
printf(VERT "\t Description : " FIN " Afficher le contenu du fichier passé en argument.\n");
printf(VERT "\t Syntaxe : " BLEU " $ " FIN "lire fichier\n\n");
}
if(strcmp(cmd, "concat") == 0 || strcmp(cmd, "ALL") == 0)
{
existe = 1;
printf(JAUNE " concat\n");
printf(VERT "\t Description : " FIN " Concaténer les fichiers passés en arguments \n");
printf(VERT "\t Syntaxe : " BLEU " $ " FIN "concat f1 f2 [f3 ..] resultat\n\n");
}
if(strcmp(cmd, "compiler") == 0 || strcmp(cmd, "ALL") == 0)
{
existe = 1;
printf(JAUNE " compiler\n");
printf(VERT "\t Description : " FIN "Compiler le programme passé en argument.\n");
printf(VERT "\t Syntaxe : " BLEU " $ " FIN "compile nom_prog_a_compiler\n\n");
}
if(strcmp(cmd, "salut") == 0 || strcmp(cmd, "ALL") == 0)
{
existe = 1;
printf(JAUNE " salut\n");
printf(VERT "\t Description : " FIN "Dire \"Salut!\" aux noms passés.\n");
printf(VERT "\t Syntaxe : " BLEU " $ " FIN "Salut nom1 [, nom2 ..]\n\n");
}
if(!existe)
{
existe = 1;
printf(ROUGE "\n La commande %s n'existe pas, Veuillez réessayer.\n\n" FIN, cmd);
}
}
|
C
|
int fact(int a) {
if (a <= 1)
return 1;
return a * fact(a - 1);
}
int main() {
int f = fact(3);
test_assert(f == 6);
return 0;
}
|
C
|
/* Test Virtual P's and V's. pvTestA (consumer) and pvTestB (producer)
* exchange a message using the shared segment for synchronization
* and data transmission.
*/
#include "../../h/const.h"
#include "../../h/types.h"
#include "h/tconst.h"
#include "/usr/local/include/umps2/umps/libumps.e"
#include "print.e"
int *hold = (int *)(SEG3);
int *empty = (int *)(SEG3 + 4);
int *full = (int *)(SEG3 + 8);
char *charbuff = (char *)(SEG3 + 12);
void main() {
int mysem;
char *msg;
print(WRITETERMINAL, "pvBTest starts\n");
/* give t3 a chance to start up and initialize shared memory */
/* Delay for 2 seconds */
SYSCALL(DELAY, 5, 0, 0);
SYSCALL(VSEMVIRT, hold, 0, 0);
print(WRITETERMINAL, "pvBTest is free\n");
msg = "virtual synch OK\n"; /* message to be sent to t3 */
/* send message to t3 */
do {
SYSCALL(PSEMVIRT, empty, 0, 0);
*charbuff = *msg;
print(WRITETERMINAL, ".");
SYSCALL(VSEMVIRT, full, 0, 0);
} while (*msg++ != '\0');
print(WRITETERMINAL, "\npvBTest finished sending\n");
print(WRITETERMINAL, "pvBTest completed\n");
/* try to block on a private semaphore */
mysem = 0;
SYSCALL(PSEMVIRT, &mysem, 0, 0);
/* should never reach here */
print(WRITETERMINAL, "pvBTest error: private sem block did not terminate\n");
SYSCALL(TERMINATE, 0, 0, 0);
}
|
C
|
#include <stdio.h> /* for print */
#include <fcntl.h> /* for open() */
#include <unistd.h> /* for pathconf() */
#include <string.h> /* for strcat() */
#include <stdlib.h> /* for malloc() */
#include <errno.h> /* for errno */
int main(int argc, char *argv[])
{
char *pathname;
pathname="/Users/zouhairkhallaf/Desktop/";
char filename[1000];
for (int i=0; i<999; i++)
(void) strcat(filename, "a");
char *abs_path;
if ( (abs_path=malloc(strlen(pathname)+strlen(filename)+1))!=NULL )
{
abs_path[0]='\0';
strcat(abs_path, pathname);
strcat(abs_path, filename);
}
else
printf("malloc() failed\n");
printf("Long path: %s\n", abs_path);
int fd=open(abs_path, O_RDWR|O_CREAT|O_TRUNC);
long e=pathconf(abs_path, _PC_NO_TRUNC);
printf("%s\n", strerror(errno));
return 0;
}
|
C
|
#include <stdio.h>
const static int MAX_LEN = 64;
int is_in_array(float, float*, int);
float floatmod(float, float);
float get_sum_of_remainders(float*, int);
int main() {
float arr[MAX_LEN];
float num;
int i = 0;
while(scanf("%f", &num) != EOF) {
if(!is_in_array(num, arr, i)) {
arr[i] = num;
i++;
}
}
printf("%d\n", i);
printf("%.3f\n", get_sum_of_remainders(arr, i));
return 0;
}
int is_in_array(float num, float* arr, int len) {
for(int i = 0; i < len; i++) {
if(arr[i] == num) {
return 1;
}
}
return 0;
}
float floatmod(float a, float b) {
// Stackoverflow <3
return (a - b * (int)(a / b));
}
float get_sum_of_remainders(float* arr, int total_count) {
float result = 0.0f;
for(int i = 0; i < total_count; i++) {
result += floatmod(arr[i], total_count);
}
return result;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.