language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h> //Bitwise stuf
#include <sys/wait.h>
#include <stdlib.h>
#include <assert.h>
#include "tokenize.h"
#include "svec.h"
#include <fcntl.h> // for open sysCall
// Written By Josh Spicer
// Used Nat Tuck's "sort-pipe.c" example from class
// HELPERS for ops
void routeInHelper(svec* left, svec* right);
void routeOutHelper(svec* left, svec* right);
void pipeHelper(svec* left, svec* right);
void pipeHelperLeft(svec* left, svec* right, int arr[]);
void pipeHelperRight(svec* right, int arr[]);
void andHelper(svec* left, svec* right);
void orHelper(svec* left, svec* right);
void backgroundHelper(svec* vector);
// STUBS
void splitInTwo(svec* original, svec* left, svec* right, int index);
int areThereMorePipes(svec* right);
// SUB-MAIN
void processTokens(svec* tokens);
void execute(char* cmd, char* arg[]);
void run(svec* cmd);
// ------------------------------------------------------------------------- //
// Handles the route in redirection
void
routeInHelper(svec* left, svec* right) {
int cpid;
// FORK
if ((cpid = fork())) {
//** PARENT ** //
int status;
waitpid(cpid, &status, 0);
} else {
// ** CHILD ** //
// OPEN TARGET
int input = open(svec_get(right,0), O_RDONLY);
// DUP
close(0); //Close std:in
dup(input);
close(input);
// EXEC
// Process additional tokens recursively
processTokens(left);
// char* args[] = {svec_get(left,0), 0};
// execute(svec_get(left,0), args);
}
}
// ------------------------------------------------------------------------- //
// Handles the route out redirection
void
routeOutHelper(svec* left, svec* right) {
int cpid;
// FORK
if ((cpid = fork())) {
//** PARENT ** //
int status;
waitpid(cpid, &status, 0);
} else {
// ** CHILD ** //
// Open Target
int output =
open(svec_get(right,0),
O_CREAT | O_TRUNC | O_WRONLY,
S_IWUSR | S_IRUSR);
// DUP
close(1); //Close std:out
dup(output);
close(output);
// EXEC
// Process additional tokens recursively
processTokens(left);
close(1); //Close std:out again
}
}
// ------------------------------------------------------------------------- //
// Helper for the pipe command
void
pipeHelper(svec* left, svec* right) {
// PIPE System Call
int pipeArr[2];
pipe(pipeArr);
if (!fork()) {
// ** CHILD ** //
// Close Std:out
close(1);
// Duplicate the Writing end of the pipe
dup(pipeArr[1]);
// Clean up!
close(pipeArr[0]);
// EXEC
processTokens(left);
} else {
// ** PARENT ** //
// int status;
// int cpid;
// waitpid(cpid, &status, 0);
// Close Std:In
close(0);
// Duplicate the reading end of the pipe
dup(pipeArr[0]);
// Clean up!
close(pipeArr[1]);
// EXEC
// Process additional tokens recursively
processTokens(right);
}
}
// ------------------------------------------------------------------------- //
// Helper for the AND command
void
andHelper(svec* left, svec* right) {
int cpid;
// FORK
if ((cpid = fork())) {
//** PARENT ** //
int status;
waitpid(cpid, &status, 0);
// Print the status returned
//printf("%d\n", status); //TEST CODE
// If and only if the left side is TRUE, evaluate the right side
if (status == 0) {
processTokens(right);
}
} else {
// ** CHILD ** //
// EXEC
run(left);
//printf("%s\n", "DANGER: ran past execvp in AND function.");
}
}
// ------------------------------------------------------------------------- //
// Helper for the OR command
void
orHelper(svec* left, svec* right) {
int cpid;
// FORK
if ((cpid = fork())) {
//** PARENT ** //
int status;
waitpid(cpid, &status, 0);
// Print the status returned
//printf("%d\n", status); //TEST CODE
// If status is not TRUE from left side, we must evaluate right side
if (status != 0) {
processTokens(right);
}
} else {
// ** CHILD ** //
// EXEC
run(left);
//printf("%s\n", "DANGER: ran past execvp in OR function.");
}
}
// ------------------------------------------------------------------------- //
// Helper for the & command
// Puts the given cmd into background process
void
backgroundHelper(svec* vector) {
int cpid;
// FORK
if ((cpid = fork())) {
//** PARENT ** //
// Don't put anything here!
} else {
// ** CHILD ** //
// EXEC
run(vector);
//printf("%s\n", "DANGER: ran past execvp in backgrounding function.");
}
}
// ------------------------------------------------------------------------- //
// Divides up an svec into two svecs split at the index
// store left and right sides into arguments as appropriate
void
splitInTwo(svec* original, svec* left, svec* right, int index) {
for (int i = 0; i < original->size;i++) {
if (i < index) {
svec_push_back(left, svec_get(original,i));
}
if (i > index) {
svec_push_back(right, svec_get(original,i));
}
}
}
// -------------------------------------------------------------------------- //
// returns 0 if a | is detected.
int
areThereMorePipes(svec* right) {
for (int i = 0; i < right->size;i++) {
char* pipeSymbol = "|";
if (strcmp(svec_get(right, i), pipeSymbol) == 0) {
return 0;
}
}
return 1;
}
// ------------------------------------------------------------------------- //
// This function will check for pipes/redirection/other operators/etc
// And do the appropriate branching when found.
// RECURSIVELY call this function to determine how to handle special ops
void
processTokens(svec* tokens) {
// HUNT DOWN SEMICOLONS
// Solve each side recursively instead of in THIS interactions
for (int index = 0; index < tokens->size;index++) {
char* semiColonStr = ";";
if (strcmp(svec_get(tokens, index), semiColonStr) == 0) {
svec* left = make_svec();
svec* right = make_svec();
splitInTwo(tokens, left, right, index);
processTokens(left);
processTokens(right);
return;
}
}
// HUNT DOWN PIPES
for (int index = 0; index < tokens->size;index++) {
// ** Check for Pipe ** //
char* pipeStr = "|";
if (strcmp(svec_get(tokens, index), pipeStr) == 0) {
// Split
svec* left = make_svec();
svec* right = make_svec();
splitInTwo(tokens, left, right, index);
// Check if there are more pipes.
if (areThereMorePipes(right)) {
}
pipeHelper(left, right);
return;
}
}
// Iterate through entire tokens looking for special operators
for (int index = 0; index < tokens->size;index++) {
// ** Check for "exit" token ** //
char* exitStr = "exit";
if (strcmp(svec_get(tokens, index), exitStr) == 0) {
// printf("%s\n", "Triggered exit"); //TEST CODE
exit(0);
}
// ** Check for "cd" token ** //
char* cd = "cd";
if (strcmp(svec_get(tokens, index), cd) == 0) {
char* dirToChangeTo = svec_get(tokens, index + 1);
//printf("cd to %s\n", dirToChangeTo); //TEST CODE
int statusCode = chdir(dirToChangeTo);
assert(statusCode == 0);
// assert(0);
// printf("Status of CD: %d\n", statusCode); //TEST CODE
return;
}
// ** Check for route-in ** //
char* routInStr = "<";
if (strcmp(svec_get(tokens, index), routInStr) == 0) {
svec* left = make_svec();
svec* right = make_svec();
splitInTwo(tokens, left, right, index);
// Defer to a helper function
routeInHelper(left, right);
return;
}
// ** Check for route-out ** //
char* routOutStr = ">";
if (strcmp(svec_get(tokens, index), routOutStr) == 0) {
svec* left = make_svec();
svec* right = make_svec();
splitInTwo(tokens, left, right, index);
// Defer to a helper function
routeOutHelper(left, right);
return;
}
// ** Check for AND ** //
char* andStr = "&&";
if (strcmp(svec_get(tokens, index), andStr) == 0) {
svec* left = make_svec();
svec* right = make_svec();
splitInTwo(tokens, left, right, index);
// Defer to a helper function
andHelper(left, right);
return;
}
// ** Check for OR ** //
char* orStr = "||";
if (strcmp(svec_get(tokens, index), orStr) == 0) {
svec* left = make_svec();
svec* right = make_svec();
splitInTwo(tokens, left, right, index);
// Defer to a helper function
orHelper(left, right);
return;
}
//** Check for background token (&) **//
char* bgStr = "&";
if (strcmp(svec_get(tokens, index), bgStr) == 0) {
// Defer to a helper function
backgroundHelper(tokens);
return;
}
} // end of big for-loop
// Got to the end without forking somewhere else
// This is simple command execution with unlimited simple args
char* command = svec_get(tokens, 0);
char* argument[20];
argument[0] = command;
for (int i = 1; i < tokens->size;i++) {
argument[i] = svec_get(tokens,i);
}
argument[tokens->size] = 0;
// Send command and args to execute method
execute(command, argument);
// *********** TEST CODE *********
// char* command = "echo";
// char* args[] = {command, "JOSHUASPICER", 0};
// execvp(command, args);
}
// ------------------------------------------------------------------------- //
// Execute the passed in {cmd} with the specified {arg}
// In a new process
// {arg}'s first element must be {cmd}, and must be null-termianted.
// Executes in a fork()
void
execute(char* cmd, char* arg[])
{
int cpid;
if ((cpid = fork())) {
// parent process
int status;
waitpid(cpid, &status, 0);
}
else {
// child process
execvp(cmd, arg);
//printf("==== EXEC ERROR ===");
}
}
// ------------------------------------------------------------------------- //
// Runs a command by setting up the correct arguments
// and then passing off to execvp
void
run(svec* cmd) {
char* command = svec_get(cmd, 0);
char* argument[50];
argument[0] = command;
for (int i = 1; i < cmd->size;i++) {
argument[i] = svec_get(cmd,i);
}
argument[cmd->size] = 0;
execvp(command, argument);
}
// ------------------------------------------------------------------------- //
int
main(int argc, char* argv[])
{
char cmd[256];
// Place where an input is temporarily sent to before tokenized
char temp[400];
// Represents the fd of inputted .sh file (if there is one)
FILE* input;
if (argc == 1) { // NO argument upon first starting nush
// Initial prompt print
printf("nush$ ");
while (fgets(cmd, 256, stdin) != NULL) {
fflush(stdout);
svec* tokens = tokenize(cmd);
// // *********** TEST CODE *********
// printf("\n\n\n\n\n\n\n\n");
// dyArray_print_with_interrupt(tokens);
// printf("\n\n\n\n\n\n\n\n");
// // **********************************
//TODO execute...
processTokens(tokens);
printf("nush$ ");
free_svec(tokens);
}
} else { // .sh file as argument upon first starting nush
// Open up the given file!
input = fopen(argv[1], "r");
while (fgets(temp, 400, input) != NULL) {
// Tokenize this line of input
svec* tokens = tokenize(temp);
// // *********** TEST CODE *********
// printf("\n\n\n\n");
// dyArray_print_with_interrupt(tokens);
// printf("\n\n\n\n");
// // **********************************
// Execute
processTokens(tokens);
// Free up tokens svec for next line (if there is one)
free_svec(tokens);
}
}
// fclose(input);
return 0;
}
|
C
|
#include "malloc2.h"
static char big_block[BLOCKSIZE];
static char* mem_val[MEMSIZE]; //stores memory addresses of allocated memory
// return a pointer to the memory buffer requested
void* my_malloc(unsigned int size, char *file, int line)
{
static int initialized = 0;
static struct MemEntry *root;
struct MemEntry *p;
struct MemEntry *succ;
char * result;
int i = 0; //used for while loop to store an allocated memory address into mem_val
if(!initialized) // 1st time called
{
// create a root chunk at the beginning of the memory block
root = (struct MemEntry*)big_block;
root->prev = root->succ = 0;
root->size = BLOCKSIZE - sizeof(struct MemEntry);
root->isfree = 1;
initialized = 1;
}
p = root;
do
{
if(p->size < size)
{
// the current chunk is smaller, go to the next chunk
p = p->succ;
}
else if(!p->isfree)
{
// this chunk was taken, go to the next
p = p->succ;
}
else if(p->size < (size + sizeof(struct MemEntry)))
{
// this chunk is free and large enough to hold data,
// but there's not enough memory to hold the HEADER of the next chunk
// don't create any more chunks after this one
p->isfree = 0;
result = (char*)p + sizeof(struct MemEntry);
//store allocated memory address into mem_val
while(1){
if(mem_val[i] == 0){
mem_val[i] = result;
break;
}
i++;
}
return result;
}
else
{
// take the needed memory and create the header of the next chunk
succ = (struct MemEntry*)((char*)p + sizeof(struct MemEntry) + size);
succ->prev = p;
succ->succ = p->succ;
//begin add
if(p->succ != 0)
p->succ->prev = succ;
p->succ = succ;
//end add
succ->size = p->size - sizeof(struct MemEntry) - size;
p->size = size;
p->isfree = 0;
succ->isfree = 1;
result = (char *)p + sizeof(struct MemEntry);
//store allocated memory address into mem_val
while(1){
if(mem_val[i] == 0){
mem_val[i] = result;
break;
}
i++;
}
return result;
}
} while(p != 0);
fprintf(stderr, "%s line: %d - Failed, dynamic memory is full, try freeing.\n", file, line);
return 0;
}
// free a memory buffer pointed to by p
void my_free(void *p, char *file, int line)
{
int i;
//checks if memory address p was allocated
for(i = 0; i < MEMSIZE; i++){
if(mem_val[i] == (char *)p)
break;
}
struct MemEntry *ptr;
struct MemEntry *prev;
struct MemEntry *succ;
ptr = (struct MemEntry*)((char*)p - sizeof(struct MemEntry));
//checks if the memory address being freed is in big_block or if it wasn't found in mem_val
if(ptr < (struct MemEntry*)big_block || ptr > (struct MemEntry*)big_block+BLOCKSIZE || i == MEMSIZE) {
fprintf(stderr, "%s line: %d - Attempting to free something that wasn't allocated or was previously freed.\n", file, line);
return;
}
if((prev = ptr->prev) != 0 && prev->isfree)
{
// the previous chunk is free, so
// merge this chunk with the previous chunk
prev->size += sizeof(struct MemEntry) + ptr->size;
//begin add
ptr->isfree=1;
prev->succ = ptr->succ;
if(ptr->succ != 0)
ptr->succ->prev = prev;
//end add
}
else
{
ptr->isfree = 1;
prev = ptr; // used for the step below
}
if((succ = ptr->succ) != 0 && succ->isfree)
{
// the next chunk is free, merge with it
prev->size += sizeof(struct MemEntry) + succ->size;
prev->isfree = 1;
//begin add
prev->succ = succ->succ;
if(succ->succ != 0)
succ->succ->prev=prev;
//end add
}
i = 0;
//delete freed memory address in mem_val
while(1){
if(mem_val[i] == (char*)p){
mem_val[i] = 0;
break;
}
i++;
}
}
|
C
|
#include <stdio.h>
//vetores
//struct
//ponteiros
void troca(int valores[]);
int main(){
int a = 2;
int b = 3;
int numeros[2];
numeros[0] = 24;
numeros[1] = 3;
troca(numeros);
printf("%d %d", numeros[0], numeros[1]);
return 0;
}
void troca(int valores[]){
int aux = valores[0];
valores[0] = valores[1];
valores[1] = aux;
}
|
C
|
#include<stdio.h>
int main()
{
int a,b,c;
scanf ("%d",&a);
scanf ("%d",&b);
c=a+b;
printf ("sum=%d",c);
return 0;
}
|
C
|
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
int main(int argc, char** argv) {
int child, status;
child = fork();
if (child == 0) {
srand(time(NULL));
if (rand() < RAND_MAX/4) {
/* kill self with a signal */
kill(getpid(), SIGTERM);
}
return rand();
}
else {
wait(&status);
if (WIFEXITED(status)) {
printf("Child exited with status %d\n", WEXITSTATUS(status));
}
else if (WIFSIGNALED(status)) {
printf("Child exited with signal %d\n", WTERMSIG(status));
}
}
return 0;
}
|
C
|
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/wait.h>
#include <math.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/fcntl.h>
#include <sys/wait.h>
#include "ppmtools.h"
#define READ_BUFFER_LEN 16
char* readType(FILE *fp)
{
char buf[READ_BUFFER_LEN];
char *t;
//get line of the file into read buffer -> type of ppm
t = fgets(buf, READ_BUFFER_LEN, fp);
//check if it reads something and if it is a P6 type
if (t == NULL)
{
printf("could not read type from file\n");
return "";
}
if(strncmp(buf, "P6\n", 3) != 0 )
{
printf("type is not P6\n");
return "";
}
else
{
printf("set type as P6\n");
//set type as P6
return "P6";
}
}
unsigned int readNextHeaderValue(FILE *fp)
{
char buf[READ_BUFFER_LEN];
char *t;
int r;
int value;
printf("read next header value\n");
//load next line
t = fgets(buf, READ_BUFFER_LEN, fp);
if(t == NULL)
{
printf("Error reading from file");
return 0;
}
//read value as unsigned int
r = sscanf(buf, "%u", &value);
//check if the read was successful
if ( r != 1 )
{
printf("Could not read width value\n");
return 0;
}
else
{
return value;
}
}
header* getImageHeader(FILE *fp)
{
//alloc header
header* h = malloc(sizeof(header));
//check if file pointer is null
if (fp == NULL)
{
//file pointer is null
return NULL;
}
//get type
char* type = readType(fp);
if(strcmp(type, "") != 0)
{
//write type
strcpy(h->type,type);
}
else
{
//error reading type
return NULL;
}
h->width = readNextHeaderValue(fp);
h->height = readNextHeaderValue(fp);
h->depth = readNextHeaderValue(fp);
//check for successful read and valid color range
if(h->depth != 255 || h->width == 0 || h->height == 0)
{
//printf("error reading values\n");
return NULL;
}
return h;
}
//NOTE:
// The program fails if the first byte of the image is equal to 32 (ascii for space char). because
// the fscanf in eats the space (ascii 32) and the image is read with one byte less
int getImageRow(int pixelNo, pixel *row, FILE *fp)
{
int i;
byte b;
//reading line
for (i = 0; i < pixelNo; i++)
{
//set pixel values
if(fread(&row[i],sizeof(b),3*sizeof(b),fp) < 1)
return -1;
}
return 0;
}
void invertRow(int pixelNo, pixel row[])
{
pixel aux;
int i;
//for each pixel
for(i=0; i <pixelNo/2; i++)
{
//exchange pixel [i] with the pixel at the end minus [i]
aux = row[i];
row[i] = row[pixelNo-i-1];
row[pixelNo-i-1] = aux;
}
}
int writeImageHeader(header* h, FILE* fp)
{
//write header fields with newline between them
if(fprintf(fp,"%s\n%u\n%u\n%u\n",h->type,h->width,h->height,h->depth) < 1)
{
return -1;
}
return 0;
}
int writeRow(int pixelNo, pixel* row, FILE* fp)
{
int i, r;
//for each pixel
for(i = 0; i < pixelNo; i++)
{
//write one byte per RGB channel in pixel
r = fwrite(&row[i],sizeof(byte),3*sizeof(byte),fp);
//check for errors
if(r <1)
{
return -1;
}
}
return 0;
}
|
C
|
/* FILE
* long_out_profile.c
*
* For profiles of the longitudinal output variable.
*
* Copyright (c) 2002 Regents of the University of California
*
*/
#include "long_out_profile.h"
/* reads a profile item from a character string */
void read_profile_item (char *linebuffer, profile_item *pitem)
{
sscanf(linebuffer, "%f %d %f %f %d %f %d %f",
&pitem->time,
&pitem->engine_command_mode,
&pitem->engine_speed,
&pitem->engine_torque,
&pitem->engine_retarder_command_mode,
&pitem->engine_retarder_torque,
&pitem->brake_command_mode,
&pitem->ebs_deceleration);
}
/* writes a profile item to a character string */
void write_profile_item (char *linebuffer, profile_item *pitem)
{
sprintf(linebuffer, "%.3f %d %.3f %.3f %d %.3f %d %.3f\n",
pitem->time,
pitem->engine_command_mode,
pitem->engine_speed,
pitem->engine_torque,
pitem->engine_retarder_command_mode,
pitem->engine_retarder_torque,
pitem->brake_command_mode,
pitem->ebs_deceleration);
}
/* out of range error values used to signal error to higher level routines */
static profile_item error_item = {
-255.0, /* time */
-255.0, /* engine speed */
-255.0, /* engine torque */
255.0, /* retarder torque */
255, /* engine command mode */
255, /* retarder command mode */
255.0, /* deceleration */
255, /* brake command mode */
};
/* updates a profile item from the data base; if data base read fails,
* leave an error code to the data item */
void update_profile_item(db_clt_typ *pclt, profile_item *pitem,
struct timeb *start_time)
{
struct timeb current_time;
db_data_typ db_data;
/* by initializing to error values, read of other variables
* can continue even if read to one of the variables fails
*/
*pitem = error_item;
ftime (¤t_time);
pitem->time = TIMEB_SUBTRACT(start_time, ¤t_time) / 1000.0;
if (clt_read(pclt, DB_LONG_OUTPUT_VAR, DB_LONG_OUTPUT_TYPE, &db_data)){
long_output_typ *p;
p = (long_output_typ *) db_data.value.user;
pitem->engine_speed = p->engine_speed;
pitem->engine_torque = p->engine_torque;
pitem->engine_command_mode = p->engine_command_mode;
pitem->engine_retarder_command_mode =
p->engine_retarder_command_mode;
pitem->brake_command_mode = p->brake_command_mode;
pitem->ebs_deceleration = p->ebs_deceleration;
}
}
static dbv_size_type dbv_used[] = {
DB_LONG_OUTPUT_VAR, sizeof(long_output_typ),
};
static int profile_num_dbvs = sizeof(dbv_used)/sizeof(int);
|
C
|
#include <stdio.h>
#define M 3
#define N 5
double row_avg(const double a[], int n) {
double total = 0;
int i;
for (i = 0; i < n; i++)
total += a[i];
return total / n;
}
double avg(const double a[][N], int m) {
double total = 0;
int i;
for (i = 0; i < m; i++)
total += row_avg(a[i], N);
return total / (m * N);
}
double peak(const double a[][N], int m) {
double peak = a[0][0];
int i, j;
for (i = 0; i < m; i++) {
for (j = 0; j < N; j++) {
if (peak < a[i][j])
peak = a[i][j];
}
}
return peak;
}
void print_array(const double array[], int n) {
int i;
for (i = 0; i < n; i++)
printf("%6.2lf ", array[i]);
printf("\n");
}
void fill_array(double array[], int n) {
int i;
double number;
for (i = 0; i < n; i++) {
while (scanf("%lf", &array[i]) != 1) {
continue;
}
}
}
int main(void) {
double array[M][N];
int i;
printf("Fill the 2D array with numbers:\n");
for (i = 0; i < M; i++) {
printf("Row %d:\n", i + 1);
fill_array(array[i], N);
}
printf("\nThis is the array you have entered:\n");
for (i = 0; i < M; i++)
print_array(array[i], N);
printf("\nAverages of each row are:\n");
for (i = 0; i < M; i++) {
printf("Row %d: %.2lf\n", i, row_avg(array[i], N));
}
printf("\nOverall average is: %.2lf\n", avg(array, M));
printf("\nPeak number is: %.2lf\n", peak(array, M));
return 0;
}
|
C
|
#include "../includes/minishell.h"
static char *get_outfile(char **arg, char *text)
{
int i;
int j;
char *check;
char *file;
char *temp;
i = 0;
j = 0;
temp = *arg;
while (*temp && (*temp == '>' || *temp == ' ' || *temp == '\t')
&& !check_inside(text, temp))
{
j++;
temp++;
}
while (!ft_strchr(">< \t", temp[i]) || (ft_strchr(">< \t", temp[i])
&& check_inside(text, temp + i)))
i++;
check = ft_substr(temp, 0, i);
if (*check == '\0' || !check)
return (print_erro(ERR_TOKEN_NEWL, check));
file = get_arg(check);
free(check);
*arg += i + j;
return (file);
}
static int open_file(char *file, int flag)
{
int fd;
fd = 1;
if (flag == 1)
fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
else if (flag == 2)
fd = open(file, O_WRONLY | O_CREAT | O_APPEND, 0644);
if (fd == -1)
print_erro_int(strerror(errno));
return (fd);
}
static int get_fd(t_cmd *cmd, char *output, int flag)
{
char *file;
char *temp;
temp = output;
while (*temp)
{
if (*temp == '>' && !check_inside(output, temp))
{
file = get_outfile(&temp, output);
if (!file)
return (0);
if (cmd->fd_out != 1)
{
close (cmd->fd_out);
cmd->fd_out = 1;
}
cmd->fd_out = open_file(file, flag);
free(file);
continue ;
}
temp++;
}
return (1);
}
int get_fdout(t_cmd *cmd, int flag, char *output)
{
if (flag > 2)
{
print_error_syntax(flag, '>');
return (0);
}
return (get_fd(cmd, output, flag));
}
|
C
|
#include "light.h"
void clear_all_order_lights(){
HardwareOrder order_types[3] = {
HARDWARE_ORDER_UP,
HARDWARE_ORDER_INSIDE,
HARDWARE_ORDER_DOWN
};
for(int f = 0; f < HARDWARE_NUMBER_OF_FLOORS; f++){
for(int i = 0; i < 3; i++){
HardwareOrder type = order_types[i];
hardware_command_order_light(f, type, 0);
}
}
}
void emergency_stop_active(){
while(hardware_read_stop_signal()){
hardware_command_movement(HARDWARE_MOVEMENT_STOP);
hardware_command_stop_light(1);
}
hardware_command_stop_light(0);
}
int door_active(void){
while (check_timer()){
hardware_command_door_open(1);
poll_buttons();
while (hardware_read_obstruction_signal() || hardware_read_stop_signal()){
set_timer();
poll_buttons();
hardware_command_door_open(1);
if (hardware_read_stop_signal()){
hardware_command_stop_light(1);
empty_all_orders();
clear_all_order_lights();
}
hardware_command_stop_light(0);
}
}
hardware_command_door_open(0);
poll_buttons();
return 1;
}
void poll_buttons(void){
for (int i=0; i<HARDWARE_NUMBER_OF_FLOORS;i++){
if (hardware_read_order(i, HARDWARE_ORDER_DOWN)){
hardware_command_order_light(i,HARDWARE_ORDER_DOWN,1);
add_order(i,HARDWARE_ORDER_DOWN);
}
if (hardware_read_order(i, HARDWARE_ORDER_UP)){
hardware_command_order_light(i,HARDWARE_ORDER_UP,1);
add_order(i,HARDWARE_ORDER_UP);
}
if(hardware_read_order(i,HARDWARE_ORDER_INSIDE)){
hardware_command_order_light(i,HARDWARE_ORDER_INSIDE,1);
add_order(i,HARDWARE_ORDER_INSIDE);
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef int RecType;
void merge(RecType * R,int low,int m,int high)
{
int i=low,j=m+1,p=0;
RecType *R1;
R1=(RecType*)malloc((high-low+1)*sizeof(RecType));
if(!R1)
{
return;
}
while(i<=m&&j<=high)
{
R1[p++]=(R[i]<R[j])?R[i++]:R[j++];
}
while(i<=m)
{
R1[p++]=R[i++];
}
while(j<=high)
{
R1[p++]=R[j++];
}
for(p=0,i=low;i<=high;p++,i++)
{
R[i]=R1[p];
}
}
void mergesort(RecType R[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(R,low,mid);
mergesort(R,mid+1,high);
merge(R,low,mid,high);
}
}
int main(int argc, char const *argv[])
{
int a[]={49,38,65,97,76,13,27};
//int a[8] = {50, 10, 20, 30, 70, 40, 80, 60};
int low=0,high=6;
int i;
for(i=low;i<=high;i++)
{
printf("%d\t",a[i]);
}
printf("\n");
mergesort(a,low,high);
for(i=low;i<=high;i++)
{
printf("%d\t",a[i]);
}
printf("\n");
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
char i,ch,j;
printf("enter the character:-\n");
scanf("%c",&ch);
if(ch>='a' && ch<='z')
{
ch=ch-32;
}
if(ch>='A' && ch<='Z')
{
ch=ch+32;
}
else
printf("Wrong input\n");
printf("\nAfter ch=%c\n",ch);
}
|
C
|
#include "Task.h"
int TaskThree(void)
{
int first_number = 0;
int second_number = 0;
int temp = 0;
int a = 1;
printf("Write two number, to find lowest common divisor");
if (2 != scanf("%i %i", &first_number, &second_number))
{
printf("Input Error");
return -1;
}
if ((first_number < 0 && second_number > 0) || (second_number < 0 && first_number > 0))
{
a = -1;
}
first_number = fabs(first_number);
second_number = fabs(second_number);
while (0 != first_number && 0 != second_number)
{
while (first_number >= second_number)
{
first_number -= second_number;
}
if (0 == first_number)
{
break;
}
temp = first_number;
first_number = second_number;
second_number = temp;
}
printf("NOD: %i \n\n", a*second_number);
return 0;
}
|
C
|
#include "holberton.h"
/**
* _isalpha - function that return 1 if c is a letter and 0 otherwise
*
* @r: parametre from 4-main.c
* Return: 0 or 1
*/
int _isalpha(int r)
{
if ((r >= 65 && r <= 90) || (r >= 97 && r <= 122))
return (1);
else
return (0);
}
|
C
|
/*
Praxis der Programmierung
Projekt 1
Abgabedatum: 2.6.2019
Gruppennummer : <64>
Gruppenmitglieder :
- <Johnny Hänsel> - MatrikelNr: 796033
- <Florian Frankreiter> - MatrikelNr: 796762
- <Maximilian Metzner> - MatrikelNr: 793692
*/
#include <stdlib.h>
#include <stdio.h>
struct le {
int value; // Initialisiert value (Wert von einem Listenelement)
struct le * next; // Definiert Adresszuweisung auf nächstes Element
};
typedef struct le listenelement; // Ersetzt le durch bezeichnung Listenelement
typedef listenelement * list; // setzt pointer
//funktion zum Einfügen eines Elements in die Liste an erste stellle
void insert(int v, list * l){
listenelement * new;
new = malloc(sizeof(listenelement));
new -> value = v;
new -> next = *l;
*l = new;
}
//funktion zum Ausgeben der Liste
void print_list(list l){
if (l==NULL){
printf("Ende");
}
while (l!=NULL){
printf("%d\n", l-> value);
l = l->next;
}
}
// funktion zum zählen der Listenelemente
int length(list l){
int count = 0;
while (l!=NULL){
count = count + 1;
l = l->next;
}
return count;
}
//funktion zum löschen des ersten (head) Elements
int delete_head(list*l){
while (l != NULL) {
if (*l == NULL){
return -1;
}
list old = *l;
*l = old->next;
free(old);
}
return 0;
}
//funktion zum löschen aller elemente
void delete_all(list l){
list next;
while (l!=NULL){
next = l->next;
free(l);
l=next;
}
}
// Löscht element an position "pos"
int delete_pos(list * l, int pos){
if (pos < 0 || pos > length(*l) || *l == NULL){ //falls Parameter pos außerhalb der Liste: Rückgabewert -1
return -1;
}
if (pos == 0){ //falls Parameter pos auf 0
*l = (*l)->next;
return 0;
}
if(pos == 1){ //falls Parameter pos auf 1
if( (*l)->next == NULL){
free(l);
return 0;
}
(*l)->next = (*l)->next->next;
return 0;
}
list lakt = *l; //Liste zwischenspeichern
return delete_pos(&lakt -> next, pos -1); //rekursiver Aufruf
}
// löscht erstes Element X aus Liste
int delete_element(list * l, int e){
if ((*l) -> value == e){
(*l) = (*l)->next;
return 0;
}
list lakt = *l; //Liste zwischenspeichern
return delete_element(&lakt->next, e ); //rekursiver Aufruf
}
// sortiert die Liste je nach Parameter m aufsteigend oder aufsteigend mit den Werten in Betragsdarstellung
void sort(list * l, int m) {
if (m > 0) { //Parameter m ist positiv (aufsteigend sortieren) (eigentlicher Sortier-Algorithmus)
int intCache = 0; //Cache um aktuelles Element zwischenzuspeichern und zu vergleichen
list poiNew = *l; //Pointer auf aktuelles Element
list poiLastVal = NULL; //Pointer auf letztes Element
while (poiNew != NULL) { //Elemente so lange vergleichen bis Zeiger auf NULL steht
poiLastVal = poiNew;
poiNew = poiNew->next;
if (poiNew == NULL) { //Wenn alle Elemente verglichen, dann Speicher freigeben und Funktion verlassen
free(poiNew);
return;
}
else if (poiNew->value > poiLastVal->value) { //falls aktueller Wert > leztzter Wert steht aktueller Wert an der richtigen Stelle, schleife von vorne
continue;
}
else if (poiNew->value < poiLastVal->value) { //falls aktueller Wert < letzter Wert müssen beide vertauscht werden
intCache = poiNew->value; //Tausch: Cache = A, A = B, B = Cache
poiNew->value = poiLastVal->value;
poiLastVal->value = intCache;
sort(l, m); //liste erneut von vorne durchgehen
}
}
}
else if (m < 0) { //Parameter m ist negativ (Liste in Betragsform umwandeln)
list listSort = *l;
while (listSort != NULL) { //Elemente in listSort so lange vergleichen bis der Zeiger auf NULL zeigt
if (listSort->value > 0) { //wenn Wert value positiv, Zeiger weiter setzen
listSort = listSort->next;
continue;
}
else if (listSort->value < 0) { //wenn Wert value negativ, absoluten Wert nehmen und Zeiger weiter setzen
listSort->value = abs(listSort->value);
listSort = listSort->next;
}
}
return sort(l, 1); //Funktion erneut mit positivem Parameter in Betragsform erneut aufrufen
}
else { //Fall Parameter = 0 (währe nicht definiert)
printf("\nUngueltiger Parameter in sort()!");
}
}
//Überprüft ob die Liste leer ist (eine leere Liste kann nicht sortiert werden!
void checkList(list * l) {
if (*l == NULL) {
printf("Liste ist leer und kann nicht behandelt werden!");
exit(EXIT_FAILURE);
}
}
int main() {
struct le *Liste;
int value;
Liste=NULL;
insert(-7, &Liste); //Elemente zur Liste hinzufügen
insert(-3, &Liste);
insert(1, &Liste);
insert(4, &Liste);
insert(6, &Liste);
insert(2, &Liste);
insert(5, &Liste);
insert(7, &Liste);
insert(9, &Liste);
checkList(Liste); //Überprüft ob die Liste Elemente enthält
printf("\nListe roh: \n");
print_list(Liste); //Liste mit Elementen ausgeben
printf("\nListe aufsteigend sortiert (Parameter 1): \n");
sort(&Liste, 1); //Liste aufsteigend sortieren
print_list(Liste); //Liste ausgeben
printf("\nListe in Betragsform (Parameter -1): \n");
sort(&Liste, -1); //Liste in Betragsform aufsteigend sortieren
print_list(Liste); //Liste ausgeben
printf("\nListe ohne 0tes Element: \n");
delete_pos(&Liste, 0); //Kopf der Liste (pos 0) löschen
print_list(Liste); //Liste ausgeben
printf("\nListe ohne Element mit wert 4: \n");
delete_element(&Liste, 4); //Element mit Wert 4 löschen
print_list(Liste); //Liste ausgeben
printf("\nListe geloescht: \n");
delete_all(Liste); //gesamte Liste löschen
print_list(Liste); //Liste ausgeben
return 0;
}
|
C
|
#include "debug-string.h"
typedef struct PccDebugString
{
int len;
char s[PccDebugStringLength];
} PccDebugString;
RTE_DEFINE_PER_LCORE(PccDebugString, gPccDebugString);
void
PccDebugString_Clear()
{
RTE_PER_LCORE(gPccDebugString).len = 0;
RTE_PER_LCORE(gPccDebugString).s[0] = '\0';
}
const char*
PccDebugString_Appendf(const char* fmt, ...)
{
char* begin = RTE_PER_LCORE(gPccDebugString).s;
int* len = &RTE_PER_LCORE(gPccDebugString).len;
char* output = RTE_PTR_ADD(begin, *len);
int room = PccDebugStringLength - *len;
va_list args;
va_start(args, fmt);
int res = vsnprintf(output, room, fmt, args);
va_end(args);
if (res < 0) {
*output = '\0';
} else if (res >= room) {
*len += room - 1;
} else {
*len += res;
}
return begin;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** my_libc
** File description:
** my_strf
*/
#include "my_libc.h"
#include "my_strf.h"
static const op_t ptr_tab[] = {
{"d", &my_strf_int},
{"i", &my_strf_int},
{"u", &my_strf_uint},
{"c", &my_strf_char},
{"s", &my_strf_str},
{"f", &my_strf_float},
{"e", &my_strf_float_sci},
{"x", &my_strf_hexa},
{"X", &my_strf_uhexa},
{"o", &my_strf_octal},
{"b", &my_strf_binary},
{"p", &my_strf_pointer},
{NULL, NULL}
};
static const op_arg_t ptr_arg_tab[] = {
{"d", &my_strf_fp_int},
{"i", &my_strf_fp_int},
{"u", &my_strf_fp_uint},
{"f", &my_strf_fp_float},
{"e", &my_strf_fp_float_sci},
{NULL, NULL}
};
static size_t call_with_parameters(char const *opt, char **str, va_list args)
{
size_t pos = 2;
char *tmp;
size_t nb;
size_t len;
for (; opt[pos] >= '0' && opt[pos] <= '9'; ++pos);
tmp = my_strndup(opt + 2, pos - 2);
nb = my_atou(tmp);
free(tmp);
for (byte_t i = 0; ptr_arg_tab[i].str; ++i) {
len = my_strlen(ptr_arg_tab[i].str);
if (my_strncmp(opt + pos, ptr_arg_tab[i].str, len)) {
ptr_arg_tab[i].ptr(args, str, nb);
return (pos + len);
}
}
*str = my_strnadd(*str, opt, pos);
return (pos);
}
static size_t call_function(char const *opt, char **str, va_list args)
{
size_t len;
if (opt[1] == '.')
return (call_with_parameters(opt, str, args));
for (byte_t i = 0; ptr_tab[i].str; ++i) {
len = my_strlen(ptr_tab[i].str);
if (my_strncmp(opt + 1, ptr_tab[i].str, len)) {
ptr_tab[i].ptr(args, str);
return (len + 1);
}
}
*str = my_stradd(*str, "%");
if (my_strncmp(opt + 1, "%", 1))
return (2);
return (1);
}
char *my_strf(char const *opt, ...)
{
char *str = NULL;
va_list args;
if (!opt)
return (NULL);
va_start(args, opt);
for (size_t i = 0; opt[i];) {
if (opt[i] == '%') {
str = my_strnadd(str, opt, i);
opt += call_function(opt + i, &str, args) + i;
i = 0;
} else
++i;
}
str = my_stradd(str, opt);
va_end(args);
return (str);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "funciones.h"
/** \brief Funcion que permite hacer la operacion de suma
*
* \param numeroUno float Primer operando
* \param numeroDos float Segundo operando
* \return float resultado
*
*/
float sumar(float numeroUno, float numeroDos)
{
float resultado;
resultado = numeroUno + numeroDos;
return resultado;
}
/** \brief Funcion que permite hacer la operacion de la resta
*
* \param numeroUno float Minuendo
* \param numeroDos float Sustraendo
* \return float resultado
*
*/
float restar(float numeroUno, float numeroDos)
{
float resultado;
resultado = numeroUno - numeroDos;
return resultado;
}
/** \brief Funcion que permite hacer la operacion de la multiplicacion,
* incluye la correccion al multiplicar un numero negativo por cero
* \param numeroUno float Primer factor
* \param numeroDos float Segundo factor
* \return float resultado
*
*/
float multiplicar(float numeroUno, float numeroDos)
{
float resultado;
resultado = numeroUno * numeroDos;
return resultado;
}
/** \brief Funcion que permite hacer la operacion de la division,
* incluye la condicion de error al dividir por cero
* \param numeroUno float Dividendo
* \param numeroDos float Divisor
* \return return division
*
*/
float dividir(float numeroUno, float numeroDos)
{
if( numeroDos == 0)
{
printf("ERROR: NO SE PUEDE DIVIDIR POR CERO\n");
return 0;
}
else
{
return (numeroUno / numeroDos);
}
}
/** \brief Funcion que permite obtener el factorial del primer operando, segundo operando, incluye error por numero negativo
* y resultado 1 del factorial del 0. Si el operando tiene decimales, opera unicamente la parte entera.
* \param numeroUno int Numero a ser factorizado
* \param numeroDos int Numero a ser factorizado
* \return int Factorial
*
*/
int factorial(int a)
{
int i, aux;
aux = 1;
for( i = 1; i <= a; i++)
{
aux *= i;
}
return aux;
}
|
C
|
#include "Types.h"
#include "Page.h"
#include "ModeSwitch.h"
void kPrintString( int iX, int iY, const char* pcString );
BOOL kInitializeKernel64Area();
BOOL kIsMemoryEnough();
void kCopyKernel64ImageTo2Mbyte();
// Main
// c코드의 엔트리 포인트 함수
// 0x10200 어드레스에 위치
// 보호모드 엔트리 포인트(EntryPoint.s)에서 최초로 실행되는 C코드
// Main()함수를 가장 앞쪽으로 위치 시켜, 컴파일 시에 코드 섹션의 가장 앞쪽에 위치하게 한 것
void Main(void)
{
DWORD i;
DWORD dwEAX, dwEBX, dwECX, dwEDX;
char vcVendorString[13] = {0, };
// 메시지 표시
kPrintString(0, 3, "Protected Mode C Language Kernel Start.....................[Pass]");
// 최소 메모리 크기를 만족하는 지 검사
kPrintString(0, 4, "Minimum Memory Size Check...................[ ]");
if(kIsMemoryEnough() == FALSE){
kPrintString(45, 4, "Fail");
kPrintString(0, 5, "Not Enough Memory!! KihOS Requires Over 64Mbyte Meemory!");
while(1);
}else{
kPrintString( 45, 4, "Pass");
}
// IA-32e 모드의 커널 영역을 초기화
kPrintString(0, 5, "IA-32e Kernel Area Initialize...............[ ]");
if(kInitializeKernel64Area() == FALSE){
kPrintString(45, 5, "Fail");
kPrintString(0, 6, "IA-32e Kernel Area Initialization Fail!");
while(1);
}
kPrintString( 45, 5, "Pass");
// IA-32e모드 커널을 위한 페이지 테이블 생성
kPrintString(0, 6, "IA-32e Page tables Initialize...............[ ]");
kInitializePageTables();
kPrintString(45, 6, "Pass");
// 프로세서 제조사 정보 읽기
kReadCPUID( 0x00, &dwEAX, &dwEBX, &dwECX, &dwEDX );
*(DWORD*)vcVendorString = dwEBX;
*( (DWORD*)vcVendorString + 1) = dwEDX;
*( (DWORD*)vcVendorString + 2) = dwECX;
kPrintString( 0, 7, "Processor Vendor String.....................[ ]");
kPrintString( 45, 7, vcVendorString);
//64비트 지원 유무 확인
kReadCPUID( 0x80000001, &dwEAX, &dwEBX, &dwECX, &dwEDX );
kPrintString( 0, 8, "64bit Mode Support Check....................[ ]");
if(dwEDX & (1<<29)){
kPrintString(45, 8, "Pass");
}else{
kPrintString(45, 8, "Fail");
kPrintString(0, 9, "This processor does not support 64bit mode!");
while(1);
}
//IA-32e모드 커널을 0x200000(2Mbyte) 어드레스로 이동
kPrintString(0, 9, "Copy IA-32e Kernel To 2M Address............[ ]");
kCopyKernel64ImageTo2Mbyte();
kPrintString(45, 9, "Pass");
//IA-32e모드로 전환
kPrintString(0, 10, "Switch To IA-32e Mode");
kSwitchAndExecute64bitKernel(); // 이부분 넣으면 자꾸 리셋됨 빼면 또 잘됨 왜?
// 무한 루프
while(1);
}
// 문자열 출력함수
// x,y에 문자열을 출력해주는 함수
// 텍스트모드용 비디오 메모리 어드레스(0xB8000)에 문자를 갱신 시킨다.
void kPrintString( int iX, int iY, const char* pcString )
{
CHARACTER* pstScreen = (CHARACTER*)0xB8000;
int i;
pstScreen += (iY * 80) + iX;
for(i = 0; pcString[i] != 0; i++){
pstScreen[i].bCharactor = pcString[i];
}
}
// IA-32e 모드용 커널 영역을 0으로 초기화
BOOL kInitializeKernel64Area()
{
DWORD* pdwCurrentAddress;
// 초기화를 시작할 어드레스인 0x100000(1MB)을 설정
pdwCurrentAddress = (DWORD*)0x100000;
// 마지막 어드레스인 0x600000(6MB)까지 루프를 돌면서 4바이트씩 0으로 채움
while( (DWORD)pdwCurrentAddress < 0x600000 ){
*pdwCurrentAddress = 0x00;
// 0으로 저장한 후 다시 읽었을 대 0이 나오지 않으면 해당 어드레스를
// 사용하는데 문제가 생긴 것이므로 더이상 진행하지 않고 종료
if(*pdwCurrentAddress != (DWORD)0x0){
return FALSE;
}
// 다음 어드레스로 이동
pdwCurrentAddress++;
}
return TRUE;
}
BOOL kIsMemoryEnough()
{
DWORD* pdwCurrentAddress;
// 0x100000(1MB)부터 검사 시작
pdwCurrentAddress = (DWORD*)0x100000;
// 0x400000(4MB)까지 루프를 돌면서 확인
while( (DWORD)pdwCurrentAddress < 0x400000 ){
*pdwCurrentAddress = 0x12345678;
// 0x12345678로 지정한 후 다시 읽었을 때 0x12345678이 나오지 않으면
// 해당 어드레스를 사용하는데 문제가 생기 것으로 판단.
// 진행하지 않고 종료
if(*pdwCurrentAddress != 0x12345678){
return FALSE;
}
// 1MB씩 이동하면서 확인
pdwCurrentAddress += (0x100000 / 4);
}
return TRUE;
}
// IA-32e 모드 커널을 0x200000(2Mbyte) 어드레스에 복사
void kCopyKernel64ImageTo2Mbyte()
{
WORD wKernel32SectorCount, wTotalKernelSectorCount;
DWORD* pdwSourceAddress, * pdwDestinationAddress;
int i;
// 0x7C05에 총 커널 섹터 수, 0x7C07에 보호모드 커널 섹터 수가 들어 있음
wTotalKernelSectorCount = *( (WORD*)0x7C05 );
wKernel32SectorCount = *( (WORD*)0x7C07 );
pdwSourceAddress = (DWORD*)(0x10000 + (wKernel32SectorCount * 512));
pdwDestinationAddress = (DWORD*)0x200000;
//IA-32e 모드 커널 섹터 크기만큼 복사
for(i=0; i<512 * (wTotalKernelSectorCount - wKernel32SectorCount) / sizeof(DWORD); i++){
*pdwDestinationAddress = *pdwSourceAddress;
pdwDestinationAddress++;
pdwSourceAddress++;
}
}
|
C
|
/**
* Gerencia e chama as funções relacionadas ao casamento de palavras através da
* força bruta, imprimindo e lendo os dados necessários
*
* Gustavo Viegas (3026) e Heitor Passeado (3055)
* @author Heitor Passeado
*/
#include "bruteForceInterface.h"
// Tela inicial da busca de padrão com força bruta
void _bruteForceInitial(int analysisMode) {
char text[FILE_MAX_SIZE] = "";
system("clear");
cprintf(GREEN,"[MODO FORÇA BRUTA]");
parseFileInString(text);
_bruteForceMenu(analysisMode, text);
}
// Exibe o menu para fazer busca com força bruta
void _bruteForceMenu(int analysisMode, char *text) {
int choice;
system("clear");
printLine();
printf("\n\n");
cprintf(GREEN, "1 - Buscar palavra\n");
cprintf(GREEN, "2 - Carregar outro arquivo\n");
cprintf(GREEN, "3 - Voltar ao menu\n");
prePrompt();
scanf("%d", &choice);
switch (choice) {
case 1:
bruteForceSearch(text, analysisMode);
break;
case 2:
return _bruteForceInitial(analysisMode);
break;
case 3:
return printHeader(analysisMode);
break;
default:
cprintf(RED, "Opção inválida!\n");
pressEnterToContinue();
break;
}
return _bruteForceMenu (analysisMode, text);
}
|
C
|
//gcc test2.c -lcurl -o test
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <curl/curl.h>
#define SIZE 200
//Buffer
struct string {
char *ptr;
size_t len;
};
//Initialize Buffer
void init_string(struct string *s) {
s->len = 0;
s->ptr = malloc(s->len+1);
if (s->ptr == NULL) {
fprintf(stderr, "malloc() failed\n");
exit(EXIT_FAILURE);
}
s->ptr[0] = '\0';
}
//Callback Function
size_t writefunc(void *ptr, size_t size, size_t nmemb, struct string *s)
{
size_t new_len = s->len + size*nmemb;
s->ptr = realloc(s->ptr, new_len+1);
if (s->ptr == NULL) {
fprintf(stderr, "realloc() failed\n");
exit(EXIT_FAILURE);
}
memcpy(s->ptr+s->len, ptr, size*nmemb);
s->ptr[new_len] = '\0';
s->len = new_len;
return size*nmemb;
}
int user_access(char *user, char *station, char *state)
{
CURL *curl;
CURLcode res;
char header[30] = "User-ID-String: ";
char header2[30] = "Station-ID: ";
char header3[30] = "Station-State: ";
strcat(header, user);
strcat(header2, station);
strcat(header3, state);
struct curl_slist *headers = NULL;
static const char *postthis = "/api/user-access";
static const char *pCertFile = "/u/guen/test/LUCCA/test/cert/combined.pem";
curl = curl_easy_init();
if(curl) {
//Append headers to list
headers = curl_slist_append(headers, header);
headers = curl_slist_append(headers, header2);
headers = curl_slist_append(headers, header3);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
//curl_easy_setopt(curl, CURLOPT_URL, "https://ruby.cecs.pdx.edu:3001");
curl_easy_setopt(curl, CURLOPT_URL, "http://ptsv2.com/t/xj3ym-1525325338/post");
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postthis);
//Set String Length
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(postthis));
//Cert stored PEM coded in file
curl_easy_setopt(curl, CURLOPT_SSLCERTTYPE, "PEM");
//Set cert for client authentication
curl_easy_setopt(curl, CURLOPT_SSLCERT, pCertFile);
//Res gets return code
res = curl_easy_perform(curl);
//Check for errors
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
long response_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
printf("\n===================\nResponse Code: %ld\n===================", response_code);
/* Clean up */
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
if(response_code == 200)
return 1;
else
return 0;
}
}
//Prints out the time
void heartbeat(char *station)
{
CURL *curl;
CURLcode res;
char *header = "Station-State: Enabled";
char header2[16] = "Station-ID: ";
strcat(header2, station);
struct curl_slist *headers = NULL;
static const char *postthis = "/api/station-heartbeat";
static const char *pCertFile = "/u/guen/test/LUCCA/test/cert/combined.pem";
curl = curl_easy_init();
if(curl) {
struct string s;
init_string(&s);
headers = curl_slist_append(headers, header);
headers = curl_slist_append(headers, header2);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
//curl_easy_setopt(curl, CURLOPT_URL, "https://ruby.cecs.pdx.edu:3001");
curl_easy_setopt(curl, CURLOPT_URL, "http://ptsv2.com/t/xj3ym-1525325338/post");
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postthis);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, writefunc);
curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &s);
//Set String Length
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(postthis));
//Cert stored PEM coded in file
curl_easy_setopt(curl, CURLOPT_SSLCERTTYPE, "PEM");
//Set cert for client authentication
curl_easy_setopt(curl, CURLOPT_SSLCERT, pCertFile);
//Res gets return code
res = curl_easy_perform(curl);
//Check for errors
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
//Take out date from headers
char * token;
token = strtok(s.ptr, "D");
token = strtok(NULL, "S");
printf("\nD%s\n", token);
// Clean up
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
}
}
int main(void)
{
int response;
char *user = "131027";
char *station = "printer";
char *state = "Enabled";
heartbeat(station);
response = user_access(user, station, state);
printf("\n Response: %d\n\n", response);
return 0;
}
|
C
|
/* Based on f477.c, from https://sourceforge.net/projects/egm96-f477-c/
which is, in turn, based on F477.F, from
http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm96/egm96.html
Preprocess the constant files CORCOEF and EGM96 to be included in
compilation.
*/
#include<stdio.h>
#include<math.h>
#include <float.h>
#define l_value (65341)
#define _361 (361)
static double cc[l_value + 1], cs[l_value + 1],
hc[l_value + 1], hs[l_value + 1];
static int nmax;
static void ddump(const char *name, double* v, size_t bytesize)
{
size_t size = bytesize / sizeof(double);
char fname[50];
snprintf(fname, 50, "build/%s.inc", name);
FILE *fd = fopen(fname, "w");
for(size_t j = 0; j < size; ++j) {
fprintf(fd, "%.*g,\n", DBL_DECIMAL_DIG, v[j]);
}
fclose(fd);
}
static void dhcsin(unsigned nmax, double hc[l_value + 1], double hs[l_value + 1])
{
FILE* f_12 = fopen("data/EGM96", "rb"); /*potential coefficient file */
int n, m;
double j2, j4, j6, j8, j10, c, s, ec, es;
/*the even degree zonal coefficients given below were computed for the
wgs84(g873) system of constants and are identical to those values
used in the NIMA gridding procedure. computed using subroutine
grs written by N.K. PAVLIS*/
j2 = 0.108262982131e-2;
j4 = -.237091120053e-05;
j6 = 0.608346498882e-8;
j8 = -0.142681087920e-10;
j10 = 0.121439275882e-13;
m = ((nmax + 1) * (nmax + 2)) / 2;
for (n = 1; n <= m; n++)
hc[n] = hs[n] = 0;
while (6 ==
fscanf(f_12, "%i %i %lf %lf %lf %lf", &n, &m, &c, &s, &ec,
&es)) {
if (n > nmax) {
continue;
}
n = (n * (n + 1)) / 2 + m + 1;
hc[n] = c;
hs[n] = s;
}
fclose(f_12);
hc[4] += j2 / sqrt(5);
hc[11] += j4 / 3;
hc[22] += j6 / sqrt(13);
hc[37] += j8 / sqrt(17);
hc[56] += j10 / sqrt(21);
}
void init_arrays(void)
{
int ig, i, n, m;
double t1, t2;
/*correction coefficient file:
modified with 'sed -e"s/D/e/g"' to be read with fscanf */
FILE *f_1 = fopen("data/CORCOEF", "rb");
nmax = 360;
for (i = 1; i <= l_value; i++)
cc[i] = cs[i] = 0;
while (4 == fscanf(f_1, "%i %i %lg %lg", &n, &m, &t1, &t2)) {
ig = (n * (n + 1)) / 2 + m + 1;
cc[ig] = t1;
cs[ig] = t2;
}
/*the correction coefficients are now read in*/
/*the potential coefficients are now read in and the reference
even degree zonal harmonic coefficients removed to degree 6*/
dhcsin(nmax, hc, hs);
fclose(f_1);
ddump("cc", cc, sizeof(cc));
ddump("cs", cs, sizeof(cs));
ddump("hc", hc, sizeof(hc));
ddump("hs", hs, sizeof(hs));
}
int main(void)
{
init_arrays();
}
|
C
|
#include "lists.h"
/**
* add_nodeint_end - Add new node at end of list
* @head: Pointer to pointer to head
* @n: Value for n in node
*
* Return: Address to new node
*/
listint_t *add_nodeint_end(listint_t **head, const int n)
{
listint_t *new, *last;
new = malloc(sizeof(listint_t));
if (new == NULL)
{
return (NULL);
}
new->n = n;
new->next = NULL;
last = *head;
if (*head == NULL)
{
*head = new;
return (*head);
}
while (last->next != NULL)
{
last = last->next;
}
last->next = new;
last = last->next;
return (last);
}
|
C
|
/*
Program 1
Using circular representation for a polynomial, design, develop, and execute a program in C to accept two polynomials, add them, and then print the resulting polynomial.
*/
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<math.h>
struct node{
int coef,exp;
struct node *link;
};
typedef struct node *NODE;
NODE attach (int coef,int exp,NODE head){
NODE temp,temp2;
temp=malloc(sizeof(temp));
temp->coef=coef;
temp->exp=exp;
temp2=head->link;
while(temp2->link!=head)
temp2=temp2->link;
temp2->link=temp;
temp->link=head;
return head;
}
NODE readpoly(NODE head){
int i,n,coef,exp;
printf("\n Enter the number of terms in polynomial:");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("\nCoefficient:");
scanf("%d",&coef);
printf("Exponent:");
scanf("%d",&exp);
head=attach(coef,exp,head);
}
return head;
}
NODE polyadd(NODE headA,NODE headB,NODE headC){
NODE a,b;
int coef,z;
a=headA->link;
b=headB->link;
while(a!=headA&& b!=headB){
if((a->exp) > (b->exp))
z=1;
else if((a->exp)==(b->exp))
z=0;
else
z=3;
switch(z){
case 0:
coef=a->coef+b->coef;
if(coef!=0)
headC=attach(coef,a->exp,headC);
a=a->link;
b=b->link;
break;
case 1:
headC=attach(a->coef,a->exp,headC);
a=a->link;
break;
case 3:
headC=attach(b->coef,b->exp,headC);
b=b->link;
break;
}
}
while(a!=headA){
headC=attach(a->coef,a->exp,headC);
a=a->link;
}
while(b!=headB){
headC=attach(b->coef,b->exp,headC);
b=b->link;
}
return headC;
}
void display(NODE head){
NODE temp2;
temp2=head->link;
while(temp2->link!=head->link){
printf("%d X^%d ",temp2->coef,temp2->exp);
temp2=temp2->link;
}
printf("\n");
}
int main(){
NODE headA,headB,headC;
headA=malloc(sizeof(headA));
headB=malloc(sizeof(headB));
headC=malloc(sizeof(headC));
headA->link=headA;
headB->link=headB;
headC->link=headC;
printf("Enter the first polynomial \n");
headA=readpoly(headA);
printf("\nEnter the second polynomial \n");
headB=readpoly(headB);
headC=polyadd(headA,headB,headC);
printf("Polynomial 1:");
display(headA);
printf("Polynomial 2:");
display(headB);
printf("Polynomial 3:");
display(headC);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#define NUM_THREADS 2
#define GULP_SIZE 156252
#include "mkl.h"
/* DGESVD prototype
extern void sgesvd_( char* jobu, char* jobvt, int* m, int* n, float* a,
int* lda, float* s, float* u, int* ldu, float* vt, int* ldvt,
float* work, int* lwork, int* info );
*/
typedef struct svdzap_data
{
int tid;
int n_files;
char ** file_names;
unsigned gulp_size;
int * flags;
int result;
int verbose;
} svdzap_data_t;
svdzap_data_t * init_pol_data(unsigned num_files, unsigned gulp_size, unsigned tid, int verbose);
long create_xcorr(float** datagulp, long gulpsize, FILE **currentFile,int numbeams,float ** xcorr_matrix);
//void close_files(FILE **currentFile, int numbeams, int numpol);
int choose_pivot(int low_index,int high_index);
void swap(float *x,float *y);
void quicksort(float* list,int low_index,int high_index);
float mean(float* gulp, long gulpsize);
float median(float* gulp, long gulpsize);
float mad(float* gulp,int mode,long gulpsize);
void * svdzap_thread (void *);
double diff_time ( struct timeval time1, struct timeval time2 );
void usage()
{
fprintf (stdout,
"dgesvd_aux_p [options] [m+n files]\n"
" -h print help text\n"
" -m <num> number of pol0 files to expect\n"
" -n <num> number of pol1 files to expect\n"
" -o <file> write output file mask\n"
" -v verbose output\n"
"\n"
" If the output file exists [-o] the RFI mask will be\n"
" appened, otherwise a new file will be created. If no\n"
" output file is specified, `pwd`/rfi.mask till be used\n");
}
/* Main program */
int main(int argc, char *argv[])
{
/* append flag for output file,
* -1 no output file
* 0 create
* 1 == append */
int append = -1;
int num_pol0 = 0;
int num_pol1 = 0;
int verbose = 0;
unsigned length = 1024;
char output_file[length];
int arg = 0;
sprintf(output_file, "rfi.mask");
while ((arg=getopt(argc,argv,"hm:n:o:v")) != -1)
{
switch (arg)
{
case 'h':
usage();
exit(EXIT_SUCCESS);
break;
case 'm':
if (optarg)
num_pol0 = atoi(optarg);
else
{
fprintf (stderr, "-m requires num arg\n");
usage();
return (EXIT_FAILURE);
}
break;
case 'n':
if (optarg)
num_pol1 = atoi(optarg);
else
{
fprintf (stderr, "-n requires num arg\n");
usage();
return (EXIT_FAILURE);
}
break;
case 'o':
if (optarg)
{
sprintf(output_file, "%s", optarg);
append = 0;
}
else
{
fprintf (stderr, "-o requires file arg\n");
usage();
return (EXIT_FAILURE);
}
break;
case 'v':
verbose++;
break;
default:
usage ();
return (EXIT_FAILURE);
}
}
int num_files = argc - optind;
if (num_files != num_pol1 + num_pol0)
{
fprintf (stderr, "ERROR: found %d files, expected %d\n", num_files, (num_pol1 + num_pol0));
return (EXIT_FAILURE);
}
// check if the specified file exists
int mask = R_OK;
if (access(output_file, mask) < 0)
append = 0;
else
append = 1;
// check the specified file is writable
mask = W_OK;
if (append == 1 && access(output_file, mask) < 0)
{
fprintf (stderr, "ERROR: could not write to output file [%s] %s\n", output_file, strerror(errno));
return EXIT_FAILURE;
}
if (verbose)
fprintf (stderr, "output_file = %s\n", output_file);
unsigned i = 0;
svdzap_data_t * p0 = 0;
svdzap_data_t * p1 = 0;
pthread_t pol0_thread_id = 0;
pthread_t pol1_thread_id = 0;
if (num_pol0)
{
p0 = init_pol_data(num_pol0, GULP_SIZE, 0, verbose);
for (i=0; i<num_pol0; i++)
p0->file_names[i] = strdup(argv[optind+i]);
}
if (num_pol1)
{
p1 = init_pol_data(num_pol1, GULP_SIZE, 1, verbose);
for (i=0; i<num_pol1; i++)
p1->file_names[i] = strdup(argv[optind+num_pol0+i]);
}
// create pthread[s]
int rval = 0;
if (num_pol0)
{
if (verbose)
fprintf (stderr, "main: launching pol0 thread with data=%x\n", p0);
rval = pthread_create (&pol0_thread_id, 0, (void *) svdzap_thread, (void *) p0);
if (rval != 0) {
fprintf (stderr, "Error creating pol0_thread: %s\n", strerror(rval));
return EXIT_FAILURE;
}
}
if (num_pol1)
{
if (verbose)
fprintf (stderr, "main: launching pol1 thread\n");
rval = pthread_create (&pol1_thread_id, 0, (void *) svdzap_thread, (void *) p1);
if (rval != 0) {
fprintf (stderr, "Error creating pol1_thread: %s\n", strerror(rval));
return EXIT_FAILURE;
}
}
if (verbose)
fprintf (stderr, "main: waiting for threads to finish\n");
// join thread[s]
if (num_pol0)
{
void* result = 0;
pthread_join (pol0_thread_id, &result);
}
if (num_pol1)
{
void* result = 0;
pthread_join (pol1_thread_id, &result);
}
if (verbose)
fprintf (stderr, "main: writing output to : %s\n", output_file);
FILE * fptr = fopen(output_file, "a");
if (fptr == NULL)
{
fprintf(stderr, "could not open output file: %s\n", output_file);
return EXIT_FAILURE;
}
if (append == 0)
fprintf(fptr, "#0 1\n");
int value = 0;
for (i=0; i<GULP_SIZE; i++)
{
value = 1;
if (num_pol0 && p0->result == 0 && p0->flags[i] == 0)
value = 0;
if (num_pol1 && p1->result == 0 && p1->flags[i] == 0)
value = 0;
fprintf(fptr, "%d\n", value );
}
fclose(fptr);
if (num_pol0)
{
free(p0->flags);
free(p0->file_names);
free(p0);
}
if (num_pol1)
{
free(p1->flags);
free(p1->file_names);
free(p1);
}
return EXIT_SUCCESS;
}
svdzap_data_t * init_pol_data(unsigned num_files, unsigned gulp_size, unsigned tid, int verbose)
{
if (verbose)
fprintf (stderr, "init_pol_data(%d, %d, %d, %d)\n", num_files, gulp_size, tid, verbose);
svdzap_data_t * data = (svdzap_data_t *) malloc(sizeof(svdzap_data_t));
assert(data != 0);
data->tid = tid;
data->n_files = num_files;
data->gulp_size = gulp_size;
data->verbose = verbose;
data->result = -1;
data->file_names = (char **) malloc(sizeof(char *) * num_files);
assert(data->file_names != 0);
data->flags = (int *) malloc(sizeof(int) * gulp_size);
assert(data->flags != 0);
return data;
}
/*
* process 1 polns worth of mon files
*/
void * svdzap_thread (void * arg)
{
svdzap_data_t * svdzap = (svdzap_data_t *) arg;
assert(svdzap != 0);
struct timeval start;
struct timeval split;
struct timeval curr;
gettimeofday (&start, 0);
gettimeofday (&split, 0);
gettimeofday (&curr, 0);
double split_time = 0;
double total_time = 0;
if (svdzap->verbose)
fprintf (stderr, "svdzap_thread[%d]: preparing\n", svdzap->tid);
FILE ** fptrs = (FILE **) malloc(sizeof(FILE *) * svdzap->n_files);
assert (fptrs);
int i = 0;
// check that all the files can be read
int mask = R_OK;
int readable_wait = 10;
int all_readable = 0;
while (!all_readable && readable_wait > 0)
{
all_readable = 1;
for (i=0; i<svdzap->n_files; i++)
{
if (access(svdzap->file_names[i], mask) < 0)
{
fprintf(stderr, "svdzap_thread[%d]: %s not readable, waiting...\n", svdzap->tid, svdzap->file_names[i]);
all_readable = 0;
}
else
{
if (svdzap->verbose)
fprintf(stderr, "svdzap_thread[%d]: %s was readable\n", svdzap->tid, svdzap->file_names[i]);
}
}
if (!all_readable)
{
sleep(1);
readable_wait--;
}
}
for (i=0; i<svdzap->n_files; i++)
{
fptrs[i] = fopen(svdzap->file_names[i], "rb");
assert(fptrs[i]);
}
long gulpsize = svdzap->gulp_size;
int numbeams = svdzap->n_files;
long gulpread;
int j,ia,ib,aindex;
int m = numbeams,n = numbeams;
int lda = numbeams,ldu = numbeams,ldvt = numbeams;
int info;
int lwork;
int final;
float workOpt,madOne,madZero,flags_sone;
float* work;
float* tmpDat;
float* sOne;
float* sTwo;
float* sFour;
float* sThirteen;
float * s = (float *) malloc(sizeof(float) * numbeams);
float * a = (float *) malloc(sizeof(float) * numbeams*numbeams);
float * u = (float *) malloc(sizeof(float) * numbeams*numbeams);
float * vt = (float *) malloc(sizeof(float) * numbeams*numbeams);
float** datagulp;
float** xcorr_matrix;
datagulp = (float **) malloc( numbeams * sizeof(float *) );
assert (datagulp != NULL);
for (i=0 ; i < numbeams ; i++ ) {
datagulp[i] = (float *) malloc( gulpsize * sizeof(float) );
assert(datagulp[i] != NULL);
}
xcorr_matrix = (float **) malloc (numbeams*numbeams * sizeof(float *));
assert (xcorr_matrix != NULL);
for (i=0; i< numbeams*numbeams; i++) {
xcorr_matrix[i] = (float *) malloc (gulpsize * sizeof(float) );
assert(xcorr_matrix[i] != NULL);
}
sOne = (float *) malloc (gulpsize * sizeof(float) );
assert(sOne != NULL);
sTwo = (float *) malloc (gulpsize * sizeof(float) );
assert(sTwo != NULL);
sFour = (float *) malloc (gulpsize * sizeof(float) );
assert(sFour != NULL);
sThirteen = (float *) malloc (gulpsize * sizeof(float) );
assert(sThirteen != NULL);
final = 0;
for (i=0;i<numbeams*numbeams;i++) {
a[i] = 0;
}
lwork=-1;
// get best parameters
sgesvd_("N","N",&m,&n,a,&lda,s,u,&ldu,vt,&ldvt,&workOpt,&lwork,&info);
lwork =(int)workOpt;
work = (float*)malloc(lwork*sizeof(float));
// timing
if (svdzap->verbose)
{
split.tv_sec = curr.tv_sec;
split.tv_usec = curr.tv_usec;
gettimeofday (&curr, 0);
split_time = diff_time (split, curr);
total_time = diff_time (start, curr);
fprintf (stderr, "svdzap_thread[%d]: sgesvd_ [%f of %f]\n", svdzap->tid, split_time, total_time);
}
gulpread = create_xcorr(datagulp,gulpsize,fptrs,numbeams,xcorr_matrix);
if (svdzap->verbose)
{
split.tv_sec = curr.tv_sec;
split.tv_usec = curr.tv_usec;
gettimeofday (&curr, 0);
split_time = diff_time (split, curr);
total_time = diff_time (start, curr);
fprintf (stderr, "svdzap_thread[%d]: svd [%f of %f]\n", svdzap->tid, split_time, total_time);
}
if (gulpread < gulpsize) {
final = 1;
}
for (j=0;j<gulpread;j++) {
for (i=0;i<numbeams*numbeams;i++) {
a[i] = 0;
}
for (ia=0;ia<numbeams;ia++) {
for (ib=ia;ib<numbeams;ib++) {
a[ia*numbeams+ib] = xcorr_matrix[ia*numbeams+ib][j];
}
}
sgesvd_("N","N",&m,&n,a,&lda,s,u,&ldu,vt,&ldvt,work,&lwork,&info);
// check successful
if( info > 0 ) {
fprintf(stderr, "svdzap_thread[%d]: sgesvd_ failed\n", svdzap->tid);
svdzap->result = -1;
pthread_exit((void *) &(svdzap->result));
}
sOne[j] = s[0];
sTwo[j] = s[1];
sFour[j] = s[3];
sThirteen[j] = s[12];
}
if (svdzap->verbose)
{
split.tv_sec = curr.tv_sec;
split.tv_usec = curr.tv_usec;
gettimeofday (&curr, 0);
split_time = diff_time (split, curr);
total_time = diff_time (start, curr);
fprintf (stderr, "svdzap_thread[%d]: mad [%f, %f]\n", svdzap->tid, split_time, total_time);
}
madOne = mad(sThirteen,1,gulpread);
madZero = mad(sThirteen,0,gulpread);
madOne = madOne*100;
madZero = madZero*100;
flags_sone = mean(sOne,gulpread);
// normally we would double this, but the data is so noisy
// too much RFI is left behind in the 1-bit version.
flags_sone = flags_sone*2;
for(i=0;i<gulpread;i++) {
if (sThirteen[i] > madZero) {
svdzap->flags[i] = 0;
}
else if (sThirteen[i] > madOne) {
if (sTwo[i] > flags_sone) {
svdzap->flags[i] = 0;
}
else {
svdzap->flags[i] = 1;
}
}
else if (sFour[i] > flags_sone) {
// there are 4 eigenvalues greater than the first is supposed to be
// even though it was not detected in the lower eigenvalues
// this is probably RFI
svdzap->flags[i] = 0;
}
else {
svdzap->flags[i] = 1;
}
//fprintf(kfile_w,"%d\n",flags[i]);
}
free(s);
free(a);
free(u);
free(vt);
free(work);
for (i=0; i<svdzap->n_files; i++)
fclose(fptrs[i]);
free(fptrs);
free(datagulp);
if (svdzap->verbose)
{
split.tv_sec = curr.tv_sec;
split.tv_usec = curr.tv_usec;
gettimeofday (&curr, 0);
split_time = diff_time (split, curr);
total_time = diff_time (start, curr);
fprintf (stderr, "svdzap_thread[%d]: finished [%f of %f]\n", svdzap->tid, split_time, total_time);
}
svdzap->result = 0;
pthread_exit((void *) &(svdzap->result));
}
long create_xcorr(float** datagulp, long gulpsize, FILE **currentFile,int numbeams, float** xcorr_matrix) {
int i,j;
int ia,ib;
int some_inf;
long num_read;
float mean_dataia;
float mean_dataib;
float* datagulp_tmpia;
float* datagulp_tmpib;
float tmpia;
float tmpib;
datagulp_tmpia = (float *) malloc( gulpsize * sizeof(float) );
assert(datagulp_tmpia != NULL);
datagulp_tmpib = (float *) malloc( gulpsize * sizeof(float) );
assert(datagulp_tmpib != NULL);
//printf("initializing xcorr\n");
for (i=0;i<numbeams*numbeams;i++) {
for (j=0;j<gulpsize;j++) {
xcorr_matrix[i][j] = 0;
}
}
for (i=0;i<gulpsize;i++) {
datagulp_tmpia[i] = 0;
datagulp_tmpib[i] = 0;
}
//printf("reading data\n");
for (i=0;i<numbeams;i++) {
num_read = fread(datagulp[i],sizeof(float),gulpsize,currentFile[i]);
some_inf = 0;
for (j=0; j<gulpsize; j++)
{
if (isinf(datagulp[i][j]))
some_inf = 1;
}
if (some_inf)
bzero(datagulp[i], sizeof(float) * gulpsize);
}
//printf("correlating\n");
for (ia=0;ia<numbeams;ia++) {
for (ib=ia;ib<numbeams;ib++) {
for (i=0;i<num_read;i++) {
datagulp_tmpia[i] = (float) datagulp[ia][i];
datagulp_tmpib[i] = (float) datagulp[ib][i];
}
mean_dataia = mean(datagulp_tmpia,num_read);
mean_dataib = mean(datagulp_tmpib,num_read);
j = ia*numbeams + ib;
for (i=0;i<num_read;i++) {
tmpia = datagulp_tmpia[i] - mean_dataia;
tmpib = datagulp_tmpib[i] - mean_dataib;
xcorr_matrix[j][i] = tmpia*tmpib;
}
}
}
free(datagulp_tmpia);
free(datagulp_tmpib);
return num_read;
}
void close_files(FILE ** currentFile,int numbeams, int numpol) {
int i;
for (i=0;i<numbeams*numpol;i++) {
fclose(currentFile[i]);
}
}
float mean(float* gulp, long gulpsize) {
int i;
float total = 0;
for (i=0;i<gulpsize;i++) {
total += gulp[i];
}
return total/gulpsize;
}
float mad(float* gulp,int mode,long gulpsize) {
float* y;
float* z;
float tmp;
int i;
y = (float *) malloc (gulpsize * sizeof(float) );
z = (float *) malloc (gulpsize * sizeof(float) );
if (mode == 0) {
tmp = mean(gulp,gulpsize);
for (i=0;i<gulpsize;i++) {
y[i] = fabs(gulp[i] - tmp);
}
tmp = mean(y,gulpsize);
free(y);
free(z);
return tmp;
}
for (i=0;i<gulpsize;i++) {
z[i] = gulp[i];
}
tmp = median(z,gulpsize);
for (i=0;i<gulpsize;i++) {
y[i] = fabs(gulp[i] - tmp);
}
tmp = median(y,gulpsize);
free(y);
free(z);
return tmp;
}
float median(float* gulp, long gulpsize) {
quicksort(gulp,0,gulpsize-1);
if (gulpsize % 2 == 0) {
return (gulp[gulpsize/2] + gulp[gulpsize/2-1])/2;
}
return gulp[gulpsize/2];
}
int choose_pivot(int low_index,int high_index ) {
return((low_index+high_index) /2);
}
void swap(float *x,float *y)
{
float temp;
temp = *x;
*x = *y;
*y = temp;
}
void quicksort(float* list,int low_index,int high_index)
{
int i,j,k;
float key;
if( low_index < high_index)
{
k = choose_pivot(low_index,high_index);
swap(&list[low_index],&list[k]);
key = list[low_index];
i = low_index+1;
j = high_index;
while(i <= j)
{
while((i <= high_index) && (list[i] <= key)) {
i++;
}
while((j >= low_index) && (list[j] > key)) {
j--;
}
if( i < j) {
swap(&list[i],&list[j]);
}
}
swap(&list[low_index],&list[j]);
// recursively sort the lesser list
quicksort(list,low_index,j-1);
quicksort(list,j+1,high_index);
}
}
double diff_time ( struct timeval time1, struct timeval time2 )
{
return ( (double)( time2.tv_sec - time1.tv_sec ) +
( (double)( time2.tv_usec - time1.tv_usec ) / 1000000.0 ) );
}
|
C
|
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int i;
int fd;
char *buff;
fd = open(argv[1], O_RDONLY);
buff = (char *)malloc(sizeof(char) * 25);
read(fd, buff, 25);
i = 0;
while (i < 25)
{
printf("%c", buff[i] - i);
i++;
}
printf("\n");
}
|
C
|
#include "curlhttps.h"
/* 读取文本文件的数据,发送给服务端的https服务器 */
int mycurl(char *url, char *filename, char param[][10])
{
CURL *curl;
CURLcode res;
char str[4094] = { };
char newurl[5120] = { };
FILE *p_file;
int size;
/* 读取文本文件中到数据 */
p_file = fopen(filename, "r");
if (p_file)
{
memset(str, 0, sizeof(str));
size = fread(str, sizeof(char), sizeof(str), p_file);
if (0 == size)
{
printf("no data....\n");
}
}
size = strlen(str);
str[size - 1] = '\0';
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl)
{
/* 生成发送的url */
//sprintf(newurl, "%s{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":\"%s\"}", url, *(param+0), str, *(param+1), "tangtest1", *(param+2), "tangtest2");
sprintf(newurl, "%s{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":\"%s\"}", url, param[0], str, param[1], "tangtest1", param[2], "tangtest2");
/* 发送数据 */
curl_easy_setopt(curl, CURLOPT_URL, newurl);
/* 跳过证书验证 */
//curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
return 0;
}
/* always cleanup */
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
/* 读取文本文件的数据,发送给服务端的https服务器 */
int mycurlstr(char *url, char msg[][1024], char param[][10])
{
CURL *curl;
CURLcode res;
char str[4094] = {};
char newurl[5120] = {};
//int size;
/* 读取文本文件中到数据 */
//str[size - 1] = '\0';
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl)
{
/* 生成发送的url */
//sprintf(newurl, "%s{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":\"%s\"}", url, *(param+0), str, *(param+1), "tangtest1", *(param+2), "tangtest2");
sprintf(newurl, "%s{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":\"%s\"}", url, param[0], msg[0], param[1], msg[1], param[2], msg[2]);
/* 发送数据 */
curl_easy_setopt (curl, CURLOPT_URL, newurl);
/* 跳过证书验证 */
//curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
#if 1
//curl_easy_setopt (curl, CURLOPT_CAPATH, ".");
curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, 1L);
curl_easy_setopt (curl, CURLOPT_CAINFO, "ca-cert.pem");
//curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 1);
//curl_easy_setopt (curl, CURLOPT_SSH_PUBLIC_KEYFILE, "public.key");
curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt (curl, CURLOPT_TIMEOUT, 30);
#endif
#if 0
/* 双向认证 */
//curl_easy_setopt (curl, CURLOPT_CAPATH, ".");
curl_easy_setopt (curl, CURLOPT_SSLCERT, "client-cert.pem");
//curl_easy_setopt (curl, CURLOPT_SSH_PRIVATE_KEYFILE, "private.key");
curl_easy_setopt (curl, CURLOPT_SSLCERTPASSWD, "123456");
curl_easy_setopt (curl, CURLOPT_SSLCERTTYPE, "PEM");
curl_easy_setopt (curl, CURLOPT_SSLKEY, "client-key.pem");
curl_easy_setopt (curl, CURLOPT_SSLKEYPASSWD, "123456");
curl_easy_setopt (curl, CURLOPT_SSLKEYTYPE, "PEM");
#endif
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
return 0;
}
/* always cleanup */
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
#if 1
int main(void)
{
int res = 0;
char paramstr[][10] = {"param1", "param2", "param3"};
char msg[][1024] = {"flag", "stat", "policymsg"};
char *url = "https://10.63.99.185:8443/cnpc_dlp_v_1.0/monitorSet.action?action=receiveData&json=";
mycurlstr(url, msg, paramstr);
#if 0
char paramstr[][10] = {"data"};
char *url = "https://10.63.99.176:8443/cnpc_dlp_v_1.0/monitorSet.action?action=receiveData&json=";
res = mycurl(url, "abc.c", paramstr);
#endif
#if 0
char *url = "http://10.63.99.185:8080/cnpc_dlp_v_1.0/monitorSet.action?action=receiveData&json=";
res = mycurl(url, "abc.c", paramstr);
#endif
return 0;
}
#endif
|
C
|
#define N 4
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int n;
int i = 0;
float tempoMedio = 0;
int vet[N]; //Vettore contenente tempi di esecuzione
float accumulatore; //Vettore contenente tempi di attesa perogni processo.
int scelta;//Variabile per il costrutto switch
// Riempo il vettore con i tempi di esecuzione
printf("Inserisci %d processi\n",N);
while(i < N){
printf("Inserisci il tempo di esecuzione del %d° processo: ",i + 1);
scanf("%d",&vet[i]);
i++;
}
//Calcolo il tempo di attesa di ogni processo e lo sposto in un altro vettore.
printf("Quale algoritmo di scheduling vuoi utilizzare ? \n1) FCFS diretto\n2) FCFS inverso\n");
scanf("%d",&scelta);
switch(scelta){
case 1:
i = 1;
while(i < N){
tempoMedio = tempoMedio + vet[i-1];
accumulatore = accumulatore + tempoMedio;
i++;
}
break;
case 2:
i = N - 2;
while(i + 1){
tempoMedio = tempoMedio + vet[i+1];
accumulatore = accumulatore + tempoMedio;
i--;
}
break;
default: printf("%d: scelta non valida.",scelta);
}
tempoMedio = accumulatore / N;
printf("Il tempo medio di attesa e' : %f",tempoMedio);
return (EXIT_SUCCESS);
}
|
C
|
/* Author: Ruiqi(Rachel) Tao
Purpose of the document: Unix HW1 Game Of Life
Default input filename: life.txt
Compiled with std=c99
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <errno.h>
extern int errno;
void generate(int rows, int columns, int **arr){
//create a new 2D array
int **next_gen = (int**)malloc(sizeof(int*)*rows);
for(int i=0; i<rows; i++)
*(next_gen+i) = (int*)malloc(sizeof(int)*columns);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
next_gen[i][j] = '-';
}
}
//Calculate number of neighbours for each cell for the current generation
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
int neighbours = 0;
if(i > 0 && arr[i - 1][j] == '*') neighbours++; //check if there's a neighbours to the North
if(i < rows - 1 && arr[i + 1][j] == '*') neighbours++; //South
if(j > 0 && arr[i][j - 1] == '*') neighbours++; //West
if(j < columns - 1 && arr[i][j + 1] == '*') neighbours++; //East
if((i > 0 & j > 0) && arr[i - 1][j - 1] == '*') neighbours++; //Northwest
if((i > 0 & j < columns - 1) && arr[i - 1][j + 1] == '*') neighbours++; //Southwest
if((i < rows - 1 & j > 0) && arr[i + 1][j - 1] == '*') neighbours++; //Northeast
if((i < rows - 1 & j < columns - 1) && arr[i + 1][j + 1] == '*') neighbours++; //Southeast
if(arr[i][j] == '*' && (neighbours == 2 || neighbours == 3)) next_gen[i][j] = '*';
if(arr[i][j] == '-' && neighbours == 3) next_gen[i][j] = '*';
}
}
//copy the new generation back
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
arr[i][j] = next_gen[i][j];
}
}
free(next_gen);
return;
}
int main(int argc, char *argv[]){
int rows, columns, generations;
rows = columns = generations = 10;
char filename[20];
strcpy(filename, "life.txt");
//set default values for different number of arguments passed into the program
if(argc == 2){
rows = atoi(argv[1]);
}
else if(argc == 3){
rows = atoi(argv[1]);
columns = atoi(argv[2]);
}
else if (argc == 4){
rows = atoi(argv[1]);
columns = atoi(argv[2]);
strcpy(filename, argv[3]);
}
else if (argc == 5){
rows = atoi(argv[1]);
columns = atoi(argv[2]);
strcpy(filename, argv[3]);
generations = atoi(argv[4]);
}
else if (argc > 5) {
printf("Too many arguments...\n");
exit(EXIT_FAILURE);
}
/* Read from input file */
FILE *fp;
char *buff;
fp = fopen(filename, "r");
if (fp == NULL){
int errnum = errno;
fprintf(stderr, "Value of errno: %d\n", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s\n", strerror(errnum));
exit(EXIT_FAILURE);
}
size_t len = 0;
ssize_t read;
//int map[rows][columns];
int count_row = 0;
//create a dynamically sized 2D array
int **map = (int**)malloc(sizeof(int*)*rows);
for(int i=0; i<rows; i++)
*(map+i) = (int*)malloc(sizeof(int)*columns);
//set all cells to dead
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
map[i][j] = '-';
}
}
//change some cells to alive based on input file
while ((read = getline(&buff, &len, fp)) != -1) {
for(int i = 0; i < strlen(buff)-1; i++){
if(buff[i] == '*') {
map[count_row][i] = '*';
}
}
count_row++;
}
fclose(fp);
free(buff);
fp = fopen("output.txt", "w");
int count = 0;
//generate a set a number of epoches
while(count <= generations){
char buffer [12];
sprintf(buffer, "%d", count);
char *target = malloc(100);
char *s1 = "Generation ";
char *s2 = buffer;
char *s3 = ":\n";
strcat(target, s1);
strcat(target, s2);
strcat(target, s3);
fputs(target, fp);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
fputc(map[i][j], fp);
}
fputs("\n", fp);
}
fputs("================================\n", fp);
generate(rows, columns, map);
count++;
}
fclose(fp);
free(map);
return 0;
}
|
C
|
/* Copyright 2021 <Bivolaru Andra> */
#include <stdlib.h>
#include <string.h>
#include "server.h"
server_memory* init_server_memory() {
// Allocating memory for the server
server_memory *server = malloc(sizeof(server_memory));
DIE(server == NULL, "Unable to allocate memory for the server!\n");
// Initializing memory for the hashtable
server->ht = ht_create(NUM_BUCKETS,
hash_function_string, compare_function_strings);
return server;
}
void server_store(server_memory* server, char* key, char* value) {
ht_put(server->ht, key, strlen(key) + 1, value, strlen(value) + 1);
}
void server_remove(server_memory* server, char* key) {
ht_remove_entry(server->ht, key);
}
char* server_retrieve(server_memory* server, char* key) {
return ht_get(server->ht, key);
}
void free_server_memory(server_memory* server) {
ht_free(server->ht);
free(server);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rotations.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mpivet-p <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/08/18 05:09:13 by mpivet-p #+# #+# */
/* Updated: 2019/08/22 04:52:46 by mpivet-p ### ########.fr */
/* */
/* ************************************************************************** */
#include <math.h>
#include <string.h>
#include "rtv1.h"
static void rot_x(t_vector *vec, double theta)
{
double save;
save = vec->y;
theta = theta * 3.141592653 / 180.0;
vec->y = vec->y * cos(theta) - vec->z * sin(theta);
vec->z = save * sin(theta) + vec->z * cos(theta);
*vec = normalize(*vec);
}
static void rot_y(t_vector *vec, double theta)
{
double save;
save = vec->x;
theta = theta * 3.141592653 / 180.0;
vec->x = vec->x * cos(theta) + vec->z * sin(theta);
vec->z = vec->z * cos(theta) - save * sin(theta);
*vec = normalize(*vec);
}
static void rot_z(t_vector *vec, double theta)
{
double save;
save = vec->x;
theta = theta * 3.141592653 / 180.0;
vec->x = vec->x * cos(theta) - vec->y * sin(theta);
vec->y = save * sin(theta) + vec->y * cos(theta);
*vec = normalize(*vec);
}
void object_translate(t_vector *pos, int key, int modif)
{
if (pos != NULL)
{
if (key == KEY_UP)
pos->z += 0.1 * modif;
else if (key == KEY_DOWN)
pos->z -= 0.1 * modif;
else if (key == KEY_RIGHT)
pos->x += 0.1 * modif;
else if (key == KEY_LEFT)
pos->x -= 0.1 * modif;
else if (key == KEY_PLUS)
pos->y += 0.1 * modif;
else if (key == KEY_LESS)
pos->y -= 0.1 * modif;
}
}
void object_rotate(t_vector *pos, int key, int modif)
{
if (pos != NULL)
{
if (key == KEY_W)
rot_x(pos, 5 * modif);
else if (key == KEY_S)
rot_x(pos, -5 * modif);
else if (key == KEY_D)
rot_y(pos, 5 * modif);
else if (key == KEY_A)
rot_y(pos, -5 * modif);
else if (key == KEY_Q)
rot_z(pos, 5 * modif);
else if (key == KEY_E)
rot_z(pos, -5 * modif);
}
}
|
C
|
/** @file
* @brief Header file for master player
*/
#ifndef PLAYER_H
#define PLAYER_H
#include "buffer.h"
#include "audio.h"
/**
* @defgroup PlayerInterface
*
* @{
*/
/** On stop callback type description */
typedef void(*playerCb_t)(void);
/** Callback structure for various player events */
typedef struct
{
buffer_OnNeedDataCb onDataRead; /** Buffer should be populated with data */
playerCb_t onStop; /** Player stopped */
} playerCbs_t;
/**
* @brief Init functions for player
* This function should be called before any actions with player
* player_Stop will be called if needed
*
* @param[in] cbs structure with event callbacks
*
* @return none
*
* @see playerCbs_t
* @see player_Stop
*/
void player_Init(playerCbs_t *cbs);
/**
* @brief Start play
*
* @param none
*
* @return none
*/
void player_Play(void);
/**
* @brief Pause music
*
* @param none
*
* @return none
*/
void player_Pause(void);
/**
* @brief Stop player and set to uninit state
* Will be called inside init function if required
*
* @param none
*
* @return none
*/
void player_Stop(void);
/**
* @brief Run managment function for player
*
* @param none
*
* @return none
*/
void player_Run(void);
/**
* @brief Get state of the player
*
* @param none
*
* @return true sound output is in progress
*/
bool player_IsPlaying(void);
/** @} */
#endif /* PLAYER_H */
|
C
|
#include<stdio.h>
int main(){
int arr[10];
int i,j;
printf("Enter 10 numbers:\n");
for(i=0;i<10;i++)
scanf("%d",&arr[i]);
for(i=0;i<10;i++){
for(j=i+1;j<10;j++){
if(arr[j]<arr[i]){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
printf("After sorting in ascending order,the array is:\n");
for(i=0;i<10;i++)
printf("%d ",arr[i]);
printf("\n");
return 0;
}
// 23/10/17
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
//Struct Definitions
typedef struct
{
char*firstname;
char*lastname;
} NAME;
typedef struct
{
int*streetno;
char*streetname;
char*streetname1;
char*city;
char*state;
char*country;
int*zip;
} ADDRESS;
typedef struct
{
int*number;
} PHONE;
typedef struct
{
NAME name;
ADDRESS address;
PHONE phone;
}PROFILE;
int countdata();
int displaymenu();
PROFILE*build(PROFILE*ptr,int count);
void populate(PROFILE*ptr,FILE*records,int count);
void searchoptions(PROFILE*ptr, int count);
void searchphone(PROFILE*ptr,int count);
void searchaddress(PROFILE*ptr,int count);
void street(PROFILE*ptr,int count);
void street1(PROFILE*ptr,int count);
void city(PROFILE*ptr,int count);
void state(PROFILE*ptr,int count);
void country(PROFILE*ptr,int count);
void zip(PROFILE*ptr,int count);
void house(PROFILE*ptr,int count);
void searchfullname(PROFILE*ptr,int count);
void deleteRecord(PROFILE*ptr,int *count,int *searchSaved);
void editrecord(PROFILE*ptr,int count);
void printdata(PROFILE*ptr,int count);
int main ()
{
//Opens the file
FILE*records;
records=fopen("People.txt","r");
if(!records)
printf("Error opening the file");
int searchSaved;
int count;int option=0;
//Counts how many records are in the file
count=countdata();
//Allocates the memory to build the database for all the information in the file
PROFILE*pointer=NULL;
pointer=build(pointer,count);
if(pointer==NULL)
{
printf("Memory not correctly allocated");
exit(1);
}
//Builds PROFILE struct. Has all the information in the file
populate(pointer,records,count);
//While loop allows multiple actions to take place in one run.
while(option != 5 || option!=4)
{
//Prompts user what they want to do
option=displaymenu();
if(option==1)
searchoptions(pointer,count);
if(option==2)
{
searchoptions(pointer,count);
deleteRecord(pointer,&count,&searchSaved);
}
if(option==3)
{
editrecord(pointer,count);
}
printf("\n");
//Check against invalid input.
if(option < 1 || option > 5)
printf("I am sorry but %d was not one of the options on the menu.\nPlease pick the correct choice from the menu options!\n", option);
if(option==4)
printdata(pointer,count);
if(option==5)
exit(0);
}
return 0;
}
//Counts how many records in the file
int countdata()
{
FILE*records;
records=fopen("People.txt","r");
if(!records)
printf("Error opening the file");
int scandata;int A=0;int streetnumber;
//Loop runs until program reaches end of file
for( ;scandata!=EOF; )
{
scandata=fscanf(records,"%*s%*s %d %*s %*s %*s %*s %*d",&streetnumber);
if(scandata==1)
A++;
}
//In case the file is empty
if(A == 0)
{
printf("There are no records in the file. Program will terminate.");
exit(0);
}
return A;
}
//Builds the PROFILE struct
PROFILE*build(PROFILE*ptr,int count)
{
ptr=(PROFILE*)calloc(count,sizeof(PROFILE));
if(ptr==NULL)
printf("Memory not allocated.");
return ptr;
}
//Gets all the data into the PROFILE struct
void populate(PROFILE*ptr,FILE*records,int count)
{
int B;
for(B=0;B<count;B++)
{
(*(ptr+B)).name.firstname=(char*)calloc(20,sizeof(char));
(*(ptr+B)).name.lastname=(char*)calloc(20,sizeof(char));
(*(ptr+B)).address.streetno=(int*)calloc(5,sizeof(int));
(*(ptr+B)).address.streetname=(char*)calloc(20,sizeof(char));
(*(ptr+B)).address.streetname1=(char*)calloc(20,sizeof(char));
(*(ptr+B)).address.city=(char*)calloc(20,sizeof(char));
(*(ptr+B)).address.state=(char*)calloc(20,sizeof(char));
(*(ptr+B)).address.country=(char*)calloc(20,sizeof(char));
(*(ptr+B)).address.zip=(int*)calloc(5,sizeof(int));
(*(ptr+B)).phone.number=(int*)calloc(100,sizeof(int));
fscanf(records,"%s %s",(ptr+B)->name.firstname,(ptr+B)->name.lastname);
fscanf(records,"%d %s %s %s %s %s %d",(ptr+B)->address.streetno,(ptr+B)->address.streetname,(ptr+B)->address.streetname1,
(ptr+B)->address.city,(ptr+B)->address.state,(ptr+B)->address.country,(ptr+B)->address.zip);
fscanf(records,"%d",(ptr+B)->phone.number);
}
}
//Displays the options the user has
int displaymenu()
{
int option;
printf(" User Options\n");
printf("-----------------------------------------\n");
printf("1. Search by name, address or phone number\n");
printf("2. Delete a record\n");
printf("3. Edit an existing record\n");
printf("4. Print all profiles\n");
printf("5. Exit\n");
printf("------------------------------------------\n");
printf("Please select one of the above options: ");
scanf("%d",&option);
printf("\n");
return option;
}
//Menu allows user to determine what part of record they want to search by
void searchoptions(PROFILE*ptr, int count)
{
int option;
printf(" Searh Options\n");
printf("------------------------------------\n");
printf("1. Phone Number\n");
printf("2. Word in Address\n");
printf("3. First and Last name\n");
printf("4. Exit and quit program\n");
printf("-------------------------------------\n");
printf("Pick one of the above search options. ");
scanf("%d",&option);
//Searches for record by phone number
if(option==1)
searchphone(ptr,count);
//Searches for record by address
if(option==2)
searchaddress(ptr,count);
//Searches for record by name
if(option==3)
searchfullname(ptr,count);
if(option==4)
exit(0);
}
void searchfullname(PROFILE * ptr, int count)
{
char*string;int matches=0;int*locarray;int B=0;int A = 0;int option;
string=(char*)calloc(20,sizeof(char));
printf("\n Searh Options\n");
printf("------------------------------------\n");
printf("1. First name\n");
printf("2. Last name\n");
printf("-------------------------------------\n");
//If user searches by name, user can determine if they want first or last name
printf("\nWhich part of the name do you want to search: ");
scanf("%d", &option);
printf("\n\nEnter the name string: ");
scanf("%s",string);
//Loop searches for location of matches in the database
for(A=0;A<count;A++)
{
if(option == 1)
if(strcmp(((*(ptr+A)).name.firstname),string) == 0)
matches++;
if(option == 2)
if(strcmp(((*(ptr+A)).name.lastname),string) == 0)
matches++;
}
if(matches==0)
printf("No matches were found\n");
//Creates an array that stores the locations for all the matches
if(matches>0)
{
locarray=(int*)calloc(matches,sizeof(int));
for(A=0;A<count;A++)
{
if(option == 1)
if(strcmp(((*(ptr+A)).name.firstname),string) == 0)
{
*(locarray+B)=A;
B++;
}
if(option == 2)
if(strcmp(((*(ptr+A)).name.lastname),string) == 0)
{
*(locarray+B)=A;
B++;
}
}
printf("The profiles with all matches are now being printed.\n\n");
//Prints all the matches that are found
for(A=0;A<matches;A++)
{
B=*(locarray+A);
printf("Name:%s %s\n",(ptr+B)->name.firstname,(ptr+B)->name.lastname);
printf("Address:%d %s %s\n",*((ptr+B)->address.streetno),(ptr+B)->address.streetname,(ptr+B)->address.streetname1);
if(*((ptr+A)->address.zip)<10000)
printf("City:%s State:%s Country: %s Zip:%05d\n",(ptr+A)->address.city,(ptr+A)->address.state,(ptr+A)->address.country,
*((ptr+A)->address.zip));
else
printf("City:%s State:%s Country: %s Zip:%d\n",(ptr+B)->address.city,(ptr+B)->address.state,(ptr+B)->address.country,
*((ptr+B)->address.zip));
printf("Phone:%d\n\n",*((ptr+B)->phone.number));
}
}
}
//Searches for record using the phone number
void searchphone(PROFILE*ptr,int count)
{
int number;int matches=0;int*locarray=NULL;int B=0;
printf("Enter the phone number you are searching for. ");
scanf("%d",&number);
for(int A=0;A<count;A++)
{
if(*((ptr+A)->phone.number)==number)
matches++;
}
if(matches==0)
printf("No matches were found\n");
if(matches>0)
{
locarray=(int*)calloc(matches,sizeof(int));
for(int A=0;A<count;A++)
{
if(*((ptr+A)->phone.number)==number)
{
*(locarray+B)=A;
B++;
}
}
printf("The profiles with all matches are now being printed.\n\n");
for(int A=0;A<matches;A++)
{
B=*(locarray+A);
printf("Name:%s %s\n",(ptr+B)->name.firstname,(ptr+B)->name.lastname);
printf("Address:%d %s %s\n",*((ptr+B)->address.streetno),(ptr+B)->address.streetname,(ptr+B)->address.streetname1);
if(*((ptr+A)->address.zip)<10000)
printf("City:%s State:%s Country: %s Zip:%05d\n",(ptr+A)->address.city,(ptr+A)->address.state,(ptr+A)->address.country,
*((ptr+A)->address.zip));
else
printf("City:%s State:%s Country: %s Zip:%d\n",(ptr+B)->address.city,(ptr+B)->address.state,(ptr+B)->address.country,
*((ptr+B)->address.zip));
printf("Phone:%d\n\n",*((ptr+B)->phone.number));
}
}
}
//Searches for record using address
void searchaddress(PROFILE*ptr,int count)
{
int opt;
//Narrows down what part of address user wants to search by
printf("What part of the address are you searching by? \n");
printf("1. Name\n");
printf("2. Type\n");
printf("3. City\n");
printf("4. State\n");
printf("5. Country\n");
printf("6. Zip\n");
printf("7. House Number\n");
scanf("%d",&opt);
if(opt==1)
street(ptr,count);
if(opt==2)
street1(ptr,count);
if(opt==3)
city(ptr,count);
if(opt==4)
state(ptr,count);
if(opt==5)
country(ptr,count);
if(opt==6)
zip(ptr,count);
if(opt==7)
house(ptr,count);
}
//Search for record using street name
void street(PROFILE*ptr,int count)
{
char*string;int matches=0;int*locarray;int B=0;
string=(char*)calloc(20,sizeof(char));
printf("Enter the address string.");
scanf("%s",string);
for(int A=0;A<count;A++)
{
if(strcmp(((*(ptr+A)).address.streetname),string) == 0)
matches++;
}
if(matches==0)
printf("No matches were found\n");
if(matches>0)
{
locarray=(int*)calloc(matches,sizeof(int));
for(int A=0;A<count;A++)
{
if(strcmp(((*(ptr+A)).address.streetname),string) == 0)
{
*(locarray+B)=A;
B++;
}
}
printf("The profiles with all matches are now being printed.\n\n");
//Prints all the records that match
for(int A=0;A<matches;A++)
{
B=*(locarray+A);
printf("Name:%s %s\n",(ptr+B)->name.firstname,(ptr+B)->name.lastname);
printf("Address:%d %s %s\n",*((ptr+B)->address.streetno),(ptr+B)->address.streetname,(ptr+B)->address.streetname1);
if(*((ptr+A)->address.zip)<10000)
printf("City:%s State:%s Country: %s Zip:%05d\n",(ptr+A)->address.city,(ptr+A)->address.state,(ptr+A)->address.country,
*((ptr+A)->address.zip));
else
printf("City:%s State:%s Country: %s Zip:%d\n",(ptr+B)->address.city,(ptr+B)->address.state,(ptr+B)->address.country,
*((ptr+B)->address.zip));
printf("Phone:%d\n\n",*((ptr+B)->phone.number));
}
}
}
//Searches for record using street name
void street1(PROFILE*ptr,int count)
{
char*string;int matches=0;int*locarray;int B=0;
string=(char*)calloc(20,sizeof(char));
printf("Enter the address string.");
scanf("%s",string);
for(int A=0;A<count;A++)
{
if(strcmp(((*(ptr+A)).address.streetname1),string) == 0)
matches++;
}
if(matches==0)
printf("No matches were found\n");
if(matches>0)
{
locarray=(int*)calloc(matches,sizeof(int));
for(int A=0;A<count;A++)
{
if(strcmp(((*(ptr+A)).address.streetname1),string) == 0)
{
*(locarray+B)=A;
B++;
}
}
printf("The profiles with all matches are now being printed.\n\n");
for(int A=0;A<matches;A++)
{
B=*(locarray+A);
printf("Name:%s %s\n",(ptr+B)->name.firstname,(ptr+B)->name.lastname);
printf("Address:%d %s %s\n",*((ptr+B)->address.streetno),(ptr+B)->address.streetname,(ptr+B)->address.streetname1);
if(*((ptr+A)->address.zip)<10000)
printf("City:%s State:%s Country: %s Zip:%05d\n",(ptr+A)->address.city,(ptr+A)->address.state,(ptr+A)->address.country,
*((ptr+A)->address.zip));
else
printf("City:%s State:%s Country: %s Zip:%d\n",(ptr+B)->address.city,(ptr+B)->address.state,(ptr+B)->address.country,
*((ptr+B)->address.zip));
printf("Phone:%d\n\n",*((ptr+B)->phone.number));
}
}
}
//Searches for record by city
void city(PROFILE*ptr,int count)
{
char*string;int matches=0;int*locarray;int B=0;
string=(char*)calloc(20,sizeof(char));
printf("Enter the address string.");
scanf("%s",string);
for(int A=0;A<count;A++)
{
if(strcmp(((*(ptr+A)).address.city),string) == 0)
matches++;
}
if(matches==0)
printf("No matches were found\n");
if(matches>0)
{
locarray=(int*)calloc(matches,sizeof(int));
for(int A=0;A<count;A++)
{
if(strcmp(((*(ptr+A)).address.city),string) == 0)
{
*(locarray+B)=A;
B++;
}
}
printf("The profiles with all matches are now being printed.\n\n");
//Prints all the matches that are found
for(int A=0;A<matches;A++)
{
B=*(locarray+A);
printf("Name:%s %s\n",(ptr+B)->name.firstname,(ptr+B)->name.lastname);
printf("Address:%d %s %s\n",*((ptr+B)->address.streetno),(ptr+B)->address.streetname,(ptr+B)->address.streetname1);
if(*((ptr+A)->address.zip)<10000)
printf("City:%s State:%s Country: %s Zip:%05d\n",(ptr+A)->address.city,(ptr+A)->address.state,(ptr+A)->address.country,
*((ptr+A)->address.zip));
else
printf("City:%s State:%s Country: %s Zip:%d\n",(ptr+B)->address.city,(ptr+B)->address.state,(ptr+B)->address.country,
*((ptr+B)->address.zip));
printf("Phone:%d\n\n",*((ptr+B)->phone.number));
}
}
}
//Searches for record by state
void state(PROFILE*ptr,int count)
{
char*string;int matches=0;int*locarray;int B=0;
string=(char*)calloc(20,sizeof(char));
printf("Enter the address string.");
scanf("%s",string);
for(int A=0;A<count;A++)
{
if(strcmp(((*(ptr+A)).address.state),string) == 0)
matches++;
}
if(matches==0)
printf("No matches were found\n");
if(matches>0)
{
locarray=(int*)calloc(matches,sizeof(int));
for(int A=0;A<count;A++)
{
if(strcmp(((*(ptr+A)).address.state),string) == 0)
{
*(locarray+B)=A;
B++;
}
}
printf("The profiles with all matches are now being printed.\n\n");
//Prints records that match state
for(int A=0;A<matches;A++)
{
B=*(locarray+A);
printf("Name:%s %s\n",(ptr+B)->name.firstname,(ptr+B)->name.lastname);
printf("Address:%d %s %s\n",*((ptr+B)->address.streetno),(ptr+B)->address.streetname,(ptr+B)->address.streetname1);
if(*((ptr+A)->address.zip)<10000)
printf("City:%s State:%s Country: %s Zip:%05d\n",(ptr+A)->address.city,(ptr+A)->address.state,(ptr+A)->address.country,
*((ptr+A)->address.zip));
else
printf("City:%s State:%s Country: %s Zip:%d\n",(ptr+B)->address.city,(ptr+B)->address.state,(ptr+B)->address.country,
*((ptr+B)->address.zip));
printf("Phone:%d\n\n",*((ptr+B)->phone.number));
}
}
}
//Search for records by country
void country(PROFILE*ptr,int count)
{
char*string;int matches=0;int*locarray;int B=0;
string=(char*)calloc(20,sizeof(char));
printf("Enter the address string.");
scanf("%s",string);
for(int A=0;A<count;A++)
{
if(strcmp(((*(ptr+A)).address.country),string) == 0)
matches++;
}
if(matches==0)
printf("No matches were found\n");
if(matches>0)
{
locarray=(int*)calloc(matches,sizeof(int));
for(int A=0;A<count;A++)
{
if(strcmp(((*(ptr+A)).address.country),string) == 0)
{
*(locarray+B)=A;
B++;
}
}
printf("The profiles with all matches are now being printed.\n\n");
//Prints all the matches when search by country
for(int A=0;A<matches;A++)
{
B=*(locarray+A);
printf("Name:%s %s\n",(ptr+B)->name.firstname,(ptr+B)->name.lastname);
printf("Address:%d %s %s\n",*((ptr+B)->address.streetno),(ptr+B)->address.streetname,(ptr+B)->address.streetname1);
if(*((ptr+A)->address.zip)<10000)
printf("City:%s State:%s Country: %s Zip:%05d\n",(ptr+A)->address.city,(ptr+A)->address.state,(ptr+A)->address.country,
*((ptr+A)->address.zip));
else
printf("City:%s State:%s Country: %s Zip:%d\n",(ptr+B)->address.city,(ptr+B)->address.state,(ptr+B)->address.country,
*((ptr+B)->address.zip));
printf("Phone:%d\n\n",*((ptr+B)->phone.number));
}
}
}
//Searches by ZIP code
void zip(PROFILE*ptr,int count)
{
int string;int matches=0;int*locarray;int B=0;
printf("Enter the zip code.");
scanf("%d",&string);
for(int A=0;A<count;A++)
{
if(*((ptr+A)->address.zip)==string)
matches++;
}
if(matches==0)
printf("No matches were found\n");
if(matches>0)
{
locarray=(int*)calloc(matches,sizeof(int));
for(int A=0;A<count;A++)
{
if(*((ptr+A)->address.zip)==string)
{
*(locarray+B)=A;
B++;
}
}
printf("The profiles with all matches are now being printed.\n\n");
//Prints all the matches that are found
for(int A=0;A<matches;A++)
{
B=*(locarray+A);
printf("Name:%s %s\n",(ptr+B)->name.firstname,(ptr+B)->name.lastname);
printf("Address:%d %s %s\n",*((ptr+B)->address.streetno),(ptr+B)->address.streetname,(ptr+B)->address.streetname1);
if(*((ptr+A)->address.zip)<10000)
printf("City:%s State:%s Country: %s Zip:%05d\n",(ptr+A)->address.city,(ptr+A)->address.state,(ptr+A)->address.country,
*((ptr+A)->address.zip));
else
printf("City:%s State:%s Country: %s Zip:%d\n",(ptr+B)->address.city,(ptr+B)->address.state,(ptr+B)->address.country,
*((ptr+B)->address.zip));
printf("Phone:%d\n\n",*((ptr+B)->phone.number));
}
}
}
//Searches for record using house number
void house(PROFILE*ptr,int count)
{
int string;int matches=0;int*locarray;int B=0;
printf("Enter the house number.");
scanf("%d",&string);
for(int A=0;A<count;A++)
{
if(*((ptr+A)->address.streetno)==string)
matches++;
}
if(matches==0)
printf("No matches were found\n");
if(matches>0)
{
locarray=(int*)calloc(matches,sizeof(int));
for(int A=0;A<count;A++)
{
if(*((ptr+A)->address.streetno)==string)
{
*(locarray+B)=A;
B++;
}
}
printf("The profiles with all matches are now being printed.\n\n");
//Prints all the records that have the same house number
for(int A=0;A<matches;A++)
{
B=*(locarray+A);
printf("Name:%s %s\n",(ptr+B)->name.firstname,(ptr+B)->name.lastname);
printf("Address:%d %s %s\n",*((ptr+B)->address.streetno),(ptr+B)->address.streetname,(ptr+B)->address.streetname1);
if(*((ptr+A)->address.zip)<10000)
printf("City:%s State:%s Country: %s Zip:%05d\n",(ptr+A)->address.city,(ptr+A)->address.state,(ptr+A)->address.country,
*((ptr+A)->address.zip));
else
printf("City:%s State:%s Country: %s Zip:%d\n",(ptr+B)->address.city,(ptr+B)->address.state,(ptr+B)->address.country,
*((ptr+B)->address.zip));
printf("Phone:%d\n\n",*((ptr+B)->phone.number));
}
}
}
//Allows user to delete record from a record from the database
void deleteRecord(PROFILE*ptr,int *count,int *searchFound)
{
int D;
if(*searchFound == -1)
printf("Failed to delete a record\n");
else
{
if((*count -1) == 1)
*count -= 1;
else
{
for(D = *searchFound; D < *count; D++)
{
*(ptr + D) = *(ptr + D + 1);
}
*count -= 1;
}
printf("\nFile %d deleted\n\n",(*searchFound+1));
}
}
//Allows user to edit a record from the database
void editrecord(PROFILE*ptr,int count)
{
if(count==0)
{
printf("No records are present to be modified.");
exit(0);
}
int record;
printf("Which record number would you like to change? ");
scanf("%d",&record);
printf("\n");
printf("You will now be asked to change the records for this profile.\n\n");
printf("Please enter the first and last name in that order\n");
scanf("%s %s",(ptr+record-1)->name.firstname,(ptr+record-1)->name.lastname);
printf("Now enter the streetnumber,street name,city,state,country and zip code\n");
scanf("%d %s %s %s %s %s %d",(ptr+record-1)->address.streetno,(ptr+record-1)->address.streetname,(ptr+record-1)->address.streetname1,
(ptr+record-1)->address.city,(ptr+record-1)->address.state,(ptr+record-1)->address.country,(ptr+record-1)->address.zip);
printf("Now please enter the phone number\n");
scanf("%d",(ptr+record-1)->phone.number);
printf("The editing process is now complete.\n\n");
}
//Prints all the data if user wants to see all the records at once
void printdata(PROFILE*ptr,int count)
{
int A;
if(count == 0)
printf("They are no records to be printed.\n\n");
else
{
for(A=0;A<count-1;A++)
{
printf("Name:%s %s\n",(ptr+A)->name.firstname,(ptr+A)->name.lastname);
printf("Address:%d %s %s\n",*((ptr+A)->address.streetno),(ptr+A)->address.streetname,(ptr+A)->address.streetname1);
if(*((ptr+A)->address.zip)<10000)
printf("City:%s State:%s Country: %s Zip:%05d\n",(ptr+A)->address.city,(ptr+A)->address.state,(ptr+A)->address.country,
*((ptr+A)->address.zip));
else
printf("City:%s State:%s Country: %s Zip:%d\n",(ptr+A)->address.city,(ptr+A)->address.state,(ptr+A)->address.country,
*((ptr+A)->address.zip));
printf("Phone:%d\n\n",*((ptr+A)->phone.number));
}
}
}
|
C
|
/*
Filename: mergeSort.c
Author: Tony Zeng
Mail: [email protected]
Function: implement of merge sorting algorithm
Time: 2013-6-24 13:56:25
*/
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
void merge(int* array, int low, int half, int high)
{
int leftLength = half - low + 1;
int rightLenght = high - half;
int* leftArray = malloc(sizeof(int) * leftLength);
int* rightArray = malloc(sizeof(int) * rightLenght);
int i, j, k; // i point to leftArray, j point to rightArray, and k point to array
if ( NULL == leftArray || NULL == rightArray)
{
printf("malloc error!\n");
exit(1);
}
// backup array with leftArray and rightArray
for (i = 0, k = low; i < leftLength; ++i, ++k)
{
leftArray[i] = array[k];
}
for (i = 0; i < rightLenght; ++i, ++k)
{
rightArray[i] = array[k];
}
for (k = low, i = j = 0; i < leftLength && j < rightLenght; ++k)
{
array[k] = (leftArray[i] < rightArray[j]) ? (leftArray[i++]) : (rightArray[j++]);
}
while (i < leftLength)
{
array[k++] = leftArray[i++];
}
while (j < rightLenght)
{
array[k++] = rightArray[j++];
}
free(leftArray);
leftArray = NULL;
free(rightArray);
rightArray = NULL;
}
void mergeSort(int* array, int low, int high)
{
if (low >= high)
{
return;
}
// int half = (low + high) / 2; // may overflow
int half = (low & high) + ((low ^ high) >> 1);
mergeSort(array, low, half);
mergeSort(array, half + 1, high);
merge(array, low, half, high);
}
int main(int argc, char** args)
{
printArray(array, length);
mergeSort(array, 0, length - 1);
printArray(array, length);
if (!checkArray(array, length))
{
printf("Error occured!\n");
}
return 0;
}
|
C
|
#include "Init_IO.h"
//ʼPB5PE5Ϊ.ʹڵʱ
//LED IOʼ
void LED_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //ʹPC˿ʱ
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15; //LED0-->PB.5 ˿
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IOٶΪ50MHz
GPIO_Init(GPIOA, &GPIO_InitStructure); //趨ʼGPIOC.13
GPIO_ResetBits(GPIOA,GPIO_Pin_15); //PC.13
GPIO_SetBits(GPIOA,GPIO_Pin_15); //PC.13
}
////ʼ̵˿ PC0\PC1\PC2
//void RELAY_Init(void)
//{
//
// GPIO_InitTypeDef GPIO_InitStructure;
//
// RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE); //ʹPC˿ʱ
//
// GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_2; //
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //
// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IOٶΪ50MHz
// GPIO_Init(GPIOC, &GPIO_InitStructure); //趨ʼGPIOC.0
// GPIO_ResetBits(GPIOC,GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_2); //PC.0 1 2
//}
|
C
|
#include "ev_iochannel.h"
#include <string.h> // memset
int check_for_close( ev_iochannel_t* self )
{
if (self->rio.eof && !self->wio.len)
if (self->on_close)
self->on_close( self );
return 0;
}
int on_rio_full( iobuf_t *io )
{
ev_iochannel_t *self = (ev_iochannel_t*)io->ctx;
ev_io_stop( self->loop, &self->ev_rio.watcher );
return 0;
}
int on_wio_empty( iobuf_t *io )
{
ev_iochannel_t *self = (ev_iochannel_t*)io->ctx;
ev_io_stop( self->loop, &self->ev_wio.watcher );
check_for_close( self );
return 0;
}
int on_rio_nonfull( iobuf_t *io )
{
ev_iochannel_t *self = (ev_iochannel_t*)io->ctx;
ev_io_start( self->loop, &self->ev_rio.watcher );
return 0;
}
int on_rio_eof( iobuf_t *io )
{
ev_iochannel_t *self = (ev_iochannel_t*)io->ctx;
ev_io_stop( self->loop, &self->ev_rio.watcher );
check_for_close( self );
return 0;
}
int on_wio_nonempty( iobuf_t *io )
{
ev_iochannel_t *self = (ev_iochannel_t*)io->ctx;
ev_io_start( self->loop, &self->ev_wio.watcher );
return 0;
}
int on_rio_data( iobuf_t *io )
{
ev_iochannel_t *self = (ev_iochannel_t*)io->ctx;
if (self->on_data) return self->on_data( self );
return 0;
}
int ev_iochannel_init
(
ev_iochannel_t *self,
struct ev_loop *loop,
void *ctx,
int rfd,
char *rbuf,
size_t rsize,
int wfd,
char *wbuf,
size_t wsize
)
{
memset( self, 0, sizeof *self );
self->loop = loop;
self->ctx = ctx;
iobuf_init( &self->rio );
iobuf_init( &self->wio );
self->rio.fd = rfd;
self->rio.buf = rbuf;
self->rio.size = rsize;
self->rio.len = 0;
self->rio.eof = 0;
self->rio.ctx = self;
self->rio.on_full = on_rio_full;
self->rio.on_nonfull = on_rio_nonfull;
self->rio.on_eof = on_rio_eof;
self->rio.on_data = on_rio_data;
self->wio.fd = wfd;
self->wio.buf = wbuf;
self->wio.size = wsize;
self->wio.len = 0;
self->wio.eof = 0;
self->wio.ctx = self;
self->wio.on_empty = on_wio_empty;
self->wio.on_nonempty = on_wio_nonempty;
self->ev_rio.io = &self->rio;
self->ev_wio.io = &self->wio;
ev_init( (ev_io*)&self->ev_rio, ev_iobuf_reader );
ev_io_set( (ev_io*)&self->ev_rio, rfd, EV_READ );
ev_init( (ev_io*)&self->ev_wio, ev_iobuf_writer );
ev_io_set( (ev_io*)&self->ev_wio, wfd, EV_WRITE );
return 0;
}
int ev_iochannel_start( ev_iochannel_t *self )
{
ev_io_start( self->loop, (ev_io*)&self->ev_rio );
return 0;
}
|
C
|
/*!
* \~chinese
* @header LLErrorCode.h
* @abstract SDK定义的错误类型
* @author Hyphenate
* @version 3.00
*
* \~english
* @header LLErrorCode.h
* @abstract SDK defined error type
* @author Hyphenate
* @version 3.00
*/
typedef enum{
LLErrorGeneral = 1, /*! \~chinese 一般错误 \~english General error */
LLErrorNetworkUnavailable, /*! \~chinese 网络不可用 \~english Network is unavaliable */
LLErrorInvalidAppkey = 100, /*! \~chinese Appkey无效 \~english App key is invalid */
LLErrorInvalidUsername, /*! \~chinese 用户名无效 \~english User name is invalid */
LLErrorInvalidPassword, /*! \~chinese 密码无效 \~english Password is invalid */
LLErrorInvalidURL, /*! \~chinese URL无效 \~english URL is invalid */
LLErrorUserAlreadyLogin = 200, /*! \~chinese 用户已登录 \~english User has already logged in */
LLErrorUserNotLogin, /*! \~chinese 用户未登录 \~english User has not logged in */
LLErrorUserAuthenticationFailed, /*! \~chinese 密码验证失败 \~english Password check failed */
LLErrorUserAlreadyExist, /*! \~chinese 用户已存在 \~english User has already exist */
LLErrorUserNotFound, /*! \~chinese 用户不存在 \~english User was not found */
LLErrorUserIllegalArgument, /*! \~chinese 参数不合法 \~english Illegal argument */
LLErrorUserLoginOnAnotherDevice, /*! \~chinese 当前用户在另一台设备上登录 \~english User has logged in from another device */
LLErrorUserRemoved, /*! \~chinese 当前用户从服务器端被删掉 \~english User was removed from server */
LLErrorUserRegisterFailed, /*! \~chinese 用户注册失败 \~english Register user failed */
LLErrorUpdateApnsConfigsFailed, /*! \~chinese 更新推送设置失败 \~english Update apns configs failed */
LLErrorUserPermissionDenied, /*! \~chinese 用户没有权限做该操作 \~english User has no right for this operation. */
LLErrorServerNotReachable = 300, /*! \~chinese 服务器未连接 \~english Server is not reachable */
LLErrorServerTimeout, /*! \~chinese 服务器超时 \~english Wait server response timeout */
LLErrorServerBusy, /*! \~chinese 服务器忙碌 \~english Server is busy */
LLErrorServerUnknownError, /*! \~chinese 未知服务器错误 \~english Unknown server error */
LLErrorFileNotFound = 400, /*! \~chinese 文件没有找到 \~english Can't find the file */
LLErrorFileInvalid, /*! \~chinese 文件无效 \~english File is invalid */
LLErrorFileUploadFailed, /*! \~chinese 上传文件失败 \~english Upload file failed */
LLErrorFileDownloadFailed, /*! \~chinese 下载文件失败 \~english Download file failed */
LLErrorMessageInvalid = 500, /*! \~chinese 消息无效 \~english Message is invalid */
LLErrorMessageIncludeIllegalContent, /*! \~chinese 消息内容包含不合法信息 \~english Message contains illegal content */
LLErrorMessageTrafficLimit, /*! \~chinese 单位时间发送消息超过上限 \~english Unit time to send messages over the upper limit */
LLErrorMessageEncryption, /*! \~chinese 加密错误 \~english Encryption error */
LLErrorGroupInvalidId = 600, /*! \~chinese 群组ID无效 \~english Group Id is invalid */
LLErrorGroupAlreadyJoined, /*! \~chinese 已加入群组 \~english User has already joined the group */
LLErrorGroupNotJoined, /*! \~chinese 未加入群组 \~english User has not joined the group */
LLErrorGroupPermissionDenied, /*! \~chinese 没有权限进行该操作 \~english User has NO authority for the operation */
LLErrorGroupMembersFull, /*! \~chinese 群成员个数已达到上限 \~english Reach group's max member count */
LLErrorGroupNotExist, /*! \~chinese 群组不存在 \~english Group is not exist */
LLErrorChatroomInvalidId = 700, /*! \~chinese 聊天室ID无效 \~english Chatroom id is invalid */
LLErrorChatroomAlreadyJoined, /*! \~chinese 已加入聊天室 \~english User has already joined the chatroom */
LLErrorChatroomNotJoined, /*! \~chinese 未加入聊天室 \~english User has not joined the chatroom */
LLErrorChatroomPermissionDenied, /*! \~chinese 没有权限进行该操作 \~english User has NO authority for the operation */
LLErrorChatroomMembersFull, /*! \~chinese 聊天室成员个数达到上限 \~english Reach chatroom's max member count */
LLErrorChatroomNotExist, /*! \~chinese 聊天室不存在 \~english Chatroom is not exist */
LLErrorCallInvalidId = 800, /*! \~chinese 实时通话ID无效 \~english Call id is invalid */
LLErrorCallBusy, /*! \~chinese 已经在进行实时通话了 \~english User is busy */
LLErrorCallRemoteOffline, /*! \~chinese 对方不在线 \~english Callee is offline */
LLErrorCallConnectFailed, /*! \~chinese 实时通话建立连接失败 \~english Establish connection failed */
}LLErrorCode;
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* heredoc_node.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fbertoia <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/12 14:25:16 by fbertoia #+# #+# */
/* Updated: 2018/03/12 14:25:18 by fbertoia ### ########.fr */
/* */
/* ************************************************************************** */
#include "sh21.h"
#include "ast.h"
void heredoc_node2(t_input *input, int fd)
{
if (input->buff && *input->buff)
{
write(fd, input->buff, ft_strlen(input->buff));
ft_putchar_fd('\n', fd);
}
input_init(input, 'h');
input_get(input);
}
void heredoc_node(t_ast_node *node)
{
t_input *input;
int fd;
char *tmp_file;
char *tmp_heredoc;
tmp_heredoc = node->content;
if (!(tmp_file = random_str(SIZE_RANDOM_STR)))
return ;
node->content = ft_strjoin(TMP_PATH_HEREDOC, tmp_file);
if ((fd = open(node->content, O_CREAT | O_WRONLY, 0644)) < 0)
{
ft_strdel(&tmp_heredoc);
return ;
}
ft_strdel(&tmp_file);
input = &sh21_get()->input;
input_init(input, 'h');
init_term(sh21_get());
while (!ft_strequ(input->buff, tmp_heredoc)
&& sh21_get()->terminal.isatty)
heredoc_node2(input, fd);
reinit_term(sh21_get());
ft_strdel(&tmp_heredoc);
close(fd);
}
|
C
|
#include "LinkedList.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
linked_list_t*
ll_create(unsigned int data_size)
{
linked_list_t *list = malloc(sizeof(linked_list_t));
list->data_size = data_size;
list->head = NULL;
list->size = 0;
return list;
}
/*
* Pe baza datelor trimise prin pointerul new_data, se creeaza un nou nod care e
* adaugat pe pozitia n a listei reprezentata de pointerul list. Pozitiile din
* lista sunt indexate incepand cu 0 (i.e. primul nod din lista se afla pe
* pozitia n=0). Daca n >= nr_noduri, noul nod se adauga la finalul listei. Daca
* n < 0, eroare.
*/
void ll_add_nth_node(linked_list_t* list, unsigned int n, const void* new_data)
{
if (list == NULL) {
printf("Nu a fost creata anterior o lista");
exit(2);
}
// luam un nod de parcurgere d ela inceputul listei
ll_node_t *current = list->head;
ll_node_t *auxiliary = malloc(sizeof(ll_node_t)); // aloc memorie pentru nodul auxiliar
auxiliary->next = NULL;
auxiliary->data = malloc(list->data_size);
memcpy(auxiliary->data, new_data, list->data_size);
if ((int)n < 0) {
printf("Pozitia nu este valida\n");
return;
} else if ((int)n >= (int)list->size) {
//daca n ul dat este mai mare sau egal decat dimensiunea, exista mai multe cauzuri
if (current == NULL) { // daca lista este goala
list->head = auxiliary;
auxiliary->next = NULL;
} else {
// daca lista nu e goala, inseamna ca trebuie sa inserez la finalul listeo
while(current->next != NULL) {
current = current->next;
}
current->next = auxiliary;
auxiliary->next = NULL;
}
} else if ((int)n == 0) { // inserare la inceputul listei
auxiliary->next = list->head;
list->head = auxiliary;
} else { //altfel, inserarea se face pe un nod ordinar
for(int i = 0; i < (int)n-1; i++) {
current = current->next;
}
auxiliary->next = current->next;
current->next = auxiliary;
}
list->size++;
}
/*
* Elimina nodul de pe pozitia n din lista al carei pointer este trimis ca
* parametru. Pozitiile din lista se indexeaza de la 0 (i.e. primul nod din
* lista se afla pe pozitia n=0). Daca n >= nr_noduri - 1, se elimina nodul de
* la finalul listei. Daca n < 0, eroare. Functia intoarce un pointer spre acest
* nod proaspat eliminat din lista. Este responsabilitatea apelantului sa
* elibereze memoria acestui nod.
*/
ll_node_t*
ll_remove_nth_node(linked_list_t* list, unsigned int n)
{
ll_node_t *current = list->head;
ll_node_t *previous, *auxiliary;
if (list == NULL) {
printf("Nu a fost creata anterior o lista");
exit(2);
}
if ((int)n < 0) {
printf("Pozitia nodului nu este valida");
exit(2);
} else if (list->head == NULL) {
printf("Nu au fost adaugate noduri in lista");
exit(2);
} else if ((int)n == 0) { // stergem la inceput
auxiliary = list->head;
list->head = auxiliary->next;
return auxiliary;
} else if ((int)n >= (int)list->size) { // elimin de la sfarsit
for (int i = 0; i < (int)list->size - 2; i++) {
current = current->next;
}
auxiliary = current->next;
current->next = NULL;
return auxiliary;
} else { // elimin nod oarecare
for (int i = 0; i < (int)n; i++) {
previous = current;
current = current->next;
}
previous->next = current->next;
return current;
}
list->size--;
}
/*
* Functia intoarce numarul de noduri din lista al carei pointer este trimis ca
* parametru.
*/
unsigned int
ll_get_size(linked_list_t* list)
{
return list->size;
}
/*
* Procedura elibereaza memoria folosita de toate nodurile din lista, iar la
* sfarsit, elibereaza memoria folosita de structura lista si actualizeaza la
* NULL valoarea pointerului la care pointeaza argumentul (argumentul este un
* pointer la un pointer).
*/
void ll_free(linked_list_t** pp_list)
{
ll_node_t *current = (*pp_list)->head;
// parcurgem fiecare nod si eliberam memoria datelor din nod si a nodului
// inainte de asta, modificam head ul
while ((*pp_list)->head != NULL) {
current = (*pp_list)->head;
(*pp_list)->head = (*pp_list)->head->next;
free(current->data);
free(current);
}
free(*pp_list);
}
/*
* Atentie! Aceasta functie poate fi apelata doar pe liste ale caror noduri STIM
* ca stocheaza int-uri. Functia afiseaza toate valorile int stocate in nodurile
* din lista inlantuita separate printr-un spatiu.
*/
void
ll_print_int(linked_list_t* list)
{
ll_node_t *current = list->head;
// parcurgem fiecare nod si il afisam
while(current != NULL) {
printf("%d ", *(int*)current->data);
current = current->next;
}
printf("\n");
}
/*
* Atentie! Aceasta functie poate fi apelata doar pe liste ale caror noduri STIM
* ca stocheaza string-uri. Functia afiseaza toate string-urile stocate in
* nodurile din lista inlantuita, separate printr-un spatiu.
*/
void
ll_print_string(linked_list_t* list)
{
ll_node_t *current = list->head;
// parcurgem fiecare nod si il afisam
while(current != NULL) {
printf("%s ", (char *)current->data);
current = current->next;
}
printf("\n");
}
|
C
|
#include <stdbool.h>
#include <stddef.h>
// stdbool.h for bool
// stddef.h for size_t, ptrdiff_t
struct linked_list;
struct node;
typedef double value_t;
typedef struct linked_list
{
struct node* first;
struct node* last;
size_t size;
} linked_list;
typedef struct node
{
struct node* prev;
struct node* next;
value_t value;
} node;
typedef bool (*comparator_t)(const value_t*, const value_t*);
typedef void (*callback_t)(const value_t*);
typedef node* iter_t;
typedef const node* const_iter_t;
/**
* Initializes a linked_list object.
*/
void linked_list_init(linked_list* list);
/**
* Copies a linked_list and all of its elements. The two lists should be fully independent of each other.
* Assume the destination list is empty.
*/
void linked_list_copy(linked_list* dest, const linked_list* src);
/**
* Clears a linked_list of all its elements.
*/
void linked_list_clear(linked_list* list);
/**
* Resizes a linked_list to the given size. For newly created nodes, initialize them with the given value.
*/
void linked_list_resize(linked_list* list, size_t newSize, value_t value);
/**
* Returns the size (number of elements) of a linked_list.
*/
size_t linked_list_size(const linked_list* list);
/**
* Returns the first element of a linked_list.
* Assume the list is not empty.
*/
value_t linked_list_front(const linked_list* list);
/**
* Returns the last element of a linked_list.
* Assume the list is not empty.
*/
value_t linked_list_back(const linked_list* list);
/**
* Adds an element with the given value to the beginning of a linked_list.
*/
void linked_list_push_front(linked_list* list, value_t value);
/**
* Adds an element with the given value to the end of a linked_list.
*/
void linked_list_push_back(linked_list* list, value_t value);
/**
* Removes the element at the beginning of a linked_list and returns it.
* Assume the list is not empty.
*/
value_t linked_list_pop_front(linked_list* list);
/**
* Removes the element at the end of a linked_list and returns it.
* Assume the list is not empty.
*/
value_t linked_list_pop_back(linked_list* list);
/**
* Returns the element at the given index of a linked_list.
* Assume idx is in the range [0, size)
*/
value_t linked_list_get(const linked_list* list, size_t idx);
/**
* Alters the element at the given index of a linked_list and returns the old value.
* Assume idx is in the range [0, size)
*/
value_t linked_list_set(linked_list* list, size_t idx, value_t newValue);
/**
* Reverses the elements of a linked_list.
*/
void linked_list_reverse(linked_list* list);
/**
* Sorts the elements of a linked_list in the order defined by the comparator.
*/
void linked_list_sort(linked_list* list, comparator_t comparator);
/**
* Appends one linked_list to the end of another. The source list should be an empty list.
* The source linked_list should become an empty linked list.
*/
void linked_list_append(linked_list* dest, linked_list* src);
/**
* Iterates over a linked_list and invokes a callback for each element.
*/
void linked_list_foreach(const linked_list* list, callback_t callback);
/**
* Swaps the elements of two linked_lists.
*/
void linked_list_swap(linked_list* list1, linked_list* link2);
/**
* Returns an iterator to the first element of a linked_list. If the list is empty, the end iterator is returned.
*/
iter_t linked_list_begin(linked_list* list);
/**
* Returns an iterator to one after the last element of a linked_list.
*/
iter_t linked_list_end(linked_list* list);
/**
* Returns the element associated with an iterator.
* Assume iter is in the range [begin, end).
*/
value_t linked_list_read(const linked_list* list, const_iter_t iter);
/**
* Alters the element associated with an iterator and returns the old value.
* Assume iter is in the range [begin, end).
*/
value_t linked_list_write(linked_list* list, iter_t iter, value_t value);
/**
* Advances an iterator by a number of steps, a negative step indicates advancing backwards.
* Assume iter + steps will be in the range [begin, end].
*/
iter_t linked_list_advance(linked_list* list, iter_t iter, ptrdiff_t steps);
/**
* Inserts an element before a given iterator and returns an iterator to the new element.
*/
iter_t linked_list_insert(linked_list* list, iter_t iter, value_t value);
/**
* Erases an element at the given iterator and returns the iterator following the erased element.
* Assume iter is in the range [begin, end) and iter != end.
*/
iter_t linked_list_erase(linked_list* list, iter_t iter);
/**
* Returns the distance between two nodes, negative if first comes after last.
*/
ptrdiff_t linked_list_dist(linked_list* list, const_iter_t iter1, const_iter_t iter2);
/**
* Inserts some number elements before the given iterator that are initialized with then given value.
* Returns an iterator to the first inserted element (or begin if count = 0).
*/
iter_t linked_list_insert_many(linked_list* list, iter_t begin, size_t count, value_t value);
/**
* Erases all elements in the range [begin, begin + count). If begin + count >= end, erase all elements after begin.
* Assume begin != end.
* Returns an iterator to the iterator following the last erased element (or begin if count = 0).
*/
iter_t linked_list_erase_many(linked_list* list, iter_t begin, size_t count);
/**
* Inserts some elements from the range [first, last) before dest.
* Assume dist(first, last) is non-negative and first != end.
* Returns an iterator to the first inserted element (or dest if first = last).
*/
iter_t linked_list_insert_range(linked_list* list, iter_t dest, const_iter_t first, const_iter_t last);
/**
* Erases all elements in the range [first, last)
* Assume dist(first, last) is non-negative and first != end.
* Returns the iterator following the last erased element (or first if first = last).
*/
iter_t linked_list_erase_range(linked_list* list, iter_t first, iter_t last);
/**
* Swaps the nodes associated with two iterators.
* Assume iter1, iter2 are in the range [begin, end).
*/
void linked_list_swap_nodes(linked_list* list, iter_t iter1, iter_t iter2);
/**
* Reverses the nodes of a linked_list by their elements from [first, last).
* Assume dist(first, last) is non-negative and first != end.
*/
void linked_list_reverse_nodes(linked_list* list, iter_t first, iter_t last);
/**
* Sorts the nodes of a linked_list by their elements from [first, last) in the order defined by a comparator.
* Assume dist(first, last) is non-negative, and and first != end.
*/
void linked_list_sort_nodes(linked_list* list, iter_t first, iter_t last, comparator_t comparator);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "ulity.h"
void *int_to_pointer(int i)
{
int *pi = (int *)malloc(sizeof(int));
*pi = i;
return (void*)pi;
}
void *float_to_pointer(float f);
{
float *pf = (float *)malloc(sizeof(float));
*pf = f;
return (void*)pf;
}
int pointer_to_int(void *pi);
{
return *((int*)pi);
}
float pointer_to_float(void *pf);
{
return *((float*)pf);
}
|
C
|
#define MAX 100
int posx = 0, posy = 0;
int cursx = 30, cursy = 30;
int nbmouv = 0;
int Choix7 ;
int Visibilite;
FILE *f ;
void Effacer_Curseur(int x, int y)
{
set_drawing_color(color_WHITE);
draw_circle_full(x, y, 15);
update_graphics () ;
return ;
}
int Verifier_Cases_Autour(int CASE[MAX][MAX], int n)
//Verifie si les cases autour de la case actuelle sont reliées au labyrinthe
//Renvoie 1 si toutes les cases autour sont reliées, 0 sinon
{
if(CASE[posx][posy+1] == 1 && CASE[posx][posy-1] == 1 && CASE[posx+1][posy] == 1 && CASE[posx-1][posy] == 1)
{return 1 ;
}
if (posx == 0 && CASE[posx][posy+1] == 1 && CASE[posx][posy-1] == 1 && CASE[posx+1][posy] == 1)
{return 1 ;
}
if (posy == 0 && CASE[posx][posy+1] == 1 && CASE[posx+1][posy] == 1 && CASE[posx-1][posy] == 1)
{return 1 ;
}
if (posx == n-1 && CASE[posx][posy+1] == 1 && CASE[posx][posy-1] == 1 && CASE[posx-1][posy] == 1)
{return 1 ;
}
if (posy == n-1 && CASE[posx][posy-1] == 1 && CASE[posx+1][posy] == 1 && CASE[posx-1][posy] == 1)
{return 1 ;
}
if (posx == 0 && posy == 0 && CASE[posx][posy+1] == 1 && CASE[posx+1][posy] == 1)
{return 1 ;
}
if (posx == 0 && posy == n-1 && CASE[posx][posy-1] == 1 && CASE[posx+1][posy] == 1)
{return 1 ;
}
if (posx == n-1 && posy == 0 && CASE[posx][posy+1] == 1 && CASE[posx-1][posy] == 1)
{return 1 ;
}
if (posx == n-1 && posy == n-1 && CASE[posx][posy-1] == 1 && CASE[posx-1][posy] == 1)
{return 1 ;
}
return 0;
}
int Verifier_Labyrinthe(int CASE[MAX][MAX], int n)
//Renvoie 1 si toutes les cases du labyrinthe sont reliées, 0 sinon
{
int i, j ;
for(i=0; i<n; i++){
for(j=0; j<n; j++){
if(CASE[i][j]==0)
{return 0;}
}
}
return 1;
}
void Demitour(int CHEMIN[MAX])
//Permet a la fonction CreationLabyrinthe de revenir en dans la case précédente
{
Effacer_Curseur(cursx, cursy);
if(CHEMIN[nbmouv] == 1)
{
posy = posy +1;
cursy = cursy +60;
}
if(CHEMIN[nbmouv] == 2)
{
posx = posx +1;
cursx = cursx +60;
}
if(CHEMIN[nbmouv] == 3)
{
posx = posx -1;
cursx = cursx-60;
}
if(CHEMIN[nbmouv] == 4)
{
posy = posy -1;
cursy = cursy -60;
}
if(Visibilite){Creer_Curseur(&cursx, &cursy);}
update_graphics () ;
nbmouv = nbmouv -1;
}
void Creation(int CHEMIN[MAX], int MUR_auto[MAX][MAX], int CASE[MAX][MAX], int n)
//Crée le labyrinthe en reliant une case de la grille non reliée à la case actuelle
{
if(Verifier_Cases_Autour(CASE, n)==1)
{
Demitour(CHEMIN);
return ;
}
int c;
c = rand()%4 +1;
//printf("direction est %d\n", c);
if(c==1)
{
if(posy-1>=0)
{
if(CASE[posx][posy-1] == 0)
{
Supprimer_Murs(2, cursx, cursy, posx, posy, MUR_auto);
posy = posy -1;
CASE[posx][posy] = 1;
nbmouv = nbmouv +1 ;
CHEMIN[nbmouv] = c;
Effacer_Curseur(cursx, cursy);
cursy = cursy -60;
if(Visibilite){Creer_Curseur(&cursx, &cursy);}
update_graphics();
}
}
}
if(c==2)
{
if(posx-1>=0)
{
if(CASE[posx-1][posy] == 0)
{
Supprimer_Murs(4, cursx, cursy, posx, posy, MUR_auto);
posx = posx -1;
CASE[posx][posy] = 1;
nbmouv = nbmouv +1 ;
CHEMIN[nbmouv] = c;
Effacer_Curseur(cursx, cursy);
cursx = cursx -60;
if(Visibilite){Creer_Curseur(&cursx, &cursy);}
}
}
}
if(c==3)
{
if(posx+1<n)
{
if(CASE[posx+1][posy] == 0)
{
Supprimer_Murs(6, cursx, cursy, posx, posy, MUR_auto);
posx = posx +1;
CASE[posx][posy] = 1 ;
nbmouv = nbmouv +1 ;
CHEMIN[nbmouv] = c;
Effacer_Curseur(cursx, cursy);
cursx = cursx +60;
if(Visibilite){Creer_Curseur(&cursx, &cursy);}
}
}
}
if(c==4)
{
if(posy+1<n)
{
if(CASE[posx][posy+1] == 0)
{
Supprimer_Murs(8, cursx, cursy, posx, posy, MUR_auto);
posy = posy +1;
CASE[posx][posy] = 1;
nbmouv = nbmouv +1 ;
CHEMIN[nbmouv] = c;
Effacer_Curseur(cursx, cursy);
cursy = cursy +60;
if(Visibilite){Creer_Curseur(&cursx, &cursy);}
}
}
}
}
void Creation_Laby_Auto(int n, int Visu)
{
int i, j;
int MUR_auto[MAX][MAX]; //tableau mur habituel
int CASE[MAX][MAX]; //Sert a savoir si une case du laby est réliée
int CHEMIN[MAX]; //Permet de connaitre les mouvements précédents
Visibilite = Visu;
for(i=0; i<=n; i++){
for(j=0; j<=n; j++){
CASE[i][j]=0;
}
}
for(i=0; i<MAX; i++){
for(j=0; j<MAX; j++){
MUR_auto[i][j]=1;
}
}
CASE[0][0] = 1;
clear_screen();
Grille(n);
Creer_Curseur(&cursx, &cursy);
if(!Visibilite){clear_screen();}
while(Verifier_Labyrinthe(CASE, n) == 0)
{
Creation(CHEMIN, MUR_auto, CASE, n);
update_graphics();
usleep(50);
}
nbmouv = 0;
posx = 0;
posy = 0;
cursx = 30;
cursy = 30;
set_drawing_color (color_BLACK) ;
set_font (font_HELVETICA_12) ;
draw_string (530, 210, "Pour finir,") ;
draw_string (490, 170, "appuyez sur une touche") ;
update_graphics () ;
get_key();
clear_screen () ;
set_drawing_color (color_RED) ;
set_font (font_HELVETICA_18) ;
draw_string (100, 400, "Entrez le chiffre correspondant a votre choix :") ;
set_drawing_color (color_BLACK) ;
set_font (font_HELVETICA_12) ;
draw_string (120, 360, "1 : Sauvegarde du labyrinthe dans 'Labyrinthe1.txt'") ;
draw_string (120, 320, "2 : Sauvegarde du labyrinthe dans 'Labyrinthe2.txt'") ;
draw_string (120, 280, "3 : Sauvegarde du labyrinthe dans 'Labyrinthe3.txt'") ;
update_graphics () ;
Choix7 = get_key () - 48 ;
if (Choix7 == 1)
// Enregister dans 'Labyrinthe1.txt'
{f = fopen ("Labyrinthe1.txt", "w") ;
Enregistrement (f, MUR_auto) ;
fclose (f) ;
f = fopen ("Labyrinthe1n.txt", "w") ;
Enregistrement_n (f, n) ;
fclose (f) ;
}
if (Choix7 == 2)
// Enregister dans 'Labyrinthe2.txt'
{f = fopen ("Labyrinthe2.txt", "w") ;
Enregistrement (f, MUR_auto) ;
fclose (f) ;
f = fopen ("Labyrinthe2n.txt", "w") ;
Enregistrement_n (f, n) ;
fclose (f) ;
}
if (Choix7 == 3)
// Enregister dans 'Labyrinthe3.txt'
{f = fopen ("Labyrinthe3.txt", "w") ;
Enregistrement (f, MUR_auto) ;
fclose (f) ;
f = fopen ("Labyrinthe3n.txt", "w") ;
Enregistrement_n (f, n) ;
fclose (f) ;
}
}
void Creation_Laby_Auto_Passer(int n, int Visu)
{
int i, j;
int MUR_auto[MAX][MAX]; //tableau mur habituel
int CASE[MAX][MAX]; //Sert a savoir si une case du laby est réliée
int CHEMIN[MAX]; //Permet de connaitre les mouvements précédents
Visibilite = Visu;
for(i=0; i<=n; i++){
for(j=0; j<=n; j++){
CASE[i][j]=0;
}
}
for(i=0; i<MAX; i++){
for(j=0; j<MAX; j++){
MUR_auto[i][j]=1;
}
}
CASE[0][0] = 1;
clear_screen();
Creer_Curseur(&cursx, &cursy);
if(!Visibilite){clear_screen();}
while(Verifier_Labyrinthe(CASE, n) == 0)
{
Creation(CHEMIN, MUR_auto, CASE, n);
update_graphics();
usleep(50);
}
nbmouv = 0;
posx = 0;
posy = 0;
cursx = 30;
cursy = 30;
clear_screen () ;
set_drawing_color (color_RED) ;
set_font (font_HELVETICA_18) ;
draw_string (100, 400, "Entrez le chiffre correspondant a votre choix :") ;
set_drawing_color (color_BLACK) ;
set_font (font_HELVETICA_12) ;
draw_string (120, 360, "1 : Sauvegarde du labyrinthe dans 'Labyrinthe1.txt'") ;
draw_string (120, 320, "2 : Sauvegarde du labyrinthe dans 'Labyrinthe2.txt'") ;
draw_string (120, 280, "3 : Sauvegarde du labyrinthe dans 'Labyrinthe3.txt'") ;
update_graphics () ;
Choix7 = get_key () - 48 ;
if (Choix7 == 1)
// Enregister dans 'Labyrinthe1.txt'
{f = fopen ("Labyrinthe1.txt", "w") ;
Enregistrement (f, MUR_auto) ;
fclose (f) ;
f = fopen ("Labyrinthe1n.txt", "w") ;
Enregistrement_n (f, n) ;
fclose (f) ;
}
if (Choix7 == 2)
// Enregister dans 'Labyrinthe2.txt'
{f = fopen ("Labyrinthe2.txt", "w") ;
Enregistrement (f, MUR_auto) ;
fclose (f) ;
f = fopen ("Labyrinthe2n.txt", "w") ;
Enregistrement_n (f, n) ;
fclose (f) ;
}
if (Choix7 == 3)
// Enregister dans 'Labyrinthe3.txt'
{f = fopen ("Labyrinthe3.txt", "w") ;
Enregistrement (f, MUR_auto) ;
fclose (f) ;
f = fopen ("Labyrinthe3n.txt", "w") ;
Enregistrement_n (f, n) ;
fclose (f) ;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main() {
pid_t result1;
pid_t result2;
printf("<A> -- pid = %d, ppid = %d\n", getpid(), getppid());
result1 = fork();
if (result1 < 0) {
perror("Failed to create process after <A>");
exit(1);
}
printf("<B> -- pid = %d, ppid = %d, result1 = %d.\n", getpid(), getppid(), result1);
result2 = fork();
if (result2 < 0) {
perror("Failed to create process after <B>");
exit(1);
}
printf("<C> -- pid = %d, ppid = %d, result2 = %d.\n", getpid(), getppid(), result2);
sleep(2);
return (EXIT_SUCCESS);
}
|
C
|
/* file: $RCSfile: v6init.c,v $
** rcsid: $Id$
** Copyright Jeffrey W Percival
** *******************************************************************
** Space Astronomy Laboratory
** University of Wisconsin
** 1150 University Avenue
** Madison, WI 53706 USA
** *******************************************************************
** Do not use this software without attribution.
** Do not remove or alter any of the lines above.
** *******************************************************************
*/
/*
** *******************************************************************
** $RCSfile: v6init.c,v $ - 6-vector initialization
** *******************************************************************
*/
#include "vec.h"
V6
v6init(int type)
{
V6 v;
if (type == SPHERICAL) {
v6SetType(v, POLAR);
v6SetR(v, 0.0);
v6SetAlpha(v, 0.0);
v6SetDelta(v, 0.0);
v6SetRDot(v, 0.0);
v6SetAlphaDot(v, 0.0);
v6SetDeltaDot(v, 0.0);
} else {
v6SetType(v, CARTESIAN);
v6SetX(v, 0.0);
v6SetY(v, 0.0);
v6SetZ(v, 0.0);
v6SetXDot(v, 0.0);
v6SetYDot(v, 0.0);
v6SetZDot(v, 0.0);
}
return(v);
}
|
C
|
/*
* Copyright (C) ST-Ericsson SA 2010. All rights reserved.
* This code is ST-Ericsson proprietary and confidential.
* Any use of the code for whatever purpose is subject to
* specific written permission of ST-Ericsson SA.
*/
/*
* UNIX domain socket server external interface.
*/
#ifndef __sockserv_h__
#define __sockserv_h__ (1)
#include <sys/types.h>
#include "cn_general.h"
typedef enum {
SOCKSERV_REASON_CONNECT_REQUEST,
SOCKSERV_REASON_CONNECTED,
SOCKSERV_REASON_RECEIVE,
SOCKSERV_REASON_DISCONNECTED,
} sockserv_reason_t;
typedef unsigned long sockserv_context_t;
/**
* @brief Callback function used by the socket server service
*
* @param instance Socket server instance
* @param client Client reference
* @param context_p Pointer to context
* @param reason Reason for callback
* @param buf Pointer to message buffer
* @param size Number of bytes in message buffer
*
* @returns Number of bytes processed
*
*/
typedef int sockserv_callback_t(const int instance, const int client,
const void *context_p, const sockserv_reason_t reason,
const cn_uint8_t *buf_p, const size_t size);
/**
* The sockserv_init() function initialises the socket server service
*
* @brief Initialise the socket server service.
*
* @param max_servers Number of simultaneous servers allowed.
*
* @return Returns an int.
* @retval >=0 if successful
* @retval <0 if not.
*/
int sockserv_init(const int max_servers);
/**
* The sockserv_create() function creates and initialises an instance of the socket server
*
* @brief Create and initialise a socket server.
*
* @param name Name of socket.
* @param max_connections Number of simultaneous connections allowed.
* @param cb_func Pointer to callback function
*
* @return Returns an int, socket server instance number.
* @retval >=0 if successful
* @retval <0 if not.
*/
int sockserv_create(const char *name, const int max_clients,
sockserv_callback_t *cb_func);
/**
* The sockserv_set_context() function to sets context for a client connected socket
*
* @brief Send through connected socket
*
* @param instance Socket server instance
* @param client Client reference
* @param context_p Pointer to context
*
* @return Returns an int.
* @retval >=0 if successful
* @retval <0 if not.
*/
int sockserv_set_context(const int instance, const int client, void *context_p);
/**
* The sockserv_send() function to send on socket
*
* @brief Send through connected socket
*
* @param instance Socket server instance
* @param client Client reference
* @param buf Pointer to buffer
* @param len Buffer length
*
* @return Returns an int.
* @retval >=0 if successful
* @retval <0 if not.
*/
int sockserv_send(const int instance, const int client, const void *buf_p,
const size_t len);
/**
* The sockserv_close() function closes a connected socket
*
* @brief Close connected socket
*
* @param instance Socket server instance
* @param client Client reference
*
* @return Returns an int.
* @retval 0 if successful
* @retval -1 if not.
*/
int sockserv_close(const int instance, const int client);
/**
* The sockserv_destroy() function shuts down a socket server
*
* @brief Shut down a socket server.
*
* @param instance Socket server instance
*
* @return Returns an int.
* @retval 0 if successful
* @retval -1 if not.
*/
int sockserv_destroy(const int instance);
/**
* The sockserv_shutdown() function shuts down the socket server service
*
* @brief Shuts down the socket server service.
*
* @return Returns an int.
* @retval 0 if successful
* @retval -1 if not.
*/
int sockserv_shutdown(void);
#endif /* __sockserv_h__ */
|
C
|
//
// Post_processing.c
// Astrophysical_Turbulence
//
// Created by Mrinal Jetti on 09/09/20.
// Copyright © 2020 Mrinal Jetti. All rights reserved.
//
#include "parameters.h"
#include "post_processing.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
//Variables, data stored at each point of the box
double *all_data_array = (double *)malloc(sizeof(double)*((nv)*(nx*ny*nz)));
double *rho = (double *)malloc(sizeof(double)*(nx*ny*nz));
double *vx1 = (double *)malloc(sizeof(double)*(nx*ny*nz));
double *vx2 = (double *)malloc(sizeof(double)*(nx*ny*nz));
double *vx3 = (double *)malloc(sizeof(double)*(nx*ny*nz));
double *prs = (double *)malloc(sizeof(double)*(nx*ny*nz));
//Derived variables
double *temp = (double *)malloc(sizeof(double)*(nx*ny*nz));//Temperature=(P/rho)*(mu*amu/Kb) multiply by UNIT_LENGTH^2 in units
double *mach = (double *)malloc(sizeof(double)*(nx*ny*nz));//Mach = |v|/cs
double *sb = (double *)malloc(sizeof(double)*(nx*ny)); //Surface brigthness = integral(n^2*lamda(T)*dz)
double *vlos = (double *)malloc(sizeof(double)*(nx*ny)); //vlos = integral(vz*n^2*lamda(T)*dz)/sb
double *sigvlos = (double *)malloc(sizeof(double)*(nx*ny));//sigvlos = integral((vz-vlos)^2*n^2*lamda(T)*dz)/sb
//Derived variables
double cs;
double cs_avg;
double num_density;
double radiation_rate; //(rho)/(mu*amu)
double sb_rms; //sb_rms = sqrt(<sb^2>-<sb>^2) where <> denotes average
double sb_avg; //sb average
double temp_avg; //temp average
double v_rms; //sqrt(<|v|^2>)
double mach_rms; //v_rms/cs_avg
//NOTE sb_rms/sb_avg is stored in the file fpsb
//Looping variables
int i,j,i1,j1,k1;
FILE *fp; // This file stores rho,vx,vy,vz,prs
FILE *fpsb; // This file stores sb_rms/sb_avg,temp_avg, mach_rms : file name sb_data.txt
char filenum[5];
char filename[100];
fpsb = fopen(sb_data_dir,"w");
fprintf(fpsb,"del_sb_rms/sb_avg\ttemp_avg\tmrms\n");
//This loop is over the .dbl files(snapshots of our box)
for(i=f1;i<=f2;i++)
{
read_dbl(i, all_data_array);
sprintf(filenum,"%04d",i);
strcpy(filename, datdir );
strcat(filename,data_prefix);
strcat(filename,filenum);
strcat(filename,data_suffix);
fp = fopen( filename ,"w");
fprintf(fp,"rho\tvx1\tvx2\tvx3\tprs\t\n");
if(fp==NULL)
{
printf("Error!!");
exit(1);
}
//This loop is over all the points of our simulation box
//rho,vx,vy,vz,prs variables are written to fp
//temp_avg,mach_rms,v_rms are evaluated
temp_avg = 0.0;
mach_rms = 0.0;
v_rms = 0.0;
cs_avg = 0.0;
for(j=0;j<(nx*ny*nz);j++)
{
rho[j] = all_data_array[j];
vx1[j] = all_data_array[j+nx*ny*nz];
vx2[j] = all_data_array[j+2*nx*ny*nz];
vx3[j] = all_data_array[j+3*nx*ny*nz];
prs[j] = all_data_array[j+4*nx*ny*nz];
temp[j] = (prs[j]/rho[j])*((CONST_mu*UNIT_VELOCITY*UNIT_VELOCITY*CONST_mp)/CONST_kB);
temp_avg += temp[j];
cs = sqrt(gamma*(prs[j])/rho[j]);
cs_avg += cs;
mach[j] = sqrt(vx1[j]*vx1[j]+vx2[j]*vx2[j]+vx3[j]*vx3[j])/cs;
v_rms += vx1[j]*vx1[j]+vx2[j]*vx2[j]+vx3[j]*vx3[j];
if(temp[j]<0.)
{
printf("error here %lf %lf %d\n", rho[j],prs[j],j);
exit(0);
}
fprintf(fp,"%f\t%f\t%f\t%f\t%f\t",rho[j],vx1[j],vx2[j],vx3[j],prs[j]);
fprintf(fp,"\n");
}
fclose(fp);
cs_avg = cs_avg/(nx*ny*nz);
v_rms = sqrt(v_rms/(nx*ny*nz));
temp_avg = temp_avg/(nx*ny*nz);
mach_rms = v_rms/cs_avg;
//This loop is to calcualte sb,vlos by keeping in focus the integral to be evaluted along the z-direction
sb_rms = 0.0;
sb_avg = 0.0;
for(i1=0;i1<nx;i1++)
{
for(j1=0;j1<ny;j1++)
{
sb[i1*ny+j1] = 0.0;
vlos[i1*ny+j1] = 0.0;
//integral along z-direction
for(k1=0;k1<nz;k1++)
{
num_density = rho[i1*(ny*nz)+(j1*nz+k1)]*UNIT_DENSITY/CONST_mu/CONST_mp;
radiation_rate = num_density*num_density*lambda(temp[i1*(ny*nz)+(j1*nz+k1)]);
sb[i1*ny+j1] += radiation_rate*(1.0/(double)nz)*UNIT_LENGTH;
vlos[i1*ny+j1] += vx3[i1*(ny*nz)+(j1*nz+k1)]*UNIT_VELOCITY*radiation_rate*(1.0/(double)nz)*UNIT_LENGTH;
}
vlos[i1*ny+j1] = vlos[i1*ny+j1]/sb[i1*ny+j1];
sb_rms += sb[i1*ny+j1]*sb[i1*ny+j1];
sb_avg += sb[i1*ny+j1];
//sigvlos calculation
sigvlos[i1*ny+j1] = 0.0;
for(k1=0;k1<nz;k1++)
{
num_density = rho[i1*(ny*nz)+(j1*nz+k1)]*UNIT_DENSITY/CONST_mu/CONST_mp;
radiation_rate = num_density*num_density*lambda(temp[i1*(ny*nz)+(j1*nz+k1)]);
sigvlos[i1*ny+j1] += (vx3[i1*(ny*nz)+(j1*nz+k1)]-vlos[i1*ny+j1])*(vx3[i1*(ny*nz)+(j1*nz+k1)]-vlos[i1*ny+j1])*UNIT_VELOCITY*radiation_rate*(1.0/(double)nz)*UNIT_LENGTH;
}
sigvlos[i1*ny+j1] = sigvlos[i1*ny+j1]/sb[i1*ny+j1];
}
}
sb_avg = sb_avg/(nx*ny);
sb_rms = (sb_rms/(nx*ny)); // - pow(sb_avg,2);
sb_rms = sqrt(sb_rms - pow(sb_avg,2));
//Write the variables to sb_data.txt
fprintf(fpsb,"%lf\t%lf\t%lf\n",sb_rms/sb_avg,temp_avg,mach_rms);
}
fclose(fpsb);
return 0;
}
|
C
|
#include <stdio.h>
main()
{
int boyut,i,dizi[]={2,5,8,9,5};
boyut=sizeof dizi / sizeof*dizi;
printf("%d\n",boyut);
getch();
int dizi2[boyut];
for(i=0;i<boyut;i++)
{
dizi2[i]=dizi[boyut-i-1];
printf("%d,",dizi2[i]);
}
getch();
}
|
C
|
/*
* sockselectcl.c : sockselect client
* gcc -Wall -ggdb3 sockselectcl.c -o sockselectcl
*/
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <netinet/in.h>
#include <resolv.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#define PORT 5555
#define MAXMSG 512
int read_from_remote (int filedes)
{
char buffer [MAXMSG];
int nbytes;
memset (buffer, 0, MAXMSG);
nbytes = read (filedes, buffer, MAXMSG);
if (nbytes < 0)
{
/* Read error */
perror ("read");
exit (EXIT_FAILURE);
}
else if (nbytes == 0)
{
/* End of file */
return -1;
}
else
{
/* Data read */
fprintf (stderr, "Server : got message: '%s'\n", buffer);
return 0;
}
}/* end of read_from_remote */
int main (int argc, char *argv[])
{
char host_name [] = {"127.0.0.1"};
struct sockaddr_in my_addr;
char buff[MAXMSG];
int bytecount = 0;
int buffer_len = 0;
int hsock;
int err;
int *p_int;
int port = PORT;
struct timeval tv;
int packets = 0;
int ret;
if (argc > 1)
{
port = atoi (argv[1]);
}
tv.tv_sec = 1;
tv.tv_usec = 0;
fd_set active_fd_set, read_fd_set, write_fd_set;
hsock = socket (AF_INET, SOCK_STREAM, 0); /* create the socket descriptor */
if (hsock == -1)
{
fprintf (stderr, "error initializing socket %d\n", errno);
exit (EXIT_FAILURE);
}
p_int = (int *) calloc (1, sizeof (int));
*p_int = 1;
if ((setsockopt (hsock, SOL_SOCKET, SO_REUSEADDR, (char *)p_int, sizeof (int)) == -1) ||
(setsockopt (hsock, SOL_SOCKET, SO_KEEPALIVE, (char *)p_int, sizeof (int)) == -1))
{
fprintf (stderr, "error setting options %d\n", errno);
free (p_int);
close (hsock);
exit (1);
}
free (p_int);
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons (port);
memset (&(my_addr.sin_zero), 0, 8);
my_addr.sin_addr.s_addr= inet_addr (host_name);
if (connect (hsock, (struct sockaddr *) &my_addr, sizeof (my_addr)) == -1)
{
if ((err = errno) != EINPROGRESS)
{
fprintf (stderr, "error connection socket %d\n", errno);
close (hsock);
exit (EXIT_FAILURE);
}
}
while (1)
{
FD_ZERO (&active_fd_set);
FD_SET (hsock, &active_fd_set);
write_fd_set = active_fd_set;
/* select returns 0 if timeout, -1 if error*/
/* http://www.gnu.org/software/libc/manual/html_node/Waiting-for-I_002fO.html */
if ((ret = select (hsock + 1, NULL, &write_fd_set, NULL, &tv))<0)
{
fprintf (stderr, "error write select %d errno %d", ret, errno);
close (hsock);
exit (EXIT_FAILURE);
}
else if (ret == 0)
{
//no bits set
fprintf (stderr, "no bits set: timeout write\n");
sleep (2);
}
else
{
if (!packets)
{
write (hsock, "sign on", 7);
packets ++;
}
}
read_fd_set = active_fd_set;
if ((ret = select (hsock + 1, &read_fd_set, NULL, NULL, &tv))<0)
{
fprintf (stderr, "error write select %d errno %d", ret, errno);
close (hsock);
exit (EXIT_FAILURE);
}
else if (ret == 0)
{
//no bits set
fprintf (stderr, "no bits set: timeout read\n");
sleep (2);
}
else
{
if (packets)
{
read_from_remote (hsock);
packets --;
}
}
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void selctionsort(int a[], int n);
void main()
{
int i,n,a[100];
printf("enter the value of n\n");
scanf("%d",&n);
printf("enter the elements of the array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
selectionsort(a,n);
}
void selectionsort(int a[], int n)
{
int i,j,k,min,temp;
for(i=0;i<n-1;i++)
{
min =i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[min])
min=j;
}
temp=a[min];
a[min]=a[i];
a[i]=temp;
}
for(k=0;k<n;k++)
{
printf("%d",a[k]);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <malloc.h>
#include <xmmintrin.h>
#include <omp.h>
//algorytm eliminacji gaussa-jordana
int main(int argc, char *argv[])
{
double **A, *b, *x;
double c;
clock_t begin_t, end_t;
double begin_to, end_to;
long i,j,k,l,n;
n=atoi(argv[1]);
//inicjacja macierzy i wektorw
A=(double**)malloc((n+1)*sizeof(double*));
b=(double*)malloc((n+1)*sizeof(double*));
x=(double*)malloc((n+1)*sizeof(double*));
for(i=1;i<=n;i++)
A[i]=(double*)malloc((n+1)*sizeof(double*));
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
A[j][i]=(double)(i+j)/1000.0f;
b[i]=(double)(i)/1000.f;
}
/*
A[1][1]=1;
A[1][2]=2;
A[2][1]=3;
A[2][2]=4;
b[1]=5;
b[2]=6;
*/
//etap eliminacji zmiennych
begin_t=clock();
begin_to=omp_get_wtime();
for(k=1;k<=n;k++)
{
#pragma omp parallel for shared(A,b,k,n) private(i,j,c)
for(i=1;i<=n;i++)
{
if(i==k){
continue;}
c=A[i][k]/A[k][k];
for(j=k;j<=n;j++)
{
A[i][j]=A[i][j]-c*A[k][j];
}
b[i]=b[i]-c*b[k];
}
}
for(l=1;l<=n;l++)
x[l]=b[l]/A[l][l];
end_t=clock();
end_to=omp_get_wtime();
//printf("ROzwiazanie: x[1], x[2]= %f %f\n",x[1],x[2]);
printf("Czas obliczen OMP (gaussa-jordana): %f.\n",end_to-begin_to);
printf("Czas obliczen zwykly (gaussa-jordana): %f.\n",(double)(end_t-begin_t)/CLOCKS_PER_SEC);
//zwalnianie pamieci
for(i=1;i<n;i++)
free(A[i]);
free(A);
free(b);
free(x);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void swap(char*,int);
void gotoloop(char*,int);
void main()
{
char *ch;
int i,j,k,l;
ch=(char*)malloc(20);
//clrscr();
printf("Enter the string\n");
gets(ch);
l=strlen(ch);
gotoloop(ch,l);
return;
}
void gotoloop(char *ch,int l)
{
int i,k;
k=l;
if(l<=1)
return;
for(i=0;i<k;i++)
{
swap(ch,k);
l--;
gotoloop(ch,l);
l++;
if(k==2)
printf("\n%s ",ch);
}
}
void swap(char *ch,int r)
{
char c;
int i;
c=ch[r-1];
for(i=r-1;i>0;i--)
ch[i]=ch[i-1];
ch[0]=c;
}
|
C
|
#include "led.h"
#include "delay.h"
#include "sys.h"
#include "usart.h"
#include "EEpromI2C.H"
//1,2,3,4,5,6,7,8,9
int main(void)
{
u16 i=0;
u16 times=0;
u8 ReadData[256]={0};
u8 WriteData[256]={0};
for(i=0;i<256;i++)
{
WriteData[i]=(255-i);
}
delay_init(); //ʱʼ
uart_init(115200); //ڳʼΪ115200
LED_Init(); //LED˿ڳʼ
I2C_EEPROM_config(); //i2cʼ
////дһֽڶ
// printf("IIC1ֽʵ\r\n");
// EEPROM_Byte_Write(0x09, 0x55); //дһֽ 洢ֵַ 洢ֵ
// EEPROM_WaitForWriteEnd(); //д
// EEPROM_Read(0x11, ReadData, 1);
// //ʾ
// printf("յ:0x%x\r\n", ReadData[0]);
//
// printf("\r\n");
//
////д8ֽڶ
// printf("IIC8ֽʵ\r\n");
// printf("յ:");
// EEPROM_8Byte_Write(0x08, WriteData, 8);
// EEPROM_WaitForWriteEnd(); //д
// EEPROM_Read(0x08, ReadData, 8);
// for(i=0; i<8; i++)
// {
// printf("0x%x ", ReadData[i]);
// }
// printf("\r\n\r\n\r\n");
//ӡ
printf("EEPROMдʵ\r\n ");
for(i=0; i<256; i++)
{
printf("0x%02x ", WriteData[i]);
if(i%16==15)//ΪǴ0ʼ 15س 31س 47637995ӡس
{ //i%15==0Ļ 0153045ӡس ÿ15س
//i%16==0Ļ 0163248ӡس Ȼÿ16س һʼ0ͻس Բ
printf("\r\n ");
}
}
//д
for(i=0;i<255;i++)
{
//EEPROM_8Byte_Write(0x00+i, WriteData, 8);
EEPROM_Byte_Write(0x00+i, 255-i);
EEPROM_WaitForWriteEnd(); //д
}
// }
printf("---------------------ָ----------\r\n ");
EEPROM_WaitForWriteEnd(); //д
EEPROM_Read(0x00, ReadData, 255);
for(i=0; i<256; i++)
{
printf("0x%02x ", ReadData[i]);
if(i%16==15)
{
printf("\r\n ");
}
}
while(1)
{
times++;
if(times%50000==0)
{
LED1=!LED1;
delay_ms(300);
}
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: elovegoo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/10 10:20:41 by elovegoo #+# #+# */
/* Updated: 2021/02/23 16:27:20 by elovegoo ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo_two.h"
size_t ft_gettime(void)
{
t_time tm;
gettimeofday(&tm, NULL);
return ((size_t)tm.tv_sec * 1000 + (size_t)tm.tv_usec / 1000);
}
void ft_sleep(size_t time)
{
size_t start;
size_t now_time;
start = ft_gettime();
while (1)
{
now_time = ft_gettime();
if (now_time - start >= time)
break ;
usleep(100);
}
}
void print_error(char *str)
{
printf("%s\n", str);
exit(EXIT_FAILURE);
}
int ft_atoi(char *str)
{
int ret;
int i;
ret = 0;
i = 0;
if (str[i] == '-' || str[i] == '+' || str[i] < '0' || str[i] > '9')
return (-1);
while (str[i] >= '0' && str[i] <= '9' && str[i])
{
ret = ret * 10 + (str[i] - '0');
i++;
}
if (str[i] != '\0')
return (-1);
return (ret);
}
|
C
|
#ifndef TESTVECTEUR_H
#define TESTVECTEUR_H
#include "cpptest.h"
#include "../src/vecteur.h"
/**
*@brief TestVecteur
* La classe de tests sur les vecteurs.
*/
CPPTEST(TestVecteur)
Vecteur vUn(1,1);
Vecteur vZero(0,0);
TESTCASE(multi1,{
Equals(1*vUn, vUn);
});
TESTCASE(multi0,{
Equals(0*vUn,vZero);
});
TESTCASE(constructeurPoints,{
Equals(vUn,Vecteur(Vecteur(0,0),Vecteur(1,1)));
});
TESTCASE(produitScalaire,{
Equals(Vecteur(5,-2) * Vecteur(7,-6), 47);
});
TESTCASE(norme,{
Equals(round(Vecteur(-2,5).norme()*100)/100,5.39);
});
ENDTEST
#endif // TESTVECTEUR_H
|
C
|
#include<stdio.h>
int main()
{ int n1,n2,temp;
printf("Enter Number 1 :");
scanf("%d",&n1);
printf("Enter Number 2 :");
scanf("%d",&n2);
temp = n1;
n1 = n2;
n2 = temp;
// Without Use Of Temp Variable
// n1 = n1 + n2;
// n2 = n1 - n2;
// n1 = n1 - n2;
printf("\nThe Number1 and Number2 after swaping is %d and %d",n1,n2);
return 0;
}
|
C
|
/*
** my_strupcase.c for my_strupcase.c in /home/kiwi/my_lib
**
** Made by Kiwi
** Login <[email protected]>
**
** Started on Tue Jan 3 10:13:35 2017 Kiwi
** Last update Wed Jan 11 14:51:31 2017 Kiwi
*/
char *my_strupcase(char *str)
{
int i;
i = 0;
while (str[i])
{
if (str[i] >= 'a' && str[i] <= 'z')
{
str[i] = str[i] - 32;
}
i++;
}
return (str);
}
|
C
|
#include <assert.h>
int
square_of(int x)
{
return x * x;
}
int cube_of(int x)
{
return x * x * x;
}
int
average(int a, int b, int c)
{
return (a + b + c) / 3;
}
int
calculate_with(int a)
{
return average(a, square_of(a), cube_of(a));
}
int main (int argc, char* argv[]) {
assert(calculate_with(10) == 370);
return 0;
}
|
C
|
/*
Date : 2-1-2021
Aim : chart
Source : ansi c e4.4
*/
#include <stdio.h>
void main()
{
float n1, n2, n3, n4;
int i, j, k;
printf("Enter four number between 0.0 and 20.0 : ");
scanf("%f%f%f%f", &n1, &n2, &n3, &n4);
//for(i = 0; i < 4; i++)
//{
printf("\n");
for(j = 0; j < 3; j++)
{
for(k = 0; k < (int)(n1+0.5f); k++)
{
printf("*");
}
if(j==1)
printf(" %.2f", n1);
printf("\n");
}
printf("\n");
for(j = 0; j < 3; j++)
{
for(k = 0; k < (int)(n2+0.5f); k++)
{
printf("*");
}
if(j==1)
printf(" %.2f", n2);
printf("\n");
}
printf("\n");
for(j = 0; j < 3; j++)
{
for(k = 0; k < (int)(n3+0.5f); k++)
{
printf("*");
}
if(j==1)
printf(" %.2f", n3);
printf("\n");
}
printf("\n");
for(j = 0; j < 3; j++)
{
for(k = 0; k < (int)(n4+0.5f); k++)
{
printf("*");
}
if(j==1)
printf(" %.2f", n4);
printf("\n");
}
//}
}
|
C
|
#include<stdio.h>
//指向函数的指针变量没有指针的++ --
//函数指针中的形参可有可无
/*
int Find_Max(int a,int b)
{
return a > b ? a : b;
}
int main(int argc,char* argv[])
{
int num1,num2,num3;
int (*P)(int,int);
P = Find_Max;
scanf("%d%d",&num1,&num2);
num3 = (*P)(num1,num2);
printf("num1 = %d,num2 = %d,num3 = %d\n",num1,num2,num3);
return 0;
}
#include<stdio.h>
void FileFunc()
{
printf("FileFunc\n");
}
void EditFunc()
{
printf("EditFunc\n");
}
int main()
{
typedef void(*funcp)();
funcp pfun=FileFunc;
pfun();
pfun=EditFunc;
pfun();
return 0;
}
*/
#include<stdio.h>
void Print_Message1(int a,int b)
{
printf("num1 = %d,num2 = %d\n",a,b);
}
void Print_Message2(int a,int b)
{
printf("数1 = %d,数2 = %d\n",a,b);
}
void Print_Message3(int a,int b)
{
printf("你好啊\n");
}
int main()
{
void (*p[3])(int,int);
p[1] = Print_Message1;
p[2] = Print_Message2;
(*p[1])(1,2);
(*p[2])(2112,221);
return 0;
}
|
C
|
#include <Python.h>
#include <numpy/arrayobject.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
PyDoc_STRVAR(popdrop__doc__, "popdrop(n_particles, box_edge_length, particle_radius, droplet_radius, random_seed=None)\n\nDrOP algorithm\n\nPopulate box with particles at non-overlapping locations and cut out spherical droplet.");
static PyObject *popdrop(PyObject *self, PyObject *args, PyObject *kwargs)
{
int n_particles;
double box_edge_length, particle_radius, droplet_radius;
static char *kwlist[] = {"n_particles", "box_edge_length", "particle_radius", "droplet_radius", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iddd", kwlist, &n_particles, &box_edge_length, &particle_radius, &droplet_radius)) {
return NULL;
}
if (box_edge_length <= 0.) {
PyErr_SetString(PyExc_ValueError, "Box edge length must be > 0.");
return NULL;
}
if (particle_radius <= 0.) {
PyErr_SetString(PyExc_ValueError, "Particle radius must be > 0.");
return NULL;
}
if (droplet_radius <= 0.) {
PyErr_SetString(PyExc_ValueError, "Droplet radius must be > 0.");
return NULL;
}
if (droplet_radius >= (box_edge_length/2.)) {
PyErr_SetString(PyExc_ValueError, "Droplet radius must be smaller than half the box edge length.");
return NULL;
}
if (droplet_radius <= particle_radius) {
PyErr_SetString(PyExc_ValueError, "Particle radius must be smaller than droplet radius.");
return NULL;
}
double * pos = (double *) malloc(sizeof(double) * n_particles * 3);
double * temp = (double *) malloc(sizeof(double) * n_particles * 3);
int i;
int n_box;
int n_droplet;
int overlap;
int try = 0;
int max_try = INT_MAX;
double x,y,z,dx,dy,dz,d_sq;
double particle_radius_sq;
double droplet_radius_sq;
// setup unbuffered urandom
FILE * urandom = fopen ("/dev/urandom", "r");
setvbuf (urandom, NULL, _IONBF, 0); // turn off buffering
// setup state buffer
unsigned short randstate[3];
// fgetc() returns a `char`, we need to fill a `short`
randstate[0] = (fgetc (urandom) << 8) | fgetc (urandom);
randstate[1] = (fgetc (urandom) << 8) | fgetc (urandom);
randstate[2] = (fgetc (urandom) << 8) | fgetc (urandom);
// cleanup urandom
fclose (urandom);
printf("n_particles = %i; box_edge_length = %e; particle_radius = %e; droplet_radius = %e\n", n_particles, box_edge_length, particle_radius, droplet_radius);
// 1) Place spherical particles at random positions in box. Do not allow overlap
// (Allow spheres to be partially outside of the box!)
n_box = 0;
particle_radius_sq = (particle_radius / box_edge_length)*(particle_radius / box_edge_length);
while ((n_box < n_particles) && (try < max_try)) {
//x = (double) rand() / (RAND_MAX+1.);
//y = (double) rand() / (RAND_MAX+1.);
//z = (double) rand() / (RAND_MAX+1.);
x = erand48(randstate);
y = erand48(randstate);
z = erand48(randstate);
overlap = 0;
// Check if position overlaps with any particle in box
for (i=0; i<n_box; i++) {
dx = x-pos[i*3+0];
dy = y-pos[i*3+1];
dz = z-pos[i*3+2];
d_sq = dx*dx + dy*dy + dz*dz;
if (d_sq < particle_radius_sq) {
overlap = 1;
}
}
// Assign particle position if no overlap found
if (overlap == 0) {
try = 0;
pos[n_box*3+0] = x;
pos[n_box*3+1] = y;
pos[n_box*3+2] = z;
n_box++;
} else {
try++;
}
}
if (try == max_try) {
PyErr_SetString(PyExc_ValueError, "Reached limit of tries for placing particles into the box. Too high particle density?");
return NULL;
}
// 2) Select spherical volume (droplet) from the box and count the particles that live in it
// (Allow particles to be partially outside of the droplet!)
n_droplet = 0;
droplet_radius_sq = (droplet_radius / box_edge_length)*(droplet_radius / box_edge_length);
for (i=0; i<n_particles; i++) {
x = pos[i*3+0];
y = pos[i*3+1];
z = pos[i*3+2];
// Check if particle entirely in droplet
dx = 0.5-x;
dy = 0.5-y;
dz = 0.5-z;
d_sq = dx*dx + dy*dy + dz*dz;
if (d_sq < droplet_radius_sq) {
temp[n_droplet*3+0] = x;
temp[n_droplet*3+1] = y;
temp[n_droplet*3+2] = z;
n_droplet++;
}
}
// Alloc python numpy array for output
int droplet_dim[] = {n_droplet, 3};
PyObject *droplet_array = (PyObject *)PyArray_FromDims(2, droplet_dim, NPY_FLOAT64);
double *droplet = PyArray_DATA(droplet_array);
for (i=0; i<(n_droplet*3); i++) {
droplet[i] = temp[i];
}
free(pos);
free(temp);
return droplet_array;
}
static PyMethodDef PopdropMethods[] = {
{"popdrop", (PyCFunction)popdrop, METH_VARARGS|METH_KEYWORDS, popdrop__doc__},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC initpopdrop(void)
{
import_array();
PyObject *m = Py_InitModule3("popdrop", PopdropMethods, "Random placement of particles into spherical volume");
if (m == NULL)
return;
}
|
C
|
// File name: ExtremeC_examples_chapter15_3.c
// Description: Demonstrate how to use a shared memory and a shared
// mutex to cancel a number of processes in progress.
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h> // For using pthread_mutex_* functions
typedef uint16_t bool_t;
#define TRUE 1
#define FALSE 0
#define MUTEX_SHM_NAME "mutex0"
#define SHM_NAME "shm0"
// Shared file descriptor used to refer to the shared memory object
// containing the cancel flag
int cancel_flag_shm_fd = -1;
// A flag which indicates whether the current process owns the shared
// memory object
bool_t cancel_flag_shm_owner = FALSE;
// Shared file descriptor used to refer to the mutex's shared memory object
int mutex_shm_fd = -1;
// The shared mutex
pthread_mutex_t* mutex = NULL;
// A flag which indicates whether the current process owns the shared
// memory object
bool_t mutex_owner = FALSE;
// The pointer to the cancel flag stored in the shared memory
bool_t* cancel_flag = NULL;
void init_shared_resource() {
// Open the shared memory object
cancel_flag_shm_fd = shm_open(SHM_NAME, O_RDWR, 0600);
if (cancel_flag_shm_fd >= 0) {
cancel_flag_shm_owner = FALSE;
fprintf(stdout, "The shared memory object is opened.\n");
} else if (errno == ENOENT) {
fprintf(stderr, "WARN: The shared memory object doesn't exist.\n");
fprintf(stdout, "Creating the shared memory object ...\n");
cancel_flag_shm_fd = shm_open(SHM_NAME, O_CREAT | O_EXCL | O_RDWR, 0600);
if (cancel_flag_shm_fd >= 0) {
cancel_flag_shm_owner = TRUE;
fprintf(stdout, "The shared memory object is created.\n");
} else {
fprintf(stderr, "ERROR: Failed to create shared memory: %s\n",
strerror(errno));
exit(1);
}
} else {
fprintf(stderr, "ERROR: Failed to create shared memory: %s\n",
strerror(errno));
exit(1);
}
if (cancel_flag_shm_owner) {
// Allocate and truncate the shared memory region
if (ftruncate(cancel_flag_shm_fd, sizeof(bool_t)) < 0) {
fprintf(stderr, "ERROR: Truncation failed: %s\n", strerror(errno));
exit(1);
}
fprintf(stdout, "The memory region is truncated.\n");
}
// Map the shared memory and initialize the cancel flag
void* map = mmap(0, sizeof(bool_t), PROT_WRITE, MAP_SHARED,
cancel_flag_shm_fd, 0);
if (map == MAP_FAILED) {
fprintf(stderr, "ERROR: Mapping failed: %s\n", strerror(errno));
exit(1);
}
cancel_flag = (bool_t*)map;
if (cancel_flag_shm_owner) {
*cancel_flag = FALSE;
}
}
void shutdown_shared_resource() {
if (munmap(cancel_flag, sizeof(bool_t)) < 0) {
fprintf(stderr, "ERROR: Unmapping failed: %s\n", strerror(errno));
exit(1);
}
if (close(cancel_flag_shm_fd) < 0) {
fprintf(stderr, "ERROR: Closing the shared memory fd filed: %s\n",
strerror(errno));
exit(1);
}
if (cancel_flag_shm_owner) {
sleep(1);
if (shm_unlink(SHM_NAME) < 0) {
fprintf(stderr, "ERROR: Unlinking the shared memory failed: %s\n",
strerror(errno));
exit(1);
}
}
}
void init_control_mechanism() {
// Open the mutex shared memory
mutex_shm_fd = shm_open(MUTEX_SHM_NAME, O_RDWR, 0600);
if (mutex_shm_fd >= 0) {
// The mutex's shared object exists and I'm now the owner.
mutex_owner = FALSE;
fprintf(stdout, "The mutex's shared memory object is opened.\n");
} else if (errno == ENOENT) {
fprintf(stderr, "WARN: Mutex's shared memory object doesn't exist.\n");
fprintf(stdout, "Creating the mutex's shared memory object ...\n");
mutex_shm_fd = shm_open(MUTEX_SHM_NAME, O_CREAT | O_EXCL | O_RDWR, 0600);
if (mutex_shm_fd >= 0) {
mutex_owner = TRUE;
fprintf(stdout, "The mutex's shared memory object is created.\n");
} else {
fprintf(stderr, "ERROR: Failed to create mutex's shared memory: %s\n",
strerror(errno));
exit(1);
}
} else {
fprintf(stderr, "ERROR: Failed to create mutex's shared memory: %s\n",
strerror(errno));
exit(1);
}
if (mutex_owner) {
// Allocate and truncate the mutex's shared memory region
if (ftruncate(mutex_shm_fd, sizeof(pthread_mutex_t)) < 0) {
fprintf(stderr, "ERROR: Truncation of the mutex failed: %s\n",
strerror(errno));
exit(1);
}
}
// Map the mutex's shared memory
void* map = mmap(0, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE,
MAP_SHARED, mutex_shm_fd, 0);
if (map == MAP_FAILED) {
fprintf(stderr, "ERROR: Mapping failed: %s\n", strerror(errno));
exit(1);
}
mutex = (pthread_mutex_t*)map;
// Initialize the mutex object
pthread_mutexattr_t attr;
if (pthread_mutexattr_init(&attr)) {
fprintf(stderr, "ERROR: Initializing mutex attributes failed: %s\n",
strerror(errno));
exit(1);
}
if (pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED)) {
fprintf(stderr, "ERROR: Setting the mutex attribute failed: %s\n",
strerror(errno));
exit(1);
}
if (pthread_mutex_init(mutex, &attr)) {
fprintf(stderr, "ERROR: Initializing the mutex failed: %s\n",
strerror(errno));
exit(1);
}
if (pthread_mutexattr_destroy(&attr)) {
fprintf(stderr, "ERROR: Destruction of mutex attributes failed: %s\n",
strerror(errno));
exit(1);
}
}
void shutdown_control_mechanism() {
sleep(1);
if (pthread_mutex_destroy(mutex)) {
fprintf(stderr, "WARN: Destruction of the mutex failed: %s\n",
strerror(errno));
}
if (munmap(mutex, sizeof(pthread_mutex_t)) < 0) {
fprintf(stderr, "ERROR: Unmapping the mutex failed: %s\n",
strerror(errno));
exit(1);
}
if (close(mutex_shm_fd) < 0) {
fprintf(stderr, "ERROR: Closing the mutex failed: %s\n",
strerror(errno));
exit(1);
}
if (mutex_owner) {
sleep(1);
if (shm_unlink(MUTEX_SHM_NAME) < 0) {
fprintf(stderr, "ERROR: Unlinking the mutex failed: %s\n",
strerror(errno));
exit(1);
}
}
}
bool_t is_canceled() {
pthread_mutex_lock(mutex);
bool_t temp = *cancel_flag;
pthread_mutex_unlock(mutex);
return temp;
}
void cancel() {
pthread_mutex_lock(mutex);
*cancel_flag = TRUE;
pthread_mutex_unlock(mutex);
}
void sigint_handler(int signo) {
fprintf(stdout, "\nHandling INT signal: %d ...\n", signo);
cancel();
}
int main(int argc, char** argv) {
signal(SIGINT, sigint_handler);
// Parent process needs to initialize the shared resource
init_shared_resource();
// Parent process needs to initialize the control mechanism
init_control_mechanism();
while(!is_canceled()) {
fprintf(stdout, "Working ...\n");
sleep(1);
}
fprintf(stdout, "Cancel signal is received.\n");
shutdown_shared_resource();
shutdown_control_mechanism();
return 0;
}
|
C
|
/*!***************************************************************************
* Mikroprosessorsystemer *
* Labving reaksjonstidsmler *
* NTNU Insitutt for elektrofag og fornybar energi *
* Rolf Kristian Snilsberg *
* Device: ATmega328P in Xplained mini *
*****************************************************************************
*/
/*!
The application is meant to be run on ATmega328P in Xplained mini or Arduino
UNOwith 16MHz system clock. It assumes a button is connected to input capture 1
i.e. PB0, one led to PB5 (or more of port B) and usart0 to a terminal.
The application waits for a low level on PINB0 (button pressed to start).
It will then wait a pseudo random time before outputting high on PORTB5 and
(thus turning on or all leds) and starting time measurement. The button
shall then be pressed again as soon as possible. The reaction time (in ms) from
the leds turn on until the button is pressed is measured and output on USART in
ASCII format. The communication format is 9600 baud, 8 data bits, 1 stop bit
and no parity (8N1).
***/
// Includes
#include "reaction_time.h"
#include "timer_routines.h"
#include "usart_routines.h"
// Main.
int main (void)
{
uint16_t reaction_time_ms;
char init_string[] = "\r\nPress button to start...";
char started_string[] = {"Started!\r\n"};
char reaction_time_string[] = {"1234ms \r\n"}; // initialized to 4 digit value
char too_slow_string[] = {"Too slow!\r\n"};
char cheater_string[] = {"Cheater!\r\n"};
USART_TX_Init(BAUD_VALUE);
DDRB = (1<<DDB5); // PB5 output.
PORTB = (0<<PORTB5) | (1<<PORTB0); // PB5 high, i.e. led off, pull-up on PB0 enabled
Timer1_Init_Capture();
do {
USART_Transmit_String(init_string);
// Wait for key press and use debouncing.
do {} while ( PINB & (1 << PINB0) ); // Wait for PINB0 to be pushed.
_delay_ms(10);
do {} while ( !(PINB & (1 << PINB0)) ); // Wait for PINB0 to be released.
USART_Transmit_String(started_string);
if(wait_random_time()) {
reaction_time_ms = measure_reaction_time();
/* Convert reaction time to ascii value and insert it into string. It
divides modulo 10 thus giving the remainder */
if (reaction_time_ms != 0 ) {
int8_t count;
for (count = 3 ; count >= 0 ; count--) {
reaction_time_string[count] = reaction_time_ms%10 + '0';
reaction_time_ms /= 10;
}
USART_Transmit_String(reaction_time_string);
} else {
USART_Transmit_String(too_slow_string);
}
} else {
USART_Transmit_String(cheater_string);
}
_delay_ms(1000); // Delay to avoid starting new measurement prematurely
} while (1);
}
|
C
|
#include "str.h"
#include "err.h"
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <error.h>
#include <stdlib.h>
#include <string.h>
char* stringDelete(char *str, const char *pat) {
char *strPtr = NULL;
while (NULL != (strPtr = strstr(str, pat))) {
memmove(strPtr, strPtr+strlen(pat), strlen(strPtr+strlen(pat))+1);
}
return str;
}
char* stringReplace(char *str, const char *pat, const char *rep) {
size_t patLen = strlen(pat);
size_t repLen = strlen(rep);
assert(repLen <= patLen);
char *strPtr = str;
while (NULL != (strPtr = strstr(strPtr, pat))) {
memcpy(strPtr, rep, repLen);
strPtr += repLen;
if (patLen > repLen) memmove(strPtr, strPtr+(patLen-repLen), strlen(strPtr+(patLen-repLen))+1);
}
return str;
}
char* stringReplaceNew(const char *str, const char *pat, const char *rep) {
const char *strPtr = str;
size_t hits = 0;
while (NULL != (strPtr = strstr(strPtr, pat))) {
++hits;
strPtr += strlen(pat);
}
char *res = calloc(strlen(str)-hits*strlen(pat)+hits*strlen(rep)+1, sizeof(*res));
if (NULL == res) error_at_line(EXIT_FAILURE, errno, __FILE__, __LINE__, "%s", errorGetMessage(ERROR_STRING_REPLACE_NEW));
const char *strPrevPtr;
strPtr = str;
char *resPtr = res;
while (NULL != (strPrevPtr = strPtr, strPtr = strstr(strPtr, pat))) {
strncpy(resPtr, strPrevPtr, strPtr-strPrevPtr);
resPtr += strPtr-strPrevPtr;
strcpy(resPtr, rep);
resPtr += strlen(rep);
strPtr += strlen(pat);
}
strcpy(resPtr, strPrevPtr);
return res;
}
char* stringTrim(char *str) {
char *strPtr = str;
while ('\0' != *strPtr) {
if (isspace(*strPtr)) memmove(strPtr, strPtr+1, strlen(strPtr+1)+1);
else ++strPtr;
}
return str;
}
|
C
|
#include "minishell.h"
int count_separator(t_shell sh)
{
t_token *token;
int i;
i = 0;
while (sh.tokens)
{
token = sh.tokens->content;
if (token->type == SEPARATOR)
i++;
sh.tokens = sh.tokens->next;
}
return (i);
}
int ft_count_exec(t_shell sh)
{
t_token *token;
int i;
i = 0;
while (sh.tokens)
{
token = sh.tokens->content;
if (token->type == EXECUTABLE)
i++;
sh.tokens = sh.tokens->next;
}
return (i);
}
void ft_brw_token(t_shell *sh, int *nb_sep)
{
t_token *token;
if (sh->tokens)
token = sh->tokens->content;
while (sh->tokens && token->type != SEPARATOR)
{
sh->tokens = sh->tokens->next;
if (sh->tokens)
token = sh->tokens->content;
else
*nb_sep = 0;
}
}
t_tree *fill_tree(t_shell *sh)
{
t_tree *root;
t_tree *begin;
int nb_sep;
t_list *tmp_token;
tmp_token = sh->tokens;
root = ft_tr_new(NULL, 5, 0);
begin = root;
nb_sep = ft_count_exec(*sh);
ft_fill_sep(*sh, root);
while (nb_sep--)
{
if (fill_cmd(root, &sh->tokens))
ft_brw_token(sh, &nb_sep);
if (root->branches)
if (root->branches->next)
root = root->branches->next->content;
}
sh->tokens = tmp_token;
return (begin);
}
int parser(t_shell *sh)
{
sh->ast = fill_tree(sh);
return (EXIT_SUCCESS);
}
|
C
|
#include<STC12C5A60S2.h>
#include<string.h>
#include<pwm.h>
#include<ds1302.h>
#include<lcd1602.h>
/*********************************************************************************************
뼶CPUʱ
ãDELAY_MS (?);
1~65535Ϊ0
ֵ
ռCPUʽʱֵͬĺʱ
עӦ1TƬʱi<600Ӧ12TƬʱi<125
/*********************************************************************************************/
void DELAY_MS (unsigned int a){
unsigned int i;
while( a-- != 0){
for(i = 0; i < 600; i++);
}
}
/*********************************************************************************************/
// ʾĴ
void print_xq(void){
switch (xq)
{
case 0x01:print(0x8b,"MON");
case 0x02:print(0x8b,"TUE");
case 0x03:print(0x8b,"WED");
case 0x04:print(0x8b,"THU");
case 0x05:print(0x8b,"FRI");
case 0x06:print(0x8b,"SAT");
case 0x07:print(0x8b,"SUN");
}
}
/*********************************************************************************************/
// ʾĿ ʱ䲿 ڵһȫʾʱ
/*********************************************************************************************/
void RealTime_Display(void){
read_clockS(); //ȶȡʱ
print(0x80,"20");
print2(0x82,yy/16+0x30);
print2(0x83,yy%16+0x30);
print(0x84,"-"); // ʾ
//
print2(0x85,mo/16+0x30);
print2(0x86,mo%16+0x30);
print(0x87,"-"); // ʾ
//
print2(0x88,dd/16+0x30);
print2(0x89,dd%16+0x30);
print_xq();
print2(0x40,hh/16+0x30);//Сʱ
print2(0x41,hh%16+0x30);
print(0x42,":"); // ʾcgramһģ""
//
print2(0x43,mm/16+0x30);//
print2(0x44,mm%16+0x30);
print(0x45,":"); // ʾcgramһģ"."
//
print2(0x46,ss/16+0x30);//
print2(0x47,ss%16+0x30);
//
}
/********************************************************************************************/
/********************************************************************************************/
//
/********************************************************************************************/
void main (void){
PWM_init();
LCM2402_Init();//LCM2402ʼ
BACK = 0; //б
PWM0_set(0xA0); //ƫѹ ԽĻԽ
Init_1302();
while(1){ //߳//
read_clockS();
RealTime_Display();
DELAY_MS(1000); //1ʱ
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "calculo_cenarios.h"
#include "ler_entrada.h"
vetor_de_parametros *create(Dados_entrada* pe) {
vetor_de_parametros *vetor_de_params = (vetor_de_parametros *)malloc(sizeof(vetor_de_parametros));
vetor_de_params->p = (Parametros_da_saida *)calloc(10, sizeof(Parametros_da_saida));
vetor_de_params->tamanho_atual = 1;
vetor_de_params->tamanho = 10;
vetor_de_params->p[0].S0 = pe->S0;
vetor_de_params->p[0].I0 = pe->I0;
vetor_de_params->p[0].R0 = pe->R0;
// convertendo de dias para horas
pe->percepcao = (pe->percepcao * 24);
vetor_de_params->p[0].tempo = 0;
return vetor_de_params;
}
vetor_de_parametros *reallocar_vetor(vetor_de_parametros *vetor_de_params) {
vetor_de_params->tamanho += 10;
vetor_de_params->p = realloc(vetor_de_params->p, (vetor_de_params->tamanho) * (sizeof(Parametros_da_saida)));
return vetor_de_params;
}
void liberar_vetor_de_parametros(vetor_de_parametros *vp) {
free(vp->p);
free(vp);
}
double calcular_b(double N_b, double T_b, double S_b0, double I_b0) {
return N_b / (T_b * S_b0 * I_b0);
}
double calcular_k(double m_k, double n_k, double T_k) {
return m_k / (n_k * T_k);
}
void calcular_mec_sir(vetor_de_parametros *vp, Dados_entrada *dados_entrada) {
double b, k;
b = calcular_b(dados_entrada->N_b, dados_entrada->T_b, dados_entrada->S_b0, dados_entrada->I_b0);
k = calcular_k(dados_entrada->m_k, dados_entrada->n_k, dados_entrada->T_k);
int tamanho_vp = (dados_entrada->dias * 24) / dados_entrada->h;
double h = dados_entrada->h;
int inicio = vp->p[0].tempo;
vp->p->M0 = dados_entrada->R0 * 0.02;
int entra = 1;
for(int i = 0; i < tamanho_vp; i++) {
if(vp->tamanho_atual >= vp->tamanho){
vp = reallocar_vetor(vp);
}
if(((int)dados_entrada->percepcao) == ((int)vp->p[i].tempo)) {
if(entra && dados_entrada->T_b2 != 0) {
b = calcular_b(dados_entrada->N_b, dados_entrada->T_b2, vp->p[i].S0, vp->p[i].I0);
entra = 0;
} else if(entra && dados_entrada->T_k2 != 0) {
k = calcular_k(dados_entrada->m_k, dados_entrada->n_k, dados_entrada->T_k2);
entra = 0;
}
}
vp->p[i+1].S0 = vp->p[i].S0 - h * (b * vp->p[i].S0 * vp->p[i].I0);
vp->p[i+1].I0 = vp->p[i].I0 + (h * (b * vp->p[i].S0 * vp->p[i].I0 - k * vp->p[i].I0));
vp->p[i+1].R0 = vp->p[i].R0 + h * k * vp->p[i].I0;
vp->p[i+1].M0 = (vp->p[i].R0) * 0.02;
vp->p[i+1].tempo = vp->p[i].tempo + h;
vp->tamanho_atual++;
}
}
|
C
|
#define ENDSTRING '\0'
int strlen(char *string){
int len=0;
while(string[len]!=ENDSTRING)
len++;
return len;
}
|
C
|
//
// main.c
// 02AddTwoNumbers
//
// Created by apple on 16/11/14.
// Copyright © 2016年 fht. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *result = NULL;
struct ListNode *temp = malloc(sizeof(struct ListNode));
struct ListNode *p = l1;
struct ListNode *q = l2;
int carry = 0;
while(p !=NULL || q != NULL){
int pVal;
int qVal;
int sum;
pVal = p!=NULL?p->val:0;
qVal = q!=NULL?q->val:0;
sum = pVal+qVal+carry;
carry = sum/10;
sum = sum%10;
struct ListNode *tempResult = malloc(sizeof(struct ListNode));
tempResult->val = sum;
tempResult->next = NULL;
if (result == NULL) {
result = tempResult;
temp = result;
}else{
temp->next = tempResult;
temp = tempResult;
}
p = p->next;
q = q->next;
}
free(temp);
return result;
}
int main(int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
return 0;
}
|
C
|
// Cezary Stajszczyk 317354
#include "traceroute.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <errno.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
static inline uint16_t seq_num(int ttl, int i) {
return (ttl << 2) | i;
}
/* funkcja z wykładu */
u_int16_t compute_icmp_checksum(const void *buff, int length) {
u_int32_t sum;
const u_int16_t* ptr = buff;
assert (length % 2 == 0);
for (sum = 0; length > 0; length -= 2)
sum += *ptr++;
sum = (sum >> 16) + (sum & 0xffff);
return (u_int16_t)(~(sum + (sum >> 16)));
}
void create_packet(struct icmphdr* packet, uint16_t sequential) {
assert(packet != NULL);
packet->type = ICMP_ECHO;
packet->code = 0;
packet->un.echo.id = getpid();
packet->un.echo.sequence = sequential;
packet->checksum = 0; // trzeba najpierw wyzerować, żeby dobrze policzyło checksum
packet->checksum = compute_icmp_checksum(packet, sizeof(struct icmphdr));
}
bool recv_response(int socket_fd, int ttl, const char* address) {
uint8_t responses = 0;
struct timeval time;
time.tv_sec = 1;
time.tv_usec = 0;
responders_t responders[3] = {0};
printf("%d. ", ttl);
while (responses < 3) {
fd_set descriptors;
FD_ZERO(&descriptors);
FD_SET(socket_fd, &descriptors);
int ready = select(socket_fd+1, &descriptors, NULL, NULL, &time);
if (ready < 0) {
fprintf(stderr, "select() error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if (ready == TIMEOUT) {
break;
}
struct sockaddr_in sender;
socklen_t sender_len = sizeof(sender);
u_int8_t buffer[IP_MAXPACKET];
ssize_t packet_len = recvfrom(socket_fd,
buffer, IP_MAXPACKET,
0,
(struct sockaddr*)&sender,
&sender_len);
if (packet_len == -1) {
fprintf(stderr, "recvfrom() error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
struct iphdr* ip_header = (struct iphdr*)buffer;
ssize_t ip_header_size = 4 * ip_header->ihl;
struct icmphdr* icmp_header = (struct icmphdr*)(buffer+ip_header_size);
int id = icmp_header->un.echo.id;
int sequential_number = icmp_header->un.echo.sequence;
if (icmp_header->type == ICMP_TIME_EXCEEDED) {
void *original_packet = (uint8_t*)icmp_header + sizeof(struct icmphdr);
struct iphdr* org_ip_header = (struct iphdr*)original_packet;
ssize_t org_ip_header_size = 4 * org_ip_header->ihl;
struct icmphdr* org_icmp_header = (struct icmphdr*)((uint8_t*)original_packet + org_ip_header_size);
int org_id = org_icmp_header->un.echo.id;
int org_sequential_number = org_icmp_header->un.echo.sequence;
if (org_id != getpid() || org_sequential_number>>2 != ttl) {
continue;
}
} else if (icmp_header->type == ICMP_ECHOREPLY) {
if (id != getpid() || sequential_number>>2 != ttl) {
continue;
}
} else {
continue;
}
responders[responses].ip = malloc(4);
const char* sender_ip = inet_ntop(AF_INET,
&sender.sin_addr,
responders[responses].ip,
20);
if (sender_ip == NULL) {
perror("inet_ntop");
exit(EXIT_FAILURE);
}
responders[responses].time.tv_usec = 1000000 - time.tv_usec;
++responses;
}
uint64_t time_total = 0;
bool dest_responded = false;
for (int i = 0; i < responses; ++i) {
bool print_addr = true;
time_total += responders[i].time.tv_usec;
for (int j = 0; j < i; ++j) {
if (strcmp(responders[i].ip, responders[j].ip) == 0) {
print_addr = false;
break;
}
}
if (print_addr) {
printf("%s ", responders[i].ip);
}
if (strcmp(responders[i].ip, address) == 0) {
dest_responded = true;
}
}
if (responses) {
uint64_t average = time_total / 1000 / responses;
printf("%ldms ", average);
}
if (responses == 0) {
printf("* ");
} else if (responses < 3) {
printf("??? ");
}
printf("\n");
return dest_responded;
}
void traceroute(const char* address, int socket_fd) {
struct sockaddr addr = {0};
addr.sa_family = AF_INET;
if (inet_pton(AF_INET, address, &addr.sa_data[2]) != 1) {
fprintf(stderr, "inet_pton() error: %s is not valid ip address; %s\n", address, strerror(errno));
exit(EXIT_FAILURE);
}
for (int ttl = 1; ttl <= 32; ++ttl) {
for (uint8_t i = 0; i < 3; ++i) {
struct icmphdr packet;
create_packet(&packet, seq_num(ttl, i));
if (setsockopt(socket_fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(int)) == -1) {
fprintf(stderr, "setsockopt() error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
ssize_t bytes = sendto(socket_fd,
&packet,
sizeof(struct icmphdr),
0,
&addr,
sizeof(struct sockaddr));
if (bytes == -1) {
fprintf(stderr, "sendto() error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if (bytes != sizeof(packet)) {
fprintf(stderr, "sendto() error: sent %ld out od %ld bytes\n", bytes, sizeof(packet));
exit(EXIT_FAILURE);
}
}
/* receive packets */
if (recv_response(socket_fd, ttl, address)) {
break;
}
}
}
|
C
|
/*Считать с клавиатуры целое основание и целый неотрицательный показатель.
Вывести через пробел степени числа основания от нулевой до заданной.*/
#include <stdio.h>
int main() {
int base, power;
int number = 1;
scanf("%d %d", &base, &power);
for ( int i = 0; i < power; i++ ) {
printf("%d ", number);
number *= base;
}
printf("%d\n", number);
return 0;
}
|
C
|
int addNewStudent(void)
{
//repeatable1
char buffer[MAXNAMELENGTH],
char ch = getchar();//does this get /\n?
int i = 0, subject, j;
struct Student *newStudent, *currentStudent = studentHead;
//repeatable1
newStudent = (struct Student *)malloc(sizeof(struct Student));
newStudent->subjects = 1;
newStudent->next = NULL;
//repeatable2
if (!isalpha(ch))
{
printf("The name can not be found, make sure you follow the correct search pattern\n");
return 1;
}
while (ch != '\n' && i < MAXNAMELENGTH - 1)
{
buffer[i] = ch;
ch = getchar();
i++;
}
if (i == MAXNAMELENGTH - 1 && ch != '\n')
{
printf("This name is too long for our current system\n");
return 1;
}
//repeatable2
else
{
//repeatable3
buffer[i] = '\0';
strcpy(newStudent->name, buffer);
j = 0;
while (1)
{
printf("Enter a subject: ");
ch = getchar();
if (!isalpha(ch))
{
printf("The name can not be found, make sure you follow the correct search pattern\n");
return 1;
}
i = 0;
while (ch != '\n' && i < MAXNAMELENGTH - 1)
{
buffer[i] = ch;
ch = getchar();
i++;
}
buffer[i] = '\0';
if (i == MAXNAMELENGTH - 1 && ch != '\n')
{
printf("This subject name is too long for our current system\n");
return 1;
}
//repeatable3
if (strcmp(buffer, "Done") == 0)
{
printf("Here\n");
break;
}
printf("What grade is the student attaining in this subject, A,B,C,D,E,F,U or X if this is not known? ");
ch = getchar();
getchar();
printf("%s\n", buffer);
subject = findOrAddSubjectCodeFromName(buffer);
newStudent->subjects = newStudent->subjects * subject;
newStudent->grades[j] = ch;
printf("%lu %s", newStudent->subjects, newStudent->grades);
j++;
}
printf("here\n");
newStudent->next = NULL;
//repeatble4
if (studentHead == NULL)
{
printf("here");
studentHead = newStudent;
return 0;
}
//repeatble4
//repeatableN
while (currentStudent->next != NULL)
{
currentStudent = currentStudent->next;
}
currentStudent->next = newStudent;
printf("Student added successfully!\n");
return 0;
//repeatableN
}
}
|
C
|
#include <stdio.h>
int main(void) {
int size;
scanf("%d",&size);
int arr[size],max = 0;
for(int i = 0; i < size; i++)
{
scanf("%d",&arr[i]);
if(arr[i > max])
max = arr[i];
}
printf("%d",max);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* threads.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jgainza- <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/05 14:15:15 by jgainza- #+# #+# */
/* Updated: 2021/11/08 13:41:20 by jgainza- ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/philo.h"
static int ft_meal_check(t_philo *philo)
{
int i;
i = -1;
while (++i < philo->info->num_philo)
if (philo->info->philo[i].meals < philo->info->time_must_eat)
return (0);
philo->info->stop = 1;
return (1);
}
static void *ft_philo(void *s)
{
t_philo *philo;
philo = s;
if (philo->info->num_philo != 1 && philo->n % 2 == 0)
usleep(1000 * philo->info->time_eat);
while (!philo->info->stop)
{
ft_eating(philo);
if ((philo->info->time_must_eat != -1 && ft_meal_check(philo))
|| philo->info->stop || philo->info->time_must_eat == philo->meals)
break ;
ft_sleeping(philo);
if (philo->info->stop)
break ;
ft_thinking(philo);
if (philo->info->stop)
break ;
}
return (NULL);
}
static void *ft_monitor_life(void *s)
{
t_philo *philo;
philo = s;
while (!philo->info->stop)
{
pthread_mutex_lock(&philo->protect);
if (ft_get_time() - philo->start >= philo->info->time_die)
{
ft_print_status(philo, 5);
philo->info->stop = 1;
pthread_mutex_unlock(&philo->protect);
break ;
}
pthread_mutex_unlock(&philo->protect);
usleep(100);
}
return (NULL);
}
int ft_dining(t_info *info)
{
int i;
info->base_time = ft_get_time();
i = -1;
while (++i < info->num_philo)
{
info->philo[i].start = ft_get_time();
if (pthread_create(&info->philo[i].philo_th, NULL, ft_philo,
&info->philo[i]) || pthread_create(&info->philo[i].monitor,
NULL, ft_monitor_life, &info->philo[i]))
return (ft_str_error("Failed to create a thread\n"));
}
i = -1;
while (++i < info->num_philo)
if (pthread_join(info->philo[i].philo_th, NULL)
|| pthread_join(info->philo[i].monitor, NULL))
return (ft_str_error("Failed to join a thread\n"));
return (0);
}
|
C
|
/*
** parse.c for zappy in /home/anthony/repository/zappy/parse.c
**
** Made by Anthony LECLERC
** Login <[email protected]>
**
** Started on lun. juin 19 23:17:29 2017 Anthony LECLERC
** Last update Fri Jun 30 11:54:58 2017 Hugo Baldassin
*/
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include "debug.h"
#include "arguments.h"
#include "serverinfo.h"
void print_arguments(t_servinfo const *infos)
{
size_t i;
i = 0;
fprintf(stdout, SLOG_FORMAT("PORT") "%hd\n", infos->port);
fprintf(stdout, SLOG_FORMAT("WIDTH") "%u\n", infos->width);
fprintf(stdout, SLOG_FORMAT("HEIGHT") "%u\n", infos->height);
fprintf(stdout, SLOG_FORMAT("FREQUENCY") "%zu\n", infos->freq);
fprintf(stdout, SLOG_FORMAT("P TEAM") "%u\n", infos->team_size);
fprintf(stdout, SLOG_FORMAT("NB TEAM") "%u\n", infos->nteam);
while (i < infos->nteam)
{
fprintf(stdout, SLOG_FORMAT("TEAM") "%s\n", infos->team_name[i]);
++i;
}
}
int parse_arguments(int ac, char **av, t_servinfo *infos)
{
assert(infos != NULL);
if (get_port_command(infos, ac, av) == 1)
return (1);
if (get_dimensions_command(infos, ac, av) == 1)
return (1);
if (get_freq_command(infos, ac, av) == 1)
return (1);
if (get_nbplayer_command(infos, ac, av) == 1)
return (1);
if (get_teams_command(infos, ac, av) == 1)
return (1);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "tree.h"
#include "mylib.h"
#include <string.h>
#define IS_BLACK(x) ((NULL == (x)) || (BLACK == (x)->colour))
#define IS_RED(x) ((NULL !=(x)) && (RED == (x)->colour))
struct treenode{
char *key;
tree left;
tree right;
int freq;
tree_t type;
rbt_colour colour;
};
/* Finds and returns the leftmost child.
* This can be used to find the successor
* by inputting the right subtree
* @param b the tree to be worked on
*
* @return the leftmost child
*/
tree get_left_most_child(tree b){
if (b->left == NULL){
return b;
}else{
return get_left_most_child(b->left);
}
}
/* Delete by key value. Input the tree and key value to be
* deleted and the subnode with that key value will be deleted
* and given root returned
*
* @param b the tree to be worked on
* @param str the key value to be deleted
*
* @return root
*/
tree tree_delete(tree b, char *str){
tree tmp;
if (tree_search(b, str) == 0){
return b; /* nothing to delete */
}else if(strcmp(b->key, str) < 0){
b->right = tree_delete(b->right, str);
return b;
}else if(strcmp(b->key, str) > 0){
b->left = tree_delete(b->left, str);
return b;
}else{
/* if current node is a leaf, free it */
if (b->left == NULL && b->right == NULL){
free(b->key);
free(b);
b = NULL;
}
/* if only one child, point to that child */
else if ((b->left==NULL&&b->right!=NULL)||
(b->left!=NULL&&b->right==NULL)){
free(b->key);
tmp = b;
if (b->left != NULL){
b = b->left;
}
else if (b->right != NULL){
b = b->right;
}
free(tmp);
}
/* if two children */
else{
tmp = get_left_most_child(b->right);
strcpy(b->key, tmp->key);
b->right = tree_delete(b->right, tmp->key);
}
}
return b;
}
/* Deletes every node, freeing them as it goes.
*
* @param b the tree to be worked on
*
* @return an empty tree
*/
tree tree_free(tree b){
if (b == NULL){
return NULL;
}else{
return tree_free(tree_delete(b, b->key));
}
}
/* An inorder traversal of the tree.
*
* @param b the tree to be worked on
*/
void tree_inorder(tree b, void f(char *str, int a)){
if (b != NULL){
tree_inorder(b->left, f);
f(b->key, b->freq);
tree_inorder(b->right, f);
}
}
/* A preorder traversal of the tree.
*
* @param b the tree to be worked on
*/
void tree_preorder(tree b, void f(char *str, int a)){
if (b != NULL){
f(b->key, b->freq);
tree_preorder(b->left, f);
tree_preorder(b->right, f);
}
}
/* Right-rotation moves branches from left to right.
*
* @param t current value of the tree
*
* @return new value of the tree
*/
tree right_rotate(tree t){
tree tmp = t;
t = t->left;
tmp->left = t->right;
t->right = tmp;
return t;
}
/* Left-rotation moves branches from right to left.
*
* @param t current value of the tree
*
* @return new value of the tree
*/
tree left_rotate(tree t){
tree tmp = t;
t = t->right;
tmp->right = t->left;
t->left = tmp;
return t;
}
/* Swap function.
*
* @param t current value of the tree
*
* @return new value of the tree
*/
tree swap(tree t){
t->colour = RED;
t->left->colour = BLACK;
t->right->colour = BLACK;
return t;
}
/* Tree fix function.
*
* @param t current value of the tree
*
* @return new value of the tree
*/
static tree tree_fix(tree t){
if(IS_RED(t->left) && IS_RED(t->left->left)){
if(IS_RED(t->right)){
swap(t);
}else if(IS_BLACK(t->right)){
/* right rotate root , colour new root (a) black,
* and new child(old root) red*/
t = right_rotate(t);
t->colour = BLACK;
t->right->colour = RED;/*old root*/
}
}else if(IS_RED(t->left) && IS_RED(t->left->right)){
if(IS_RED(t->right)){
swap(t);
}
else if(IS_BLACK(t->right)){
/* left rotate left child (a), right rotate root (r),
* colour new root (d) black and new child (R) red */
t->left = left_rotate(t->left);
t = right_rotate(t);
t->colour = BLACK;
t->right->colour = RED;/* old root */
}
}else if(IS_RED(t->right) && IS_RED(t->right->left)){
if(IS_RED(t->left)){
swap(t);
}else if(IS_BLACK(t->left)){
/* right rotate right child(b), left rotate root(r),
* colour new root (e) black and new child (r) red */
t->right = right_rotate(t->right);
t = left_rotate(t);
t->colour = BLACK;
t->left->colour = RED;/* old root */
}
}else if(IS_RED(t->right) && IS_RED(t->right->right)){
if(IS_RED(t->left)){
swap(t);
}
else if(IS_BLACK(t->left)){
/* left rotate root R, colour new root b black and new child R red */
t = left_rotate(t);
t->colour = BLACK;
t->left->colour = RED;/*old root*/
}
}
return t;
}
/* Makes the node black. This should be called on the root node after each
* insertion.
*
* @param t the node to turn black
*/
tree tree_make_black(tree t){
t->colour = BLACK;
return t;
}
/* Tree insert function. Allocates memory.
*
* @param b the current value of the tree.
* @param str pointer to array of char to be inserted
* @param t for emalloc
*
* @return new value of the tree
*/
tree tree_insert(tree b, char *str, tree_t t){
if (b == NULL){ /* empty tree, base case */
b = tree_new(t);
b->key = emalloc((strlen(str)+1) * sizeof b->key[0]);
strcpy(b->key, str);
b->freq = 1;
b->colour = RED;
return b;
}else if (strcmp(b->key, str) < 0){
b->right = tree_insert(b->right, str, t);
}else if (strcmp(b->key, str) > 0){
b->left = tree_insert(b->left, str, t);
}else{
/* we have a duplicated item, increase freq */
b->freq++;
}
if (b->type == RBT){
b = tree_fix(b);
}
return b;
}
/* Tree new function to empty the tree.
*
* @param t current value of the tree
*
* @result new value of the tree
*/
tree tree_new(tree_t t){
tree result = emalloc(sizeof *result);
result->left = NULL;
result->right = NULL;
result->key = NULL;
result->freq = 0;
result->type = t;
return result;
}
/* Tree search function traverses the tree.
*
* @param b the tree to be worked on
* @param str char pointer of value to be searched for
*/
int tree_search(tree b, char *str){
if (b == NULL){
return 0;
}else if (strcmp(str, b->key) == 0){
return 1;
}else if (strcmp(str, b->key) > 0){
return tree_search(b->right, str);
}else{
return tree_search(b->left, str);
}
}
/* Traverses the tree writing a DOT description about connections, and
* possibly colours, to the given output stream.
*
* @param t the tree to output a DOT description of
* @param out the stream to write the DOT output to
*/
static void tree_output_dot_aux(tree t, FILE *out) {
if(t->key != NULL) {
fprintf(out, "\"%s\"[label=\"{<f0>%s:%d|{<f1>|<f2>}}\"color=%s];\n",
t->key, t->key, t->freq,
(RBT == t->type && RED == t->colour) ? "red":"black");
}
if(t->left != NULL) {
tree_output_dot_aux(t->left, out);
fprintf(out, "\"%s\":f1 -> \"%s\":f0;\n", t->key, t->left->key);
}
if(t->right != NULL) {
tree_output_dot_aux(t->right, out);
fprintf(out, "\"%s\":f2 -> \"%s\":f0;\n", t->key, t->right->key);
}
}
/* Output a DOT description of this tree to the given output stream.
* DOT is a plain text graph description language (see www.graphviz.org).
* You can create a viewable graph with the command
*
* dot -Tpdf < graphfile.dot > graphfile.pdf
*
* You can also use png, ps, jpg, svg... instead of pdf
*
* @param t the tree to output the DOT description of
* @param out the stream to write the DOT description to
*/
void tree_output_dot(tree t, FILE *out) {
fprintf(out, "digraph tree {\nnode [shape = Mrecord, penwidth = 2];\n");
tree_output_dot_aux(t, out);
fprintf(out, "}\n");
}
/* Print key function prints to stdout.
*
* @param s char pointer
* @param f
*/
void tree_print_key(char *s, int f){
printf("%-5d%s\n",f, s);
}
|
C
|
#include<stdio.h>
int main(void)
{
int n,b,c,a;
char str1[5],str2[5],str3[5];
scanf("%d",&n);
printf("%d",n);
scanf("%d %d %d",&a,&b,&c);
printf(" \n %d %d %d",a,b,c);
scanf("%s %s %s",&str1,&str2,&str3);
printf("\n %s %s %s",str1,str2,str3);
for (int i=1; i<=100; i++)
{
if ((i%a) == 0)
printf(" %s\t",str1);
else if ((i%b) == 0)
printf(" %s\t",str2);
else if ((i%c) == 0)
printf(" %s\t",str3);
else
printf("%d\t",i);
}
return 0;
}
|
C
|
#include <stdio.h>
double valorAbsoluto(double x)
{
if (x >= 0.0) return x;
else return -(x);
}
int main(void)
{
double valor;
printf("Digite um número:\n");
scanf("%lf", &valor);
printf("%.2lf\n", valorAbsoluto(valor));
return 0;
}
|
C
|
#include "holberton.h"
/**
* more_numbers - Prints from 1 to 14, ten times.
*/
void more_numbers(void)
{
char num, i;
for (i = 0; i < 10; i++)
{
for (num = 0; num <= 14; num++)
{
if (num >= 10)
_putchar(num / 10 + '0');
_putchar(num % 10 + '0');
}
_putchar('\n');
}
}
|
C
|
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
/**
* Main
*/
int main(int argc, char **argv)
{
// Parse command line
DIR *dir;
struct dirent *ent;
struct stat fileStat;
// Open directory
if(argc < 2){
dir = opendir(".");
}
else{
dir = opendir(argv[1]);
}
if(dir == NULL){
printf("Could not open current directory %s\n", argv[1]);
return 0;
}
// Repeatly read and print entries
while ((ent = readdir(dir))!=NULL){
stat(ent->d_name, &fileStat);
printf("%10lld %s\n", fileStat.st_size, ent->d_name);
}
// Close
closedir(dir);
return 0;
}
|
C
|
/**
* @file gdt.h
* @author James T Oswald
* @brief This header library contains code for loading the Global Descriptor Table.
* @details For information on why we need a global descriptor table and how we set it up, see:
* <a href="https://wiki.osdev.org/LGDT">The OS dev GDT reffrence</a>,
* <a href="https://wiki.osdev.org/GDT_Tutorial">The OS dev GDT tutorial</a>,
* <a href="https://samypesse.gitbook.io/how-to-create-an-operating-system/chapter-6">This other tutorial</a>
* */
#ifndef gdt_header
#define gdt_header
#include<int.h>
/**
* @struct gdtDescriptor
* @brief A structre representing a gdt table descriptor to be passed to lgdt and be stored in the gdtr.
* @var gdtDescriptor::limit
* @brief the size of the GDT in bytes, minus 1
* @var gdtDescriptor::offset
* @brief the location of the GDT in memory, basically a pointer to it.
*/
struct gdtDescriptor{
u16 limit;
u32 offset;
} __attribute__((packed));
typedef struct gdtDescriptor gdtDescriptor;
/**
* @struct gdtEntry
* @brief An entry in the GDT
* @details entries are 8 bytes and contain information about memory segments.
* for some reason these segments are stored all scrablmed, for the details on whats in here see
* <a href="https://wiki.osdev.org/LGDT">https://wiki.osdev.org/LGDT</a>
* @var u16 gdtEntry::limit0_15
* @brief first 2 bytes of the limit (size of the segment)
* @var u16 gdtEntry::base0_15
* @brief first 2 bytes of the base (start address of the segment)
* @var u8 gdtEntry::base16_23
* @brief third byte of the base (start address of the segment)
* @var u8 gdtEntry::access
* @brief access flags for the segment, includes the priv level.
* @var u8 gdtEntry::limit16_19
* @brief final nibble of the limit (size of the segment)
* @var u8 gdtEntry::flags
* @brief even more flags for the segment, inclduing granularity and size
* @var u8 gdtEntry::base24_31
* @brief fourth byte of the base (start address of the segment)
*/
struct gdtEntry{
u16 limit0_15;
u16 base0_15;
u8 base16_23;
u8 access;
u8 limit16_19 : 4;
u8 flags : 4;
u8 base24_31;
} __attribute__((packed));
typedef struct gdtEntry gdtEntry;
/**
* @brief generates a new gdtEntry in memory at the provided address
* @param entry the address to write the gdtEntry to
* @param base the base address of the segment
* @param size the size of the segment
* @param access access flags
* @param flags other flags
*/
void newGdtEntry(gdtEntry* entry, u32 base, u32 size, u8 access, u8 flags){
entry->limit0_15 = (size & 0xffff);
entry->base0_15 = (base & 0xffff);
entry->base16_23 = (base & 0xff0000) >> 16;
entry->access = access;
entry->limit16_19 = (size & 0xf0000) >> 16;
entry->flags = (flags & 0xf);
entry->base24_31 = (base & 0xff000000) >> 24;
return entry;
}
/**
* @brief generates a new gdtDescriptor in memory at the provided address
* @param desc the address to write the gdtDescriptor to
* @param base the base address of the gdt
* @param size the TRUE size of the gdt
*/
void newGdtDescriptor(gdtDescriptor* desc, u32 base, u16 size){
desc->offset = base;
desc->limit = size - 1;
}
//This whole section should be fixed to have the globals be in the assembly
#define gdtSize 3 //!< the number of entries in the GDT
gdtDescriptor gdtDesc; //!< the memory storing the gdt descriptor to pass to lgdt
gdtEntry gdtRegistry[gdtSize]; //!< the memory storing the gdt itself
/**
* @brief The assembly proceduere to load the GDT.
* @details Depends on the globals gdtDesc and gdtRegistry to be set.
* Also reloads all segment registers
*/
extern void gdtLoad(); //from gdt.s
/**
* @brief sets up the OS's GDT
*/
void gdtInit(){
//to understand what all these random flags mean it is essentail to see GDT documentation
// https://wiki.osdev.org/LGDT
newGdtEntry(&gdtRegistry[0], 0, 0, 0, 0);
newGdtEntry(&gdtRegistry[1], 0, 0xffffffff, 0b10011010, 0b1100); //code segment, offset 0x8
newGdtEntry(&gdtRegistry[2], 0, 0xffffffff, 0b10010010, 0b1100); //data segment, offset 0x10
//These were recomended by the tutorial, for some reason the granulatity bit needs to be set?
//Without setting the granularity bit the longjump from gdtLoad fails.
//newGdtEntry(&gdtRegistry[1], 0, 0xffffffff, 0x9A, 0xd); //code segment, offset 0x8
//newGdtEntry(&gdtRegistry[2], 0, 0xffffffff, 0x92, 0xd); //data segment, offset 0x10
newGdtDescriptor(&gdtDesc, (u32)&gdtRegistry, sizeof(gdtRegistry));
gdtLoad(); //call the assembly method that actually loads the GDT in gtd.s
}
#endif
|
C
|
// seating arrangement
#include<stdio.h>
int main(){
int testcase,seat;
printf("number of testcases: ");
scanf("%d",&testcase);
for(int i=0;i<testcase;i++){
printf("seat number: ");
scanf("%d",&seat);
switch(seat%6){
case 0: printf("%d WS\n",seat+1);break;
case 1: printf("%d WS\n",seat+11);break;
case 2: printf("%d MS\n",seat+9);break;
case 3: printf("%d AS\n",seat+7);break;
case 4: printf("%d AS\n",seat+5);break;
case 5: printf("%d MS\n",seat+3);break;
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char** argv){
if(argc < 2){
exit(0);
}
int size;
for(int i = 1; i < argc; i++){
size = strlen(argv[i]);
printf("%c", argv[i][size - 1]);
}
printf("\n");
return 0;
}
|
C
|
/* Generates the Nth lexicographical permutation of
* the integers 1, 2, ... n
*
* Internally it first calculates the factoradic representation of N
* before the permutation is generated and returned.
*
* The returned array will have n elements and it is
* the responsibility of the caller to free it.
*
* Reference:
* https://en.wikipedia.org/wiki/Factorial_number_system
*/
#ifndef permn_h_
#define permn_h_h
#include <stdlib.h>
int * permn(size_t N, int n);
#endif
|
C
|
#include <pebble.h>
#include "window.h"
#include "loadscreen.h"
// Keys for AppMessage Dictionary
enum {
STATUS_KEY = 0,
MESSAGE = 1,
MODE = 2,
CURRENT = 3,
REMAIN = 4,
BATTERY = 5,
RECORDING = 6,
POWER = 7
};
static bool initialized = false;
static int mode = -1;
char* tupleStr(DictionaryIterator *received, int dict) {
Tuple *tuple;
tuple = dict_find(received, dict);
if(tuple) {
return tuple->value->cstring;
}
return "";
}
int tupleInt(DictionaryIterator *received, int dict) {
Tuple *tuple;
tuple = dict_find(received, dict);
if(tuple) {
return (int)tuple->value->uint32;
}
return -1;
}
// Called when a message is received from PebbleKitJS
static void in_received_handler(DictionaryIterator *received, void *context) {
bool ok = false;
int status = 0;
Tuple *tuple;
tuple = dict_find(received, STATUS_KEY);
if(tuple) {
status = (int)tuple->value->uint32;
//APP_LOG(APP_LOG_LEVEL_DEBUG, "Received Status: %d", (int)tuple->value->uint32);
}
if (status == 1) {
/*
tuple = dict_find(received, MESSAGE_KEY);
if(tuple) {
APP_LOG(APP_LOG_LEVEL_DEBUG, "Received Message: %s", tuple->value->cstring);
}*/
if (!initialized) {
initialized = true;
hide_loadscreen();
show_window();
}
if (tupleInt(received, RECORDING) == 1) {
vibes_double_pulse();
}
mode = tupleInt(received, MODE);
setMode(mode, tupleInt(received, RECORDING));
setBattery(tupleInt(received, BATTERY));
set_text(tupleStr(received, CURRENT), tupleStr(received, REMAIN));
}
else {
if (initialized) {
initialized = false;
hide_window();
show_loadscreen();
}
set_loadText(status);
}
}
// Called when an incoming message from PebbleKitJS is dropped
static void in_dropped_handler(AppMessageResult reason, void *context) {
}
// Called when PebbleKitJS does not acknowledge receipt of a message
static void out_failed_handler(DictionaryIterator *failed, AppMessageResult reason, void *context) {
}
static void init(void) {
show_loadscreen();
// Register AppMessage handlers
app_message_register_inbox_received(in_received_handler);
app_message_register_inbox_dropped(in_dropped_handler);
app_message_register_outbox_failed(out_failed_handler);
// Initialize AppMessage inbox and outbox buffers with a suitable size
const int inbox_size = 128;
const int outbox_size = 128;
app_message_open(inbox_size, outbox_size);
}
static void deinit(void) {
if (initialized)
hide_window();
else
hide_loadscreen();
app_message_deregister_callbacks();
}
int main(void) {
init();
app_event_loop();
deinit();
}
|
C
|
#include "binary_trees.h"
/**
* binary_tree_is_root - Check if @node is root of binary tree
*
* @node: Node to be checked
*
* Return: (1) If @node is the root of binary tree
* (0) All other cases
*/
int binary_tree_is_root(const binary_tree_t *node)
{
return (node && !node->parent);
}
|
C
|
#include <stdio.h>
#include <string.h>
// #include <math.h>
int main(int argc, char *argv[]) {
char truthTable[17];
char cur[5];
char gate[5];
int inputs;
int totalBits;
int truthTableLen;
// power function
int pow(int b, int e) {
int result=1;
int power = e;
while (e != 0) { result *= b; --e; }
return result;
}
// dec to binary char[]
void toBin(int value, int bitsCount, char* output) {
int i;
output[bitsCount] = '\0';
for (i = bitsCount - 1; i >= 0; --i, value >>= 1) {
output[i] = (value & 1) + '0';
}
}
// boolean functions
int and(int a, int b) { return (a&b);}
int or(int a, int b) { return (a|b);}
int xor(int a, int b) { return (a^b);}
// calculate bit
char calculateResult(char gate[],int bitsCount, char current[]) {
int result=current[0]-'0';
for(int i=1; i<bitsCount; i++){
if(strcmp(gate, "AND")==0) result = and(result,(int)(current[i]-'0'));
else if(strcmp(gate, "OR")==0) result = or(result,(int)(current[i]-'0'));
else if(strcmp(gate, "XOR")==0) result = xor(result,(int)(current[i]-'0'));
else if(strcmp(gate, "NAND")==0) result = !and(result,(int)(current[i]-'0'));
else if(strcmp(gate, "NOR")==0) result = !or(result,(int)(current[i]-'0'));
else if(strcmp(gate, "NXOR")==0) result = !xor(result,(int)(current[i]-'0'));
}
return result+'0';
}
printf("\nEnter gate name: ");
scanf("%s",&gate);
printf("\nEnter number of inputs: ");
scanf("%d",&inputs);
printf("\nTruth Table is:: ");
// printf("\n%d\n",!(1^0));
truthTableLen = pow(2,inputs);
for(int i=0;i<truthTableLen;i++){
toBin(i,inputs,cur);
// e.g. 0,0,0,1
truthTable[i] = calculateResult(gate,inputs,cur);
printf("%c",truthTable[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <time.h>
double factorial_with_ll(int number, int ll) // ll - lower limit
{
if (number < 2) return 1;
double product = 1;
for (double i = number; i > ll; --i)
{
product *= i;
}
return product;
}
double combinations(int n, int r)
{
if (n - r < r) r = n - r;
return factorial_with_ll(n, n - r) / factorial_with_ll(r, 1);
}
double permutations(int n, int r)
{
return factorial_with_ll(n, n - r);
}
double duration(clock_t start, clock_t end)
{
return (double)(end - start)/CLOCKS_PER_SEC;
}
void main()
{
int n, r;
scanf("%d %d", &n, &r);
clock_t start1, end1, start2, end2;
double duration_perm, duration_comb;
start1 = clock();
double noof_perms = permutations(n, r);
end1 = clock();
duration_perm = duration(start1, end1);
start2 = clock();
double noof_combs = combinations(n, r);
end2 = clock();
duration_comb = duration(start2, end2);
printf("(Perms, Combs) = (%lf, %lf)\n", noof_perms, noof_combs);
printf("\nFor perms, start = %ld, end = %ld, duration = %lf", start1, end1, duration_perm);
printf("\nFor combs, start = %ld, end = %ld, duration = %lf\n", start2, end2, duration_comb);
}
|
C
|
/*************************************************************
* This is the code by Saurabh Lanje.
* YouTube Channel - www.youtube.com/saurabhlanje
* Linkedin - www.linkedin.com/in/saurabhlanje
*************************************************************/
#include <stdint.h> // Integer declaration
#include <stdbool.h> // Boolean values
#include "inc/hw_memmap.h" // Each and every peripheral is assigned with memeory address i.e. it is memory mapped
#include "driverlib/debug.h" //for debug purpose
#include "driverlib/gpio.h" //gpio pin values and address with API's
#include "driverlib/sysctl.h" //Sysctl API's
//*****************************************************************************
//
// Blink the on-board LED.
//
//*****************************************************************************
int main(void)
{
//volatile uint32_t ui32Loop; //used for loop variable
SysCtlClockSet(SYSCTL_SYSDIV_5|SYSCTL_USE_PLL|SYSCTL_OSC_MAIN|SYSCTL_XTAL_16MHZ);
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF); // Enable the GPIO port that is used for the on-board LED.
GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1);// Enable the GPIO pin for the LED (PF3). Set the direction as output
//and enable the GPIO pin for digital function.
GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_2);
GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_3);
while(1) // Loop forever.
{
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1, GPIO_PIN_1); // Turn on the LED.
SysCtlDelay(6666666);
//for(ui32Loop = 0; ui32Loop < 200000; ui32Loop++); // Delay for a bit.
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1, 0x00); // Turn off the LED.
SysCtlDelay(6666666);
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_2, GPIO_PIN_2); // Turn on the LED.
SysCtlDelay(6666666);
//for(ui32Loop = 0; ui32Loop < 200000; ui32Loop++); // Delay for a bit.
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_2, 0x00); // Turn off the LED.
SysCtlDelay(6666666);
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_3, GPIO_PIN_3); // Turn on the LED.
SysCtlDelay(6666666);
//for(ui32Loop = 0; ui32Loop < 200000; ui32Loop++); // Delay for a bit.
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_3, 0x00); // Turn off the LED.
SysCtlDelay(6666666);
//for(ui32Loop = 0; ui32Loop < 200000; ui32Loop++); // Delay for a bit.
}
}
|
C
|
//-----------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------
#include <softi2c.h>
void delay_1ms(void) // 0us ʱ1ms
{
uint8 a,c;
for(c=4;c>0;c--)
{
//for(b=142;b>0;b--)
{
for(a=2;a>0;a--)
{
}
}
}
}
/****************************************************************************
* : DelayMS()
* : ԺΪλʱϵͳʱӲʱĬΪ16M(ʾ൱ȷ)
* ڲ: msec ʱֵԽʱԽ
* ڲ:
****************************************************************************/
void DelayMS(uint16 msec)
{
uint16 i,j;
for (i=0; i<msec; i++)
for (j=0; j<535; j++);
}
void IIC_Init(void)//IICʼ
{
P1DIR |= 0x01; //P1.5P1.6Ϊ
P1DIR |= 0x04;
SDA_0;
SCL_0;
delay_1ms();
SCL_1;
SDA_1;
delay_1ms();
}
//***********************************************************************************
//*ƣi2c_send_noack() *
//*ܣӦI2C *
//* *
//*أ1 NOACKź 0 NOACKź *
//***********************************************************************************
void send_noack(void){
SDA_OUT; //·,
SDA_1; //SDA = 1; NO ACK
delay_1ms();
SCL_1; //SCL = 1;
delay_1ms();
SCL_0; //SCL = 0; //START
}
// iic Ӧ for slaver
void send_ack(void) {
SDA_OUT; //·,
SDA_0; //OUT 0 ACK
delay_1ms();
SCL_1;
delay_1ms();
SCL_0;
}
/*
*ֹͣiic
*/
void stop(void){
SDA_OUT; //·,0.
SCL_0; //SCL = 0;
delay_1ms();
SCL_1; //SCL = 1; STOP
delay_1ms();
SDA_1; //SDA = 1;
SDA_IN;
SCL_IN;
}
/*
* iic
*/
// static void start(void) {
void start(void){
SDA_OUT; //·,0.
SCL_OUT;
SDA_1; //SDA = 1;
SCL_1; //SCL = 1;
delay_1ms();
SDA_0; //SDA = 0;
delay_1ms();
SCL_0; //SCL = 0; //START
}
/*
* iicдһֽ
*/
void iic_write(uint8 datIn) {
uint8 dat, j;
dat = datIn;
SDA_OUT;
SCL_0;
for (j = 0; j < 8; j++) {
if((dat & 0x80)) SDA_1;
else SDA_0;
delay_1ms();
delay_1ms();
SCL_1; //write TDOS_SDA begin
delay_1ms();
dat <<= 1;
SCL_0; //write TDOS_SDA end
delay_1ms();
}
}
uint8 check_ack(void) {
uint8 ack_flag;
SDA_IN; //·,
delay_1ms();
SCL_1; //read ask begin
delay_1ms();
if(I2C_SDA_READ == BIT7){ //if (SDA==1)
ack_flag = 0; //1: err
}else{
ack_flag = 1; //0: ok
}
SCL_0; //read ask end
return ack_flag;
}
/*
* iicһֽ
*/
uint8 iic_read(void) {
uint8 j, dat = 0;
SDA_IN; //·,
for (j = 0; j < 8; j++) {
SCL_1; //read TDOS_SDA begin. delay 0.7us
dat <<= 1;
delay_1ms();
delay_1ms();
if(I2C_SDA_READ == BIT2){ //if (SDA==1)
dat |= 0x01; //input TDOS_SDA
}
SCL_0; //read TDOS_SDA end. delay 1.4us
}
return dat;
}
//-----------------------------------------------------------------------------
// End Of File
//-----------------------------------------------------------------------------
|
C
|
#include<stdlib.h>
#include<stdio.h>
// Video resolution
#define W 1920
#define H 1279
// Allocate a buffer to store one frame
unsigned char frame[H][W][3] = {0};
int main()
{
int x, y, count;
//ffmpeg -loop 1 -i after_10_mins_nnet_1L.jpg -c:v libx264 -t 10 -pix_fmt yuv420p -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" output3.mp4
// Open an input pipe from ffmpeg and an output pipe to a second instance of ffmpeg
FILE *pipein = popen("ffmpeg -i after_10_mins_nnet_1L.jpg -f image2pipe -vcodec rawvideo -pix_fmt rgb24 -", "r");
FILE *pipein2 = popen("ffmpeg -i captions.jpg -f image2pipe -vcodec rawvideo -pix_fmt rgb24 -", "r");
FILE *pipeout = popen("ffmpeg -y -f rawvideo -vcodec rawvideo -pix_fmt rgb24 -s 1280x720 -r 60 -i - -f mp4 -q:v 5 -an -vcodec mpeg4 combined4.mp4", "w");
int img_h = 1279;
int img_w = 1920;
count = fread(frame, 1, img_h*img_w*3, pipein);
// If we didn't get a frame of video, we're probably at the end
if (count != img_h*img_w*3) {
fprintf(stderr, "Problem!!!!!!!!!!\n");
exit(1);
}
int caption_w = 942;
int caption_h = 178;
unsigned char text_frame[178][942][3] = {0};
count = fread(text_frame, 1, 178*942*3, pipein2);
// Process video frames
int i = 0;
while(i < 510)
{
// Read a frame from the input pipe into the buffer
//count = fread(frame, 1, H*W*3, pipein);
// If we didn't get a frame of video, we're probably at the end
//if (count != H*W*3) break;
// Process this frame
int video_h = 720;
int video_w = 1280;
unsigned char temp_frame[720][1280][3] = {0};
for (y=0 ; y<video_h ; ++y){
for (x=0 ; x<video_w ; ++x){
// Invert each colour component in every pixel
if(x > (video_w - caption_w)/2 && x<(video_w + caption_w)/2 && y > (video_h - caption_h - 10) && y < (video_h - 10)&& (text_frame[y - video_h + caption_h + 10][(2*x-video_w+caption_w)/2][0]<205 || text_frame[y - video_h + caption_h + 10][(2*x-video_w+caption_w)/2][1]<205 || text_frame[y - video_h + caption_h + 10][(2*x-video_w+caption_w)/2][2]<205)){
temp_frame[y][x][0] = text_frame[y - video_h + caption_h + 10][(2*x-video_w+caption_w)/2][0]; // red
temp_frame[y][x][1] = text_frame[y - video_h + caption_h + 10][(2*x-video_w+caption_w)/2][1]; // green
temp_frame[y][x][2] = text_frame[y - video_h + caption_h + 10][(2*x-video_w+caption_w)/2][2];
continue;
}
if(i<=255){
temp_frame[y][x][0] = frame[y][x][0] + (char)(i - frame[y][x][0]*(i/255.0)); // red
temp_frame[y][x][1] = frame[y][x][1] + (char)(i - frame[y][x][1]*(i/255.0)); // green
temp_frame[y][x][2] = frame[y][x][2] + (char)(i - frame[y][x][2]*(i/255.0)); // blue
}
else{
temp_frame[y][x][0] = frame[y][x][0] + (char)((510-i) - frame[y][x][0]*((510-i)/255.0)); // red
temp_frame[y][x][1] = frame[y][x][1] + (char)((510-i) - frame[y][x][1]*((510-i)/255.0)); // green
temp_frame[y][x][2] = frame[y][x][2] + (char)((510-i) - frame[y][x][2]*((510-i)/255.0)); // blue
}
}
}
if(i == 255){
pclose(pipein);
FILE *pipein = popen("ffmpeg -i one.jpg -f image2pipe -vcodec rawvideo -pix_fmt rgb24 -", "r");
count = fread(frame, 1, img_h*img_w*3, pipein);
// If we didn't get a frame of video, we're probably at the end
if (count != img_h*img_w*3) {
fprintf(stderr, "Problem!!!!!!!!!!\n");
exit(1);
}
}
// Write this frame to the output pipe
fwrite(temp_frame, 1, video_h*video_w*3, pipeout);
i++;
}
i = 0;
while(i<20){
unsigned char temp_frame[720][1280][3] = {0};
fseek(pipeout, (255+i)*720*1280*3, SEEK_SET);
fwrite(temp_frame, 1, 720*1280*3, pipeout);
i++;
}
// Flush and close input and output pipes
fflush(pipein);
pclose(pipein);
fflush(pipeout);
pclose(pipeout);
fflush(pipein2);
pclose(pipein2);
return 0;
}
|
C
|
#include "matriks.h"
#include <stdio.h>
void BuatMatriks(int Baris, int Kolom, Matriks *M){
indeks i,j;
(*M).Baris = Baris;
(*M).Kolom = Kolom;
for (i = 0; i < Baris; i++){
for (j = 0; j < Kolom; j++){
(*M).Mem[i][j] = 0;
}
}
}
indeks BarisPertama (Matriks M) {
return BarisMin;
}
indeks KolomPertama (Matriks M) {
return KolomMin;
}
indeks BarisTerakhir(Matriks M){
return M.Baris - 1;
}
indeks KolomTerakhir(Matriks M){
return M.Kolom - 1;
}
void IsiMatriks(Matriks *M){
indeks i, j;
for (i = 0; i < (*M).Baris; i++){
for (j = 0; j < (*M).Kolom; j++){
int x;
scanf("%d", &x);
Elmt(*M, i, j) = x;
}
}
}
void PrintMatriks(Matriks M){
indeks i, j;
for (i = 0; i <= BarisTerakhir(M); i++) {
for (j = 0; j <= KolomTerakhir(M); j++) {
printf(((j != KolomTerakhir(M)) ? "%d " : ((i != BarisTerakhir(M)) ? "%d\n" : "%d")), M.Mem[i][j]);
}
}
}
|
C
|
/* inherit to have the attachment functionality, i.e. the
* object (which must have an inventory) gets the possibility to
* hold items in its attach slots.
* E.g. a bag which is attached to a belt.
*/
#include <composite.h>
#include <event.h>
#include <language.h>
#include <macros.h>
#include <properties.h>
#include <slots.h>
private int slots; /* number of attach slots */
/*
* Function name: set_slots
* Description: set the number of attach slots this object should have
* Arguments: s - the number of attach slots
*/
static nomask void
set_attach_slots(int s)
{
slots = s;
}
/*
* Function name: query_slots
* Description: how many attach slots does this object have
* Returns: int, number of slots
*/
static nomask int
query_attach_slots()
{
return slots;
}
/*
* Function name: show_attached
* Description: return a description string for all attached items
* Arguments: tp - the looking living
* Returns: string, 0 if nothing visible
*/
nomask string
show_attached(object tp)
{
object *obj;
if (!sizeof(obj = tp->visible(this_object()->attached())))
return 0;
return capitalize(BS(COMPOSITE(obj, tp) +
((sizeof(obj) > 1 || obj[0]->query_heap_size() > 1) ?
" are " : " is ") + "attached to it.\n", 75, 0));
}
/*
* Function name: attach_filter
* Description: this function can be overwritten to have a filter
* functionality. If the filter function returns 0 for an
* object, the object cannot be attached.
* Arguments: ob - the object to check
* Returns: integer
*/
int
attach_filter(object ob)
{
return 1;
}
/*
* Function name: attach_check
* Description: check if an object is allowed to get attached to this_object
* Arguments: ob - the object to attach
* Returns: 1 if allowed, else 0
*/
nomask int
attach_check(object ob)
{
int size;
if (sizeof(this_object()->attached()) >= slots ||
!(size = ob->query_prop(OBJ_ATTACH_SIZE)) ||
size > this_object()->query_size() ||
!attach_filter(ob))
return 0;
return 1;
}
/*
* Function name: attach_cmd
* Description: called from cmdsoul to attach an item
* Arguments: ob - the object to attach to this object
* tp - acting living
* Returns: 1 if success, -1 else
*/
nomask int
attach_cmd(object ob, object tp)
{
if (!attach_check(ob))
{
tp->catch_tell("It's not possible to attach it there.\n");
return -1;
}
ob->attach(this_object());
tp->echo(({ "You attach ", QTNAME(ob), " to ", QTNAME(this_object()),
".\n" }), 0, 0);
tell_objects(LISTEN(E(tp)) - ({ tp }),
({ QCTNAME(tp), " attaches ", QNAME(ob), " to ",
QNAME(this_object()), ".\n" }), MSG_SEE, tp);
return 1;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* map.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sscottie <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/08/12 21:17:18 by sscottie #+# #+# */
/* Updated: 2019/08/13 00:04:40 by sscottie ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
void set_colours(t_map *map)
{
t_vector v;
t_vector *cur;
v.y = 0;
while (v.y < map->height)
{
v.x = 0;
while (v.x < map->width)
{
cur = map->vectors[(int)v.y * map->width + (int)v.x];
cur->colour = rgb(0xFF0000, 0xFFFFFF, ft_minus_color(cur->z,
map->depth_min, map->depth_max));
v.x++;
}
v.y++;
}
}
t_vector proj_vector(t_vector v, t_mlx *mlx)
{
v.x -= (float)(mlx->map->width - 1) / 2.0f;
v.y -= (float)(mlx->map->height - 1) / 2.0f;
v.z -= (float)(mlx->map->depth_min + mlx->map->depth_max) / 2.0f;
v = rotate(v, mlx->cam);
v.x *= mlx->cam->zoom;
v.y *= mlx->cam->zoom;
v.x += mlx->cam->offset_x;
v.y += mlx->cam->offset_y;
return (v);
}
t_vector vector_at(t_map *map, int x, int y)
{
return (*map->vectors[y * map->width + x]);
}
t_vector *get_vector(int x, int y, char *str)
{
t_vector *v;
v = ft_memalloc(sizeof(t_vector));
if (v == NULL)
return (NULL);
v->x = (float)x;
v->y = (float)y;
v->z = (float)ft_atoi(str);
v->colour = 0xFFFFFF;
return (v);
}
t_map *get_map(int width, int height)
{
t_map *map;
map = ft_memalloc(sizeof(t_map));
if (map == NULL)
return(NULL);
map->width = width;
map->height = height;
map->depth_min = 0;
map->depth_max = 0;
map->vectors = ft_memalloc(sizeof(t_vector *) * width * height);
if (map->vectors == NULL)
{
ft_memdel((void **)&map);
return (NULL);
}
return (map);
}
|
C
|
/*************************************************************************
> File Name: triangle.c
> Author:
> Mail:
> Created Time: Sat Oct 22 23:30:35 2016
************************************************************************/
#include<stdio.h>
int main() {
int line;
int lspace = 0;
scanf("%d", &line);
for (int i = 0; i < line; i++){
for(int j = 0; j < lspace; j++) {
printf(" ");
}
for(int k = 0; k < 2*(line - i)-1; k++) {
printf("#");
}
printf("\n");
lspace++;
}
return 0;
}
|
C
|
#ifndef _STACK_H_
#define _STACK_H_
#include <stddef.h>
#include <stdlib.h>
typedef struct stack Stack_t;
/**
* Initializes a stack.
*
* @return Pointer to a new Stack_t structure.
*/
Stack_t *stack_init();
/**
* Pushes an element to the stack.
*
* @param stack The stack to push the element onto.
* @param element The element to push on the stack.
*/
void stack_push(Stack_t*, void *);
/**
* Pops an element from the stack.
*
* @param stack The stack to pop an element from.
* @return The front most element on the stack.
*/
void *stack_pop(Stack_t *);
/**
* Returns the size of the stack.
*
* @param stack A stack.
* @return The size of a stack.
*/
size_t stack_size(Stack_t *);
/**
* Deallocates a stack.
*
* @param stack The stack to delete.
*/
void stack_delete(Stack_t *);
#endif
|
C
|
// 6-3. ϰ Ű ִ get_factorial Լ ȣ
#include <stdio.h>
int get_factorial(int num)
{
int i;
int result = 1;
for (i = 1; i <= num; i++)
result *= i;
return result;
}
int main()
{
int i;
int fact;
for (i = 0; i <= 5; i++)
{
fact = get_factorial(i);
printf("%2d!= %3d\n", i, fact);
}
get_factorial(20);
}
|
C
|
/* screen.h - (c) 2016 James S Renwick
-----------------------------------
Authors: James S Renwick
*/
#pragma once
#define _packed_ __attribute__((packed))
#define _noreturn_ __attribute__((noreturn))
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;
typedef unsigned long int uint32_t;
typedef struct
{
uint8_t column;
uint8_t row;
} tmpoint;
typedef struct
{
unsigned fore : 4;
unsigned back : 4;
} _packed_ tmcolor;
typedef struct
{
uint8_t character;
tmcolor color;
} _packed_ tmchar;
typedef enum
{
TMCOLOR_BLACK = 0x0,
TMCOLOR_BLUE = 0x1,
TMCOLOR_GREEN = 0x2,
TMCOLOR_CYAN = 0x3,
TMCOLOR_RED = 0x4,
TMCOLOR_MAGENTA = 0x5,
TMCOLOR_BROWN = 0x6,
TMCOLOR_GRAY = 0x7,
TMCOLOR_DARKGRAY = 0x8,
TMCOLOR_LIGHTBLUE = 0x9,
TMCOLOR_LIGHTGREEN = 0xA,
TMCOLOR_LIGHTCYAN = 0xB,
TMCOLOR_LIGHTRED = 0xC,
TMCOLOR_LIGHTMAGENTA = 0xD,
TMCOLOR_YELLOW = 0xE,
TMCOLOR_WHITE = 0xF
} tmcolors;
void screen_setmode(uint8_t columns, uint8_t rows);
void screen_color(tmcolors foreColor, tmcolors backColor);
void screen_forecolor(tmcolors color);
void screen_backcolor(tmcolors color);
void screen_print(const char* string);
void screen_newline();
void screen_clear();
tmpoint screen_getpos();
void screen_setpos(tmpoint point);
void screen_setposxy(uint8_t column, uint8_t row);
void screen_set(const tmchar* chars, uint32_t length);
|
C
|
#include "headers.h"
int main(int argc, char const *argv[])
{
printf("Parent process started...\n");
if (fork() == 0)
{
printf("Inside first child process\n");
if (fork() == 0)
{
printf("Inside second child process\n");
}
}
printf("Parent process ends.\n");
return 0;
}
|
C
|
#include "FileManager.h"
#include "assert.h"
void photostovis_get_filenames_from_client(char* const currentPath, const unsigned int currentPathLen, char full_exe_path[])
{
DIR *dirp;
char* path = currentPath;
assert(path[currentPathLen-1]=='/');
struct dirent *dp;
char * filename;
char * fullpath;
dirp = opendir(path);
while((dp = readdir(dirp)) != NULL)
{
if(!strcmp(dp->d_name,".") || !strcmp(dp->d_name,"..") || !strcmp(dp->d_name,"./"))
{
continue;
}
else
{
if(dp->d_type==DT_DIR)
{
int nameLen = strlen(dp->d_name);
memcpy(path+currentPathLen, dp->d_name, nameLen);
path[currentPathLen+nameLen] = '/';
path[currentPathLen+nameLen+1] = '\0';
photostovis_get_filenames_from_client(path, currentPathLen+nameLen+1, full_exe_path);
}
else
{
filename = dp->d_name;
fullpath = (char *) malloc(1 + strlen(path)+ strlen(filename) );
strcpy(fullpath, path);
strcat(fullpath, filename);
char hash_content[65];
photostovis_hash_file_content_on_client(fullpath, hash_content);
char hash_path[65];
photostovis_hash_file_path_on_client(fullpath, hash_path);
char* newpath = fullpath;
photostovis_write_to_backup_file(newpath, hash_path, hash_content, full_exe_path);
}
}
path[currentPathLen]='\0';
}
closedir(dirp);
}
int photostovis_hash_file_content_on_client(char* fullpath, char output[65])
{
FILE* file = fopen(fullpath, "rb");
if(!file) return -1;
unsigned char hash[SHA256_BLOCK_SIZE];
SHA256_CTX sha256;
sha256_init(&sha256);
const int bufSize = 32768;
char* buffer = malloc(bufSize);
int bytesRead = 0;
if(!buffer) return -1;
while((bytesRead = fread(buffer, 1, bufSize, file)))
{
sha256_update(&sha256, buffer, bytesRead);
}
sha256_final(&sha256, hash);
sha256_hash_string(hash, output);
fclose(file);
free(buffer);
return 0;
}
void photostovis_hash_file_path_on_client(char* path, char output[65])
{
unsigned char buf[SHA256_BLOCK_SIZE];
SHA256_CTX ctx;
sha256_init(&ctx);
sha256_update(&ctx, path, strlen(path));
sha256_final(&ctx, buf);
sha256_hash_string(buf, output);
}
void sha256_hash_string (char hash[SHA256_BLOCK_SIZE], char outputBuffer[65])
{
int i = 0;
for(i = 0; i < SHA256_BLOCK_SIZE; i++)
{
sprintf(outputBuffer + (i * 2), "%02x", (unsigned char)hash[i]);
}
outputBuffer[64] = 0;
}
void photostovis_write_to_backup_file(char* path, char hash_path[65], char hash_file[65], char full_exe_path[])
{
char backup_path[strlen(full_exe_path)];
strcpy(backup_path, full_exe_path);
strcat(backup_path, "backup.txt");
FILE* file = fopen(backup_path, "a");
fprintf(file,"%s",path);
fprintf(file,"%s",",");
fprintf(file,"%s",hash_path);
fprintf(file,"%s",",");
fprintf(file,"%s",hash_file);
fprintf(file,"%s","\n");
fclose(file);
}
void photostovis_clear_backup_file(char full_exe_path[])
{
char backup_path[strlen(full_exe_path)];
strcpy(backup_path, full_exe_path);
strcat(backup_path, "backup.txt");
FILE* file = fopen(backup_path, "w");
fclose(file);
printf("Clearing local backup file");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.