language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
// Patrick Musau
// 09-2020
// Header file for safety checking of wall points
#ifndef BICYCLE_SAFETY_H_
#define BICYCLE_SAFETY_H_
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include "geometry.h"
// array that will store the points describing the wall
// number of rows, and columns in wall description file
extern double ** wallCoords;
extern int file_rows;
extern int file_columns;
// array that will store the hyper-rectangle representations of the objects
// in this particular example they are conese but this can be easily converted to generic obstacles
extern double *** obstacles;
extern int obstacle_count;
void load_wallpoints(const char * filename,bool print);
void allocate_2darr(int rows,int columns);
void deallocate_2darr(int rows,int columns);
int countlines(const char * filename);
bool check_safety(HyperRectangle* rect, double (*box)[2]);
bool check_safety_obstacles(HyperRectangle* rect);
bool check_safety_wall(HyperRectangle* rect);
void allocate_obstacles(int num_obstacles,double (*points)[2]);
void deallocate_obstacles(int num_obstacles);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct tsk_node_s{
int task_num; //starting from 0 and increase one by one
int task_type; // insert:0, delete:1, search:2
int value;
struct tsk_node_s* next;
};
struct lst_node_s {
int data;
struct lst_node_s* next;
};
// Two glboal variables to store address of front and rear nodes.
struct tsk_node_s* front = NULL; //head of Task Queue
struct tsk_node_s* rear = NULL; //tail of Task Queue
struct lst_node_s* headList = NULL; //head of List Queue
struct lst_node_s* tailList = NULL; //tail of List Queue
int searchInsert(int value){ //to check if the value was added before
struct lst_node_s* queueList = (struct lst_node_s*)malloc(sizeof(struct lst_node_s*));
queueList = headList;
while (queueList != NULL ) {
if (queueList->data == value) {
return 0; // returns 0 if previously added
}
queueList = queueList->next;
}
return 1; //returns 1 if it has not been added before
}
void insert(int numOfTask,int value){ // insert to the list queue
struct lst_node_s* queueList = (struct lst_node_s*)malloc(sizeof(struct lst_node_s*));
int temp = searchInsert(value); //to find out if it was added before
if(temp == 1){ //is added because it has not been added before.
queueList -> data = value;
queueList -> next = headList;
headList = queueList;
printf(" Task %d ~ Insert %d ==> %d inserted. \n", numOfTask ,value , value );
}
else{
printf(" Task %d ~ Insert %d ==> %d cannot be inserted. \n", numOfTask ,value , value );
}
}
void delete(int numOfTask,int value){ //to delete the requested value
struct lst_node_s* queueList = (struct lst_node_s*)malloc(sizeof(struct lst_node_s*));
struct lst_node_s* prev = (struct lst_node_s*)malloc(sizeof(struct lst_node_s*));
int flag = 0 ;
prev = NULL;
queueList=headList;
while(queueList != NULL ){
if (queueList-> data == value)
{
if(prev==NULL)
headList = queueList->next;
else
prev->next = queueList->next;
printf(" Task %d ~ Delete %d ==> %d deleted. \n", numOfTask ,value , value );
flag = 1;
free(queueList); //need to free up the memory to prevent memory leak
break;
}
prev = queueList;
queueList = queueList->next;
}
if(flag==0){
printf(" Task %d ~ Delete %d ==> %d cannot be deleted. \n", numOfTask ,value , value );
}
}
void search(int numOfTask,int value){ //checks whether there is a requested value in the list
struct lst_node_s* queueList = (struct lst_node_s*)malloc(sizeof(struct lst_node_s*));
int founded = -1;
queueList = headList;
while (queueList != NULL ) {
if (queueList->data == value) {
founded=value;
printf(" Task %d ~ Search %d ==> %d found. \n", numOfTask ,value , value );
}
queueList = queueList->next;
}
if (founded==-1)
{
printf(" Task %d ~ Search %d ==> %d is not found. \n", numOfTask ,value , value );
}
}
void sortList(){ // to sort from small to large
if(headList == NULL){ // if queue is empty
return;
}
//if is not empty
struct lst_node_s* i = (struct lst_node_s*)malloc(sizeof(struct lst_node_s*));
struct lst_node_s* j = (struct lst_node_s*)malloc(sizeof(struct lst_node_s*));
int temp;
for (i = headList ; i -> next != NULL ; i = i -> next)
{
for (j = i-> next ; j != NULL ; j=j->next)
{
if (i->data > j-> data)
{
temp = i->data;
i->data = j ->data;
j->data =temp;
}
}
}
}
void Task_enqueue(int numTask,int type,int value) { //allows tasks to add to queue.
struct tsk_node_s* queueTask = (struct tsk_node_s*)malloc(sizeof(struct tsk_node_s*));
queueTask -> task_num = numTask ; // to queue properties
queueTask -> task_type = type ;
queueTask -> value = value ;
queueTask -> next = NULL ;
if(front == NULL && rear == NULL){ // for empty queue
front = rear = queueTask;
return;
}
rear->next = queueTask;
rear = queueTask;
}
void Task_dequeue(){ //allows tasks to be removed from the queue.
struct tsk_node_s* queueTask = (struct tsk_node_s*)malloc(sizeof(struct tsk_node_s*));
queueTask = front; //to store head node
if(front == NULL) { // if head is null
printf("Queue is Empty\n");
return;
}
if(front == rear) { // if head and tail are same nome
front = rear = NULL;
}
else {
front = front->next;
}
if(queueTask-> task_type == 0){ //to call insert process if type = 0
insert(queueTask -> task_num , queueTask -> value);
}
else if(queueTask -> task_type == 1){ //to call delete process if type = 1
delete(queueTask -> task_num ,queueTask -> value);
}
else if(queueTask -> task_type == 2){
search(queueTask -> task_num ,queueTask -> value); //to call search process if type = 2
}
free(queueTask); // to free memory
}
void outOfTask(int numOfTasks){ //to pull all tasks from queue
int temp_numTask = 0 ;
while(temp_numTask < numOfTasks){
Task_dequeue();
temp_numTask = temp_numTask + 1;
}
}
void Task_queue(int numOfTasks){ // To Enqueue an integer
int temp_numTask = 0 ;
srand(time(NULL)); // provide to generate different numbers.
while(temp_numTask < numOfTasks){ //allows us to create as many task as we get from the console.
int rand_type = rand() % 3; // generate 0,1,2 for insert , delete and search process
int rand_value = rand() % 5; // generate task value for each Task
Task_enqueue(temp_numTask,rand_type,rand_value); //for task_queue
temp_numTask = temp_numTask + 1;
}
}
void display_Lists(){ // to show list Nodes Value
struct lst_node_s* queueList = (struct lst_node_s*)malloc(sizeof(struct lst_node_s*));
queueList = NULL; // we create a null node
printf("\n ************* Final List ************* \n");
if(headList == NULL){ // if not contain any node
printf("\n Empty List\n");
}else{
queueList=headList;
while(queueList != NULL){ //to control each element and write it's data
printf(" %d ", queueList -> data );
queueList = queueList -> next ;
}
}
printf("\n ************************************** \n");
}
int main(int argc, char* argv[]) {
if(argc == 2) {
int numOfTasks = atoi(argv[1]); // to get value from console
printf("\n ************************************** \n\n");
printf("\n Generated %d random list tasks... \n", numOfTasks);
printf("\n\n ************************************** \n\n");
Task_queue(numOfTasks); //creates the task according to the number received from the consol.
outOfTask(numOfTasks); //removes the Task from the Taskqueue and starts the necessary operations.
sortList(); //to sort the List Queue
display_Lists(); //to show the List Queue after all operations
}
else {
printf("We only need 2 arguments\n");
}
return 0;
}
|
C
|
#pragma once
typedef enum {
CS_PQ_LOWEST_PRIORITY, /* lowest key have highest priorit */
CS_PQ_HIGHEST_PRIORITY /* highest key have highest priorit */
} cs_pqueue_mode_t;
typedef struct cs_pqnode cs_pqnode_t;
typedef struct cs_pqueue cs_pqueue_t;
struct cs_pqnode {
int priority;
char* value;
cs_pqnode_t* parent;
cs_pqnode_t* left;
cs_pqnode_t* right;
};
struct cs_pqueue {
int mode;
cs_pqnode_t* root;
cs_pqnode_t* lowest;
cs_pqnode_t* highest;
};
cs_pqueue_t* cs_pqueue_new(cs_pqueue_mode_t mode);
void cs_pqueue_free(cs_pqueue_t*);
int cs_pqueue_push(cs_pqueue_t*, int priority, char* value);
/* Pop the highest priority node */
cs_pqnode_t* cs_pqueue_pop(cs_pqueue_t*);
void cs_pqueue_delete(cs_pqueue_t*, cs_pqnode_t* node);
void cs_pqueue_inorder_walk(cs_pqueue_t*);
|
C
|
/* hw13_13.c */
#include <stdio.h>
#include <stdlib.h>
#include "c:\prog\volume2.h"
#include "c:\prog\area2.h"
int main(void)
{
printf("CIRCLE(1.0)=%5.2f\n",CIRCLE(1.0));
printf("SPHERE(1.0)=%5.2f\n",SPHERE(1.0));
system("pause");
return 0;
}
/* output----------
CIRCLE(1.0)= 3.14
SPHERE(1.0)= 4.19
-----------------*/
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<limits.h>
int min(int a,int b){return a<b?a:b;}
int max(int a,int b){return a>b?a:b;}
int cmp (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main() {
int N;
scanf("%d", &N);
int v[N];
for (int i = 0; i < N; ++i) {
scanf("%d", &v[i]);
}
int productOfFive(){
int Max=-2140000000;
qsort(v,N,sizeof(int),cmp);
for(int i=0;i<=5;i++)
{
int Sum=1;
for(int j=0;j<i;j++)
Sum*=v[j];
for(int j=0;j<5-i;j++)
Sum*=v[N-j-1];
Max=max(Max,Sum);
}
return Max;
}
printf("%d\n", productOfFive(v) );
return 0;
}
|
C
|
/* Copyright 2013-2014 Dietrich Epp.
This file is part of SGLib. SGLib is licensed under the terms of the
2-clause BSD license. For more information, see LICENSE.txt. */
#include "sg/defs.h"
/* A note about timestamps: The input timestamps are floating point
seconds, and the output timestamps are signed integer sample
positions. Input timestamps are absolute, output timestamps are
relative to the current buffer. */
enum {
/* Number of sample points used to predict latency. A typical
buffer size is 1024, so this uses just under 1 second of
data at 44.1 kHz. This must be a power of 2. */
SG_MIXER_TIME_NSAMP = 32
};
/* Mixer timing state. This is used to adjust command timestamps for
live mixers. */
struct sg_mixer_time {
/* (Public) Audio sample rate, in Hz. */
int samplerate;
/* (Public) Audio buffer size, in samples. Do not modify this
value after calling update(). */
int bufsize;
/* (Public) The distance between points in the function mapping
input timestamps to output timestamps, in seconds. */
double deltatime;
/* (Public) Fudge factor to add to mixahead. */
double mixahead;
/* (Public) Buffer safety margin, in standard deviations. 0
selects a mixahead delay that puts 50% of commit times after
the end of the buffer, 1 gives 84%, 2 gives 98%. These
percentages are calculated assuming that commit time deviations
from linearity are normally distributed. */
double safety;
/* (Public) The maximum slope of the map from input to output
time. Increasing this can cause latency spikes to have a
longer lasting effect on delay. Decreasing this increases the
time required to respond to increases in latency. The value
should be larger than the ratio of the output clock rate
divided by the input clock rate (nominally 1.0). */
double maxslope;
/* (Public) The smoothing factor for changes in latency, between
0.0 and 1.0. Larger numbers apply more smoothing. */
double smoothing;
/* Flag indicating the rest of the structure is initialized */
int initted;
/* The actual timestamps of the beginning and end of the current
buffer, and the ratio bufsize / (buftime[1] - buftime[0]). */
double buftime[2];
double buftime_m;
/* Map from input to output timestamps. The function is defined
as f(t) = (t - out_x0) * out_m[i] + out_y0, where i = 0 when t
< outx0 and i = 1 when t >= outx0. */
double out_x0, out_m[2], out_y0;
/* Past commit times. */
double commit_sample[SG_MIXER_TIME_NSAMP];
int commit_sample_num;
};
/* Initialize the timing system. This uses default values for public
parameters, which can be adjusted if you're insane enough to
care. */
void
sg_mixer_time_init(struct sg_mixer_time *SG_RESTRICT mtime,
int samplerate, int bufsize);
/* Update the state for the next buffer. The commit time is the most
recent commit time. The buffer time is the timestamp corresponding
to the end of the new buffer. This must be called at least once
before sg_mixer_time_get() is called. */
void
sg_mixer_time_update(struct sg_mixer_time *SG_RESTRICT mtime,
double committime, double buffertime);
/* Get the sample position for the given timestamp. Returns the
buffer size if the sample position is after the current buffer. */
int
sg_mixer_time_get(struct sg_mixer_time const *SG_RESTRICT mtime,
double time);
/* Get the current mixer latency, in samples. */
double
sg_mixer_time_latency(struct sg_mixer_time const *SG_RESTRICT mtime);
/* Mixer timing for an offline mixer. */
struct sg_mixer_timeexact {
/* The audio buffer size, in samples. */
int bufsize;
/* Function mapping input to output timestamps. The function is
defined as f(t) = t * m + y0. */
double m, y0;
};
/* Initialize the timing system. */
void
sg_mixer_timeexact_init(struct sg_mixer_timeexact *mtime,
int bufsize, int samplerate, double reftime);
/* Update the state for the next buffer. */
void
sg_mixer_timeexact_update(struct sg_mixer_timeexact *mtime);
/* Get the sample position for the given timestamp. */
int
sg_mixer_timeexact_get(struct sg_mixer_timeexact *mtime, double time);
|
C
|
#include <stdio.h>
#include <stdlib.h>
double saving_plan(double initial, double payments, double debit_ann_rate,
double credit_ann_rate, int years);
int
main(int argc, char **argv){
double initial, payments, debit_ann_rate, credit_ann_rate, balance;
int years;
printf("Enter initial balance :");
scanf("%lf", &initial);
printf("Enter monthly transfers to be made :");
scanf("%lf", &payments);
printf("Enter the number of years of the annuity :");
scanf("%d", &years);
printf("Enter the annual interest rate on savings :");
scanf("%lf", &debit_ann_rate);
printf("Enter the annual interest rate on mortgage loans :");
scanf("%lf", &credit_ann_rate);
balance = saving_plan(initial, payments, debit_ann_rate, credit_ann_rate,
years);
printf("Savings of $%f plus $%f per month for %d years is $%f\n", initial,
payments, years, balance);
return 0;
}
double saving_plan(double initial, double payments, double debit_ann_rate,
double credit_ann_rate, int years){
int month;
double monthly_interest, balance = initial;
for (month=0; month<12*years; month++){
if (balance>=0){
monthly_interest = 1.00 + ((debit_ann_rate/100)/12);
}
else {
monthly_interest = 1.00 +((credit_ann_rate/100)/12);
}
balance *= monthly_interest;
balance += payments;
}
return balance;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "chaine.h"
void init_chaine (struct chaine* c)
{
init_liste_caractere (&c->L);
}
void clear_chaine (struct chaine* c)
{
clear_liste_caractere (&c->L);
}
/*
* Affecte à *c la chaîne de caractères s, qui est au format f
*/
void set_chaine_string (struct chaine* c, char* s, enum type_format f)
{ struct caractere k;
int i, n;
clear_chaine (c);
init_chaine (c);
i = 0;
while (s [i] != '\0')
{ init_caractere (&k);
set_caractere_string (&k, &n, s+i, f);
ajouter_en_queue_liste_caractere (&c->L, &k);
i += n;
}
}
void imprimer_chaine (struct chaine* c, enum type_format f)
{ struct maillon_caractere* M;
for (M = c->L.tete; M != (struct maillon_caractere*)0; M = M->next)
imprimer_caractere (&M->value, f);
}
int nb_octets_chaine (struct chaine* c)
{ struct maillon_caractere* M;
int n;
n = 0;
for (M = c->L.tete; M != (struct maillon_caractere*)0; M = M->next)
n += nb_octets_caractere (&M->value);
return n;
}
int nb_caracteres_chaine (struct chaine* c)
{
return c->L.nbelem;
}
|
C
|
#include "test.h"
#include "widget.h"
extern int _mgos_timers;
static void test_widget_default_ev(int ev, struct widget_t *w, void *ev_data) {
char evname[15];
if (!w)
return;
widget_ev_to_str(ev, evname, sizeof(evname)-1);
LOG(LL_INFO, ("Event %s received for widget '%s'", evname, w->name));
switch(ev) {
case EV_WIDGET_CREATE:
case EV_WIDGET_DRAW:
case EV_WIDGET_REDRAW:
case EV_WIDGET_TIMER:
case EV_WIDGET_TOUCH_UP:
case EV_WIDGET_TOUCH_DOWN:
case EV_WIDGET_DESTROY:
default: // EV_WIDGET_NONE
break;
}
(void) ev_data;
}
static int test_widget_create_from_file(void) {
struct widget_t *w;
int ret;
char *fn = "data/TestWidget.json";
LOG(LL_INFO, ("widget_create_from_file(%s)", fn));
w = widget_create_from_file(fn);
ASSERT(w, "widget_create_from_file()");
ASSERT(w->x == 16, "'x' field is invalid");
ASSERT(w->y == 16, "'x' field is invalid");
ASSERT(w->w == 48, "'x' field is invalid");
ASSERT(w->h == 48, "'x' field is invalid");
ret = strncmp("/some/file.ext", w->img, strlen("/some/file.ext"));
ASSERT(ret == 0, "'img' field is invalid");
ret = strncmp("One", w->label, strlen("One"));
ASSERT(ret == 0, "'label' field is invalid");
LOG(LL_INFO, ("widget_set_timer()"));
widget_set_timer(w, 1000);
ASSERT(_mgos_timers==1, "timer not found");
LOG(LL_INFO, ("widget_set_handler()"));
widget_set_handler(w, test_widget_default_ev);
LOG(LL_INFO, ("widget_delete_timer()"));
widget_delete_timer(w);
ASSERT(_mgos_timers==0, "timers found");
fn = "data/TestWidget-invalid.json";
LOG(LL_INFO, ("widget_create_from_file(%s)", fn));
w = widget_create_from_file(fn);
ASSERT(!w, "invalid widget created");
return 0;
}
int test_widget() {
test_widget_create_from_file();
LOG(LL_INFO, ("ensure we have no timers"));
ASSERT(_mgos_timers==0, "timers found");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int la_somme(int a, int b);
int main()
{
int nombre_1,nombre_2;
printf(" BONJOUR LES ZOZOS COMMENT VOUS ALLEZ!\n");
printf("entrer le premier nombre : ");
scanf("%d",&nombre_1);
printf("entrer le deuxieme nombre : ");
scanf("%d",&nombre_2);
printf(" la somme est : %d",la_somme(nombre_1,nombre_2));
return 0;
}
int la_somme(int a, int b)
{
return a+b;
}
|
C
|
/*******************************************************************************
* Course: C Intermediate Programming *
* *
* Program Name: Assignment7A.c *
* *
* Author: your name *
* *
* Date: June 1, 2002 *
* *
* Description: This program simulates an airlines reservation system. It *
* consists of one plane with a seating capacity of 12. It *
* makes one flight daily. *
* *
* The program uses an array of 12 structures. Each structure *
* holda a seat identification number (1A, 1B, 2A, 2B, ... 6A, *
* 6B), a marker that indicates whether the seat is assigned, *
* the last name of the seat holder, and the first name of the *
* seat holder. *
* *
* The program displays the following menu: *
* *
* To choose a function, enter its letter label: *
* a) Show number of empty seats *
* b) Show list of empty seats *
* c) Show alphabetical list of assigned seats and customer name *
* d) Assign a customer to a seat assignment *
* e) Delete a seat assignment *
* f) Quit *
* *
* The program successfully executes the promises of its menu. *
* Choices d) and e) require additional input, and each enables *
* the user to abort entry. *
* *
* After executing a particular function, the program shows the *
* menu again, except for choice f). *
* *
* Data is saved in a file between runs. When the program is *
* restarted, it first loads in the data, if any, from the file. *
* *
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 12
struct reservation {
char seat[4];
char lastName[20];
char firstName[20];
char seatMarker;
};
char getOption();
void readReservationFile();
void countEmptySeats();
void showEmptySeats();
void assignSeat();
void deleteSeatAssignment();
void showReservedSeats();
void loadReservationFile();
struct reservation seatArray[SIZE] = { {"1A"," "," ",'N'}, {"1B"," "," ",'N'},
{"2A"," "," ",'N'}, {"2B"," "," ",'N'},
{"3A"," "," ",'N'}, {"3B"," "," ",'N'},
{"4A"," "," ",'N'}, {"4B"," "," ",'N'},
{"5A"," "," ",'N'}, {"5B"," "," ",'N'},
{"6A"," "," ",'N'}, {"6B"," "," ",'N'} };
FILE *inputPtr, *outputPtr;
int main( ) {
char option;
//Read and Load Reservation File.
readReservationFile();
option = getOption();
while ( option != 'Q' && option != 'q' ) {
switch ( option ) {
case 'A':
case 'a':
countEmptySeats();
break;
case 'B':
case 'b':
showEmptySeats();
break;
case 'C':
case 'c':
showReservedSeats();
break;
case 'D':
case 'd':
assignSeat();
break;
case 'E':
case 'e':
deleteSeatAssignment();
break;
default:
printf("\nIncorrect option, please try again.\n");
}
option = getOption();
}
//Load Reservation File.
loadReservationFile();
}
/**************************************************************************
* This function displays the option menu and returns the users selection. *
**************************************************************************/
char getOption() {
char option;
printf("\nTo choose a function, enter its letter label:\n");
printf("a) Show number of empty seats\n");
printf("b) Show list of empty seats\n");
printf("c) Show alphabetical list of assigned seats and customer name\n");
printf("d) Assign a customer to a seat assignment\n");
printf("e) Delete a seat assignment\n");
printf("q) Quit\n ");
printf("> ");
scanf("%c", &option);
while ( getchar() != '\n');
return (option);
}
/***********************************************************************
* This function reads an input file containing a list of reservations. *
* It contains the seat number, first name, last name, and seat marker *
* value of 'Y'. If no file exists processing continues. *
***********************************************************************/
void readReservationFile() {
}
/*****************************************************************************
* This function determines the number of empty seats and displays the value. *
*****************************************************************************/
void countEmptySeats() {
}
/**************************************************
* This function displays the list of empty seats. *
**************************************************/
void showEmptySeats() {
}
/****************************************************************************
* This function lists the reserves seats, seat number, first and last name. *
****************************************************************************/
void showReservedSeats() {
}
/**********************************************
* This function assigns a seat to a customer. *
**********************************************/
void assignSeat() {
}
/*****************************************
* This function removes a reserved seat. *
*****************************************/
void deleteSeatAssignment() {
}
/***********************************************************
* This function load a file with the current reservations. *
***********************************************************/
void loadReservationFile() {
}
|
C
|
#include <string.h>
//文字列中の語の数をcountする関数
//「語」の定義は空白で区切られていること
int count_word(char str[]){
int i;
int whitespace_count = 0;
for(i = 0; i < strlen(str); i++){
if(str[i] == ' ')
whitespace_count++;
}
return whitespace_count + 1;
}
|
C
|
/* range.h - ranges of integer or float values */
#ifndef _RANGE_H
#define _RANGE_H
/* We'll allow multiple ranges and/or individual values. */
typedef struct _range {
int min, max;
} Range;
typedef struct _rangelist {
int nranges;
Range ranges[0];
} Rangelist;
/* For the sake of definiteness, have some sort of limit */
#define RANGEMAX 32000
extern Rangelist *protocols, *ports;
typedef struct _drange {
double min, max;
} DRange;
typedef struct _drangelist {
int nranges;
DRange ranges[0];
} DRangelist;
int readdoublerange(char *string, DRange *range);
DRangelist *readdoublerangelist(char *string);
int readintrange(char *string, Range *range);
Rangelist * readintrangelist(char *string);
int readportrange(char *string, Range *range);
Rangelist * readportrangelist(char *string);
int readprotorange(char *string, Range *range);
Rangelist * readprotorangelist(char *string);
int inrange(int value, Range *range);
int inrangelist(int value, Rangelist *rangelist);
int indoublerange(double value, DRange *range);
int indoublerangelist(double value, DRangelist *rangelist);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define MAXWORKERS 64
void *parentBird(void *);
void *babyBird(void *);
sem_t busy, empty;
int W = 5;
int dish;
int main(int argc, char *argv[]) {
pthread_t pid, bid[MAXWORKERS];
int numBirds;
numBirds = (argc > 1)? atoi(argv[1]) : MAXWORKERS;
if (numBirds > MAXWORKERS) numBirds = MAXWORKERS;
W = (argc > 2)? atoi(argv[2]) : W;
dish = W;
sem_init(&busy, 1, 0);
sem_init(&empty, 1, 0);
printf("main started\n");
pthread_create(&pid, NULL, parentBird, NULL);
long i;
for (i = 0; i < numBirds; i++)
pthread_create(&bid[i], NULL, babyBird, (void *) i);
sem_post(&busy);
sleep(1);
}
void *babyBird(void *arg) {
long myid = (long) arg;
while(1){
sem_wait(&busy);
if (dish > 0) {
dish--; //eat a worm
printf("#%ld ", myid);
sem_post(&busy);
usleep(100000); //sleep a bit
} else {
sem_post(&empty); //chirps the parent bird
}
}
}
void *parentBird(void *arg) {
while(1) {
sem_wait(&empty);
dish = W; //refill the dish
printf("\nparentBird!\n");
sem_post(&busy); //make the dish available again
}
}
|
C
|
#include <stdio.h>
int main(){
int lista[100002];
int turma, i, valor, aux=1, j;
int total=0;
scanf("%d", &turma);
for(i=0; i<turma; i++){
scanf("%d", &valor);
lista[i] = valor;
for(aux=1, j=i-1; j>=0; j--){
if(valor == lista[j]){
aux = 0;
break;
}
}
total = total + aux;
}
printf("%d\n", total);
return 0;
}
|
C
|
#ifndef LASER_UTILS
#define LASER_UTILS
static void hsbToRgb(GLfloat *hsb, GLfloat *rgb) {
if ( hsb[1] == 0.0 )
{
rgb[0] = hsb[2];
rgb[1] = hsb[2];
rgb[2] = hsb[2];
}
else
{
float var_h = hsb[0] * 6;
float var_i = floor( var_h ) ; //Or ... var_i = floor( var_h )
float var_1 = hsb[2] * ( 1 - hsb[1] );
float var_2 = hsb[2] * ( 1 - hsb[1] * ( var_h - var_i ) );
float var_3 = hsb[2] * ( 1 - hsb[1] * ( 1 - ( var_h - var_i ) ) );
if ( var_i == 0 ) { rgb[0] = hsb[2] ; rgb[1] = var_3 ; rgb[2] = var_1; }
else if ( var_i == 1 ) { rgb[0] = var_2 ; rgb[1] = hsb[2] ; rgb[2] = var_1; }
else if ( var_i == 2 ) { rgb[0] = var_1 ; rgb[1] = hsb[2] ; rgb[2] = var_3; }
else if ( var_i == 3 ) { rgb[0] = var_1 ; rgb[1] = var_2 ; rgb[2] = hsb[2]; }
else if ( var_i == 4 ) { rgb[0] = var_3 ; rgb[1] = var_1 ; rgb[2] = hsb[2]; }
else { rgb[0] = hsb[2] ; rgb[1] = var_1 ; rgb[2] = var_2; }
rgb[0];
rgb[1];
rgb[2];
}
}
static void rgbToHsb(GLfloat *hsb, GLfloat *rgb)
{
double hue, sat, value;
double diff, x, r, g, b;
double red, green, blue;
red = rgb[0];
green = rgb[1];
blue = rgb[2];
hue = sat = 0.0;
value = x = red;
if (green > value) value = green; else x = green;
if (blue > value) value = blue;
if (blue < x) x = blue;
if (value != 0.0) {
diff = value - x;
if (diff != 0.0) {
sat = diff / value;
r = (value - red) / diff;
g = (value - green) / diff;
b = (value - blue) / diff;
if (red == value) hue = (green == x) ? 5.0 + b : 1.0 - g;
else if (green == value) hue = (blue == x) ? 1.0 + r : 3.0 - b;
else hue = (red == x) ? 3.0 + g : 5.0 - r;
hue /= 6.0; if (hue >= 1.0 || hue <= 0.0) hue = 0.0;
}
}
hsb[0] = hue;
hsb[1] = sat;
hsb[2] = value;
}
#endif
|
C
|
#include<stdio.h>
int n1, n2, p1, p2;
int i, j, k;
int x[100];
int h[100];
int y[100];
int xo[100];
int ho[100];
int yo[100];
void restarts()
{
int i = 0;
for (; i < 100; i++)
{
x[i] = xo[i];
y[i] = 0;
h[i] = ho[i];
}
}
void linearcircular()
{
int k;
int m = n1 + n2 - 1;
k = m - n1;
i = n1;
while (k>0)
{
x[i++] = 0;
k--;
}
k = m - n2;
i = n2;
while (k>0)
{
h[i++] = 0;
k--;
}
for (i = 0; i<m; i++)
for (j = 0; j<m; j++)
{
y[(i + j) % m] = y[(i + j) % m] + x[i] * h[j];
}
printf("Linear using Circular Convolution : Y[n] = \n");
for (i = 0; i<m; i++)
printf("%d\t", y[i]);
printf("\nThe starting Index being : %d\n", (p1 + p2));
}
//////////////////////////////////////////////////////////////////////////
void circularlinear()
{
int m = 0;
int max = 0;
if (n1>n2)
{
m = n1;
int k = n1 - n2;
i = n2;
while (k>0)
{
h[i++] = 0;
k--;
}
}
if (n2>n1)
{
m = n2;
int k = n2 - n1;
i = n1;
while (k>0)
{
x[i++] = 0;
k--;
}
}
for (i = 0; i<m; i++)
for (j = 0; j<m; j++)
{
y[(i + j)] = y[(i + j)] + x[i] * h[j];
}
int z, z1 = 0;
for (z = m; z<2 * m; z++)
{
y[z1] = y[z1] + y[z];
z1++;
}
printf("Circular using Linear Convolution : Y[n] = \n");
for (i = 0; i<m; i++)
printf("%d\t", y[i]);
printf("\nThe starting Index being : %d\n", (p1 + p2));
}
//////////////////////////////////////////////////////////////////////
void linear()
{
for (i = 0; i<n1; i++)
for (j = 0; j<n2; j++)
{
y[i + j] = y[i + j] + x[i] * h[j];
}
printf("Linear Convolution : Y[n] = \n");
for (i = 0; i<(n1 + n2 - 1); i++)
printf("%d\t", y[i]);
printf("\nThe starting Index being : %d\n", (p1 + p2));
}
/////////////////////////////////////////////////////////////////////
void circular()
{
int m = 0;
int max = 0;
if (n1>n2)
{
m = n1;
int k = n1 - n2;
i = n2;
while (k>0)
{
h[i++] = 0;
k--;
}
}
if (n2>n1)
{
m = n2;
int k = n2 - n1;
i = n1;
while (k>0)
{
x[i++] = 0;
k--;
}
}
for (i = 0; i<m; i++)
for (j = 0; j<m; j++)
{
y[(i + j) % m] = y[(i + j) % m] + x[i] * h[j];
}
printf("Circular Convolution : Y[n] = \n");
for (i = 0; i<m; i++)
printf("%d\t", y[i]);
printf("\nThe starting Index being : %d\n", (p1 + p2));
}
////////////////////////////////////////////////////////////////////
int read(){
int x;
scanf("%d", &x);
return x;
}
void main()
{
printf("Enter the number elements in X(n) : ");
n1 = read();
for (i = 0; i<n1; i++)
{
printf("Enter the element at X(%d): ", i);
xo[i]=x[i] = read();
}
printf("Enter the start index X(N) : ");
p1 = read();
printf("Enter the number elements in H(n) : ");
n2 = read();
for (i = 0; i<n2; i++)
{
printf("Enter the element at H(%d): ", i);
ho[i]=h[i] = read();
}
printf("Enter the index H(N) : ");
p2 = read();
printf("Enter the Convolution : \n1.Linear\n2.Circular\n3.Linear From Circular\n4.Circular from Linear\nEnter Option ");
switch(read())
{
case 1: linear();break;
case 2: circular();break;
case 3: linearcircular();break;
case 4: circularlinear();break;
}
}
|
C
|
#ifndef __BIT_OPERATOR_H__
#define __BIT_OPERATOR_H__
#define bit(m) (1<<(m))
//returns an integer with the m'th bit set to 1
#define bit_set(p,m) ((p)|= bit(m))
//p= p | bit(m),sets the mth bit of p to 1
#define bit_clear(p,m) ((p)&=~(bit(m)))
//p= p & ~(bit(m)) sets the mth bit of p to 0
#define bit_check(p,m) ((p)&(bit(m)))
//check the m'th bit is 0 or not 0
#define bit_get(p,m) (((p)&(bit(m))) >>m)
//get the m'th bit is 0 or 1
#define bit_put(c,p,m) (c ? bit_set(p,m) : bit_clear(p,m))
//put c into the m'th bit of p
#define bit_flip(p,m) bit_put((~(bit_get(p,m))),p,m)
//flip the mth bit of p, 1->0, 0->1
#define mask (bit(1)|bit(2)|bit(3))
//mask is group mask has bit 1,2,3 setted
#define bits_set(dest, mask) ((dest)|=(mask))
//設定目標變數的遮罩區位元為1
#define bits_clear(dest, mask) ((dest)&=(~mask))
//清除目標變數的遮罩區位元為0
#define bits_get(source, mask, shift) (((source) & (mask)) >> shift)
//讀取來源變數之連續遮罩區位元串並向右位移對齊取得遮罩區位元串對應整數值
#define bits_put(source, dest, mask, shift) (dest = (dest&~mask) | ((source <<shift) & mask))
//將資料來源左移到其所佔用旗標群區域後蓋寫到目標變數
#endif
|
C
|
///////////////////////////////////////////////////////////////////////
//
// Accept N numbers from user check whether that numbers contains 11 in
// it or not.
// Input : N : 6
// Elements : 85 66 11 80 93 88
// Output : 11 is present
// Input : N : 6
// Elements : 85 66 3 80 93 88
// Output : 11 is absent
//
///////////////////////////////////////////////////////////////////////
//Header File
#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
typedef int BOOL;
//Prototype
BOOL Check( int * , int , int);
//Entry-Point Function
int main()
{
int iSize = 0 , i = 0 , iNo = 0;
int *p = NULL;
BOOL bRet = FALSE;
printf("Enter the Number of Elements :\n");
scanf("%d",&iSize);
p = (int *)malloc(iSize*sizeof(int));
if( NULL == p )
{
printf("Unable to Allocate Memory.\n");
return -1;
}
printf("Enter the Elements :\n");
for( i=0; i<iSize; i++)
{
scanf("%d",&p[i]);
}
printf("Enter the Element which you want to check :");
scanf("%d",&iNo);
bRet = Check( p , iSize , iNo );
if( bRet == TRUE )
{
printf("%d is Present.\n",iNo);
}
else
{
printf("%d is not Present.\n",iNo);
}
free(p);
return 0;
}
//function
BOOL Check( int Arr[] , int iLength , int iNo)
{
int i=0;
for( i=0; i<iLength; i++)
{
if( Arr[i] == iNo )
{
return TRUE;
break;
}
}
}
/* Output :
Enter the Number of Elements :
6
Enter the Elements :
85
66
11
80
93
88
Enter the Element which you want to check :11
11 is Present.
*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <math.h>
#include <omp.h>
#include "queue.h"
#define log2(x) ((int) (log(x) / log(2)))
#define getlevels(nthreads) log2(nthreads)
#define BARR_ITER 4.0
enum {FALSE, TRUE};
struct tnode *createnode();
struct tnode *createtree(int levels, struct tnode *parent);
struct tnode **getleaves(struct tnode *p, int nleaves);
void treeprint(struct tnode *p);
void printleaves(struct tnode **leaves, int nleaves);
void tree_bar(struct tnode *node, char *localsense, int);
int power2(int p);
struct tnode {
char locksense; /* 'global' to two threads */
int count;
struct tnode *parent;
struct tnode *left;
struct tnode *right;
};
struct tnode *createnode()
{
struct tnode *node;
node = malloc(sizeof(struct tnode));
node->locksense = TRUE;
node->count = 2;
node->left = node->right = NULL;
return node;
}
struct tnode *createtree(int levels, struct tnode *parent)
{
struct tnode *p;
p = NULL;
if (levels > 0) {
p = createnode();
p->left = createtree(levels - 1, p);
p->right = createtree(levels - 1, p);
p->parent = parent;
}
return p;
}
struct tnode **getleaves(struct tnode *p, int nleaves)
{
struct tnode **leaves;
struct tnode **leaves_cp;
struct tnode *node;
leaves = (struct tnode **) malloc(nleaves * sizeof(struct tnode *));
leaves_cp = leaves;
/* BFS */
enqueue(p);
while (qlen() != 0) {
node = (struct tnode *) dequeue();
if (node->left != NULL && node->right != NULL) {
enqueue(node->left);
enqueue(node->right);
} else
*leaves_cp++ = node;
}
return leaves;
}
void treeprint(struct tnode *p)
{
if (p != NULL) {
treeprint(p->left);
printf("%d\t%d\n", p->count, p->locksense);
treeprint(p->right);
}
}
void printleaves(struct tnode **leaves, int nleaves)
{
while (nleaves-- > 0)
printf("%p\t", *leaves++);
printf("\n");
}
int power2(int p)
{
int ans;
ans = 1;
while (p-- > 0)
ans *= 2;
return ans;
}
void _tree_bar(struct tnode *node, char *localsense, int thread)
{
#pragma omp atomic
(node->count)--;
//printf("thread %d: node count: %d\n", thread, node->count);
//printf("thread %d: node locksense: %d\n", thread, node->locksense);
if (node->parent == NULL) {
//printf("thread %d: root reached\n", thread);
if (node->count == 0) {
node->count = 2;
node->locksense = *localsense;
}
else
while (*localsense != node->locksense)
; /* spin */
} else {
if (node->count == 0) {
_tree_bar(node->parent, localsense, thread);
node->count = 2;
node->locksense = *localsense;
}
else {
while (*localsense != node->locksense)
; /* spin */
}
}
}
void tree_bar(struct tnode *node, char *localsense, int thread)
{
*localsense = !*localsense;
//printf("thread %d: localsense = %d\tleaf: %p\n", thread, *localsense, node);
_tree_bar(node, localsense, thread);
}
int main(int argc, char *argv[])
{
int nthreads, nleaves, levels;
int thread_num;
int priv;
int pub;
struct tnode *root;
struct tnode **leaves;
struct timeval tv_before;
struct timeval tv_after;
double total_time;
double avg_time;
nthreads = atoi(*++argv);
levels = getlevels(nthreads);
nleaves = nthreads / 2;
root = createtree(levels, NULL);
leaves = getleaves(root, nleaves);
thread_num = -1;
priv = 0;
pub = 0;
total_time = 0;
#pragma omp parallel num_threads(nthreads) firstprivate(thread_num, priv) shared(pub)
{
thread_num = omp_get_thread_num();
//printf("thread %d: hello\n", thread_num);
char localsense; /* local to each processor */
localsense = TRUE;
unsigned long thread_time;
double thread_avg;
thread_time = 0;
thread_avg = 0;
for (int i = 0; i < BARR_ITER; i++) {
#pragma omp critical
{
priv += thread_num;
pub += thread_num;
}
gettimeofday(&tv_before, NULL);
tree_bar(leaves[thread_num/2], &localsense, thread_num);
gettimeofday(&tv_after, NULL);
thread_time += tv_after.tv_usec - tv_before.tv_usec;
printf("[iter %d] time spent by thread %d: %lu\n", i, thread_num, thread_time);
}
thread_avg = thread_time / BARR_ITER;
//printf("thread %d: avg time = %f\n", thread_num, thread_avg);
total_time += thread_avg;
}
avg_time = total_time / nthreads;
printf("average time: %f\n", avg_time);
return 0;
}
|
C
|
#include <pthread.h>
#include <stdio.h>
#include <stdbool.h>
#include <errno.h>
#include <sys/mman.h>
// CONFIGS
static int create_thread(pthread_t* thread, void* (func)(), int sched, int prio) {
pthread_attr_t attr;
struct sched_param param = {prio};
pthread_attr_init(&attr);
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedpolicy(&attr, sched);
pthread_attr_setschedparam(&attr, ¶m);
int r = pthread_create(thread, &attr, func, NULL);
pthread_attr_destroy(&attr);
return r;
}
static int change_priority(int sched, int prio) {
struct sched_param param = {prio};
return pthread_setschedparam(pthread_self(), sched, ¶m);
}
// definitions
#define MAX 40
pthread_mutex_t mutex;
int shared_resource;
void* add_task();
void* sub_task();
// we're not using
int main() {
mlockall(MCL_CURRENT | MCL_FUTURE);
pthread_t a, b;
create_thread(&a, add_task, SCHED_FIFO, 26);
create_thread(&b, sub_task, SCHED_FIFO, 26);
// highest priority to the main thread
change_priority(SCHED_FIFO, 30);
pthread_join(a, NULL);
pthread_join(b, NULL);
return 0;
}
void* add_task() {
int i = 0;
struct timespec next;
clock_gettime(CLOCK_MONOTONIC, &next);
next.tv_sec += 1;
while(i < MAX) {
while(clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL) == EINTR);
pthread_mutex_lock(&mutex);
shared_resource++;
printf("[ADD TASK]: %d. Iteration number: %d\n", shared_resource, i);
pthread_mutex_unlock(&mutex);
next.tv_sec += 1;
i++;
}
return 0;
}
void* sub_task() {
int i = 0;
struct timespec next;
clock_gettime(CLOCK_MONOTONIC, &next);
next.tv_sec += 1;
while(i < MAX) {
while(clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL) == EINTR);
pthread_mutex_lock(&mutex);
shared_resource--;
printf("[SUB TASK]: %d. Iteration number: %d\n", shared_resource, i);
pthread_mutex_unlock(&mutex);
next.tv_sec += 1;
i++;
}
return 0;
}
|
C
|
/* #include <iostream> */
/* #include <random> */
#include <stdio.h>
#include <stdlib.h>
#define N 10000000
/* using namespace std; */
/* std::random_device seed_gen; */
/* std::mt19937 engine(seed_gen()); */
unsigned int xorshift();
int random_integer(int);
int main()
{
int dian, diaboxn;
int select[4];
int dia;
int i,j, k, d;
for (k = 0; k < 10; k++) {
dian = diaboxn = 0;
for (i = 0; i < N; i++) {
d = 0;
dia = 1;
for (j = 0; j < 4; j++ ){
select[j] = random_integer(52-j);
if (select[j] <= 12-d) {
d++;
} else if(j >= 1) {
break;
}
if (j == 3) {
dian++;
if (select[0] >= 0 && select[0] <= 12 && j == 3) {
diaboxn++;
}
}
}
}
printf("%lf\n", (double)diaboxn/(double)dian);
}
return 0;
}
unsigned int xorshift()
{
static unsigned int x = 1;
static unsigned int y = 2;
static unsigned int z = 3;
static unsigned int w = 4;
unsigned int t;
t = x ^ (x << 11);
x = y;
y = z;
z = w;
return w = (w^ (w>>19)) ^ (t ^ (t >> 8));
/* return engine(); */
}
int random_integer(int m)
{
return xorshift() % m;
}
|
C
|
#include<stdio.h>
#include<string.h>
int main ()
{
char a[] ="Just some random string";
char * ptr_b;
ptr_b = strstr (a,"other some random");
if(ptr_b != NULL)
{
printf("found\n");
}
else
{
printf("not found \n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[1024];
int integerGuess, clientFlagCorrect;
int numberOfTries;
char charGuess[1024], answerServer[1];
char* delimiter = "\\n";
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
// Creates the socket socket() --> endpoints of sockets
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
// Creates the socket socket() --> endpoints of sockets
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
// connects to the service in connect()
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
// connects to the service
/** variables **/
clientFlagCorrect = 0;
numberOfTries = 0;
while (clientFlagCorrect != 1)
{
numberOfTries = numberOfTries + 1;
/** initializing vars **/
integerGuess = 0;
memset(charGuess, 0, sizeof(charGuess));
// ask for the number
printf("Guess: ");
bzero(buffer,sizeof(buffer));
fgets(buffer,sizeof(buffer)-1,stdin);
printf("Buffer to process is : <%s>\n", buffer);
// ask to see if the number is guessed
/** string and delimeter **/
integerGuess = atoi(buffer);
printf("int Guess : <%d> \n", integerGuess);
sprintf( charGuess, "%d", integerGuess);
strcat( charGuess, delimiter);
printf("String Guess : <%s> \n", charGuess);
memset(buffer,0,sizeof(buffer));
memcpy(buffer, charGuess, sizeof(charGuess));
printf("Buffer to be sent is: : <%s>\n",buffer);
/** process the integer to string and add a delimiter **/
// send the string that was processed
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
// send the string that was processed
// reads the data being received
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
// reads the data being received
printf("Buffer received : <%s>\n",buffer);
memcpy(&answerServer, buffer, sizeof(answerServer));
printf ("Value of answerServer : <%c> \n", *answerServer);
/** Client response **/
if (strncmp ( & answerServer[0],"Lower",sizeof(answerServer)) == 0)
printf("The number is lower \n");
else if (strncmp ( & answerServer[0],"Higher",sizeof(answerServer)) == 0)
printf("The number is higher \n");
else if (strncmp ( & answerServer[0],"Correct",sizeof(answerServer)) == 0)
{
printf("Your guess is correct! \n");
clientFlagCorrect = 1;
}
else
error("ERROR Wrong message received");
}
printf ("It took you this many tries: %d \n", numberOfTries);
printf("%s\n",buffer);
close(sockfd);
return 0;
}
|
C
|
#include<stdio.h>
static int test_pix_sum_c(unsigned char * pix, int line_size)
{
int s, i, j;
s = 0;
for (i = 0; i < 16; i++) {
for (j = 0; j < 16; j += 8) {
s += pix[0];
s += pix[1];
s += pix[2];
s += pix[3];
s += pix[4];
s += pix[5];
s += pix[6];
s += pix[7];
pix += 8;
}
pix += line_size - 16;
}
return s;
}
extern int my_pix_sum_c(unsigned char *pix, int line_size);
extern int my_test_pix_sum_c(unsigned char *pix, int line_size);
int main()
{
unsigned char data[272];
int line_size = 17;
int i, j;
//init data array
for( i = 0; i<16; i++)
for( j = 0; j< line_size; j++)
data[ i * line_size + j ] = i + 1 ;
//calc sum
// int sum = my_pix_sum_c( data, line_size);
// int sum = test_pix_sum_c( data, line_size);
int sum = my_test_pix_sum_c( data, line_size);
printf("sum = %d\n",sum);
return 0;
}
|
C
|
#include <glu3.h>
#include <assert.h>
static GLboolean vec4_equals(const GLUvec4 *a, const GLUvec4 *b)
{
int i;
for (i = 0; i < 4; i++) {
if (a->values[i] != b->values[i])
return GL_FALSE;
}
return GL_TRUE;
}
static void vec4_divide(GLUvec4 *a)
{
a->values[0] /= a->values[3];
a->values[1] /= a->values[3];
a->values[2] /= a->values[3];
a->values[3] = 1.0;
}
int main(int argc, char **argv)
{
GLUvec4 a = {{1.0, 2.0, 1.0, 1.0}};
GLUvec4 b = {{-2.0, 3.0, 1.0, 1.0}};
GLUvec4 result;
GLUmat4 identity_frustum;
(void)argc;
(void)argv;
gluFrustum6(&identity_frustum,
-1, 1,
-1, 1,
-1, 1);
gluMult4m_4v(&result, &identity_frustum, &a);
vec4_divide(&result);
assert(vec4_equals(&result, &a));
gluMult4m_4v(&result, &identity_frustum, &b);
vec4_divide(&result);
assert(vec4_equals(&result, &b));
return 0;
}
|
C
|
// testTransmissionAmts.c
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "Graph.h"
void calculateViralTransmission(Graph g, int src, int srcViralLoad,
double *trasmissionArray);
int main(void) {
int nV;
if (scanf("nV: %d ", &nV) != 1) {
printf("error: failed to read nV\n");
return 1;
}
int src;
if (scanf("src: %d ", &src) != 1) {
printf("error: failed to read src\n");
return 1;
}
int srcViralLoad;
if (scanf("srcViralLoad: %d ", &srcViralLoad) != 1) {
printf("error: failed to read srcViralLoad\n");
return 1;
}
printf("nV: %d\nsrc: %d\nsrcViralLoad: %d\n\n",
nV, src, srcViralLoad);
Graph g = GraphNew(nV);
int v, w;
while (scanf("%d %d", &v, &w) == 2) {
GraphAddEdge(g, v, w);
printf("Edge inserted: %d-%d\n", v, w);
}
printf("\n");
double *trasmissionArray = malloc(nV * sizeof(double));
int i;
for (i = 0; i < nV; i++) {
trasmissionArray[i] = -1.0;
}
calculateViralTransmission(g, src , srcViralLoad, trasmissionArray);
printf("Viral load:\n");
for (i = 0; i < nV; i++) {
printf(" trasmissionArray[%d] is %10.3lf \n",
i, trasmissionArray[i]);
}
free(trasmissionArray);
GraphFree(g);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
void handler(int signum, siginfo_t *info, void *extra)
{
void *ptr_val = info->si_value.sival_ptr;
int int_val = info->si_value.sival_int;
printf("Sum=%d\n",int_val);
printf("SIGUSR1 was used to recieve the data of the variable sum\n");
}
static volatile int keepRunning = 1;
void intHandler(int dummy) {
keepRunning = 0;
}
static volatile int tap = 6;
void sig_handler(int signo)
{
//looks for ctrl-c which has a value of 2
if (signo == SIGINT){
tap = 0;
printf("\nControl C was used on process: ");
}
//looks for ctrl-\ which has a value of 9
else if (signo == SIGQUIT){
tap = 1;
}
//looks for ctrl-z
else if (signo == SIGTSTP){
tap = 2;
}
else if (signo == SIGTERM){
tap = 3;
}
}
int main(){
signal(SIGINT, intHandler);
signal(SIGQUIT, sig_handler);
signal(SIGTSTP, sig_handler);
signal(SIGTERM, sig_handler);
sigset_t mask;
sigset_t orig_mask;
struct sigaction act;
int id1 = 0, id2 = 0, id3 = 0;
int min=0;
int max=0;
int sum=0;
int i, status;
FILE *file1 = fopen("Input_Problem0.txt", "r");
int size = 1;
int ch = 0;
if(file1 == NULL){
printf("no numbers in the input file \n");
}
while(!feof(file1)){
ch = fgetc(file1);
if(ch == '\n'){
size++;
}
}
int arrNum[size];
rewind(file1);
for (i = 0; i < size; i++)
{
fscanf(file1, "%d", &arrNum[i]);
}
if(size == 1){
printf("Max = %d\n", arrNum[0]);
printf("Min = %d\n", arrNum[0]);
printf("Sum = %d\n", arrNum[0]);
return 0;
}
pid_t pid1 = fork();
if (pid1 == 0){
memset (&act, 0, sizeof(act));
act.sa_handler = sig_handler;
if (sigaction(SIGINT, &act, 0) || sigaction(SIGQUIT, &act, 0) || sigaction(SIGTSTP, &act, 0)) {
perror ("sigaction");
return 1;
}
sigemptyset (&mask);
sigaddset (&mask, SIGINT);
sigaddset (&mask, SIGQUIT);
sigaddset (&mask, SIGTSTP);
if (sigprocmask(SIG_BLOCK, &mask, &orig_mask) < 0) {
perror ("sigprocmask");
return 1;
}
sleep (2);
if (sigprocmask(SIG_SETMASK, &orig_mask, NULL) < 0) {
perror ("sigprocmask");
return 1;
}
if (tap == 3){
printf("SIGTERM was used on process: %d\n", getpid());
}
sleep(5);
wait(&status);
if(arrNum[0] > arrNum[1]){
max = arrNum[0];
min = arrNum[1];
}else{
max = arrNum[1];
min = arrNum[0];
}
printf("Hi I am Process 2 and my pid is %d. My Parent's pid is %d\n", getpid(), getppid());
pid_t pid2 = fork();
if(pid2 == 0){
memset (&act, 0, sizeof(act));
act.sa_handler = sig_handler;
if (sigaction(SIGTERM, &act, 0)) {
perror ("sigaction");
return 1;
}
sigemptyset (&mask);
sigaddset (&mask, SIGTERM);
if (sigprocmask(SIG_BLOCK, &mask, &orig_mask) < 0) {
perror ("sigprocmask");
return 1;
}
sleep (2);
if (sigprocmask(SIG_SETMASK, &orig_mask, NULL) < 0) {
perror ("sigprocmask");
return 1;
}
wait(&status);
printf("Hi I am Process 3 and my pid is %d. My Parent's pid is %d\n", getpid(), getppid());
for(i = 0; i < size; i++){
if(max < arrNum[i]){
max = arrNum[i];
}
}
pid_t pid3 = fork();
if(pid3 == 0){
memset (&act, 0, sizeof(act));
act.sa_handler = sig_handler;
if (sigaction(SIGTERM, &act, 0)) {
perror ("sigaction");
return 1;
}
sigemptyset (&mask);
sigaddset (&mask, SIGTERM);
if (sigprocmask(SIG_BLOCK, &mask, &orig_mask) < 0) {
perror ("sigprocmask");
return 1;
}
sleep (2);
if (sigprocmask(SIG_SETMASK, &orig_mask, NULL) < 0) {
perror ("sigprocmask");
return 1;
}
wait(&status);
printf("Hi I am Process 4 and my pid is %d. My Parent's pid is %d\n",getpid(),getppid());
for(i = 0; i < size; i++){
if(min > arrNum[i]){
min = arrNum[i];
}
}
printf("Max=%d\n", max);
printf("Min=%d\n", min);
exit(0);
} else{
wait(&status);
}
exit(0);
}else{
//kill(pid2, SIGTERM);
wait(&status);
}
for(i = 0; i < size; i++){
sum += arrNum[i];
}
sigqueue(getppid(),SIGUSR1,(const union sigval) sum);
exit(0);
}
else {
struct sigaction action;
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask,SIGUSR1);
action.sa_flags = SA_SIGINFO;
action.sa_mask =mask;
action.sa_sigaction = &handler;
if (sigaction(SIGUSR1,&action,NULL)==-1) {
perror("sigaction");
exit(EXIT_FAILURE);
}
//kill(pid1, SIGTERM);
wait(&status);
}
if (keepRunning == 0){
printf("Control C was used on process: %d\n", getpid());
}
if (tap == 1){
printf("SIGQUIT was used on process: %d\n", getpid());
}
if (tap == 2){
printf("SIGTSTP was used on process: %d\n", getpid());
}
fclose (file1);
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
main()
{
int i, j, k, f, pf=0, count=0, rs[25], m[10], n;
clrscr();
printf("\n Enter the length of reference string -- ");
scanf("%d",&n);
printf("\n Enter the reference string -- ");
for(i=0;i<n;i++)
scanf("%d",&rs[i]);
printf("\n Enter no. of frames -- ");
scanf("%d",&f);
for(i=0;i<f;i++) m[i]=-1;
printf("\n The Page Replacement Process is -- \n");
for(i=0;i<n;i++)
{
for(k=0;k<f;k++)
{
if(m[k]==rs[i]) break;
}
if(k==f) { m[count++]=rs[i];
pf++;
}
for(j=0;j<f;j++) printf("\t%d",m[j]);
if(k==f) printf("\tPF No. %d",pf);
printf("\n");
if(count==f) count=0;
}
printf("\n The number of Page Faults using FIFO are %d",pf);
getch();
}
|
C
|
double judge(int t){
if( t > 0 ){
return 1.0;
}else if( t < 0){
return -1.0;
}else{
return 0.0;
}
}
void sign(double* x, double* y, int m){
int i;
int a = m >> 2;
int b = a << 2;
for(i = 0;i < b; i+=4){
y[i] = judge(x[i]);
y[i+1] = judge(x[i+1]);
y[i+2] = judge(x[i+2]);
y[i+3] = judge(x[i+3]);
}
for(i = b ; i< m; i++){
y[i] = judge(x[i]);
}
}
/*
int main(){
double* x;
double* y;
x = malloc(10*sizeof(double));
y = malloc(10*sizeof(double));
int i;
for(i=0;i<10;i++){
x[i] = 8-i;
}
sign(x,y,10);
for(i=0;i<10;i++){
printf("y[%d] is %f\n",i,y[i]);
}
}
*/
|
C
|
#include "holberton.h"
/**
* _pali - Checks for palindrome.
* @len: Lenght of string.
* @s1: Target string.
* @i: 0, Init of string.
*
* Return: 1 if palindrome, 0 otherwise.
*/
int _pali(int len, char *s1, int i)
{
if (s1[i] == s1[len - 1])
{
_pali((len - 1), s1, i + 1);
return (1);
}
else if (s1[i] != s1[len])
{
return (0);
}
return (1);
}
/**
* _lenght - Calculates lenght of a string, recursively.
* @len: 0, Init value.
* @s1: Target string.
*
* Return: Lenght of string.
*/
int _lenght(int len, char *s1)
{
if (s1[len] != '\0')
{
return (_lenght(len + 1, s1));
}
return (len);
}
/**
* is_palindrome - Checks if a string is palindrome or not.
* @s: Target string.
*
* Return: 1 if it's palindrome, 0 otherwise.
*/
int is_palindrome(char *s)
{
int l = _lenght(0, s);
return (_pali(l, s, 0));
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, a[100], *ptr = a, x;
scanf("%d", &n);
for (int i = 0; i<n; i++)
{
scanf("%d", ptr);
ptr++;
}
ptr = a;
scanf("%d", &x);
int *x_ptr = &x;
for (int i = 0; i<n; i++)
{
if (*ptr == *x_ptr)
{
printf("%d is found in position %d\n", *x_ptr, i + 1);
break;
}
ptr++;
}
}
|
C
|
#include <stdio.h>
main()
{
int startH,startM,endH,endM,resultH,resultM;
scanf("%d%d%d%d",&startH,&startM,&endH,&endM);
resultH=endH-startH;
if(resultH<0){
resultH=24+resultH;
}
resultM=endM-startM;
if(resultM<0){
resultM=60+resultM;
resultH--;
}
if(startH==endH&&startM==endM){
printf("O JOGO DUROU 24 HORA(S) E 0 MINUTO(S)\n");
}else{
printf("O JOGO DUROU %d HORA(S) E %d MINUTO(S)\n",resultH,resultM);
}
return 0;
}
|
C
|
#include <math.h>
#include <stdio.h>
double maxim(double a, double b) {
if (a > b) {
return a;
} else {
return b;
}
}
double absol(double a) {
if (a >= 0) {
return a;
} else {
return -a;
}
}
int main(void) {
double x, mx, x3, max;
printf("Input x: ");
scanf("%lf", &x);
x3 = x * x * x;
mx = -x;
max = maxim(absol(x), maxim(mx, maxim(x, x3)));
printf("Maximum value is %.2f\n", max);
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
void main()
{
int base,power,result;
printf("Entr base: ");
scanf("%d", &base);
printf("Entr power: ");
scanf("%d", &power);
result = pow(base,power); //pow function use get power result value
printf("Result is : %d",result);
}
|
C
|
/*
* See Copyright Notice in qnode.h
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "qassert.h"
#include "qengine.h"
#include "qlog.h"
#include "qmempool.h"
#include "qthread_log.h"
#define QRETIRED_FD -1
extern const struct qdispatcher_t epoll_dispatcher;
static void init_qevent(qevent_t *event) {
event->fd = QRETIRED_FD;
event->flags = 0;
event->read = event->write = NULL;
event->data = NULL;
}
static void init_engine_time(qengine_t *engine) {
struct tm tm;
time_t t;
t = time(NULL);
localtime_r(&t, &tm);
strftime(engine->time_buff, sizeof(engine->time_buff), "[%m-%d %T]", &tm);
/*
* convert to ms
*/
engine->now = 1000 * t;
}
qengine_t* qengine_new(qmem_pool_t *pool) {
int i;
qengine_t *engine;
qevent_t *event;
engine = qcalloc(pool, sizeof(qengine_t));
if (engine == NULL) {
goto error;
}
engine->pool = pool;
engine->max_fd = 0;
engine->dispatcher = &(epoll_dispatcher);
if (engine->dispatcher->init(engine) < 0) {
goto error;
}
engine->events = qalloc(pool, sizeof(qevent_t) * QMAX_EVENTS);
if (engine->events == NULL) {
goto error;
}
engine->active_events = qalloc(pool, sizeof(qevent_t) * QMAX_EVENTS);
if (engine->active_events == NULL) {
goto error;
}
for (i = 0; i < QMAX_EVENTS; ++i) {
event = &(engine->events[i]);
init_qevent(event);
event = &(engine->active_events[i]);
init_qevent(event);
}
qtimer_manager_init(&engine->timer_mng, engine);
init_engine_time(engine);
return engine;
error:
if (engine->events) {
qfree(pool, engine->events, sizeof(qevent_t) * QMAX_EVENTS);
}
if (engine->active_events) {
qfree(pool, engine->active_events, sizeof(qevent_t) * QMAX_EVENTS);
}
if (engine) {
engine->dispatcher->destroy(engine);
qfree(pool, engine, sizeof(qengine_t));
}
return NULL;
}
int qengine_add_event(qengine_t *engine, int fd, int flags,
qevent_func_t *callback, void *data) {
qevent_t *event;
if (fd > QMAX_EVENTS) {
qerror("extends max fd");
return -1;
}
event = &(engine->events[fd]);
if (engine->dispatcher->add(engine, fd, flags) < 0) {
qerror("add event error");
return -1;
}
event->fd = fd;
event->flags |= flags;
event->data = data;
if (flags & QEVENT_READ) {
event->read = callback;
}
if (flags & QEVENT_WRITE) {
event->write = callback;
}
if (fd > engine->max_fd) {
engine->max_fd = fd;
}
return 0;
}
int qengine_del_event(qengine_t* engine, int fd, int flags) {
int i;
qevent_t *event;
if (fd > QMAX_EVENTS) {
qerror("extends max fd");
return -1;
}
if (flags == QEVENT_NONE) {
return -1;
}
event = &(engine->events[fd]);
event->flags = event->flags & (~flags);
if (fd == engine->max_fd && event->flags == QEVENT_NONE) {
for (i = engine->max_fd - 1; i > 0; --i) {
if (engine->events[i].flags != QEVENT_NONE) {
engine->max_fd = i;
break;
}
}
}
engine->dispatcher->del(engine, fd, flags);
return 0;
}
int qengine_loop(qengine_t* engine) {
int num, i;
int next;
int flags;
int fd;
int read;
qevent_t *event;
init_engine_time(engine);
next = qtimer_next(&engine->timer_mng);
num = engine->dispatcher->poll(engine, next);
for (i = 0; i < num; i++) {
event = &(engine->events[engine->active_events[i].fd]);
flags = engine->active_events[i].flags;
fd = engine->active_events[i].fd;
read = 0;
if (event->flags & flags & QEVENT_READ) {
read = 1;
event->read(fd, flags, event->data);
}
if (event->flags & flags & QEVENT_WRITE) {
if (!read || event->write != event->read) {
event->write(fd, flags, event->data);
}
}
}
qtimer_process(&(engine->timer_mng));
return 0;
}
void qengine_destroy(qengine_t *engine) {
qmem_pool_t *pool;
pool = engine->pool;
engine->dispatcher->destroy(engine);
qfree(pool, engine->events, sizeof(qevent_t) * QMAX_EVENTS);
qfree(pool, engine->active_events, sizeof(qevent_t) * QMAX_EVENTS);
qfree(pool, engine, sizeof(qengine_t));
}
qid_t qengine_add_timer(qengine_t* engine, uint32_t timeout_ms,
qtimer_func_t *func, int type, void *data) {
return qtimer_add(&engine->timer_mng, timeout_ms, func, type, data);
}
int qengine_del_timer(qengine_t* engine, qid_t id) {
return qtimer_del(&engine->timer_mng, id);
}
|
C
|
#include "mbed.h"
#include <stdarg.h>
#ifndef DEBUG_H_
#define DEBUG_H_
// Prints to a serial port. Max string size is 255.
void inline print_serial(Serial* serial, const char* format, ...)
{
char buffer[256];
va_list args;
va_start (args, format);
vsprintf(buffer, format, args);
buffer[255] = '\0'; //Ensure that the buffer is null terminated.
// We print one character at a time because we drop characters otherwise.
for (int i = 0; buffer[i] != '\0'; i++)
{
while (!serial->writeable());
serial->putc(buffer[i]);
}
va_end(args);
}
//Lights!
extern DigitalOut led1, led2, led3, led4;
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#define BUFSIZE 512
int fifofd;
char* fifoname;
void sig_handler (int sig);
int main (int argc, char *argv[])
{
if (argc != 3) {
printf ("usage: %s < 8-bit (symbols) pattern > <fifo name>\n", argv[0]);
return 1;
}
if (strlen (argv[1]) != 8) {
printf ("usage: %s < 8-bit (symbols) pattern > <fifo name>; pattern is incorrect\n", argv[0]);
return 2;
}
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_handler = sig_handler;
if (sigaction(SIGTERM, &sa, NULL) || sigaction(SIGPIPE, &sa, NULL) || sigaction(SIGINT, &sa, NULL)) {
perror (NULL);
return 6;
}
char pattern = 0;
for (int i = 0; i < 8; i++)
{
if (argv[1][i] == '1')
pattern |= 1 << i;
if (!(argv[1][i] == '0' || argv[1][i] == '1')) {
printf ("usage: %s < 8-bit (symbols) pattern > <fifo name>; pattern is incorrect\n", argv[0]);
return 3;
}
}
char buf[BUFSIZE];
for (int i = 0; i < BUFSIZE; i++)
buf[i] = pattern;
if (mkfifo (argv[2], 0644)) {
perror (NULL);
return 4;
}
fifoname = argv[2];
fifofd = open (fifoname, O_WRONLY);
if (fifofd == -1) {
perror (NULL);
return 5;
}
while (1) {
write (fifofd, buf, BUFSIZE);
}
return 0;
}
void sig_handler (int sig)
{
if (sig == SIGPIPE) {
fifofd = open (fifoname, O_WRONLY);
if (fifofd == -1) {
perror (NULL);
unlink (fifoname);
exit (5);
}
return;
}
if (sig == SIGTERM || sig == SIGINT) {
unlink (fifoname);
exit (0);
}
}
|
C
|
// 210603
// 1100-2.c - 더하기 사이클 sol 2 (Short solution)
#include <stdio.h>
int main()
{
int N, num1, cnt;
// printf("enter num1: ");
scanf("%d", &N);
num1 = N;
cnt = 0;
while(1){
// printf("start while\n");
num1 = num1%10*10 + (num1/10 + num1%10)%10;
cnt ++;
// printf("%d %d\n", cnt, num2);
if(num1 == N){
printf("%d\n", cnt);
break;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
typedef struct { // ʵ
int id;
int primeNumber;
int arrival_time[2];
int service_time;
}element;
typedef struct Atmqueue{// ATM
element data;
struct Atmqueue* link;
}Atm;
typedef struct { // ũ忡ƼŸ ťŸ
Atm* front, * rear;
int leng, service_time;
int getout_customer;
}LinkedAtmType;
void init_atmqueue(LinkedAtmType* q) { // ʱȭ Լ
q->front = NULL;
q->rear = NULL;
q->leng = 0;
q->service_time = 0;
q->getout_customer = 0;
}
int is_empty_Atm(LinkedAtmType* q) { // ִ Ȯ Լ ̸ Ȯ
return (q->leng == 0);
}
void enqueue_Atm(LinkedAtmType* q, element data) { //Ϲ ť
Atm* temp = NULL;
temp = (Atm*)malloc(sizeof(Atm));
if (temp == NULL) exit(1);
temp->data = data;
temp->link = NULL;
if (is_empty_Atm(q)) {
q->front = temp;
q->rear = temp;
}
else {
q->rear->link = temp;
q->rear = temp;
}
q->leng++;
}
element dequeue_Atm(LinkedAtmType* q) { // Ϲ ť
Atm* temp = q->front;
element data;
if (is_empty_Atm(q)) exit(1);
else {
data = temp->data;
q->front = q->front->link;
if (q->front == NULL)
q->rear = NULL;
free(temp);
q->leng--;
return data;
}
}
void dequeuefree_Atm(LinkedAtmType* q) { // ťε ʵ带 ȯϴ Լ-> free
Atm* temp = q->front;
if (is_empty_Atm(q)) exit(1);
else {
q->front = q->front->link;
if (q->front == NULL){
q->rear = NULL;
}
free(temp);
}
}
int sumAnd_delete_primenumber(LinkedAtmType* q, int* time) { // Ҽſ ð ִ Լ ð迭 ̸ ּҸ ڷ
if (is_empty_Atm(q)) return 0;
int sum = 0;
Atm* p= q->front;
Atm* pre = NULL;
Atm* temp;
while (p != q->rear) { // p ť ƴҶ
if (p->data.primeNumber == 1) {
if (p->data.arrival_time[0] == time[0]) // hour ׳ E ٸ 60
sum += time[1] - p->data.arrival_time[1];
else sum += time[1] + 60 - p->data.arrival_time[1];
if (p == q->front) {
q->front = p->link;
temp = p;
p = p->link;
free(temp);
q->leng--;
q->getout_customer++;
}
else {
pre->link = p->link;
temp = p;
p = p->link;
free(temp);
q->leng--;
q->getout_customer++;
}
}
else {
pre = p;
p = p->link;
} // pre ؼ ߰ ִ rear Ű 带
}
if (p->data.primeNumber == 1) {
if (p->data.arrival_time[0] == time[0]) // hour ׳ E ٸ 60
sum += time[1] - p->data.arrival_time[1];
else sum += time[1] + 60 - p->data.arrival_time[1]; // 60
if (p == q->front) {
q->front = NULL;
q->rear = NULL;
free(p);
q->leng--;
q->getout_customer++;
return sum;
}
else if (pre->link == p) {
q->rear = pre;
free(p);
q->leng--;
q->getout_customer++;
}
}
return sum;
}
void vip_insert(LinkedAtmType* q, element data) { // vip Ǿտ ϴ Լ
Atm* temp = (Atm*)malloc(sizeof(Atm));
if (temp == NULL) exit(1);
temp->data = data; //
temp->link = NULL;
if (q->front == NULL && q->rear == NULL) {
q->front = temp;
q->rear = temp;
}
else {
temp->link = q->front;
q->front = temp;
}
q->leng++;
}
int is_prime(int number) { // Ҽ ȮԼ
if (number <= 1) return 0;
if (number == 2) return 1;
for (int i = 2; i < number; i++) {
if (number % i == 0) return 0;
}
return 1;
}
// ̰ ۰ų, atmⰡ ִ , ̰ ؼ
LinkedAtmType* minimum_lengthq(LinkedAtmType* q1, LinkedAtmType* q2, LinkedAtmType* q3) {
if (q1->front == NULL && q1->rear == NULL && q1->service_time == 0) return q1;
else if (q2->front == NULL && q2->rear == NULL && q2->service_time == 0) return q2;
else if (q3->front == NULL && q3->rear == NULL && q3->service_time == 0) return q3;
else {
int arr[3];
int min = q1->leng;
arr[0] = q1->leng;
arr[1] = q2->leng;
arr[2] = q3->leng;
if (q1->leng == q2->leng) {
if (q1->leng == q3->leng) min = arr[rand() % 3];
else if (q1->leng < q3->leng) min = arr[rand() % 2];
else min = arr[2];
}
else if (q1->leng < q2->leng) {
if (q1->leng == q3->leng) {
int k = rand() % 2;
if (k == 1) min = arr[k + 1];
else min = arr[k];
}
else if (q1->leng < q3->leng) min = arr[0];
else arr[2];
}
else {
if (q2->leng > q3->leng) min = arr[2];
else if (q2->leng < q3->leng) min = arr[1];
else min = arr[(rand() % 2) + 1];
}
if (min == q1->leng) return q1;
else if (min == q2->leng) return q2;
else return q3;
}
}
int main(void) {
int hour;
int minutes = 0;
int total_wait = 0;
int total_customers = 0;
int wait_customer = 0;
int total_getout_customer = 0;
LinkedAtmType atmq1; // 3 ť
LinkedAtmType atmq2;
LinkedAtmType atmq3;
init_atmqueue(&atmq1); // 3 ť ʱȭ
init_atmqueue(&atmq2);
init_atmqueue(&atmq3);
srand((unsigned)time(NULL));
for (hour = 9; hour < 11; hour++) {
int vip_number = rand() % 10;
for (minutes = 0; minutes < 60; minutes++) {
element customer;
customer.id = minutes;
customer.arrival_time[0] = hour;
customer.arrival_time[1] = minutes;
customer.primeNumber = is_prime(minutes);
customer.service_time = (rand() % 9) + 2;
LinkedAtmType* min_q = minimum_lengthq(&atmq1, &atmq2, &atmq3); // ּҰ̳ ATM ּҰ min_q ȯ
if (vip_number == minutes % 10 ) { //10ۼƮ Ȯ ٿ Ǿ
vip_insert(min_q, customer);
}
else
enqueue_Atm(min_q, customer);
if ((&atmq1)->service_time > 0) { // ATM⸦ ϴ ִٴ ǹ
(&atmq1)->service_time--;
if ((&atmq1)->service_time == 0) total_customers++;
}
else {
if (!is_empty_Atm(&atmq1)) { //ť ° ƴ ť NULL ƴҶ = ̰ 0 ƴҶ
element data = dequeue_Atm(&atmq1);// dequeue
(&atmq1)->service_time = data.service_time;
if (hour == data.arrival_time[0]) { // ð time[0] = hour ϰ -> ׳ ٸ 60 ؼ
total_wait += minutes - data.arrival_time[1];
}
else
total_wait += minutes +60 - data.arrival_time[1];
printf("%d %d - ", hour, minutes);
printf("%d (%d ҿ) 1 ATM \n", data.id, data.service_time);
}
}
if ((&atmq2)->service_time > 0) {// ATM⸦ ϴ ִٴ ǹ
(&atmq2)->service_time--;
if ((&atmq2)->service_time == 0) total_customers++;
}
else {
if (!is_empty_Atm(&atmq2)) {//ť ° ƴ ť NULL ƴҶ = ̰ 0 ƴҶ
element data = dequeue_Atm(&atmq2);// dequeue
(&atmq2)->service_time = data.service_time;
if (hour == data.arrival_time[0]) { // ð time[0] = hour ϰ -> ׳ ٸ 60 ؼ
total_wait += minutes - data.arrival_time[1];
}
else
total_wait += minutes + 60 - data.arrival_time[1];
printf("%d %d - ", hour, minutes);
printf("%d (%d ҿ) 2 ATM \n", data.id, data.service_time);
}
}
if ((&atmq3)->service_time > 0) {// ATM⸦ ϴ ִٴ ǹ
(&atmq3)->service_time--;
if ((&atmq3)->service_time == 0) total_customers++;
}
else {
if (!is_empty_Atm(&atmq3)) {//ť ° ƴ ť NULL ƴҶ = ̰ 0 ƴҶ
element data = dequeue_Atm(&atmq3);// dequeue
(&atmq3)->service_time = data.service_time;
if (hour == data.arrival_time[0]) {// ð time[0] = hour ϰ -> ׳ ٸ 60 ؼ
total_wait += minutes - data.arrival_time[1];
}
else
total_wait += minutes + 60 - data.arrival_time[1];
printf("%d %d - ", hour, minutes);
printf("%d (%d ҿ) 3 ATM \n", data.id, data.service_time);
}
}
int array[2]; array[0] = hour; array[1] = minutes; // ð 迭 ε 0 1
if ((hour == 9 && minutes != 0 && minutes % 10 == 0)|| (hour == 10 && minutes % 10 == 0) ) { // 9 10
if(!is_empty_Atm(&atmq1))
total_wait += sumAnd_delete_primenumber(&atmq1, array); //sum Ϲ total wait ߰
if (!is_empty_Atm(&atmq2))
total_wait += sumAnd_delete_primenumber(&atmq2, array);//sum Ϲ total wait ߰
if (!is_empty_Atm(&atmq3))
total_wait += sumAnd_delete_primenumber(&atmq3, array);//sum Ϲ total wait ߰
}
}
}
printf(" %d Ҵ.\n", total_customers); // 1 1 Ϸ Ѵ.( ִ )
printf(" ų ٿ Ż %d ٷȴ\n", total_wait / (total_customers
+ (&atmq1)->getout_customer + (&atmq2)->getout_customer + (&atmq3)->getout_customer) ); // 2
printf("ٿ %d ̴\n", (&atmq1)->getout_customer + (&atmq2)->getout_customer + (&atmq3)->getout_customer);
// ð µ ִ° Ҵ
while ((&atmq1)->front != NULL) {
dequeuefree_Atm(&atmq1);
wait_customer++;
}
while ((&atmq2)->front != NULL ) {
dequeuefree_Atm(&atmq2);
wait_customer++;
}
while ((&atmq3)->front != NULL ) {
dequeuefree_Atm(&atmq3);
wait_customer++;
}
printf(" ٸ ִ %d̴.\n", wait_customer);//(3 )
return 0;
}
|
C
|
/////////////////////////////////////////////////////////////////////////////
//
// (c) Copyright 2000-2016 CodeMachine Incorporated. All rights Reserved.
// Developed by CodeMachine Incorporated. (http://www.codemachine.com)
//
/////////////////////////////////////////////////////////////////////////////
#include "ntddk.h"
#pragma warning(disable:4311)
NTSTATUS
DriverEntry(
PDRIVER_OBJECT DriverObject,
PUNICODE_STRING RegistryPath );
VOID
DriverUnload (
PDRIVER_OBJECT DriverObject );
#ifdef ALLOC_PRAGMA
#pragma alloc_text(INIT,DriverEntry)
#endif
NTSTATUS RegisterCallback(
PCALLBACK_FUNCTION CallbackFunction,
PVOID CallbackContext,
PCALLBACK_OBJECT* CallbackObject,
PVOID* CallbackRegistration );
VOID DeregisterCallback(
PCALLBACK_OBJECT CallbackObject,
PVOID CallbackRegistration );
VOID
PowerStateCallback(
PVOID Context,
PVOID Argument1,
PVOID Argument2 );
PCALLBACK_OBJECT g_CallbackObject = NULL;
PVOID g_CallbackRegistration = NULL;
NTSTATUS
DriverEntry(
PDRIVER_OBJECT DriverObject,
PUNICODE_STRING RegistryPath )
{
NTSTATUS Status;
UNREFERENCED_PARAMETER(RegistryPath);
DbgPrint ( "%s DriverObject=%p\n", __FUNCTION__, DriverObject );
DriverObject->DriverUnload = DriverUnload;
// call the function to register the power callback
Status = RegisterCallback (
PowerStateCallback,
DriverObject,
&g_CallbackObject,
&g_CallbackRegistration );
if ( ! NT_SUCCESS(Status) ) {
DbgPrint("%s RegisterCallback() FAIL\n", __FUNCTION__);
} else {
DbgPrint("%s g_CallbackObject=%p g_CallbackRegistration=%p\n", __FUNCTION__,
g_CallbackObject, g_CallbackRegistration);
}
return Status;
} // DriverEntry()
VOID
DriverUnload (
PDRIVER_OBJECT DriverObject )
{
DbgPrint ( "%s DriverObject=%p\n", __FUNCTION__, DriverObject );
// call the function to deregister the power callback
DeregisterCallback(
g_CallbackObject,
g_CallbackRegistration );
} // DriverUnload()
VOID
PowerStateCallback(
PVOID Context,
PVOID Argument1,
PVOID Argument2 )
{
UNREFERENCED_PARAMETER(Context);
if ( ((ULONG)Argument1) == PO_CB_SYSTEM_STATE_LOCK ) {
if ( ((ULONG)Argument2) == 1 ) {
DbgPrint ("%s: Power Up\n", __FUNCTION__ );
} else {
DbgPrint ("%s: Shutdown or Standby\n", __FUNCTION__ );
}
}
} // PowerStateCallback()
NTSTATUS RegisterCallback(
PCALLBACK_FUNCTION CallbackFunction,
PVOID CallbackContext,
PCALLBACK_OBJECT* CallbackObject,
PVOID* CallbackRegistration )
{
OBJECT_ATTRIBUTES ObjectAttributes;
UNICODE_STRING String;
NTSTATUS Status;
PCALLBACK_OBJECT CallbackObjectTemp;
PVOID* CallbackRegistrationTemp;
// Step #1 : Initialize String with \Callback\PowerState (RtlInitUnicodeString())
RtlInitUnicodeString(&String, L"\\Callback\\PowerState");
// Step #2 : Initialize OBJECT_ATTRIBUTES with String (InitializeObjectAttributes())
InitializeObjectAttributes(&ObjectAttributes, &String, OBJ_CASE_INSENSITIVE, NULL, NULL);
// Step #3 : Create the callback (ExCreateCallback())
if (!NT_SUCCESS(Status = ExCreateCallback(&CallbackObjectTemp, &ObjectAttributes, FALSE, TRUE)))
{
DbgPrint("ERROR ExCreateCallback (%d)\n", Status);
goto Exit;
}
// Step #4 : Register the callback (ExRegisterCallback())
if (NULL == (CallbackRegistrationTemp = ExRegisterCallback(CallbackObjectTemp, CallbackFunction, CallbackContext)))
{
DbgPrint("ERROR ExRegisterCallback\n");
goto Exit;
}
*CallbackObject = CallbackObjectTemp;
*CallbackRegistration = CallbackRegistrationTemp;
return STATUS_SUCCESS;
Exit :
// Step #5 : Dereference the callback object (ObDereferenceObject())
if (NULL != CallbackObjectTemp)
{
ObDereferenceObject(CallbackObject);
}
return Status;
} // RegisterCallback()
VOID DeregisterCallback(
PCALLBACK_OBJECT CallbackObject,
PVOID CallbackRegistration )
{
// Step #6 : Deregister the callback (ExUnregisterCallback())
ExUnregisterCallback(CallbackRegistration);
// Step #7 : Dereference the callback object (ObDereferenceObject())
ObDereferenceObject(CallbackObject);
} // DeregisterCallback()
|
C
|
#include <stdio.h> /* for puts, */
#include <stdlib.h> /* for malloc */
#include <assert.h> /* for assert */
#include <string.h> /* for strcmp */
#include "bst.h"
int bstDoCheck = 1;
#define doCheck(_bst) (bstDoCheck)
/* create a new bst */
BST *BSTAlloc() {
BST *bst = (BST *)malloc(sizeof(BST));
bst->root = 0;
doCheck(bst);
return bst;
}
/* Check if employee is a leaf in the bst */
int isLeaf(Employee *e){
if(!e->right && !e->left)
return 1;
return 0;
}
/* return parent node */
struct Employee *getParent(Employee *curr, Employee *prev, char *n) {
if(!curr){
printf("%s is not on the list\n", n);
return curr;
}
/* compare name of current employee with input name*/
int cmp = strcmp(curr->name, n);
/* if value of cmp is 0, strings are equal */
if(cmp == 0)
return prev;
/* if value of cmp is less than 0, input string is after curr employee */
if(cmp < 0){
return getParent(curr->right, curr, n);
}
/* if value of cmp is less than 0, input string is before curr employee */
if(cmp > 0){
return getParent(curr->left, curr, n);
}
return curr;
}
/* append a copy of name to bst */
void bstPut(BST *bst, char *n) {
int len;
char *ncopy;
Employee *e;
doCheck(bst);
/* ncopy = freshly allocated copy of n */
for (len = 0; n[len]; len++) /* compute length */
;
ncopy = (char *)malloc(len+1);
for (len = 0; n[len]; len++) /* copy chars */
ncopy[len] = n[len];
ncopy[len] = 0; /* terminate copy */
/* e = new Employee with copy of name */
e = (Employee *)malloc(sizeof(Employee));
e->name = ncopy;
e->right = 0;
e->left = 0;
/* locate employee in bst */
if(bst->root){
Employee *curr = bst->root;
/* looking for leaf*/
while(curr) {
if(strcmp(curr->name, ncopy)<0){ /* if new employee goes after curr */
if(curr->right == 0){
curr->right = e;
return;
}
curr = curr->right;
}else{
if(curr->left == 0){ /* else new employee goes before curr */
curr->left = e;
return;
}
curr = curr->left;
}
}
}else{
/* if tree is empty */
bst->root = e;
}
}
/* Print employees in ascending order */
void printAsc(Employee *e) {
if(!e){
return;
}
printAsc(e->left);
printf("%s\n", e->name); /* go left, print, go right */
printAsc(e->right);
}
/* Print preorder to file to preserve "balance", and deletes employees that were removed */
void printToFile(FILE *fp, Employee *e) {
if(!e)
return;
fprintf(fp,"%s\n", e->name); /* print, go left, go right */
printToFile(fp, e->left);
printToFile(fp, e->right);
}
/* search and return employee with name n */
struct Employee *search(Employee *e, char *n) {
if(!e){
printf("%s is not on the list\n", n);
return e;
}
/* get value of string comparision between current node and string n */
int cmp = strcmp(e->name, n);
/* if cmp is 0, strings are the same, return curr employee */
if(cmp == 0)
return e;
/* if cmp is less than 0, traverse to right child */
if(cmp < 0)
return search(e->right, n);
/* if cmp is more than 0, traverse to left child */
if(cmp > 0)
return search(e->left, n);
return e;
}
/* Read file and rebuild bst */
BST *readFile(FILE *fp){
BST *bst = BSTAlloc();
char line[255];
char name[255];
while(fgets(line, 255, fp) != NULL)
{
/* get a line, up to 255 chars from fp done if NULL */
sscanf ( line, "%[^\t\n]s",name);
/* add curr name to bst */
bstPut(bst, name);
}
/* print in ascending order, for debugging purposes */
/*printAsc(bst->root);*/
return bst;
}
/* replace parent node with newChild, used for remove fuction */
void replaceInParent(Employee *parent, Employee *child, Employee *newChild){
/* replace right child */
if(parent->right == child)
parent->right = newChild;
/* replace left child */
else if(parent->left == child)
parent->left = newChild;
}
/* get last element on left child of given employee */
struct Employee *getLargestLeft(Employee *e) {
Employee *parent = e; /* set parent as e */
Employee *largest = e->left; /* start at left child */
/* if left employee is leaf replace node with left child */
if(isLeaf(largest)) {
parent->left = 0;
return largest;
}
/* traverse left node to find last employee */
while(!isLeaf(largest)){
parent = largest;
largest=largest->right;
}
/* delete pointer to largest element from immediate parent */
parent->right = 0;
return largest;
}
/* remove employee with employee to be removed, and parent as inputs */
void removeEmployee(Employee *e, Employee *parent){
/* print employee to be removed, for debugging purposes */
/* printf("<%s>\n", e->name);
printf("p: <%s>\n", parent ->name); */
/* if current employee has both children, replace with last element in left child */
if(e->left && e->right){
Employee *newChild = getLargestLeft(e);
e->name = newChild->name;
}
/* if only left child is present, replace node with left child */
else if(e->left){
replaceInParent(parent, e, e->left);
}
/* if only left child is present, replace node with right child */
else if(e->right){
replaceInParent(parent, e, e->right);
}
/* if employee is leaf delete pointer from parent to employee */
else{
if(parent->right == e){
parent->right = 0;
}else{
parent->left = 0;
}
}
}
|
C
|
/* Lista enlazada */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <stdbool.h>
typedef char tString[30];
typedef struct {
tString fecha;
int codigoLoc;
int postivosPorDia;
}tDatos;
typedef struct nodo {
tDatos datosCovid;
struct nodo * siguiente;
} tListaCovid;
void inicializarListaCovid();
bool listaVacia( tListaCovid * );
void insertarDatos( tDatos );
void visualizarDatos( tListaCovid * );
void calcularCasos( tListaCovid * );
void eliminarK( int k );
void eliminarPrimero();
void mostrarCasosLocalidad();
void mostrarLocalidadMayor();
void solicitarDatos();
void menu();
int vector[10];
char * localidadString( int );
void calcularCasosYMostrar(tListaCovid *);
tListaCovid * listaCovid;
void inicializarListaCovid() {
listaCovid = NULL;
}
bool listaVacia( tListaCovid * pLista ) {
return ( pLista == NULL );
}
void insertarDatos( tDatos pDatos ) {
/* Se crea el nodo que se va a insertar */
tListaCovid * nuevoNodo;
/* Se asigna memoria al nodo */
nuevoNodo = ( tListaCovid * ) malloc( sizeof( tListaCovid ) );
/* Se asigna el dato recibido al componente correspondiente al elemento */
nuevoNodo->datosCovid = pDatos;
/* Se indica que el primer nodo apunta a NULL */
if ( listaVacia( listaCovid ) ) {
nuevoNodo->siguiente = NULL;
/* Se agrega el nodo a la lista: la lista debe apuntar al nuevo nodo */
listaCovid = nuevoNodo;
printf("-------------------------------------------------------------" );
printf("\n| Primer dato insertado! |\n");
printf("-------------------------------------------------------------\n" );
}
else{
/* Como la insercin es por la parte de adelante de la lista, se indica que al nuevo nodo le sigue el resto de la lista */
nuevoNodo->siguiente = listaCovid;
/* Como en el nuevo nodo qued la lista completa, nos queda indicar que la lista que se recibe como parmetro es igual a nuevo nodo */
listaCovid = nuevoNodo;
printf("-------------------------------------------------------------" );
printf("\n| Dato insertado! |\n");
printf("-------------------------------------------------------------\n" );
}
}
void visualizarDatos( tListaCovid * pListaCovid ) {
tListaCovid * aux;
aux = pListaCovid;
if( listaVacia(aux) ) {
printf("-------------------------------------------------------------\n" );
printf("| No hay datos en la lista! |\n" );
printf("-------------------------------------------------------------\n" );
}else {
printf("------------------------------------------------------------" );
printf("\n|Seguimiento de COVID-19 en las localidades de la provincia|\n" );
printf("|DIA\tLOCALIDAD\tPOSITIVOS DETECTADOS |\n" );
while ( aux != NULL) {
printf( "|%s\t%i.%s\t\t%i |\n", aux->datosCovid.fecha, aux->datosCovid.codigoLoc,localidadString( aux->datosCovid.codigoLoc ),aux->datosCovid.postivosPorDia);
aux = aux->siguiente;
}
printf("------------------------------------------------------------\n" );
}
}
char * localidadString( int pCodLocalidad ) {
char * localidad;
localidad = ( char * ) malloc( sizeof( char * ) );
/* 1.Capital, 2.Richuelo, 3.Santa Ana, 4.Paso de la Patria, 5.San Cosme */
switch ( pCodLocalidad ) {
case 1: strcpy( localidad, "Capital");
break;
case 2: strcpy( localidad, "Riachuelo");
break;
case 3: strcpy( localidad, "Santa Ana");
break;
case 4: strcpy( localidad, "Paso de la Patria");
break;
case 5: strcpy( localidad, "San Cosme");
break;
default: strcpy( localidad, "error");
}
return localidad;
}
void calcularCasos(tListaCovid * pListaCovid ){
tListaCovid * aux;
aux = pListaCovid;
int i;
for (i = 0; i < 5; i++){
vector[i] = 0;
}
while ( aux != NULL) {
vector[aux->datosCovid.codigoLoc-1]=vector[aux->datosCovid.codigoLoc-1]+aux->datosCovid.postivosPorDia;
aux = aux->siguiente;
}
}
void mostrarCasosLocalidad(){
int i;
calcularCasos( listaCovid );
printf(" Total de casos por localidad\n" );
printf("-------------------------------------------------------------\n" );
for (i = 0; i<5; i++){
printf("|%d.%s -\t%d\t\t\t\t\t|\n", i+1,localidadString( i+1 ), vector[i]);
}
printf("-------------------------------------------------------------\n" );
}
void mostrarLocalidadMayor(){
int i;
int auxMayor = 0;
int localidad = 0;
calcularCasos( listaCovid );
for (i = 0; i <5; i++){
if (vector[i] > auxMayor){
auxMayor = vector[i];
localidad = i+1; }
}
printf("-----------------------------------------------------------------------------\n" );
printf("| La mayor cantidad positivos fue de %i |\n", auxMayor);
printf("| Para el departamento %s |\n", localidadString( localidad ));
printf("-----------------------------------------------------------------------------\n" );
}
void eliminarPrimero(){
tListaCovid * datoSuprimir;
datoSuprimir = listaCovid;
listaCovid = listaCovid->siguiente;
printf("-------------------------------------------------------------\n" );
printf("| Dato eliminado |\n" );
printf("-------------------------------------------------------------\n" );
free( datoSuprimir );
datoSuprimir = NULL;
}
void eliminarK( int k ) {
/* Se debe utilizar una lista auxiliar (aux) */
tListaCovid * aux;
tListaCovid * nodoSuprimir;
int i;
aux = listaCovid;
/* Utilizar un bucle para avanzar aux hasta el nodo K-1 si es igual a 1 elimina el primero */
if( k==1 ) {
eliminarPrimero();
}
else{
for ( i=1; i < k-1; i++) {
aux = aux->siguiente;
}
/* Se resguarda el nodo que se va a suprimir en una variable auxiliar */
nodoSuprimir = aux->siguiente;
/* Se indica a qu nodo tiene que apuntar aux: al siguiente del que se va a eliminar */
aux->siguiente = nodoSuprimir->siguiente;
printf("-------------------------------------------------------------\n" );
printf("| Dato eliminado |\n");
printf("-------------------------------------------------------------\n" );
/* Se libera la memoria del nodo a suprimir que contena el elemento de la posicin K de la lista */
free( nodoSuprimir );
/* Se asigna NULL a la variable auxiliar que guarda el nodo a suprimir */
nodoSuprimir = NULL;
}
}
void solicitarDatos(){
tDatos doc;
char opcion = 's';
while (opcion !='n'){
printf("Ingrese datosCovid por favor: \n");
printf("\tFecha(Formato(dd/mm)): ");
fflush(stdin);
scanf("%[^\n]s", &doc.fecha);
printf("\tCodigo de localidad(1.Capital, 2.Richuelo, 3.Santa Ana, 4.Paso de la Patria, 5.San Cosme)");
scanf("%i", &doc.codigoLoc);
printf("\tCantidad de positivos del dia:");
scanf("%i", &doc.postivosPorDia);
insertarDatos( doc );
printf("Cargar otro? s-n: ");
opcion=getch();
system("cls");
}
}
int main() {
system("color 03"); /* Funcion para colores :D*/
setlocale(LC_ALL, "spanish"); /* Implementacin de caracteres del teclado espaol */
inicializarListaCovid();
menu();
return 0;
}
void menu() {
int opcion;
int k = 0;
printf("****** Diario digital noticiasYa.com ******\n\n");
printf("|Seleccione una opcion por favor|\n");
printf("->1- Cargar datos COVID\n->2- Eliminar Dato\n->3- Visualizar Casos\n");
printf("->4- Visualizar Totales De Casos Por Localidad\n->5- Visualizar Localidad Con Mayor Cantidad De Casos \n->6- Salir \n");
printf("|Seleccione una opcion por favor|\n");
opcion = getch();
system("cls");
switch (opcion) {
case 49:
solicitarDatos();
break;
case 50:
printf("Digite el numero del dato que desea eliminar\n");
scanf("%i", &k);
eliminarK( k );
break;
case 51:
visualizarDatos( listaCovid );
break;
case 52:
mostrarCasosLocalidad();
break;
case 53:
mostrarLocalidadMayor();
break;
case 54:
printf("----------HASTA LA PROXIMA----------"); return ;
break;
}
opcion=0;
printf("|Seleccione una opcion por favor|");
printf("\n->1-Volver al menu\n->2-Salir\n ");
printf("|Seleccione una opcion por favor|\n");
opcion = getch();
system("cls");
switch ( opcion ){
case 49:
menu();
break;
case 50: printf("----------HASTA LA PROXIMA----------"); return;
break;}
}
|
C
|
/*
* Functions etc pertaining to 3d triangle creation.
*/
#ifndef TRIANGLE3D_H
#define TRIANGLE3D_H
#include<stdio.h>
#include "../common/common.h"
#include "../line/line.h"
#include "triangle2d.h"
/*
* Create 3d triangle -- get points in/on a 3d triangle.
* Input -- the 3 corners of a triangle
* a length variable
* Ouput -- returns an array of points
* populates len variable with length of said array
*/
Point* getTriangle3dPoints(Point a, Point b, Point c, size_t* len);
/*
* Draw a 3d Triangle.
* Input -- the 3 corners of a triangle
* Output -- creates the output.obj file required.
*/
void draw3dTriangle(Point a, Point b, Point c);
#endif
|
C
|
#include<stdio.h>
int a,b,resultado;
int i=1;
int main() {
int a,b,resultado;
int i=1;
printf("INGRESE EL PRIMER DIGITO\n");
scanf("%d",&a);
printf("INGRESE EL SEGUNDO DIGITO\n");
scanf("%d",&b);
while(i<=a){
resultado=resultado+b;
i=i+1;
}
printf("EL RESULTADO ES\n %d",resultado);
}
|
C
|
#include "item.h"
void construct_item(Item **item, char *name, char *description, char *feedback_on_use, short effect_type, short effect_value)
{
*item = malloc(sizeof(Item));
// Won't need to type (*item) four times
Item *i = *item;
i->name = name;
i->description = description;
i->feedback_on_use = feedback_on_use;
// 0 = type, 1 = value
i->effect[0] = effect_type;
i->effect[1] = effect_value;
}
void use_item(Item *item, Player *player)
{
printf("%s\n", item->feedback_on_use);
short effect = item->effect[1];
switch (item->effect[0])
{
case AWAKENESS : player->awakeness_percent += effect; break;
case BODY_TEMPERATURE : player->body_temperature_percent += effect; break;
case NOTHING :
default : return;
}
}
void print_item(Item *item)
{
printf("Item { name: %s, description: %s, feedback on use: %s, effect: { %s, %d} }",
item->name,
item->description,
item->feedback_on_use,
item->effect[0] == AWAKENESS ? "awakeness" : "body_temperature",
item->effect[1]
);
}
|
C
|
//
// simplest_rgb24_split.c
// simplest_rgb24_split
//
// Created by angle on 21/03/2018.
// Copyright © 2018 angle. All rights reserved.
//
#include <stdio.h>
//add
#include <stdlib.h>
#include <string.h>
/**
Splicing string exp: splicingString_f("123","456") out:"123456"
@param string_1 string on the left
@param string_2 string on the right
@return new string
*/
char * splicingString_f (char *string_1, char *string_2) {
size_t len = strlen(string_1) + strlen(string_2) + 1;
char * p;
p = (char * ) malloc (len);
memset ( p , 0 , len);
strcpy ( p, string_1);
strcat ( p, string_2);
return p;
}
/**
* Split R, G, B planes in RGB24 file.
* @param url Location of Input RGB file.
* @param w Width of Input RGB file.
* @param h Height of Input RGB file.
* @param outUrl Location of outPut YUV file.
* @return 1-successed, 0-failed
*
*/
int simplest_rgb24_split(char *url, int w, int h,int num, char *outUrl){
FILE *fp=fopen(url,"rb+");
FILE *fp1=fopen(splicingString_f(outUrl, "output_r.y"),"wb+");
FILE *fp2=fopen(splicingString_f(outUrl, "output_g.y"),"wb+");
FILE *fp3=fopen(splicingString_f(outUrl, "output_b.y"),"wb+");
unsigned char *pic=(unsigned char *)malloc(w*h*3);
if (fp != NULL && fp1 != NULL && fp2 != NULL && fp3 != NULL) {
for(int i=0;i<num;i++){
fread(pic,1,w*h*3,fp);
for(int j=0;j<w*h*3;j=j+3){
//R
fwrite(pic+j,1,1,fp1);
//G
fwrite(pic+j+1,1,1,fp2);
//B
fwrite(pic+j+2,1,1,fp3);
}
}
free(pic);
fclose(fp);
fclose(fp1);
fclose(fp2);
fclose(fp3);
fp = NULL;
fp1 = NULL;
fp2 = NULL;
fp3 = NULL;
return 1;
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* tools2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: garouche <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/04/26 18:13:07 by garouche #+# #+# */
/* Updated: 2017/05/03 15:14:35 by garouche ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void change_env_var(char ***environ, char *var, char *new_value)
{
char *ptr;
char *str;
int i;
i = 0;
if (!new_value)
new_value = "";
if ((ptr = find_env(*environ, var)))
{
while ((*environ)[i] && ft_strncmp(var, (*environ)[i], ft_strlen(var)))
i++;
ptr = ft_strjoin(var, "=");
str = ft_strjoin(ptr, new_value);
free(ptr);
ptr = (*environ)[i];
(*environ)[i] = str;
free(ptr);
}
}
int find_builtin(char ***cmd, char ***environ)
{
if (!ft_strcmp((*cmd)[0], "cd"))
{
return (builtin_cd(*cmd, environ));
}
else if (!ft_strcmp((*cmd)[0], "setenv"))
{
return (builtin_setenv(environ, *cmd));
}
else if (!ft_strcmp((*cmd)[0], "unsetenv"))
{
return (builtin_unsetenv(environ, *cmd));
}
else if (!ft_strcmp((*cmd)[0], "env"))
{
return (builtin_env(*environ, *cmd));
}
else if (!ft_strcmp((*cmd)[0], "echo"))
{
aff_env(&(*cmd)[1]);
return (0);
}
return (-1);
}
void dot_dot(char *buf, char *dir)
{
char *ptr;
int i;
i = 0;
if (ft_strcmp(dir, "."))
{
ptr = ft_strrchr((char*)buf, '/');
if ((i = ptr - (char*)buf) > 0)
buf[i] = 0;
else
ft_memcpy(buf, "/", 2);
}
else
{
if (!buf[0])
ft_strcpy(buf, "/");
}
}
char **copy_env(char **env)
{
int i;
char **envcpy;
i = 0;
while (env[i])
i++;
if (!(envcpy = malloc(sizeof(char*) * (i + 1))))
exit(EXIT_FAILURE);
i = 0;
while (env[i])
{
if (!(envcpy[i] = ft_strdup(env[i])))
exit(EXIT_FAILURE);
i++;
}
envcpy[i] = 0;
return (envcpy);
}
void aff_env(char **env)
{
int i;
i = 0;
while (env[i])
{
ft_putstr(env[i++]);
ft_putchar('\n');
}
}
|
C
|
#include <stdio.h>
int main(int argc, char** argv) {
int sum = 0;
for (int i = 0; i < 1001; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
printf("The sum: %i\n", sum);
return 0;
}
|
C
|
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
struct alarm
{
int seconds;
char message[64];
};
void *alarm_thread(struct alarm *a)
{
int status = pthread_detach(pthread_self());
if (status != 0)
{
fprintf(stderr, "pthread_detach: %s\n", strerror(status));
exit(EXIT_FAILURE);
}
sleep(a->seconds);
printf("(%d) %s\n", a->seconds, a->message);
free(a);
return NULL;
}
int main(void)
{
int status;
char line[128];
struct alarm *a;
pthread_t thread;
while (printf("Alarm> ") && fgets(line, sizeof(line), stdin))
{
if (strlen(line) <= 1)
continue;
if (!(a = malloc(sizeof(*a))))
{
fputs("Failed to allocate alarm\n", stderr);
return EXIT_FAILURE;
}
if (sscanf(line, "%d %64[^\n]", &a->seconds, a->message) < 2)
{
fputs("Bad command\n", stderr);
free(a);
}
else
{
status = pthread_create(&thread, NULL, (void *(*)(void*))alarm_thread, a);
if (status != 0)
{
fprintf(stderr, "pthread_create: %s\n", strerror(status));
return EXIT_FAILURE;
}
}
}
}
|
C
|
#include "crypt_helper.h"
#include "aes_vector.h"
global_variable u8 GlobalScratch[AES_TEST_MAX_MSG_SIZE];
internal b32
AesVectorsPass(aes_test_vector *TestVector, u32 VectorCount)
{
Stopif(TestVector == 0, "Null input to TestAesVectors");
b32 Result = true;
for (u32 TestVecIndex = 0;
TestVecIndex < VectorCount;
++TestVecIndex, ++TestVector)
{
Stopif(TestVector->MessageLength > AES_TEST_MAX_MSG_SIZE, "Test vector length too large");
// NOTE(bwd): Test encrypt/decrypt in place
memcpy(GlobalScratch, TestVector->Message, TestVector->MessageLength);
AesEcbEncrypt(GlobalScratch, GlobalScratch, TestVector->MessageLength, TestVector->Key);
Result = AreVectorsEqual(GlobalScratch, TestVector->Cipher, TestVector->MessageLength);
if (Result == false)
{
break;
}
memcpy(GlobalScratch, TestVector->Cipher, TestVector->MessageLength);
AesEcbDecrypt(GlobalScratch, GlobalScratch, TestVector->MessageLength, TestVector->Key);
Result = AreVectorsEqual(GlobalScratch, TestVector->Message, TestVector->MessageLength);
if (Result == false)
{
break;
}
}
return Result;
}
internal MIN_UNIT_TEST_FUNC(TestAesVectors)
{
MinUnitAssert(AesVectorsPass(GlobalAesVectors, ARRAY_LENGTH(GlobalAesVectors)),
"Expected/Actual mismatch in TestVector()");
}
int main()
{
TestAesVectors();
printf("All tests passed!\n");
}
|
C
|
//
// main.c
// 8.2
//
// Created by 林斌 on 2017/6/12.
// Copyright © 2017年 林斌. All rights reserved.
//
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
char c = 0;
int flag = 0;
int count = 0;
FILE* file_name = fopen("D:\\abc2.txt", "w");
//fputc(c, stdout);
while ((c = getchar()) != EOF)
{
count++;
if (c == '\n') count = 0;
if (count == 1)
{
if ('a' <= c&&c <= 'z')
{
fputc(c + 'A' - 'a', file_name);
flag = 0;
continue;
}
else
{
fputc(c, file_name);
continue;
}
}
if (c == ' ') flag = 1;
if ('a' <= c&&c <= 'z')
{
if (flag == 1)
{
fputc(c + 'A' - 'a', file_name);
flag = 0;
}
else fputc(c, file_name);
}
else fputc(c, file_name);
}
system("PAUSE");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../include/radixHashJoin.h"
//Create new node to add to list
resultNode * createNode() {
resultNode * newNode;
if ((newNode = malloc(sizeof(resultNode))) == NULL) {
return NULL;
}
//initialize newNode
newNode->next = NULL;
newNode->num_of_elems = 0;
for (int i=0; i<ARRAYSIZE; i++) {
newNode->array[i].rowId1 = -1;
newNode->array[i].rowId2 = -1;
}
return newNode;
}
result* createList() {
result* list;
if ((list = malloc(sizeof(result))) == NULL) {
return NULL;
}
list->head = createNode();
if (list->head == NULL) {
return NULL;
}
return list;
}
//Create result as a list of arrays
int insertToList(result** list, tuple RItemTuple, tuple SItemTuple) {
if (*list == NULL) {
*list = createList();
}
resultNode *temp = (*list)->head;
while (temp->num_of_elems == ARRAYSIZE) {
if (temp->next == NULL) {
temp->next = createNode();
}
temp = temp->next;
}
//insert to current node (new node)
temp->array[temp->num_of_elems].rowId1 = RItemTuple.rowId;
temp->array[temp->num_of_elems].rArrayRow1 = RItemTuple.rArrayRow;
temp->array[temp->num_of_elems].rowId2 = SItemTuple.rowId;
temp->array[temp->num_of_elems].rArrayRow2 = SItemTuple.rArrayRow;
temp->num_of_elems++;
return 0;
}
void printList(result * list) {
resultNode * curr = list->head;
printf("1st Relation's RowID (R)--------2nd Relation's RowID (S)\n");
while (curr != NULL) {
for (int i=0; i < curr->num_of_elems; i++) {
printf("%8d %31d\n", curr->array[i].rowId1, curr->array[i].rowId2);
}
curr = curr->next;
}
return;
}
void deleteList(result ** list) {
if(list == NULL || *list == NULL)
return;
resultNode * curr = (*list)->head;
if(curr == NULL)
return;
resultNode * prev;
while (curr->next != NULL) {
prev = curr;
curr = curr->next;
free(prev);
}
free(curr);
free(*list);
*list = NULL;
return;
}
//H1 for bucket selection, get last 3 bits
int hashFunction1(uint64_t value){
return value & HEXBUCKETS;
}
//H2 for indexing in buckets, get last 4 bits
int hashFunction2(uint64_t value){
return value & HEXHASH2;
}
//create relation array for field
relation* createRelation(uint64_t* col, uint64_t* rowIds, uint64_t noOfElems){
relation* rel = malloc(sizeof(relation));
rel->tuples = malloc(noOfElems*sizeof(tuple));
for (int i = 0; i < noOfElems; i++){
if (rowIds == NULL) {
rel->tuples[i].rowId = i;
} else {
rel->tuples[i].rowId = rowIds[i];
}
rel->tuples[i].value = col[i];
rel->tuples[i].rArrayRow = -1;
}
rel->num_tuples = noOfElems;
return rel;
}
void deleteRelation(relation** rel){
if(*rel == NULL)
return;
if((*rel)->tuples == NULL){
free(*rel);
*rel = NULL;
return;
}
free((*rel)->tuples);
(*rel)->tuples = NULL;
free(*rel);
*rel = NULL;
}
void printRelation(relation* rel){
printf("Relation has %d tuples\n",rel->num_tuples);
for (int i=0;i<rel->num_tuples;i++){
printf("Row with rowId: %ld and value: %ld\n",rel->tuples[i].rowId,rel->tuples[i].value);
}
}
// Create the Histogram, where we store the number of elements corresponding with each hash value
// The size of tuples array is the number of buckets (one position for each hash value)
relation* createHistogram(relation* R){
if(R == NULL)
return NULL;
if(R->tuples == NULL || R->num_tuples == 0)
return NULL;
relation* Hist = malloc(sizeof(relation));
Hist->num_tuples = BUCKETS;
Hist->tuples = malloc(BUCKETS * sizeof(tuple));
//initialize Hist
for(int i=0;i<Hist->num_tuples;i++){
Hist->tuples[i].rowId = i;
Hist->tuples[i].value = 0;
}
//populate Hist
for(int i=0;i<R->num_tuples;i++){
int bucket = hashFunction1(R->tuples[i].value);
Hist->tuples[bucket].value++;
}
return Hist;
}
// Create Psum just like histogram, but for different purpose
// We calculate the position of the first element from each bucket in the new ordered array
relation* createPsum(relation* Hist){
if(Hist == NULL)
return NULL;
if(Hist->tuples == NULL || Hist->num_tuples == 0)
return NULL;
relation* Psum = malloc(sizeof(relation));
Psum->num_tuples = BUCKETS;
Psum->tuples = malloc(BUCKETS * sizeof(tuple));
uint32_t sum = 0;
for(int i=0;i<Psum->num_tuples;i++){
Psum->tuples[i].rowId = Hist->tuples[i].rowId;
if (Hist->tuples[i].value == 0)
Psum->tuples[i].value = -1; // If there is no item for a hash value, we write -1
else
Psum->tuples[i].value = sum;
sum += Hist->tuples[i].value;
}
return Psum;
}
// Create the new ordered array (R')
relation* createROrdered(relation* R, relation* Hist, relation* Psum){
if(R == NULL || Hist == NULL || Psum == NULL)
return NULL;
if(R != NULL){
if(R->tuples == NULL)
return NULL;
}
if(Hist != NULL){
if(Hist->tuples == NULL)
return NULL;
}
if(Psum != NULL){
if(Psum->tuples == NULL)
return NULL;
}
// Allocate a relation array same as R
relation* ROrdered = malloc(sizeof(relation));
ROrdered->num_tuples = R->num_tuples;
ROrdered->tuples = malloc(ROrdered->num_tuples * sizeof(tuple));
// Create a copy of Histogram, so as to use it while filling in the new ordered array
// Whenever we copy an element from old array to the new one, reduce the counter of its hist id (in RemainHist)
// In this way, we read the old array only one time - complexity O(n) (n = R->num_tuples)
// We copy all the elements one by one, in the proper position of the new array
relation* RemainHist = malloc(sizeof(relation));
RemainHist->num_tuples = Hist->num_tuples;
RemainHist->tuples = malloc(RemainHist->num_tuples * sizeof(tuple));
for (int i = 0; i < Hist->num_tuples; i++) {
RemainHist->tuples[i].rowId = Hist->tuples[i].rowId;
RemainHist->tuples[i].value = Hist->tuples[i].value;
}
// Now copy the elements of old array to the new one by buckets (ordered)
for (int i = 0; i < R->num_tuples; i++) {
int hashId = hashFunction1(R->tuples[i].value);
int offset = Hist->tuples[hashId].value - RemainHist->tuples[hashId].value; // Total hash items - hash items left
int ElementNewPosition = Psum->tuples[hashId].value + offset; // Position = bucket's position + offset
RemainHist->tuples[hashId].value--;
ROrdered->tuples[ElementNewPosition].rArrayRow = R->tuples[i].rArrayRow;
ROrdered->tuples[ElementNewPosition].rowId = R->tuples[i].rowId; // Copy the element form old to new array
ROrdered->tuples[ElementNewPosition].value = R->tuples[i].value;
}
// Delete the RemainHist Array
deleteRelation(&RemainHist);
return ROrdered;
}
// Create indexes for each bucket in the smaller one, compare the items of bigger with smaller's and finally join the same values (return in the list rowIds)
// We create indexes for each bucket, one by one, for the smaller bucket of the 2 arrays (for optimization)
int indexCompareJoin(result* ResultList, relation* ROrdered, relation* RHist, relation* RPsum, relation* SOrdered, relation* SHist, relation* SPsum) {
for (int i = 0; i < BUCKETS; i++) {
// Find which of the 2 buckets (from R and S array) is the smaller one, in order to create the index in that one
relation *smallOrdered, *smallHist, *smallPsum, *bigOrdered, *bigHist, *bigPsum;
if (RHist->tuples[i].value < SHist->tuples[i].value) {
smallOrdered = ROrdered;
smallHist = RHist;
smallPsum = RPsum;
bigOrdered = SOrdered;
bigHist = SHist;
bigPsum = SPsum;
}
else {
smallOrdered = SOrdered;
smallHist = SHist;
smallPsum = SPsum;
bigOrdered = ROrdered;
bigHist = RHist;
bigPsum = RPsum;
}
int itemsInSmallBucket = smallHist->tuples[i].value;
int chain[itemsInSmallBucket];
int bucket[HASH2];
for (int j = 0; j < HASH2; j++) { // Initialize bucket array with -1
bucket[j] = -1;
}
// Create the index for smaller bucket with a second hash value
for (int j = 0; j < itemsInSmallBucket; j++){
int itemSmallOrderedOffset = smallPsum->tuples[i].value + j;
int hash2Id = hashFunction2(smallOrdered->tuples[itemSmallOrderedOffset].value);
if (bucket[hash2Id] == -1)
chain[j] = -1; // The first item hashed (2) with current value, is set to -1
else chain[j] = bucket[hash2Id]; // Write the last position to chain and current to bucket array
bucket[hash2Id] = j;
}
// Print Chain and Bucket arrays (indexing on smaller bucket)
if (PRINT) {
char arrayStr[3];
if (RHist->tuples[i].value < SHist->tuples[i].value)
strcpy(arrayStr, "R");
else strcpy(arrayStr, "S");
}
// Search all the items from unindexed bigger bucket in the same bucket and compare them with smaller's
int itemsInBigBucket = bigHist->tuples[i].value;
for (int j = 0; j < itemsInBigBucket; j++){
int itemBigOrderedOffset = bigPsum->tuples[i].value + j;
int hash2Id = hashFunction2(bigOrdered->tuples[itemBigOrderedOffset].value);
if (bucket[hash2Id] != -1) {
int currentInChain = bucket[hash2Id]; // Search each item from bigger to the similarly hashed ones from smaller (help from bucket and chain)
do {
int itemSmallOrderedOffset = smallPsum->tuples[i].value + currentInChain;
if (smallOrdered->tuples[itemSmallOrderedOffset].value == bigOrdered->tuples[itemBigOrderedOffset].value) {
int itemROrderedOffset, itemSOrderedOffset;
if (RHist->tuples[i].value < SHist->tuples[i].value) {
itemROrderedOffset = itemSmallOrderedOffset;
itemSOrderedOffset = itemBigOrderedOffset;
} // First field of result tuples is for R's rowId while second for S's rowId
else {
itemROrderedOffset = itemBigOrderedOffset;
itemSOrderedOffset = itemSmallOrderedOffset;
}
if (insertToList(&ResultList, ROrdered->tuples[itemROrderedOffset], SOrdered->tuples[itemSOrderedOffset])) {
printf("Error\n");
return -1; // Insert the rowIds of same valued tuples in Result List (if error return)
}
}
currentInChain = chain[currentInChain]; // Go on in chain to compare other similar items of smaller with the current one from bigger
} while (currentInChain != -1); // When a chain item is -1, then there is no similar tuple from smaller left
}
}
}
return 0;
}
// Create Histogram with thread
void createHistogramThread(histArgs* args){
relation* R = args->R;
relation** Hist = args->Hist;
if(R == NULL)
return;
if(R->tuples == NULL || R->num_tuples == 0)
return;
*Hist = malloc(sizeof(relation));
(*Hist)->num_tuples = BUCKETS;
(*Hist)->tuples = malloc(BUCKETS * sizeof(tuple));
//initialize Hist
for(int i=0;i<(*Hist)->num_tuples;i++){
(*Hist)->tuples[i].rowId = i;
(*Hist)->tuples[i].value = 0;
}
//populate Hist
for(int i=0;i<R->num_tuples;i++){
int bucket = hashFunction1(R->tuples[i].value);
(*Hist)->tuples[bucket].value++;
}
}
void indexCompareJoinThread(indexCompareJoinArgs* args) {
result* ResultList = args->ResultList;
relation* ROrdered = args->ROrdered;
relation* RHist = args->RHist;
relation* RPsum = args->RPsum;
relation* SOrdered = args->SOrdered;
relation* SHist = args->SHist;
relation* SPsum = args->SPsum;
int i = args->currentBucket;
// Find which of the 2 buckets (from R and S array) is the smaller one, in order to create the index in that one
relation *smallOrdered, *smallHist, *smallPsum, *bigOrdered, *bigHist, *bigPsum;
if (RHist->tuples[i].value < SHist->tuples[i].value) {
smallOrdered = ROrdered;
smallHist = RHist;
smallPsum = RPsum;
bigOrdered = SOrdered;
bigHist = SHist;
bigPsum = SPsum;
}
else {
smallOrdered = SOrdered;
smallHist = SHist;
smallPsum = SPsum;
bigOrdered = ROrdered;
bigHist = RHist;
bigPsum = RPsum;
}
int itemsInSmallBucket = smallHist->tuples[i].value;
int chain[itemsInSmallBucket];
int bucket[HASH2];
for (int j = 0; j < HASH2; j++) { // Initialize bucket array with -1
bucket[j] = -1;
}
// Create the index for smaller bucket with a second hash value
for (int j = 0; j < itemsInSmallBucket; j++){
int itemSmallOrderedOffset = smallPsum->tuples[i].value + j;
int hash2Id = hashFunction2(smallOrdered->tuples[itemSmallOrderedOffset].value);
if (bucket[hash2Id] == -1)
chain[j] = -1; // The first item hashed (2) with current value, is set to -1
else chain[j] = bucket[hash2Id]; // Write the last position to chain and current to bucket array
bucket[hash2Id] = j;
}
// Print Chain and Bucket arrays (indexing on smaller bucket)
if (PRINT) {
char arrayStr[3];
if (RHist->tuples[i].value < SHist->tuples[i].value)
strcpy(arrayStr, "R");
else strcpy(arrayStr, "S");
}
// Search all the items from unindexed bigger bucket in the same bucket and compare them with smaller's
int itemsInBigBucket = bigHist->tuples[i].value;
for (int j = 0; j < itemsInBigBucket; j++){
int itemBigOrderedOffset = bigPsum->tuples[i].value + j;
int hash2Id = hashFunction2(bigOrdered->tuples[itemBigOrderedOffset].value);
if (bucket[hash2Id] != -1) {
int currentInChain = bucket[hash2Id]; // Search each item from bigger to the similarly hashed ones from smaller (help from bucket and chain)
do {
int itemSmallOrderedOffset = smallPsum->tuples[i].value + currentInChain;
if (smallOrdered->tuples[itemSmallOrderedOffset].value == bigOrdered->tuples[itemBigOrderedOffset].value) {
int itemROrderedOffset, itemSOrderedOffset;
if (RHist->tuples[i].value < SHist->tuples[i].value) {
itemROrderedOffset = itemSmallOrderedOffset;
itemSOrderedOffset = itemBigOrderedOffset;
} // First field of result tuples is for R's rowId while second for S's rowId
else {
itemROrderedOffset = itemBigOrderedOffset;
itemSOrderedOffset = itemSmallOrderedOffset;
}
if (insertToList(&ResultList, ROrdered->tuples[itemROrderedOffset], SOrdered->tuples[itemSOrderedOffset])) {
printf("Error\n");
return; // Insert the rowIds of same valued tuples in Result List (if error return)
}
}
currentInChain = chain[currentInChain]; // Go on in chain to compare other similar items of smaller with the current one from bigger
} while (currentInChain != -1); // When a chain item is -1, then there is no similar tuple from smaller left
}
}
}
|
C
|
// $Id: raw2hist.C 3406 2015-06-26 06:13:58Z onuchin $
// Author: Valeriy Onuchin 28.07.2011
/*************************************************************************
* *
* Copyright (C) 2011, Valeriy Onuchin *
* All rights reserved. *
* *
*************************************************************************/
#include <stdio.h>
#include "TString.h"
#include "TH1F.h"
#include "TFile.h"
#include "TNtuple.h"
#include "TStyle.h"
#include "TF1.h"
#include "TMath.h"
#include "TROOT.h"
TString rtitle = "Red color hist ";
TString gtitle = "Green color hist ";
TString btitle = "Blue color hist ";
TH1F *red = 0;
TH1F *green = 0;
TH1F *blue = 0;
TNtuple *tuple = 0;
TFile *rootfile = 0;
TString doseFname;
int nullDoseChannel = 0;
int minDoseChannel = 0;
Bool_t nullDoseProcessing = false;
Double_t minDose = 0.05; // hardcoded
Double_t nullDose = 0.05;
Bool_t minDoseProcessing = false;
int nFileProcessed = 0;
//___________________________________________________________________
float GetDoseFromName(const char *fname)
{
// Parse file name and extract dose
float dose = 0;
TString str = fname;
int idx = str.Index("Gy");
str = str(0, idx);
idx = str.Index("_");
str = str(idx + 1, str.Length());
idx = str.Index("_");
if (idx > 0 && !str.BeginsWith("0")) {
str = str(idx + 1, str.Length());
}
if (str.EndsWith("_")) {
str.Chop();
}
str.ReplaceAll("_", ".");
dose = atof(str.Data());
return dose;
}
//______________________________________________________________________________
void raw2hist(const char *file)
{
// read RAW data file and create hists
TString fname = file;
FILE *fp = fopen(file, "rb");
if (!fp) {
fprintf(stderr, "Failed to open file: %s", file);
return;
}
printf("Processing file - %s ", file);
UInt_t w, h;
fread(&w, sizeof(w), 1, fp);
fread(&h, sizeof(h), 1, fp);
long sz = w*h*3;
unsigned short *rgb = new unsigned short[sz];
fread(rgb, sizeof(short), sz, fp);
fclose(fp);
TString str;
int orient = fname.BeginsWith("L") ? 0 : 1; // landscape - 0, portrait - 1
if (!rootfile) {
if (orient) {
doseFname = "dosePortrait.root";
} else {
doseFname = "doseLandscape.root";
}
rootfile = new TFile(doseFname, "RECREATE");
}
float dose = GetDoseFromName(fname);
printf("dose = %f\n", dose);
nFileProcessed++;
nullDoseProcessing = false;
if (dose < nullDose) { // null dose
dose = nullDose;
nullDoseProcessing = true;
}
minDoseProcessing = false;
if (nFileProcessed == 2) { // hardcode min dose
minDoseProcessing = true;
}
str = rtitle;
str += TString::Format("(%3.1f", dose);
str += " Gy)";
red = new TH1F(fname + " red", str.Data(), 1000, 0, 66000); // 65536
red->SetFillColor(2);
str = gtitle;
str += TString::Format("(%3.1f", dose);
str += " Gy)";
green = new TH1F(fname + " green", str.Data(), 1000, 0, 66000);
green->SetFillColor(3);
str = btitle;
str += TString::Format("(%3.1f", dose);
str += " Gy)";
blue = new TH1F(fname + " blue", str.Data(), 1000, 0, 66000);
blue->SetFillColor(4);
if (!tuple) {
tuple = new TNtuple("dose", "Dose vs 16 bit color",
"dose:r:g:b:sr:sg:sb:mr:mg:mb");
}
Float_t r, g, b;
long n = w*h;
long j = 0;
for (long i = 0; i < n; i++) {
r = rgb[j];
red->Fill(r);
g = rgb[++j];
green->Fill(g);
b = rgb[++j];
blue->Fill(b);
j++;
}
TF1 *fblue = new TF1("gaus", "gaus", blue->GetMean() - blue->GetRMS(),
blue->GetMean() + blue->GetRMS());
fblue->SetLineColor(1);
blue->Fit("gaus", "Q");
TF1 *fgreen = new TF1("gaus", "gaus", green->GetMean() - green->GetRMS(),
green->GetMean() + green->GetRMS());
fgreen->SetLineColor(1);
green->Fit("gaus", "Q");
TF1 *fred = new TF1("gaus", "gaus", red->GetMean() - red->GetRMS(),
red->GetMean() + red->GetRMS());
fred->SetLineColor(1);
red->Fit("gaus", "Q");
if (nullDoseProcessing) {
nullDoseChannel = (Int_t)fred->GetParameter(1);
printf("null dose channel = %d\n", nullDoseChannel);
}
if (minDoseProcessing) {
minDoseChannel = (Int_t)fred->GetParameter(1);
printf("minimum dose = %f, channel = %d\n", minDose, minDoseChannel);
}
gStyle->SetOptFit(111);
gStyle->SetOptStat(1111111);
tuple->Fill(dose, (Float_t)fred->GetParameter(1),
(Float_t)fgreen->GetParameter(1), (Float_t)fblue->GetParameter(1),
(Float_t)fred->GetParameter(2), (Float_t)fgreen->GetParameter(2),
(Float_t)fblue->GetParameter(2), (Float_t)red->GetMean(),
(Float_t)green->GetMean(), (Float_t)blue->GetMean());
delete [] rgb;
//delete red;
//delete green;
//delete blue;
}
|
C
|
/************************************************************************************************
*Define la estructura y funciones asociadas para un Nodo a ser utilizado en listas encadenadas *
*Un nodo esta formado por : *
*- info : la informacion contenida por el nodo *
*- next : un puntero al siguiente nodo *
*************************************************************************************************/
#ifndef LINKNODEOFFSET_H
#define LINKNODEOFFSET_H
typedef struct NodeStackOffset {
int *info;
struct NodeStackOffset *next;
} NodeStackOffset;
/*funciones publicas para manipular nodos*/
/*constructores*/
NodeStackOffset* new_link_node_offset();
NodeStackOffset* new_link_node_offset_info(int info);
NodeStackOffset* new_link_node_offset_info_next(int info, NodeStackOffset *next);
/*lectura de informacion*/
int get_info_link_node_offset(NodeStackOffset *node);
NodeStackOffset* get_next_link_node_offset(NodeStackOffset *node);
/*escritura de informacion*/
void set_info_link_node_offset(NodeStackOffset *node, int info);
void set_next_link_node_offset(NodeStackOffset *node, NodeStackOffset *next);
#endif
|
C
|
#include "config.h"
#include <gem.h>
#include <time.h>
#include "debug.h"
/* 1024 entries, means at least 8 KB, plus 8 bytes per string,
* plus the lengths of strings
*/
#define TH_BITS 10
#define TH_SIZE (1 << TH_BITS)
#define TH_MASK (TH_SIZE - 1)
#define TH_BMASK ((1 << (16 - TH_BITS)) - 1)
/*
* set this to one to first hash addresses in RAM before
* computing actual string hashes. (experimental)
*/
#define USE_RAM_HASH 0
#if USE_RAM_HASH
static char *ram_hash[(TH_SIZE + 10) * 2];
#endif
/* initialisation */
void nls_init(nls_domain *domain)
{
domain->hash = NULL;
nls_gettext_init(domain);
}
void nls_gettext_init(nls_domain *domain)
{
(void) domain;
#if USE_RAM_HASH
memset(ram_hash, 0, sizeof(ram_hash));
#endif
}
unsigned int nls_hash(const char *t)
{
const unsigned char *u = (const unsigned char *) t;
unsigned short a, b;
a = 0;
while (*u)
{
a = (a << 1) | ((a >> 15) & 1);
a += *u++;
}
b = (a >> TH_BITS) & TH_BMASK;
a &= TH_MASK;
a ^= b;
return a;
}
char *nls_dgettext(const nls_domain *domain, const char *key)
{
unsigned int hash;
const char *const *chain;
const char *cmp;
/* check for empty string - often used in RSC - must return original address */
if (domain == NULL || key == NULL || *key == '\0' || domain->hash == NULL)
return (char *)NO_CONST(key);
hash = nls_hash(key);
if ((chain = domain->hash[hash]) != NULL)
{
while ((cmp = *chain++) != NULL)
{
if (strcmp(cmp, key) == 0)
{
/* strings are equal, return next string */
key = *chain;
break;
}
/* the strings differ, next */
chain++;
}
}
/* not in hash, return original string */
#if USE_RAM_HASH
store_ram_hash();
#else
return (char *)NO_CONST(key);
#endif
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define EXEC_PATH "./ex3"
int main(int argc, char *argv[]) {
pid_t id = fork();
if (id == 0) {
/* Child process executes command */
/* Memory allocation for the arguments */
char **command_args = malloc((argc) * sizeof(char));
/* Arguments are all entities without the name of executed program */
for (int i = 0; i < argc - 1; ++i) {
command_args[i] = argv[i + 1];
}
/* Execution! */
execve(EXEC_PATH, command_args, NULL);
} else if (id > 0) {
/* Parent process waits */
pid_t status;
waitpid(id, &status, 0);
} else {
return -1;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <stdlib.h>
#define PORT 1234
#define BACKLOG 1
#define Max 5 //設定連線人數上限
#define MAXSIZE 1024
struct userinfo {
char id[100];
int playwith;
};
int fdt[Max] = {0};
char mes[1024];
int SendToClient(int fd, char* buf, int Size);
struct userinfo users[100];
int find_fd(char *name);
int win_dis[8][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}};
void message_handler(char *mes, int sender)
{
int instruction = 0, i;
sscanf (mes, "%d", &instruction);
switch (instruction)
{
//新增一個使用者
case 1: {
char name[100];
sscanf (mes, "1 %s", name);
strncpy (users[sender].id, name, 100);
send(sender, "1", 1, 0);
printf("1:%s\n", name);
break;
}
//顯示所有使用者
case 2:{
char buf[MAXSIZE], tmp[100];
int p = sprintf(buf, "2 ");
for (i = 0; i < 100; i++){
if (strcmp(users[i].id, "") != 0){
sscanf(users[i].id, "%s", tmp);
p = sprintf(buf+p,"%s ", tmp) + p;
}
}
printf("2:%s\n", buf);
send(sender, buf, strlen(buf),0);
break;
}
//邀請玩家
case 3:{
char a[100], b[100];
char buf[MAXSIZE];
sscanf (mes, "3 %s %s", a, b);
int b_fd = find_fd(b);
sprintf(buf, "4 %s 來玩 ⭕ ⭕ ❌ ❌ ,要不要隨便你?\n", a);
send(b_fd, buf, strlen(buf), 0);
printf("3:%s", buf);
break;
}
//是否接受邀請
case 5:{
int agree;
char inviter[100];
sscanf(mes, "5 %d %s", &agree, inviter);
//同意開始
if (agree == 1){
send(sender, "6\n", 2, 0);
send(find_fd(inviter), "6\n", 2, 0);
int fd = find_fd(inviter);
users[sender].playwith = fd;
users[fd].playwith = sender;
printf("6:\n");
}
break;
}
//處理棋盤
case 7:{
int board[9];
char state[100], buf[MAXSIZE];
sscanf(mes, "7 %d %d %d %d %d %d %d %d %d", &board[0], &board[1], &board[2], &board[3], &board[4], &board[5], &board[6], &board[7], &board[8]);
for (i = 0; i < 100; i++)
state[i] = '\0';
memset(buf, '\0', MAXSIZE);
memset(state, '\0', sizeof(state));
strcat(state, users[sender].id);
for (i = 0; i < 8; i++) {
if (board[win_dis[i][0]] == board[win_dis[i][1]] && board[win_dis[i][1]] == board[win_dis[i][2]]) {
if (board[win_dis[i][0]] != 0) {
strcat(state, "_Win!\n");
sprintf (buf, "8 %d %d %d %d %d %d %d %d %d %s\n", board[0], board[1], board[2], board[3], board[4], board[5], board[6], board[7], board[8], state);
printf ("7:%s",buf);
send(sender, buf, sizeof(buf), 0);
send(users[sender].playwith, buf, sizeof(buf), 0);
return;
}
}
}
memset(buf, '\0', MAXSIZE);
memset(state, '\0', sizeof(state));
//平手
for (i = 0; i < 9; i++) {
if (i == 8) {
strcat(state, "平手啦!\n");
sprintf (buf, "8 %d %d %d %d %d %d %d %d %d %s\n", board[0], board[1], board[2], board[3], board[4], board[5], board[6], board[7], board[8], state);
printf ("7:%s", buf);
send(sender, buf, sizeof(buf), 0);
send(users[sender].playwith, buf, sizeof(buf), 0);
return;
}
if (board[i] == 0)
break;
}
memset(buf,'\0', MAXSIZE);
memset(state,'\0', sizeof(state));
strcat(state, users[users[sender].playwith].id);
strcat(state, "的回合!\n");
sprintf(buf,"8 %d %d %d %d %d %d %d %d %d %s\n", board[0], board[1], board[2], board[3], board[4], board[5], board[6], board[7], board[8], state);
printf("7:%s", buf);
send(sender, buf, sizeof(buf), 0);
send(users[sender].playwith, buf, sizeof(buf), 0);
break;
}
}
}
void *pthread_service(void* sfd)
{
int fd = *(int *)sfd;
while(1)
{
int numbytes, i;
numbytes = recv(fd, mes, MAXSIZE, 0);
printf ("\n%s\n", mes);
// close socket
if(numbytes <= 0){
for(i = 0; i < Max; i++){
if(fd == fdt[i]){
fdt[i] = 0;
}
}
memset(users[fd].id, '\0', sizeof(users[fd].id));
users[fd].playwith = -1;
break;
}
message_handler(mes, fd);
//bzero(mes, MAXSIZE);
memset(mes, 0, MAXSIZE);
}
close(fd);
}
int main()
{
int listenfd, connectfd, i, j, sin_size, fd, number = 0;
struct sockaddr_in server;
struct sockaddr_in client;
sin_size = sizeof(struct sockaddr_in);
//初始化
for (i = 0; i < 100; i++) {
for (j = 0; j < 100; j++)
users[i].id[j] = '\0';
users[i].playwith = -1;
}
//檢查有沒有成功創造socket
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("failed to creat socket");
exit(1);
}
int opt = SO_REUSEADDR;
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = htonl(INADDR_ANY);
//檢查bind error
if (bind(listenfd, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1) {
perror("Bind error.");
exit(1);
}
//檢查有沒有成功listen
if(listen(listenfd,BACKLOG) == -1) {
perror("listen() error\n");
exit(1);
}
printf("😴 😴 等待其他使用者連線中 😴 😴 \n");
while(1){
if ((fd = accept(listenfd, (struct sockaddr *)&client, &sin_size)) == -1) {
perror("accept() error\n");
exit(1);
}
//設定人數上限
if(number >= Max){
printf("😵 😵 overflow了啦,太多人了 😵 😵\n");
close(fd);
}
for(int i = 0; i < Max; i++){
if(fdt[i] == 0){
fdt[i] = fd;
break;
}
}
pthread_t tid;
pthread_create(&tid, NULL, (void*)pthread_service, &fd);
number++;
}
close(listenfd);
}
//尋找fd
int find_fd(char *name)
{
for (int i = 0; i < 100; i++)
if (strcmp(name, users[i].id) == 0)
return i;
return -1;
}
|
C
|
#include "gpio.h"
#define RPI_GPIO_OUT 21
#define RPI_GPIO_IN 4
#include <unistd.h> //sleep();
int main(void)
{
gpio my_read = gpio_init(RPI_GPIO_IN,"in");
gpio my_led = gpio_init(RPI_GPIO_OUT,"out");
printf("%i",gpio_get_value(my_read));
sleep(1);
gpio_set_value(my_led, 1);
sleep(1);
printf("%i",gpio_get_value(my_read));
gpio_set_value(my_led, 0);
sleep(1);
printf("%i",gpio_get_value(my_read));
printf("%i",gpio_get_value(my_read));
printf("%i",gpio_get_value(my_read));
gpio_destroy(my_read);
gpio_destroy(my_led);
return 0;
}
|
C
|
/*
* File: main.c
* Author: JBurnworth
*
* Created on December 17, 2014, 3:21 PM
*-----------------------------------------------------------------------
* This project mounts an SD Card with Fat Formating and looks for wav
* files in the root directory. It will try to play those files using
* functions in waveReader.c. This project implements a Petit FATFs
* module with directory, read and seek functionality enabled. Data
* forwarding is not implemented.
*
* The modules in this project make Mercury18 compatible with an
* Adafruit wavShield for arduino.
*
* https://learn.adafruit.com/adafruit-wave-shield-audio-shield-for-arduino/overview
*-----------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include <usart.h>
#include <spi.h>
#include "../mercury18.h"
#include "diskio.h"
#include "integer.h"
#include "pff.h"
#include "pffconf.h"
#include "waveReader.h"
/* Set the configuration bits:
* - No extended instruction set
* - Oscillator = HS
* - PLL = 4x
* - SOSC set to digital => PORTC.1 and PORTC.0 are I/O
*/
#pragma config XINST = 0
#pragma config FOSC = HS2
#pragma config PLLCFG = 1
#pragma config SOSCSEL = 2
/*-----------------------------------------------------------------------
* Open the COM port to talk to a computer terminal and make pins used in
* SPI bit-bang outputs.
*-----------------------------------------------------------------------*/
void init_COM (unsigned short baud_rate) {
/* Serial port, etc. initialization */
ANCON2 = 0;
TRISG &= 0xFD;
TRISG |= 0x04;
Open2USART(USART_RX_INT_OFF
& USART_TX_INT_OFF
& USART_ASYNCH_MODE
& USART_EIGHT_BIT
& USART_CONT_RX
& USART_BRGH_HIGH, baud_rate);
// Set the pins used to bit-bang spi to the DAC as outputs.
// See waveReader.h for definitions
dacCsTris = 0;
dacSckTris = 0;
dacSdiTris = 0;
}
int main() {
init_COM(BAUD_38400);
BYTE res; // Holds function return/error vaules
FATFS fs; // File system object
// <editor-fold defaultstate="collapsed" desc="DEBUG - play middle C">
// Code used in debugging, plays a slightly flat middle C
// BYTE goingUp = 1;
// WORD step = 1560;
// timer2_ON();
// </editor-fold>
printf("%cc",0x1B); // Reset COM Terminal
while (1) {
res = pf_mount(&fs); // Mount SD card
if (res == FR_OK) {
printf("SD card initialized succesfully: ");
put_rc(res);
OpenSPI1(SPI_FOSC_4,MODE_00,SMPMID); // Reinitialize SPI to fastest speed for maximum data rates with SD Card
} else {
printf("Error initializing SD card.");
put_rc(res);
}
// As long as the sd was mounted successfully, play files in root over and over
while (res == FR_OK) {
BYTE wavRes;
wavRes = rootPlay();
// if rootPlay returned an error, print it and break loop
if (wavRes != FR_OK) {
printf("break while_main;");
put_rc(wavRes);
break;
}
// <editor-fold defaultstate="collapsed" desc="DEBUG - play middle C">
// ****See interruptDAC.h/.c for more debug code****
// Code used in debugging, plays a slightly flat middle C
// if (update) {
// if (goingUp) {
// middleC += step;
// } else {
// middleC -= step;
// }
// if (goingUp && middleC < step) {
// goingUp = 0;
// middleC = 0xFFFF;
// } else if (!goingUp && middleC > (0xFFFF-step)) {
// goingUp = 1;
// middleC = 0;
// }
// update = 0;
// }
// </editor-fold>
}
}
return (EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <locale.h>
int main()
{
// Variaveis para armazenar o tamanho de cada frase e o nome
const char *nomeArquivo = "./frases.txt";
char frases[5][50];
char buffer[50];
int fraseAtual = 0;
// Abre o arquivo em modo de escrita+
FILE *arquivo = fopen(nomeArquivo, "w+");
// Loop para obter as frases
for (int i = 0; i <= 4; i++) {
// Pergunta ao usuário a frase pelo numero
printf("Digite a frase nº %d: ", i + 1);
fgets(frases[i], 50, stdin);
// Percorre cada letra da frase e transforma em maiuscula
for (int j = 0; j <= strlen(frases[i]); j++) {
int ch = toupper(frases[i][j]);
frases[i][j] = ch;
}
// Salva as frases maiusculas no arquivo
fputs(frases[i], arquivo);
}
// Mensagem de aviso
printf("Frases gravadas.\nLendo frases gravadas...\n");
// Fecha o arquivo
fclose(arquivo);
// Reabre o arquivo, em modo leitura
fopen(nomeArquivo, "r");
// Percorre cada linha do arquivo com cada frase
while(fgets(buffer, 50, arquivo)) {
fraseAtual += 1;
// Exibe o numero da linha e a frase
printf("Frase nº%d: %s", fraseAtual, buffer);
}
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
char c=-1;
int i=-1;
printf("c=%u, i=%u \n", c,i);
return 0;
}
|
C
|
/* print square roots in C language. R. Brown, 9/2010 */
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
int n;
int max;
printf("sqrt(n)\n--------\n");
max = atoi(argv[1]);
for (n=0; n<=max; n++)
printf("%f\n", sqrt(n));
return 0;
}
|
C
|
#include "menu.h"
//Créer un menu
menu_t* createMenu(const char* text){
menu_t* menu = malloc(sizeof(menu_t));
menu->pere = NULL;
menu->k = 0;
char* desc = malloc(strlen(text)+1);
strcpy(desc,text);
menu->description = desc;
return menu;
}
//Ajoute une action à un menu
void addMenuAction(menu_t* m, const char* text, void(*f)()){
char* desc = malloc(strlen(text)+1);
strcpy(desc,text);
m->tab[m->k].label = ACT;
m->tab[m->k].act.description = desc;
m->tab[m->k].act.fonc = f;
m->k++;
}
//Ajoute un sous menu à un menu
void addSubMenu(menu_t* m, menu_t* sm){
assert(sm->pere == NULL);
sm->pere = m;
m->tab[m->k].fiston = sm;
m->k++;
}
//Ajoute un jeu à un menu
void addMenuJeu(menu_t* m, jeu_t jeux){
m->tab[m->k].label = JEU;
m->tab[m->k].jeu = jeux;
m->k++;
}
//Vérifie que l'on ne dépasse pas les 9 éléments d'un menu
bool verif(long c, menu_t* m){
if((c >= 1 && c <= ((m->k)+1)) || c == 10) return true;
else return false;
}
//Récupère une chaine de caractère et lui en enlève le '\n' et vide le buffer
int lire(char *chaine, int longueur){
char *positionEntree = NULL;
if (fgets(chaine, longueur, stdin) != NULL){
positionEntree = strchr(chaine, '\n');
if (positionEntree != NULL) *positionEntree = '\0';
else viderBuffer(stdin);
return 1;
} else {
viderBuffer(stdin);
return 0;
}
}
//Retourne soit p soit un chiffre entre 1 et 9
long entreeChar(const char* c){
if(c[0] == 'p')return 10;
else return strtol(c, NULL, 10);
}
//Fonction intermediaire pour lire et entreechar
long lireLong(){
char nombreTexte[100] = {0};
if (lire(nombreTexte, 100)) return entreeChar(nombreTexte);
else return 0;
}
//Lance un menu
void launchMenu(menu_t* m){
int i;
long c;
printf("%s :\n\n",m->description);
for(i=0;i<(m->k);i++){
switch(m->tab[i].label) {
case ACT:
printf("%d - %s\n\n",(i+1),m->tab[i].act.description);
break;
case SUBM:
printf("%d - %s\n\n",(i+1),m->tab[i].fiston->description);
break;
case JEU:
printf("%d - %s\n\n",(i+1),m->tab[i].jeu.titreJeu);
}
}
c=lireLong();
while(verif(c,m) == false) c = lireLong();
system("clear");
if(c != 10){
switch(m->tab[c-1].label) {
case ACT:
m->tab[c-1].act.fonc();
break;
case SUBM:
launchMenu(m->tab[c-1].fiston);
break;
case JEU:
m->tab[c-1].jeu.fonc();
break;
}
}else if(c == 10 && m->pere != NULL)launchMenu(m->pere);
}
//Affiche un menu
void afficheMenu(menu_t* m){
printf("%s \n %d \n",m->description,m->k);
int i;
for(i=0;i<(m->k);i++){
switch(m->tab[i].label) {
case ACT:
printf("%d - %s\n\n",i,m->tab[i].act.description);
break;
case SUBM:
printf("%d - %s\n\n",i,m->tab[i].fiston->description);
break;
case JEU:
printf("%d - %s\n\n",i,m->tab[i].jeu.titreJeu);
break;
}
}
}
//Supprime un menu
void deleteMenu(menu_t* m){
assert(m->pere == NULL);
int i;
for(i=0;i<9;i++){
if(i >= 0 && i< m->k){
switch(m->tab[i].label) {
case ACT:
free(m->tab[i].act.description);
break;
case SUBM:
m->tab[i].fiston->pere = NULL;
deleteMenu(m->tab[i].fiston);
break;
case JEU:
free(m->tab[i].jeu.regles);
free(m->tab[i].jeu.titreJeu);
break;
}
}
}
free(m->description);
free(m);
}
|
C
|
/*
** EPITECH PROJECT, 2018
** Malloc
** File description:
** realign_size.c
*/
#include <unistd.h>
size_t realign_size(size_t size)
{
if (size > 0 && size % 4 != 0)
size += 4 - (size % 4);
return (size);
}
|
C
|
#include "scope.h"
t_scope* init_scope()
{
t_scope* scope = (t_scope *)calloc(1, sizeof(t_scope));
scope->function_definitions = 0;
scope->function_definitions_size = 0;
scope->variable_definitions = 0;
scope->variable_definitions_size = 0;
return scope;
}
t_ast* scope_add_function_definition(t_scope* scope, t_ast* fdef)
{
scope->function_definitions_size += 1;
if (scope->function_definitions == (void *) 0) {
scope->function_definitions = (t_ast **)calloc(1, sizeof(t_ast *));
} else {
scope->function_definitions = (t_ast **)realloc(
scope->function_definitions,
scope->function_definitions_size * sizeof(t_ast *));
}
scope->function_definitions[scope->function_definitions_size - 1] = fdef;
return fdef;
}
t_ast* scope_get_function_definition(t_scope* scope, const char* fname)
{
for (int i = 0; i < (int)scope->function_definitions_size; i++) {
t_ast* fdef = scope->function_definitions[i];
if (strcmp(fdef->function_definition_name, fname) == 0) {
return fdef;
}
}
return 0;
}
t_ast* scope_add_variable_definition(t_scope* scope, t_ast* var_def)
{
scope->variable_definitions_size += 1;
if (scope->variable_definitions == (void *)0) {
scope->variable_definitions = (t_ast **)calloc(1, sizeof(t_ast *));
} else {
scope->variable_definitions = (t_ast **)realloc(
scope->variable_definitions,
scope->variable_definitions_size * sizeof(t_ast *));
}
scope->variable_definitions[scope->variable_definitions_size - 1] = var_def;
return var_def;
}
t_ast* scope_get_variable_definition(t_scope* scope, const char* var_name)
{
for (int i = 0; i < (int)scope->variable_definitions_size; i++) {
t_ast* var_def = scope->variable_definitions[i];
if (strcmp(var_def->variable_definition_name, var_name) == 0) {
return var_def;
}
}
return 0;
}
|
C
|
#include "Texture.h"
#include <assert.h>
void CreateTexture(DeccanTexture *texture, int32_t width, int32_t height, int format, sg_image_content *image_content) {
texture->width = width;
texture->height = height;
texture->pixel_format = format;
sg_image_desc desc = {
.width = texture->width,
.height = texture->height,
.pixel_format = texture->pixel_format,
.min_filter = SG_FILTER_NEAREST,
.mag_filter = SG_FILTER_NEAREST,
.content = *image_content,
};
texture->image = sg_make_image(&desc);
}
void DE_TextureCreateFromMem(DeccanTexture *texture, int32_t width, int32_t height, size_t count, DeccanSurface *surfaces) {
assert(&surfaces[0] != NULL);
sg_image_content image_content;
memcpy(&image_content, surfaces, sizeof(sg_subimage_content) * count);
CreateTexture(texture, width, height, surfaces[0].format, &image_content);
}
void DE_TextureCreateBlankRGBA(DeccanTexture *texture, int32_t width, int32_t height, uint32_t color) {
int size_bytes = sizeof(uint32_t) * width * height;
uint32_t *pixels = malloc(size_bytes);
for(int w = 0; w < width; w++) {
for(int h = 0; h < height; h++) {
pixels[h * width + w] = color;
}
}
sg_image_content image_content = {
.subimage[0][0] = {
.ptr = pixels,
.size = size_bytes,
},
};
CreateTexture(texture, width, height, SG_PIXELFORMAT_RGBA8, &image_content);
free(pixels);
}
void DE_TextureDestroy(DeccanTexture *texture) {
sg_destroy_image(texture->image);
}
|
C
|
int mandel(float x, float y, int max_iters, unsigned char * val);
typedef struct _Img{
int width;
int height;
unsigned char * data;
} Img;
void create_fractal(Img img, int iters) {
float pixel_size_x = 3.0 / img.width;
float pixel_size_y = 2.0 / img.height;
for (int y=0; y < img.height; y++) {
float imag = y * pixel_size_y - 1;
int yy = y * img.width;
for (int x=0; x < img.width; x++) {
float real = x * pixel_size_x - 2;
unsigned char color;
int ret = mandel(real, imag, iters, &color);
img.data[yy + x] = color;
}
}
}
|
C
|
#ifndef __CORE_PRIMITIVES_H_
#define __CORE_PRIMITIVES_H_
struct RAY
{
RAY()
{
this->origin = VEC4(0.0f, 0.0f, 0.0f, 1.0f);
this->direction = VEC3(0.0f, 0.0f, 0.0f);
this->color = COLOR(0.0f, 0.0f, 0.0f, 1.0f);
this->length = 0.0f;
}
RAY(VEC4& position, VEC3& direction)
{
this->origin = position;
this->direction = direction;
this->color = COLOR(0.0f, 0.0f, 0.0f, 1.0f);
this->length = 0.0f;
}
RAY(VEC4& position, VEC3& direction, float length)
{
this->origin = position;
this->direction = direction;
this->color = COLOR();
this->length = length;
}
VEC4 origin;
VEC3 direction;
COLOR color;
float length;
};
struct RAYHIT
{
RAYHIT()
{
this->t = FLT_MAX;
this->surfaceMaterial = NULL;
this->surface = NULL;
}
RAYHIT(RAY ray, float t, VEC4& intersection, VEC3& surfaceNormal, VEC3& surfaceTangent, VEC3& surfaceBinormal, Material* surfaceMaterial, VEC2& surfaceUV, Entity* surface)
{
this->ray = ray;
this->t = t;
this->intersection = intersection;
this->surfaceNormal = surfaceNormal;
this->surfaceTangent = surfaceTangent;
this->surfaceBinormal = surfaceBinormal;
this->surfaceMaterial = surfaceMaterial;
this->surfaceUV = surfaceUV;
this->surface = surface;
}
RAY ray;
float t;
VEC4 intersection;
VEC3 surfaceNormal;
VEC3 surfaceTangent;
VEC3 surfaceBinormal;
Material* surfaceMaterial;
VEC2 surfaceUV;
Entity* surface;
};
#endif
|
C
|
#include <stdio.h>
#include "cdg.h"
#define MAX_NODES 500
CDGNode* nodes[MAX_NODES] = {NULL}; //Holds all the nodes in the tree
CDGNode* root = NULL;
void preOrderCDG(CDGNode*);
void addtoCDGnode(int , int , int);
void setArray();
void printArray();
// branch variable tell on which branch of parent the node is to be attached
void addtoCDGnode(int id, int pid, int branch) {
CDGNode* node = newBlankNode();
setID(node, id);
if ( 0 == id ) {
root = node;
} else {
if (branch) {
addTrueNode(nodes[pid], node);
} else {
addFalseNode(nodes[pid], node);
}
}
nodes[id] = node;
}
void setArray(int id, const char *expr) {
setExpr(nodes[id], expr);
}
void printArray()
{
CDGNode* node = root;
preOrderCDG(node);
}
void preOrderCDG(CDGNode* node) {
while (node) {
if ( 0 == getID(node) )
printf("ID: %d, PID: 0", getID(node));
else
printf("ID: %d, PID: %d", getID(node), getID(getParent(node)));
preOrderCDG(getTrueNodeSet(node));
preOrderCDG(getFalseNodeSet(node));
node = getNextNode(node);
}
}
|
C
|
/**
* water.c
*
* Lizzie Eng
*
* CONDITIONS
* (1) Input (minutes) must be a positive integers
* (2) If Input = positive int, output must reflect input in bottles of water
* (3) Else prompt user to "Retry"
*/
#include <stdio.h>
#include <cs50.h>
int GetPositiveInt();
int main(void)
{
int b = 16; // bottles of water
int w = 1.5 * 128; // water in ounces
int n = GetPositiveInt();
printf("bottles: %i\n", n * w / b);
}
// gets a positive integer from the user
int GetPositiveInt(void)
{
int n;
do
{
printf("minutes: ");
n = GetInt();
}
while (n <= 0);
return n./;
}
|
C
|
#include<stdio.h>
int main()
{
int tc,e,f,c,l,t,count,i;
scanf("%d",&tc);
for(i=1;i<=tc;i++)
{
count=0;
scanf("%d %d %d",&e,&f,&c);
l=e+f;
while(1)
{
t=l-c+1;
l=t;
if(l<=0)
break;
count++;
}
printf("%d\n",count);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "utils/vec.h"
#include "utils/math.h"
#include "utils/utils.h"
#include "d3v/d3v.h"
#include "d3v/object.h"
#include "display/animator.h"
#define MAX_ANIMATION_STEP 20
/**
* Description d'une animation.
*/
typedef struct animation_step {
struct object *obj; // targeted object
anim_object_type_t type; //0=penguin, 1=tile
int shouldTranslate; //1= animation step must translate the object
int shouldRotate; // 1= animation step must rotate the object
int shouldFlip; // wwhoooo 360 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
int shouldHide;
// 1 means object should be hidden when animation is executed
// (and remain hidden afterwards)
// 0 means object should be revealed when animation is executed
// (and remains visible afterwards)
float finalAngle; // final rotation angle that should eventually be adopted by the object
vec3 finalPosition; // final position that should eventually be adopted by the object
int frame_length; // animation duration in frame
int current_frame; // current frame of animation (between 0 and frame_length)
} animation_step_t;
/**
* Gestion des animations.
*/
typedef struct animation {
animation_step_t steps[MAX_ANIMATION_STEP];
int nb_step; // number of animation
int cur_step; // current animation that is executed
int can_edit_animation;
// 0=animation can run, but cannot be edited (all edition methods will fail)
// 1=animation cannot run and is in preparation phase
int animation_is_running;
// 1=animation is currently running and cannot be locked for modification
} animation_t;
static animation_t animation;
/**
* Initialisation du module animation.
*/
void init_anim_module(void)
{
animation.nb_step = 0;
animation.cur_step = 0;
animation.can_edit_animation = 0;
animation.animation_is_running = 0;
}
/**
* Active le mode préparation d'une séquence d'animations.
* @return int - 1 Si l'activation a fonctionné.
*/
int anim_prepare(void)
{
if (animation.animation_is_running || animation.nb_step == MAX_ANIMATION_STEP) {
return 0;
}
animation.can_edit_animation = 1;
return 1;
}
/**
* Active le mode lecture d'une séquence d'animations.
*/
void anim_launch(void)
{
animation.can_edit_animation = 0;
animation.animation_is_running = 1;
}
/**
* Enclenche l'ajout d'un nouveau mouvement dans la séquence.
* @param o - Élément subissant le mouvement.
* @param type - Type de l'élément. 0=penguins, 1=tile
* @param total - Durée total du mouvement. (frame)
* @return int - 1 Si l'ajout a fonctionné.
*/
int anim_new_movement(void *obj, anim_object_type_t type, int length)
{
if (!animation.can_edit_animation) {
return 0;
}
int s = animation.nb_step;
animation_step_t *step = &animation.steps[s];
memset(step, 0, sizeof *step);
step->obj = obj;
step->type = type;
step->frame_length = length;
step->current_frame = 0;
step->shouldRotate = 0;
step->shouldTranslate = 0;
step->shouldFlip = 0;
step->shouldHide = 0;
step->finalPosition = (vec3){0,0,0};
step->finalAngle = 0;
return 1;
}
/**
* Enregistrement de la translation dans le mouvement à ajouter.
* @param dest - Destination de la translation.
* @return int - 1 Si l'enregistrement a fonctionné.
*/
int anim_set_translation(vec3 dest)
{
if (!animation.can_edit_animation) {
return 0;
}
int s = animation.nb_step;
animation_step_t *step = &animation.steps[s];
step->finalPosition = dest;
step->shouldTranslate = 1;
return 1;
}
int anim_set_flip(void)
{
// special case where penguin is going up or down
// make it do a 360 roll on itself !!!! because why not
if (!animation.can_edit_animation) {
return 0;
}
int s = animation.nb_step;
animation_step_t *step = &(animation.steps[s]);
vec3 src;
d3v_object_get_position(step->obj, &src);
double height = step->finalPosition.y - src.y;
step->finalAngle = d3v_object_get_orientationY(step->obj);
step->shouldFlip = 1;
step->shouldRotate = 0;
return 1;
}
/**
* Enregistrement de la rotation dans le mouvement à ajouter.
* @param dest - Angle de destination (En degré).
* @return int - 1 Si l'enregistrement a fonctionné.
*/
int anim_set_rotation(float dest)
{
if (!animation.can_edit_animation) {
return 0;
}
int s = animation.nb_step;
animation_step_t *step = &(animation.steps[s]);
step->finalAngle = angle_normalize(dest);
step->shouldRotate = 1;
step->shouldFlip = 0;
float cur = d3v_object_get_orientationY(step->obj);
return 1;
}
/**
* Enregistrement de l'état dans le mouvement à ajouter.
* @param hide - 1 Pour cacher l'element, 0 pour le dévoiler.
* @return int - 1 Si l'enregistrement a fonctionné.
*/
int anim_set_hide(int shouldHide)
{
if (!animation.can_edit_animation) {
return 0;
}
animation.steps[animation.nb_step].shouldHide = shouldHide;
return 1;
}
/**
* Ajouter l'animation dans la séquence.
* @return int - 1 Si l'ajout a fonctionné.
*/
int anim_push_movement(void)
{
if (!animation.can_edit_animation) {
return 0;
}
animation.nb_step++;
return 1;
}
/**
* Exécuter l'animation courrante.
* @return int - 1 S'il reste des animations à exécuter. 0 si l'animation est terminé.
*/
int anim_run(void)
{
if (animation.can_edit_animation || animation.nb_step == 0) {
return 0;
}
animation.animation_is_running = 1;
animation_step_t *step = &animation.steps[animation.cur_step];
if (step->type == ANIM_O_PENGUIN)
{
if (step->shouldHide) {
d3v_object_hide(step->obj);
} else {
d3v_object_reveal(step->obj);
}
if (step->shouldTranslate) {
vec3 src;
vec3 dst = step->finalPosition;
d3v_object_get_position(step->obj, &src);
float nb_frame = max(step->frame_length - step->current_frame, 1);
vec3 d = {dst.x - src.x, dst.y - src.y, dst.z - src.z};
d.x /= nb_frame;
d.y /= nb_frame;
d.z /= nb_frame;
vec3 dest = {
src.x + d.x,
src.y + d.y,
src.z + d.z
};
d3v_object_set_position(step->obj, dest);
}
if (step->shouldRotate) {
float cur = angle_normalize(d3v_object_get_orientationY(step->obj));
float dest = angle_normalize(step->finalAngle);
float da = dest - cur;
int nb_step = max(step->frame_length - step->current_frame, 1);
if (da > 180) {
da = da - 360; // shortest path: if more than 180 go the other way
}
else if (da < -180) {
da = 360 + da; // shortest path: if more than 180 go the other way
}
da /= nb_step;
float rot = angle_normalize(cur + da);
d3v_object_set_orientationY(step->obj, rot);
}
if (step->shouldFlip) {
float ratio = (float)step->current_frame / (float)step->frame_length;
float wantedAngle = step->finalAngle + ratio * 1.5 * 360;
float rot = angle_normalize(wantedAngle);
d3v_object_set_orientationY(step->obj, rot);
}
++step->current_frame;
if (step->current_frame >= step->frame_length)
{
if (step->shouldTranslate) {
d3v_object_set_position(step->obj, step->finalPosition);
}
if (step->shouldRotate || step->shouldFlip) {
d3v_object_set_orientationY(step->obj, step->finalAngle);
}
}
}
else if (step->type == ANIM_O_TILE) {
if (step->shouldHide == 1) {
d3v_object_hide(step->obj);
}
else if (step->shouldHide == 0) {
d3v_object_reveal(step->obj);
}
++step->current_frame;
}
d3v_request_animation_frame();
// transition to next step
if (step->current_frame >= step->frame_length) {
++animation.cur_step;
if (animation.cur_step == animation.nb_step) {
// if all steps are finished, reset the animation
animation.cur_step = 0;
animation.nb_step = 0;
animation.animation_is_running = 0;
return 0;
}
}
return 1;
}
|
C
|
/*******************************************************************************
* Ver 15.02.04
*******************************************************************************/
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include "Parser.h"
void reverse(char s[]);
/* itoa: n s */
void itoaf(int n, char s[], int l)
{
int i=l, sign;
//
if ((sign = n) < 0) n = -n; // n
i = 0;
//
do
{
s[i++] = n % 10 + '0'; //
if (i==l) s[i++]='.';
(n /= 10) > 0; //
} while (n||(l>=i-1));
if (sign < 0) s[i++] = '-';
s[i] = '\0';
reverse(s);
}
/* itoa: n s */
void itoa(int n, char s[])
{
int i, sign;
//
if ((sign = n) < 0) n = -n; // n
i = 0;
//
do
{
s[i++] = n % 10 + '0'; //
} while ((n /= 10) > 0); //
if (sign < 0) s[i++] = '-';
s[i] = '\0';
reverse(s);
}
void ltoa(long int n,char *str)
{
unsigned long i;
unsigned char j,p;
i=1000000000L;
p=0;
if (n<0)
{
n=-n;
*str++='-';
};
do
{
j=(unsigned char) (n/i);
if (j || p || (i==1))
{
*str++=j+'0';
p=1;
}
n%=i;
i/=10L;
}
while (i!=0);
*str=0;
}
void ltoa_null(long n, char s[], int l)
{
long sign;
//
if ((sign = n) < 0) n = -n; // n
for (uint8_t i=0; i<l; i++)
{
s[i] = n%10+'0';
n/=10;
};
if (sign<0)
{
s[l] = '-';
s[l+1] = '\0';
}
else s[l] = '\0';
reverse(s);
}
/*******************************************************************************
* str - *
* ch - *
* num - *
* return - , *
* , -1
*******************************************************************************/
int Parser_FindPos(const char *str, char ch, char num)
{
int pos;
pos=0;
while (*str)
{
if (num==0) return pos;
if (*str==ch) num--;
pos++;
str++;
}
return -1;
}
/*******************************************************************************
* str - *
* ch - *
* num - *
* val - () *
* return - , *
* , 0 *
*******************************************************************************/
int Parser_GetParamChar(const char *str, char ch, char num, char *val)
{
int pos;
pos=Parser_FindPos(str, ch, num);
if (pos==-1) return 0;
if (str[pos]!=ch) *val=str[pos]; else val=0;
return *val;
}
/*******************************************************************************
* str - *
* ch - *
* num - *
* val - ( int) *
* return - , *
* , 0, *
*******************************************************************************/
int Parser_GetParamInt(const char *str, char ch, char num, int *val)
{
char intstr[11];
char ptr;
int pos;
pos=Parser_FindPos(str, ch, num);
if (pos==-1) return 0;
if (str[pos]==ch)
{
val=0;
return 0;
}
for (ptr=0; ptr<11;)
{
if ((str[pos]==ch)||(str[pos]==0)) break;
if (((str[pos]>0x39)||(str[pos]<0x30))&&
((str[pos]!='-')&&(str[pos]!=' ')&&(str[pos]!='.'))) return 0;
if ((str[pos]!=' ')&&(str[pos]!='.')) intstr[ptr++]=str[pos];
pos++;
}
intstr[ptr]=0;
*val=atoi(intstr);
return ptr;
}
/*******************************************************************************
* str - *
* ch - *
* num - *
* val - ( long) *
* return - , *
* , 0, *
*******************************************************************************/
int Parser_GetParamLong(const char *str, char ch, char num, long *val)
{
char intstr[11];
char ptr;
int pos;
pos=Parser_FindPos(str, ch, num);
if (pos==-1) return 0;
if (str[pos]==ch)
{
val=0;
return 0;
}
for (ptr=0; ptr<11;)
{
if ((str[pos]==ch)||(str[pos]==0)) break;
if (((str[pos]>0x39)||(str[pos]<0x30))&&
((str[pos]!='-')&&(str[pos]!=' ')&&(str[pos]!='.'))) return 0;
if ((str[pos]!=' ')&&(str[pos]!='.')) intstr[ptr++]=str[pos];
pos++;
}
intstr[ptr]=0;
*val=atol(intstr);
return ptr;
}
/*******************************************************************************
* str - *
* ch - *
* num - *
* val - ( long) *
* return - , *
* , 0, *
*******************************************************************************/
int Parser_GetParamShort(const char *str, char ch, char num, short *val)
{
char intstr[11];
char ptr;
int pos;
pos=Parser_FindPos(str, ch, num);
if (pos==-1) return 0;
if (str[pos]==ch)
{
val=0;
return 0;
}
for (ptr=0; ptr<11;)
{
if ((str[pos]==ch)||(str[pos]==0)) break;
if (((str[pos]>0x39)||(str[pos]<0x30))&&
((str[pos]!='-')&&(str[pos]!=' ')&&(str[pos]!='.'))) return 0;
if ((str[pos]!=' ')&&(str[pos]!='.')) intstr[ptr++]=str[pos];
pos++;
}
intstr[ptr]=0;
*val=atoi(intstr);
return ptr;
}
/*******************************************************************************
* str - *
* ch - *
* num - *
* val - ( char) *
* return - , *
* , 0, *
*******************************************************************************/
int Parser_GetParamHex(const char *str, char ch, char num, short *val)
{
char ptr;
int pos;
char ret_val=0;
pos=Parser_FindPos(str, ch, num);
if (pos==-1) return 0;
if (str[pos]==ch)
{
val=0;
return 0;
}
for (ptr=0; ptr<11; ptr++)
{
if ((str[pos]==ch)||(str[pos]==0)) break;
/*if (((str[pos]>'9')||(str[pos]<'0'))&& //
((str[pos]>'F')||(str[pos]<'A'))&& // A...F
((str[pos]>'f')||(str[pos]<'a'))&& // a...f
(str[pos]!=' ')) return 0; // , */
if ((str[pos]>='0')&&(str[pos]<='9')) ret_val=(ret_val<<4)|(str[pos]-'0'); //
else if ((str[pos]>='A')&&(str[pos]<='F')) ret_val=(ret_val<<4)|(str[pos]-'A'+10); // A...F
else if ((str[pos]>='a')&&(str[pos]<='f')) ret_val=(ret_val<<4)|(str[pos]-'a'+10); // a...f
else if (str[pos]==' ') break;
else return 0;
pos++;
}
*val=ret_val;
return pos;
}
/*******************************************************************************
* str - *
* ch - *
* num - *
* val - () *
* return - , *
* , 0, *
*******************************************************************************/
int Parser_GetParam(const char *str, char ch, char num, char *val)
{
char ptr;
int pos;
pos=Parser_FindPos(str, ch, num);
if ((pos==-1)||(str[pos]==ch))
{
val[0]=0;
return 0;
}
int max_str_len;
max_str_len=strlen(str)-pos;
for (ptr=0; ptr<max_str_len; ptr++)
{
if ( (str[pos]== ch)||(str[pos] == 0)) break;
val[ptr]=str[pos++];
}
val[ptr]=0;
return ptr;
}
void Parser_write(uint8_t b)
{
}
/*******************************************************************************
*
* str -
* format -
* :
* - %s -
* - %i, %ni - (int), n -
* - %l - (long)
* - %nL - (long) c n
* - %h, %nh, %H, %nH, - HEX, n -
* - % - (char)
*******************************************************************************/
void Parser_BufPrintf(char *str, const char *format, ...)
{
va_list list;
int pos_str=0;
int pos_format=0;
int n=0;
va_start(list, format);
while(1)
{
if (format[pos_format]==0) break;
if (format[pos_format]!='%') str[pos_str++]=format[pos_format++];
else
{
pos_format++;
if (format[pos_format]=='%') str[pos_str++]=format[pos_format++];
//
else if (format[pos_format]=='s')
{
char *pp;
pp = va_arg(list, char *);
for (n=0; n<strlen(pp); n++) if (pp[n]) str[pos_str++]=pp[n];
pos_format++;
}
//
else if (format[pos_format]=='i')
{
int p;
p = va_arg(list, int);
itoa(p, &str[pos_str]);
pos_str=strlen(str);
pos_format++;
}
//
else if ((format[pos_format]>=0x30)&&(format[pos_format]<=0x39)&&(format[pos_format+1]=='i'))
{
int p;
p = va_arg(list, int);
itoaf(p, &str[pos_str], (format[pos_format]&0x0f));
pos_str=strlen(str);
pos_format+=2;
}
// LONG
else if (format[pos_format]=='l')
{
long p;
p = va_arg(list, long);
ltoa(p, &str[pos_str]);
pos_str=strlen(str);
pos_format++;
}
// LONG
else if ((format[pos_format]>=0x30)&&(format[pos_format]<=0x39)&&(format[pos_format+1]=='L'))
{
long p;
p = va_arg(list, long);
ltoa_null(p, &str[pos_str], (format[pos_format]&0x0f));
pos_str=strlen(str);
pos_format+=2;
}
// HEX
else if ((format[pos_format]=='h')||(format[pos_format]=='H'))
{
char p;
char tmpstr[9];
p = va_arg(list, char);
for (uint8_t i=0; i<8; i++)
{
if ((p&0x0F)>=10) tmpstr[i]=(p&0x0F)-10+((format[pos_format]=='h')?'a':'A');
else tmpstr[i]=(p&0x0F)+'0';
p/=0x10;
if (p==0) break;
}
reverse(tmpstr);
strcpy(&str[pos_str], tmpstr);
pos_str=strlen(str);
pos_format++;
}
// HEX
else if ((format[pos_format]>=0x30)&&(format[pos_format]<=0x39)&&((format[pos_format+1]=='h')||(format[pos_format+1]=='H')))
{
long p;
char tmpstr[9]={0};
char num_col=format[pos_format]&0x0f;
if (num_col<=2) p = va_arg(list, char);
else if (num_col<=4) p = va_arg(list, short);
else if (num_col<=8) p = va_arg(list, long);
//else p = va_arg(list, long long);
else num_col=0;
for (uint8_t i=0; i<num_col; i++)
{
if ((p&0x0F)>=10) tmpstr[i]=(p&0x0F)-10+((format[pos_format+1]=='h')?'a':'A');
else tmpstr[i]=(p&0x0F)+'0';
p/=0x10;
}
reverse(tmpstr);
strcpy(&str[pos_str], tmpstr);
pos_str=strlen(str);
pos_format+=2;
}
//
else if (format[pos_format]=='c')
{
char p;
p = va_arg(list, char);
str[pos_str++]=p;
pos_format++;
}
}
}
str[pos_str]=0;
va_end(list);
}
/* reverse: s */
void reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
/* itoa: n s */
void itoa_dot(int n, char s[], int l)
{
int i=l, sign;
//
if ((sign = n) < 0) n = -n; // n
i = 0;
//
do
{
s[i++] = n % 10 + '0'; //
if (i==l) s[i++]='.';
(n /= 10) > 0; //
} while (n||(l>=i-1));
if (sign < 0) s[i++] = '-';
s[i] = '\0';
reverse(s);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "chain.h"
#include "utils.h"
int *build_dimensions(const int n) {
int *dims = (int *)malloc(sizeof(int) * (n + 1));
for (size_t i = 0; i < n + 1; i++) {
dims[i] = rand() % 600;
}
return dims;
}
float ***build_problem_instance(const int *dims, const int n) {
float ***A = (float ***)malloc(sizeof(float **) * n);
for (size_t i = 0; i < n; i++) {
A[i] = allocate_matrix(dims[i], dims[i + 1]);
}
return A;
}
int main() {
for(int n=10;n<100;n=n+10){
int *P = build_dimensions(n);
float ***A = build_problem_instance(P, n);
//matrixes for partial results
float **C=allocate_matrix(P[0],P[1]);
copy_matrix(A[0],C,P[0],P[1]);
//time stuff
struct timespec b_time, e_time;
double time=0.0;
clock_gettime(CLOCK_REALTIME, &b_time);
//naive ordered matrix_multiplication
for(size_t i = 0; i < n-1; i++)
{
float **D=allocate_matrix(P[0],P[i+2]); //allocate new D
naive_matrix_mult(D,C,A[i+1],P[0],P[i+1],P[i+1],P[i+2]);
deallocate_matrix_fl(C,P[0]); //free partial results
C=allocate_matrix(P[0],P[i+2]);
copy_matrix(D,C,P[0],P[i+2]); //prepare new partial results
deallocate_matrix_fl(D,P[0]);
}
deallocate_matrix_fl(C,P[0]);
clock_gettime(CLOCK_REALTIME, &e_time);
time=get_execution_time(b_time, e_time);
printf("size\tnaive time\tnew time\n");
printf("%d\t%lf\t",n, time);
int** s=matrixchain(P,n);
clock_gettime(CLOCK_REALTIME, &b_time);
float **res=allocate_matrix(P[0],P[n]);
using_s(res,A,P,s,0,n-1);
clock_gettime(CLOCK_REALTIME, &e_time);
time=get_execution_time(b_time, e_time);
printf("%lf\n",time);
//deallocating everything
for(size_t i = 0; i < n; i++)
{
deallocate_matrix_fl(A[i],P[i]);
}
free(A);
//deallocate res
deallocate_matrix_fl(res,P[0]);
//deallocate s
for (size_t i=0; i<n-1; i++) {
free(s[i]);
}
free(s);
free(P);
}
return 0;
}
|
C
|
/*
* Copyright (c) 2017 RnDity Sp. z o.o.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr.h>
#include <watchdog.h>
#include <misc/printk.h>
/*
* The independent watchdog (IWDG) is clocked by its own dedicated
* 40kHz (STM32F1X or STM32F3X) or 32kHz (STM32F4X or STM32L4X)
* low-speed internal clock (LSI).
*
* Sample application is dedicated to STM32 family.
*
* For STM32F1X/STM32F3X family:
* prescaler register should be set to 'divider /16' and the reload
* register to 2500.
*
* For STM32F4X/STM32L4X family:
* prescaler register should be set to 'divider /16' and the reload
* register to 2000.
*
* Then it takes 1 second a reset signal is generated.
*/
#define TIMEOUT_VALID 900
#define TIMEOUT_INVALID 1100
void main(void)
{
struct device *iwdg = device_get_binding("IWDG");
struct k_timer iwdg_timer;
struct wdt_config config;
u8_t counter = 0;
wdt_enable(iwdg);
k_timer_init(&iwdg_timer, NULL, NULL);
/* Set IWDG timeout to 1 second. */
config.timeout = 1000000;
wdt_set_config(iwdg, &config);
while (1) {
printk("Welcome...\n");
if (counter % 2 == 0) {
/* Less than IWDG reload value. */
k_timer_start(&iwdg_timer, K_MSEC(TIMEOUT_VALID), 0);
} else {
/* More than IWDG reload value. */
k_timer_start(&iwdg_timer, K_MSEC(TIMEOUT_INVALID), 0);
}
counter++;
/* Wait till application timer expires. */
k_timer_status_sync(&iwdg_timer);
printk("Watchdog refreshed...\n");
k_sleep(2);
wdt_reload(iwdg);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void) {
{
int a = rand()%20;
int isDivisibleByAny = 0;
int numbers[] = {2, 3, 5, 7, 11, 13, 17, 19};
for (int i = 0; i <= 7; ++i) {
switch(a % numbers[i]) {
case 0:
printf("%d is divisible by %d \n", a, numbers[i]);
isDivisibleByAny = 1;
}
}
switch(isDivisibleByAny) {
case 0:
printf("%d is a prime or 1", a);
}
}
// For
{
int a = rand()%40;
int sum = 0;
for (int i = a; i > 0; i--) {
sum = sum + a--;
}
printf("sum is %d \n", sum);
}
// Do while
{
int a = rand()%40;
int sum = 0;
do {
sum = sum + a--;
} while (a > 0);
printf("sum is %d \n", sum);
}
}
|
C
|
// Welch, Wright, & Morrow,
// Real-time Digital Signal Processing, 2017
///////////////////////////////////////////////////////////////////////
// Filename: ISRs.c
//
// Synopsis: Interrupt service routine for codec data transmit/receive
//
///////////////////////////////////////////////////////////////////////
#include "DSP_Config.h"
#include <math.h>
// Data is received as 2 16-bit words (left/right) packed into one
// 32-bit word. The union allows the data to be accessed as a single
// entity when transferring to and from the serial port, but still be
// able to manipulate the left and right channels independently.
#define LEFT 1
#define RIGHT 0
volatile union {
Uint32 UINT;
Int16 Channel[2];
} CodecDataIn, CodecDataOut;
/* add any global variables here */
//#define NumTableEntries 100
#define NumTableEntries 17
#define Phase 0.0
float desiredFreq = 1000.0;
//float desiredFreq = 6000.0;
float SineTable[NumTableEntries];
void FillSineTable()
{
Int32 i;
for(i = 0; i < NumTableEntries; i++) // fill table values
//SineTable[i] = sinf(i * (float)(6.283185307 / NumTableEntries));
SineTable[i] = sinf( i* (float)(6.283185307 /(4*NumTableEntries)));
}
interrupt void Codec_ISR()
///////////////////////////////////////////////////////////////////////
// Purpose: Codec interface interrupt service routine
//
// Input: None
//
// Returns: Nothing
//
// Calls: CheckForOverrun, ReadCodecData, WriteCodecData
//
// Notes: None
///////////////////////////////////////////////////////////////////////
{
/* add any local variables here */
static float index = Phase;
float sine_left, sine_right;
if(CheckForOverrun()) // overrun error occurred (i.e. halted DSP)
return; // so serial port is reset to recover
CodecDataIn.UINT = ReadCodecData(); // get input data samples
/* ISR's algorithm begins here */
index += desiredFreq; // calculate the next phase
if (index >= GetSampleFreq()) // keep phase between 0-2*pi
index -= GetSampleFreq();
sine_left = SineTable[(int)(index / GetSampleFreq() * NumTableEntries)];
sine_right = sine_left + (SineTable[(int)(index / GetSampleFreq() * NumTableEntries)+1] - sine_left) * (sine_left-floor(sine_left));
CodecDataOut.Channel[LEFT] = 4096*sine_left; // scale the result
CodecDataOut.Channel[RIGHT] = 4096*sine_right;
/* ISR's algorithm ends here */
WriteCodecData(CodecDataOut.UINT); // send output data to port
}
|
C
|
#include <stdio.h>
/* Include other headers as needed */
int firstOccurence(int a[],int l,int r,int key)
{
if(l<r)
{
int mid=l+(r-l)/2;
if(a[mid]>=key)
{
r=mid;
return firstOccurence(a,l,r,key);
}
else
{
l=mid+1;
return firstOccurence(a,l,r,key);
}
}
return l;
}
int main()
{
int t;
scanf("%d",&t);
while(t>0){
int n,key,index;
scanf("%d%d",&n,&key);
int a[n];
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
index=firstOccurence(a,0,n-1,key);
printf("%d\n",index);
t--;
}
return 0;
}
|
C
|
/*
* & defines the address of
* * dereferences/declares ptr
* ** dereferences/declares ptr2ptr
*/
#include<stdio.h>
int main(int argc,char** argv){
{
int a=8;
int *b=&a;
int **c=&b;
fprintf(stdout,"%d\n",a);
fprintf(stdout,"%d\n",*b);
fprintf(stdout,"%d\n",**c);
}
{
char *a="0123456789abcdef";
char *b=a;
char **c=&a;/*ptr2ptr*/
fprintf(stdout,"%s\n",a);
fprintf(stdout,"%s\n",b);
fprintf(stdout,"%s\n",*c);
}
return 0;
}
|
C
|
#include "tables.h"
#include "storage_mgr.h"
#include "record_mgr.h"
#include "buffer_mgr.h"
#include <string.h>
#include <stdlib.h>
#include <math.h>
#define META_PAGENO 0 // Page reserved for metadata
#define MAX_ATTRNAME_LEN 30 //Maximum length of the attribute name
#define BUFFER_FRAME_SIZE 10 // Size of page frame to initialize buffer pool
#define PAGE_REPLACEMENT_ALGO RS_FIFO // Page replacement algorithm to use
#define RECORD_DELIMITER '#'
#define RECORD_DELIMITER_TOMB '~'
#define TOMBSTONE 0
// Table meta data
typedef struct RecordMgrData
{
int numberOfTuples;
int firstFreePage;
int recordSize;
int numberOfAttr;
Schema schema;
BM_BufferPool bufferPool;
}RecordMgrData;
typedef struct RM_ScaningRecordInfo
{
Expr *condition; //Search condition
int pageCurrentPosition; //Current page index
int slotCurrentPosition; // Current slot index
}RM_ScaningRecordInfo;
// table and manager
RC initRecordManager(void *mgmtData)
{
RC retVal = RC_OK;
initStorageManager();
return retVal;
}
RC shutdownRecordManager()
{
RC retVal = RC_OK;
return retVal;
}
void printRecordManager(RecordMgrData* recordMgr, Schema * schema, char *callingFunctionName)
{
int i;
printf("\n*********%s********\n", callingFunctionName);
printf("Number of Tuples = %d\n", recordMgr->numberOfTuples);
printf("First Free Page = %d\n", recordMgr->firstFreePage);
printf("Number of Attributes = %d\n", recordMgr->numberOfAttr);
printf("Record Size = %d\n", recordMgr->recordSize);
for (i = 0; i < recordMgr->numberOfAttr; i++) {
printf("AttributeName %s ", schema->attrNames[i]);
printf("DataType %d ", schema->dataTypes[i]);
printf("DataLength %d \n", schema->typeLength[i]);
}
printf("Number of Key Attributes = %d\nKey Attributes = ", schema->keySize);
for (i = 0; i < schema->keySize; i++) {
printf("%d, ", schema->keyAttrs[i]);
}
printf("\b\b\n");
}
RC createTable(char *name, Schema *schema) {
RC retVal = RC_OK;
SM_FileHandle fh;
RecordMgrData metaData;
int i = 0;
int intSize = sizeof(int);
//Create pagefile for each table
retVal = createPageFile(name);
if (retVal != RC_OK)
{
printf("Failed to create pageFile");
goto END;
}
//Open pagefile to write metadata
retVal = openPageFile(name, &fh);
if (retVal != RC_OK)
{
printf("Failed to open pageFile");
goto END;
}
//Initialize
metaData.numberOfTuples = 0;
metaData.firstFreePage = 1;
metaData.recordSize = getRecordSize(schema);
metaData.numberOfAttr = schema->numAttr;
//Copy all schema related data from schema structure
metaData.schema.attrNames = schema->attrNames;
metaData.schema.dataTypes = schema->dataTypes;
metaData.schema.keyAttrs = schema->keyAttrs;
metaData.schema.keySize = schema->keySize;
metaData.schema.numAttr = schema->numAttr;
metaData.schema.typeLength = schema->typeLength;
//For writing first page of pagefile with table metadata
char page[PAGE_SIZE];
char *pagePtr = page;
//For validating the write
//char readPage[PAGE_SIZE];
//char *readPagePtr = readPage;
//memset(readPagePtr, 0, PAGE_SIZE);
memset(pagePtr, 0, PAGE_SIZE);
*((int*)pagePtr) = metaData.numberOfTuples;
pagePtr = pagePtr + intSize;
*((int*)pagePtr) = metaData.firstFreePage;
pagePtr = pagePtr + intSize;
*((int*)pagePtr) = metaData.recordSize;
pagePtr = pagePtr + intSize;
*((int*)pagePtr) = metaData.numberOfAttr;
pagePtr = pagePtr + intSize;
// Copy all attribute's detail
for (i = 0; i < schema->numAttr; i++) {
strncpy(pagePtr, schema->attrNames[i], MAX_ATTRNAME_LEN);
pagePtr = pagePtr + MAX_ATTRNAME_LEN;
*(int*)pagePtr = (int)schema->dataTypes[i];
pagePtr = pagePtr + intSize;
*(int*)pagePtr = (int)schema->typeLength[i];
pagePtr = pagePtr + intSize;
}
*(int*)pagePtr = (int)schema->keySize;
pagePtr = pagePtr + intSize;
//Copy all key details
for (i = 0; i < schema->keySize; i++) {
*(int*)pagePtr = schema->keyAttrs[i];
pagePtr = pagePtr + intSize;
}
retVal = writeBlock(META_PAGENO, &fh, page);
if (retVal != RC_OK) {
printf("Writing block failed\n");
goto END;
}
//For validating the write
//retVal = readBlock(META_PAGENO, &fh, readPagePtr);
//if (retVal != RC_OK)
//{
//printf("Reading block failed\n");
//goto END;
//}
retVal = closePageFile(&fh);
if (retVal != RC_OK) {
printf("close pageFile failed");
goto END;
}
/* enable below function to cross verify data */
printRecordManager(&metaData, schema, "createTable");
END:
return retVal;
}
RC openTable(RM_TableData *rel, char *name)
{
RC retVal = RC_OK;
SM_PageHandle pagePtr;
RecordMgrData* recordMgrData = (RecordMgrData*)malloc(sizeof(RecordMgrData));
Schema *schema = (Schema*)malloc(sizeof(Schema));
int i = 0;
int intSize = sizeof(int);
BM_PageHandle bufferPageHandle;
rel->mgmtData = recordMgrData;
rel->name = name;
retVal = initBufferPool(&recordMgrData->bufferPool, name, BUFFER_FRAME_SIZE, PAGE_REPLACEMENT_ALGO, NULL);
if (retVal != RC_OK) {
printf("BufferPool initialization failed \n");
return retVal;
}
retVal = pinPage(&recordMgrData->bufferPool, &bufferPageHandle, META_PAGENO);
if (retVal != RC_OK) {
printf("Pin page failed\n");
return retVal;
}
pagePtr = (char*)bufferPageHandle.data;
recordMgrData->numberOfTuples = *((int*)pagePtr);
pagePtr = pagePtr + intSize;
recordMgrData->firstFreePage = *((int*)pagePtr);
pagePtr = pagePtr + intSize;
recordMgrData->recordSize = *((int*)pagePtr);
pagePtr = pagePtr + intSize;
recordMgrData->numberOfAttr = *((int*)pagePtr);
schema->numAttr = *((int*)pagePtr);
pagePtr = pagePtr + intSize;
// based on attrib num allocate memory for details of attrib
schema->attrNames = (char**)malloc((sizeof(char*))*(schema->numAttr));
schema->dataTypes = (DataType*)malloc(sizeof(DataType)*(schema->numAttr));
schema->typeLength = (int*)malloc(sizeof(int)*schema->numAttr);
//allocate and copy back every attribute's detail
for (i = 0; i < schema->numAttr; i++) {
schema->attrNames[i] = (char*)malloc(MAX_ATTRNAME_LEN);
strncpy( schema->attrNames[i], pagePtr, MAX_ATTRNAME_LEN);
pagePtr = pagePtr + MAX_ATTRNAME_LEN;
schema->dataTypes[i] = (*(int*)pagePtr);
pagePtr = pagePtr + intSize;
schema->typeLength[i] = (*(int*)pagePtr);
pagePtr = pagePtr + intSize;
}
schema->keySize = *(int*)pagePtr;
pagePtr = pagePtr + intSize;
schema->keyAttrs = (int*)malloc(((sizeof(int))*(schema->keySize)));
//copy all key details
for (i = 0; i < schema->keySize; i++) {
schema->keyAttrs[i] = *(int*)pagePtr;
pagePtr = pagePtr + intSize;
}
rel->schema = schema;
retVal = unpinPage(&recordMgrData->bufferPool, &bufferPageHandle);
if (retVal != RC_OK) {
printf("Unpin page failed\n");
return retVal;
}
/* enable below function to cross verify data */
printRecordManager(recordMgrData, schema, "OpenTable");
return retVal;
}
RC closeTable(RM_TableData *rel)
{
RC retVal = RC_OK;
//SM_FileHandle fh;
RecordMgrData* recordMgrData = (RecordMgrData*)rel->mgmtData;
BM_PageHandle bufferPageHandle;
retVal = pinPage(&recordMgrData->bufferPool, &bufferPageHandle, META_PAGENO);
if (retVal != RC_OK) {
printf("Pin page failed\n");
return retVal;
}
char* slotPageData = bufferPageHandle.data;
//First data item in page is numberofTuples, update the field with new data
*(int*)slotPageData = recordMgrData->numberOfTuples;
markDirty(&recordMgrData->bufferPool, &bufferPageHandle);
retVal = unpinPage(&recordMgrData->bufferPool, &bufferPageHandle);
if (retVal != RC_OK) {
printf("Unpin page failed\n");
return retVal;
}
retVal = shutdownBufferPool(&recordMgrData->bufferPool);
if (retVal != RC_OK) {
printf("Shutdown buffer pool failed\n");
return retVal;
}
if (rel->mgmtData != NULL) {
free(rel->mgmtData);
rel->mgmtData = NULL;
}
if (rel->schema != NULL) {
freeSchema(rel->schema);
}
return retVal;
}
RC deleteTable(char *name)
{
RC retVal = RC_OK;
retVal = destroyPageFile(name);
if (retVal != RC_OK) {
printf("destroyPageFile failed");
return retVal;
}
return retVal;
}
int getNumTuples(RM_TableData *rel)
{
RecordMgrData* recordMgrData = (RecordMgrData*)rel->mgmtData;
return recordMgrData->numberOfTuples;
}
int searchForFreeSlot(char* bufferSlotPage, int totalSlotCount, int recordSizeWithDelimiter) {
int retVal = -1;
int i = 0;
for (i = 0; i < totalSlotCount; i++) {
if (bufferSlotPage[recordSizeWithDelimiter*i] != RECORD_DELIMITER){
retVal = i;
return retVal;
}
}
return retVal;
}
// handling records in a table
RC insertRecord(RM_TableData *rel, Record *record) {
RC retVal = RC_OK;
RecordMgrData* recordMgrData = (RecordMgrData*)rel->mgmtData;
int recordSizeWithDelimiter = recordMgrData->recordSize + 1; // + 1 for extra delimiter character
int recordSizeWithoutDelimiter = recordMgrData->recordSize;
RID *rid = &(record->id);
char *bufferSlotPage = NULL;
int totalSlotCount = 0;
BM_PageHandle bufferPageHandle;
/**********************Label************************/
retryWithNextPage:
// update record id
rid->page = recordMgrData->firstFreePage;
rid->slot = -1;
// pin the free page to write record
retVal = pinPage(&recordMgrData->bufferPool, &bufferPageHandle, rid->page);
if (retVal != RC_OK) {
printf("Pin page failed\n");
return retVal;
}
// get the page from buffer slot and insert record
bufferSlotPage = bufferPageHandle.data;
totalSlotCount = (int)(PAGE_SIZE / recordSizeWithDelimiter);
rid->slot = searchForFreeSlot(bufferSlotPage, totalSlotCount, recordSizeWithDelimiter);
if (rid->slot == -1) {
//printf("No Free slot in current page retrying with nextPage");
retVal = unpinPage(&recordMgrData->bufferPool, &bufferPageHandle);
if (retVal != RC_OK) {
printf("Unpin page failed\n");
return retVal;
}
recordMgrData->firstFreePage++;
goto retryWithNextPage;
}
retVal = markDirty(&recordMgrData->bufferPool, &bufferPageHandle);
if (retVal != RC_OK) {
printf("markDirty failed\n");
return retVal;
}
// move pointer to slot address
bufferSlotPage = bufferSlotPage + rid->slot * recordSizeWithDelimiter;
// add delimiter in beginning
*bufferSlotPage = RECORD_DELIMITER;
bufferSlotPage = bufferSlotPage + 1;
memcpy(bufferSlotPage, record->data, recordSizeWithoutDelimiter);
retVal = unpinPage(&recordMgrData->bufferPool, &bufferPageHandle);
if (retVal != RC_OK) {
printf("Unpin page failed\n");
return retVal;
}
// copy updated new record id
record->id = *rid;
// update totalNoOfTuples
recordMgrData->numberOfTuples++;
return retVal;
}
RC deleteRecord(RM_TableData *rel, RID id) {
RC retVal = RC_OK;
RecordMgrData* recordMgrData = (RecordMgrData*)rel->mgmtData;
int recordSizeWithDelimiter = recordMgrData->recordSize + 1; // + 1 for extra delimiter character
int recordSizeWithoutDelimiter = recordMgrData->recordSize;
char *bufferSlotPage = NULL;
char *tempBufferSlotPage = NULL; // for address movement
BM_PageHandle bufferPageHandle;
RID *rid = &id;
// pin the free page to write record
retVal = pinPage(&recordMgrData->bufferPool, &bufferPageHandle, rid->page);
if (retVal != RC_OK) {
printf("Pin page failed\n");
return retVal;
}
//As we are deleting we are updating number of tuples
recordMgrData->numberOfTuples--;
bufferSlotPage = bufferPageHandle.data;
// move to the slot which needs to be deleted
tempBufferSlotPage = bufferSlotPage + (recordSizeWithDelimiter * rid->slot);
if (TOMBSTONE) {
// add tombstone to avoid reusing
*tempBufferSlotPage = RECORD_DELIMITER_TOMB;
}
else {
// we want to reuse deleted record space
*tempBufferSlotPage = '\0';
}
retVal = markDirty(&recordMgrData->bufferPool, &bufferPageHandle);
if (retVal != RC_OK) {
printf("markDirty failed\n");
return retVal;
}
retVal = unpinPage(&recordMgrData->bufferPool, &bufferPageHandle);
if (retVal != RC_OK) {
printf("Unpin page failed\n");
return retVal;
}
return retVal;
}
RC updateRecord(RM_TableData *rel, Record *record)
{
RC retVal = RC_OK;
RecordMgrData* recordMgrData = (RecordMgrData*)rel->mgmtData;
int recordSizeWithDelimiter = recordMgrData->recordSize + 1; // + 1 for extra delimiter character
int recordSizeWithoutDelimiter = recordMgrData->recordSize;
char *bufferSlotPage = NULL;
char *tempBufferSlotPage = NULL; // for address movement
BM_PageHandle bufferPageHandle;
RID *rid = &(record->id);
// pin the free page to write record
retVal = pinPage(&recordMgrData->bufferPool, &bufferPageHandle, rid->page);
if (retVal != RC_OK) {
printf("Pin page failed\n");
return retVal;
}
bufferSlotPage = bufferPageHandle.data;
tempBufferSlotPage = bufferSlotPage;
tempBufferSlotPage = tempBufferSlotPage + recordSizeWithDelimiter * (rid->slot);
// skip delimiter
tempBufferSlotPage = tempBufferSlotPage + 1;
memcpy(tempBufferSlotPage, record->data, recordSizeWithoutDelimiter);
retVal = markDirty(&recordMgrData->bufferPool, &bufferPageHandle);
if (retVal != RC_OK) {
printf("markDirty failed\n");
return retVal;
}
retVal = unpinPage(&recordMgrData->bufferPool, &bufferPageHandle);
if (retVal != RC_OK) {
printf("Unpin page failed\n");
return retVal;
}
return retVal;
}
RC getRecord(RM_TableData *rel, RID id, Record *record)
{
RC retVal = RC_OK;
RecordMgrData* recordMgrData = (RecordMgrData*)rel->mgmtData;
RID *rid = &id;
int recordSizeWithDelimiter = recordMgrData->recordSize + 1; // + 1 for extra delimiter character
int recordSizeWithoutDelimiter = recordMgrData->recordSize;
//RID *rid = &(record->id);
char *bufferSlotPage = NULL;
char *recordData = NULL;
BM_PageHandle bufferPageHandle;
int maxSlots = (int)(PAGE_SIZE / recordSizeWithDelimiter);
if(rid->slot > maxSlots)
{
retVal = RC_RECORD_NOT_FOUND;
return retVal;
}
// pin the page to read record
retVal = pinPage(&recordMgrData->bufferPool, &bufferPageHandle, rid->page);
if (retVal != RC_OK) {
printf("Pin page failed\n");
return retVal;
}
// get the page from buffer slot and insert record
bufferSlotPage = bufferPageHandle.data;
// move to the slot in the give page
bufferSlotPage = bufferSlotPage + (recordSizeWithDelimiter * (rid->slot));
if (*bufferSlotPage != RECORD_DELIMITER)
{
retVal = RC_RECORD_NOT_FOUND;
unpinPage(&recordMgrData->bufferPool, &bufferPageHandle);
return retVal;
}
else {
// move one character so we wont read delimiter to record data
bufferSlotPage = bufferSlotPage + 1;
// updated data
recordData = record->data;
memcpy(recordData, bufferSlotPage, recordSizeWithoutDelimiter);
// updated id
record->id = id;
}
retVal = unpinPage(&recordMgrData->bufferPool, &bufferPageHandle);
if (retVal != RC_OK) {
printf("Unpin page failed\n");
return retVal;
}
return retVal;
}
// scans
RC startScan(RM_TableData *rel, RM_ScanHandle *scan, Expr *cond)
{
RC retVal = RC_OK;
RM_ScaningRecordInfo *scan_mgmt = (RM_ScaningRecordInfo *)malloc(sizeof(RM_ScaningRecordInfo));
scan->rel = rel;
scan->mgmtData= scan_mgmt;
scan_mgmt->pageCurrentPosition = 1;
scan_mgmt->slotCurrentPosition = 0;
scan_mgmt->condition = cond;
return retVal;
}
RC next(RM_ScanHandle *scan, Record *record)
{
RC retVal = RC_OK;
RecordMgrData *recordMgrData = (RecordMgrData *)scan->rel->mgmtData;
RM_ScaningRecordInfo *scan_mgmt = (RM_ScaningRecordInfo *)scan->mgmtData;
Value *value;
int recordSizeWithDelimiter = recordMgrData->recordSize + 1; // + 1 for extra delimiter character
RC evalRet = RC_OK;
bool tupleFound = FALSE;
record->id.page = scan_mgmt->pageCurrentPosition;
record->id.slot = scan_mgmt->slotCurrentPosition;
retVal = getRecord(scan->rel, record->id, record); //Get the record information
while(retVal != RC_RECORD_NOT_FOUND)
{
if(scan_mgmt->condition != NULL)
{
evalRet = evalExpr(record, scan->rel->schema, scan_mgmt->condition, &value);
if(evalRet == RC_OK)
{
if(value->dt == DT_BOOL && value->v.boolV == TRUE)
{
tupleFound = TRUE;
break;
}
if(value->dt == DT_INT && value->v.intV >= 1)
{
tupleFound = TRUE;
break;
}
}
}
else
{
tupleFound = TRUE;
break;
}
if(scan_mgmt->slotCurrentPosition < (int)(PAGE_SIZE / recordSizeWithDelimiter))
{
scan_mgmt->slotCurrentPosition++;
}
else if (scan_mgmt->pageCurrentPosition <= recordMgrData->firstFreePage)
{
scan_mgmt->pageCurrentPosition++;
scan_mgmt->slotCurrentPosition = 0;
}
else
{
break;
}
record->id.page = scan_mgmt->pageCurrentPosition;
record->id.slot = scan_mgmt->slotCurrentPosition;
retVal = getRecord(scan->rel, record->id, record); //Get the record information
}
if(tupleFound != TRUE)
{
retVal = RC_RM_NO_MORE_TUPLES;
}
else
{
if(scan_mgmt->slotCurrentPosition < (int)(PAGE_SIZE / recordSizeWithDelimiter))
{
scan_mgmt->slotCurrentPosition++;
}
else if (scan_mgmt->pageCurrentPosition <= recordMgrData->firstFreePage)
{
scan_mgmt->pageCurrentPosition++;
scan_mgmt->slotCurrentPosition = 0;
}
}
return retVal;
}
RC closeScan(RM_ScanHandle *scan)
{
RM_ScaningRecordInfo *scan_mgmt = (RM_ScaningRecordInfo *)scan->mgmtData;
free(scan_mgmt);
scan->mgmtData = NULL;
return RC_OK;
}
// dealing with schemas
int getRecordSize(Schema *schema)
{
int recordSize = 0;
int i;
for (i = 0; i < schema->numAttr; i++)
{
switch (schema->dataTypes[i]) {
case DT_BOOL:
recordSize = recordSize + sizeof(bool);
break;
case DT_FLOAT:
recordSize = recordSize + sizeof(float);
break;
case DT_INT:
recordSize = recordSize + sizeof(int);
break;
case DT_STRING:
recordSize = recordSize + schema->typeLength[i];
break;
default:
printf("\ngetRecordSize : Shouldn't be here!!\n");
break;
}
}
return recordSize;
}
Schema *createSchema(int numAttr, char **attrNames, DataType *dataTypes, int *typeLength, int keySize, int *keys) {
Schema *schema = malloc(sizeof(Schema));
schema->attrNames = attrNames;
schema->dataTypes = dataTypes;
schema->keyAttrs = keys;
schema->keySize = keySize;
schema->numAttr = numAttr;
schema->typeLength = typeLength;
return schema;
}
RC freeSchema(Schema *schema) {
RC retVal = RC_OK;
int i;
if(schema != NULL)
{
if (schema->dataTypes != NULL) {
free(schema->dataTypes);
schema->dataTypes = NULL;
}
if (schema->typeLength != NULL) {
free(schema->typeLength);
schema->typeLength = NULL;
}
if (schema->keyAttrs != NULL) {
free(schema->keyAttrs);
schema->keyAttrs = NULL;
}
if(schema->attrNames != NULL) {
for(i = 0; i < schema->numAttr; i++)
{
if(schema->attrNames[i] != NULL)
free(schema->attrNames[i]);
}
free(schema->attrNames);
}
free(schema);
schema = NULL;
}
return retVal;
}
// dealing with records and attribute values
RC createRecord(Record **record, Schema *schema) {
RC retVal = RC_OK;
*record = (Record*)malloc(sizeof(Record));
(*record)->data = (char*)malloc(getRecordSize(schema));
(*record)->id.page = -1;
(*record)->id.slot = -1;
return retVal;
}
RC freeRecord(Record *record) {
RC retVal = RC_OK;
if (record != NULL) {
if (record->data != NULL) {
free(record->data);
record->data = NULL;
}
free(record);
}
return retVal;
}
RC getAttr(Record *record, Schema *schema, int attrNum, Value **value) {
RC retVal = RC_OK;
int offsetInsideRecord = 0;
char* recordData = record->data;
int stringLength = 0;
char* tempBuffer = NULL;
*value = (Value*)malloc(sizeof(Value));
findOffsetForAttrNum(attrNum, schema, &offsetInsideRecord);
// move record pointer to the attrNum position
recordData = recordData + offsetInsideRecord;
switch (schema->dataTypes[attrNum])
{
case DT_BOOL:
(*value)->dt = DT_BOOL;
memcpy(&((*value)->v.boolV), recordData, sizeof(bool));
break;
case DT_FLOAT:
(*value)->dt = DT_FLOAT;
memcpy(&((*value)->v.floatV), recordData, sizeof(float));
break;
case DT_INT:
(*value)->dt = DT_INT;
memcpy(&((*value)->v.intV), recordData, sizeof(int));
break;
case DT_STRING:
stringLength = 0;
stringLength = schema->typeLength[attrNum];
(*value)->dt = DT_STRING;
(*value)->v.stringV = (char*)malloc(stringLength + 1);
strncpy((*value)->v.stringV, recordData, stringLength);
(*value)->v.stringV[stringLength] = '\0';
break;
default:
printf("setAttr() Shouldn't be here !!!\n");
break;
}
return retVal;
}
RC setAttr(Record *record, Schema *schema, int attrNum, Value *value) {
RC retVal = RC_OK;
int offsetInsideRecord = 0;
char* recordData = record->data;
int stringLength = 0;
char* tempBuffer = NULL;
findOffsetForAttrNum(attrNum, schema, &offsetInsideRecord);
// move record pointer to the attrNum position
recordData = recordData + offsetInsideRecord;
switch (schema->dataTypes[attrNum])
{
case DT_BOOL:
*(bool*)recordData = value->v.boolV;
break;
case DT_FLOAT:
*(float*)recordData = value->v.floatV;
break;
case DT_INT:
*(int*)recordData = value->v.intV;
break;
case DT_STRING:
stringLength = 0;
stringLength = schema->typeLength[attrNum];
tempBuffer = (char*)malloc(stringLength + 1);
strncpy(tempBuffer, value->v.stringV, stringLength);
// add delimiter at the end
tempBuffer[stringLength] = '\0';
strncpy(recordData, tempBuffer, stringLength);
free(tempBuffer);
break;
default:
printf("setAttr() Shouldn't be here !!!\n");
break;
}
return retVal;
}
// find the offset for the attrNum and give back the offset
RC findOffsetForAttrNum(int attrNum, Schema *schema, int *offset) {
RC retVal = RC_OK;
int posOffset = 0;
int currentPosition = 0;
DataType dataTypes;
// while attribute's position is not reached add the typelength /sizeof to current offset
while (currentPosition < attrNum) {
// get data type
dataTypes = schema->dataTypes[currentPosition];
if (dataTypes == DT_STRING) {
posOffset = posOffset + schema->typeLength[currentPosition];
}
else if (dataTypes == DT_FLOAT) {
posOffset = posOffset + sizeof(float);
}
else if (dataTypes == DT_INT) {
posOffset = posOffset + sizeof(int);
}
else if (dataTypes == DT_BOOL) {
posOffset = posOffset + sizeof(bool);
}
currentPosition++;
}
*offset = posOffset;
return retVal;
}
|
C
|
#include <iostream>
//class A;
template <class T>
class base
{
public:
//T Tval_; //This is wrong
T * pt(){return static_cast<T*>(this);}//static_cast<T*>(this);
int baseVal_;
base()
{
baseVal_ = 99;
std::cout << "This is in base(), baseVal_ = " << baseVal_ << std::endl;
pt()->printA();
}
base(int val)
{
baseVal_ = val;
std::cout << "This is in base(int val), baseVal_ = " << baseVal_ << std::endl;
}
};
class A: public base<A>
{
public:
int AVal_;
A()
:
base<A>()
{
AVal_ = 999;
std::cout << "This is in A(), baseVal_ = " << baseVal_ << ", AVal_ = " << AVal_ << std::endl;
}
A(int val)
:
base<A>(val)
{
AVal_ = val;
std::cout << "This is in A(int val), baseVal_ = " << baseVal_ << ", AVal_ = " << AVal_ << std::endl;
}
void printA()
{
std::cout << "This is in printA()" << std::endl;
}
};
int main()
{
A a1;
A a2(1);
};
|
C
|
// tjadanel - C Programming 2nd Ed.
// Chapter 6 - Program Exercise 6.12
// This program
#include <stdio.h>
int main(void)
{
float n, e = 1.0f;
printf("Enter a small floating point number: ");
scanf("%f", &n);
int term = 1, factorial = 1;
for (;;) {
factorial *= term;
if (1.0f / factorial < n) {
break;
}
e += (1.0f / factorial);
term++;
}
printf("Result is: %f\n", e);
return 0;
}
|
C
|
#include "../HEADER/header.h"
void swap(long *a, long *b)
{
long temp;
temp = *a;
*a = *b;
*b = temp;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int even(int n)
{
if (n % 2 == 0)
return 1;
else if (n % 2 == 1)
return 0;
}
int absolute(int n)
{
return abs(n);
}
int sign(int n)
{
if (n < 0)
return -1;
else if (n > 0)
return 1;
else
return 0;
}
int main()
{
int num;
int a, b, c;
printf(" ԷϽÿ: ");
scanf("%d", &num);
a = even(num);
(a == 1) ? printf("even() : ¦\n") : printf("even() : Ȧ\n");
b = absolute(num);
printf("absolute() : %d\n", b);
c = sign(num);
(c == -1) ? printf("sign() : ") :
(c == 1) ? printf("sign() : ") : printf("sign() : 0");
return 0;
}
|
C
|
#ifndef __SCHEDULER_H__
#define __SCHEDULER_H__
//------ Loop 1 -------
// Initialize a "loop" to run every X milliseconds
// Sets up a variable to hold time of last run
// Must be called outside of the infinite loop
#define INIT_LOOP_1_FREQUENCY(X) \
unsigned long lastRun1 = 0;
// Start of code to run every X milliseconds
// May run slower than every X milliseconds if loop and rest of code too slow
#define BEGIN_LOOP_1_FREQUENCY(X) \
if ( (lastRun1 + (X)) <= millis()) {
// end of loop to run every X milliseconds
#define END_LOOP_1_FREQUENCY(X) \
lastRun1 = millis(); \
}
//------- Loop 2 --------
// Initialize a "loop" to run every X milliseconds
// Sets up a variable to hold time of last run
// Must be called outside of the infinite loop
#define INIT_LOOP_2_FREQUENCY(X) \
unsigned long lastRun2 = 0;
// Start of code to run every X milliseconds
// May run slower than every X milliseconds if loop and rest of code too slow
#define BEGIN_LOOP_2_FREQUENCY(X) \
if ( (lastRun2 + (X)) <= millis()) {
// end of loop to run every X milliseconds
#define END_LOOP_2_FREQUENCY(X) \
lastRun2 = millis(); \
}
//-------- Loop 3 ---------
// Initialize a "loop" to run every X milliseconds
// Sets up a variable to hold time of last run
// Must be called outside of the infinite loop
#define INIT_LOOP_3_FREQUENCY(X) \
unsigned long lastRun3 = 0;
// Start of code to run every X milliseconds
// May run slower than every X milliseconds if loop and rest of code too slow
#define BEGIN_LOOP_3_FREQUENCY(X) \
if ( (lastRun3 + (X)) <= millis()) {
// end of loop to run every X milliseconds
#define END_LOOP_3_FREQUENCY(X) \
lastRun3 = millis(); \
}
#endif
|
C
|
#include "holberton.h"
/**
*read_textfile - Reads a text file and prints it to the POSIX standard output.
*@filename: Name of the file to read.
*@letters: Letters to print.
*Return: Number of letters could read-print. 0 if file cannot opened or NULL.
*/
ssize_t read_textfile(const char *filename, size_t letters)
{
char buff;/*Buffer*/
int RETVAL, READVAL, file;/*Return Value - Read Value*/
unsigned int a;/*Number of letters*/
file = RETVAL = a = 0;
if (filename == NULL)/*Guard case*/
return (0);
file = open(filename, O_RDWR);
if (file == -1)/*Guard Case*/
return (0);
READVAL = read(file, &buff, 1);
if (READVAL == -1)/*Guard Case*/
return (0);
for (a = 0; READVAL != 0 && a != letters; a++)/*Counting Letters*/
{
RETVAL = write(STDOUT_FILENO, &buff, 1);
if (RETVAL == -1)
return (0);
READVAL = read(file, &buff, 1);
if (READVAL == -1)
return (0);
}
READVAL = close(file);
if (READVAL == -1)
return (0);
return (a);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "wavetype.h"
#include "exception.h"
typedef struct TriangleFilter
{
int l;
int c;
int h;
float step1;
float step2;
}TriangleFilter;
#define TRAINGLE_PARA(low,med,high,para) {\
para.c = med;\
\
if(low==med)\
para.l = med-1;\
else\
para.l = low;\
\
if(med==high)\
para.h = med+1;\
else\
para.h = high;\
\
para.step1 = 2.0/((float)((para.h-para.l)*(para.c-para.l)));\
para.step2 = 2.0/((float)((para.h-para.l)*(para.h-para.c)));\
}
#define USE_FILTER(wave,filter,feature) {\
float k;\
\
feature = 0.0;\
k = 0.0;\
for(j=filter.l+1;j<=filter.c;j++)\
{\
k = k + filter.step1;\
feature = feature + (wave->data[cn][j])*k;\
}\
for(j=filter.c+1;j<=filter.h;j++)\
{\
k = k - filter.step2;\
feature = feature + (wave->data[cn][j])*k;\
}\
}
static TriangleFilter g_uniform_para[128];
static int g_uniform_low_frequency = 0;
static int g_uniform_high_frequency = 0;
static int g_uniform_num = 0;
void GetUniformPara()
{
int i;
int frq[130];
float frequency;
float step;
step = ((float)(g_uniform_high_frequency - g_uniform_low_frequency))/((float)(g_uniform_num+1));
frequency = (float)g_uniform_low_frequency;
frq[0] = g_uniform_low_frequency;
for(i=1;i<=g_uniform_num;i++)
{
frequency = frequency + step;
frq[i] = (int)(frequency + 0.5);
}
frq[i] = g_uniform_high_frequency;
for(i=0;i<g_uniform_num;i++)
TRAINGLE_PARA(frq[i],frq[i+1],frq[i+2],g_uniform_para[i]);
}
/////////////////////////////////////////////////////////
// 接口功能:
// 对功率谱使用均匀分布的三角滤波器滤波
//
// 参数:
// (I)src(NO) - 输入的功率谱
// (I)Start(0) - 滤波的起始位置,对应滤波器的最低频率
// (I)End(src->size) - 滤波的终止位置,对应滤波器的最高频率
// (I)NumCutOffFreq(NO) - 使用的滤波器个数
// (O)MelFilterFeature(NO) - 输出的各通道滤波结果
//
// 返回值:
// 无
/////////////////////////////////////////////////////////
void maUniformFilterBank(MAWave *src, int Start, int End, int NumUniformFilter, float** UniformFilterFeature)
{
int i,j;
int cn;
float k;
maException((src == NULL),"invalid input",EXIT);
maException((src->info.wave_type != MA_WAVE_PS),"please check input wave type",NULL);
maException((UniformFilterFeature == NULL),"invalid input",EXIT);
if(Start == MA_DEFAULT)
Start = 0;
maException((Start < 0),"invalid input",EXIT);
if(End == MA_DEFAULT)
End = src->size;
maException((End > src->size),"invalid input",EXIT);
maException((NumUniformFilter > 128)||(NumUniformFilter <0),"invalid operate",EXIT);
if((g_uniform_low_frequency != Start)||(g_uniform_high_frequency != End)||(g_uniform_num != NumUniformFilter))
{
g_uniform_low_frequency = Start;
g_uniform_high_frequency = End;
g_uniform_num = NumUniformFilter;
GetUniformPara();
}
for(cn = 0;cn<src->cn;cn++)
for(i=0;i<NumUniformFilter;i++)
USE_FILTER(src,g_uniform_para[i],UniformFilterFeature[cn][i]);
}
static TriangleFilter g_mel_para[128];
static int g_mel_low_frequency = 0;
static int g_mel_high_frequency = 0;
static int g_mel_num = 0;
#define HZ2MEL(hz) (float)(1127.0*log(1.0 + ((double)(hz))/700.0))
#define MEL2HZ(mel) (float)(700.0*exp(((double)(mel))/1127.0) - 700.0)
void GetMelPara()
{
int i;
float h2w_low,h2w_high,h2w;
float hz;
int mel[130];
h2w_low=HZ2MEL(g_mel_low_frequency);
h2w_high=HZ2MEL(g_mel_high_frequency);
h2w=(h2w_high-h2w_low)/(float)(g_mel_num+1);
mel[0] = g_mel_low_frequency;
hz = h2w_low;
for(i=1;i<=g_mel_num;i++)
{
hz = hz + h2w;
mel[i] = (int)(MEL2HZ(hz)+0.5);
}
mel[i] = g_mel_high_frequency;
for(i=0;i<g_mel_num;i++)
TRAINGLE_PARA(mel[i],mel[i+1],mel[i+2],g_mel_para[i]);
}
/////////////////////////////////////////////////////////
// 接口功能:
// 对功率谱使用Mel滤波器滤波
//
// 参数:
// (I)src(NO) - 输入的功率谱
// (I)Start(0) - 滤波的起始位置,对应滤波器的最低频率
// (I)End(src->size) - 滤波的终止位置,对应滤波器的最高频率
// (I)NumCutOffFreq(NO) - 使用的滤波器个数
// (O)MelFilterFeature(NO) - 输出的各通道滤波结果
//
// 返回值:
// 无
/////////////////////////////////////////////////////////
void maMelFilterBank(MAWave *src, int Start, int End, int NumMelFilter, float** MelFilterFeature)
{
int i,j;
int cn;
float k;
maException((src == NULL),"invalid input",EXIT);
maException((src->info.wave_type != MA_WAVE_PS),"please check input wave type",NULL);
maException((MelFilterFeature == NULL),"invalid input",EXIT);
if(Start == MA_DEFAULT)
Start = 0;
maException((Start < 0),"invalid input",EXIT);
if(End == MA_DEFAULT)
End = src->size;
maException((End > src->size),"invalid input",EXIT);
maException((NumMelFilter > 128)||(NumMelFilter <0),"invalid operate",EXIT);
if((g_mel_low_frequency != Start)||(g_mel_high_frequency != End)||(g_mel_num != NumMelFilter))
{
g_mel_low_frequency = Start;
g_mel_high_frequency = End;
g_mel_num = NumMelFilter;
GetMelPara();
}
for(cn = 0;cn<src->cn;cn++)
for(i=0;i<NumMelFilter;i++)
USE_FILTER(src,g_mel_para[i],MelFilterFeature[cn][i]);
}
|
C
|
/* Copyright 2017 Federico Cerisola */
/* MIT License (see root directory) */
/* see header file for detailed documentation of each function */
#include <stdlib.h>
#include <math.h>
double * create_linear_grid(const double xmin, const double xmax,
const int npoints, const int round_digits)
{
double slope = (xmax - xmin)/(npoints - 1);
double * grid = malloc(npoints * sizeof(*grid));
for (int n = 0; n < npoints; n++) {
grid[n] = xmin + n * slope;
}
if (round_digits) {
for (int n = 0; n < npoints; n++) {
grid[n] = ((int)(grid[n]*((int)pow(10, round_digits))))/((double)pow(10, round_digits));
}
}
return grid;
}
int update_online_mean_variance(double new_value, int n, double * mean, double * variance)
{
double delta = new_value - (*mean);
(*mean) += delta / n;
double delta2 = new_value - (*mean);
(*variance) += delta * delta2;
return 0;
}
|
C
|
#include "trtSettings.h"
#include "trtkernel_1284.c"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <avr/sleep.h>
// serial communication library
// Don't mess with the semaphores
#define SEM_RX_ISR_SIGNAL 1
#define SEM_STRING_DONE 2 // user hit <enter>
#include "trtUart.h"
#include "trtUart.c"
#include "chord_lookup_table.h"
#include <util/delay.h>
#include "WS2811.h"
#define BIT(B) (0x01 << (uint8_t)(B))
#define SET_BIT_HI(V, B) (V) |= (uint8_t)BIT(B)
#define SET_BIT_LO(V, B) (V) &= (uint8_t)~BIT(B)
#define PAUSE 1000 // msec
#define DELAY 10 // msec
#define COUNT_INDEX 37
// Define the output function, using pin 0 on port a.
DEFINE_WS2811_FN(WS2811RGB, PORTA, 0)
// UART file descriptor
// putchar and getchar are in uart.c
FILE uart_str = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW);
// semaphore to protect shared variable
#define SEM_SHARED 3
// --- control LEDs from buttons and uart -------------------
// input arguments to each thread
// not actually used in this example
int args[2] ;
// song table containing chord indices at each time step
int song[1000];
// current indices into the song table and chord table
volatile int song_idx = 0;
volatile int chord_idx = 0;
// tempo of song
int bpm;
// time signature of song
int time_sig;
// current count-in value
int count;
// flag:
// 0 means nothing is happening
// 1 means we are in practice mode
// 2 means we are in play mode
char go = 0;
/* send the output signal to the RGB LEDs periodically */
void driveLED(void* args) {
long rel;
long dead;
while (1) {
// use RGB LED driver with current chord
WS2811RGB(lookup_table[chord_idx], 16);
rel = trtCurrentTime() + SECONDS2TICKS(0.01);
dead = trtCurrentTime() + SECONDS2TICKS(0.01);
trtSleepUntil(rel, dead);
}
}
/* convert a song string (from USART) into a chord table */
void strToSong(char *str, int *song) {
int song_idx = 0;
int str_idx = 0;
while( str_idx < strlen( str ) ) {
char buf[3];
strncpy(buf, str + str_idx, 2);
song[song_idx++] = atoi(buf);
str_idx += 3;
}
}
/* get the string from the USART */
void serialComm(void* args) {
int val;
char cmd[1000];
while(1) {
gets(cmd);
trtWait(SEM_STRING_DONE);
// don't interrupt the current song
if (go != 2) {
// practice mode
if (cmd[0] == '1') {
char buf1[3];
strncpy(buf1, cmd + 2, 2);
chord_idx = atoi(buf1);
go = 1;
continue;
}
// play mode
char buf2[4];
strncpy(buf2, cmd + 2, 3);
bpm = atoi(buf2);
if (bpm < 60) {
bpm = 60;
}
if (bpm > 240) {
bpm = 240;
}
// convert bpm to timer period
OCR3A = (62500 * 60) / bpm - 1;
char buf3[2];
strncpy(buf3, cmd + 6, 1);
time_sig = atoi(buf3);
if (time_sig < 1) {
time_sig = 1;
}
count = 0;
strToSong(cmd + 8, song);
song_idx = 0;
go = 2;
}
}
}
/* timer3 compare match ISR */
ISR (TIMER3_COMPA_vect) {
if(go == 2) {
if(count < time_sig) {
chord_idx = COUNT_INDEX + count;
count++;
} else {
chord_idx = song[song_idx];
// end of song
if(chord_idx == -1) {
go = 0;
chord_idx = 0;
}
song_idx++;
}
} else if (!go) {
chord_idx = 0;
}
}
/* MAIN */
int main(void) {
// setup neopixel driver
SET_BIT_HI(DDRA, 0);
SET_BIT_LO(PORTA, 0);
// setup timer 3
TCCR3B = (1<<WGM32) + 0x04; // ctc, prescale by 256
OCR3A = 10000; // 1 second (DEFAULT)
TIMSK3= (1<<OCIE3A); // enable interrupt
//init the UART -- trt_uart_init() is in trtUart.c
trt_uart_init();
stdout = stdin = stderr = &uart_str;
fprintf(stdout,"\n\r TRT 9feb2009\n\r\n\r");
// start TRT
trtInitKernel(80); // 80 bytes for the idle task stack
// --- create semaphores ----------
// You must creat the first two semaphores if you use the uart
trtCreateSemaphore(SEM_RX_ISR_SIGNAL, 0) ; // uart receive ISR semaphore
trtCreateSemaphore(SEM_STRING_DONE,0) ; // user typed <enter>
// variable protection
trtCreateSemaphore(SEM_SHARED, 1) ; // protect shared variables
// --- creat tasks ----------------
trtCreateTask(driveLED, 100, SECONDS2TICKS(1), SECONDS2TICKS(1), &(args[0]));
trtCreateTask(serialComm, 100, SECONDS2TICKS(0.1), SECONDS2TICKS(0.1), &(args[1]));
// --- Idle task --------------------------------------
// just sleeps the cpu to save power
// every time it executes
set_sleep_mode(SLEEP_MODE_IDLE);
sleep_enable();
while (1) {
sleep_cpu();
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdlib.h>
typedef struct {
char **arr;
int top, max_len;
} Stack;
int initStack(Stack *);
int pushStack(Stack *, char *);
char *popStack(Stack *);
int emptyStack(Stack *);
int destroyStack(Stack *);
Stack back_stack;
Stack forward_stack;
char nowUrl[1000];
char ignore[7] = "Ignore";
void initData() {
fflush(stdout);
static int flag = 1;
if (flag) {
initStack(&back_stack);
initStack(&forward_stack);
nowUrl[0] = '\0';
flag = 0;
}
}
char* visitPage(char *url) {
initData();
while (!emptyStack(&forward_stack)) {
free(popStack(&forward_stack));
}
if (nowUrl[0] != '\0') {
pushStack(&back_stack, nowUrl);
}
strcpy(nowUrl, url);
return url;
}
char* back() {
initData();
char *temp = popStack(&back_stack);
if (temp != NULL) {
pushStack(&forward_stack, nowUrl);
strcpy(nowUrl, temp);
} else {
temp = ignore;
}
return temp;
}
char* forward() {
initData();
char *temp = popStack(&forward_stack);
if (temp != NULL) {
pushStack(&back_stack, nowUrl);
strcpy(nowUrl, temp);
} else {
temp = ignore;
}
return temp;
}
int initStack(Stack *s) {
s->arr = (char **)malloc(1 * sizeof(char *));
s->max_len = 1;
s->top = 0;
return 1;
}
int pushStack(Stack *s, char *a) {
if (s->arr == NULL) return 0;
if (s->top == s->max_len) {
s->arr = (char **)realloc(s->arr, s->max_len * 2 * sizeof(char *));
if (s->arr == NULL) return 0;
s->max_len *= 2;
}
char *temp = (char *)malloc(strlen(a) + 1);
strcpy(temp, a);
s->arr[s->top++] = temp;
return 1;
}
char *popStack(Stack *s) {
if (!emptyStack(s)) {
--(s->top);
return s->arr[s->top];
}
return NULL;
}
int emptyStack(Stack *s) {
return !(s->top);
}
int main() {
int n;
scanf("%d", &n);
while (n--) {
char op[1024];
char* result;
scanf("%s", op);
if (strcmp(op, "VISIT") == 0) {
char url[1024];
scanf("%s", url);
result = visitPage(url);
} else if (strcmp(op, "BACK") == 0) {
result = back();
} else if (strcmp(op, "FORWARD") == 0) {
result = forward();
}
printf("%s\n", result);
}
return 0;
}
|
C
|
/*Escola Politecnica
* Departamento de Eletronica e de Computacao
* EEL270 - Computacao II - Turma: 2014/2
* Prof. Marcelo Luiz Drumond Lanza
*
* $Author: vitor.schoola $
* $Date: 2015/01/10 19:14:53 $
* $Log: geCgiHelp.c,v $
* Revision 1.1 2015/01/10 19:14:53 vitor.schoola
* Initial revision
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#include "mlcgi.h"
#include "geTypes.h"
#include "geConst.h"
#include "geError.h"
#include "geFunctions.h"
int
main ( int argc, char *argv[] )
{
environmentType environment;
languageType language;
char geLanguage [LANGUAGE_MAX_LENGTH];
if ( mlCgiInitialize ( &environment ) )
exit ( ML_CGI_OK );
if ( environment == commandLine )
{
printf("Incorrect environment. This program was developed for the web.\n");
exit( INCORRECT_ENVIRONMENT );
}
mlCgiBeginHttpHeader ( "text/html" );
mlCgiEndHttpHeader ( );
if ( mlCgiGetFormStringNoNewLines ( "geLanguage", geLanguage, LANGUAGE_MAX_LENGTH ) != ML_CGI_OK )
{
mlCgiShowErrorPage ( "Error", "Could not retrieve language", "<a href=\"geShowMainForm.cgi?geLanguage=english\">Sail back to the main page</a>" );
mlCgiFreeResources ( );
exit ( ML_CGI_OK );
}
language = HandleLanguage ( geLanguage );
if ( language == portuguese )
{
printf("<html>\n");
printf(" <head>\n");
printf(" <title> GelaDOS - Cervejarias Ajuda</title>\n");
printf(" <style> \n" );
printf(" html,body { background: url(\"../Files/background.jpg\") no-repeat center center fixed; -webkit-background-size: cover;-moz-background-size: cover; -o-background-size: cover;background-size: cover; } \n" );
printf(" </style> \n" );
printf(" </head>\n");
printf(" <body onload=\"document.getElementById('player').volume -= 0.5\">\n");
printf(" <br><div align=\"center\"><font size=\"+3\"> Cervejarias - Ajuda</font> \n" );
printf(" <table align=\"center\"> \n" );
printf(" <tr><td> \n" );
printf(" <img src=\"../Files/logo.png\" alt=\"GlaDOS\">\n" );
printf(" </td></tr></table> \n" );
printf(" Yaaaar, marujo, preste atenção que só falarei uma vez: <br>\n" );
printf(" Você está em um sistema de avaliação de cervejas.<br>\n" );
printf(" Nele você pode: <br><br>\n" );
printf(" Se estiver no grupo [Recruta]: <br>\n" );
printf(" - Avaliar cervejas<br>\n" );
printf(" - Convidar novos recrutas<br><br>\n" );
printf(" Se estiver no grupo [Pirata Experiente]: <br>\n");
printf(" - Avaliar e Criar novas cervejas no sistema<br>\n");
printf(" - Convidar novos recrutas e Piratas Experientes<br>\n");
printf(" - Banir ou perdoar recrutas <br><br>\n" );
printf(" Se estiver no grupo [Capitão]: <br>\n");
printf(" - Avaliar e Criar novas cervejas no sistema<br>\n" );
printf(" - Convidar novos recrutas, piratas experientes e capitães ( Vai dá-los barcos? ) <br>\n" );
printf(" - Banir ou perdoar qualquer uma pessoa.<br>\n" );
printf(" <br><br>Toda interação é feita depois do login e senha do usuário <br>\n" );
printf(" <a href=\"geShowMainForm.cgi?geLanguage=portuguese\">Velejar ao menu principal</a>" );
printf(" </div>\n" );
printf(" </body> " );
printf("</html>" );
}
else
{
printf("<html>\n");
printf(" <head>\n");
printf(" <title> GelaDOS - Breweries Help</title>\n");
printf(" <style> \n" );
printf(" html,body { background: url(\"../Files/background.jpg\") no-repeat center center fixed; -webkit-background-size: cover;-moz-background-size: cover; -o-background-size: cover;background-size: cover; } \n" );
printf(" </style> \n" );
printf(" </head>\n");
printf(" <body onload=\"document.getElementById('player').volume -= 0.5\">\n");
printf(" <br> \n" );
printf(" <table align=\"center\"> \n" );
printf(" <tr><td> \n" );
printf(" <img src=\"../Files/logo.png\" alt=\"GlaDOS\">\n" );
printf(" </td></tr></table> \n" );
printf(" <div align=\"center\"><font size=\"+3\"> Breweries</font> \n" );
printf(" <br>\n" );
printf(" Yaaaar, sailor, pay atention, 'cause I'll say it just once: <br>\n" );
printf(" You're in a Beer Rating System.<br>\n" );
printf(" You are able to: <br><br>\n" );
printf(" If a [Recruit]: <br>\n" );
printf(" - Rate beers<br>\n" );
printf(" - Invite new recruits<br><br>\n" );
printf(" If an [Adept Pirate]: <br>\n");
printf(" - Rate and create new beers in our system<br>\n");
printf(" - Invite new recruits and Adept Pirates<br>\n");
printf(" - Ban or Unban recruits <br><br>\n" );
printf(" If a [Captain]: <br>\n");
printf(" - Rate and create new beers in our system<br>\n" );
printf(" - Invite new recruits, adept pirates and captains ( you'll give 'em a boat? ) <br>\n" );
printf(" - Ban or unban anyone<br>\n" );
printf(" <br><br> Any and every interaction is made after logging in.<br>\n" );
printf(" <a href=\"geShowMainForm.cgi?geLanguage=english\">Sail back to the main page</a>" );
printf(" </div>\n" );
printf(" </body>" );
printf("</html>");
}
mlCgiFreeResources();
return ML_CGI_OK;
}
/* $RCSfile: geCgiHelp.c,v $ */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>
#include <string.h>
#include <openssl/sha.h>
#include "../devices/sha1.h"
#include "../devices/reduction.h"
// apt-get install libcurl4-openssl-dev
const unsigned int REP = 1000000 ;
void test_1(){
unsigned int foo = 1;
unsigned int i;
for( i = 0 ; i < REP ; i++ ){
foo = (foo*i) % 99 ;
}
}
void test_sha1(SHA1Context *h){
unsigned int i;
for( i = 0 ; i < REP ; i++ ){
SHA1Reset(h);
SHA1Input(h, (const unsigned char *) "Password", strlen("Password"));
if (!SHA1Result(h)){
printf("ERROR-- could not compute message digest\n");
break;
}
}
}
void test_sha1_openssl(){
unsigned char ibuf[] = "Password";
unsigned char obuf[20];
unsigned int i;
for (i = 0; i < REP; i++) {
SHA1(ibuf, strlen(ibuf), obuf);
}
}
void test_reduction(SHA1Context *h){
char *r = (char *) malloc(10);
unsigned int i, index;
for( i = 0 ; i < REP ; i++ ){
index = sha2index(h, i, 1);
index2plain(index,r);
}
}
void main (argc, argv)
int argc;
char *argv[];
{
clock_t t_ini1, t_fin1;
clock_t t_ini2, t_fin2;
double secs1, secs2;
reduction_init(7, "a0");
SHA1Context h;
t_ini1 = clock();
test_sha1(&h);
t_fin1 = clock();
t_ini2 = clock();
test_sha1_openssl();
t_fin2 = clock();
secs1 = (double)(t_fin1 - t_ini1) / CLOCKS_PER_SEC;
printf("TEST1: %.16g milisegundos\n", secs1 * 1000.0);
secs2 = (double)(t_fin2 - t_ini2) / CLOCKS_PER_SEC;
printf("TEST2: %.16g milisegundos\n", secs2 * 1000.0);
return 0;
}
|
C
|
#include<stdio.h>
int a=0,num=0,other=0;
void count(char c[])
/************program************/
int i;
for (i=0;a[i]!='\0';i++){
if(a[i]>='a'&&a[i]<='z')||(a[i]>='A'&&a[i]<='z')
a++;
else if(a[i]>='0'&&a[i]<='9')
num++;
else if(a[i]='')
b++
else
other++;
}
/**************end**************/
void main(){
char ch[80];
printf("input string:");
gets(ch);
count(ch);
printf("a=%d,num=%d,other=%d\n",a,num,b,other);
}
|
C
|
#include <stdio.h>
int main() {
int N[10],i,x;
scanf("%d",&x);
for(i=0; i<=9; i++)
{
printf("N[%d] = %d\n",i,x);
x=x*2;
}
return 0;
}
|
C
|
#include "lists.h"
/**
* sum_listint - returns the sum of all the data (n)
*of a listint_t linked list.
*@head:double pointer to head node.
*Return: plus of the nodes
*/
int sum_listint(listint_t *head)
{
listint_t *ptr;
int cont = 0;
if (!(head == NULL))
{
ptr = head;
while (ptr != NULL)
{
cont += ptr->n;
ptr = ptr->next;
}
return (cont);
}
return (cont);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char** argv)
{
if(argc != 4)
{
printf("usage: %s input.grey output.dat rate\n", argv[0]);
return -1;
}
const char* input = argv[1];
const char* output = argv[2];
float rate = atof(argv[3]);
FILE* fp = fopen(input, "r");
FILE* fp2 = fopen(output, (rate < 1.0)?"a":"w");
char c;
float f;
while(fread(&c, 1, 1, fp))
{
f = c;
fprintf(fp2, "%.4f ", f);
}
fprintf(fp2, "%.4f\n", rate);
fclose(fp);
fclose(fp2);
return 0;
}
|
C
|
#include"touch_screen.h"
static int fd_event0 = 0;
int open_ts(void) {
fd_event0 = open("/dev/input/event0", O_RDWR);
if (-1 == fd_event0) {
perror("Open /dev/intpu/event0 error!\n");
exit(EXIT_FAILURE);
}
return 0;
}
int read_ts(unsigned short *px, unsigned short *py) {
struct input_event SIevent;
while(1){
if (-1 == read(fd_event0, &SIevent, sizeof(SIevent))) {
perror("Read File Error!");
printf("fd: %d\n",fd_event0);
return -1;
}
if(SIevent.type == EV_ABS && SIevent.code == ABS_X && SIevent.value > 0 && SIevent.value < 800) {
*px = SIevent.value;
}
if(SIevent.type == EV_ABS && SIevent.code == ABS_Y && SIevent.value > 0 && SIevent.value < 480) {
*py = SIevent.value;
}
if(SIevent.type == EV_KEY && SIevent.code == BTN_TOUCH && SIevent.value == 0) {
break;
}
printf("read_in_OK (%d, %d)\n", *px, *py);
}
return 0;
}
int close_ts(void) {
close(fd_event0);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
int spawn_childs(int n)
{
pid_t pid;
int i;
for (i = 0; i < n; i++)
{
pid = fork();
if (pid < 0)
return -1;
else if (pid == 0)
return i + 1;
}
return 0;
}
int main(void)
{
const int LEITURA = 0;
const int ESCRITA = 1;
const int BUFFER_SIZE = 50;
const int NUMBER_OF_CHILDREN = 10;
struct s1
{
char message[4];
int round;
};
int fd[2];
if (pipe(fd) == -1)
{
perror("Pipe failed");
return 1;
}
int id = spawn_childs(NUMBER_OF_CHILDREN);
if (id == 0) //PAI
{
close(fd[LEITURA]);
int i;
for (i = 0; i < NUMBER_OF_CHILDREN; i++)
{
struct s1 s;
strcpy(s.message, "WIN");
s.round = i + 1;
sleep(1);
write(fd[ESCRITA], &s, sizeof(s));
}
close(fd[ESCRITA]);
}
if (id > 0)
{
close(fd[ESCRITA]);
struct s1 s;
read(fd[LEITURA], &s, BUFFER_SIZE);
close(fd[LEITURA]);
printf(s.message);
printf(" round %d\n", s.round);
exit(s.round);
}
int status;
int i;
for (i = 0; i < NUMBER_OF_CHILDREN; i++)
{
pid_t pid = wait(&status);
if (WIFEXITED(status))
{
int exit_round = WEXITSTATUS(status);
printf("Child with pid number %d won the round number %d\n", pid, exit_round);
}
}
return 0;
}
|
C
|
/*
File: adc.c
Date:
Info: datasheet p.150
Functions:
-adc_init()
-adc_get_sample()
Notes: Analog input is on pin 6, RC3/AN7
*/
#include <htc.h>
#include <adc.h>
/*
Considerations:
-For now using 8 MSBs instead of full 10 bit
Process for onfigure for ADC:
1) Port configuration
2) Channel selection
3) ADC voltage reference selection
4) ADC conversion clock source
5) interrupt control
6) result formatting
*/
void adc_init()
{
TRISCbits.TRISC3=1; //set RC3 input
ANSELCbits.ANSC3=1; //set RC analog input
//weak pull up??
ADCON0=0b00011100;
//ADCON1=0b
ADCON0bits.CHS=1;
}
unsigned char adc_get_sample(void) //triggers adc_sample
{
ADCON0bits.ADON=1; //ADC turned on here to conserve power
ADCON0bits.ADGO=1;
while (ADGO)
{
continue;
}
//get's 8 MSb's from ADC result high register
return (ADRESH);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.