language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>//This header file contains definitions of a number of function and datatypes used in signals
#include <sys/types.h>//This header file contains definitions of a number of data types used in system calls
#include <sys/socket.h>//The header file socket.h includes a number of definitions of structures needed for sockets
#include <string.h>
#include <sys/wait.h>
#include <netdb.h> // The file netdb.h defines the structure hostent, which will be used below.
#include <ctype.h>
#include <arpa/inet.h>
#define SHM_SIZE 1024 /* make it a 1K shared memory segment */
#define GOLD 0
#define ARMOR 1
#define AMMO 2
#define LUMBER 3
#define MAGIC 4
#define ROCK 5
#define BADKEY 6
#define PORT "5005"
#define NKEYS (sizeof(lookuptable)/sizeof(t_symstruct))
/*Handler declerations */
void sigchld_handler(int signo);
void sigint_handler(int signo);
//void sigchld_handler(int signo);
int sockfd, cnt, i,len;
pid_t parent_pid, child_pid; //process that will block on recv
struct sockaddr_in serv_addr; //serv_addr will contain the address of the server to which we want to connect.
//The variable server is a pointer to a structure of type hostent. This structure is defined in the header file netdb.h
struct hostent *server;
int inventory[6]; //This will contain the values of a chosen item, if the item has not be chosen zero will be placed instead
int quota;
char c,*fileName, *server_name,*player_name, message[SHM_SIZE], item_name[30];
FILE *fp; //Pointer to file inventory
void *__gxx_personality_v0;
typedef struct { const char *key; int val; } t_symstruct;
char buf[80];
char serv_msg[80];
/*t_symstruct lookuptable[] = {
{ "gold", GOLD }, { "armor", ARMOR }, { "ammo", AMMO }, { "lumber", LUMBER }, { "magic", MAGIC }, { "rock", ROCK },
};
t_symstruct *sym;
int keyfromstring(char *key); */
int main( int argc, char *argv[] )
{
parent_pid = getpid();
/*Check if argv is passed as argument and if it exists store it on server_name, if not terminate*/
if (argc != 6)
{
printf("Wrong number of arguments %d\n", argc);
exit(1);
}
else
{
server_name = (char*)malloc((strlen(argv[5]))*sizeof (char));
server_name = strcpy(server_name,argv[5]);
}
//getopt is explained thoroughly in server's code
while ( (c = getopt(argc, argv, "n:i:"))!= -1 )
{
switch(c)
{
case 'n':
player_name = (char*)malloc((strlen(optarg))*sizeof (char));
player_name = strcpy(player_name,optarg);
break;
case 'i':
fileName = (char*)malloc((strlen(optarg))*sizeof (char));
fileName = optarg;
break;
case '?':
if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
}
}
char cwd[80]; //cwd has the current working dirrectory
memset(cwd, 0, sizeof(cwd));
char ch;
int k=0,flag=0; //k is used for an index on item_name array, flag is for when we finished reading an item's name,
getcwd(cwd, sizeof(cwd));
cwd[strlen(cwd)] = '/'; //Put '/' at the end of cwd
strcat(cwd, fileName); //Append file name to cwd
printf("%s\n" , cwd);
fp = fopen(cwd , "r"); // open file in read mode
if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
strcpy(message, player_name); //Top of the message contains the name
message[strlen(message)] = '\n'; //replace \0 with \n
len = strlen(message); //store index so far
i=0;
char temp[5]; //storing quota as characters
while( ( ch = fgetc(fp) ) != EOF )
{
if( ch == '\t') //If we see a tab character it means the next character will have a a value, set flag and start loop
{
flag = 1;
k=0; //item name read, reset for the next item name
continue;
}
if(flag == 1 && ch != '\n' && ch != '\r') //Every character we will read from now on will be a digit of the value,store it on temp[], when \n is seen break.
{
temp[k] = ch;
k++;
continue;
}
if (ch == '\n') //We saw a new line character, process data so far (item name and quota)
{
flag = 0;
quota = atoi(temp); //Make an integer out of the temp string, which has the item value
item_name[strlen(item_name)] = '\0';
/*Store the value quota read on the player's inentory
according the item_name that was read */
if (strcmp(item_name, "gold")==0)
inventory[GOLD] = quota;
else if (strcmp(item_name, "armor") == 0)
inventory[ARMOR] = quota;
else if (strcmp(item_name, "ammo") == 0)
inventory[AMMO] = quota;
else if (strcmp(item_name, "lumber") == 0)
inventory[LUMBER] = quota;
else if (strcmp(item_name, "magic") == 0 )
inventory[MAGIC] = quota;
else if (strcmp(item_name, "rock") == 0)
inventory[ROCK] = quota;
/* zero values */
quota= 0;
memset(item_name, 0 , sizeof (item_name));
memset(temp, 0 , sizeof (temp));
i=0;
continue;
}
item_name[i] = ch; //If nothing of the above occures, the character is part of the item's name
i++;
}
fclose(fp); //close file
fp = fopen(cwd , "r"); // reopen file in read mode
if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
/* Read whole message to a buffer (after the name) */
while( ( ch = fgetc(fp) ) != EOF )
{
message[len] = ch;
len++;
}
message[len]='\0';
fclose(fp);
puts(message);
/*The socket() system call creates a new socket. It takes three arguments. The first is the address domain of the socket.
* We use AF_INET for internet domain for connection of any two hosts on the Internet
* The second argument is the type of socket. We use SOCK_STREAM for stream socket that uses TCP protocol.
* The third argument is the protocol. The zero argument will leave the operating system to choose the most appropriate protocol. It will choose TCP for stream sockets */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
printf("client socket failure %d\n", errno);
perror("client: ");
exit(1);
}
struct addrinfo hints, *serverinfo; //for getaddrinfo()
memset(&hints, 0 , sizeof hints);
hints.ai_family = AF_UNSPEC; // use AF_INET6 to force IPv6
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
hints.ai_flags = AI_PASSIVE; // use my IP address
/* int getaddrinfo(const char *node, // e.g. "www.example.com" or IP
const char *service, // e.g. "http" or port number
const struct addrinfo *hints, // hints parameter points to a struct addrinfo filled above
struct addrinfo **res) // will point to the results */
int rv;
if ((rv = getaddrinfo(server_name, PORT , &hints, &serverinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
exit(1);
}
freeaddrinfo(serverinfo); // free the linked list
struct sockaddr_in *addr;
addr = (struct sockaddr_in *)serverinfo->ai_addr;
/*inet_nota converts from a struct in_addr (part of struct sockaddr_in)
to a string in dots-and-numbers format (e.g. "192.168.5.10") and vice-versa */
printf("Server's IP address is: %s\n",inet_ntoa((struct in_addr)addr->sin_addr));
/*Take a server's name as an argument and returns a pointer to a hostent containing information about that host.
If this structure is NULL, the system could not locate a host with this name. */
if (serverinfo == NULL)
{
fprintf(stderr,"ERROR, no such host");
exit(0);
}
/*The connect function is called by the client to establish a connection to the server.
It takes three arguments, the socket file descriptor, the address of the host to which
it wants to connect (including the port number), and the size of this address.
This function returns 0 on success and -1 if it fails.
*/
if (connect(sockfd,(struct sockaddr *)serverinfo->ai_addr ,serverinfo->ai_addrlen) < 0)
{
perror("client connect failure: ");
exit(1);
}
signal(SIGINT, sigint_handler); //Install handler for SIGINT ( also CTR+C)
child_pid = fork(); //Create a child proccess for recieving messages from server
while(1)
{
if (child_pid > 0)//Parent proccess
{
/*Send name and item info */
if ((cnt = send(sockfd,message, strlen(message),0))== -1)
{
fprintf(stderr, "Failure Sending Message\n");
}
//Read \n character and send it to server
printf("Confirming connection to server:\n");
// ch = getchar(); //Uncomment when not run as a background process
sleep(2);
ch = '\n';
if ((cnt = send(sockfd, &ch, sizeof(char),0))== -1)
{
fprintf(stderr, "Failure Sending Message\n");
}
char final_message[100]; //Buffer containing message to send
memset( final_message, 0 , sizeof(final_message));
/* Place the server in an infinite loop,
of reading strings with fgets and and sending to server */
while(1)
{
/* append [*name*] style before any message */
final_message[0] = '[';
strcat(final_message, player_name);
strcat(final_message , "]: ");
// fgets(buf, sizeof(buf), stdin);
strcat(buf, "hello\n"); //Uncomment above line and comments this and the line bellow if you want to write messages manually
sleep(3);
strcat(final_message, buf); //append it to final message
if ((cnt = send(sockfd, final_message, strlen(final_message),0))== -1)
{
fprintf(stderr, "Failure Sending Message\n");
}
memset( final_message, 0 , sizeof(final_message));
memset( buf, 0, sizeof(buf));
}
}
else if (child_pid == 0) //Child process, recieves messages from server
{
signal( SIGINT, SIG_IGN);
while(1)
{
cnt = recv(sockfd, serv_msg, sizeof(serv_msg),0);
if ( cnt == 0 ) //Server has closed their socket or explicitly disconnected us
{
printf("Disconnected from server\n");
close(sockfd);
kill(parent_pid, SIGINT); //Inform parent to terminate
sleep(100); //wait for parent to kill us from his sigint handler
}
serv_msg[cnt] = '\0';
printf("%s",serv_msg); //\n should be included in message
memset(serv_msg, '0', sizeof(serv_msg));
}
}
else if (child_pid < 0)
{
fprintf(stderr, "Fork Failed");
exit(1);
}
}
}
/*This handler recieves SIGINT and terminates the main process plus the kid process if it exists*/
void sigint_handler(int signo)
{
if (child_pid > 0 ) //If main thread created a
{
pid_t PID;
kill(child_pid, SIGTERM); //Terminate recieving child process
int status;
do {
PID = waitpid(-1,&status,WAIT_ANY); //Clean zombie child function, wait any children
printf("Reciever terminated\n");
}
while ( PID != -1 );
}
close(sockfd); //close socket
exit(1);
}
|
C
|
#include<stdio.h>
void main()
{
printf("\nHello world!\nThis is my First Git Commit.\n");
printf("First change.");
}
|
C
|
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "ftp_client.h"
int main()
{
ftp_init();
struct ftp_connect client;
memcpy(client.hostname, "192.168.0.107", sizeof(client.hostname));
client.control_port = 21;
memcpy(client.username, "odin", sizeof(client.username));
memcpy(client.password, "odin", sizeof(client.password));
client.mode = 0;
struct file_description file;
memcpy(file.remote_dir, "/test/X00/192.168.0.188/20121128/09", sizeof(file.remote_dir));
memcpy(file.file_name, "a.txt", sizeof(file.file_name));
int size = 1024 * 1024;
char *ptr = (char *)malloc(size * sizeof(char));
file.file_buffer = ptr;
file.file_size = size;
if (ftp_open(&client) == FTP_OK) {
ftp_upload(&client, &file);
}
ftp_close(&client);
free(ptr);
ptr = NULL;
ftp_release();
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "bst.h"
#define ADD_RED printf("\033[1;31m")
#define END_RED printf("\033[0m")
static void CreateTest();
static void InsertTest();
static void IterTest(bst_t *tree);
int IsBefore(void *data1, void *data2, void *param);
int main()
{
/*CreateTest();*/
InsertTest();
return 0;
}
static void CreateTest()
{
bst_t *tree = NULL;
bst_iter_t it;
printf("\nBST Create test:\n");
tree = BSTCreate(IsBefore, NULL);
if (NULL != tree)
{
printf("Allocated a new tree. . .\n");
}
else
{
ADD_RED; printf("Could not allocate the tree.\n"); END_RED;
}
}
static void InsertTest()
{
bst_t *tree = NULL;
int num1 = 1, num2 = 2, num3 = 3;
bst_iter_t it;
printf("\nBST Insert test:\n");
tree = BSTCreate(IsBefore, NULL);
it = BSTInsert(tree, (void *)&num2);
printf("\nInserting to root. . .\n");
if (num2 == *(int *)BSTGetData(it))
{
it = BSTBegin(tree);
if (!(num2 == *(int *)BSTGetData(it)) )
{
ADD_RED; printf("ERROR: data is: %d\n", *(int *)BSTGetData(it)); END_RED;
}
}
else
{
ADD_RED; printf("ERROR: data is: %d\n", *(int *)BSTGetData(it)); END_RED;
}
printf("\nInserting to left node. . .\n");
it = BSTInsert(tree, (void *)&num1);
if (!(num1 == *(int *)BSTGetData(it)) )
{
ADD_RED; printf("ERROR: data is: %d\n", *(int *)BSTGetData(it)); END_RED;
}
printf("\nInserting to right node. . .\n");
it = BSTInsert(tree, (void *)&num3);
if (!(num3 == *(int *)BSTGetData(it)))
{
ADD_RED; printf("ERROR: data is: %d\n", *(int *)BSTGetData(it)); END_RED;
}
IterTest(tree);
}
static void IterTest(bst_t *tree)
{
bst_iter_t it = BSTBegin(tree);
printf("\nBST Iterators test:\n");
printf("Begin iterator's data is: %d\n", *(int *)BSTGetData(it));
printf("Prev iterator's data is: %d\n", *(int *)BSTGetData(BSTIterPrev(it)));
}
/**********************
* FUNCTIONS *
**********************/
int IsBefore(void *data1, void *data2, void *param)
{
(void) param;
return *(int *)data1 < *(int *)data2;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int altura,idade,cont;
scanf("%d %d",&altura,&idade);
if(altura>=140 && idade>=14)
{
cont++;
}
if(altura>=150 && idade>=12)
{
cont++;
}
if(altura>=170 || idade>=16)
{
cont++;
}
printf("%d\n",cont);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<assert.h>
#include<stdbool.h>
#include<limits.h>
#define clr(arr)do{ memset(arr, 0, sizeof(arr)); }while(0)
#define swap(a,b) do{ typeof(a) tp; tp = a; a = b; b = tp; }while(0)
typedef long long ll;
const ll mod = 1000000007ll;
int main() {
int N, P;
scanf("%d %d", &N, &P);
int ed[N]; clr(ed);
for (int i = 0; i < (P); ++i){
int a, b;
scanf("%d %d", &a, &b);
--a, --b;
if(a > b)
swap(a, b);
ed[b] = fmax(ed[b], a+1);
}
ll res [N+1]; clr( res);
ll sumres[N+1]; clr(sumres);
res[0] = 1;
int howfar = 0;
ll sumall = 0;
for (int i = 0; i < (N); ++i){
sumall = (sumall + res[i]) % mod;
sumres[i+1] = sumall;
howfar = fmax(howfar, ed[i]);
res[i+1] = (sumall - sumres[howfar]) % mod;
}
ll r = res[N] % mod;
if(r < 0)
r += mod;
printf("%lld\n", r);
return 0;
}
|
C
|
// ļҪڹڶάIJ
#ifndef __MAT_
#define __MAT_
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
//#include <random>
#include <time.h>
#define full 0
#define same 1
#define valid 2
typedef struct Mat2DSize{
int c; // У
int r; // Уߣ
}nSize;
float** rotate180(float** mat, nSize matSize);// ת180
void addmat(float** res, float** mat1, nSize matSize1, float** mat2, nSize matSize2);//
float** correlation(float** map,nSize mapSize,float** inputData,nSize inSize,int type);//
float** cov(float** map,nSize mapSize,float** inputData,nSize inSize,int type); //
// Ǿϲֵڲ壩upcuprڲ屶
float** UpSample(float** mat,nSize matSize,int upc,int upr);
// άԵaddwС0ֵ
float** matEdgeExpand(float** mat,nSize matSize,int addc,int addr);
// άԵСshrinkcСı
float** matEdgeShrink(float** mat,nSize matSize,int shrinkc,int shrinkr);
void savemat(float** mat,nSize matSize,const char* filename);//
void multifactor(float** res, float** mat, nSize matSize, float factor);// ϵ
float summat(float** mat,nSize matSize);// Ԫصĺ
char * combine_strings(char *a, char *b);
char* intTochar(int i);
#endif
|
C
|
#include "asprintfx.h"
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <assert.h>
char *asprintfx(const char *fmt, ...)
{
char *dest;
va_list ap;
int len;
assert(fmt != NULL);
dest = NULL;
va_start(ap, fmt);
len = vsnprintf(dest, 0, fmt, ap);
dest = (char*)malloc(len + 1);
vsprintf(dest, fmt, ap);
va_end(ap);
return dest;
}
|
C
|
/*#include<stdio.h>
int calculation(int fac_number){
if(fac_number==0 || fac_number==1){
return 1;
}
else{
return fac_number*calculation(fac_number-1);
}
}
void main(){
int number,factorial;
printf("enter a number for factorial:");
scanf("%d",&number);
factorial=calculation(number);
printf("factorial ans is:%d",factorial);
}*/
/*#include <stdio.h>
int calculate(int sum_number){
if(sum_number==1){
return 1;
}
else{
return sum_number+calculate(sum_number-1);
}
}
void main(){
int summation,number;
printf("enter a number for summation:");
scanf("%d",&number);
summation=calculate(number);
printf("summation number is:%d",summation);
}
*/
#include <stdio.h>
int calculation(int even_number){
if(even_number==0){
return 0;
}
else if(even_number%2==0){
return even_number+calculation(even_number-1);
}
else{
return calculation(even_number-1);
}
}
void main(){
int number,even_summation;
printf("enter a number for even summation:");
scanf("%d",&number);
even_summation=calculation(number);
printf("even number is %d",even_summation);
}
|
C
|
#include <stdio.h>
int main (){
long int n_segundos;
printf("Insira o numero em segundos: "); scanf("%ld", &n_segundos);
printf("Horas \t: %d\n",(int) n_segundos/3600);
printf("Minutos \t: %d\n",(int) (n_segundos%3600/60));
printf("Segundos \t: %d\n",(int) n_segundos%60);
}
|
C
|
//
// Created by Jedrzej on 03.07.2018.
//
#import <stdio.h>
void cwiczenie19(void) {
int c;
int space_counter = 0;
while ((c = getchar()) != EOF) {
if (' ' == c) {
space_counter++;
if(space_counter < 2) {
printf("%c", c);
}
continue;
}
else
space_counter = 0;
printf("%c", c);
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#defineCOMPARE(x,y)((x==y)?0:(x>y)?1:-1)
structnode
{
floatcoeff;
intexp;
structnode*link;
};
typedefstructnode*polypointer;
voidattach(floatcoefficient,intexponent,polypointer*ptr)
{
polypointertemp;
temp=(polypointer)malloc(sizeof(structnode));
temp->coeff=coefficient;
temp->exp=exponent;
(*ptr)->link=temp;
*ptr=temp;
(*ptr)->link=NULL;
}
polypointercadd(polypointera,polypointerb)
{
polypointerc,lastC,startA;
intsum,done=0;
startA=a;
a=a->link;
b=b->link;
c=(polypointer)malloc(sizeof(structnode));
c->exp=-1;
lastC=c;
do
{
switch(COMPARE(a->exp,b->exp))
{
case1:attach(a->coeff,a->exp,&lastC);
a=a->link;
break;
case0:if(startA==a)
done=1;
else
{
sum=a->coeff+b->coeff;
if(sum)
attach(sum,a->exp,&lastC);
a=a->link;
b=b->link;
}
break;
case-1:attach(b->coeff,b->exp,&lastC);
b=b->link;
break;
}
}while(!done);
lastC->link=c;
returnc;
}
voidprintPoly(polypointerk)
{
k=k->link;
while(((k->link)->exp)!=-1)
{
printf("%fx^%d+",k->coeff,k->exp);
k=k->link;
}
printf("%fx^%d",k->coeff,k->exp);
printf("\n");
}
intmain()
{
polypointera,b,c,endA,endB;
intn,i,expon;
floatcoef;
a=(polypointer)malloc(sizeof(structnode));
a->exp=-1;
b=(polypointer)malloc(sizeof(structnode));
b->exp=-1;
printf("enterthenumberoftermsforfirstpolynomial\n");
scanf("%d",&n);
endA=a;
for(i=0;i<n;i++)
{
printf("enterthecoefficient\n");
scanf("%f",&coef);
printf("entertheexponenet\n");
scanf("%d",&expon);
attach(coef,expon,&endA);
}
endA->link=a;
printf("enterthenumberoftermsforsecondpolynomial\n");
scanf("%d",&n);
endB=b;
for(i=0;i<n;i++)
{
printf("enterthecoefficient\n");
scanf("%f",&coef);
printf("entertheexponenet\n");
scanf("%d",&expon);
attach(coef,expon,&endB);
}
endB->link=b;
c=cadd(a,b);
printPoly(a);
printPoly(b);
printPoly(c);
}
|
C
|
/*
* @file taskpool_policies_wrapper.c
*
* Created on: Mar 30, 2015
* Author: yulongb
*/
#include "lift_task_queue.h"
#include <malloc.h>
#include <stdlib.h>
#include <pthread.h>
static unsigned int N_LENGTH_OF_TASK_POOL = 4;
static request_type_t *task_pool_secret = (void *)0;
static pthread_mutex_t task_pool_lock = PTHREAD_MUTEX_INITIALIZER;
void default_task_pool_init( unsigned int length){
N_LENGTH_OF_TASK_POOL = length;
get_nearest_length_init(length);
task_pool_secret = malloc(length*sizeof(request_type_t));
memset(task_pool_secret, 0, length*sizeof(request_type_t));
if(!task_pool_secret){
perror("default_task_pool_init, bad malloc");
exit(-1);
}
}
void default_task_pool_destroy(void){
if(task_pool_secret){
free(task_pool_secret);
}
N_LENGTH_OF_TASK_POOL = 4;
}
void default_task_pool_print(void){
print_request_pool(task_pool_secret, N_LENGTH_OF_TASK_POOL);
}
void push_request(int floor, request_type_t type){
pthread_mutex_lock(&task_pool_lock);
set_request_type(task_pool_secret+floor, type);
pthread_mutex_unlock(&task_pool_lock);
}
void pop_request(int floor, request_type_t type){
pthread_mutex_lock(&task_pool_lock);
clr_request_type(task_pool_secret+floor, type);
pthread_mutex_unlock(&task_pool_lock);
}
request_type_t get_request(int floor, request_type_t type){
return get_request_type(task_pool_secret+floor, type);
}
static int get_optimal_request_from_specified_on_search_direction(
const request_type_t * const pool, int specified, int *direction,
request_type_t * ret_type) {
int failed_count = 0;
int ret = specified;
if (*direction == 0){
*ret_type = request_up_dn_cmd;
return ret;
}
while (1) {
/* failed even */
if (failed_count % 2 == 0){
if (*direction > 0) {
ret = get_nearest_request_of_specified_upward(pool, specified,
request_up_n_cmd);
*ret_type = request_up_n_cmd;
} else {
ret = get_nearest_request_of_specified_downward(pool, specified,
request_dn_n_cmd);
*ret_type = request_dn_n_cmd;
}
if (ret == -1) {
failed_count++;
*direction = -*direction;
} else {
return ret;
}
}
/* failed odd */
if (failed_count % 2 == 1) {
if (*direction > 0) {
ret = get_nearest_request_of_specified_upward(pool, 0,
request_up_n_cmd);
*ret_type = request_up_n_cmd;
}
else {
ret = get_nearest_request_of_specified_downward(pool,
N_LENGTH_OF_TASK_POOL - 1, request_dn_n_cmd);
*ret_type = request_dn_n_cmd;
}
if (ret == -1) {
failed_count++;
*direction = -*direction;
} else {
return ret;
}
}
/* failed limit */
if (failed_count >= 4){
*ret_type = request_empty;
return -1;
}
}
return ret;
}
static unsigned int get_nr_of_req(const request_type_t * pool, unsigned int length) {
int ret = 0;
for (int i = 0; i < length; i++) {
switch (pool[i]) {
case request_call_up:
case request_call_down:
case request_call_cmd:
ret++;
break;
case request_call_up | request_call_down:
case request_call_up | request_call_cmd:
case request_call_cmd | request_call_down:
ret += 2;
break;
case request_call_up | request_call_down | request_call_cmd:
ret += 3;
break;
default:
break;
}
}
return ret;
}
int get_optimal_req(int from, int *dir, request_type_t *ret_type){
pthread_mutex_lock(&task_pool_lock);
int rc = get_optimal_request_from_specified_on_search_direction(
task_pool_secret, from, dir,
ret_type);
pthread_mutex_unlock(&task_pool_lock);
return rc;
}
unsigned int get_req_count(void){
return get_nr_of_req(task_pool_secret, N_LENGTH_OF_TASK_POOL);
}
|
C
|
#include <avr/io.h>
#include "UART.h"
int main( void ) {
char cad[20];
uint16_t num;
UART0_init(1);
while(1)
{
UART0_getchar();
UART0_puts("\n\rIntroduce un nmero:\n\r");
UART0_gets(cad);
num = atoi(cad);
itoa(cad,num,16);
UART0_puts("\n\rHex:");
UART0_puts(cad);
itoa(cad,num,2);
UART0_puts("\n\rBin:");
UART0_puts(cad);
}
}
|
C
|
#ifndef ALUMNO_H_INCLUDED
#define ALUMNO_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int d;
int m;
int a;
}t_fecha_ing;
typedef struct
{
int dni;
char nya[40];
char sexo;
float prom;
int notas[10];
t_fecha_ing fecha;
char estado;
}t_alumno;
int cargarArchivo(char * path, char * modoApertura);
int leerArchivo(char * path, char * modoApertura);
/*
Crearemos un archivo binario con una estructura con varios alumnos.
Luego procedemos a leer el archivo.
Y luego haremos una actualizacion del mismo.
Los que tengan fecha de ingreso menor al ao 2000, se cambiara el estado
de ACTIVO(A) a INACTIVO(I).
Por ultimo leemos el archivo ya actualizado.
*/
#endif // ALUMNO_H_INCLUDED
|
C
|
/* Programming Exercise 12-4.c */
// Write and test in a loop a function that returns the number of times it has been called.
#include <stdio.h>
int function();
int main(void)
{
int times;
scanf("%d", ×);
for (int i = 0; i < times; i++)
{
printf("The function has been called for %d times.\n", function());
}
return 0;
}
int function()
{
static int times = 0;
return ++times;
}
|
C
|
/*+-------------------------------------------------------------------+
| <DOC> |
| <NAME> obj_cmod(), obj_change_mode() |
| <AUTHOR> John L. Foster |
| <DATE> March 7, 1989 |
| <LEVEL> OBJ |
| |
| <GLOBAL> None |
| |
| <PARAM> object OCB * INPUT OCB to alter mode of. |
| <PARAM> mode hword INPUT Mode bit flags to set to.|
| |
| <PURPOSE> Change the mode of an open object by the following |
| rules: |
| |
| If the object has the OBJ_READ flag set and the mode |
| change requests OBJ_UPDATE, then close the object and |
| re-open it in update mode forcing a new view and al- |
| lowing future updates to occur. |
| |
| If the object has the OBJ_UPDATE flag set and the mode |
| change requests OBJ_READ, close-flush the object to |
| commit prior updates and re-open the object in Read |
| mode. Future updates to the object will not be allowed|
| |
| Any other mode changes have no effect except to alter |
| (or toggle, in case of conflict) the mode flags. |
| |
| <OUTPUT> sint |
| </DOC> |
+-------------------------------------------------------------------+*/
#include "defs.h"
#include "debug.h"
#include "str.h"
#include "osk.h"
#include "obj.h"
sint obj_cmod( object, mode )
OCB * object;
hword mode;
{
sint rc = 0;
hword mode_set_flag = 0,
mode_reset_flag = 0,
dms_close_mode = 0,
dms_open_mode = 0;
boolean change_mode = FALSE;
if( OCB_POINTER_OK( object ) )
{
if( (object->mode & OBJ_READ) && (mode & OBJ_UPDATE) )
{
mode_set_flag = OBJ_READ ;
mode_reset_flag = OBJ_UPDATE ;
dms_close_mode = DMS_CLOSE_BACKOUT ;
dms_open_mode = DMS_OPEN_UPDATE ;
change_mode = TRUE ;
}
else if( (object->mode & OBJ_UPDATE) && (mode & OBJ_READ) )
{
mode_set_flag = OBJ_UPDATE ;
mode_reset_flag = OBJ_READ ;
dms_close_mode = DMS_CLOSE_COMMIT ;
dms_open_mode = DMS_OPEN_READ_ONLY ;
change_mode = TRUE ;
}
else
{
obj_set_mode( object, mode );
change_mode = FALSE;
}
if( change_mode )
{
object->mode &= ~ mode_set_flag;
rc = dms_cls( object->dmscb, dms_close_mode );
if( rc != DMS_CLOSE_OK )
{
}
else
{
rc = 0;
}
object->dmscb = dms_opn( object->lfd, object->goid, dms_open_mode );
if( object->dmscb == NIL )
{
rc = DMS_OPEN_ERROR;
}
object->mode |= mode_reset_flag;
}
}
else
{
rc = INVALID_OCB;
}
return(rc);
}
|
C
|
/*
* Copyright (c) 2009 Sven Bachmann ([email protected])
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <ftdi.h>
#include <fcntl.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include "ws.h"
/* variables */
extern struct ftdi_context ftdic;
int thread_exit;
pthread_t ws_recv_thread_data;
/* prototypes */
void* ws_recv_thread(void*);
/*
* ws_recv_init
*
* Initialize the receiving thread.
*/
int ws_recv_init(struct receive_s* recv)
{
int ret;
/* clear thread exit condition */
thread_exit = 0;
/* initialize semaphore */
recv->wait = (sem_t *) malloc(sizeof(sem_t));
sem_init(recv->wait, 0, 0);
check_cond(pthread_create(&ws_recv_thread_data, NULL, ws_recv_thread, recv), != 0, return -1);
return 0;
}
/*
* ws_recv_stop
*
* Stop the receiving thread.
*/
void ws_recv_stop(struct receive_s* recv)
{
int ret;
/* send exit signal to thread */
thread_exit = 1;
/* wait for thread to exit */
check_cond(pthread_join(ws_recv_thread_data, NULL), != 0, return);
/* close semaphore */
sem_close(recv->wait);
}
/*
* ws_recv_thread
*
* Receive data from weatherstation.
*/
void* ws_recv_thread(void* recv_void)
{
int ret;
int data_beg = 0;
int data_end = 0;
int data_last = 0;
u_char data;
struct receive_s* recv = recv_void;
/* check for buffer with zero or less length */
check_cond(recv->length, <= 0, goto bye);
/* set buffer position to zero */
recv->pos = 0;
/* exit condition (pos <= lenght to have one byte extra for record end checking) */
while ((!thread_exit) && (recv->pos <= (recv->length))) {
/* receive one byte */
check_ftdi(ftdi_read_data(&ftdic, &data, 1), break);
/* no byte received? sleep a bit */
if (ret == 0) {
if (recv->tries-- > 0) {
usleep(WS_RECV_TIMEOUT);
continue;
}
break;
}
/* bytestream begin */
if ((data == CMD_BEG) && (data_last != CMD_ESCAPE)) {
recv->pos = 0;
data_last = data;
continue;
}
/* command byte */
if ((data == recv->command) && (data_last == CMD_BEG)) {
data_beg = 1;
data_last = 0;
continue;
}
/* bytestream end */
if ((data == CMD_END) && (data_last != CMD_ESCAPE) && (data_beg)) {
data_end = 1;
break;
}
/* escape character handling
*
* if found and escape is already set, take char as it is,
* otherwise only set escape flag
*/
if ((data == CMD_ESCAPE) && (data_last != CMD_ESCAPE)) {
data_last = data;
continue;
}
/* add character to stream if this was not the "end-of-record" check */
if (recv->pos >= recv->length) {
break;
}
recv->buffer[recv->pos++] = data;
}
/* if record end is not reached, invalidate data */
if (!data_end) {
recv->pos = 0;
}
bye:
/* release waiter */
sem_post(recv->wait);
return NULL;
}
|
C
|
//AITKEN.C
//Aitken
#include <math.h>
#include <stdio.h>
double aitken(x, eps, f)
double x, eps, (*f)(double);
{
int flag = 0, k = 0;
double u, v;
while ((flag == 0) && (k <= 100))
{
k = k + 1;
u = (*f)(x); v = (*f)(u);
if (fabs(u-v)<eps) { x = v; flag = 1; }
else x = v - (v - u)*(v - u)/(v - 2.0*u + x);
}
if (k > 100) printf("100,ܲ!\n");
return(x);
}
//ļAITKEN.C
main()
{
double x, f(double);
x = aitken(0.5 ,0.0000001, f);
printf("x=%f\n", x);
}
double f(double x)
{ return(6.0-x*x); }
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int sumTwo(int a, int b)
{
return (a+b);
}
int square(int n)
{
result(n*n);
}
int get_max(int x, int y)
{
if(x > y)
return(x);
else
return(y);
}
int main(int argc, char *argv[]) {
printf("sunTwo : %i\n", sumTwo(1, 2));
printf("square : %i\n", square(5));
printf("get_max : %i\n", get_max(10, 30));
return 0;
}
|
C
|
#include "lista_sentinela.h"
int main() {
TipoElemento aux;
char string[256] = {};
// lista_criar ============================================================
Lista* l = lista_criar();
printf("Lista: %p ", l);
printf("Sentinela: %p\n\n", l->sentinela);
// printf("Ant: %p | Prox: %p\n", l->sentinela->ant, l->sentinela->prox);
// lista_destruir =========================================================
// lista_destruir(l);
// lista_inserirFim =======================================================
lista_inserirFim(l, 10);
lista_inserirFim(l, 20);
// lista_inserir ==========================================================
lista_inserir(l, 15, 1);
// lista_imprimir(l);
// lista_removerPosicao ===================================================
// lista_removerPosicao(l, 0, &aux);
// printf("Endereco removido: [%d]\n", aux);
// lista_removerElemento ==================================================
// lista_removerElemento(l, 20);
// lista_substituir =======================================================
lista_substituir(l, 2, 25);
// lista_posicao ==========================================================
// printf("lista_posicao: %d\n", lista_posicao(l, 25));
// lista_buscar ===========================================================
// lista_buscar(l, 0, &aux);
// printf("lista_buscar: [%d]\n", aux);
// lista_contem ===========================================================
// printf("lista_contem: %d\n", lista_contem(l, 15));
// lista_tamanho ===========================================================
// printf("lista_tamanho: %d\n", lista_tamanho(l));
// lista_toString =========================================================
lista_toString(l, string);
printf("lista_toString: %s\n\n", string);
// lista_imprimir =========================================================
lista_imprimir(l);
return 0;
}
|
C
|
#include <stdio.h>
#include <io_utils.h>
#include <errno.h>
#include <string.h>
#define COPY_SUCCESS 0
#define COPY_ILLEGAL_ARGUMENTS -1
#define COPY_SRC_OPEN_ERROR -2
#define COPY_SRC_READ_ERROR -3
#define COPY_DEST_OPEN_ERROR -4
#define COPY_DEST_WRITE_ERROR -5
#define COPY_UNKNOWN_ERROR -100
int CopyFile(char const *src, char const *dest) {
if (!src || !dest) {
return COPY_ILLEGAL_ARGUMENTS;
}
FILE *src_file = fopen(src, "r");
if (!src_file) {
return COPY_SRC_OPEN_ERROR;
}
FILE *dest_file = fopen(dest, "w");
if (!dest_file) {
fclose(src_file);
return COPY_DEST_OPEN_ERROR;
}
int result;
while (1) {
int next = fgetc(src_file);
if (next == EOF) {
if (ferror(src_file)) {
result = COPY_SRC_READ_ERROR;
} else if(feof(src_file)) {
result = COPY_SUCCESS;
} else {
result = COPY_UNKNOWN_ERROR;
}
break;
}
if (fputc(next, dest_file) == EOF) {
result = COPY_DEST_WRITE_ERROR;
break;
}
}
fclose(src_file);
fclose(dest_file);
return result;
}
int main() {
int result = CopyFile("data/io_utils.h", "data_copy/io_utils.h");
PRINT_INT(result);
result = CopyFile("data/logo.bmp", "data_copy/logo.bmp");
PRINT_INT(result);
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include "misc.h"
#define MAX_ITEM_NAME_LEN 100
void fillDate(Date *d)
{
struct timeval tv;
struct tm *now;
gettimeofday(&tv, NULL);
now = gmtime(&tv.tv_sec);
d->month = now->tm_mon + 1;
d->year = now->tm_year + 1900;
d->day = now->tm_mday;
}
int fetchItemsFromCli(Items *items, int maxItems)
{
int i = 0;
int err = 0;
char iName[MAX_ITEM_NAME_LEN];
char amount[10];
char quantity[10];
char c = 'y';
for(i = 0; i < maxItems; i++) {
c = 'y';
printf("Want to enter Item?(y\\n) [y]:");
c = getchar();
getchar();
if(c == 'n')
break;
printf("###################################\n");
printf("Item Name:");
if (fgets(iName, MAX_ITEM_NAME_LEN, stdin) == NULL)
perror("Item name");
else
ASSIGN_STR(items[i].name, iName);
printf("Price:");
if (fgets(amount, MAX_ITEM_NAME_LEN, stdin) == NULL)
perror("Price");
else
items[i].amount = atoi(amount);
printf("Quantity:");
if (fgets(quantity, MAX_ITEM_NAME_LEN, stdin) == NULL)
perror("Quantity");
else
items[i].quantity = atoi(quantity) ? atoi(quantity) : 1;
printf("-----------------------------------\n");
}
if(i == maxItems)
printf("MAX Items reached!!!");
Finally:
return i;
}
int addItems(Items *items)
{
printf("Adding Items \n");
return fetchItemsFromCli(items, MAX_ITEMS);
}
void printDate(Date d)
{
printf("[%u-%u-%u]", d.day, d.month, d.year);
}
|
C
|
/* 2014-Apr-03: Why??? Just use doubles... */
static inline double tv_to_double(struct timeval *tv) {
return (tv->tv_sec + tv->tv_usec/1000000.0);
}
static inline int tv_lt_diff(struct timeval *tv1, struct timeval *tv2, struct timespec *diff)
{
if (tv1->tv_sec > tv2->tv_sec ||
(tv1->tv_sec == tv2->tv_sec && tv1->tv_usec > tv2->tv_usec)) {
diff->tv_sec = 0;
diff->tv_nsec = 0;
return 0;
}
diff->tv_sec = tv2->tv_sec - tv1->tv_sec;
if (tv2->tv_usec > tv1->tv_usec) {
/* Straight subtraction. */
diff->tv_nsec = (tv2->tv_usec - tv1->tv_usec)*1000;
}
else {
/* Subtract with borrow. */
diff->tv_nsec = (1000000 + tv2->tv_usec - tv1->tv_usec)*1000;
diff->tv_sec -= 1;
}
return 1;
}
static inline int tv_gt_diff(struct timeval *tv1, struct timeval *tv2, struct timespec *diff)
{
if (tv1->tv_sec < tv2->tv_sec ||
(tv1->tv_sec == tv2->tv_sec && tv1->tv_usec < tv2->tv_usec)) {
diff->tv_sec = 0;
diff->tv_nsec = 0;
return 0;
}
diff->tv_sec = tv1->tv_sec - tv2->tv_sec;
if (tv1->tv_usec > tv2->tv_usec) {
/* Straight subtraction. */
diff->tv_nsec = (tv1->tv_usec - tv2->tv_usec)*1000;
}
else {
/* Subtract with borrow. */
diff->tv_nsec = (1000000 + tv1->tv_usec - tv2->tv_usec)*1000;
diff->tv_sec -= 1;
}
return 1;
}
static inline void tv_ts_add(struct timeval *tv, struct timespec *ts, struct timeval *tv_out)
{
tv_out->tv_sec = tv->tv_sec + ts->tv_sec;
tv_out->tv_usec = tv->tv_usec + (ts->tv_nsec/1000);
if (tv_out->tv_usec > 1000000) {
/* Carry. */
tv_out->tv_usec -= 1000000;
tv_out->tv_sec += 1;
}
}
static inline void tv_clear(struct timeval *tv)
{
tv->tv_sec = 0;
tv->tv_usec = 0;
}
#if 0
/* FIXME: Use this or delete it. */
static void handle_playback_timing(SDLstuff_private *priv, struct timeval *tv_current)
{
struct timeval now;
struct timespec ts;
double d;
d = fabs(tv_to_double(&priv->tv_last) - tv_to_double(tv_current));
if (d > 1.0) {
/* tv_last is unset, or tv_current has changed substantially. */
fprintf(stderr, "d:%.3f too big\n", d);
goto out1;
return;
}
gettimeofday(&now, 0L);
if (tv_lt_diff(&now, &priv->tv_sleep_until, &ts)) {
fprintf(stderr, "nanosleep %ld.%09ld\n", ts.tv_sec, ts.tv_nsec);
if (nanosleep(&ts, 0L) != 0) { perror("nanosleep"); }
}
else {
// fprintf(stderr, "no sleep\n");
/* FIXME: If we took too long more than once, should do something... */
gettimeofday(&priv->tv_sleep_until, 0L);
}
if (tv_gt_diff(tv_current, &priv->tv_last, &ts)) {
/* Normally expect this. */
tv_ts_add(&priv->tv_sleep_until, &ts, &priv->tv_sleep_until);
// fprintf(stderr, "normal; sleep until { %ld.%06ld } \n", priv->tv_sleep_until.tv_sec, priv->tv_sleep_until.tv_usec);
}
else {
/* tv_current is unexpectedly behind tv_last. Clear sleep_until and hope things
work out. */
}
out1:
priv->tv_last = *tv_current;
}
#endif
|
C
|
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */
/*
* See COPYRIGHT in top-level directory.
*/
#include <stdio.h>
#include <pthread.h>
#include "abt.h"
#include "abttest.h"
void task_hello(void *arg)
{
ABT_xstream xstream;
ABT_thread thread;
ABT_task task;
ABT_unit_type type;
ABT_bool flag;
int ret;
ret = ABT_xstream_self(&xstream);
ABT_TEST_ERROR(ret, "ABT_stream_self");
ret = ABT_thread_self(&thread);
assert(ret == ABT_ERR_INV_THREAD && thread == ABT_THREAD_NULL);
ret = ABT_task_self(&task);
ABT_TEST_ERROR(ret, "ABT_task_self");
ret = ABT_self_get_type(&type);
assert(ret == ABT_SUCCESS && type == ABT_UNIT_TYPE_TASK);
ret = ABT_self_is_primary(&flag);
assert(ret == ABT_ERR_INV_THREAD && flag == ABT_FALSE);
ret = ABT_self_on_primary_xstream(&flag);
assert(ret == ABT_SUCCESS);
ABT_test_printf(1, "TASK %d: running on the %s\n", (int)(size_t)arg,
(flag == ABT_TRUE ? "primary ES" : "secondary ES"));
}
void thread_hello(void *arg)
{
ABT_xstream xstream;
ABT_pool pool;
ABT_thread thread;
ABT_thread_id my_id;
ABT_task task;
ABT_unit_type type;
ABT_bool flag;
int ret;
ret = ABT_xstream_self(&xstream);
ABT_TEST_ERROR(ret, "ABT_stream_self");
ret = ABT_thread_self(&thread);
ABT_TEST_ERROR(ret, "ABT_thread_self");
ret = ABT_thread_get_id(thread, &my_id);
ABT_TEST_ERROR(ret, "ABT_thread_get_id");
ret = ABT_task_self(&task);
assert(ret == ABT_ERR_INV_TASK && task == ABT_TASK_NULL);
ret = ABT_self_get_type(&type);
assert(ret == ABT_SUCCESS && type == ABT_UNIT_TYPE_THREAD);
ret = ABT_self_is_primary(&flag);
assert(ret == ABT_SUCCESS && flag == ABT_FALSE);
ret = ABT_thread_is_primary(thread, &flag);
assert(ret == ABT_SUCCESS && flag == ABT_FALSE);
/* Get the first pool */
ret = ABT_xstream_get_main_pools(xstream, 1, &pool);
ABT_TEST_ERROR(ret, "ABT_xstream_get_main_pools");
/* Create a task */
ret = ABT_task_create(pool, task_hello, (void *)my_id, NULL);
ABT_TEST_ERROR(ret, "ABT_task_create");
ret = ABT_self_on_primary_xstream(&flag);
assert(ret == ABT_SUCCESS);
ABT_test_printf(1, "ULT %lu running on the %s\n", my_id,
(flag == ABT_TRUE ? "primary ES" : "secondary ES"));
}
void *pthread_hello(void *arg)
{
ABT_xstream xstream;
ABT_thread thread;
ABT_task task;
ABT_unit_type type;
ABT_bool flag;
int ret;
/* Since Argobots has been initialized, we should get ABT_ERR_INV_XXX. */
ret = ABT_xstream_self(&xstream);
assert(ret == ABT_ERR_INV_XSTREAM && xstream == ABT_XSTREAM_NULL);
ret = ABT_thread_self(&thread);
assert(ret == ABT_ERR_INV_XSTREAM && thread == ABT_THREAD_NULL);
ret = ABT_task_self(&task);
assert(ret == ABT_ERR_INV_XSTREAM && task == ABT_TASK_NULL);
ret = ABT_self_get_type(&type);
assert(ret == ABT_ERR_INV_XSTREAM && type == ABT_UNIT_TYPE_EXT);
ret = ABT_self_is_primary(&flag);
assert(ret == ABT_ERR_INV_XSTREAM && flag == ABT_FALSE);
ret = ABT_self_on_primary_xstream(&flag);
assert(ret == ABT_ERR_INV_XSTREAM && flag == ABT_FALSE);
ABT_test_printf(1, "pthread: external thread\n");
pthread_exit(NULL);
return NULL;
}
int main(int argc, char *argv[])
{
ABT_xstream xstreams[2];
ABT_pool pools[2];
ABT_thread threads[2];
ABT_thread my_thread;
ABT_thread_id my_thread_id;
ABT_task my_task;
ABT_unit_type type;
ABT_bool flag;
pthread_t pthread;
int i, ret;
/* Self test: we should get ABT_ERR_UNITIALIZED */
ret = ABT_xstream_self(&xstreams[0]);
assert(ret == ABT_ERR_UNINITIALIZED && xstreams[0] == ABT_XSTREAM_NULL);
ret = ABT_thread_self(&my_thread);
assert(ret == ABT_ERR_UNINITIALIZED && my_thread == ABT_THREAD_NULL);
ret = ABT_task_self(&my_task);
assert(ret == ABT_ERR_UNINITIALIZED && my_task == ABT_TASK_NULL);
ret = ABT_self_get_type(&type);
assert(ret == ABT_ERR_UNINITIALIZED && type == ABT_UNIT_TYPE_EXT);
ret = ABT_self_is_primary(&flag);
assert(ret == ABT_ERR_UNINITIALIZED && flag == ABT_FALSE);
ret = ABT_self_on_primary_xstream(&flag);
assert(ret == ABT_ERR_UNINITIALIZED && flag == ABT_FALSE);
/* Initialize */
ABT_test_init(argc, argv);
/* Execution Streams */
ret = ABT_xstream_self(&xstreams[0]);
ABT_TEST_ERROR(ret, "ABT_xstream_self");
ret = ABT_xstream_create(ABT_SCHED_NULL, &xstreams[1]);
ABT_TEST_ERROR(ret, "ABT_xstream_create");
/* Test self routines */
ret = ABT_thread_self(&my_thread);
ABT_TEST_ERROR(ret, "ABT_thread_self");
ABT_thread_get_id(my_thread, &my_thread_id);
ABT_test_printf(1, "ID: %lu\n", my_thread_id);
ret = ABT_task_self(&my_task);
assert(ret == ABT_ERR_INV_TASK && my_task == ABT_TASK_NULL);
ret = ABT_self_get_type(&type);
assert(ret == ABT_SUCCESS && type == ABT_UNIT_TYPE_THREAD);
ret = ABT_self_is_primary(&flag);
assert(ret == ABT_SUCCESS && flag == ABT_TRUE);
ret = ABT_thread_is_primary(my_thread, &flag);
assert(ret == ABT_SUCCESS && flag == ABT_TRUE);
ret = ABT_self_on_primary_xstream(&flag);
assert(ret == ABT_SUCCESS && flag == ABT_TRUE);
/* Create ULTs */
for (i = 0; i < 2; i++) {
ret = ABT_xstream_get_main_pools(xstreams[i], 1, &pools[i]);
ABT_TEST_ERROR(ret, "ABT_xstream_get_main_pools");
ret = ABT_thread_create(pools[i], thread_hello, NULL,
ABT_THREAD_ATTR_NULL, &threads[i]);
ABT_TEST_ERROR(ret, "ABT_thread_create");
}
/* Create a pthread */
ret = pthread_create(&pthread, NULL, pthread_hello, NULL);
assert(ret == 0);
/* Switch to other work units */
ABT_thread_yield();
/* Join & Free */
ret = pthread_join(pthread, NULL);
assert(ret == 0);
for (i = 0; i < 2; i++) {
ret = ABT_thread_join(threads[i]);
ABT_TEST_ERROR(ret, "ABT_thread_join");
ret = ABT_thread_free(&threads[i]);
ABT_TEST_ERROR(ret, "ABT_thread_free");
}
ret = ABT_xstream_join(xstreams[1]);
ABT_TEST_ERROR(ret, "ABT_xstream_join");
ret = ABT_xstream_free(&xstreams[1]);
ABT_TEST_ERROR(ret, "ABT_xstream_free");
/* Finalize */
return ABT_test_finalize(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#define BUFFER_SIZE 4096
struct time
{
size_t hours;
size_t minutes;
size_t seconds;
size_t milliseconds;
};
void die(const char *msg);
void process_time(struct time *t, char *token, size_t offset);
int main()
{
size_t offset;
if (scanf("%lu", &offset) != 1)
{
printf("Invalid input!");
return 1;
}
FILE *fileSrc = fopen("source.sub", "r");
if (!fileSrc)
{
die(NULL);
}
FILE *fileDest = fopen("fixed.sub", "w");
if (!fileDest)
{
die(NULL);
}
char *line = NULL;
size_t size = 0;
while (!feof(fileSrc))
{
size_t lineLength = getline(&line, &size, fileSrc);
char *isTimeLine = strstr(line, " -->");
if (!isTimeLine)
{
fwrite(line, 1, lineLength, fileDest);
}
else
{
char *token = strtok(line, " --> ");
char *token1 = strtok(NULL, " --> ");
struct time t1, t2;
process_time(&t1, token, offset);
process_time(&t2, token1, offset);
char result[30];
sprintf(result,
"%02lu:%02lu:%02lu,%03lu -->%02lu:%02lu:%02lu,%03lu\n",
t1.hours, t1.minutes, t1.seconds, t1.milliseconds,
t2.hours, t2.minutes, t2.seconds, t2.milliseconds);
fwrite(result, 1, strlen(result), fileDest);
}
}
printf("Fixed!");
free(line);
fclose(fileSrc);
fclose(fileDest);
return 0;
}
void die(const char *msg)
{
if (errno)
{
perror(msg);
}
else
{
printf("ERROR: %s\n", msg);
}
exit(1);
}
void process_time(struct time *t, char *token, size_t offset)
{
int hours = offset / 10000000;
int minutes = ((offset / 100000) % 100) % 60;
int seconds = ((offset / 1000) % 1000) % 60;
int milliseconds = offset % 1000;
char *current = strtok(token, " :,");
t->hours = atoi(current) + hours;
t->minutes = atoi(strtok(NULL, " :,")) + minutes;
t->seconds = atoi(strtok(NULL, " :,")) + seconds;
t->milliseconds = atoi(strtok(NULL, " :,")) + milliseconds;
t->hours += t->minutes / 60;
t->minutes %= 60;
t->minutes += t->seconds / 60;
t->seconds %= 60;
t->seconds += t->milliseconds / 1000;
t->milliseconds %= 1000;
}
|
C
|
#include "param.h"
#include "types.h"
#include "stat.h"
#include "user.h"
#include "syscall.h"
#include "traps.h"
#define TEST_NAME "crowd_outofthreads"
#include "318_test-tapish.h"
#define LOTS NTHR-3
#define SLEEP_EVERY 4
#define STKSIZE 1024
#define STRINGIFY(x) # x
#define XTRINGIFY(x) STRINGIFY(x)
#define BAILOUT (*(int *)0x1000000) = 3;
#define ARG ((void *)0x15410DE0U)
/*Authors: Jose and Emily*/
/*This just allocated all available thread slots and checks that doing one
* more causes tspawn to return -1.*/
/*Meant to be run when you only have init and sh running. Check to make
* that everyone gets cleaned up at the end with ^P. This will take a while
* as resources get shared between more and more threads.*/
static void
spawnee(void *a) {
TEST_EXIT_IF(a != ARG, "arg");
while(1){yield(-1);}
}
int main() {
int i;
void *s;
TEST_STRT(1);
TEST_DIAG("WARNING: this test will fail if run with more than two existing processes");
for(i = 0; i <= LOTS; i++) {
TEST_EXIT_IF((s = malloc(STKSIZE)) == 0, "oom");
s += STKSIZE;
if (i < LOTS) {
TEST_EXIT_IF(tspawn(s, spawnee, ARG) < 0,
"spawn fail before full at i=%d", i);
} else {
TEST_EXIT_IF(tspawn(s, spawnee, ARG) > 0,"spawn success after full");
}
}
TEST_FINI();
exit();
}
|
C
|
#include <stdio.h>
#define isopen(p) ((p)->flag & (_READ | _WRITE))
int fseek(FILE *fp, long offset, int origin)
{
if (fp == NULL || !isopen(fp))
return EOF;
if (fp->flag & _WRITE) {
if (fflush(fp))
return EOF;
} else {
offset -= (origin == SEEK_CUR) ? fp->cnt : 0L;
fp->cnt = 0;
}
if (lseek(fp->fd, offset, origin) == -1) {
fp->flag |= _ERR;
return EOF;
} else {
fp->flag &= ~_EOF;
return 0;
}
}
int main(void)
{
FILE *temp;
int i;
char c, *s, tpath[] = "temp-8-4.txt";
char draft[] = "My Ham is Green and I like to Eat it.\n";
write(1, "Started with: ", 15);
write(1, draft, 38);
/* Write draft text to temp file */
if ((temp = fopen(tpath, "w")) == NULL) {
write(2, "error: failed to open temp to write!\n", 37);
return 1;
}
for (s = draft; *s; s++)
putc(*s, temp);
/* edit the temp file */
fseek(temp, 3L, SEEK_SET);
for (s = "Dog"; *s; s++)
putc(*s, temp);
fseek(temp, 4L, SEEK_CUR);
for (s = "Beige"; *s; s++)
putc(*s, temp);
fseek(temp, -8L, SEEK_END);
for (s = "Pat"; *s; s++)
putc(*s, temp);
fclose(temp);
write(1, "Ended with: ", 15);
/* read temp file and write to stdout */
if ((temp = fopen(tpath, "r")) == NULL) {
write(2, "error: failed to open temp to read!\n", 36);
return 1;
}
while ((c = getc(temp)) != EOF)
putchar(c);
fflush(stdout);
/* fseek with read and SEEK_CUR */
fseek(temp, 0, SEEK_SET);
write(1, "Read SEEK_CUR: ", 15);
for (i = 0; i < 22; i++)
putchar(getc(temp));
fseek(temp, 8L, SEEK_CUR);
while ((c = getc(temp)) != EOF)
putchar(c);
fclose(stdout);
fclose(temp);
return 0;
}
|
C
|
#include "util.h"
typedef int bool;
#define true 1
#define false 0
#define SYS_READ 3
#define SYS_WRITE 4
#define SYS_OPEN 5
#define SYS_CLOSE 6
#define SYS_LSEEK 19
#define SYS_EXIT 1
#define STDIN 0
#define STDOUT 1
#define STDERR 2
#define SEEK_CUR 1
#define SEEK_END 2
#define O_RDONLY 0
#define O_WRONLY 1
#define O_RDRW 2
#define O_CREAT 64
#define MAX_LEN 50
char *input_file = "stdin", *output_file = "stdout";
char sys_id, ret_code;
bool debug = false;
int input_desc = STDIN, output_desc = STDOUT;
char toLower(char ch);
void print_debug(void);
void error_quit(char * msg);
int main (int argc , char* argv[], char* envp[])
{
char ch;
int i;
/* Parse program arguments */
for(i=1 ;i<argc; i++) {
if(strcmp(argv[i], "-D") == 0)
debug = true;
else if(strncmp(argv[i], "-i", 2*sizeof(char)) == 0) {
input_file = argv[i]+2;
if((ret_code = input_desc = system_call(sys_id = SYS_OPEN, input_file, O_RDONLY, 0777)) < 0)
error_quit("\nError opening input file! EXITING.\n");
print_debug();
}
else if(strncmp(argv[i], "-o", 2*sizeof(char)) == 0) {
output_file = argv[i]+2;
if((ret_code = output_desc = system_call(sys_id = SYS_OPEN, output_file, O_WRONLY | O_CREAT, 0777)) < 0)
error_quit("\nError opening output file! EXITING.\n");
print_debug();
}
}
/* Get input and print output char by char loop */
while ((ret_code = system_call(sys_id = SYS_READ, input_desc, &ch, 1)) > 0) /* while ch != EOF */
{
print_debug();
ch = toLower(ch);
ret_code = system_call(sys_id = SYS_WRITE, output_desc, &ch, 1);
print_debug();
}
ret_code = system_call(sys_id = SYS_CLOSE, input_desc);
print_debug();
if(strcmp(output_file, "stdout") != 0) {
ret_code = system_call(sys_id = SYS_CLOSE, output_desc);
print_debug();
}
system_call(SYS_EXIT, 0);
return 0;
}
void print_debug(void)
{
char *sys_call_str, *ret_code_str, *in, *out;
if(debug) {
in = "\nInput file: ";
out = "\nOutput file: ";
sys_call_str = "\nSystem call ID: ";
ret_code_str = "\nReturn Code: ";
system_call(SYS_WRITE, STDERR, in, strlen(in));
system_call(SYS_WRITE, STDERR, input_file, strlen(input_file));
system_call(SYS_WRITE, STDERR, out, strlen(out));
system_call(SYS_WRITE, STDERR, output_file, strlen(output_file));
system_call(SYS_WRITE, STDERR, sys_call_str, strlen(sys_call_str));
system_call(SYS_WRITE, STDERR, itoa(sys_id), 2);
system_call(SYS_WRITE, STDERR, ret_code_str, strlen(ret_code_str));
system_call(SYS_WRITE, STDERR, itoa(ret_code), 2);
system_call(SYS_WRITE, STDERR, "\n", 1);
}
}
void error_quit(char * msg)
{
ret_code = system_call(sys_id = SYS_WRITE, STDERR, msg, strlen(msg));
print_debug();
system_call(SYS_EXIT, 0x55);
}
char toLower(char ch)
{
if(ch>='A' && ch<='Z')
ch += 32;
return ch;
}
|
C
|
/*
* @Author: your name
* @Date: 2020-01-04 11:11:55
* @LastEditTime : 2020-01-09 15:56:53
* @LastEditors : Please set LastEditors
* @Description: 假定数据域的四个变量存的数据是唯一的
注意字符串的比较,必须用函数strcmp()
* @FilePath: \myshare\manager_system_v3\show.c
*/
#include "show.h" //头文件
int show(stPeople *head)
{
stPeople *p; //通过p找到最后一个节点
p = head;
while (p->next != head) //如果记录下一个节点的地址不是头结点的地址
{
p = p->next; //将下一个节点的地址赋给p,即,p往下一个节点移动
//将遍历的节点的顺序、地址好人数据打印显示
printf("姓名:%s\t性别:%s\t身份证:%s\t年龄:%d\n", p->name, p->gend, p->id, p->age);
} //直到遍历到的最后一个节点的指针域保存了头结点的地址,则循环结束
return 0;
}
int SearchName(stPeople *head, char *name)
{
stPeople *p; //通过p找到最后一个节点
int i = 0;
p = head;
while (p->next != head) //遍历整个链表
{
if (strcmp(p->next->name, name) == 0) //判断p->next指向的节点里面的数据域保存的数据是否和number相等
{
//相等即找到节点的前一个节点,返回该节点的地址
//return p->next;
i++;
printf("第%d条记录:\t", i);
printf("姓名:%s\t性别:%s\t身份证:%s\t年龄:%d\n",\
p->next->name, p->next->gend, p->next->id, p->next->age);
}
p = p->next; //p往下一个节点移动
}
//循环正常结束的时候表示在该链表里面找不到对应的节点,此时p指向最后一个节点
return i;
}
int SearchGend(stPeople *head, char *gend)
{
stPeople *p; //通过p找到最后一个节点
int i = 0;
p = head;
while (p->next != head) //遍历整个链表
{
if (strcmp(p->next->gend, gend) == 0) //判断p->next指向的节点里面的数据域保存的数据是否和number相等
{
i++;
printf("第%d条记录:\t", i);
printf("姓名:%s\t性别:%s\t身份证:%s\t年龄:%d\n",\
p->next->name, p->next->gend, p->next->id, p->next->age);
}
p = p->next; //p往下一个节点移动
}
//循环正常结束的时候表示在该链表里面找不到对应的节点,此时p指向最后一个节点
return i;
}
int SearchId(stPeople *head, char *id)
{
stPeople *p; //通过p找到最后一个节点
p = head;
while (p->next != head) //遍历整个链表
{
if (strcmp(p->next->id, id) == 0) //判断p->next指向的节点里面的数据域保存的数据是否和number相等
{
printf("姓名:%s\t性别:%s\t身份证:%s\t年龄:%d\n",\
p->next->name, p->next->gend, p->next->id, p->next->age);
return 1;
}
p = p->next; //p往下一个节点移动
}
return 0;
}
int SearchAge(stPeople *head, unsigned age)
{
stPeople *p; //通过p找到最后一个节点
int i = 0;
p = head;
while (p->next != head) //遍历整个链表
{
if (p->next->age == age) //判断p->next指向的节点里面的数据域保存的数据是否和number相等
{
i++;
printf("第%d条记录:\t", i);
printf("姓名:%s\t性别:%s\t身份证:%s\t年龄:%d\n",\
p->next->name, p->next->gend, p->next->id, p->next->age);
}
p = p->next; //p往下一个节点移动
}
return i;
}
//单次查找信息
int FindOne(stPeople *head)
{
char ch;
char name[32];
char gend[8];
char id[20];
unsigned age;
int FoundNode = 0;
printf("=================================================================\n");
printf("请选择查找方式:\n");
printf("1-按姓名查找\t2-按性别查找\t3-按身份证查找\t4-按年龄查找\n");
scanf(" %c", &ch);
switch (ch)
{
case '1':
printf("请输入要查找的姓名:");
scanf("%s", name);
FoundNode = SearchName(head, name);
break;
case '2':
printf("请输入要查找的性别:");
scanf("%s", gend);
FoundNode = SearchGend(head, gend);
break;
case '3':
printf("请输入要查找的身份证:");
scanf("%s", id);
FoundNode = SearchId(head, id);
break;
case '4':
printf("请输入要查找的年龄:");
scanf("%d", &age);
FoundNode = SearchAge(head, age);
break;
default:
printf("没有该选项!!!\n");
return FoundNode;
}
printf("总共找到%d条记录!\n", FoundNode);
return FoundNode;
}
//实现循环查找
int find(stPeople *head)
{
int flag = 1;
char ch;
int FoundNode;
while (flag)
{
FoundNode = FindOne(head);
if (FoundNode == 0)
{
printf("输入错误或查询条件不存在,请重新输入!!!\n");
}
printf("=================================================================\n");
printf("退出查找请按数字“1”,否则继续查找\n");
scanf(" %c", &ch);
if (ch == '1')
{
flag = 0;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void pr1(int *a){
*a = 10123;
}
void pr2(int** a){
*a = (int*) malloc(sizeof(int) * 10);
**a = 1;
}
int main(){
int c[] = {5,3,2,10};
int *a = c;
printf("%d\n", a[0]);
pr1(a);
printf("%d\n", a[0]);
pr2(&a);//direccion de la direccion, apuntador a un apuntador
printf("%d\n", a[0]);
return 0;
}
|
C
|
#define solution isJasons
#include <stdio.h>
int n, m, t1, t2, a[100000], b[100000], c[100000];
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
b[i] = c[i] = 0;
}
scanf("%d", &m);
while (m--) {
scanf("%d%d", &t1, &t2);
b[t1] = -t2;
}
b[0] = a[0];
for (int i = 1; i < n; i++) {
b[i] += b[i - 1] + a[i];
if (b[i] < c[i - 1] + a[i])
b[i] = c[i - 1] + a[i];
c[i] = c[i - 1] > b[i - 1] ? c[i - 1] : b[i - 1];
}
printf("%d", b[n - 1] > c[n - 1] ? b[n - 1] : c[n - 1]);
}
|
C
|
#include <sys/types.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main(int argc, char **argv) {
int fd;
off_t from, till;
size_t sz;
char *endptr, *buf;
if ((fd = open(argv[1], O_RDONLY)) == -1)
err(1, "open: %s", argv[1]);
from = strtoull(argv[2], &endptr, 10);
if (!endptr)
errx(1, "from is wrong: %s", argv[2]);
till = strtoull(argv[3], &endptr, 10);
if (!endptr)
errx(1, "till is wrong: %s", argv[3]);
sz = (size_t)(till - from);
buf = malloc(sz);
if (pread(fd, buf, sz, from) == -1)
err(1, "read");
puts(buf);
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int a, b, c, m, n;
scanf("%d%d", &a, &b);
if (a < b)
{
c = b;
b = a;
a = c;
}
m = a * b;
n = a % b;
while (n != 0) {
a = b;
b = n;
n = a % b;
}
printf("%d %d", b, m / b);
return 0;
}
|
C
|
#include <stdio.h>
#define MAX_DEER_COUNT 200
int get_rudolph_number(int barn[]);
int array_value_count(int , int array[]);
int main()
{
int barn[MAX_DEER_COUNT]={0};
int deer_count;
int counter = 0;
int rudolph_index;
scanf("%d",&deer_count);
if(deer_count > 200)
{
printf("deer count can't be more than 200\n");
return -1;
}
else if(!(deer_count % 2))
{
printf("deer count must be odd\n");
}
for(; counter < deer_count; counter++)
{
int current_deer;
scanf("%d",¤t_deer);
if(current_deer < 1 || current_deer > 100)
{
printf("Invalid deer number\n");
}
barn[counter] = current_deer;
}
rudolph_index = get_rudolph_number(barn);
printf("%d", rudolph_index);
return 0;
}
int get_rudolph_number(int barn[])
{
int counter = 0;
while(barn[counter] > 0)
{
int count = array_value_count(barn[counter],barn);
if(count == 1)
{
return barn[counter];
}
counter++;
}
return -1;
}
int array_value_count(int number, int array[])
{
int count = 0;
int counter = 0;
while(array[counter] > 0)
{
if(array[counter] == number)
{
count++;
}
counter++;
}
return count;
}
|
C
|
#ifndef INT_UTILS_H
#define INT_UTILS_H
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
//#define MAX(x, y) (((x) > (y)) ? (x) : (y))
//#define MIN(x, y) (((x) < (y)) ? (x) : (y))
void max_z();
void min_z();
void gcd_z();
void lcm_z();
void pow_z();
void max_z(mpz_t max, mpz_t a, mpz_t b) {
if(mpz_cmp(a,b)>0) {
mpz_set(max, a);
}
else {
mpz_set(max, b);
}
}
void min_z(mpz_t min, mpz_t a, mpz_t b) {
if(mpz_cmp(a,b)>0) {
mpz_set(min, b);
}
else {
mpz_set(min, a);
}
}
void gcd_z(mpz_t gcd, mpz_t a, mpz_t b) {
mpz_t a_abs; mpz_init(a_abs);
mpz_t b_abs; mpz_init(b_abs);
mpz_abs(a_abs, a);
mpz_abs(b_abs, b);
if(mpz_cmp(a_abs,b_abs)==0) {
mpz_set(gcd, a_abs);
}
else {
if(mpz_cmp_si(a_abs,0)==0 || mpz_cmp_si(b_abs,0)==0) {
mpz_t max; mpz_init(max);
max_z(max, a_abs, b_abs);
mpz_set(gcd, max);
mpz_clear(max);
}
else {
mpz_t r; mpz_init(r);
mpz_t max; mpz_init(max);
mpz_t min; mpz_init(min);
max_z(max, a_abs, b_abs);
min_z(min, a_abs, b_abs);
mpz_tdiv_r(r, max, min);
gcd_z(gcd, min, r);
mpz_clears(r, max, min, NULL);
}
}
mpz_clears(a_abs, b_abs, NULL);
}
void lcm_z(mpz_t lcm, mpz_t a, mpz_t b) {
mpz_t a_abs; mpz_init(a_abs);
mpz_t b_abs; mpz_init(b_abs);
mpz_abs(a_abs, a);
mpz_abs(b_abs, b);
mpz_t mult; mpz_init(mult);
mpz_t gcd; mpz_init(gcd);
mpz_mul(mult, a_abs, b_abs);
gcd_z(gcd, a, b);
mpz_cdiv_q(lcm, mult, gcd);
mpz_clears(a_abs, b_abs, mult, gcd, NULL);
}
void pow_z(mpz_t pow, mpz_t b, int exp) {
if (exp==0) {
mpz_set_ui(pow, 1);
}
else {
pow_z(pow, b, exp-1);
mpz_mul(pow, pow, b);
}
}
#endif /* INT_UTILS_H */
|
C
|
// importe de input e output
#include <stdio.h>
#include "teste.h"
// *p
// p = ponteiro
// &p = endereço de p na memoria
// *p = conteudo do endereço de memoria
int main ()
{
int a,b, *c, g;
// =========== Ponteiro ==========
// se *c então o valor é atribuido no endereço, caso c entao o valor se torna o endereço da memoria
c = &a;
a = 5;
b = 50;
// a = c2f(50);
char vet[10];
// Coloca-se & para que o scan guarde o valor digitado na memoria, caso sem, ele pega o valor e defini como endereço de memoria
scanf("%i", &g);
// printf("Ponteiro: %i %i %p %p %p\n", a, b, &g, &vet[0], &vet[1]);
// printf("%p %p\n", &vet, &vet+1);
printf("%p \n", &g);
return 0;
}
|
C
|
#include <stdio.h>
#include <pthread.h>
#include "programs.h"
#include <semaphore.h>
//office acts as the buffer to queue students to talk to the professor
int office[officeSize];
int officeSize;
int officeCounter;
//students are semaphores
void Student(int id) {
int i;
int length = (id % 4) + 1;
sem_t studentSem;
sem_init(&studentSem, 0, 1);
//pthread_t studentThread = malloc(sizeof(studentThread));
EnterOffice(id);
for(i = 0; i < length; i++) {
QuestionStart(id);
QuestionDone(id);
}
}
//professor is a thread
void Professor() {
pthread_t professorThread = malloc(sizeof(professorThread));
int i;
for(i = 0; i < 2; i++) {
AnswerStart(i);
AnswerDone(i);
}
}
int main(int argc, char **argv) {
}
void AnswerStart(int id) {
printf("Professor starts to answer question for student %d\n", id);
}
void AnswerDone(int id) {
printf("Professor is done with answer for student %d\n", id);
}
|
C
|
#include<stdio.h>
int main(){
int number;
printf("Enter a number : \n");
scanf("%d",&number);
if(number>=0){
printf("This is a Positive number");
}else {
printf("This is a Negative number");
}
return 0;
}
|
C
|
#include "Utils.h"
void __listR(Tree_t *bst, Tree_t **arr, int *count)
{
if (!bst)
return;
__listR(bst->left, arr, count);
arr[(*count)++] = bst;
__listR(bst->right, arr, count);
}
Tree_t *__pushR(Tree_t *bst, void *key, void *value, size_t ks, int *hchange)
{
if (!bst) //node folha
{
*hchange = 1;
return tree_init(key, value, ks, NULL);
}
else //caso geral
{
Tree_t *child;
if (bst->compare(bst->key, key) == 1)
{
child = __pushR(bst->left, key, value, ks, hchange);
child->compare = bst->compare;
bst->left = child;
if (*hchange)
{
if (bst->balance == +1)
{
bst->balance = 0;
*hchange = 0;
}
else if (bst->balance == 0)
{
bst->balance = -1;
*hchange = 1;
}
else if (bst->balance == -1)
{
if (bst->left->balance == -1)
{
bst = tree_rotate(bst, RIGHT);
bst->right->balance = 0;
}
else
{
bst->left = tree_rotate(bst->left, LEFT);
bst = tree_rotate(bst, RIGHT);
if (bst->balance == 0)
{
bst->right->balance = bst->left->balance = 0;
}
else if (bst->balance == -1)
{
bst->left->balance = 0;
bst->right->balance = +1;
}
else
{
bst->left->balance = -1;
bst->right->balance = 0;
}
}
bst->balance = 0;
*hchange = 0;
}
}
}
else
{
child = __pushR(bst->right, key, value, ks, hchange);
child->compare = bst->compare;
bst->right = child;
if (*hchange)
{
if (bst->balance == -1)
{
bst->balance = 0;
*hchange = 0;
}
else if (bst->balance == 0)
{
bst->balance = +1;
*hchange = 1;
}
else if (bst->balance == +1)
{
if (bst->right->balance == +1)
{
bst = tree_rotate(bst, LEFT);
bst->left->balance = 0;
}
else
{
bst->right = tree_rotate(bst->right, RIGHT);
bst = tree_rotate(bst, LEFT);
if (bst->balance == 0)
{
bst->right->balance = bst->left->balance = 0;
}
else if (bst->balance == +1)
{
bst->left->balance = 0;
bst->right->balance = -1;
}
else
{
bst->left->balance = +1;
bst->right->balance = 0;
}
}
bst->balance = 0;
*hchange = 0;
}
}
}
child->parent = bst;
return bst;
}
}
void setBalance(Tree_t *t)
{
if (!t)
return;
t->balance = tree_height(t->right) - tree_height(t->left);
setBalance(t->left);
setBalance(t->right);
}
|
C
|
#include<stdio.h>
int fact(int n)
{
if(n==0)
return 1;
else
return n*fact(n-1);
}
int ncr(int n,int r)
{
int num,den;
num=fact(n);
den=fact(r)*fact(n-r);
return num/den;
}
int main()
{
int n,r;
scanf("%d%d",&n,&r);
printf("%d",ncr(n,r));
return 0;
}
|
C
|
#include <stdio.h>
#include <assert.h>
#include "linkedList.h"
/* Double Link Struture */
struct DLink {
TYPE value;/* value of the link */
struct DLink * next;/* pointer to the next link */
struct DLink * prev;/* pointer to the previous link */
};
/* Double Linked List with Head and Tail Sentinels */
struct linkedList{
int size;
struct DLink *firstLink;
struct DLink *lastLink;
};
void printList(struct linkedList* lst)
{
assert(lst);
assert(lst->lastLink);
assert(lst->firstLink);
for(struct DLink *l=lst->firstLink->next;
l!=lst->lastLink;
l=l->next){
//null checking
assert(l);
printf("%d, ",l->value);
}
printf("\n");
}
int main(){
struct linkedList *b = createLinkedList();
for(int i = 0 ; i < 15 ; i++) {
addList(b, (TYPE)i);/*Add elements*/
printList(b);
}
}
|
C
|
/*
** EPITECH PROJECT, 2019
** pushswap
** File description:
** my_put.c
*/
#include "pushswap.h"
void my_put_array(int len, int *arr)
{
int i = 0;
for (i = 0; i < len; i++) {
my_put_nbr(arr[i]);
my_put_char(' ');
}
my_put_char('\n');
}
|
C
|
#include<stdio.h>
int chkprop(int n){
int i, num_of_factors=0;
int factors[n];
for(i=1; i<n; i++){
if(n%i==0){
factors[num_of_factors]=i;
num_of_factors++;
}
}
int j,k,l, prod, max=0;
for(i=0; i<num_of_factors; i++){
for(j=0; j<num_of_factors; j++){
for(k=0; k<num_of_factors; k++){
for(l=0; l<num_of_factors; l++){
if(n==(factors[i]+factors[j]+factors[k]+factors[l])){
prod=factors[i]*factors[j]*factors[k]*factors[l];
}
else
continue;
if(prod>max){
max=prod;
}
}
}
}
}
return max;
}
int main(){
int i,queries;
scanf("%d", &queries);
int* arr_queries = (int*)malloc(queries*sizeof(int));
for(i=0; i<queries; i++){
scanf("%d", &arr_queries[i]);
}
int tmp;
for(i=0; i<queries; i++){
if(chkprop(arr_queries[i])==0)
printf("-1\n");
else{
printf("%d\n", chkprop(arr_queries[i]));
}
}
}
|
C
|
/*Program to use for loop */
#include<stdio.h>
void main()
{
int x,y;
for(x=1,y=100;x<=100,y>=1;x++,y--)
printf(" %d \t %d \n",x,y);
}
|
C
|
#include <stdio.h>
int main() {
int a, b, c;
scanf("%d", &a);
b = (a - 1) / 2;
c = b;
for (int i = 1; i <= (a - 1) / 2; i++) {
for (int j = 1; j <= b; j++) {
printf(" ");
}
b--;
for (int j = 1; j <= 2 * i - 1; j++) {
printf("*");
}
printf("\n");
}
b++;
for (int i = 1; i <= a; i++) {
printf("*");
}
printf("\n");
for (int i = 1; i <= (a - 1) / 2; i++) {
for (int j = 1; j <= b; j++) {
printf(" ");
}
b++;
for (int j = 1; j <= 2 * c - 1; j++) {
printf("*");
}
c--;
printf("\n");
}
}
|
C
|
//==============================================================================
// Message Class Library
//
// (C) Copyright IBM Corp. 1997, 2005 All Rights Reserved
//==============================================================================
//-----------------------------------------------------------------------------
// File unitTest.C
//
// Contains main program for unitTest
//
// Contains the implementation of the following classes:
//
// Tester
// TestOutputDisplayer
// TestMsg
//
//-----------------------------------------------------------------------------
#include <mcl/src/unitTest.h>
#include <mcl/src/arg.h>
#include <mcl/src/facility.h>
#include <mcl/src/level.h>
#include <mcl/src/set.h>
//-----------------------------------------------------------------------------
// Turn on assert.
//-----------------------------------------------------------------------------
//#ifdef NDEBUG
//#undef NDEBUG
//#endif
#include <assert.h>
#include <iostream>
//-----------------------------------------------------------------------------
// Main program.
//-----------------------------------------------------------------------------
int main ()
{
MclTester theTester;
theTester.unitTest ();
return 0;
}
//-----------------------------------------------------------------------------
// Implementation of class Tester.
//-----------------------------------------------------------------------------
MclTester::MclTester ()
{
}
//-----------------------------------------------------------------------------
MclTester::~MclTester ()
{
}
//-----------------------------------------------------------------------------
void MclTester::unitTest ()
{
testArg ();
testStringArg ();
testArgList ();
testMsgUnit ();
testMsg ();
testMsgFrag ();
testLevel ();
testDictEl ();
testMsgUnitSet ();
testOutputDisplayer ();
testMsgUnitItr ();
testFacility ();
testingMessage ("All tests completed successfully.\n");
}
//-----------------------------------------------------------------------------
void MclTester::testArg ()
{
testingMessage ("Testing MclArg\n");
bool theBoolVec[] = {false, true, true, false};
int iv[] = {1,2,3,4,5};
MclBoolean bv[] = {TRUE, FALSE, TRUE};
float fv[] = {0.3F, 3.5F, 4.21F};
double dv[] = {1.0000000000001,
1.0000000000002,
1.0000000000003};
const char * sv[] = {"Zero", "One", "Two", "Three"};
//--------------------------------------------------------------------------
// Set up testing environment.
//--------------------------------------------------------------------------
MclTestOutputDisplayer theDisp;
MclFacility theFacility ("TST", theDisp);
MclTestMsg * theInfoMsg = new MclTestMsg (
theFacility,
"setStringAttrMsg",
MclLevel::info (),
"%1$s changed from \"%2$s\" to \"%3$s\".",
99);
MclMsgFrag * theFrag =
new MclMsgFrag (theFacility, "hardLowerBoundFrag", "Hard lower bound");
//--------------------------------------------------------------------------
//Test constructors
MclStringArg s("This is a test");
MclBoolArg theBoolArg (true);
MclIntArg i(123);
MclIntArg b(FALSE);
MclFloatArg f(1.2345f);
MclDoubleArg theDblArg (1.23456789012345);
MclMsgFragArg theMsgFragArg (theFrag);
MclBoolVectorArg theBoolVectorArg(theBoolVec, 4);
MclIntVectorArg theIntVectorArg(iv, 5);
MclIntVectorArg theBoolIntVectorArg(bv, 3);
MclFloatVectorArg theFloatVectorArg(fv, 3);
MclDoubleVectorArg theDoubleVectorArg (dv, 3);
MclStringVectorArg theStringVectorArg(sv, 4);
// Test method clone()
MclArg * a = s.clone();
assert (valueText (* a, theInfoMsg) == "This is a test");
delete a;
// Test valueText
assert (valueText (theIntVectorArg, theInfoMsg) == "\n1 2 3 4 5");
// Test format
std::string formattedArg;
s.format (formattedArg, "%-20s", FALSE, 1, theInfoMsg);
assert (formattedArg == "This is a test ");
theBoolArg.format (formattedArg, "%-6b", FALSE, 1, theInfoMsg);
assert (formattedArg == "TRUE ");
i.format (formattedArg, "%-6d", FALSE, 1, theInfoMsg);
assert (formattedArg == "123 ");
b.format (formattedArg, "%-6b", FALSE, 1, theInfoMsg);
assert (formattedArg == "FALSE ");
f.format (formattedArg, "%7.3f", FALSE, 1, theInfoMsg);
assert (formattedArg == " 1.235");
theDblArg.format (formattedArg, "%15.12f", FALSE, 1, theInfoMsg);
assert (formattedArg == " 1.234567890123");
theMsgFragArg.format (formattedArg, "%s", FALSE, 1, theInfoMsg);
assert (formattedArg == "Hard lower bound");
theMsgFragArg.format (formattedArg, "%-20m", FALSE, 1, theInfoMsg);
assert (formattedArg == "Hard lower bound ");
theBoolVectorArg.format (formattedArg, "%-5b", TRUE, 1, theInfoMsg);
assert (formattedArg == "\nFALSE TRUE TRUE FALSE");
theIntVectorArg.format (formattedArg, "%2d", TRUE, 1, theInfoMsg);
assert (formattedArg == "\n 1 2 3 4 5");
theBoolIntVectorArg.format (formattedArg, "%b", TRUE, 1, theInfoMsg);
assert (formattedArg == "\nTRUE FALSE TRUE");
theFloatVectorArg.format (formattedArg, "%.3f", TRUE, 1, theInfoMsg);
assert (formattedArg == "\n0.300 3.500 4.210");
theDoubleVectorArg.format (formattedArg, "%.13f", TRUE, 1, theInfoMsg);
assert (formattedArg == "\n1.0000000000001 1.0000000000002 1.0000000000003");
theStringVectorArg.format (formattedArg, "%-6s", TRUE, 1, theInfoMsg);
assert (formattedArg == "\nZero One Two Three ");
// Test MclMakeVec functions.
assert (
valueText (MclMakeVec (theBoolVec, 4), theInfoMsg)
== "\nFALSE TRUE TRUE FALSE");
assert (valueText (MclMakeVec (iv, 5), theInfoMsg) == "\n1 2 3 4 5");
assert (valueText (MclMakeVec (fv, 3), theInfoMsg) == "\n0.3 3.5 4.21");
assert (valueText (MclMakeVec (sv, 4), theInfoMsg) == "\nZero One Two Three");
}
//-----------------------------------------------------------------------------
void MclTester::testStringArg ()
{
testingMessage ("Testing MclStringArg\n");
//--------------------------------------------------------------------------
// Set up testing environment.
//--------------------------------------------------------------------------
MclTestOutputDisplayer theDisp;
MclFacility theFacility ("TST", theDisp);
MclTestMsg * theInfoMsg = new MclTestMsg (
theFacility,
"setStringAttrMsg",
MclLevel::info (),
"%1$s changed from \"%2$s\" to \"%3$s\".",
99);
//--------------------------------------------------------------------------
//Test constructors
MclStringArg s("This is a test");
// Test method clone()
MclArg * a = s.clone();
assert (valueText (* a, theInfoMsg) == "This is a test");
// Test destructor
delete a;
}
//-----------------------------------------------------------------------------
void MclTester::testArgList ()
{
testingMessage ("Testing MclArgList\n");
//--------------------------------------------------------------------------
// Set up testing environment.
//--------------------------------------------------------------------------
MclTestOutputDisplayer theDisp;
MclFacility theFacility ("TST", theDisp);
MclTestMsg * theInfoMsg = new MclTestMsg (
theFacility,
"setStringAttrMsg",
MclLevel::info (),
"%1$s changed from \"%2$s\" to \"%3$s\".",
99);
//--------------------------------------------------------------------------
// Test constructor
MclArgList argList;
// Test append methods
MclStringArg arg("1st arg");
argList << arg<<"2nd arg"<<true<<123<<1.23456f;
MclMsgFrag * theFrag =
new MclMsgFrag (theFacility, "materialFrag", "Material");
argList << theFrag;
bool theBoolVec[] = {false,false,true};
argList << MclBoolVectorArg(theBoolVec, 3);
int iv[] = {1,2,3,4,5,6,7,8,9,10,11,12};
argList << MclIntVectorArg(iv, 12);
float fv[] = {1.1F,2.2F,3.3F};
argList << MclFloatVectorArg(fv, 3);
double dv[] = {1.0000000000001, 1.0000000000026};
argList << MclDoubleVectorArg (dv, 2);
// Test operator[]
assert (valueText (argList[1], theInfoMsg) == "1st arg");
assert (valueText (argList[2], theInfoMsg) == "2nd arg");
assert (valueText (argList[3], theInfoMsg) == "TRUE");
assert (valueText (argList[4], theInfoMsg) == "123");
assert (valueText (argList[5], theInfoMsg) == "1.23456");
assert (valueText (argList[6], theInfoMsg) == "Material");
assert (valueText (argList[7], theInfoMsg) == "\nFALSE FALSE TRUE");
assert (valueText (argList[8], theInfoMsg) ==
"\n1 2 3 4 5 6 7 8 9 10 11 12");
assert (valueText (argList[9], theInfoMsg) == "\n1.1 2.2 3.3");
assert (valueText (argList[10], theInfoMsg) ==
"\n1.0000000000001 1.0000000000026");
// Test length
assert (argList.length () == 10);
}
//-----------------------------------------------------------------------------
void MclTester::testMsgUnit ()
{
testingMessage ("Testing MclMsgUnit\n");
//--------------------------------------------------------------------------
// Set up testing environment.
//--------------------------------------------------------------------------
MclTestOutputDisplayer theDisp;
MclFacility theFacility ("TST", theDisp);
//--------------------------------------------------------------------------
// Test constructor.
//--------------------------------------------------------------------------
MclMsgUnit * theMsg = new MclMsg (
theFacility,
"witFuncCalled",
MclLevel::info (),
"PRM function %1$s entered.",
98);
MclMsgUnit * theFrag =
new MclMsgFrag (theFacility, "capacityFrag", "Capacity");
//--------------------------------------------------------------------------
// Test access functions.
//--------------------------------------------------------------------------
assert (& (theMsg ->myFacility ()) == & theFacility);
match ( theMsg ->id (), "witFuncCalled");
match ( theFrag->text (), "Capacity");
assert (! theFrag->isInserting ());
//--------------------------------------------------------------------------
// Test type conversion.
//--------------------------------------------------------------------------
assert (theMsg ->asaMsg () == theMsg);
assert (theMsg ->asaMsgFrag () == NULL);
assert (theFrag->asaMsg () == NULL);
assert (theFrag->asaMsgFrag () == theFrag);
}
//-----------------------------------------------------------------------------
void MclTester::testMsg ()
{
MclArgList emptyArgList;
testingMessage ("Testing MclMsg\n");
//--------------------------------------------------------------------------
// Set up testing environment.
//--------------------------------------------------------------------------
MclTestOutputDisplayer theDisp;
MclFacility theFacility ("TST", theDisp);
//--------------------------------------------------------------------------
// Test constructor.
//--------------------------------------------------------------------------
MclMsg * const theWarningMsg = new MclMsg (
theFacility,
"compatible34WarningMsg",
MclLevel::warning (),
"wit34Compatible is TRUE.\n"
"Your application should be updated to work with PRM Release 4.0.",
538);
MclMsg * const theInfoMsg = new MclMsg (
theFacility,
"witFuncCalled",
MclLevel::info (),
"PRM function %1$s entered.",
98);
match (theWarningMsg->id (), "compatible34WarningMsg");
match (theInfoMsg ->id (), "witFuncCalled");
//--------------------------------------------------------------------------
// Test issue.
//--------------------------------------------------------------------------
theWarningMsg->issue (emptyArgList);
//
// The local variable emptyArgList is being passed to the issue function.
// The natural alternative to this would be to create an empty ArgList
// with an explicit call to the constructor and pass the resulting
// temporary object to the issue function. But this causes some compilers
// to invoke the copy ctor for class MclArgList (or at least require that
// it be accessible), and this causes a syntax error, because the copy
// ctor has been declared private in order to prevent unintentional copy
// constructing. (See "Effective C++", Item 27.)
theDisp.reqText (
"TST0538W wit34Compatible is TRUE.\n"
" Your application should be updated "
"to work with PRM Release 4.0.\n",
TRUE);
theInfoMsg ->issue (MclArgList () << "witInitialize");
theDisp.reqText ("TST0098I PRM function witInitialize entered.\n", FALSE);
//--------------------------------------------------------------------------
// Test data setting and access functions.
//--------------------------------------------------------------------------
theInfoMsg ->
maxTimesIssued (2)->
preceedingLineFeeds (1)->
trailingLineFeeds (3)->
displayExternalNumber (FALSE)->
allowedToChange (FALSE);
assert (theInfoMsg->maxTimesIssued () == 2);
assert (theInfoMsg->preceedingLineFeeds () == 1);
assert (theInfoMsg->trailingLineFeeds () == 3);
assert (theInfoMsg->displayExternalNumber () == FALSE);
assert (theInfoMsg->allowedToChange () == FALSE);
theInfoMsg ->issue (MclArgList () << "<#2>");
theDisp.reqText ("\nPRM function <#2> entered.\n\n\n", FALSE);
theInfoMsg ->issue (MclArgList () << "<#3>");
theDisp.reqText ("\nPRM function <#2> entered.\n\n\n", FALSE);
assert (theInfoMsg->timesIssued () == 3);
//---------------------------------------------------------------------------
// Test vectorIndent.
//---------------------------------------------------------------------------
MclMsg * const theVecMsg = new MclMsg (
theFacility,
"extSupplyVolDdMsg",
MclLevel::info (),
" External supply volumes:%1v$8.0f",
131);
float theVec [] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
theVecMsg->vectorIndent (6);
assert (theVecMsg->vectorIndent () == 6);
theVecMsg->issue (MclArgList () << MclMakeVec (theVec, 20));
theDisp.reqText (
"TST0131I External supply volumes:\n"
" 0 1 2 3 4 5 6"
"\n"
" 7 8 9 10 11 12 13"
"\n"
" 14 15 16 17 18 19\n",
FALSE);
theVecMsg->displayExternalNumber (FALSE);
theVecMsg->issue (MclArgList () << MclMakeVec (theVec, 20));
theDisp.reqText (
" External supply volumes:\n"
" 0 1 2 3 4 5 6 7"
"\n"
" 8 9 10 11 12 13 14 15"
"\n"
" 16 17 18 19\n",
FALSE);
}
//-----------------------------------------------------------------------------
void MclTester::testMsgFrag ()
{
testingMessage ("Testing MclMsgFrag\n");
//--------------------------------------------------------------------------
// Set up testing environment.
//--------------------------------------------------------------------------
MclTestOutputDisplayer theDisp;
MclFacility theFacility ("TST", theDisp);
//--------------------------------------------------------------------------
// Test constructor.
//--------------------------------------------------------------------------
MclMsgFrag * theFrag =
new MclMsgFrag (theFacility, "hardLowerBoundFrag", "Hard lower bound");
}
//-----------------------------------------------------------------------------
void MclTester::testLevel ()
{
testingMessage ("Testing MclLevel and its derived classes\n");
//--------------------------------------------------------------------------
// Set up testing environment.
//--------------------------------------------------------------------------
MclTestOutputDisplayer theDisp;
MclFacility theFacility ("TST", theDisp);
//--------------------------------------------------------------------------
// (Test of Level instance access functions is implied by the other tests.)
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Test Level access functions.
//--------------------------------------------------------------------------
assert (MclLevel::warning ().flag () == 'W');
assert (MclLevel::error ().severity () == 2 );
//--------------------------------------------------------------------------
// Test comparison operators.
//--------------------------------------------------------------------------
assert (! (MclLevel::info () == MclLevel::warning ()));
assert (MclLevel::warning () != MclLevel::error ());
assert (MclLevel::error () <= MclLevel::severe ());
assert (! (MclLevel::severe () >= MclLevel::fatal ()));
assert (! (MclLevel::severe () < MclLevel::severe ()));
assert (MclLevel::fatal () > MclLevel::warning ());
}
//-----------------------------------------------------------------------------
void MclTester::testDictEl ()
{
testingMessage ("Testing MclDictEl\n");
//--------------------------------------------------------------------------
// Set up testing environment.
//--------------------------------------------------------------------------
MclTestOutputDisplayer theDisp;
MclFacility theFacility ("TST", theDisp);
MclMsg * const theInfoMsg =
new MclTestMsg (
theFacility,
"titleMsg",
MclLevel::info (),
"Problem Title:"
"%1$s",
101);
//--------------------------------------------------------------------------
// Test main ctor.
//--------------------------------------------------------------------------
/* MclDictEl theEl (theInfoMsg);
//--------------------------------------------------------------------------
// Test myMsg.
//--------------------------------------------------------------------------
assert (theEl.myMsgUnit () == theInfoMsg);*/
}
//-----------------------------------------------------------------------------
void MclTester::testMsgUnitSet ()
{
testingMessage ("Testing MclMsgUnitSet\n");
// Set up testing environment.
// Implicitly test MsgUnitSet's ctor.
//
MclTestOutputDisplayer theDisp;
MclFacility theFacility ("TST", theDisp);
MclMsgUnitSet & theMsgUnitSet = theFacility.myMsgUnitSet_;
// Implicitly test insertKeyAndValue
MclMsg * theMsg =
new MclTestMsg (
theFacility,
"testMsgId",
MclLevel::fatal (),
"A message to test class MsgUnitSet.",
53);
//test method findValue
const MclMsgUnit * msg2 = theMsgUnitSet.findValue ("testMsgId");
match (msg2->id (), "testMsgId");
}
//-----------------------------------------------------------------------------
void MclTester::testOutputDisplayer ()
{
testingMessage ("Testing MclOutputDisplayer and its derived classes\n");
//test constructor
MclPrintfOutputDisplayer out("mclOut.tmp", "w");
out.output("This is a test\n");
MclTestOutputDisplayer tester;
tester.output ("Test output.\n");
tester.reqText ("Test output.\n", FALSE);
tester.outputError ("Test error output.\n");
assert (tester.outputErrorText_ == "Test error output.\n");
}
//-----------------------------------------------------------------------------
void MclTester::testMsgUnitItr ()
{
testingMessage ("Testing MclMsgUnitItr");
//--------------------------------------------------------------------------
// Set up testing environment.
//--------------------------------------------------------------------------
MclTestOutputDisplayer theDisp;
MclFacility theFacility ("TST", theDisp);
new MclMsgFrag (theFacility, "softLowerBoundFrag", "Soft lower bound");
new MclTestMsg (
theFacility,
"timingMismatchFmsg",
MclLevel::fatal (),
"Timing section mismatch.",
192);
new MclMsgFrag (theFacility, "capacityFrag", "Capacity");
new MclTestMsg (
theFacility,
"witFuncCalled",
MclLevel::info (),
"PRM function %1$s entered.",
198);
(new MclTestMsg (
theFacility,
"witFileParam",
MclLevel::info (),
"The file \"%1$s\" will be accessed.",
100))->
allowedToChange (FALSE);
//--------------------------------------------------------------------------
// Test ctor, nextMsgUnit.
//--------------------------------------------------------------------------
MclMsgUnitItr theItr (theFacility);
match (theItr.nextMsgUnit ()->id (), "softLowerBoundFrag"); // 1st Frag inserted
match (theItr.nextMsgUnit ()->id (), "capacityFrag"); // 2nd Frag inserted
match (theItr.nextMsgUnit ()->id (), "witFileParam"); // lowest ext msg no
match (theItr.nextMsgUnit ()->id (), "timingMismatchFmsg"); // middle ext msg no
match (theItr.nextMsgUnit ()->id (), "witFuncCalled"); // highest external msg no
assert (theItr.nextMsgUnit () == NULL);
//--------------------------------------------------------------------------
// Test reset, nextMsg.
//--------------------------------------------------------------------------
theItr.reset ();
match (theItr.nextMsg ()->id (), "witFileParam");
match (theItr.nextMsg ()->id (), "timingMismatchFmsg");
match (theItr.nextMsg ()->id (), "witFuncCalled");
assert (theItr.nextMsg () == NULL);
//--------------------------------------------------------------------------
// Test reset, nextMsgForChange.
//--------------------------------------------------------------------------
theItr.reset ();
match (theItr.nextMsgForChange (MclLevel::info ())->id (), "witFuncCalled");
assert (theItr.nextMsgForChange (MclLevel::info ()) == NULL);
//--------------------------------------------------------------------------
// Test nextMsgFrag.
//--------------------------------------------------------------------------
theItr.reset ();
match (theItr.nextMsgFrag ()->id (), "softLowerBoundFrag");
match (theItr.nextMsgFrag ()->id (), "capacityFrag");
assert (theItr.nextMsgFrag () == NULL);
}
//-----------------------------------------------------------------------------
void MclTester::testFacility ()
{
MclArgList emptyArgList;
testingMessage ("Testing MclFacility");
// test constructor and methods insert() and operator()
// Simple messages for testing
const char * msgId[] = {
"paramReadErrorInt",
"callostd::cerror",
"invalidAttr",
"intRangeError",
"floatRangeError",
"IntegerVector",
"FloatVector",
"StringVector",
"setBooleanAttrMsg",
"hasSubsInEffectDdMsg",
"categorySizeDdMsg",
"floatRangeErrorG",
"formatedStringWithAnyWidth",
"formatedIntWithAnyWidth",
};
const char * formatList[] = {
"Test_a_sequence_of_non-blanks_longer_than_lineLengthxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%1$s.",
"Memory allocation error when attempting to obtain %1$d bytes of memory.",
"Unrecognized attribute passed as parameter.",
"Value specified was %2$d. Attribute %1$s is out of range.",
"Float Value was %0002$-2.3f. Attribute %1$s is out of range.",
"Integer $ Vector in print format %%1v$d:%1v$d",
"2%%NOTFmt$10 Float Vector in the format %%1v$2.1f:%1v$2.1f",
"String v Vector:$%1v$s",
"%1$s changed from %2$b to %3$b.",
"Has Substitute Bom Entries In Effect?%1v$-5b",
"Number of %1$-8m Parts: %2$5d",
"Float Value was %2$9.3g. Attribute %1$s is out of range.",
"Value specified was %2$d. Attribute %1$-50s is out of range.",
"Number of Parts:%1$9d %2$s",
};
const char * finalTextList[] =
{
"\n\nTST0000E Test_a_sequence_of_non-blanks_longer_than_lineLengthxxxxxxxxxxxxxxxxxxx\n"
" xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"
" Parameter.txt.\n\n\n",
"TST0001W Memory allocation error "
"when attempting to obtain 123 bytes of memory.\n",
"TST0002I Unrecognized attribute passed as parameter.\n",
"TST0003S Value specified was 123. "
"Attribute IntegerAttribute is out of range.\n",
"TST0004F Float Value was 1.235. "
"Attribute FloatAttribute is out of range.\n",
"TST0005F Integer $ Vector in print format %1v$d:\n 1 2 3 4 5\n",
"TST0006F 2%NOTFmt$10 Float Vector in the format %1v$2.1f:\n"
" 1.1 2.2 3.3 4.4 5.5\n",
"TST0007F String v Vector:$\n str1 st%r2 ~!@#$%^&*()_+`0-=[]{}\\|:;'\"<>,./? %1$d str5%\n",
"TST0183I execEmptyBom changed from FALSE to TRUE.\n",
"TST0544I Has Substitute Bom Entries In Effect?\n"
" FALSE TRUE FALSE\n",
"TST0098I Number of Capacity Parts: 412\n",
"TST0073S Float Value was 3.46e+03. "
"Attribute FloatAttribute is out of range.\n",
"TST0012S Value specified was 123. "
"Attribute This is a test is out of"
" range.\n",
};
MclTestOutputDisplayer theDisp;
MclFacility msgFacil ("TST", theDisp);
//---------------------------------------------------------------------------
// Implictly test insert by constructing Msgs and MsgFrags.
//---------------------------------------------------------------------------
new MclTestMsg (msgFacil, msgId[4], MclLevel::fatal (), formatList[4], 4);
new MclTestMsg (msgFacil, msgId[3], MclLevel::severe (), formatList[3], 3);
new MclTestMsg (msgFacil, msgId[0], MclLevel::error (), formatList[0], 0);
new MclTestMsg (msgFacil, msgId[1], MclLevel::warning (), formatList[1], 1);
new MclTestMsg (msgFacil, msgId[2], MclLevel::info (), formatList[2], 2);
new MclTestMsg (msgFacil, msgId[5], MclLevel::fatal (), formatList[5], 5);
new MclTestMsg (msgFacil, msgId[6], MclLevel::fatal (), formatList[6], 6);
new MclTestMsg (msgFacil, msgId[7], MclLevel::fatal (), formatList[7], 7);
new MclTestMsg (msgFacil, msgId[8], MclLevel::info (), formatList[8],183);
new MclTestMsg (msgFacil, msgId[9], MclLevel::info (), formatList[9],544);
new MclTestMsg (msgFacil, msgId[10],MclLevel::info (), formatList[10],98);
new MclTestMsg (msgFacil, msgId[11],MclLevel::severe (), formatList[11],73);
new MclTestMsg (msgFacil, msgId[12], MclLevel::severe (), formatList[12], 12);
new MclTestMsg (msgFacil, msgId[13], MclLevel::severe (), formatList[13], 13);
new MclMsgFrag (msgFacil, "capacityFrag", "Capacity");
//---------------------------------------------------------------------------
// Test operator ()
//---------------------------------------------------------------------------
msgFacil.findMsg (msgId[0])->
preceedingLineFeeds (2) ->
trailingLineFeeds (3);
msgFacil(msgId[0], MclArgList() << "Parameter.txt");
theDisp.reqText (finalTextList[0], TRUE);
msgFacil(msgId[1], MclArgList() << 123);
theDisp.reqText (finalTextList[1], TRUE);
msgFacil(msgId[2], emptyArgList);
theDisp.reqText (finalTextList[2], FALSE);
msgFacil(msgId[2]);
theDisp.reqText (finalTextList[2], FALSE);
msgFacil(msgId[3], MclArgList() << "IntegerAttribute" << 123);
theDisp.reqText (finalTextList[3], TRUE);
msgFacil(msgId[4], MclArgList() << "FloatAttribute" << 1.23456f);
theDisp.reqText (finalTextList[4], TRUE);
int iv[] = {1,2,3,4,5};
msgFacil(msgId[5], MclArgList() << MclMakeVec (iv, 5));
theDisp.reqText (finalTextList[5], TRUE);
float fv[] = {1.1F,2.2F,3.3F,4.4F,5.5F};
msgFacil(msgId[6], MclArgList() << MclMakeVec (fv, 5));
theDisp.reqText (finalTextList[6], TRUE);
const char* sv[] = {"str1", "st%r2", "~!@#$%^&*()_+`0-=[]{}\\|:;'\"<>,./?", "%1$d", "str5%"};
msgFacil(msgId[7], MclArgList() << MclMakeVec (sv, 5));
theDisp.reqText (finalTextList[7], TRUE);
msgFacil(msgId[8], MclArgList() << "execEmptyBom" << FALSE << TRUE);
theDisp.reqText (finalTextList[8], FALSE);
bool bv[] = {false, true, false};
msgFacil(msgId[9], MclArgList() << MclMakeVec (bv, 3));
theDisp.reqText (finalTextList[9], FALSE);
msgFacil (
msgId[10],
MclArgList() << msgFacil.findMsgFrag ("capacityFrag") << 412);
theDisp.reqText (finalTextList[10], FALSE);
msgFacil(msgId[11], MclArgList() << "FloatAttribute" << 3456.789f);
theDisp.reqText (finalTextList[11], TRUE);
// Test string,int format with any width, such as %-20s
msgFacil(msgId[12], MclArgList() << "This is a test" << 123);
//---------------------------------------------------------------------------
// Test findMsgUnit, findMsg, and findMsgFrag functions
//---------------------------------------------------------------------------
match (msgFacil.findMsgUnit (msgId[3])->id (), msgId[3]);
match (msgFacil.findMsg (msgId[4])->id (), msgId[4]);
match (msgFacil.findMsg (5) ->id (), msgId[5]);
match (
msgFacil.findMsgFrag ("capacityFrag")->text (),
"Capacity");
//---------------------------------------------------------------------------
// Test attribute set-by-Level functions.
//---------------------------------------------------------------------------
msgFacil.findMsg (msgId[8])->allowedToChange (FALSE);
msgFacil.maxTimesIssued (MclLevel::info (), 73);
msgFacil.displayExternalNumber (MclLevel::info (), FALSE);
msgFacil(msgId[1], MclArgList() << 123);
theDisp.reqText (finalTextList[1], TRUE);
msgFacil(msgId[2], emptyArgList);
theDisp.reqText ("Unrecognized attribute passed as parameter.\n", FALSE);
msgFacil(msgId[8], MclArgList() << "execEmptyBom" << FALSE << TRUE);
theDisp.reqText (finalTextList[8], FALSE);
//---------------------------------------------------------------------------
// Test boolean functions.
//---------------------------------------------------------------------------
new MclMsgFrag (msgFacil, "yesFrag", "Yes");
new MclMsgFrag (msgFacil, "noFrag", "No");
msgFacil.booleanMsgFrags (
msgFacil.findMsgFrag ("yesFrag"),
msgFacil.findMsgFrag ( "noFrag"));
match (msgFacil.booleanText (TRUE), "Yes");
msgFacil ("setBooleanAttrMsg", MclArgList () << "mandEC" << TRUE << FALSE);
theDisp.reqText ("TST0183I mandEC changed from Yes to No.\n", FALSE);
//---------------------------------------------------------------------------
// Test lineLength
//---------------------------------------------------------------------------
msgFacil.lineLength (24);
assert (msgFacil.lineLength () == 24);
msgFacil (msgId[3], MclArgList () << "latestPeriod" << 5432);
theDisp.reqText (
"TST0003S Value\n"
" specified was\n"
" 5432. Attribute\n"
" latestPeriod is\n"
" out of range.\n",
TRUE);
msgFacil.findMsg (3)->displayExternalNumber (FALSE);
msgFacil (msgId[3], MclArgList () << "latestPeriod" << 5432);
theDisp.reqText (
"Value specified was\n"
"5432. Attribute\n"
"latestPeriod is out of\n"
"range.\n",
TRUE);
msgFacil.lineLength (80);
//---------------------------------------------------------------------------
// Test deletingMsgUnits.
//---------------------------------------------------------------------------
assert (! msgFacil.deletingMsgUnits ());
//---------------------------------------------------------------------------
// Test co-existence of Facilities.
//---------------------------------------------------------------------------
MclFacility mfb ("MFB", theDisp);
new MclTestMsg (mfb, msgId[4], MclLevel::severe (), formatList[1], 27);
mfb (msgId[4], MclArgList() << 8765);
theDisp.reqText (
"MFB0027S Memory allocation error "
"when attempting to obtain 8765 bytes of memory.\n",
TRUE);
//---------------------------------------------------------------------------
// Test minErrOutLevel.
//---------------------------------------------------------------------------
msgFacil.minErrOutLevel (MclLevel::severe ());
assert (msgFacil.minErrOutLevel () == MclLevel::severe ());
msgFacil(msgId[0], MclArgList() << "Parameter.txt");
theDisp.reqText (finalTextList[0], FALSE);
msgFacil(msgId[1], MclArgList() << 123);
theDisp.reqText (finalTextList[1], FALSE);
msgFacil.findMsg (2)->displayExternalNumber (TRUE);
msgFacil(msgId[2], emptyArgList);
theDisp.reqText (finalTextList[2], FALSE);
msgFacil.findMsg (3)->displayExternalNumber (TRUE);
msgFacil(msgId[3], MclArgList() << "IntegerAttribute" << 123);
theDisp.reqText (finalTextList[3], TRUE);
msgFacil(msgId[4], MclArgList() << "FloatAttribute" << 1.23456f);
theDisp.reqText (finalTextList[4], TRUE);
}
//-----------------------------------------------------------------------------
void MclTester::testingMessage (const char * msg)
{
std::cout <<std::endl <<"************************************************"
<<std::endl <<msg <<std::endl;
}
//-----------------------------------------------------------------------------
std::string MclTester::valueText (
const MclArg & theArg,
const MclMsg * theMsg)
const
{
std::string theText;
theArg.getValueText (theText, theMsg);
return theText;
}
//-----------------------------------------------------------------------------
void MclTester::match (const char * charStar1, const char * charStar2)
{
assert (std::string (charStar1) == charStar2);
}
//-----------------------------------------------------------------------------
// Implementation of class TestOutputDisplayer
//-----------------------------------------------------------------------------
MclTestOutputDisplayer::MclTestOutputDisplayer ():
MclOutputDisplayer (),
outputText_ (),
outputErrorText_ ()
{
}
//-----------------------------------------------------------------------------
MclTestOutputDisplayer::~MclTestOutputDisplayer ()
{
}
//-----------------------------------------------------------------------------
void MclTestOutputDisplayer::output (const char * finalText)
{
std::cout <<
"\n"
"------\n"
"Output\n"
"------\n"
"" << finalText << std::flush;
outputText_ = finalText;
outputErrorText_ = "";
}
//-----------------------------------------------------------------------------
void MclTestOutputDisplayer::outputError (const char * finalText)
{
std::cerr <<
"\n"
"------------\n"
"Error Output\n"
"------------\n"
"" << finalText << std::flush;
outputErrorText_ = finalText;
}
//-----------------------------------------------------------------------------
void MclTestOutputDisplayer::reqText (
const char * theText,
MclBoolean isErrorText)
{
testText ("outputText_", outputText_, theText);
testText ("outputErrorText_", outputErrorText_, (isErrorText? theText: ""));
}
//-----------------------------------------------------------------------------
void MclTestOutputDisplayer::testText (
const char * textName,
const std::string & actualText,
const char * expectedText)
{
if (actualText != expectedText)
{
std::cerr <<
"\n\n"
"MCL UNIT TEST ERROR:\n\n"
" Unexpected value in " << textName << ".\n\n"
" " << textName << " actual contents:\n"
"----->\n" << actualText.c_str() << "<-----\n\n"
" " << textName << " expected contents:\n"
"----->\n" << expectedText << "<-----\n";
MclFacility::abortMcl ();
}
}
//-----------------------------------------------------------------------------
// Implementation of class TestMsg
//-----------------------------------------------------------------------------
MclTestMsg::MclTestMsg (
MclFacility & theFacility,
const char * msgId,
const MclLevel & theLevel,
const char * format,
int externalNumber):
MclMsg (theFacility, msgId, theLevel, format, externalNumber)
{
}
//-----------------------------------------------------------------------------
MclTestMsg::~MclTestMsg ()
{
}
//-----------------------------------------------------------------------------
void MclTestMsg::postIssue ()
{
if (myLevel () < MclLevel::error ())
return;
std::cerr <<
"\n\n"
"The above message was of severity level \"error\" or higher.\n"
"However, since this is only an MCL unit test, "
"the program will continue.\n\n";
}
|
C
|
#include<stdio.h>
int main()
{ int n,year;
printf("enter the months");
scanf("%d",&n);
printf("enter the year");
scanf("%d",&year);
switch(n)
{case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:printf("no.of days is 31");
break;
case 2:if(year%400==0)
{ printf("display 28 days");}
else if(year%100==0)
{printf("display 29 days");}
else if(year%4==0)
{ printf("display 28 days");}
else
{printf("display 29 days");}
break;
default:printf("no.of days is 30");
break;
}
}
|
C
|
/** Triggers the options for the different game states.
* This option also invokes the get up behavior after a fall, as this is needed in most game states.
*/
option(HandleGameState)
{
/** As game state changes are discrete external events and all states are independent of each other,
a common transition can be used here. */
float angle_temp=0;
static int flag=0;
common_transition
{
//OUTPUT_TEXT("HandleGameState_common_transition");
if(theGameInfo.state == STATE_INITIAL)
{
//OUTPUT_TEXT("HandleGameState_STATE_INITIAL");
goto initial;
}
if(theGameInfo.state == STATE_FINISHED)
{
//OUTPUT_TEXT("HandleGameState_STATE_FINISHED");
goto finished;
}
if(theFallDownState.state == FallDownState::fallen)
{
//OUTPUT_TEXT("HandleGameState_FallDownState::fallen");
flag=1;
goto getUp;
}
if(theGameInfo.state == STATE_READY)
{
//OUTPUT_TEXT("HandleGameState_STATE_READY");
flag=0;
goto ready;
}
if(theGameInfo.state == STATE_SET)
{
//OUTPUT_TEXT("HandleGameState_STATE_SET");
flag=0;
goto set;
}
if(theGameInfo.state == STATE_PLAYING)
{
if(theGameInfo.setPlay == SET_PLAY_PUSHING_FREE_KICK||theGameInfo.setPlay == SET_PLAY_GOAL_FREE_KICK)
{
flag=1;
if(theGameInfo.kickingTeam != theOwnTeamInfo.teamNumber)
goto pushingfree;
else{
goto secondPlaying;
}
}
else if(flag==0)
goto playing;
else if(flag==1)
goto secondPlaying;
}
if(theGameInfo.gamePhase==GAME_PHASE_PENALTYSHOOT){
flag=0;
goto penltyKick;
}
}
/** Stand still and wait. */
initial_state(initial)
{
action
{
// OUTPUT_TEXT("HandleGameState_initial_action");
SetHeadPanTilt(0.f, 0.f, 150_deg);
HeadControlMode(HeadControl::none);
SpecialAction(SpecialActionRequest::standHigh);
}
}
/** Stand still and wait. If somebody wants to implement cheering moves => This is the place. ;-) */
state(finished)
{
action
{
if(theRobotInfo.number == 2)
finishedState(2);
if(theRobotInfo.number == 5)
finishedState(5);
}
}
state(afterFinished)
{
transition
{
if(state_time>100)
goto initial;
}
action
{
LookForward();
Stand();
}
}
/** Get up from the carpet. */
state(getUp)
{
action
{
flag=1;
GetUp();
}
}
/** Walk to kickoff position. */
state(ready)
{
action
{
if(theRobotInfo.number == 2)
Ready(2);
if(theRobotInfo.number == 5)
Ready(5);
}
}
/** Stand and look around. */
state(set)
{
action
{
if(theControlParameter.Ball_Seen_flag)
HeadPanTurn(theControlParameter.Ball_RobotPose.angle(),12_deg);
else
HeadScan(45_deg,10_deg);
OUTPUT_TEXT("set");
Stand();
}
}
/** Play soccer! */
state(playing)
{
action
{
if(theRobotInfo.number == 2) Striker2();
if(theRobotInfo.number == 5)Striker5();
//test1();
//penltyKick();
//pushingfreeKick();
}
}
state(secondPlaying){
action{
if(theRobotInfo.number == 2) Striker2_attack();
if(theRobotInfo.number == 5)Striker5_attack();
}
}
state(pushingfree){
action{
pushingfreeKick();
}
}
state(penltyKick){
action{
penltyKick();
}
}
}
option(pushingfreeKick,(int)(0)kind){
static Vector2f temp_pose_aw,temp_pose_df;
common_transition{
float temp_dis;
Vector2f temp_pose1;
Vector2f temp_pose2;
if(option_time>=40000&&kind==0)
goto end;
if(kind==0){
if(theControlParameter.Ball_Seen_flag)
temp_pose2=theControlParameter.Ball_GlobalPoseEs;
else if(theRobotPose.translation.y()>0)
temp_pose2=Vector2f(3200,1100);
else
temp_pose2=Vector2f(3200,-1100);
}
else{
temp_pose2=theControlParameter.Ball_GlobalPoseEs;
}
if(theControlParameter.Ball_Seen_flag)
HeadPanTurn(theControlParameter.Ball_RobotPose.angle());
else
HeadScan(20_deg);
temp_pose1.x()=theRobotPose.translation.x()-temp_pose2.x();
temp_pose1.y()=theRobotPose.translation.y()-temp_pose2.y();
temp_dis=temp_pose1.norm();
temp_pose1.x()=(temp_pose1.x()/temp_dis)*800+temp_pose2.x();
temp_pose1.y()=(temp_pose1.y()/temp_dis)*800+temp_pose2.y();
temp_pose_aw=Transformation::fieldToRobot(theRobotPose,temp_pose1);
temp_pose1.x()=-4500-temp_pose2.x();
temp_pose1.y()=0-temp_pose2.y();
temp_dis=temp_pose1.norm();
temp_pose1.x()=(temp_pose1.x()/temp_dis)*800+temp_pose2.x();
temp_pose1.y()=(temp_pose1.y()/temp_dis)*800+temp_pose2.y();
temp_pose_df=Transformation::fieldToRobot(theRobotPose,temp_pose1);
if(theControlParameter.Ball_RobotPose.norm()<800)
goto farAway;
else
goto defense;
}
initial_state(start){
transition{
float temp_dis;
Vector2f temp_pose1;
Vector2f temp_pose2;
if(option_time>=40000&&kind==0)
goto end;
if(kind==0){
if(theControlParameter.Ball_Seen_flag)
temp_pose2=theControlParameter.Ball_GlobalPoseEs;
else if(theRobotPose.translation.y()>0)
temp_pose2=Vector2f(3200,1100);
else
temp_pose2=Vector2f(3200,-1100);
}
else{
temp_pose2=theControlParameter.Ball_GlobalPoseEs;
}
if(theControlParameter.Ball_Seen_flag)
HeadPanTurn(theControlParameter.Ball_RobotPose.angle());
else
HeadScan(20_deg);
temp_pose1.x()=theRobotPose.translation.x()-temp_pose2.x();
temp_pose1.y()=theRobotPose.translation.y()-temp_pose2.y();
temp_dis=temp_pose1.norm();
temp_pose1.x()=(temp_pose1.x()/temp_dis)*800+temp_pose2.x();
temp_pose1.y()=(temp_pose1.y()/temp_dis)*800+temp_pose2.y();
temp_pose_aw=Transformation::fieldToRobot(theRobotPose,temp_pose1);
temp_pose1.x()=-4500-temp_pose2.x();
temp_pose1.y()=0-temp_pose2.y();
temp_dis=temp_pose1.norm();
temp_pose1.x()=(temp_pose1.x()/temp_dis)*800+temp_pose2.x();
temp_pose1.y()=(temp_pose1.y()/temp_dis)*800+temp_pose2.y();
temp_pose_df=Transformation::fieldToRobot(theRobotPose,temp_pose1);
if(theControlParameter.Ball_RobotPose.norm()<800)
goto farAway;
else
goto defense;
}
}
state(farAway){
action{
WalkToTarget(Pose2f(MOVE_ROTATION_SPEED,MOVE_X_SPEED,MOVE_Y_SPEED),Pose2f(theControlParameter.Ball_RobotPose.angle(),temp_pose_aw));
}
}
state(defense){
action{
WalkToTarget(Pose2f(MOVE_ROTATION_SPEED,MOVE_X_SPEED,MOVE_Y_SPEED),Pose2f(theControlParameter.Ball_RobotPose.angle(),temp_pose_df));
}
}
target_state(end){
OUTPUT_TEXT("dianqiu end");
goto start;
}
}
option(penltyKick){
static Vector2f goal_pose;
initial_state(start){
transition{
if(state_time>2000)
goto walkToBAll;
}
action{
goal_pose=theControlParameter.PosChange(2,Vector2f(0,0),Vector2f(0,0));
}
}
state(walkToBAll){
transition{
if(action_done)
goto Kick;
}
action{
HeadPanTurn(theControlParameter.Ball_RobotPose.angle());
WalkToBall(goal_pose);
}
}
state(Kick){
transition{
if(action_done)
goto end;
}
action{
kick(3);
}
}
target_state(end){
transition{
if(state_time>100)
goto start;
}
action{
OUTPUT_TEXT("kick:::::endp");
}
}
}
|
C
|
#include "config.h"
#define MSG_BUFFER_SIZE (50)
char *msg = (char *)malloc(MSG_BUFFER_SIZE);
enum Status
{
ON,
OFF,
UNKNOWN
};
Status stat = OFF;
unsigned long lastMsg = 0;
unsigned long lastReading = 0;
unsigned long started = 0;
unsigned long duration = 0;
void setupOutputs()
{
pinMode(digitalOutputPin1, OUTPUT);
digitalWrite(digitalOutputPin1, HIGH); // inversed polarity STOP
}
void pumpOn(int timeDuration)
{
stat = ON;
snprintf(msg, MSG_BUFFER_SIZE, "PUMP TURNED ON FOR %d seconds!!", timeDuration);
Serial.println(msg);
started = millis();
duration = timeDuration * 1000;
digitalWrite(digitalOutputPin1, LOW); // IRRIGATE
}
void pumpOff()
{
stat = OFF;
Serial.println("PUMP TURNED OFF!!");
digitalWrite(digitalOutputPin1, HIGH); // STOP
}
|
C
|
#include "varray.h"
#include <ctype.h>
void varray_init(varray * v, unsigned int minsize) {
if ( minsize < 8 ) minsize = 8;
v->capacity = minsize;
v->array = (int*) malloc(sizeof(int) * v->capacity);
v->size = 0;
}
void varray_free(varray * v) {
free(v->array);
v->capacity = 0;
v->size = 0;
}
int varray_capacity(varray * v) {
return v->capacity;
}
int varray_size(varray * v) {
return v->size;
}
void varray_reallocate(varray * v) {
unsigned int newcapa = 8;
while ( newcapa <= v->capacity ) {
newcapa <<= 1;
}
int * newarray = (int*)malloc(sizeof(int)*newcapa);
v->capacity = newcapa;
for(int i = 0; i < v->size; ++i) {
newarray[i] = v->array[i];
}
free(v->array);
v->array = newarray;
}
int varray_at(varray * v, unsigned int i) {
return v->array[i];
}
int varray_back(varray * v) {
return v->array[v->size - 1];
}
void varray_pushback(varray * v, int d) {
if ( !(v->size < v->capacity) ) {
varray_reallocate(v);
}
v->array[v->size] = d;
v->size += 1;
}
int varray_strscan(varray * v, char * ptr) {
int cnt = 0;
while ( *ptr != 0 ) {
//printf("'%s'\n", ptr);
while ( !isdigit(*ptr) && *ptr != '-' && *ptr != 0 ) { ++ptr; }
if ( *ptr == 0 )
break;
long val = strtol(ptr, &ptr, 10);
//printf("%ld, '%s'\n", val, ptr);
varray_pushback(v, val);
++cnt;
}
return cnt;
}
|
C
|
void printPatients(int client_connection_fd){
PatientList* current = head;
while(current != NULL) {
write(client_connection_fd, &(current->patient), sizeof(Patient));
current = current->next;
}
char endString[10];
strcpy(endString, "end");
write(client_connection_fd, &endString, sizeof(endString));
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* cursoractions.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ysalaun <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/13 23:19:50 by ysalaun #+# #+# */
/* Updated: 2018/04/16 11:58:18 by ysalaun ### ########.fr */
/* */
/* ************************************************************************** */
#include "../vingtetunsh.h"
void go_home(t_line *line)
{
size_t i;
struct winsize ws;
ioctl(0, TIOCGWINSZ, &ws);
i = 0;
if (ft_strlen(line->line) < (ws.ws_row - 1) * (ws.ws_col - 1))
{
while (i < line->count)
{
ft_putstr_fd(tgetstr("le", NULL), 0);
i++;
}
line->count = 0;
}
}
void go_end(t_line *line)
{
struct winsize ws;
ioctl(0, TIOCGWINSZ, &ws);
if (ft_strlen(line->line) < (ws.ws_row - 1) * (ws.ws_col - 1))
{
while (line->count != ft_strlen(line->line))
going_right(line);
}
}
void opt_right(t_line *line)
{
struct winsize ws;
ioctl(0, TIOCGWINSZ, &ws);
if (ft_strlen(line->line) < (ws.ws_row - 1) * (ws.ws_col - 1))
{
while (line->count < ft_strlen(line->line) &&
line->line[line->count] == ' ')
going_right(line);
while (line->count < ft_strlen(line->line) &&
line->line[line->count] != ' ')
going_right(line);
}
}
void opt_left(t_line *line)
{
struct winsize ws;
ioctl(0, TIOCGWINSZ, &ws);
if (ft_strlen(line->line) < (ws.ws_row - 1) * (ws.ws_col - 1))
{
while (line->count > 0 && line->line[line->count - 1] == ' ')
{
ft_putstr_fd(tgetstr("le", NULL), 0);
line->count--;
}
while (line->count > 0 && line->line[line->count - 1] != ' ')
{
ft_putstr_fd(tgetstr("le", NULL), 0);
line->count--;
}
}
}
void curs_right(t_line *line)
{
if (line->line)
{
if (line->count < ft_strlen(line->line))
going_right(line);
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "dictionary.h"
void print_list(VNode *head){
VNode *cur = head;
while(cur){
printf("%s ", cur->value);
cur = cur->next;
}
printf("\n");
}
int compare(const void *l1, const void *l2) {
return *(char*)l1 - *(char*)l2;
}
int main (int argc, char ** argv) {
/*
DNode* result;
//either static or use calloc - to set all bytes initially to 0
static DNode* dictionary [DEFAULT_HASH_SIZE];
set(dictionary, DEFAULT_HASH_SIZE, "pore", "repo");
set(dictionary, DEFAULT_HASH_SIZE, "pore", "rope");
result = get (dictionary, DEFAULT_HASH_SIZE, "pore");
if (result != NULL) {
printf("Anagrams for 'pore':\n");
print_list (result->values);
}
else
printf ("'pore' not found\n");
set(dictionary, DEFAULT_HASH_SIZE, "bore", "robe");
result = get (dictionary, DEFAULT_HASH_SIZE, "bore");
if (result != NULL) {
printf("Anagrams for 'bore':\n");
print_list (result->values);
}
else
printf ("'bore' not found\n");
free_dictionary(dictionary, DEFAULT_HASH_SIZE);*/
DNode* result;
static DNode* dictionary [DEFAULT_HASH_SIZE];
FILE *f = fopen("words.txt", "r");
char buffer[25];
while (fscanf(f, "%s", buffer) != EOF) {
char* word = copystr(buffer);
qsort(word, strlen(word), sizeof(char), compare);
set(dictionary, DEFAULT_HASH_SIZE, word, buffer);
free(word);
}
int total = 0;
for (int i = 0; i < DEFAULT_HASH_SIZE; i++) {
if (dictionary[i] != NULL) {
result = get(dictionary, DEFAULT_HASH_SIZE, dictionary[i]->key);
VNode* head = (result->values)->next;
if (head) {
printf("%s\n", (result->values)->value);
while (head) {
printf("%s\n\n", head->value);
head = head->next;
}
total++;
}
}
}
printf("%d\n", total);
free_dictionary(dictionary, DEFAULT_HASH_SIZE);
return 0;
}
|
C
|
#include "../../../inc/mh_collection.h"
typedef struct mh_array {
mh_collection_t collection;
mh_ref_t ptr;
size_t size;
size_t element_size;
mh_context_t *context;
} mh_array_t;
typedef struct mh_array_iterator {
mh_iterator_t iterator;
size_t position;
mh_array_t *array;
} mh_array_iterator_t;
static mh_memory_t mh_array_iterator_current(mh_iterator_t *iterator) {
MH_THIS(mh_array_iterator_t*, iterator);
if (this->array->size <= this->array->element_size * this->position) {
return MH_MEM_NULL;
}
return mh_memory_reference((char *) this->array->ptr + (this->array->element_size * this->position),
this->array->element_size);
}
static bool mh_array_iterator_start(mh_iterator_t *iterator) {
MH_THIS(mh_array_iterator_t*, iterator);
if (this->array->size < this->array->element_size) {
return false;
}
this->position = 0;
return true;
}
static bool mh_array_iterator_next(mh_iterator_t *iterator) {
MH_THIS(mh_array_iterator_t*, iterator);
if (this->array->size <= this->array->element_size * (this->position + 1)) {
return false;
}
this->position++;
return true;
}
static mh_iterator_t *mh_array_get_iterator(mh_collection_t *collection) {
MH_THIS(mh_array_t*, collection);
mh_array_iterator_t *it = mh_context_allocate(this->context, sizeof(mh_array_iterator_t), false).ptr;
*it = (mh_array_iterator_t) {
.array = this,
.position = 0,
.iterator = {
.current = mh_array_iterator_current,
.next = mh_array_iterator_next,
.start = mh_array_iterator_start
}
};
return &it->iterator;
}
mh_collection_t *mh_array_new(mh_context_t *context, mh_ref_t array, size_t size, size_t element_size) {
MH_THIS(mh_array_t*, mh_context_allocate(context, sizeof(mh_array_t), false).ptr);
*this = (mh_array_t) {
.element_size = element_size,
.size = size,
.ptr = array,
.context = context,
.collection = {
.get_iterator = mh_array_get_iterator,
.destructor = {NULL}
}};
return &this->collection;
}
|
C
|
//how to insert all element of array into another array
#include<stdio.h>
void main()
{
int i,m,n,loc;
printf("Enter size of array a: ");
scanf("%d",&m);
int a[m];
for(i=0;i<m;i++)
{
printf("Enter a[%d]: ",i);
scanf("%d",&a[i]);
}
printf("Enter size of array b: ");
scanf("%d",&n);
int b[n];
for(i=0;i<n;i++)
{
printf("Enter b[%d]: ",i);
scanf("%d",&b[i]);
}
printf("Enter location to insert: ");
scanf("%d",&loc);
for(i=m-1;i>=loc;i--)
{
a[i+n]=a[i];
}
for(i=0;i<n;i++)
{
a[loc+i]=b[i];
}
for(i=0;i<n+m;i++)
{
printf(" a[%d]: %d\n ",i,a[i]);
}
}
|
C
|
#define _XOPEN_SOURCE 600
#ifndef _UT_COMMON_H_
#define _UT_COMMON_H_
/**
* ut Private API
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <ucontext.h>
#include "list.h"
#define MAX_TIME_SEC 99999
#define MAX_TIME_USEC 99999
#define UT_TCB_NAMELEN 100
#define STKSIZE (64*1024)
#define ut_tcb_set_name(tcb_name, name) strcpy(tcb_name, name)
#define UT_DEBUG
#ifndef UT_DEBUG
#define ut_debug(msg)
#else
#define ut_debug(msg) ut_debug_msg(msg)
#endif
static inline void ut_debug_msg(char *msg){
printf("%s\n",msg);
}
typedef struct list_head queue_st;
typedef queue_st *queue_t; // queue head
typedef queue_st *queue_ele; // queue element
typedef struct timeval ut_time_t;
typedef enum ut_state_en {
UT_STATE_SCHEDULER = 0,
UT_STATE_NEW,
UT_STATE_READY,
UT_STATE_DEAD
}ut_state_t;
/* user thread control block structure */
typedef struct ut_tcb_st{
ut_state_t state;
char name[UT_TCB_NAMELEN];
/* queues */
queue_st new_q; // new queue
queue_st ready_q; // ready queue
queue_st dead_q; // dead queue
/* timing */
ut_time_t spawned;
ut_time_t lastran;
ut_time_t running;
/* ucontext */
ucontext_t uctx;
char* stack;
void (*start_func)(void );
void *start_arg;
} *ut_tcb_t;
#define __gettimeofday(t) gettimeofday(t, NULL)
#define UT_TIME_NOW (ut_time_t *)(0)
#define ut_time_set(t1,t2) \
do { \
if ((t2) == UT_TIME_NOW) \
__gettimeofday((t1)); \
else { \
(t1)->tv_sec = (t2)->tv_sec; \
(t1)->tv_usec = (t2)->tv_usec; \
} \
} while (0)
#define ut_time_sub(t1,t2) \
(t1)->tv_sec -= (t2)->tv_sec; \
(t1)->tv_usec -= (t2)->tv_usec; \
if ((t1)->tv_usec < 0) { \
(t1)->tv_sec -= 1; \
(t1)->tv_usec += 1000000; \
}
/* t1 = t1 + t2 */
#define ut_time_add(t1,t2) \
(t1)->tv_sec += (t2)->tv_sec; \
(t1)->tv_usec += (t2)->tv_usec; \
if ((t1)->tv_usec > 1000000) { \
(t1)->tv_sec += 1; \
(t1)->tv_usec -= 1000000; \
}
/* time value constructor */
static inline ut_time_t ut_time(long sec, long usec)
{
ut_time_t tv;
tv.tv_sec = sec;
tv.tv_usec = usec;
return tv;
}
/* convert a time structure into a double value */
static inline double ut_time_t2d(ut_time_t *t)
{
double d;
d = ((double)t->tv_sec*1000000 + (double)t->tv_usec) / 1000000;
return d;
}
#endif
|
C
|
#include <stdio.h>
float o_to_c(int o);
int main(void){
int o;
float c;
printf("IX͂ĂF");
scanf("%d", &o);
c = o_to_c(o);
printf("%d IX%f Jbvł",o,c);
return 0;
}
float o_to_c(int o){
return o / 8.0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
main()
{
int a[2][2],i,j;
clrscr();
printf("enter elements into array:\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("the elements in the array are:\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
getch();
}
|
C
|
struct neuron
{
vector<double> weights;
double activation=1;
neuron() {}
neuron(int n) //n = number of dendrites
{
weights.resize(n);
assign_random_wts();
}
void create(int n)
{
weights.resize(n);
assign_random_wts();
}
void assign_random_wts()
{
for(int i =0 ; i < weights.size() ; i++)
{
weights[i] = 100 - rand()%200;
}
}
void assign_wts(double wts[])
{
for(int i = 0 ; i < weights.size(); i++)
{
weights[i] = wts[i];
}
}
};
struct neural_layer
{
vector<neuron> neurons;
neural_layer(int m,int n) // m = number of neurons in current layer, n = dendrites per neuron
{
neurons.resize(m+1); // one more neuron for the bias
for(int i = 0 ; i < m+1 ; i++)
{
neurons[i].create(n);
}
}
};
struct neural_network
{
vector <neural_layer> layers;
void add_layer(int m)
{
if(!layers.size())
{
layers.push_back(neural_layer(m,0));
}
else
{
layers.push_back(neural_layer(m,layers[layers.size()-1].neurons.size()));
}
}
void req_inp()
{
cout<<"Please give "<<layers[0].neurons.size()-1<<" inputs (parameters) to the Network ( 0 or 1)\n";
for(int i = 1 ; i < layers[0].neurons.size(); i++)
{
// cout<<"Enter the "<<i<<" parameter (input)\n";
cin>>layers[0].neurons[i].activation;
//cout<<" 0 "<<i<<" = "<<layers[0].neurons[i].activation<<endl;
}
}
void input(double params[])
{
for(int i = 1 ; i < layers[0].neurons.size(); i++)
{
// cout<<"Enter the "<<i<<" parameter (input)\n";
layers[0].neurons[i].activation = params[i];
//cout<<" 0 "<<i<<" = "<<layers[0].neurons[i].activation<<endl;
}
}
double sigmoid(double val)
{
return (1/(1+exp(-val)));
}
void forward_prop()
{
for(int i = 1 ; i < layers.size(); i++) // for each layer
{
for(int j = 1 ; j < layers[i].neurons.size(); j++) // for each neuron in this layer (ignoring the bias)
{
double accum = 0;
for(int k = 0 ; k < layers[i].neurons[j].weights.size(); k++) // for each neuron it is connected to in the previous layer
{
accum += layers[i].neurons[j].weights[k] * layers[i-1].neurons[k].activation;
}
layers[i].neurons[j].activation = sigmoid(accum);
// cout<<"For layer "<<i+1<<" , neuron "<<j+1<<" has activation : "<<round(layers[i].neurons[j].activation)<<" sigmoid("<<accum<<")"<<endl;
}
}
}
vector<int> output()
{
// cout<<"The final layer of the neural network is .... \n";
vector<int> res;
for(int i = 1 ; i < layers[layers.size()-1].neurons.size() ; i++)
{
//cout<<round(layers[layers.size()-1].neurons[i].activation)<<" ";
res.push_back(round(layers[layers.size()-1].neurons[i].activation));
}
//cout<<endl;
// cout<<"\n\n";
return res;
}
};
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define SIZE 5
int main()
{
int i;
int A[SIZE];
int *ptr;
ptr=(int *)malloc(SIZE*sizeof(int));
printf("Enter %d elements:\n",SIZE);
for(i=0;i<SIZE;i++)
{
scanf("%d",(ptr+i));
}
printf("Elements Are:\n");
for(i=0;i<SIZE;i++)
{
printf("%d\t",*(ptr+i));
}
free(ptr);
return 0;
}
|
C
|
给定一个文档 (Unix-style) 的完全路径,请进行路径简化。
例如,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
边界情况:
你是否考虑了 路径 = "/../" 的情况?
在这种情况下,你需返回 "/" 。
此外,路径中也可能包含多个斜杠 '/' ,如 "/home//foo/" 。
在这种情况下,你可忽略多余的斜杠,返回 "/home/foo" 。
//2018-12-27
//2018-12-28 "/EQnvK///U/./../LQnJc/./rI/Ckzz/lmO/./"
//2018-12-29 "/...", "/.", "/.."
char* simplifyPath(char* path) {
typedef struct stack
{
char character[1000];
int top;
}stack;
char *newpath;
int i = 0;
int dotcount = 0;
stack *s1 = (stack *)malloc(sizeof(stack));
memset(s1,0,sizeof(stack));
if(path[0]=='\0')
{
return NULL;
}
while(path[i]!='\0')
{
switch(path[i])
{
case '/':
if(dotcount==1&&s1->character[s1->top-1]=='.')
{
dotcount = 0;
s1->top-=1;
if(s1->character[s1->top-1]!='/')
{
s1->character[s1->top]=path[i];
s1->top++;
i++;
break;
}
else
{
i++;
break;
}
}
else if(dotcount==2&&s1->character[s1->top-1]=='.')
{
dotcount = 0;
s1->top-=2;
if(s1->top==1&&s1->character[s1->top-1]=='/')
{
i++;
break;
}
s1->top-=1;
while(s1->top>0&&s1->character[s1->top-1]!='/')
{
s1->top--;
}
if(s1->character[s1->top-1]!='/')
{
s1->character[s1->top]=path[i];
s1->top++;
i++;
break;
}
else
{
i++;
break;
}
}
else
{
if(s1->top>0)
{
if(s1->character[s1->top-1]=='/')
{
i++;
break;
}
}
s1->character[s1->top]=path[i];
s1->top++;
i++;
break;
}
case '.':
dotcount++;
//i++;顺序错误
s1->character[s1->top]=path[i];
i++;
s1->top++;
break;
default:
dotcount=0;
s1->character[s1->top]=path[i];
s1->top++;
i++;
break;
}
}
if(s1->top>1)
{
if(dotcount==2&&s1->character[s1->top-1]=='.')
{
dotcount=0;
s1->top-=2;
if(s1->top>1&&s1->character[s1->top-1]=='/')
{
s1->top-=1;
while(s1->top>0&&s1->character[s1->top-1]!='/')
{
s1->top--;
}
}
}
if(dotcount==1&&s1->character[s1->top-1]=='.')
{
dotcount=0;
s1->top-=1;
}
if(s1->top>1&&s1->character[s1->top-1]=='/')
{
s1->top--;
}
}
newpath = (char *)malloc(sizeof(char)*(s1->top+20));//多分配字节留给结束符
strncpy(newpath,s1->character,s1->top);//拷贝不带结束符的字符串
newpath[s1->top]='\0';//手动添加结束符
return newpath;
}
int main()
{
//char *p ="/";典型错误,指针存地址不存常量//"/EQnvK///U/./../LQnJc/./rI/Ckzz/lmO/./";
char p[]="/EQnvK///U/./../LQnJc/./rI/Ckzz/lmO/./";//"/";
char *path = simplifyPath(p);
printf("%sthe length is %d\n",path,strlen(path));
system("pause");
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* left;
struct Node* right;
};struct Node* root=NULL;
struct stacknode{
struct Node* t;
struct stacknode* link;
};struct stacknode* top=NULL;
struct Node* create(int element){
struct Node* newnode=(struct Node*)malloc(sizeof(struct Node));
newnode->data=element;
newnode->left= NULL;
newnode->right=NULL;
return newnode;
}
struct Node* insert(struct Node* root, int element){
struct Node* temp=(struct Node*)malloc(sizeof(struct Node));
temp=create(element);
if(root==NULL){
return create(element);
}
struct Node* current=root;
struct Node* parent=NULL;
while(current){
parent=current;
if(element<current->data){
current=current->left;
}
else{
current=current->right;
}
}
if(element<parent-> data){
parent->left=temp;
}
else{
parent->right=temp;
}
return root;
}
void push(struct stacknode** top_ref,struct Node* t);
struct Node* pop(struct stacknode** top_ref);
int isEmpty(struct stacknode* top);
void traverse(struct Node* root);
int isEmpty(struct stacknode* top){
return (top==NULL)?1:0;
}
void inOrder(struct Node* root){
struct Node* current=root;
struct stacknode* s=NULL;
while(1){
while(current){
push(&s,current);
current=current->left;
}
if(isEmpty(s))
break;
current=pop(&s);
printf("%d->" ,current->data);
current=current->right;
}
}
void preOrder(struct Node* root){
struct Node* current=root;
struct stacknode* s=NULL;
while(1){
while(current){
push(&s,current);
printf("%d->",current->data);
current=current->left;
}
if(isEmpty(s))
break;
current=pop(&s);
if(current->left==NULL && current->right==NULL)
if(isEmpty(s))
break;
current=pop(&s);
current=current->right;
}
}
void postOrder(struct Node* root){
struct Node* current=root;
struct stacknode* s=NULL;
struct Node* temp=NULL;
while(1){
while(current){
push(&s,current);
current=current->left;
}
if(isEmpty(s))
break;
current=pop(&s);
printf("%d->",current->data);
if(temp)
printf("%d->",temp->data);
if(current->left==NULL && current->right==NULL)
if(isEmpty(s))
break;
if(current->right!=NULL){
current=current->right;
}
else{
current=pop(&s);
temp=current;
}
current=current->right;
}
}
void push(struct stacknode** top_ref,struct Node* t){
struct stacknode* temp;
temp=(struct stacknode*)malloc(sizeof(struct stacknode));
temp->t=t;
temp->link=(*top_ref);
(*top_ref)=temp;
}
struct Node* pop(struct stacknode** top_ref){
struct Node*res;
struct stacknode* top;
if(isEmpty(*top_ref))
{
printf("Stack Underflow \n");
getchar();
exit(0);
}
else{
top=*top_ref;
res=top->t;
*top_ref=top->link;
free(top);
return res;
}
}
void traverse(struct Node* root){
while (root) {
printf("%d\n",root->data );
root=root->left;
}
}
int main(){
root=insert(root,20);
insert(root,15);
insert(root,10);
insert(root,18);
insert(root,5);
insert(root,12);
insert(root,25);
insert(root,22);
insert(root,27);
traverse(root);
printf("\n _______In Order________\n\n");
inOrder(root);
printf("\n\n _______Pre Order________\n\n");
preOrder(root);
printf("\n\n _______Post Order________\n\n");
postOrder(root);
printf("\n");
return 0;
}
|
C
|
#include <leetcode.h>
bool canPlaceFlowers(int* flowerbed, int flowerbedSize, int n)
{
int i, j;
if (!n)
return true;
i = 0;
if (!flowerbed[i]) {
i++;
if (i < flowerbedSize) {
if (!flowerbed[i])
n--;
} else {
n--;
}
}
for (j = 0; i < flowerbedSize && n; i++) {
if (flowerbed[i]) {
if (j)
j = 0;
continue;
}
j++;
if (j >= 3) {
j = 1;
n--;
}
}
if (j >= 2 && n)
n--;
if (n)
return false;
return true;
}
void tc_0(void)
{
int flowerbed[] = {0};
int flowerbedSize = sizeof(flowerbed)/sizeof(*flowerbed);
printf("true\n%s\n\n",
canPlaceFlowers(flowerbed, flowerbedSize, 1) ?
"true" : "false");
}
void tc_1(void)
{
int flowerbed[] = {0,0};
int flowerbedSize = sizeof(flowerbed)/sizeof(*flowerbed);
printf("true\n%s\n\n",
canPlaceFlowers(flowerbed, flowerbedSize, 1) ?
"true" : "false");
}
void tc_2(void)
{
int flowerbed[] = {0,0,0};
int flowerbedSize = sizeof(flowerbed)/sizeof(*flowerbed);
printf("true\n%s\n\n",
canPlaceFlowers(flowerbed, flowerbedSize, 1) ?
"true" : "false");
}
void tc_3(void)
{
int flowerbed[] = {0,1};
int flowerbedSize = sizeof(flowerbed)/sizeof(*flowerbed);
printf("false\n%s\n\n",
canPlaceFlowers(flowerbed, flowerbedSize, 1) ?
"true" : "false");
}
void tc_4(void)
{
int flowerbed[] = {1,0};
int flowerbedSize = sizeof(flowerbed)/sizeof(*flowerbed);
printf("false\n%s\n\n",
canPlaceFlowers(flowerbed, flowerbedSize, 1) ?
"true" : "false");
}
void tc_5(void)
{
int flowerbed[] = {0,0,0};
int flowerbedSize = sizeof(flowerbed)/sizeof(*flowerbed);
printf("true\n%s\n\n",
canPlaceFlowers(flowerbed, flowerbedSize, 2) ?
"true" : "false");
}
void tc_6(void)
{
int flowerbed[] = {1,0,0,0,1};
int flowerbedSize = sizeof(flowerbed)/sizeof(*flowerbed);
printf("true\n%s\n\n",
canPlaceFlowers(flowerbed, flowerbedSize, 1) ?
"true" : "false");
}
void tc_7(void)
{
int flowerbed[] = {1,0,0,0,0,1};
int flowerbedSize = sizeof(flowerbed)/sizeof(*flowerbed);
printf("false\n%s\n\n",
canPlaceFlowers(flowerbed, flowerbedSize, 2) ?
"true" : "false");
}
int main(int argc, char *argv[])
{
tc_0();
tc_1();
tc_2();
tc_3();
tc_4();
tc_5();
tc_6();
tc_7();
return 0;
}
|
C
|
//α 7. ϴ Լ
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int print_leapYear(int year)
{
if (year % 4 == 0)
return year;
}
int main()
{
int year, count=0;
for (year = 2000; year < 2100; year += 4)
{
printf("%d ", print_leapYear(year));
count++;
if (count % 10 == 0)
printf("\n");
}
}
|
C
|
#include "main.h"
#include "menu.h"
#include "storage.h"
void testMenu()
{
consoleSelect(&topScreen);
consoleClear();
iprintf("Storage Check Test\n\n");
consoleSelect(&bottomScreen);
consoleClear();
int free = -1;
int size = -1;
//Home menu slots
{
iprintf("Free Home Menu Slots:\n"); swiWaitForVBlank();
free = getMenuSlotsFree();
iprintf("\t%d / ", free); swiWaitForVBlank();
size = getMenuSlots();
iprintf("%d\n", size); swiWaitForVBlank();
}
//SD Card
{
iprintf("\nFree SD Space:\n\t"); swiWaitForVBlank();
free = getSDCardFree();
printBytes(free);
iprintf(" / "); swiWaitForVBlank();
size = getSDCardSize();
printBytes(size);
iprintf("\n"); swiWaitForVBlank();
printf("\t%.0f / %.0f blocks\n", (float)free / BYTES_PER_BLOCK, (float)size / BYTES_PER_BLOCK);
}
//Emunand
{
iprintf("\nFree DSi Space:\n\t"); swiWaitForVBlank();
free = getDsiFree();
printBytes(free);
iprintf(" / "); swiWaitForVBlank();
size = getDsiSize();
printBytes(size);
iprintf("\n"); swiWaitForVBlank();
printf("\t%.0f / %.0f blocks\n", (float)free / BYTES_PER_BLOCK, (float)size / BYTES_PER_BLOCK);
}
//
iprintf("\nBack - B\n");
keyWait(KEY_B);
}
|
C
|
#pragma once
#include "Math/Math.h"
#include "Math/Vec.h"
#include "Math/Mat.h"
struct Quaternion {
union {
struct {
union {
struct {
float x;
float y;
float z;
};
Vec3f v;
};
float w;
};
float data[4];
};
Quaternion() : x(0), y(0), z(0), w(1) {};
Quaternion(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {};
};
// Alias so that we dont have to type "Quaternion" everytime we want to use them
// Qaut is easier, faster, less verbose to type
typedef Quaternion Quat;
Quat quat_from_axis_angle(const Vec3f& n, float deg);
Quat quat_conj(const Quat& q);
Quat quat_normalize(const Quat& q);
Quat quat_invert(const Quat& q);
Vec4f quat_to_vec(const Quat& q);
// Rotate around a local axis: rotation = rotation * quat_from_axis_angle(Vec3f_Up, angle)
// Rotate around a world axis : rotation = quat_from_axis_angle(Vec3f_Up, angle) * rotation;
Quat operator*(const Quat& q1, const Quat& q2);
Quat& operator*=(Quat& q1, const Quat& q2);
Vec3f operator*(const Quat& q, const Vec3f& pt);
Mat4x4f quat_to_rotation_matrix(const Quat& q);
Vec3f quat_to_euler(const Quat& q);
Quat euler_to_quat(const Vec3f& euler);
// TODO: implement slerp
|
C
|
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <assert.h>
#include <unistd.h>
#include <sys/sysinfo.h>
#include <pthread.h>
#include "list.h"
#include "times.h"
#include "sched_timer.h"
#include "logger.h"
#define TIMER_MAX_ARG 8
struct timer {
struct list_head list;
long long deadline;
timer_callback_t *callback;
int argc;
void *argv[TIMER_MAX_ARG];
};
static struct list_head timer_list;
static pthread_mutex_t timer_lock;
static pthread_t *task_vec = NULL;
static int task_nr = 0;
static int is_exit = 0;
static struct timer* timer_alloc()
{
struct timer *timer;
timer = malloc(sizeof(struct timer));
assert(timer != NULL);
memset(timer, 0, sizeof(struct timer));
return timer;
}
static void timer_free(struct timer *timer)
{
free(timer);
}
static void timer_add(struct timer *timer)
{
struct list_head *pos;
struct timer *tmp, *find = NULL;
INIT_LIST_HEAD(&timer->list);
pthread_mutex_lock(&timer_lock);
list_for_each_prev(pos, &timer_list) {
tmp = container_of(pos, struct timer, list);
if (timer->deadline >= tmp->deadline) {
find = tmp;
break;
}
}
if (find == NULL) {
list_add(&timer->list, &timer_list);
} else {
list_add(&timer->list, &find->list);
}
pthread_mutex_unlock(&timer_lock);
}
static void __timer_remove(struct timer *timer)
{
list_del(&timer->list);
}
static struct timer* __timer_peek()
{
if (list_empty(&timer_list)) {
return NULL;
} else {
return container_of(timer_list.next, struct timer, list);
}
}
static void* do_timer_fn(void *arg)
{
while (!is_exit) {
sched_yielded();
}
return NULL;
}
void sched_yielded()
{
struct timer *timer;
int n = 0;
while (1) {
pthread_mutex_lock(&timer_lock);
timer = __timer_peek();
if (timer == NULL || timer->deadline > nowus()) {
pthread_mutex_unlock(&timer_lock);
break;
} else {
__timer_remove(timer);
pthread_mutex_unlock(&timer_lock);
if (timer->callback) {
timer->callback(timer->argc, timer->argv);
}
timer_free(timer);
n++;
}
}
if (n <= 0) {
usleep(10 * 1000);
}
}
int sched_timer(long long usec, timer_callback_t *callback, ...)
{
struct timer *timer;
va_list ap;
void *arg;
int i = 0;
timer = timer_alloc();
timer->deadline = nowus() + usec;
timer->callback = callback;
va_start(ap, callback);
while (1) {
arg = va_arg(ap, void *);
if (arg == NULL) {
break;
}
if (i >= TIMER_MAX_ARG) {
assert(0 && "timer args over maxnum.\n");
}
timer->argv[i] = arg;
i++;
}
va_end(ap);
timer->argc = i;
timer_add(timer);
return 0;
}
void sched_sleep(long long usec)
{
usleep(usec);
}
int sched_timer_init()
{
int i;
is_exit = 0;
INIT_LIST_HEAD(&timer_list);
if (pthread_mutex_init(&timer_lock, NULL) != 0) {
assert(0 && "pthread_mutex_init error.\n");
}
task_nr = get_nprocs();
if (task_nr < 4) {
task_nr = 4;
};
if (task_nr > 0) {
task_vec = malloc(sizeof(pthread_t) * task_nr);
for (i = 0; i < task_nr; i++) {
if (pthread_create(&task_vec[i], NULL, do_timer_fn, NULL) != 0) {
assert(0 && "pthread_create error.\n");
}
}
}
return 0;
}
void sched_timer_exit()
{
int i;
is_exit = 1;
for (i = 0; i < task_nr; i++) {
pthread_join(task_vec[i], NULL);
}
pthread_mutex_destroy(&timer_lock);
free(task_vec);
task_vec = NULL;
}
|
C
|
/* Exercizer for gaussian integration package.
/**/
#include <math.h>
#include <stdio.h>
#include "Laguerre.h"
#include "Jacobi.h"
#include "Hermite.h"
#define N 8
#define k 5
#define FLOATk 5.0
#define ZERO 0.0
#define SqrtPI 1.77245385090551603
main()
{
short m;
double abscis[N];
double wt[N];
double left, right;
printf("Table 25.8, k= %1d, n=%1d\n\n", k, N);
Jacobi(N, FLOATk, ZERO, abscis, wt);
for (m=0; m<N; m++) wt[m] /= (k+1);
for (m=0; m<N; m++) printf("%2d %20.18g %20.18g\n", m, abscis[m], wt[m]);
getchar();
printf("\n\n\nTable 25.4, n=9\n\n");
Radau_Jacobi(4, -0.5, ZERO, abscis, wt, &left);
left *= 2;
for (m=0; m<4; m++) abscis[m]= sqrt(abscis[m]);
printf("%2d %20.18g %20.18g\n", 0, ZERO, left);
for (m=0; m<4; m++) printf("%2d %20.18g %20.18g\n", m, abscis[m], wt[m]);
getchar();
printf("\n\n\nTable 25.9, n= %1d\n\n", N);
Laguerre(N, ZERO, abscis, wt);
for (m=0; m<N; m++) printf("%2d %20.18g %20.18g\n", m, abscis[m], wt[m]);
getchar();
printf("\n\n\nTable 25.10, n= %1d\n\n", N);
Hermite(N, ZERO, abscis, wt);
for (m=0; m<N; m++) wt[m] *= SqrtPI;
for (m=0; m<N; m++) printf("%2d %20.18g %20.18g\n", m, abscis[m], wt[m]);
getchar();
printf("\n\n\nSame, n= %1d\n\n", 2*N);
Even_Hermite(2*N, ZERO, abscis, wt);
for (m=0; m<N; m++) wt[m] *= SqrtPI;
for (m=0; m<N; m++) printf("%2d %20.18g %20.18g\n", m, abscis[m], wt[m]);
getchar();
printf("\n\n\nSame, n= %1d\n\n", 9);
Odd_Hermite(9, ZERO, abscis, wt, &left);
left *= SqrtPI;
for (m=0; m<4; m++) wt[m] *= SqrtPI;
printf("%2d %20.18g %20.18g\n", 0, ZERO, left);
for (m=0; m<4; m++) printf("%2d %20.18g %20.18g\n", m, abscis[m], wt[m]);
getchar();
printf("\n\n\nTable 25.6, n= %1d\n\n", N+1);
Lobatto_Jacobi(N-1, ZERO, ZERO, abscis, wt, &left, &right);
for (m=0; m<(N-1); m++) wt[m] *= 2;
left *= 2; right *= 2;
for (m=0; m<(N-1); m++) abscis[m] = (2*abscis[m] - 1);
printf(" %20.18g %20.18g\n", -1.0, left);
for (m=0; m<(N-1); m++)
printf("%2d %20.18g %20.18g\n", m, abscis[m], wt[m]);
printf(" %20.18g %20.18g\n", 1.0, right);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int SLDataType;
struct ListNode
{
int val;
struct ListNode* next;
};
void SListInit(struct ListNode** pplist);
void SListDestroy(struct ListNode** pplist);
int SListSize(struct ListNode* plist);
struct ListNode* SListFind(struct ListNode* plist, SLDataType x);
void SListPrint(struct ListNode* plist);
void SListPushBack(struct ListNode** pplist, SLDataType x);
void SListPushFront(struct ListNode** pplist, SLDataType x);
void SListPopBack(struct ListNode** pplist);
void SListPopFront(struct ListNode** pplist);
void SListInsertAfter(struct ListNode* pos, SLDataType x);
void SListEraseAfter(struct ListNode* pos);
|
C
|
#include <stdio.h>
#include <stdlib.h>
void clrscr() {
// for (size_t i = 0; i < n; i++)
// {
// printf("\n");
// }
system("@cls||clear"); // this shit uses the system commands
}
int main()
{
double n1;
double n2;
char op;
printf("Enter a number: ");
scanf("%lf", &n1);
clrscr();
printf("Options:\nMultiplication * | Sum + | Division / | Subtraction -\n");
printf("Enter operator:");
scanf(" %c", &op);
printf("Enter a number: ");
scanf("%lf", &n2);
if(op == '+') {
printf("%3.0f", n1 + n2);
} else if (op == '-') {
printf("%3.0f", n1 - n2);
} else if (op == '/') {
printf("%3.9f", n1 / n2);
} else if (op == '*') {
printf("%3.0f", n1 * n2);
} else {
clrscr();
printf("Invalid operator");
}
return 0;
}
|
C
|
/*---------------------------------------------------------------------------
|
| Framework 2 - Associations
|
| So events can trigger multiple actions.
|
|--------------------------------------------------------------------------*/
#ifndef LINKS_H
#define LINKS_H
#include "sysobj.h"
// An association between objects
typedef struct
{
T_ObjAddr sender; // the sending object
T_AnyAddr dest; // destination object or handler function
U8 event; // senders event to match
U8 destEvent; // event to be sent to dest.
U8 linkType; // precanned link type (below)
} S_Link;
// Precanned link types
#define _Link_Null 0
#define _Link_CopyToDest 1 // treat sender and dest as variables, U16, copy sender to dest
#define _Link_Execute_NoParms 2
#define _Link_Execute_wParms 3
#define _Link_MapEvent 4 // map to a different event, send to 'dest' with _SendEvent()
// Globally defined events (refer to sender)
#define _Link_Event_Null 0
#define _Link_Event_Created 1
#define _Link_Event_Destroyed 2
#define _Link_Event_Changed 3
#define _Link_Event_Started 4
#define _Link_Event_Stopped 5
PUBLIC void Link_SendEvent( T_ObjAddr sender, U8 event );
PUBLIC void Link_SenderChanged( T_ObjAddr sender );
#endif // LINKS_H
|
C
|
#include "stdio.h"
int max(int x, int y, int z)
{
if(x<y)
{
if(z<y)
return y;
else
return z;
}
else
{
if(z<x)
return x;
else
return z;
}
}
int main()
{
int t,i,j,k,cal,r,c,x,y,swp;
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d %d",&r,&c);
int arr[r][c],rra[2][c];
for(j=0;j<r;j++)
{
for(k=0;k<c;k++)
{
scanf("%d",&arr[j][k]);
if(j==r-1)
rra[0][k]=arr[j][k];
}
}
x=1;
y=0;
for(j=r-2;j>=0;j--)
{
swp=x;
x=y;
y=swp;
for(k=0;k<c;k++)
{
if(k>0 && k<c-1)
rra[y][k]=arr[j][k]+max(rra[x][k-1], rra[x][k], rra[x][k+1]);
else
{
if(k==0)
rra[y][k]=arr[j][k]+max(-1, rra[x][k], rra[x][k+1]);
else
rra[y][k]=arr[j][k]+max(rra[x][k-1], rra[x][k], -1);
}
}
}
cal=0;
for(k=0;k<c;k++)
{
if(rra[y][k]>cal)
cal=rra[y][k];
}
printf("%d\n",cal);
}
return 0;
}
/*
One of the secret chambers in Hogwarts is full of philosopher’s stones. The floor of the chamber is covered by h × w square tiles, where there are h rows of tiles from front (first row) to back (last row) and w columns of tiles from left to right. Each tile has 1 to 100 stones on it. Harry has to grab as many philosopher’s stones as possible, subject to the following restrictions:
He starts by choosing any tile in the first row, and collects the philosopher’s stones on that tile. Then, he moves to a tile in the next row, collects the philosopher’s stones on the tile, and so on until he reaches the last row.
When he moves from one tile to a tile in the next row, he can only move to the tile just below it or diagonally to the left or right.
Given the values of h and w, and the number of philosopher’s stones on each tile, write a program to compute the maximum possible number of philosopher’s stones Harry can grab in one single trip from the first row to the last row.
Input
The first line consists of a single integer T, the number of test cases. In each of the test cases, the first line has two integers. The first integer h (1<=h<=100) is the number of rows of tiles on the floor. The second integer w (1<=w<=100) is the number of columns of tiles on the floor. Next, there are h lines of inputs. The ith line of these, specifies the number of philosopher’s stones in each tile of the ith row from the front. Each line has w integers, where each integer m (0<=m<=100) is the number of philosopher’s stones on that tile. The integers are separated by a space character.
Output
The output should consist of T lines, (1<=T<=100), one for each test case. Each line consists of a single integer, which is the maximum possible number of philosopher’s stones Harry can grab, in one single trip from the first row to the last row for the corresponding test case.
Example
Input:
1
6 5
3 1 7 4 2
2 1 3 1 1
1 2 2 1 8
2 2 1 5 3
2 1 4 4 4
5 2 7 5 1
Output:
32
//7+1+8+5+4+7=32
*/
|
C
|
#include "chardev.h"
/* Globals localized to file (by use of static */
static int Major; /* assigned to device driver */
static char msg[BUF_LEN]; /* a stored message */
static struct request *task_queue = NULL; //head of linked_list for mode 5 & 6
//struct used to send requests to threads
static struct request {
char fd;
struct request *next;
};
static struct file_operations fops = {
.read = device_read,
.write = device_write,
.open = device_open,
.release = device_release
};
static int device_open(struct inode *inode, struct file *file)
{
try_module_get(THIS_MODULE);
return 0;
}
static int device_release(struct inode *inode, struct file *file)
{
module_put(THIS_MODULE);
//deallocate the space for the head
return 0;
}
/* Called when a process writes to dev file: echo "hi" > /dev/hello */
static ssize_t device_write(struct file *filp, const char *buff,
size_t len, loff_t * off)
{
int copy_len = len > BUF_LEN ? BUF_LEN : len;
unsigned long amnt_copied = 0;
//at some point append the buff/msg to the list
/* NOTE: copy_from_user returns the amount of bytes _not_ copied */
amnt_copied = copy_from_user(msg, buff, copy_len);
if (copy_len == amnt_copied)
return -EINVAL;
struct request *new_request = kmalloc(sizeof(struct request), GFP_KERNEL);
new_request->fd = msg;
new_request->next = task_queue;
task_queue = new_request;
//create linked list, add (int) msg to the linked list
return copy_len - amnt_copied;
}
static ssize_t device_read(struct file *filp, char *buffer, size_t len,
loff_t * offset)
{
unsigned long amnt_copied;
int amnt_left = BUF_LEN - *offset;
char *copy_position = msg + *offset;
int copy_len = len > amnt_left ? amnt_left : len;
struct request *temp;
/* are we at the end of the buffer? */
if (amnt_left <= 0)
return 0;
msg[0] = task_queue->fd;
printk("the task_queue is %c, while msg[0] is %c\n", task_queue->fd, msg[0]);
/* NOTE: copy_to_user returns the amount of bytes _not_ copied */
amnt_copied = copy_to_user(buffer, copy_position, copy_len);
if (copy_len == amnt_copied)
return -EINVAL;
temp = task_queue;
task_queue = task_queue->next;
kfree(temp);
/* adjust the offset for this process */
*offset += copy_len;
return copy_len - amnt_copied;
}
int init_module(void)
{
Major = register_chrdev(0, DEVICE_NAME, &fops);
if (Major < 0) {
printk(KERN_ALERT "Failed to register char device.\n");
return Major;
}
memset(msg, '+', BUF_LEN);
printk(KERN_INFO "chardev is assigned to major number %d.\n",
Major);
return 0;
}
void cleanup_module(void)
{
int ret = unregister_chrdev(Major, DEVICE_NAME);
if (ret < 0)
printk(KERN_ALERT "Error in unregister_chrdev: %d\n", ret);
}
|
C
|
/*
* File: server_functions.c
* Authors: DanMat27
* AMP
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "../includes/server.h"
#include "../includes/server_functions.h"
#include "../includes/picohttpparser.h"
CONTROL leer_fichero_conf(config* conf){
FILE *f=NULL;
char line[MAXBUF]="";
char* toks=NULL;
char ip[IPBUF]="";
f = fopen("./data/server.conf", "r");
if(!f){
liberar_conf(conf);
return ERROR;
}
fprintf(stdout, "----Fichero de configuracion leido con exito----\n");
/* Leemos el fichero de configuracion */
while(fgets(line, MAXBUF, f)){
/* Ignoramos comentarios */
if(strncmp("//", line, 2) != 0){
/* Leemos puerto servidor */
if(strncmp("PUERTO", line, 6) == 0){
toks = strtok(line + 7, "\n");
conf->num_puerto = atoi(toks);
}
/* Leemos IP servidor */
else if(strncmp("IP", line, 2) == 0){
toks = strtok(line + 3, "\n");
strcpy(ip, toks);
strcpy(conf->ip_server, toks);
}
/* Leemos numero maximo de clientes concurrentes */
else if(strncmp("CLIENTES", line, 8) == 0){
toks = strtok(line + 9, "\n");
conf->num_clientes = atoi(toks);
}
/* Leemos ruta por defecto del servidor */
else if(strncmp("SERVER_ROUTE", line, 12) == 0){
toks = strtok(line + 13, "\n");
strcpy(conf->server_route, toks);
}
/* Leemos firma del servidor en mensajes */
else if(strncmp("SIGNATURE", line, 9) == 0){
toks = strtok(line + 10, "\n");
strcpy(conf->signature, toks);
}
/* Leemos version http del servidor */
else if(strncmp("HTTP_VERSION", line, 12) == 0){
toks = strtok(line + 13, "\n");
conf->http_version = atoi(toks);
}
/* Atributo erroneo */
else{
fprintf(stderr, "Atributo de configuracion invalido: %s\n", line);
}
}
}
fprintf(stdout, "Puerto: %d\nIP: %s\nClientes: %d\nRuta: %s\nFirma: %s\nVersion HTTP: %d\n", conf->num_puerto, ip, conf->num_clientes, conf->server_route, conf->signature, conf->http_version);
fclose(f);
return OK;
}
config* reservar_conf(){
config* conf=NULL;
conf = (config*)calloc(1, sizeof(config));
if(!conf){
return NULL;
}
return conf;
}
void liberar_conf(config* conf){
if(conf){
free(conf);
}
}
void manejador_Control_C(int sig){
fprintf(stdout, "\nCrl+C hecho. Liberando recursos del servidor...\n");
servidor_activo = 0;
}
void procesar_peticion(char* msg, config* conf, ssize_t buflen, char* cabecera, int clientfd) {
char* metodo=NULL;
char* path=NULL;
char* host=NULL;
char* contenido=NULL;
char* fin_msg=NULL;
char* body=NULL;
char* path_args=NULL;
int version_http;
int codigo;
int tipo_peticion;
int i, script=0, args=0;
// Creamos buffers
metodo = crea_buffer(MAXBUF);
path = crea_buffer(MAXBUF);
host = crea_buffer(MAXBUF);
// Obtenemos el metodo de la peticion
for(i = 0; i < (int)buflen; i++){
if(msg[i] == ' '){
break;
}
sprintf(metodo, "%s%c", metodo, msg[i]);
}
metodo[i] = '\0';
// Obtenemos el path de la peticion
for(i = i + 1; i < (int)buflen; i++){
if(msg[i] == ' '){
break;
}
else if(msg[i] == '?'){
args = 1;
break;
}
else{
sprintf(path, "%s%c", path, msg[i]);
}
}
path[i] = '\0';
// Obtenemos argumentos del path si los hay
if(args == 1){
path_args = crea_buffer(MAXBUF);
for(i = i + 1; i < (int)buflen; i++){
if(msg[i] == ' '){
break;
}
sprintf(path_args, "%s%c", path_args, msg[i]);
}
path_args[i] = '\0';
}
// Obtenemos la version http de la peticion
for(i = i + 1; i < (int)buflen; i++){
if(msg[i] == '\r'){
version_http = (int)msg[i - 1] - 48;
break;
}
}
// Comprobamos si soportamos la version http
if(version_http != conf->http_version){
sprintf(cabecera, "HTTP/1.%d %s\r\n\r\n", version_http, ERROR_505);
fprintf(stdout, "Error Peticion: %s\n", ERROR_505);
write(clientfd, cabecera, strlen(cabecera));
libera_buffer(metodo);
libera_buffer(path);
libera_buffer(host);
return;
}
// Miramos que tipo de peticion es (GET, POST u OPTIONS)
if(strcmp(metodo, "GET") == 0){
tipo_peticion = GET;
script = procesa_get_post(path, cabecera, conf);
}
else if(strcmp(metodo, "POST") == 0){
tipo_peticion = POST;
body = crea_buffer(buflen);
// Leemos hasta llegar al cuerpo del mensaje
for(i=i+1; i < (int)buflen; i++) {
if(msg[i]=='\r') {
if(msg[i+1]=='\n' && msg[i+2]=='\r' && msg[i+3]=='\n') {
break;
}
}
}
// Leemos el cuerpo del mensaje
for(i=i+4; i < (int)buflen; i++) {
sprintf(body, "%s%c", body, msg[i]);
}
body[i] = '\n';
script = procesa_get_post(path, cabecera, conf);
}
else if(strcmp(metodo, "OPTIONS") == 0){
procesa_options(cabecera, conf);
// Al ser options enviamos directamente la cabecera
send(clientfd, cabecera, strlen(cabecera), 0);
// Liberamos buffers
libera_buffer(metodo);
libera_buffer(path);
libera_buffer(host);
return;
}
else{
fprintf(stdout, "Error Peticion: %s\n", ERROR_400);
script = 400;
}
// En caso de que haya habido un error
if(script==400){
send_error_html(clientfd, 400, cabecera, conf);
libera_buffer(metodo);
libera_buffer(path);
libera_buffer(host);
return;
}
else if(script==404){
send_error_html(clientfd, 404, cabecera, conf);
libera_buffer(metodo);
libera_buffer(path);
libera_buffer(host);
return;
}
else if(script==500){
send_error_html(clientfd, 500, cabecera, conf);
libera_buffer(metodo);
libera_buffer(path);
libera_buffer(host);
return;
}
// Imprimimos valores peticion recibida
fprintf(stdout, "\n----Cabecera Peticion----\n");
fprintf(stdout, "Peticion de tipo: %s\n", metodo);
fprintf(stdout, "Path: %s\n", path);
fprintf(stdout, "Version HTTP: 1.%d\n\n", version_http);
// Imprimimos valores cabecera y contenido (cuerpo)
fprintf(stdout, "----Cabecera Respuesta----\n%s\n\n", cabecera);
// Enviamos la cabecera
send(clientfd, cabecera, strlen(cabecera)*sizeof(char), 0);
// Reservamos buffer del contenido del mensaje
contenido = crea_buffer(MOREBUF);
// Enviamos el contenido
envia_por_trozos(clientfd, contenido, path, path_args, body, conf, tipo_peticion, script);
fin_msg = crea_buffer(MSG);
strcpy(fin_msg, "\r\n\r\n");
send(clientfd, fin_msg, strlen(fin_msg), 0);
fprintf(stdout, "----Respuesta Enviada----\n");
fprintf(stdout, "#########################\n\n\n");
// Liberamos buffers
if(path_args) libera_buffer(path_args);
if(body) libera_buffer(body);
libera_buffer(fin_msg);
libera_buffer(metodo);
libera_buffer(path);
libera_buffer(host);
libera_buffer(contenido);
}
int procesa_get_post(char* path, char* cabecera, config* conf){
FILE* f=NULL;
char* full_path=NULL;
char* content_type=NULL;
char* date=NULL;
char* last_modified=NULL;
int i, j, script=0;
time_t now = time(0);
struct tm tm = *gmtime(&now);
struct tm tm2;
struct stat recurso;
// Creamos buffers
full_path = crea_buffer(MAXBUF);
content_type = crea_buffer(MAXBUF);
date = crea_buffer(MAXBUF);
last_modified = crea_buffer(MAXBUF);
// Inicializamos path
strcpy(full_path, "./");
// Buscamos y abrimos el recurso solicitado
sprintf(full_path, "%s%s%s", full_path, conf->server_route, path);
f = fopen(full_path, "rb");
if(!f){
fprintf(stdout, "Error Peticion: %s\n", ERROR_404);
return 404;
}
//Identificamos content-type del recurso solicitado
for(i = strlen(path) - 1; i > -1; i--){
if(path[i] == '.'){
for(j = i+1; j < strlen(path); j++) {
sprintf(content_type, "%s%c", content_type, path[j]);
}
break;
}
}
if(strcmp(content_type, "txt") == 0){
strcpy(content_type, "text/plain; charset=utf-8");
}
else if(strcmp(content_type, "jpg") == 0){
strcpy(content_type, "image/jpg");
}
else if(strcmp(content_type, "jpeg") == 0){
strcpy(content_type, "image/jpeg");
}
else if(strcmp(content_type, "png") == 0){
strcpy(content_type, "image/png");
}
else if(strcmp(content_type, "gif") == 0){
strcpy(content_type, "image/gif");
}
else if(strcmp(content_type, "mpeg") == 0){
strcpy(content_type, "video/mpeg");
}
else if(strcmp(content_type, "webm") == 0){
strcpy(content_type, "video/webm");
}
else if(strcmp(content_type, "html") == 0){
strcpy(content_type, "text/html; charset=utf-8");
}
else if(strcmp(content_type, "css") == 0){
strcpy(content_type, "text/css; charset=utf-8");
}
else if(strcmp(content_type, "pdf") == 0){
strcpy(content_type, "application/pdf");
}
else if(strcmp(content_type, "doc") == 0 || strcmp(content_type, "dot") == 0){
strcpy(content_type, "application/msword");
}
else if(strcmp(content_type, "docx") == 0){
strcpy(content_type, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
}
else if(strcmp(content_type, "xls") == 0 || strcmp(content_type, "xlt") == 0){
strcpy(content_type, "application/vnd.ms-excel");
}
else if(strcmp(content_type, "xlsx") == 0){
strcpy(content_type, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
else if(strcmp(content_type, "ppt") == 0 || strcmp(content_type, "pot") == 0){
strcpy(content_type, "application/vnd.ms-powerpoint");
}
else if(strcmp(content_type, "pptx") == 0){
strcpy(content_type, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
}
else if(strcmp(content_type, "php") == 0){
strcpy(content_type, "text/plain; charset=utf-8");
script = PHP;
}
else if(strcmp(content_type, "py") == 0){
strcpy(content_type, "text/plain; charset=utf-8");
script = PY;
}
else {
fprintf(stdout, "Error Peticion: %s\n", ERROR_500);
return 500;
}
// Obtenemos el Date
strftime(date, MAXBUF*sizeof(char), "%a, %d %b %Y %H:%M:%S %Z", &tm);
// Obtenemos el Last-modified del recurso
stat(full_path, &recurso);
tm2 = *gmtime(&(recurso.st_mtime));
strftime(last_modified, MAXBUF*sizeof(char), "%a, %d %b %Y %H:%M:%S %Z", &tm2);
// Obtenemos el Content-length
if(script == PY || script == PHP) conf->content_length = MAXBUF + 2;
else conf->content_length = recurso.st_size + 2;
sprintf(cabecera, "HTTP/1.%d %s\r\nHost: %s:%d\r\nServer: %s\r\nDate: %s\r\nLast-modified: %s\r\nContent-length: %ld\r\nContent-type: %s\r\n\r\n",
conf->http_version, OK_200, conf->ip_server, conf->num_puerto, conf->signature, date, last_modified, conf->content_length, content_type);
// Liberamos buffers
libera_buffer(full_path);
libera_buffer(content_type);
libera_buffer(date);
libera_buffer(last_modified);
// Cerramos el fichero
fclose(f);
return script;
}
void procesa_options(char* cabecera, config* conf){
char* date=crea_buffer(MAXBUF);
time_t now = time(0);
struct tm tm = *gmtime(&now);
// Obtenemos el Date
strftime(date, MAXBUF*sizeof(char), "%a, %d %b %Y %H:%M:%S %Z", &tm);
sprintf(cabecera, "HTTP/1.%d %s\r\nAllowed: GET, POST, OPTIONS\r\nHost: %s:%d\r\nServer: %s\r\nDate: %s\r\n",
conf->http_version, OK_200, conf->ip_server, conf->num_puerto, conf->signature, date);
libera_buffer(date);
}
char* crea_buffer(int tam){
char* buffer=NULL;
buffer = (char*)calloc(tam, sizeof(char));
if(!buffer) return NULL;
return buffer;
}
void libera_buffer(char* buffer){
if(buffer){
free(buffer);
}
}
void envia_por_trozos(int clientfd, char* buffer, char* path, char* path_args, char* body_args, config* conf, int tipo, int script){
int bytesres; // Bytes restantes por enviar
int bytesRead = 0; // Bytes leidos
int bytesToRead = MSG; // Bytes a leer
FILE* f=NULL; // Recurso solicitado
char* full_path=NULL; // Path completo
char* command=NULL; // Comando script
// Reservamos buffers
full_path = crea_buffer(MAXBUF);
// Inicializamos path
strcpy(full_path, "./");
// Buscamos y abrimos el recurso solicitado
sprintf(full_path, "%s%s%s", full_path, conf->server_route, path);
// Abrimos el recurso (script o normal)
if(script == PHP){
command = crea_buffer(MAXBUF);
sprintf(command, "php %s", full_path);
// Obtiene e introduce los argumentos al comando (si hay)
if(tipo == GET){
if(path_args){
obtiene_args_path(command, path_args);
}
}
else if(tipo == POST){
obtiene_args_path(command, body_args);
}
printf("----Ejecutado----\n %s\n\n\n", command);
// Abre descriptor y ejecuta el comando
f = popen(command, "r");
}
else if(script == PY){
command = crea_buffer(MAXBUF);
sprintf(command, "python %s", full_path);
// Obtiene e introduce los argumentos al comando (si hay)
if(tipo == GET){
if(path_args){
obtiene_args_path(command, path_args);
}
}
else if(tipo == POST){
obtiene_args_path(command, body_args);
}
printf("----Ejecutado----\n%s\n\n\n", command);
// Abre descriptor y ejecuta el comando
f = popen(command, "r");
}
else{
f = fopen(full_path, "rb");
}
if(!f){
perror("Error abriendo el recurso");
return;
}
if(script != PY && script != PHP){
// Inicializamos bytes por leer
bytesres = conf->content_length;
// Leemos y enviamos recurso en cachos
while ((bytesRead = fread(buffer, 1, bytesToRead, f)) > 0){
if(bytesres <= 0){
break;
}
send(clientfd, buffer, bytesRead, 0);
bytesres -= bytesRead;
if(bytesres < MSG) bytesToRead = bytesres;
// printf("Bytes ->>>> %d\n", bytesRead);
}
}
else{
strcpy(command, "");
fread(command, 1, MAXBUF, f);
send(clientfd, command, strlen(command), 0);
libera_buffer(command);
}
// Liberamos recursos
libera_buffer(full_path);
if(script == PHP || script == PY) pclose(f);
else fclose(f);
}
void obtiene_args_path(char* command, char* path_args){
int i=0, out=0;
for(i = 0; i < MAXBUF && out == 0; i++){
if(path_args[i] == '\n'){
break;
}
else if(path_args[i] == '='){
sprintf(command, "%s%c", command, ' ');
for(i = i + 1; i < MAXBUF; i++){
if(path_args[i] == '\n'){
out = 1;
break;
}
else if(path_args[i] == ' ' || path_args[i] == '&'){
break;
}
else if(path_args[i] == '+'){
sprintf(command, "%s%c", command, ' ');
}
else{
sprintf(command, "%s%c", command, path_args[i]);
}
}
}
}
}
void send_error_html(int clientfd, int error, char* cabecera, config* conf){
char* contenido=NULL;
char* fin_msg=NULL;
char* full_path=NULL;
char* date=NULL;
char* last_modified=NULL;
time_t now = time(0);
struct tm tm = *gmtime(&now);
struct tm tm2;
struct stat recurso;
FILE* f=NULL;
// Inicializamos path
full_path = crea_buffer(MAXBUF);
strcpy(full_path, "./");
// Buscamos y abrimos el recurso solicitado segun tipo de error
if(error == 400){
sprintf(full_path, "%s%s%s", full_path, conf->server_route, "/error_400.html");
}
else if(error == 404){
sprintf(full_path, "%s%s%s", full_path, conf->server_route, "/error_404.html");
}
else if(error == 500){
sprintf(full_path, "%s%s%s", full_path, conf->server_route, "/error_500.html");
}
// Abrimos recurso para obtener info
f = fopen(full_path, "rb");
if(!f){
libera_buffer(full_path);
return;
}
// Obtenemos el Date
strftime(date, MAXBUF*sizeof(char), "%a, %d %b %Y %H:%M:%S %Z", &tm);
// Obtenemos el Last-modified del recurso
stat(full_path, &recurso);
tm2 = *gmtime(&(recurso.st_mtime));
strftime(last_modified, MAXBUF*sizeof(char), "%a, %d %b %Y %H:%M:%S %Z", &tm2);
// Obtenemos el Content-length
conf->content_length = recurso.st_size + 2;
// Creamos cabecera segun tipo de error
if(error == 400){
sprintf(cabecera, "HTTP/1.%d %s\r\nHost: %s:%d\r\nServer: %s\r\nDate: %s\r\nLast-modified: %s\r\nContent-length: %ld\r\nContent-type: %s\r\n\r\n",
conf->http_version, ERROR_400, conf->ip_server, conf->num_puerto, conf->signature, date, last_modified, conf->content_length, "text/html; charset=utf-8");
}
else if(error == 404){
sprintf(cabecera, "HTTP/1.%d %s\r\nHost: %s:%d\r\nServer: %s\r\nDate: %s\r\nLast-modified: %s\r\nContent-length: %ld\r\nContent-type: %s\r\n\r\n",
conf->http_version, ERROR_404, conf->ip_server, conf->num_puerto, conf->signature, date, last_modified, conf->content_length, "text/html; charset=utf-8");
}
else if(error == 500){
sprintf(cabecera, "HTTP/1.%d %s\r\nHost: %s:%d\r\nServer: %s\r\nDate: %s\r\nLast-modified: %s\r\nContent-length: %ld\r\nContent-type: %s\r\n\r\n",
conf->http_version, ERROR_500, conf->ip_server, conf->num_puerto, conf->signature, date, last_modified, conf->content_length, "text/html; charset=utf-8");
}
// Envia cabecera de error
write(clientfd, cabecera, strlen(cabecera));
contenido = crea_buffer(MAXBUF);
// Enviamos el contenido con el html de error
if(error == 400){
envia_por_trozos(clientfd, contenido, "/error_400.html", NULL, NULL, conf, 0, 0);
}
else if(error == 404){
envia_por_trozos(clientfd, contenido, "/error_404.html", NULL, NULL, conf, 0, 0);
}
else if(error == 500){
envia_por_trozos(clientfd, contenido, "/error_500.html", NULL, NULL, conf, 0, 0);
}
fin_msg = crea_buffer(MSG);
strcpy(fin_msg, "\r\n\r\n");
send(clientfd, fin_msg, strlen(fin_msg), 0);
libera_buffer(full_path);
libera_buffer(contenido);
libera_buffer(fin_msg);
}
|
C
|
/*
* Copyright 2017 kapejod, all rights reserved.
*
* Scanner for RTP NAT stealing vulnerability, for research / educational purposes only!
* Works only on big endian machines and ipv4 targets.
*/
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <netdb.h>
struct sockaddr_in *create_peer(char *host, int port) {
struct sockaddr_in *addr = NULL;
struct hostent *hp = NULL;
addr = malloc(sizeof(struct sockaddr_in));
if (!addr) {
printf("create_peer: unable to malloc peer address\n");
return NULL;
}
memset(addr, 0, sizeof(struct sockaddr_in));
hp = gethostbyname(host);
if (!hp) {
printf("create_peer: unable to resolv host (%s)\n", host);
free(addr);
return NULL;
}
addr->sin_family = AF_INET;
addr->sin_port = htons(port);
bzero(&(addr->sin_zero), 8);
bcopy(hp->h_addr,(char *)&addr->sin_addr, hp->h_length);
return addr;
}
void rtp_scan(char *host, int port_range_start, int port_range_end, int ppp, int payload_size, int payload_type) {
struct sockaddr_in *target;
struct sockaddr_in sender;
socklen_t sender_len = sizeof(sender);
char packet[12 + payload_size];
char response[512];
int flags;
int port;
int loops;
int udp_socket;
target = create_peer(host, port_range_start);
if (!target) return;
udp_socket = socket(PF_INET, SOCK_DGRAM, 0);
if (udp_socket == -1) {
printf("unable to create udp socket\n");
free(target);
return;
}
flags = fcntl(udp_socket, F_GETFL);
fcntl(udp_socket, F_SETFL, flags | O_NONBLOCK);
memset(&packet, 0, sizeof(packet));
packet[0] = 0x80; // RTP version 2
packet[1] = 0x80 | (payload_type & 0x7F); // marker bit set
printf("scanning %s ports %d to %d with %d packets per port and %d bytes of payload type %d\n", host, port_range_start, port_range_end, ppp, payload_size, payload_type);
for (port = port_range_start; port < port_range_end; port += 2) {
target->sin_port = htons(port);
for (loops = 0; loops < ppp; loops++) {
packet[3] = loops; // increase seq with every packet
sendto(udp_socket, &packet, sizeof(packet), 0, (const struct sockaddr *)target, sizeof(struct sockaddr_in));
usleep((5 + loops) * 1000);
int bytes_received = recvfrom(udp_socket, &response, sizeof(response), 0, (struct sockaddr *)&sender, &sender_len);
if (bytes_received >= 12) {
uint16_t seq = ntohs(response[2]);
printf("received %d bytes from target port %d, seq %u\n", bytes_received, ntohs(sender.sin_port), seq);
}
}
}
close(udp_socket);
free(target);
}
int main(int argc, char *argv[]) {
int ppp = 4;
int payload_size = 0;
int payload_type = 0;
if (argc < 4) {
printf("syntax: rtpscan hostname port_range_start port_range_end [packets_per_port] [payload_size] [payload_type]\n");
return -1;
}
if (argc >= 5) ppp = atoi(argv[4]);
if (argc >= 6) payload_size = atoi(argv[5]);
if (argc == 7) payload_type = atoi(argv[6]);
rtp_scan(argv[1], atoi(argv[2]), atoi(argv[3]), ppp, payload_size, payload_type);
return 0;
}
|
C
|
// Creates a child process and registers a signal handler to get exit status of child process
// asynchronously
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#define true (1)
#define false (0)
void signalHandler(int);
int stop = false;
int main() {
srand(time(0));
if(!fork()) {
sleep(rand() % 15 + 1);
exit((rand() % 100));
}
signal(SIGCHLD, signalHandler);
int i = 1;
while (!stop) {
printf("\rWaiting for Child Exit Signal..... %d", i);
fflush(stdout);
sleep(1);
i++;
}
return 0;
}
void signalHandler(int signum) {
printf("\nChild Exit Signal Received.\n");
int wstatus;
int cid = wait(&wstatus);
if(WIFEXITED(wstatus))
printf("\033[0;32m> child(pid): %d of parent (pid): %d exited normally with status: "
"%d\033[0m\n", cid, getpid(), WEXITSTATUS(wstatus));
else
printf("\033[0;31m> child(pid): %d of parent (pid): %d exited abnormally\033[0m\n",
cid, getpid());
stop = true;
}
|
C
|
#include <stdio.h>
#define SIZE 50
long int A[SIZE];
long int dpfib(int n);
int main()
{
int i;
A[0] = 0, A[1] = 1;
for(i = 2; i < SIZE; i++)
A[i] = -1;
int n = 40;
printf("%d fib no %ld\n", n, dpfib(n));
return 0;
}
long int dpfib(int n)
{
if(A[n - 1] == -1)
A[n - 1] = dpfib(n - 1);
if(A[n - 2] == -1)
A[n - 2] = dpfib(n - 2);
return(A[n - 1] + A[n - 2]);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct stu
{
int num;
char name[30];
float grade[3];
float avevage;
struct stu *next;
}STU;
int main(){
STU *head = NULL;
STU *p = NULL;
STU stu_med;
FILE *fp;
int i = 0;
fp = fopen("stud_dat","r");
if (fp)
{
printf("file opened\n");
}
else
{
printf("can't open\n");
return (-1);
}
int size;
size = fread(&stu_med,sizeof(STU),1,fp);
while (size == 1)
{
head = (STU*) malloc(sizeof(STU));
*head = stu_med;
(*head).next = p;
p = head;
size = fread((void*)&stu_med,sizeof(STU),1,fp);
i++;
}
if ( fclose(fp) == 0 )
{
printf("stud_dat closed\n");
}
else
{
printf("can't close\n");
return (-1);
}
fp = fopen("stud_sort","w");
if (fp)
{
printf("file opened\n");
}
else
{
printf("can't open\n");
return (-1);
}
for (int j = 0; j<i; j++)
{
if (head->avevage < head->next->avevage)
{
p = head;
head = head->next;
p->next = head->next;
head->next = p;
}
STU **med;
med = &head->next;
while ((*med)->next)
{
if ((*med)->avevage < (*med)->next->avevage)
{
p = *med;
(*med) = (*med)->next;
p->next = (*med)->next;
(*med)->next = p;
}
med = &(*med)->next;
}
}
p = head;
while (head)
{
fwrite(head,sizeof(STU),1,fp);
head = head->next;
free(p);
p = head;
}
fflush(fp);
if ( fclose(fp) == 0 )
{
printf("file closed\n");
}
else
{
printf("can't close\n");
}
return (0);
}
|
C
|
#include <libopencm3/cm3/common.h>
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/f4/spi.h>
#include "lcd.h"
static void delay(int i)
{
int j,k=0;
while(k++ < i)
for (j = 0; j <= 300; j++) {
__asm__("nop");
}
}
void transfer_command(int data1)
{
gpio_clear(LCD_PORT,cs1);
delay(1);
gpio_clear(LCD_PORT,rs);
delay(1);
spi_send(SPI1,data1);
}
void transfer_data(int data1)
{
gpio_clear(LCD_PORT,cs1);
delay(1);
gpio_set(LCD_PORT,rs);
delay(1);
spi_send(SPI1,data1);
}
void lcd_address(unsigned char page,unsigned char column)
{
column = column - 1;
page = page - 1;
transfer_command(0xb0+page);
transfer_command(((column>>4)&0x0f)+0x10);
transfer_command(column&0x0f);
}
void clear_screen(void)
{
unsigned char i,j;
for(i=1;i<9;i++) {
lcd_address(i,1);
for(j=0;j<132;j++) {
transfer_data(0x00);
}
}
}
void test_display(unsigned char data1)
{
int i,j;
for(j=0;j<8;j++) {
lcd_address(j+1,0);
for(i=0;i <128;i++) {
transfer_data(data1);
}
}
}
void initial_lcd(void)
{
gpio_clear(LCD_PORT,reset);
/* 低电平复位*/
delay(200);
gpio_set(LCD_PORT,reset);
/* 复位完毕*/
delay(50);
transfer_command(0xe2);
/* 软复位*/
delay(5);
transfer_command(0x2c); /* 升压步聚 1*/
delay(5);
transfer_command(0x2e); /* 升压步聚 2*/
delay(5);
transfer_command(0x2f); /* 升压步聚 3*/
delay(5);
transfer_command(0x24); /*粗调对比度 , 可设置范围0x20 ~ 0x27*/
transfer_command(0x81); /*微调对比度*/
transfer_command(0x0f); /*0x22,微调对比度的值 , 可设置范围0x00 ~ 0x3f*/
transfer_command(0xa2); /*1/9 偏压比(bias ) */
transfer_command(0xc8); /*行扫描顺序:从上到下 */
transfer_command(0xa0); /*列扫描顺序:从左到右 */
transfer_command(0x40); /*起始行:第一行开始*/
transfer_command(0xaf); /*开显示*/
}
/*
* x:0-127
* y:0-63
*/
void lcd_draw_point(int x,int y)
{
lcd_address((y>>3)+1,x+1);
transfer_data(1<<(y%8));
}
void lcd_draw_image(const unsigned char image[])
{
unsigned int pos=0;
while(pos < 1024){
lcd_address((pos>>7)+1,pos%128+1);
transfer_data((int)image[pos]);
pos++;
}
}
|
C
|
#include <video.h>
#include <salir.h>
#include <matar.h>
#include <video.h>
#include <sodero/syscalls.h>
/**
* Ejecutable encargado de interrumpir la ejecucion de un proceso que se
* encuentra corriendo.
*/
int main (int argc, char* argv[]) {
int pid;
int rta;
if ( argc != 2 ) {
imprimir_cadena ( "Error en los argumentos\n" );
imprimir_cadena ( "\t Utilizar matar <numero_pid>\n" );
salir ( 1 );
}
pid = ctoi (argv[1]);
if ( pid == NULL ) {
imprimir_cadena ("pid incorrecto\n");
salir (1);
}
rta = matar (pid);
if ( rta == -1 ) {
imprimir_cadena ( "error en matar\n" );
} else if ( rta == -2 ) {
imprimir_cadena ( "imposible matar un proceso de sistema\n" );
} else if (rta == pid) {
imprimir_cadena ( "proceso interceptado y eliminado de la cola\n" );
} else {
imprimir_cadena ( "no se encontro al proceso en la cola\n" );
}
salir (2);
imprimir_cadena ( "si ves esto algo anda mal!!!\n" );
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <wait.h>
int pid;
int pipe1[2];
int pipe2[2];
int main(){
// create pipe1
if (pipe(pipe1) == -1) {
perror("bad pipe1");
exit(1);
}
// fork (ps aux)
if ((pid = fork()) == -1) {
perror("bad fork1");
exit(1);
}else if (pid == 0) {
// input from stdin
// output to pipe1
dup2(pipe1[1], 1);
// close fds
close(pipe1[0]);
close(pipe1[1]);
// exec
execlp("ps", "ps", "aux", NULL);
// exec didn't work, exit
perror("bad exec ps");
exit(1);
}
// parent
// create pipe2
if (pipe(pipe2) == -1) {
perror("bad pipe2");
exit(1);
}
// fork (sort -nrk 3,3)
if ((pid = fork()) == -1) {
perror("bad fork2");
exit(1);
} else if (pid == 0) {
// input from pipe1
dup2(pipe1[0], 0);
// output to pipe2
dup2(pipe2[1], 1);
// close fds
close(pipe1[0]);
close(pipe1[1]);
close(pipe2[0]);
close(pipe2[1]);
// exec
execlp("sort", "sort", "-nrk 3,3", NULL);
// exec didn't work, exit
perror("bad exec sort -nrk 3,3");
exit(1);
}
// parent
// close unused fds
close(pipe1[0]);
close(pipe1[1]);
// fork (head -5)
if ((pid = fork()) == -1) {
perror("bad fork3");
exit(1);
}else if (pid == 0){
// input from pipe2
dup2(pipe2[0], 0);
// output to stdout (already done)
// close fds
close(pipe2[0]);
close(pipe2[1]);
// exec
execlp("head", "head", "-5", NULL);
// exec didn't work, exit
perror("bad exec head -5");
exit(1);
}
// parent
}
|
C
|
#include <stdio.h>
#include "tree.h"
#include <stdlib.h>
#include "pessoa.h"
Tnode *ABPRemoveUmFilho(Tnode *root, void *key, int(*cmp)(void*, void*));
int CheckBin(Tnode *t);
int CheckSearchTree(Tnode *t, int(*cmp)(void*, void*));
void visit(void *data){
int *aux;
if (data != NULL){
aux = (int*)data;
printf("%d ", aux);
}
}
int compare(void *key, void* data){
int *a;
int *b;
a = (int*)key;
b = (int*)data;
if ( a > b){
return 1;
} else if(a < b){
return -1;
} else {
return 0;
}
}
int main(int argc, char const *argv[]) {
int menuOption = 0;
int data;
void* query = NULL;
void* aux = NULL;
Tnode *remove = NULL;
Tnode *root = NULL;
int check, check2;
do{
system("cls");
printf("%s\n", "*************************");
printf("%s\n", " [1] Criar Arvore Binaria ");
printf("%s\n", " [2] Inserir Elemento");
printf("%s\n", " [3] Procurar Elemento");
printf("%s\n", " [4] Remover Elemento");
printf("%s\n", " [5] Destruir Arvore");
printf("%s\n", " [8] Sair");
printf("%s\n", "*************************");
if(root!=NULL){
int size = ABPContaNo(root);
printf("Arvore organizada de acordo com a idade dos elementos!\n");
printf("Arvore em Pos-Ordem:\t");
treePosOrdem(root, visit);
putchar('\n');
printf("Arvore em Pre-Ordem:\t");
treePreOrdem(root, visit);
putchar('\n');
printf("Arvore em Simetria :\t");
treeSimetria(root, visit);
putchar('\n');
int nos = ABPContaNo(root);
printf("Numero de nos: %d\n", nos-1);
printf("Numero de nos maiores que 10: %d\n", numMaiores(root, 10, visit, compare));
printf("Altura da arvore: %d\n", TnodeAltura(root));
check = CheckBin(root);
// check2 = CheckSearchTree(root, compare);
if(check == true){
printf("E uma arvore binaria completa\n");
}else{
printf("Nao e uma arvore binaria completa\n");
}
// if(check2 == true){
// printf("E uma arvore binaria de pesquisa\n");
// }else{
// printf("Nao e uma arvore binaria de pesquisa\n");
// }
putchar('\n');
}
printf("Sua escolha: ");
scanf("%d", &menuOption);
switch (menuOption) {
case 1:
if(root == NULL){
root = ABPCreate();
}
if (root != NULL){
printf("%s\n", "Arvore criada com sucesso");
system("pause");
} else {
printf("%s\n", "Ops, Arvore n pode ser criada");
system("pause");
}
break;
case 2:
// insertPessoa(root);
ABPInsert(root, (void *)40, (void*)40, compare);
ABPInsert(root, (void *)5, (void*)5, compare);
ABPInsert(root, (void *)100, (void*)100, compare);
ABPInsert(root, (void *)1, (void*)1, compare);
ABPInsert(root, (void *)6, (void*)6, compare);
system("pause");
break;
case 3:
// searchPessoa(root);
break;
case 4:
ABPRemoveUmFilho(root, (void*)5, compare);
break;
case 5:
if (ABPDestroy(root) == true){
printf("%s\n", "A arvore foi destruida");
} else {
printf("%s\n", "A arvore nao pode ser destruida ainda");
}
system("pause");
break;
case 6:
system("pause");
break;
default:
break;
}
}while(menuOption!=8);
return 0;
}
Tnode *ABPRemoveUmFilho(Tnode *root, void *key, int(*cmp)(void*, void*)){
Tnode *aux;
void *data;
if(root!=NULL){
int stat;
stat = cmp(key, root->data);
if(stat == 1){
root->right = ABPRemoveUmFilho(root->right, key, cmp);
}else if(stat == -1){
root->left = ABPRemoveUmFilho(root->left, key, cmp);
}else{
if(root->left != NULL && root->right == NULL){
aux = root->left;
free(root);
return aux;
}else{
printf("tem mais ou nao tem nenhum filho\n");
return NULL;
}
}
}
return NULL;
}
int CheckBin(Tnode *t){
int l, r;
if(t!=NULL){
if(t->right!=NULL && t->left != NULL){
l = CheckBin(t->left);
r = CheckBin(t->right);
}else if(t->right == NULL && t->left == NULL){
return true;
}else{
return false;
}
}
}
int CheckSearchTree(Tnode *t, int(*cmp)(void*, void*) ){
int l, r;
int cmpL, cmpR;
int statL, statR;
if(t!=NULL){
statL = cmp(t->left->data, t->data);
statR = cmp(t->right->data, t->data);
if(statR == 1 && statL == -1){
cmpL = CheckSearchTree(t->left, cmp);
cmpR = CheckSearchTree(t->right, cmp);
}else{
return false;
}
}
return false;
}
|
C
|
#ifndef GAMEUTILS_H
#define GAMEUTILS_H
#include "types.h"
/*!
* \file GameUtils.h
* \brief A set of functions to deal with game mechanics
* \author BOULAY Mathias
* \version 1.0
* \date 15 janvier 2021
*/
/**
* @brief Tells if someone won.
* @param[in] Map The GameMap to Check on
* @fn bool HasSomeoneWon(const GameMap & Map);
* @return bool
*/
bool HasSomeoneWon(const GameMap & Map);
/**
* @brief Tell if the map is full.
* @param[in] Map The GameMap to Check on
* @fn bool HasSomeoneWon(const GameMap & Map);
* @return bool
*/
bool IsGameMapFull(const GameMap & Map);
/**
* @brief Put a token "X,O..." on the GameMap.
* @param[in, out] Map The GameMap to put the token on
* @param[in] Token The token to put
* @param[in] index The index to put the token at.
* @fn PutToken(GameMap & Map, const char Token, const unsigned index);
* @return bool
*/
bool PutToken(GameMap & Map, const char Token, const unsigned index);
/**
* @brief Return an empty GameMap
* @fn GameMap InitGameMap();
* @return GameMap
*/
GameMap InitGameMap();
#endif // GAMEUTILS_H
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#define ALARM_TIME 15
void miFuncion(int);
void miAlarma(int);
void seCorto(int);
int condicion = 1;
int cant = 0;
int main(void) {
signal(SIGUSR1, miFuncion);
signal(SIGINT, seCorto); // ctrl+C
signal(SIGALRM, miAlarma); // alarma
alarm(ALARM_TIME);
while(condicion);
printf("Sali del while\n");
kill(getpid(), SIGUSR1); // Envio una señal a mi mismo
signal(SIGINT, SIG_IGN);
return 0;
}
void seCorto(int a) {
signal(SIGINT, SIG_IGN); // Ignoro la señal por defecto
printf("\nIntentaste cerrar. Sobrevivi al ctrl+c!\n");
cant++;
printf("Van %d veces\n", cant);
signal(SIGINT, seCorto); // Reinstalo la señal
}
void miAlarma(int a) {
printf("------- ¡¡Alarma!! -------\n");
printf("Mi PID es: %d\n", getpid());
condicion = 0;
}
void miFuncion(int a) {
printf("Estoy en SIGUSR1\n");
}
|
C
|
#include <stdio.h>
#include <string.h>
void subs(char firstStr[], char secondStr[], int start, int end){ // i'll make this a function for substringing.
int i=0;
while ((i) < end) { // while the length exists, i want to add the the value of firstStr (start+i) into secondStr.
secondStr[i] = firstStr[start+i]; // iterate
i++; // keep doing until reaching end
}
}
int main()
{
char str1[20] = "testingthis";
char str2[20] = "valuetestin";
printf("string one : %s",str1);
printf("\nstring two: %s ", str2 );
printf("\n---------------------------");
strcat(str1, str2); // concat the strings into a large array
subs(str1, str2, 0, (strlen(str1) - strlen(str2))); // iterate starting from 0 to the length starting from the val of str1 - str2
subs(str1, str1, strlen(str2), strlen(str1)); // iterate within the lenght of the char arrays
printf("\nstring one : %s",str1);
printf("\nstring two: %s", str2 );
return 0;
}
|
C
|
#include <stdio.h>
/**
* main - entry into the function
* Description: prints all possible combinations
* of 2 digit numbers
* Return: Always 0 (successful)
*/
int main(void)
{
int first;
int second;
for (second = 0; second <= 9; second++)
{
for (first = second + 1; first <= 9; first++)
{
putchar(second + '0');
putchar(first + '0');
if (second == 8 && first == 9)
{
continue;
}
putchar(',');
putchar(' ');
}
}
putchar('\n');
return (0);
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
char str[100],str1[50]={"HELLO"},str2[50]={"HOLA"},str3[50]={"HALLO"},str4[50]={"BONJOUR"},str5[50]={"CIAO"},str6[50]={"ZDRAVSTVUJTE"};
char str7[10]={"#"};
long long i=0;
while(1)
{
i++;
scanf("%s",str);
if(strcmp(str,str7)==0)
return 0;
else if(strcmp(str,str1)==0)
{
printf("Case %d: ENGLISH\n",i);
continue;
}
else if(strcmp(str,str2)==0)
{
printf("Case %d: SPANISH\n",i);
continue;
}
else if(strcmp(str,str3)==0)
{
printf("Case %d: GERMAN\n",i);
continue;
}
else if(strcmp(str,str4)==0)
{
printf("Case %d: FRENCH\n",i);
continue;
}
else if(strcmp(str,str5)==0)
{
printf("Case %d: ITALIAN\n",i);
continue;
}
else if(strcmp(str,str6)==0)
{
printf("Case %d: RUSSIAN\n",i);
continue;
}
else
{
printf("Case %d: UNKNOWN\n",i);
continue;
}
}
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int a, b, c, maxx;
printf("a=");
scanf("%d", &a);
printf("b=");
scanf("%d", &b);
printf("c=");
scanf("%d", &c);
if(a>=b && a>=c)
{
maxx = a;
}
else if(b>=a && b>=c)
{
maxx = b;
}
else
{
maxx = c;
}
printf("Maximul este %d\n", maxx);
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
int num,temp,sum=0,rem;
printf("\n Enter the number");
scanf("%d",&num);
temp=num;
while(temp!=0)
{
rem=temp%10;
sum=sum+rem;
temp=temp/10;
}
printf("\n%d",sum);
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(){
int hash[256] = {0};
int n, k, i;
scanf("%d\n", &k);
char s[100];
scanf("%[^\t\n]s",s);
n = strlen(s);
for(i=0; i<n; i++)
hash[(int)s[i]]++;
int a=0;
for(i=0; i<256; i++)
if(hash[i]==k)
a++;
printf("%d\n", a);
return 0;
}
|
C
|
#include <stdlib.h>
#include <mysql.h>
#include "DbConnection.h"
#include "LibRoo.h"
int dbSet = 0;
DbConnectionSettings _dbConnection;
// Implementation of DbConnection.h
DbConnectionSettings* GetDbConnectionSettings ()
{
return &_dbConnection;
}
#define DBCLEANSE(dbattr) tryfree (settings->dbattr);
void CleanseDbConnectionSettings ()
{
DbConnectionSettings* settings;
settings = GetDbConnectionSettings ();
if (dbSet)
{
trace ("Cleansing db connection settings.");
DBCLEANSE (Hostname);
DBCLEANSE (User);
DBCLEANSE (Password);
DBCLEANSE (Database);
DBCLEANSE (Socket);
settings->Port = 0;
settings->Flags = 0;
dbSet = 0;
}
}
#define DBCLONE(dbset,dbval) settings->dbset = strclone (dbval);
void SetDbConnectionSettings (const char* host, const char* user, const char* password,
const char* dbName, unsigned int port, const char* socket, unsigned long flag)
{
DbConnectionSettings* settings;
settings = GetDbConnectionSettings ();
trace ("Setting db connection settings.");
CleanseDbConnectionSettings ();
DBCLONE (Hostname, host);
DBCLONE (User, user);
DBCLONE (Password, password);
DBCLONE (Database, dbName);
DBCLONE (Socket, socket);
settings->Port = port;
settings->Flags = flag;
dbSet = 1;
}
#define ASSERT_DB_ASSET(asset,message) if (!asset) { error (message); CleanseDbConnection (conn); return NULL; }
MYSQL* NewDbConnection()
{
MYSQL* conn, *connected;
DbConnectionSettings* settings;
ASSERT_DB_ASSET (dbSet, "The database connection settings were never set.");
settings = GetDbConnectionSettings ();
trace ("Opening a new db connection.");
conn = mysql_init (NULL);
ASSERT_DB_ASSET (conn, "Error initializing database connection object.");
connected = mysql_real_connect (conn,
settings->Hostname,
settings->User,
settings->Password,
settings->Database,
settings->Port,
settings->Socket,
settings->Flags);
ASSERT_DB_ASSET (connected, "Error connection to the database.");
return connected;
}
void CleanseDbConnection (MYSQL* conn)
{
if (mysql_errno (conn))
error (mysql_error (conn));
trace ("Closing db connection object.");
mysql_close (conn);
}
|
C
|
/*
* (C) Copyright 2010
* Texas Instruments, <www.ti.com>
* Aneesh V <[email protected]>
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#ifndef _UTILS_H_
#define _UTILS_H_
static inline s32 log_2_n_round_up(u32 n)
{
s32 log2n = -1;
u32 temp = n;
while (temp) {
log2n++;
temp >>= 1;
}
if (n & (n - 1))
return log2n + 1; /* not power of 2 - round up */
else
return log2n; /* power of 2 */
}
static inline s32 log_2_n_round_down(u32 n)
{
s32 log2n = -1;
u32 temp = n;
while (temp) {
log2n++;
temp >>= 1;
}
return log2n;
}
#endif
|
C
|
#include<stdio.h>
void main()
{
int n,r,q;
printf("enter the number");
scanf("%d",&n);
if(n<27)
{
printf("%c",64+n);
}
else if(n>=27)
{
q=n/26;
r=n%26;
printf("%c%c",64+q,64+r);
}
}
|
C
|
#include <stdio.h>
int _naive_set( double *in_data, int in_time, double *out_data)
{
if(in_time==0) //Used on the first forecast
{
*out_data = in_data[0];
return 0;
}
else if(in_time==1) //Used on the second forecast
{
*out_data = in_data[1];
return 0;
}
else if(in_time<0) //Erro: negative time
return -1;
*out_data = in_data[in_time-1] * ( 1 + ( (in_data[in_time-1] - in_data[in_time-2] )/in_data[in_time-2] ) );
return 0;
}
double naive_set( double *in_data, int in_time, double *out_data)
{
double out_data;
int i=0,result,dif=0;
double MAPE=0;
for(i=0;i<len;i++)
{
result=_naive_set(in_data,i,&out_data);
dif=out_data-in_data[i];
if(dif<0)
dif=-dif;
MAPE=MAPE+(dif/in_data[i]);
}
return MAPE/len;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* des_convertors.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nkolosov <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/24 14:43:56 by nkolosov #+# #+# */
/* Updated: 2018/01/24 14:43:56 by nkolosov ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_ssl.h"
#include "libft.h"
static void hex_to_bits(char c, t_bits *b, size_t from)
{
size_t i;
size_t num;
if (c >= '0' && c <= '9')
num = c - '0';
else if (c >= 'a' && c <= 'f')
num = c + 10 - 'a';
else if (c >= 'A' && c <= 'F')
num = c + 10 - 'A';
else
key_error();
i = -1;
while (++i < 4)
{
b->bits[from + 3 - i] = num % 2;
num /= 2;
}
}
static void fill_remainder(t_des *d, size_t i)
{
size_t j;
unsigned char c;
char num;
num = 8 - i;
i--;
while (++i < 8)
{
c = num;
j = -1;
while (++j < 8)
{
d->block.bits[i * 8 + 7 - j] = c % 2;
c /= 2;
}
}
}
void des_str_to_bits(t_des *d, char *str)
{
size_t i;
size_t j;
unsigned char c;
i = 0;
while (i < 8)
{
c = str[i];
j = -1;
while (++j < 8)
{
d->block.bits[i * 8 + 7 - j] = c % 2;
c /= 2;
}
i++;
}
fill_remainder(d, i);
}
void des_key_to_bits(char *str, t_bits *b)
{
size_t i;
i = -1;
while (str[++i] && i < 16)
hex_to_bits(str[i], b, i * 4);
i--;
while (++i < 16)
hex_to_bits('0', b, i * 4);
}
void des_bits_to_str(t_des *d, char *str)
{
unsigned char c;
size_t i;
size_t j;
i = -1;
while (++i < 8)
{
j = -1;
c = 0;
while (++j < 8)
c = c * 2 + d->block.bits[i * 8 + j];
str[i] = c;
}
}
|
C
|
#include "holberton.h"
/**
* add - a function that adds two numbers.
* @m: int
* @n: int
* Return: an int
**/
int add(int m, int n)
{
int result;
result = m + n;
return (result);
}
|
C
|
//Determinar si los delimitadores en una expresion aritmetica estan balanceados
//Delimitadores (),[],{}.
//Por ejemplo: (x + 4), (x + 3 * [2 + 4])
#include <stdio.h>
#include "Pila.h"
int main(){
PILA mipila;
char expresion[100],i;
int band = 0;
init(&mipila);
printf("Expresion: ");
gets(expresion);
for(i = 0; expresion[i] != '\0'; i++){
if(expresion[i] == '(' || expresion[i] == '[' || expresion[i] == '{' )
push(&mipila, expresion[i]);
if(expresion[i] == ']' || expresion[i] == '}' || expresion[i] == ')')
if(empty(&mipila)){
printf("\nExpresion incorrecta\n\n");
band = 1;
}
else
switch(expresion[i]){
case ')': if(pop(&mipila) != '('){
printf("\nExpresion incorrecta\n");
band = -1;
}
break;
case ']': if(pop(&mipila) != '['){
printf("\nExpresion incorrecta\n");
band = -1;
}
break;
case '}': if(pop(&mipila) != '{'){
printf("\nExpresion incorrecta\n");
band = -1;
}
break;
}
if(band == -1)
break;
}
if(empty(&mipila) == 1 && band == 0)
printf("La expresion es correcta\n");
else if(band == 0)
printf("\nExpresion incorrecta\n");
return 0;
}
|
C
|
int
abs_diff(int x,int y)
{
int res = 0;
if(x>=y){
res = x-y;
}
else{
res = y-x;
}
return res;
}
|
C
|
//#include <stdio.h>
//
//void main() {
// /*
// * նѭ5ɼ浽double飬
// */
// //ͳʼķʽ
// int arr2[3] = {10, 20, 80};
// //ڶʱֱӾֵָʡС
// int arr3[] = {10, 20, 80};
// //һ
// double arr[5];
// int arrLen = sizeof(arr) / sizeof(double);
// int i;
// for (i = 0; i < arrLen; i++) {
// printf("һС");
// scanf("%lf", &arr[i]);
// }
//
// //
// printf("\n==============================");
// for (i = 0; i < arrLen; i++) {
// printf("\narr[%d]=%.2f", i, arr[i]);
// }
//}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.