language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/*
** EPITECH PROJECT, 2019
** PSU_my_sokoban_2019
** File description:
** check_map
*/
#include "sokoban.h"
int check_how_many_o(char **map)
{
int a = 0;
int b;
int count = 0;
while (map[a]) {
b = 0;
while (map[a][b]) {
if (map[a][b] == 'O')
count++;
b++;
}
a++;
}
return (count);
}
int check_how_many_x(char **map)
{
int a = 0;
int b;
int count = 0;
while (map[a]) {
b = 0;
while (map[a][b]) {
if (map[a][b] == 'X')
count++;
b++;
}
a++;
}
return (count);
}
int check_valid_map(char *buffer)
{
int i = 0;
char c;
int x = 0;
int o = 0;
while (buffer[i]) {
c = buffer[i];
if (!(c == ' ' || c == '\n' || c == 'O' || c == 'P' || c == 'X' || c == '#'))
return (-1);
else if (c == 'X' || c == 'O') {
if (c == 'X')
x++;
else
o++;
}
i++;
}
if (o > x)
return (-1);
else
return (1);
}
|
C
|
#include <stdio.h>
int main()
{
int num,i,p=2,result=1;
scanf("%d",&num);
for(i=1;i<=num;i++)
{
result=result*p;
if(result==num)
{
printf("yes");
break;
}
else
{
continue;
}
}
if(result!=num)
{
printf("no");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "bubblefunc.h"
#define ARRAY_NUM 20
/* program entry */
int main(int argc, char **argv) {
int array[ARRAY_NUM] = {0};
int i, j, r;
int fFind;
srand(time(NULL));
/* 1 からARRAY_NUMの重複しない値をランダムにarrayに格納する。*/
for( i = 0; i < ARRAY_NUM; i++ ) {
do {
fFind = 0;
r = rand() % ARRAY_NUM + 1;
for( j = 0; j < i; j++){
if( array[j] == r ) {
fFind = 1;
break;
}
}
}while(fFind);
array[i] = r;
}
printf("--Before--\n");
printarray(&array[0], ARRAY_NUM);
sort(array, ARRAY_NUM);
printf("--After--\n");
printarray(&array[0], ARRAY_NUM);
return 0;
}
|
C
|
#include"Stack.h"
#include<stdio.h>
#include<stdlib.h>
void create(stack *s)
{
s->sz=500;
s->top=0;
s->A=(char *)malloc(s->sz*sizeof(char));
}
void push(stack *s,char st)
{
if(isFull(s)==0)
{
printf("\nStack is Full!You cannot insert more\n");
return ;
}
s->A[s->top++]=st;
}
char pop(stack *s)
{
if(isEmpty(s)==0)
return '\0';
s->top--;
char st=s->A[s->top];
s->A[s->top]='\0';
return st;
}
char top(stack *s)
{
if(isEmpty(s)==0)
return '\0';
return s->A[s->top-1];
}
int isFull(stack *s)
{
if(s->top==s->sz)
return 0;
return 1;
}
int isEmpty(stack *s)
{
if(s->top==0)
return 0;
return 1;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <getopt.h>
static struct option main_options[] = {
{ "help", 0, 0, 'h' },
{ "verbose", 0, 0, 'v' },
{ "msbc", 0, 0, 'm' },
{ "subbands", 1, 0, 's' },
{ "bitpool", 1, 0, 'b' },
{ "joint", 0, 0, 'j' },
{ "dualchannel",0, 0, 'd' },
{ "snr", 0, 0, 'S' },
{ "blocks", 1, 0, 'B' },
{ 0, 0, 0, 0 }
};
int main(int argc, char *argv[])
{
char *output = NULL;
int i, opt, tofile = 0;
bool msbc = false;
while ((opt = getopt_long(argc, argv, "+hmvd:f:",
main_options, NULL)) != -1) {
switch(opt) {
case 'h':
exit(0);
case 'v':
break;
case 'm':
msbc = true;
break;
case 'd':
free(output);
output = strdup(optarg);
//printf("%s",output);
tofile = 0;
break;
case 'f' :
free(output);
output = strdup(optarg);
//printf("%s",output);
tofile = 1;
break;
default:
exit(1);
}
}
argc -= optind;
argv += optind;
optind = 0;
if (argc < 1) {
exit(1);
}
for (i = 0; i < argc; i++)
printf("%s \n\t",argv[i]);
free(output);
return 0;
}
|
C
|
/*
* Board.h
*
* Created on: Mar 30, 2017
* Author: luke
*/
#ifndef BOARD_H_
#define BOARD_H_
#include "Piece.h"
#include "Types.h"
#define BOARD_SIZE 8
typedef struct _Board {
Piece pieces[BOARD_SIZE][BOARD_SIZE];
} Board;
typedef struct {
Piece piece;
Coordinate coordinate;
} PlacedPiece;
typedef struct {
PlacedPiece pieces[12];
int count;
} PieceList;
extern void initialize(Board *board);
extern int isPiece(Piece *piece);
extern PieceList getPiecesForColor(Board *board, color_t color);
extern int isValidPosition(Board *board, Coordinate coordinate);
extern Piece *getPieceAt(Board *board, Coordinate coordinate);
extern void removePieceAt(Board *board, Coordinate coordinate);
extern void placePieceAt(Board *board, Piece *piece, Coordinate coordinate);
extern void moveAndKingPiece(Piece *piece, Board *board, Coordinate coordinate);
extern int pieceIsJumpable(Board *board, Piece *piece, Coordinate location);
extern int nextSpaceIsLandable(Board *board, Piece *piece, Coordinate location, Coordinate next);
extern void printBoard(Board *board);
#endif /* BOARD_H_ */
|
C
|
/*
* keyboard.c
*
* Created on: 2015/12/19
* Author: koji
*/
#include "keyboard.h"
#define PORT_KEYSTA 0x0064
#define KEYSTA_SEND_NOTREADY 0x02
#define KEYCMD_WRITE_MODE 0x60
#define KBC_MODE 0x47
void wait_KBC_sendready(void)
{
/* wait until KBC can send */
while(1){
if((io_in8(PORT_KEYSTA) & KEYSTA_SEND_NOTREADY) == 0) {
break;
}
}
return;
}
void init_keyboard(void)
{
/* init keyboard controller */
wait_KBC_sendready();
io_out8(PORT_KEYCMD, KEYCMD_WRITE_MODE);
wait_KBC_sendready();
io_out8(PORT_KEYDAT, KBC_MODE);
return;
}
|
C
|
#include "header.h"
//to check the extension
status extention(char *arr,FILE **fp,int *end)
{
//check for file extention
int j;
for(j=0;arr[j] != '\0';j++)
{
if(arr[j] == '.')
{
char *temp = &arr[j];
if(0 == strcmp(".c",temp))
{
break;
}
else
{
puts("Not a C file");
//return e_failure;
}
}
}
if(arr[j] == '\0')
{
puts("file extension not specified/not proper");
return e_failure;
}
//if c file -> open the file
*fp = fopen(arr,"r");//open file in read mode
if(*fp == NULL)
{
fprintf(stderr,"opening of %s file unsuccessfull", arr);
return e_failure;
}
int i;
//open the file n check whether it is empty or not
fseek(*fp, 0L, SEEK_SET);
int start = ftell(*fp);
fseek(*fp,0L,SEEK_END);
*end = ftell(*fp);
fseek(*fp, 0L, SEEK_SET);
if(start == (*end))
{
fprintf(stderr,"file is empty\n");
return e_failure;
}
return e_success;
}
status parse(FILE *fp)
{
int i=0;
char buf[1000];
char temp;
char iden[1000];
int j=0,count =0;
do
{
fread(&buf[i],1,1,fp);
if(buf[i] == '"')
{
buf[i++]='"';
fread(&buf[i],1,1,fp);
for( ;buf[i++] != '"'; )
{
fread(&buf[i],1,1,fp);
}
buf[i++] ='\0';
buf[i]='"';
break;
}
else if(buf[i] == ' '|| buf[i] == '\n'||buf[i] == ';')
{
buf[i]='\0';
strcpy(iden,buf);
if(e_failure == keyword(iden))
{
fprintf(stderr,"keyword not found\n");
}
if(e_failure == variable(iden))
{
fprintf(stderr,"keyword not found\n");
}
break;
}
else if(buf[i] == '('|| buf[i]=='=')
{
fseek(fp,-1L,SEEK_CUR);
fread(&temp,1,1,fp);
buf[i] = '\0';
if(e_failure == variable(buf))
{
fprintf(stderr,"identifier not found\n");
}
break;
}
/* else if(buf[i] == '=')
{
fseek(fp,-1L,SEEK_CUR);
fread(&temp,1,1,fp);
buf[i] = '\0';
if(e_failure == variable(buf))
{
fprintf(stderr,"identifier not found\n");
}
break;
}*/
else if(0 != isdigit(buf[i]))
{
printf("literal: %c\n",buf[i]);
break;
}
else if(buf[i]==')'||buf[i]=='('||buf[i]=='{' || buf[i] == '}' || buf[i] == '+'||buf[i] == '-'||buf[i]=='*' || buf [i] == '/'||buf[i] == '=')
{
printf("operator: %c\n",buf[i]);
break;
}
else
{
temp = buf[i];
}
}while(buf[i++] != '\n');
if(buf[i]=='"')
{
if(e_failure == s_n_literals(buf))
{
fprintf(stderr,"s_n_literals not found\n");
}
}
if(buf[i] == '\0')
{
#if 0
if(e_failure == keyword(iden))
{
fprintf(stderr,"keyword not found\n");
}
#endif
/*if(e_failure == variable(iden))
{
fprintf(stderr,"keyword not found\n");
}*/
}
if(e_failure == operators(&temp))
{
fprintf(stderr,"operator not found\n");
}
if(e_failure == literals(&temp))
{
fprintf(stderr,"Literals not found\n");
}
return e_success;
}
status s_n_literals(char *buf)
{
int i=0;
if(buf[i++] == '"');
if(buf[i]>='a'|| buf[i]<='z'|| buf[i] <= 'A' || buf[i] >= 'Z' ||buf[i]<='0'||buf[i]>= '9')
{
printf("s_n_literals: %s\n",buf);
}
}
status keyword( char *buf)
{
char key[32][10]={"auto", "break","case ", "char", "const","continue","deafult","do","int","long","register","return","short","signed","sizeof","static","struct","switch","typedef","union","unsigned","void","volatile","while","double","else","enum","extern", "float","for","goto"};
int i=0;
if(buf[0] == '\0')
return e_success;
for(i=0;i<32;i++)
{
if(0 == strcmp(buf,key[i]))
{
printf("keyword: %s\n",key[i]);
}
}
return e_success;
}
status variable( char *buf)
{
if (buf[0] == '\0')
return e_success;
char key[32][10]={"auto", "break","case ", "char", "const","continue","deafult","do","int","long","register","return","short","signed","sizeof","static","struct","switch","typedef","union","unsigned","void","volatile","while","double","else","enum","extern", "float","for","goto", "if"};
int i=0;
int count=2;
for(i=0;i<32;i++)
{
if(count= strcmp(buf,key[i]));
if(count == 0)
{
return e_success;
}
}
if(count != 0)
printf("identifier: %s\n",buf);
}
/*status identifier( char *buf)
{
char key[3][10]={"main","printf","scanf"};
int i=0;
for(i=0;i<3;i++)
{
if(0 == strcmp(buf,key[i]))
{
printf("identifier: %s\n",key[i]);
}
}
return e_success;
}*/
status operators( char *buf)
{
char key[5][10]={"(",")","{","}","="};
char str[2];
str[0]=*buf;
str[1]='\0';
int i;
for(i=0;i<5;i++)
{
if(0 == strcmp(str,key[i]))
{
printf("operator: %s\n",key[i]);
}
}
*buf='a';
return e_success;
}
status literals( char *buf)
{
char key[5][10]={"0","1","2","3","4"};
char str[2];
str[0]=*buf;
str[1]='\0';
int i;
for(i=0;i<5;i++)
{
if(0 == strcmp(str,key[i]))
{
printf("literals: %s\n",key[i]);
}
}
*buf = 'a';
return e_success;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main () {
/* greeting */
printf("hi\n");
/* farewell */
printf("bye\n");
/* all went well */
exit(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "tipusok.h"
#include "econio.h"
#include "start.h"
#if defined(WIN32) || defined(_WIN32)
#include <windows.h>
#endif
int main()
{
#if defined(WIN32) || defined(_WIN32)
SetConsoleCP(1250);
SetConsoleOutputCP(1250);
#endif
printf("Hello world!\n");
int v;
while(1)
{
draw_menu();
scanf("%d",&v);
switch(v)
{
case 1: /* Keress megnevezs alapjn! */
break;
case 2: /* Listzs dtum alapjn! */
break;
case 3: /* Bejegyzs mdstsa/trlse */
break;
case 4: /* Adatok betltse/mentse */
break;
case 5: /* Kilps a programbl */
exit(0);
break;
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
}*front = NULL, *rear = NULL;
int isEmpty()
{
if(front == NULL)
{
return 1;
}
else
{
return 0;
}
}
void insert(int item)
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
if(temp == NULL)
{
printf("Queue is not Allocated\n");
return;
}
temp->data = item;
temp->link = NULL;
if(front == NULL)
{
front = temp;
}
else
{
rear->link = temp;
}
rear = temp;
}
int delete_node()
{
struct node *temp;
int item;
if(isEmpty())
{
printf("Queue is Empty\n");
exit(1);
}
temp = front;
item = temp->data;
front = front->link;
free(temp);
return item;
}
int front()
{
if(isEmpty())
{
printf("Queue is Empty\n");
exit(1);
}
return front->data;
}
void display()
{
struct node *ptr;
if(isEmpty())
{
printf("Queue is Empty\n");
return;
}
printf("Queue Elements (or Nodes):\n");
for(ptr = front; ptr != NULL; ptr = ptr->link)
{
printf("%d ", ptr->data);
}
printf("\n\n");
}
int main()
{
int option, item;
while(1)
{
printf("1. Insert an Element in the Queue\n");
printf("2. Delete an Element from the Queue\n");
printf("3. Display Element at the Front position\n");
printf("4. Display All Elements of the queue\n");
printf("5. Exit\n");
printf("Enter your option:\t");
scanf("%d", &option);
switch(option)
{
case 1:
printf("Enter the Element to Add in Queue:\t");
scanf("%d", &item);
insert(item);
break;
case 2:
printf("The Deleted Element from the Queue:\t%d\n", delete_node());
break;
case 3:
printf("Element at the Front:\t%d\n", front());
break;
case 4:
display();
break;
case 5:
exit(1);
default:
printf("Wrong option\n");
}
}
return 0;
}
|
C
|
/*
Uri 1018 - Cedulas
Autor: Carlos Henrique Silva Correia de Araujo
Aluno de Engenharia de Computacao - UFPB (1° Semestre)
*/
#include <stdio.h>
int main(void){
int valor, notas, resto;
scanf("%d", &valor);
printf("%d\n", valor);
notas = valor / 100;
valor = valor % 100;
printf("%d nota(s) de R$ 100,00\n", notas);
notas = valor / 50;
valor = valor % 50;
printf("%d nota(s) de R$ 50,00\n", notas);
notas = valor / 20;
valor = valor % 20;
printf("%d nota(s) de R$ 20,00\n", notas);
notas = valor / 10;
valor = valor % 10;
printf("%d nota(s) de R$ 10,00\n", notas);
notas = valor / 5;
valor = valor % 5;
printf("%d nota(s) de R$ 5,00\n", notas);
notas = valor / 2;
valor = valor % 2;
printf("%d nota(s) de R$ 2,00\n", notas);
notas = valor / 1;
valor = valor % 1;
printf("%d nota(s) de R$ 1,00\n", notas);
return 0;
}
|
C
|
#include <stdio.h>
void multiplicar_matrizes(int l1, int c1, int matriz1[][c1], int l2, int c2, int matriz2[][c2])
{
//A matriz produto terá o número de linhas de A e o número de colunas de B
int i,j, produto[l1][c2], ki, kj,aux;
for (ki = 0; ki <= l1; ++ki)
{//primeiro laço para fixar as linhas, percorre a matriz[ki]
for (kj = 0; kj <= c2; ++kj)
{//segundo laço para fixar as colunas, percorre a matriz[kj]
aux=0;
for (i = 0; i <c1; ++i)
{//o i irá percorrer as linhas e colunas de 1 e 2, logo elas serao iguais
//tanto faz colocar l1 ou c2;
aux = aux+(matriz1[ki][i]*matriz2[i][kj]);
//o aux irá receber ele mesmo mais a resolucao do produto por matriz;
//aux ira armazenar os resultados e joga-los na matriz produto;
}
produto[ki][kj] = aux;
}
}
printf("O resultado do produto é:\n");
for (i = 0; i < l1; ++i)
{
for (j = 0; j < c2; ++j)
{
printf("%d ", produto[i][j]);
}
printf("\n");
}
}
int main()
{//o programa ira definir o produto de duas funcoes;
printf("Observação, só é possivel efetuar o produto se\n");
printf("numero de colunas da primeira matriz for igual ao numero de linhas da segunda matriz.\n");
printf("\n");
int l1, c1, l2, c2, i, j;
printf("Insira o numero de linhas e colunas da primeira matriz:\n");
scanf("%d %d", &l1, &c1);
printf("Agora insira o numero de linhas e colunas da segunda matriz:\n");
scanf("%d %d", &l2, &c2);
int matriz1[l1][c1], matriz2[l2][c2];
if (c1!=l2)
{
printf("Nâo é possivel efetuar o produto, pois o numero de colunas e o numero de linhas nao batem.\n");
return 0;
}
else
{
printf("Insira a matriz um:\n");
for (i = 0; i < l1; ++i)
{
for (j = 0; j < c1; ++j)
{
scanf("%d", &matriz1[i][j]);
}
}
printf("Insira a matriz dois:\n");
for (i = 0; i < l2; ++i)
{
for (j = 0; j < c2; ++j)
{
scanf("%d", &matriz2[i][j]);
}
}
multiplicar_matrizes(l1,c1, matriz1, l2,c2,matriz2);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*
BUT Ecrire un programme en C qui dtermine la nime valeur 'un', 'n' fournit par l'utilisateur de la suite de fibonacci
ENTREE Le numero de la Nieme valeur rechercher
SORTIE La la Nieme valeur
*/
int main()
{
int nPremierNombre=0,nSecondNombre=1,nMem=0,nNiemeValeur=0,nCpt=0;
printf("Entrez la nieme valeur : ");
scanf("%i",&nNiemeValeur);
if(nNiemeValeur==0){
printf("Le resultat est : %i",nPremierNombre);
}else if(nNiemeValeur==1){
printf("Le resultat est : %i",nSecondNombre);
}else{
for(nCpt=2;nCpt<=nNiemeValeur;nCpt++){
nMem=nPremierNombre+nSecondNombre; //calcul de la valeur
nPremierNombre=nSecondNombre; //sauvegarde de la valeur prcdente dans nombre premier
nSecondNombre=nMem; //enregistrement du resultat dans nombre second
}
printf("Le resultat est : %i",nSecondNombre);
}
return 0;
}
|
C
|
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc<2){
printf("Please provide at least one hostname\n");
exit(0);
}
struct addrinfo hints;
struct addrinfo *ai0, *ai;
int i;
char* hostname;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC; // unspecified protocol both v4/6 okay
hints.ai_socktype = SOCK_STREAM; // TCP socket
for (int count=1; count < argc; count++)
{
// each hostname from commandline
hostname = argv[count];
// DNSlookup
if ((i= getaddrinfo(hostname, "80", &hints, &ai0))!=0)
{
printf("Error: unable to lookup IP address: %s", gai_strerror(i));
}
// ai0 head pointer, ai pointer used to iterate the linked list
for (ai = ai0; ai!=NULL; ai= ai->ai_next)
{
if(ai->ai_family==AF_INET){
// IPV4 type
char ip_addr[INET_ADDRSTRLEN];
struct sockaddr_in *infov4 = (struct sockaddr_in *) ai->ai_addr;
inet_ntop(AF_INET, &infov4->sin_addr, ip_addr, sizeof(ip_addr));
// print out the information for each ip node
// hostname, address type, IP addr
printf("%s IPv4 %s \n", argv[count], ip_addr);
} else {
// IPV6 type
char ip_addr[INET6_ADDRSTRLEN];
struct sockaddr_in6 *infov6 = (struct sockaddr_in6 *) ai->ai_addr;
inet_ntop(AF_INET6, &infov6->sin6_addr, ip_addr, sizeof(ip_addr));
// print out the information for each ip node
// hostname, address type, IP addr
printf("%s IPv6 %s \n", argv[count], ip_addr);
}
}
}
return 0;
}
|
C
|
#include <unistd.h>
#include <stdio.h>
int main(int argc, char**argv) {
char mesg[50];
while(1) {
ssize_t bytes_read = read( 0, mesg, sizeof(mesg) );
//write( 1, mesg, bytes_read );
if(bytes_read == 0) {
return 0;
}
mesg[bytes_read] = '\0';
puts(mesg);
}
return 0;
}
|
C
|
/**
* @file actor.h
*
* @brief file containing actor system for animation control
*/
#ifndef __ACTOR__
#define __ACTOR__
#include "types.h"
/**
* @brief defines the animation types
*/
typedef enum
{
ANIM_NO = 0,
ANIM_PASS = 1,
ANIM_LOOP = 2,
ANIM_OSCI = 3
}Anim_Type;
/**
* @brief defines the Actor struct for animation handling
*/
typedef struct
{
int inuse; /**< determines if the actor is being used */
int done; /**< determines if the actor is finish being player */
char action[ TYPE_NAME_LEN ]; /**< the action the actor does */
int numFrames; /**< the number of frames the actor uses */
int frame; /**< the current frame the actor is on */
int frameRate; /**< how often the animation updates */
int animStart; /**< the frame to start on */
int animEnd; /**< the frame to end on */
int direction; /**< the direction the animation is being player */
int type; /**< the Anim_Type the actor is */
}Actor;
/**
* @brief creates a new actor
*
* @param filename the file name and path of the actor
*
* @return a pointer to the newly created actor
*/
Actor *NewActor( char *filename );
/**
* @brief updates the actor
*
* @param actor the actor to use
*
* @return the current frame of the animation
*/
int UseActor( Actor *actor );
/**
* @brief resets an actor
*/
void ResetActor( Actor *actor );
#endif
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int select;
int iq,mathss,english;
char ans='y';
long sum;
int exit;
int a,b,c;
clrscr();
printf("\t\t***Aptitude Test***\n");
printf("1.IQ\n2.English\n3.General knowledge\n4.Exit\n");
printf("Press Any number to skip :");
scanf("%d",&select);
switch(select)
{
case 1:
do{
printf("what number does computer understand\n");
printf("\t1.0 and 1\n\t2.1 and 2\n\t3.0 and 0\n\t 4.none of these\n");
scanf("%d",&iq);
if(iq==1)
sum+=10;
printf("Press y for second question?\n");
ans=getch();
break;
}while (ans=='y'|| ans=='Y');
case 2:
do{
printf("What is the name of country which has a river in two shade :\n");
printf("\t1.Pakistan\n\t2.India\n\t3.africa\n\t 4.none of these\n");
scanf("%d",english);
if(english==3)
sum+=10;
printf("Press y for third question :\n");
ans=getch();
break;
}while (ans=='y'|| ans=='Y');
case 3:
printf("What will the answer of 0x0x2x0 :");
printf("\t1.10\n\t2.20\n\t3.30\n\t 4.none of these\n");
scanf("%d",&mathss);
if(mathss==2)
sum+=10;
break;
}/*Switch*/
printf("press 4 for exit");
scanf("%d",exit);
printf("sum is %d",sum);
getch();
}
|
C
|
#include <stdio.h>
/*
Faça um programa em C para converter graus Celsius para Fahrenheit.
Seu programa deve ler o valor em Celsius, calcular e imprimir o correspondente e, Fahrenheit.
Fórmula: F = C × 1,8 + 32
*/
int main()
{
float celsius, fah;
printf("\nEntre com temperatura em Celsius:");
scanf("%f", &celsius);
fah = celsius*1.8 + 32;
printf ("\nTemperatura convertida para Fahreinheit=%.2f", fah);
return 0;
}
|
C
|
#ifndef GIT_CHAT_RUN_COMMAND_H
#define GIT_CHAT_RUN_COMMAND_H
#include <sys/types.h>
#include "argv-array.h"
#include "str-array.h"
#include "strbuf.h"
/**
* run-command api
*
* The run-command api provides an interface for executing programs and shell
* commands as child processes, manipulating their standard streams and capturing
* their output for external processing.
*
* Internally, run-command fork()s the current process and execve()s the executable
* as a child process.
*
*
* `child_process_def` Data Structure:
* . pid_t pid
* The process id for the child process that was forked from the current process.
* This property has no real external usefulness, and is only used by run_command()
* and capture_command().
* . dir
* The directory from which the executable should be run. This buffer should be
* statically allocated, since it will not be free()d by child_process_def_release.
* . executable
* Name or full path to the executable that is to be run.
* . args
* The arguments passed to the executable.
* . env
* A list of environment variables that will be passed to the child process.
* Variables must have the form "key=value".
* . git_cmd
* If true, `git` is used as the executable.
* . use_shell
* Run the executable through '/bin/sh -c'.
* . std_fd_info
* Set of flags that indicate how the child process std streams should behave.
* Flags are bitwise OR'ed.
* . in_fd
* If STDIN_PROVISIONED, should be the fd pair for a pipe
* . out_fd
* If STDOUT_PROVISIONED, should be the fd pair for a pipe
* . err_fd
* If STDERR_PROVISIONED, should be the fd pair for a pipe
*
*
* Managing Standard Streams:
* Each standard stream has three modes: INHERITED, PROVISIONED, and NULL.
*
* - If INHERITED, the child process will inherit the standard streams from the parent
* process.
* - If PROVISIONED, the standard streams are redirected to the file
* descriptors in the child_process_def structure (in_fd, out_fd, err_fd).
* - If NULL, the standard streams for the child process are redirected to/from /dev/null.
* */
#define STDIN_INHERITED (1 << 0)
#define STDIN_PROVISIONED (1 << 1)
#define STDIN_NULL (1 << 2)
#define STDOUT_INHERITED (1 << 4)
#define STDOUT_PROVISIONED (1 << 5)
#define STDOUT_NULL (1 << 6)
#define STDERR_INHERITED (1 << 8)
#define STDERR_PROVISIONED (1 << 9)
#define STDERR_NULL (1 << 10)
struct child_process_def_internal {
int notify_pipe[2];
};
struct child_process_def {
pid_t pid;
const char *dir;
const char *executable;
struct argv_array args;
struct str_array env;
unsigned int git_cmd: 1;
unsigned int use_shell: 1;
unsigned int std_fd_info;
int in_fd[2];
int out_fd[2];
int err_fd[2];
struct child_process_def_internal internals;
};
/**
* Initialize a child_process_def to default values. After use, the child_process_def
* should be child_process_def_release()d.
* */
void child_process_def_init(struct child_process_def *cmd);
/**
* Set the stdin flag without changing the stdout or stderr flags.
* */
void child_process_def_stdin(struct child_process_def *cmd, unsigned int flag);
/**
* Set the stdout flag without changing the stdin or stderr flags.
* */
void child_process_def_stdout(struct child_process_def *cmd, unsigned int flag);
/**
* Set the stderr flag without changing the stdin or stdout flags.
* */
void child_process_def_stderr(struct child_process_def *cmd, unsigned int flag);
/**
* Release any resources tracked under a child_process_def.
*
* If any pipes were provisioned, they must be closed manually by the caller since
* this child_process_def_release() will not close them.
* */
void child_process_def_release(struct child_process_def *cmd);
/**
* Run an executable, as described by the child_process_def, but wait for the
* child process to terminate.
*
* The child process will inherit all standard streams from the parent process,
* however this can be manipulated in the child_process_def.
*
* This function must only be used when standard streams are inherited or null;
* using provisioned streams can cause this function to block indefinitely if the
* pipe to/from the child process has been filled.
*
* Returns the exit status of the command.
* */
int run_command(struct child_process_def *cmd);
/**
* Run an executable, as described by the child_process_def, and return the pid
* of the child process. This is primarily used to run executables with provisioned
* standard streams.
*
* After start_command() is invoked, the finish_command() function should be
* called after the standard streams are written to or read from to close any
* open pipes.
* */
int start_command(struct child_process_def *cmd);
/**
* Finish running a command by waiting for the child process to exit. Once the
* child process has terminated, closes any open pipes, and returns the exit
* status of the child process.
*
* Note that the caller must manually close any provisioned pipes.
* */
int finish_command(struct child_process_def *cmd);
/**
* Run a command, as described by the child_process_def, but capture the command
* stdout to the given strbuf.
*
* All other standard streams will be inherited from the parent process.
*
* Returns the exit status of the command.
* */
int capture_command(struct child_process_def *cmd, struct strbuf *buffer);
#endif //GIT_CHAT_RUN_COMMAND_H
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 5;
printf("Tipo inteiro\n");
printf("Conteudo %d\n", x);
// Impresso do endereo
printf("Endereo %p\n", &x);
// Impresso da quantidade de bytes ocupada
printf("Qtd bytes: %d\n\n\n", sizeof(x));
float y = 6.5;
printf("Tipo real float\n");
printf("Conteudo %f\n", y);
// Impresso do endereo
printf("Endereo %p\n", &y);
// Impresso da quantidade de bytes ocupada
printf("Qtd bytes: %d\n\n\n", sizeof(y));
double z = 7.689245275;
printf("Tipo real double\n");
printf("Conteudo %.9f\n", z);
// Impresso do endereo
printf("Endereo %p\n", &z);
// Impresso da quantidade de bytes ocupada
printf("Qtd bytes: %d\n\n\n", sizeof(z));
char c = 'A';
printf("Tipo caractere\n");
printf("Conteudo %c\n", c);
// Impresso do endereo
printf("Endereo %p\n", &c);
// Impresso da quantidade de bytes ocupada
printf("Qtd bytes: %d\n\n\n", sizeof(c));
double e = 666.66;
printf("Tipo real double\n");
printf("Conteudo %.9f\n", e);
// Impresso do endereo
printf("Endereo %p\n", &e);
// Impresso da quantidade de bytes ocupada
printf("Qtd bytes: %d\n\n\n", sizeof(e));
int d = 18;
printf("Tipo inteiro\n");
printf("Conteudo %d\n", d);
// Impresso do endereo
printf("Endereo %p\n", &d);
// Impresso da quantidade de bytes ocupada
printf("Qtd bytes: %d\n\n\n", sizeof(d));
struct Cliente {
int codigo;
char status;
double renda;
};
struct Cliente cli;
cli.codigo = 10;
cli.status = 'I';
cli.renda = 2000.0;
printf("Endereco de cli: %p\n", &cli);
printf("Qtd bytes cli: %d\n", sizeof(cli));
printf("\n");
printf("Campo cli.codigo\n");
printf("Conteudo: %d\n", cli.codigo);
printf("Endereco: %p\n", &(cli.codigo));
printf("Quantidade de Bytes: %d\n\n\n", sizeof(cli.codigo));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define p printf
int len(char *stream)
{
int co=0;
while (*stream)
{
++stream;
co += 1;
}
return co; /*including null character*/
}
void key_seg(char *key)
{
int i;
for (i=0; i<len(key) - 1; i++)
{
if (48 <= key[i] <= 57)
{
key[i] = key[i] - 48;
}
else if (65 <= key[i] <= 90)
{
key[i] = key[i] - 65 + 10; /*'A' is 10*/
}
else /*not needed actually, put your remarks*/
{
key[i] = key[i] - 97 + 10; /*"a" is also treated as A*/
}
}
}
void binkey(char *key_in, int *f_key)
{
int i, j, ind, co = 0;
int temp[4];
int mask;
for (i =0; i<len(key_in)-1; i++)
{
mask = 4 << 1; /* 100 */
j = 0;
while (mask>0)
{
temp[j] = (((int)key_in[i] & mask) > 0 );
mask = mask >> 1; /* move the bit down */
j++;
}
for (j = 0; j < 4; j++)
{
f_key[co + j] = temp[j];
}
co += 4;
}
}
int main()
{
char key_in[17];
int f_key[64], i;
puts("put the key");
fgets(key_in, 17, stdin);
key_seg(key_in); /*convert alphabets to numbers*/
binkey(key_in, f_key); /*convert them to binary*/
for (i=0; i<64; i++)
{
p("%d", f_key[i]); /*put and 16 numbers in the fgets() for 64 else, instead of 64 put = numbers entered * 4*/
}
return 0;
}
|
C
|
#pragma once
#include <common_types.h>
#include <limits.h>
#include <openssl/ssl.h>
#include <unistd.h>
static const ErrorCode ERROR_INVALIDATED_SSL = 1;
// Must be a multiple of 8 due to struct packing
#define NODE_SIZE (0x1000)
/*
Represents a (node of a) potentially infinitely-long string that gets read
from a pipe/socket/etc.
String gets read in small blocks, which can then be coalesced into a single
string. In typical linked-list fashion, a NULL value for next indicates the
end of the string.
*/
typedef struct StreamedStringNode {
Char data [NODE_SIZE - sizeof(struct StreamedStringNode*) - sizeof(Size)];
struct StreamedStringNode* next;
Size size;
} StreamedStringNode;
/*
Represents a potentially infinitely-long string that gets read from a pipe/
socket/etc.
IMPORTANT: Any function that uses StreamedStrings should be very aware of the
memory layout. The string itself holds the head's data instead of a pointer to
(hopefully) improve performance.
Most requests should be less than NODE_SIZE, so ideally
multiple nodes won't have to be used. This means that the majority of strings
can be statically allocated - so just create the space needed on the stack and
dynamically allocate subsequent nodes as needed.
One caveat, though, is that any method that takes a StreamedString as a param
should probably take a pointer to it instead, as the SreamedString type itself
can be quite large. (Probably not unreasonably large for a modern computer,
but just a precaution).
*/
typedef struct {
StreamedStringNode head;
} StreamedString;
/*
Read in a string from a stream, returning an error if necessary.
Does not cap the size of the resulting string.
Writes back to the given string.
If this function errors, then this function will free the memory that has been
created so far before exiting - the caller does not have to.
*/
ErrorCode read_streamed_string(FileDescriptor stream, StreamedString* string);
/*
Read in a string from an encrypted SSL stream, returning an error if necessary.
Does not cap the size of the resulting string.
Writes back to the given string.
If this function errors, then this function will free the memory that has been
created so far before exiting - the caller does not have to.
*/
ErrorCode read_ssl_streamed_string(SSL* ssl, StreamedString* string);
/*
Free the memory allocated to a streamed string.
It is assumed that the head node has not been dynamically allocated.
*/
Void free_streamed_string(StreamedString* string);
|
C
|
/*
Single Author info:
hmajety Hari Krishna Majety
Group info:
hmajety Hari Krishna Majety
srout Sweta Rout
mreddy2 Harshavardhan Reddy Muppidi
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include "my_mpi.h"
char *numToString(int num, char *str)
{
if(str == NULL)
{
return NULL;
}
sprintf(str, "%d", num);
return str;
}
int MPI_Comm_rank(MPI_Comm comm, int *rank)
{
*rank = comm.rank;
return 0;
}
int MPI_Comm_size(MPI_Comm comm, int *size)
{
*size = comm.size;
return 0;
}
int createSocket(int rank,int gather){
struct sockaddr_in serv_addr, my_addr;
int sock = socket(AF_INET, SOCK_STREAM, 0); //Create socket
if(sock==-1)
{
printf("Error in creating the socket\n" );
exit(0);
}
int on = 1;
setsockopt(sock, SOL_SOCKET,SO_REUSEADDR, &on, sizeof(on)); // Set socket to reuse same address
fflush(stdin);
bzero((char *) &serv_addr, sizeof(serv_addr));
unsigned short portno = 0;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = 0;
if (bind(sock, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0){ //Configure the socket to a port
printf("Bind Failed!\n" );
exit(0);
}
listen(sock,5); // Listening for connections
int len = sizeof(my_addr);
if(getsockname(sock, (struct sockaddr *) &my_addr, &len)<0){ // Get the port number assigned to the socket
printf("Error getting socket info\n" );
exit(0);
}
char fname[20];
numToString(MPI_COMM_WORLD.rank,fname);
if(gather == 1){
strcat(fname,"gather.txt");
}else if(gather == 2){
strcat(fname,"gather1.txt");
}else{
strcat(fname,".txt");
}
int myPort = ntohs(my_addr.sin_port);
FILE *file = fopen(fname, "w");
fprintf(file, "%d",myPort); //Write the port number to a file
fclose(file);
return sock;
}
int MPI_Init(int *argc, char **argv[] )
{
int n;
char **argv_param = *argv;
fflush(stdin);
struct sockaddr_in serv_addr;
int numProc = atoi(argv_param[3]);
MPI_COMM_WORLD.size = numProc; // Read the num of nodes participating parameter passed as command line argument
MPI_COMM_WORLD.rank = atoi(argv_param[1]); //Read in the rank of the node
strcpy(MPI_COMM_WORLD.myHostName,argv_param[4]); // Read the node name passed
MPI_COMM_WORLD.gather = 0;
MPI_COMM_WORLD.hostList = (char **)malloc(numProc * sizeof(char*)); //Allocate memory for fetching node names
char* host = (char *)malloc(numProc * MAXNAMELEN * sizeof(char));
for(int i = 0; i <numProc; i++){
MPI_COMM_WORLD.hostList[i] = &host[i * MAXNAMELEN];
}
fflush(stdin);
strcat(argv_param[2],"/nodefile.txt"); //Open file to read the node names
FILE *fp = fopen(argv_param[2], "r");
if(fp == NULL){
printf("No hosts\n");
exit(0);
}
for(int i = 0; i< numProc; i++){
fscanf(fp, "%s", MPI_COMM_WORLD.hostList[i]); //Read node names into an array
}
MPI_COMM_WORLD.sockfd = createSocket(MPI_COMM_WORLD.rank,0); //Create a socket to listen for connections
if(MPI_COMM_WORLD.rank == 0){
MPI_COMM_WORLD.sockfd_gather = createSocket(MPI_COMM_WORLD.rank,1);
MPI_COMM_WORLD.sockfd_gather1 = createSocket(MPI_COMM_WORLD.rank,2);
}else{
MPI_COMM_WORLD.sockfd_gather = -1;
MPI_COMM_WORLD.sockfd_gather1 = -1;
}
return 0;
}
int MPI_Send(void *buf, int count, MPI_Datatype datatype, int dest, int tag,MPI_Comm comm)
{
int receiverPort;
struct hostent *receiver;
struct sockaddr_in client_addr;
FILE *file;
receiver = gethostbyname(comm.hostList[dest]); //Get IP address of the host by it's name
if (receiver == NULL) {
printf("No host %s found\n", comm.hostList[dest]);
exit(0);
}
char fname[30];
numToString(dest,fname);
if(comm.gather == 1 && dest == 0){
// printf("\n gather send \n");
strcat(fname,"gather.txt");
}else if(comm.gather == 2 && dest == 0){
strcat(fname,"gather1.txt");
}else{
strcat(fname,".txt");
}
file = fopen(fname, "r");
while(file == NULL)
{
file = fopen(fname, "r"); // Get the port number the host is listening to.
}
fscanf(file, "%d", &receiverPort);
fclose(file);
bzero((char *) &client_addr, sizeof(client_addr));
client_addr.sin_family = AF_INET;
bcopy( (char *)receiver->h_addr, (char *)&client_addr.sin_addr.s_addr,receiver->h_length);
client_addr.sin_port = htons(receiverPort);
fflush(stdin);
int sendingSocket = socket(AF_INET, SOCK_STREAM, 0); // Create a socket to connect to host
if (sendingSocket < 0) {
printf("Error in creating the socket\n" );
exit(0);
}
int flag = connect(sendingSocket,(struct sockaddr *) &client_addr,sizeof(client_addr)); //Connect to the host
if ( flag < 0) {
printf("Error in connecting to the client\n" );
exit(0);
}
flag = send(sendingSocket,buf,datatype * count,0); //Send the message to the host
if (flag < 0) {
printf("Unable to send to %s from %s\n", comm.hostList[dest],comm.myHostName );
exit(0);
}
fflush(stdin);
return 0;
}
int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status)
{
socklen_t clilen;
struct sockaddr_in cli_addr;
clilen = sizeof(cli_addr);
int newsockfd;
int diff;
if(comm.gather==1 || comm.gather==2){
struct sockaddr_in serv_addr;
struct hostent *server;
// printf("\n gather recv\n");
int sck = (comm.gather == 1)?comm.sockfd_gather:comm.sockfd_gather1;
newsockfd = accept(sck, (struct sockaddr *) &cli_addr , &clilen); //Accept connection on the already created socket during MPI_Init()
int sender,i=0;
while(i<comm.size){
server = gethostbyname(comm.hostList[i]);
bzero((char *) &serv_addr, sizeof(serv_addr));
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
if(serv_addr.sin_addr.s_addr == cli_addr.sin_addr.s_addr ){ //save the client with whom the connection is accepted by the server
sender = i;
break;
}
i++;
}
if(sender!=source)
buf = buf+((sender-source)*count*sizeof(double));
}
else{
newsockfd = accept(comm.sockfd, (struct sockaddr *) &cli_addr , &clilen);
}
if (newsockfd < 0) {
printf("Error accepting connection from %s on %s\n", comm.hostList[source],comm.myHostName );
exit(0);
}
int flag= recv(newsockfd,buf,count*datatype,MSG_WAITALL); //Receive the message
// printf("Size recevide from %d at %u is %d\n",source,buf,flag);
if (flag < 0){
printf("Error receiving from %s on %s\n", comm.hostList[source],comm.myHostName );
exit(0);
}
fflush(stdin);
close(newsockfd); //Close the newly created socket after connection establishment
return 0;
}
int MPI_Gather(void *buf,int count, MPI_Datatype datatype, void *res, int gCount, MPI_Datatype gdatatype,int root, MPI_Comm comm){
// printf("\n gathering \n");
if(comm.rank!=0){
comm.gather = root;
MPI_Send((double*)buf, count, MPI_DOUBLE,0,root, comm);
return 0;
}
int status = 0;
for (int i=1; i<comm.size; i++) {
comm.gather=root;
MPI_Recv(((double*)res)+(i*count),count,MPI_DOUBLE,i,root,comm,&status);
}
return 0;
}
int MPI_Finalize(MPI_Comm comm){
close(comm.sockfd);
if(comm.rank == 0){
close(comm.sockfd_gather);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "experiment.h"
LinkList* CreatList() { //创建链表
LinkList *head;
head = (LinkList*)malloc(sizeof(LinkList));
head->next = NULL;
return head;
}
int Size(LinkList *list) { //求链表的元素个数
LinkList *p = list->next;
int k = 0;
while (p) {
k++;
p = p->next;
}
return k;
}
void Insert(LinkList *list, int k, dataType x) { //在链表1的第k位置插入元素x
if (k<1) exit(1);
LinkList *p = list;
int i = 0;
while (p && i<k-1) {
p = p->next;
i++;
}
if (!p) exit (1);
LinkList *s = (LinkList*)malloc(sizeof(LinkList));
s->data = x;
s->next = p->next;
p->next = s;
}
void Delete(LinkList *list, int k) { //删除链表1的第k个元素
if (k<1) exit (1);
LinkList *p = list;
int i = 0;
while (p->next && i<k-1) {
p = p->next;
i++;
}
if (p->next==NULL) exit(1);
LinkList *q = p->next;
p->next = q->next;
free(q);
}
int Empty(LinkList *list) { //判断链表是否为空
return list->next == NULL;
}
dataType GetData(LinkList *list, int k) { //求链表1的第k个元素的值
if (k<1) exit (1);
LinkList *p = list;
int i = 0;
while (p && i<k) {
p = p->next;
i++;
}
if (!p) exit(1);
return p->data;
}
LinkList* Find(LinkList *list, dataType x) { //在链表1中查找值为x的元素
LinkList *p = list->next;
while (p && p->data!=x)
p = p->next;
return p;
}
void Print(LinkList *list) { //输出链表
LinkList *p = list->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void ClearList (LinkList *list) { //清空链表
LinkList *p, *q;
p = list->next;
while (p) {
q = p;
p = p->next;
free(q);
}
list->next = NULL;
}
|
C
|
/*
* Copyright (c) 2008-2010 Sander van der Burg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[])
{
struct sockaddr_un server_addr;
int sockfd;
char *socket_path = "/tmp/disnix-tcp-proxy.sock";
char line[BUFFER_SIZE];
ssize_t line_size;
/* Create socket */
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if(sockfd < 0)
fprintf(stderr, "Error creating socket\n");
/* Create address struct */
memset(&server_addr, '\0', sizeof(server_addr));
server_addr.sun_family = AF_UNIX;
strcpy(server_addr.sun_path, socket_path);
/* Create connection */
if(connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
fprintf(stderr, "Error connecting to TCP proxy: %s\n", strerror(errno));
/* Retrieve result */
while((line_size = recv(sockfd, line, BUFFER_SIZE - 1, 0)) > 0)
{
line[line_size] = '\0';
printf("%s\n", line);
}
/* Close connection */
close(sockfd);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 10
void bubble_sort(int array[], int length);
void print(int array[]);
int main()
{
int i, buf[10];
srand(time(NULL));
for(i=0; i<10; i++)
{
buf[i] = (long) rand() % 100 + 1;
printf("%3d ", buf[i]);
}
printf("\n");
bubble_sort(buf, 10);
print(buf);
return 0;
}
void bubble_sort(int array[], int length)
{
int i, j;
int next;
for(i = length-1; i>0; i--)
{
for(j=0; j<i; j++)
{
if(array[j] > array[j+1]){
next = array[j];
array[j] = array[j+1];
array[j+1] = next;
}
}
}
}
void print(int array[])
{
int i;
for(i=0; i<MAX; i++)
{
printf("%3d ", array[i]);
}
printf("\n");
}
|
C
|
#include<stdio.h>
void bubblesort(int k[], int n)
{
int i, j, tmp, flag = 1;
for(i=1; i<=n-1 && flag==1; i++){
flag = 0;
for(j=1; j<=n-i; j++){
if(k[j] < k[j+1]){
tmp = k[j+1];
k[j+1] = k[j];
k[j] = tmp;
flag = 1;
}
}
}
}
|
C
|
#include <windows.h>
#include <stdio.h>
#define LECTION_EXAMPLE 1
#define QUANTITY_NEED_ITERATION_PROGRAMM 5
#define TIME_DELAY_PROGRAMM_IN_THOUSANDTH_OF_SECOND 5000
#if LECTION_EXAMPLE
typedef int (*function)(int); //new type that is pointer function for return integer
#endif
int main()
{
int iteration = 0; //counter for exiting the program
HINSTANCE hInst; //handle to the instance (void pointer for differently objects)
do
{
hInst = LoadLibrary("library_1.dll"); //loading the specified module(library.dll) in the program
printf("loaded\n"); //message for clarity about what library loaded
Sleep(TIME_DELAY_PROGRAMM_IN_THOUSANDTH_OF_SECOND); //program execution delay to allow time for the monitor to read the modules(with library.dll)
#if LECTION_EXAMPLE
function pf; //variable for first funtion
function pg; //variable for second funtion
int* pa; //variable for first value
pa=(int*)GetProcAddress(hInst, "value_one"); //extract adress variable "value_one" from dll which it points to hInst
pf=(function)GetProcAddress(hInst, "function_one"); //same as above but for the "function_one"
pg=(function)GetProcAddress(hInst, "function_two"); //same as above but for the "function_two"
printf("%i %i %i\n",*pa,pf(4),pg(5)); //print all gets
#else
FARPROC return_value_one = NULL; //pointer type reterned import function
FARPROC return_function_one = NULL;
FARPROC return_function_two = NULL;
hInst = LoadLibrary("library_1.dll");
return_value_one = GetProcAddress(hInst, "value_one");
return_function_one = GetProcAddress(hInst, "function_one");
return_function_two = GetProcAddress(hInst, "function_two");
printf("1)%i\n", *(int*)return_value_one); //dereferencing pointer for value_one
printf("2)%i\n", return_function_one(4));
printf("3)%i\n", return_function_two(5));
Sleep(5000);
#endif
FreeLibrary(hInst); //unloaded module which points to hInst
printf("unloaded\n"); //message for clarity about what library loaded
Sleep(TIME_DELAY_PROGRAMM_IN_THOUSANDTH_OF_SECOND); //program execution delay to allow time for the monitor to read the modules(without library.dll)
iteration++; //increment iteration
} while(iteration < QUANTITY_NEED_ITERATION_PROGRAMM);
printf("End programm\n");
getch();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void operate1(char *, char *, char *, char *, int, int);//Interval comparison
void operate2(char *, char *, char *, char *, int, int);//Sequence comparison
int main(int argc, char *argv[]){
int arg = argc, start, end;
char filenameA[20], filenameB[20];
if (arg == 1) {
printf("no file inputed");
return 0;
}
if (argv[1][1] == 'c') {
start = (argv[3][0] - '0' + 1);
end = (argv[5][0] - '0' + 1);
strcpy(filenameA,argv[6]);
strcpy(filenameB,argv[7]);
operate1(filenameA,filenameB,"A&B_A.txt","A-B.txt",start,end);//get "A&B_A.txt","A-B.txt"
operate1(filenameB,filenameA,"A&B_B.txt","B-A.txt",end,start);//get "A&B_B.txt","B-A.txt"
}
if (argv[1][1] == 'n') {
start = argv[3][0] - '0' + 1;
end = argv[5][0] - '0' + 1;
strcpy(filenameA,argv[6]);
strcpy(filenameB,argv[7]);
operate2(filenameA,filenameB,"A&B_A.txt","A-B.txt",start,end);//get "A&B_A.txt","A-B.txt"
operate2(filenameB,filenameA,"A&B_B.txt","B-A.txt",end,start);//get "A&B_B.txt","B-A.txt"
}
return 0;
}
void operate1(char *filenamea, char *filenameb, char *target1, char *target2, int start, int end)
{
FILE *fp1, *fp2, *fp3, *fp4;
int i = 0, k = 0, flag = 1, jud = 0, s = start, e = end, jud1, jud2, jud3, jud4;
char a1[50], a2[50], b[500], c1[50], c2[50], d[500];
if ((fp1 = fopen(filenamea,"r")) == NULL) exit(1);
if ((fp2 = fopen(filenameb,"r")) == NULL) exit(1);
if ((fp3 = fopen(target1,"w")) == NULL) exit(1);
if ((fp4 = fopen(target2,"w")) == NULL) exit(1);
while (fgets(b,500,fp1) != NULL){//1
if (b[0] == '#') continue;
while (flag != s){//2
if(b[i] == '\t') flag++;
i++;
}//2
while (flag == s){//3
a1[k++]=b[i++];
a1[k]='\0';
if (b[i] == '\t') flag++;
}//3
k=0;i++;
while (flag == (s+1)){//4
a2[k++]=b[i++];
a2[k]='\0';
if (b[i] == '\t') flag++;
if (b[i] == '\0' || b[i] == '\n') break;
}//4
flag=1; i=0; k=0; jud=0;
while (fgets(d,1000,fp2) != NULL){//5
jud = 0;
if (d[0] == '#') continue;
while (flag != e){//6
if (d[i] == '\t') flag++;
i++;
}//6
while (flag == e){//7
c1[k++]=d[i++];
c1[k]='\0';
if (d[i] == '\t') flag++;
}//7
k=0;i++;
while (flag == (e+1)){//8
c2[k++]=d[i++];
c2[k]='\0';
if (d[i] == '\t') flag++;
if (d[i] == '\0' || d[i] == '\n') break;
}//8
flag=1; i=0; k=0;
jud1=atoi(a1);
jud2=atoi(a2);
jud3=atoi(c1);
jud4=atoi(c2);
if (jud1 <= jud4 && jud3 <= jud2) jud = 1;
if (jud == 1){//9
fputs(b,fp3);
break;
}//9
}//5
if (jud == 0) fputs(b,fp4);
rewind(fp2);
flag=1; i=0; k=0;
}//1
fclose(fp1);
fclose(fp2);
fclose(fp3);
fclose(fp4);
}
void operate2(char *filename1, char *filename2, char *target1, char *target2, int start, int end)//two inputs files two output files two positional parameter
{
FILE *fp5, *fp6, *fp7, *fp8;
int i = 0, k = 0, flag = 1, s = start, e = end, jud = 0;
char A[50]={'\0'}, B[500]={'\0'}, C[50]={'\0'}, D[500]={'\0'};
if ((fp5 = fopen(filename1,"r")) == NULL) exit(1);
if ((fp6 = fopen(filename2,"r")) == NULL) exit(1);
if ((fp7 = fopen(target1,"w")) == NULL) exit(1);
if ((fp8 = fopen(target2,"w")) == NULL) exit(1);
while(fgets(B,500,fp5) != NULL){//1
if (B[0] == '#') continue;
while (flag != s){//2
if (B[i] == '\t') flag++;
i++;
}//2
while (flag == s){//3
if (B[i] == '\t' || B[i] == '\0') {flag++; break;}
A[k++]=B[i++];
A[k]='\0';
if (B[i] == ';' || B[i] == '\t' || B[i] == '\n') break;
}//3
i=0; k=0; flag=1;
while(fgets(D,500,fp6) != NULL){//4
jud=0;
if (D[0] == '#') continue;
while (flag != e) {//5
if (D[i] == '\t') flag++;
i++;
}//5
while (flag == e){//6
if (D[i] == '\t' || D[i] == '\0') flag++;
C[k++]=D[i++];
C[k]='\0';
if (D[i] == ';' || D[i] == '\t' || D[i] == '\n') break;
}//6
if (strstr(C,A)) jud = 1;
if (strstr(A,C)) jud = 1;
if (jud == 1) fputs(B,fp7);
if (jud == 1) break;
i=0; k=0; flag=1;
}
if (jud == 0) fputs(B,fp8);
rewind(fp6);
i=0; k=0; flag=1;
}
fclose(fp5);
fclose(fp6);
fclose(fp7);
fclose(fp8);
}
|
C
|
#include "select.h"
/** \Função que faz a seleção de dados
*
* \param CountryHead -> ponteiro para a head da lista de países
* \param select_data -> Argumento dado pelo utilizador para o tipo de seleção de dados
* \return
*
*/
void select_d(Country* CountryHead, char select_data[12])
{
Country* country = CountryHead;
Week* Change_week = CountryHead->week_head;
while (country != NULL)
{
Change_week = country->week_head;
Week* Save_week = (Week*)calloc(1, sizeof(Week));
while (Change_week != NULL)
{
if (Change_week->week_cases > Save_week->week_cases && strcmp(select_data, "inf") == 0)
{
strcpy(Save_week->n_week, Change_week->n_week);
Save_week->total_cases = Change_week->total_cases;
Save_week->week_cases = Change_week->week_cases;
Save_week->week_cases_ratio = Change_week->week_cases_ratio;
}else if (Change_week->week_cases_ratio > Save_week->week_cases_ratio && strcmp(select_data, "racioinf") == 0)
{
strcpy(Save_week->n_week, Change_week->n_week);
Save_week->total_cases = Change_week->total_cases;
Save_week->week_cases = Change_week->week_cases;
Save_week->week_cases_ratio = Change_week->week_cases_ratio;
}else if (Change_week->week_deaths > Save_week->week_deaths && strcmp(select_data, "dea") == 0)
{
strcpy(Save_week->n_week, Change_week->n_week);
Save_week->total_deaths = Change_week->total_deaths;
Save_week->week_deaths = Change_week->week_deaths;
Save_week->week_deaths_ratio = Change_week->week_deaths_ratio;
}else if (Change_week->week_deaths_ratio > Save_week->week_deaths_ratio && strcmp(select_data, "raciodea") == 0)
{
strcpy(Save_week->n_week, Change_week->n_week);
Save_week->total_deaths = Change_week->total_deaths;
Save_week->week_deaths = Change_week->week_deaths;
Save_week->week_deaths_ratio = Change_week->week_deaths_ratio;
}
Change_week = Change_week->next_week;
}
Change_week = country->week_head;
remove_country_weeks(Change_week);
country->week_head = (Week*)calloc(1, sizeof(Week));
if (strcmp(select_data, "inf") == 0 || strcmp(select_data, "racioinf") == 0)
{
strcpy(country->week_head->n_week, Save_week->n_week);
country->week_head->total_cases = Save_week->total_cases;
country->week_head->week_cases =Save_week->week_cases;
country->week_head->week_cases_ratio = Save_week->week_cases_ratio;
country->week_head->indicator = 1;
}else if (strcmp(select_data, "dea") == 0 || strcmp(select_data, "raciodea") == 0)
{
strcpy(country->week_head->n_week, Save_week->n_week);
country->week_head->total_deaths = Save_week->total_deaths;
country->week_head->week_deaths =Save_week->week_deaths;
country->week_head->week_deaths_ratio = Save_week->week_deaths_ratio;
country->week_head->indicator = 2;
}
country = country->next_country;
free(Save_week);
}
return;
}
|
C
|
//
// repository.c
// Lab4
//
// Created by andreio on 06.03.2017.
// Copyright © 2017 Andrei. All rights reserved.
//
#include <string.h>
#include "repository.h"
#include <stddef.h>
#include <assert.h>
EstateRepo createRepo()
{
EstateRepo v;
v.length = 0;
return v;
}
int find(EstateRepo* v, char address[])
{
//Estate* x = NULL;
for (int i = 0; i < v->length; i++)
{
if (strcmp(v->estate[i].address, address) == 0)
return i;
}
return -1;
}
int add(EstateRepo* v, Estate x)
{
// first search for a estate with the same address as the one that is to be added and do not add it if it already exists
if (find(v, x.address) != -1)
return 0;
v->estate[v->length] = x;
v->length++;
return 1;
}
int delete(EstateRepo* v, char address[30+1])
{
//first search for a estate with the same address as the one that is to be deleted and do not delete it if it doesn't exist
int pos = find(v, address);
if (pos == -1)
return 0;
else
{
for (int i = pos; i < v-> length; i++)
{
v->estate[i]=v->estate[i+1];
}
}
v->length--;
return 1;
}
int update(EstateRepo* v, Estate x)
{
//first search for a estate with the same address as the one that is to be updated and do not update it if it doesn't exist
int pos = find(v, x.address);
if (pos == -1)
return 0;
else
{
v->estate[pos] = x;
}
return 1;
}
int getLength(EstateRepo* v)
{
return v->length;
}
Estate getEstateOnPos(EstateRepo* v, int pos)
{
if (pos < 0 || pos >= v->length)
return createEstate("", "", -1, -1);
return v->estate[pos];
}
// Tests
void initEstateRepoForTests(EstateRepo* v)
{
Estate x = createEstate("house", "calea turzii ", 800,300000 );
add(v, x);
}
void testAdd()
{
Estate x = createEstate("penthouse", "dorobanti", 200, 98000);
EstateRepo v = createRepo();
initEstateRepoForTests(&v);
assert(getLength(&v) == 1);
assert(add(&v, x) == 1);
assert(getLength(&v) == 2);
// now try to add the same estate again -> add must return 0
assert(add(&v, x) == 0);
}
void testEstateRepo()
{
testAdd();
}
|
C
|
#include<string.h>
#include<stdio.h>
int main()
{
char *str=NULL;
str = (char *)malloc(sizeof(char));
printf("enter a string::\n");
gets(str);
int i=0,count=1;
int j;
int l;
l=strlen(str);
for(i=0;i<l;i++)
{
count=1;
for(j=i+1;j<l;j++)
{
if(str[i] == str[j])
{
count++;
str[j]='0';
}
}
if(str[i]!='0')
printf("%c=%d\n",str[i],count);
}
}
|
C
|
#ifndef CHESS_
#define CHESS_
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <SDL/SDL.h>
#include <SDL_image.h>
#include <math.h>
#include <time.h>
/* structs */
struct checker{
char x;
int y;
};
typedef struct checker checker;
struct legalMovesRepository{
int size;
int pos;
char **legalMoves;
};
typedef struct legalMovesRepository legalMovesRepository;
struct treeNode
{
struct treeNode **branch;
int boardValue;
char *move;
int childAmount;
};
typedef struct treeNode treeNode;
/* enums */
typedef enum { BLACK, WHITE } color;
typedef enum { PAWN, KING } rank;
/* macros */
#define OPPOSITE_COLOR(clr) ((clr == WHITE)? BLACK: WHITE)
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#define INF 2147483647
#define WHITE_P 'm'
#define WHITE_B 'b'
#define WHITE_R 'r'
#define WHITE_N 'n'
#define WHITE_Q 'q'
#define WHITE_K 'k'
#define WHITE_TOOL(tool) ((tool==WHITE_P || tool==WHITE_B || tool==WHITE_R || tool==WHITE_N || tool==WHITE_Q || tool==WHITE_K) ? 1:0)
#define BLACK_P 'M'
#define BLACK_B 'B'
#define BLACK_R 'R'
#define BLACK_N 'N'
#define BLACK_Q 'Q'
#define BLACK_K 'K'
#define BLACK_TOOL(tool) ((tool==BLACK_P || tool==BLACK_B || tool==BLACK_R || tool==BLACK_N || tool==BLACK_Q || tool==BLACK_K) ? 1:0)
#define EMPTY ' '
#define SCORE_P 1
#define SCORE_N 3
#define SCORE_B 3
#define SCORE_R 5
#define SCORE_Q 9
#define SCORE_K 400
#define BOARD_SIZE 8
#define STRING_SIZE 50
#define NUM_OF_REPS 20
#define BOARD_SIZE 8
#define MAX_NODES 1000000
#define WRONG_MINIMAX_DEPTH "Wrong value for minimax depth. Value should be between 1 to 4\n"
#define WRONG_GAME_MODE "Wrong game mode\n"
#define WRONG_POSITION "Invalid position on the board\n"
#define NO_DICS "The specified position does not contain your piece\n"
#define ILLEGAL_COMMAND "Illegal command, please try again\n"
#define ILLEGAL_MOVE "Illegal move\n"
#define ILLEGAL_CASTLE "Illegal casteling move\n"
#define NO_ROOK "Wrong position for a rook\n"
#define WROND_BOARD_INITIALIZATION "Wrong board initialization\n"
#define WRONG_FILE "Wrong file name\n"
#define perror_message(func_name) (perror("Error: standard function %s has failed", func_name))
#define print_message(message) (printf("%s", message));
extern treeNode *gameTree;
extern int minimaxDepth;
extern int game_mode;
extern color user_color;
extern int initDepth;
/* methods declaration */
/* board methods */
void print_line();
void print_board_(char board[BOARD_SIZE][BOARD_SIZE]);
void init_board_(char board[BOARD_SIZE][BOARD_SIZE]);
void clear_board(char board[BOARD_SIZE][BOARD_SIZE]);
void copyBoard(char oldBoard[BOARD_SIZE][BOARD_SIZE], char newBoard[BOARD_SIZE][BOARD_SIZE]);
int boardScore(char board[BOARD_SIZE][BOARD_SIZE], color curColor);
int bestBoardScore(char board[BOARD_SIZE][BOARD_SIZE], color curColor);
/* prime methods */
color settings_state(char board[BOARD_SIZE][BOARD_SIZE]);
void game_state(char board[BOARD_SIZE][BOARD_SIZE], color current_player_color);
void user_turn(char board[BOARD_SIZE][BOARD_SIZE], color current_player_color);
void computer_turn(char board[BOARD_SIZE][BOARD_SIZE], color current_player_olor);
void simulateTurn(char oldBoard[BOARD_SIZE][BOARD_SIZE], char* move, char newBoard[BOARD_SIZE][BOARD_SIZE]);
/* moves methods */
void getAllLegalMoves(char board[BOARD_SIZE][BOARD_SIZE], color player_color, legalMovesRepository* rep, int checkThreat, int depthFlag);
void getLegalMoves(char board[BOARD_SIZE][BOARD_SIZE], color player_color, checker srcChkr, legalMovesRepository* rep, int checkThreat);
int underAttack(int i, int j, char board[BOARD_SIZE][BOARD_SIZE], color attacker);
int isKingSafe(char board[BOARD_SIZE][BOARD_SIZE], color c);
int isItLegal( char board[BOARD_SIZE][BOARD_SIZE], char *move, color c);
/* minor helping methods */
int pieceToNum(char c);
checker stringToChecker(char* str);
void substringFromString(char* str, int i, int j, char *cpy);
void convertMoveToString(char* str, checker srcChkr, checker dstChkr);
void convertCheckerToString(char* str, checker chkr);
/* repository methods */
void addPromotionMoveToRep (char *str, legalMovesRepository* rep );
void addMoveToRepository(legalMovesRepository* rep, char* str);
int isItInRepository(legalMovesRepository* rep, char* str);
void freeRepository(legalMovesRepository* repository);
void freeAllRepositories();
void sortRepository(char board[BOARD_SIZE][BOARD_SIZE], legalMovesRepository* rep, color current_player_color, int ascending);
void initArrayOfReps();
int addRepToArrayOfReps(legalMovesRepository* rep);
void removeRepFromArrayOfReps(legalMovesRepository* rep);
/* wrappers*/
void scanfWrapper(int num);
void* allocWrapper(void* ptr, char* allocName);
/* game tree methods */
int getBestScoreBybuildingGameTree(char board[BOARD_SIZE][BOARD_SIZE], int depth, color PlayerA, color currentColor,
char* curMove, treeNode* father, int whichSon, int alpha, int beta, int maximizingPlayer);
void freeTree(treeNode *tree);
char* chooseMove(int bestValue, treeNode *tree, int randomly);
/* file methods */
int saveGame(char board[BOARD_SIZE][BOARD_SIZE], char* filename, color current_player_color);
int loadGame(char board[BOARD_SIZE][BOARD_SIZE], char* filename, color* current_player_color);
/* GUI methods */
SDL_Surface *load_image( char *filename, int transparent ) ;
void apply_surface (int x, int y, SDL_Surface *source, SDL_Surface *destination, SDL_Rect* clip);
void initWindow ();
int guiSplashScreen (char board[BOARD_SIZE][BOARD_SIZE], color* current_player_color_pointer);
void guiLoadScreen (char board[BOARD_SIZE][BOARD_SIZE], color* current_player_color_pointer);
void loadState(char board[BOARD_SIZE][BOARD_SIZE], int state, color* current_player_color_pointer);
void guiSettingsState (char board[BOARD_SIZE][BOARD_SIZE]);
void refresh();
void chooseGameType (char board[BOARD_SIZE][BOARD_SIZE]);
void guiWinMessage(color c, char board[BOARD_SIZE][BOARD_SIZE], color current_color);
char * guiGetMove(char board[BOARD_SIZE][BOARD_SIZE],color current_player_color);
void moveError ();
char * choosePromotion();
void guiCheckMessage (char board[BOARD_SIZE][BOARD_SIZE]);
void saveState (char board[BOARD_SIZE][BOARD_SIZE], color c);
void guiUserTurn (char board[BOARD_SIZE][BOARD_SIZE], color current_player_color);
int guiGetSaveSlot();
/* gui set functions */
void guiSetMainStage (char board[BOARD_SIZE][BOARD_SIZE]);
void setBoard (char board[BOARD_SIZE][BOARD_SIZE], int piecesOnly );
void setBelowBoard(color current_player_color);
void drawSaveScreen ();
void drawLoadScreen ();
#endif
CHESS_
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <windows.h>
#define N 20
void Names(char A[][25],int n)
{
srand(time(0));
int i,j,k;
for(i=0;i<n;i++)
{
k=2*(rand()%10+3); //
for(j=0;j<k;j++)
A[i][j]=rand()%30+176; //
A[i][j]='\0';
}
}
void NameBubble(char A[][25],int n){
for(int i=0;i<n-1;i++){
for(int j=0;j<n-i-1;j++){
if(strcmp(A[j],A[j+1])>0){
char temp[25];
strcpy(temp,A[j]);
strcpy(A[j],A[j+1]);
strcpy(A[j+1],temp);
}
}
}
}
int main(){
char Mname[N][25];
Names(Mname,N);
printf("ǰ\n");
for(int i=0;i<N;i++){
printf("%d:%s\n",i,Mname[i]);
}
NameBubble(Mname,N);
printf("\n\n");
for(int i=0;i<N;i++){
printf("%d:%s\n",i,Mname[i]);
}
system("pause");
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/ptrace.h>
int main()
{
static int i;//静态全局变量,每次运行地址不变
int abc=9527;//临时变量,地址不固定 但是依然有办法修改。用内存扫描工具 scanmem
printf("pid %d\n",getpid());
printf("i=%x abc=%x\n",&i,&abc);
for(i=0;i<10000;i++)
{
printf("i = %d abc = %d\n",i,abc);//让i每10秒自增一次,然后我们用另一个程序对 修改i的值
sleep(10);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "simpleCChatConfig.h"
#ifdef _WIN32
#include <windows.h>
#include "helloWindows.h"
#else
#include <pthread.h>
#include "helloWorld.h"
#endif
int main(){
printf("Version %d.%d.%d\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH);
printf("Hello World!\n");
#ifdef _WIN32
int *thr = malloc(sizeof(*thr));
int *thr2 = malloc(sizeof(*thr2));
*thr = 1;
*thr2 = 2;
HANDLE thread = CreateThread(NULL, 0, windowsThreadFunc, (void *) thr, 0, NULL);
HANDLE thread2 = CreateThread(NULL, 0, windowsThreadFunc, (void *)thr2, 0, NULL);
#else
pthread_t thread1, thread2;
int *thr = malloc(sizeof(*thr));
int *thr2 = malloc(sizeof(*thr2));
*thr = 1;
*thr2 = 2;
if(pthread_create(&thread1, NULL, thread, (void *) thr) != 0){
perror("Error Creating Thread");
exit(1);
}
if(pthread_create(&thread2, NULL, thread, (void *) thr2) != 0){
perror("Error Creating Thread");
exit(1);
}
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
#endif
return 0;
}
|
C
|
/*------------------------------------------------
*------------------------------------------------
* |id : 112 0821 042
* |name : Alim Ul Karim
* |email : alim.karim.nsu@gmail.com
* |course : CSE 115.2
* |blog : http://bit.ly/auk-blog
* |linkedin : http://linkd.in/alim-ul-karim
* |cell : +880-1673-175222
* |cell : +880-1913-500863
*------------------------------------------------
*------------------------------------------------
*/
// hello world
// 012345678910
// st =4 , end =7 print "o wo" , tested works fine. Written by Alim Ul Karim
void substring(char s[] , int start , int end , char return_substr[] ){
int i , r=0 , count = getLen(s) - 1;
if (end < count) {
count = end;
}
if(start >= end) {
return_substr[r] = '\0';
}
for (i = start; i <= count ; i++ )
{
return_substr[r++] = s[i];
}
return_substr[r] = '\0';
}
void show_index_of_chars(char s[])
void copy_from_array(char from[] , char to[]){
char c;
int i = 0;
while(c = from[i++]){
to[i-1] = c;
}
to[i] = '\0';
}
int string_compare(char c1[] , char c2[]){
int a1 = getLen(c1);
int a2 = getLen(c2);
if(a1 == a2){
char c;
int i =0;
while(c=c1[i++]){
if(c != c2[i-1]){
return 0;
}
}
} else {
return 0;
}
return 1;
}
// char des[N] = "MyName(some)";
// //first b:6
// //last bracket:11
// char src[N] = "(source)";
// //01234567
// //source start index : =1 , it means it will start from index 1: s
// //source start index : =7 and it will get the output before 7 index means : e
// string_copy(des,src, 1, 7, 7 , 13);
// printf("output :: |%s|n" , des);
// //output: MyName(source
void string_copy(char destination[] , char source[] , int souce_start = 0 , int source_end = -1 , int dest_start = 0 , int dest_end = -1){
char temp[N];
int i , count ;
//getting count
if(source_end == -1){
count = getLen(source);
} else {
count = source_end ;
}
int r = 0;
for (i = souce_start; i < count ; i++ )
{
temp[r++] = source[i];
}
//ending temp;
temp[r] = '\0';
//getting count
if(dest_end == -1){
count = (r) + dest_start; // becuase count gets from : i < count
} else {
count = dest_end ;
}
r = 0;
for (i = dest_start; i < count ; i++ )
{
destination[i] = temp[r++];
}
//end the destination;
destination[i] = '\0';
}
/* Suppouse we have a input on s = "Hello World"
012345678910
Now we want to put 'C Programming' in middle of the 'o w' so the return of s would be
"Hello C Programming World". To do above , input s ="Hello World" ,
replace = " C Programming " , start = 5 , end = 5;
output = "Hello C Programming World". If end = -1 then it means replace
from the index 5 and then the output would be "Hello C Programming ".
For input start = 5 , end =6; output = "Hello C Programming orld"
*/
void substring_replace(char s[] , char replace[] , int start , int end = -1) {
int replace_count = getLen(replace), i=0;
int whiteSpace_enough = 0;
//if start = end , no remove
//if end =-1 , replace the whole thing from the start index
//if start < end remove chars from those position and insert space for the replace and then put the replace
//printf("\nase\n");
if (replace_count <= 0 || start < 0) return;
replace_count--;
int distance = (end - start);
int con1 = (start == end);
int con2 = (start > 0 && end == -1);
int con3 = (start < end );
int con4 = (distance < replace_count);
int con5 = (distance >= replace_count);
//printf("\ncon1:%d , con2:%d , con3:%d con4:%d con5:%d\n" , con1, con2 , con3 , con4 , con5);
if( con1 ){
//do not remove any .
insert_space(s , start , replace_count + 1);
} else if( con2 ){
//replace the whole replace char from the start index
} else if( con3 && con4 ) {
//remove between char and insert white spaces
for (i = start; i <= end ; i++ )
{
s[i] = ' ';
}
//insert white spaces which are not covert in the top
int whiteSpace_count = replace_count - (end-start) ;
if(whiteSpace_count < 0) whiteSpace_count = whiteSpace_count * -1;
insert_space(s , start , whiteSpace_count);
} else if( con3 && con5 ){
for (i = start; i <= end ; i++ )
{
s[i] = ' ';
}
int whiteSpace_count = replace_count;
if(whiteSpace_count < 0) whiteSpace_count = whiteSpace_count * -1;
insert_space(s , start , whiteSpace_count);
}
int r = 0;
replace_count = getLen(replace) + start;
//printf("s:%d e:%d rcount:%d\n",start , end , replace_count );
for (i = start; i < replace_count ; i++ )
{
s[i] = replace[r++];
//printf("s:%c r:%c , i:%d r:%d\n" , s[i] , replace[r-1] , i , r-1);
}
removeChar_method(s, ' ');
return;
}
void insert_space(char s[] , int pos , int count_space = 1) {
int i , r = 0 , r2 = 0 , r3 = 0, count = getLen(s);
//for instance.
/* If we want to put 3 spaces between "Hello World"
012345678910
and if the index starts from 5 then first we will put
extra boundary with the last index. like "H e l l o W o r l d"
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
*/
char a[N] , c;
int con1 = pos > count;
int con2 = pos < 0;
//printf("con1:%d , con2:%d , con3:%d , loop:%d\n" , con1,con2 ,con3 , loopCon);
if( con1 || con2 ) return ;
while(c = s[r++]) {
i = r-1;
if(i==pos) {
for (r2 = 1 ; r2 <= count_space ; r2++ ) {
a[r3++] = ' ';
}
}
a[r3++] = s[i];
}
a[r3] = '\0';
//printf("output :: |%s|\n" , a);
clean_up_whole_array(s);
copy_from_array(a,s);
return ;
}
|
C
|
#include "../includes/putYesNo.h"
int putYesNo(SDL_Surface *dest, TTF_Font *font, SDL_Color color)
{
SDL_Rect pos;
pos.x = 64;
pos.y = 148;
if (!putFont(font, "Yes", color, dest, &pos))
{
fputs("Error : Can't put yes\n", stderr);
return (0);
}
pos.x += 270;
if (!putFont(font, "No", color, dest, &pos))
{
fputs("Error : Can't put no\n", stderr);
return (0);
}
return (1);
}
|
C
|
/*
* badcnt.c - An improperly synchronized counter program
*/
#include "csapp.h"
void *thread1 (void *vargp); /* Thread routine prototype */
void *thread2 (void *vargp); /* Thread routine prototype */
void *thread3 (void *vargp); /* Thread routine prototype */
/* Global shared variables */
volatile int cnt = 0; /* Counter */
/* Objects declared as volatile are omitted from optimization because their
values can be changed by code outside the scope of current code at any time. */
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char **argv){
int niters;
pthread_t tid1, tid2;
/* Check input argument */
if (argc != 2)
{
printf("usage: %s <niters>\n", argv[0]);
exit(0);
}
printf("thread1\n");
niters = atoi(argv[1]);
/* Create threads and wait for them to finish */
Pthread_create(&tid1, NULL, thread1, &niters);
Pthread_create(&tid2, NULL, thread1, &niters);
Pthread_join(tid1, NULL);
Pthread_join(tid2, NULL);
/* Check result */
if (cnt != (2 * niters))
printf("BOOM! cnt=%d\n", cnt);
else
printf("OK cnt=%d\n", cnt);
cnt = 0;
printf("thread2\n");
niters = atoi(argv[1]);
/* Create threads and wait for them to finish */
Pthread_create(&tid1, NULL, thread2, &niters);
Pthread_create(&tid2, NULL, thread2, &niters);
Pthread_join(tid1, NULL);
Pthread_join(tid2, NULL);
/* Check result */
if (cnt != (2 * niters))
printf("BOOM! cnt=%d\n", cnt);
else
printf("OK cnt=%d\n", cnt);
cnt = 0;
printf("thread3\n");
niters = atoi(argv[1]);
/* Create threads and wait for them to finish */
Pthread_create(&tid1, NULL, thread3, &niters);
Pthread_create(&tid2, NULL, thread3, &niters);
Pthread_join(tid1, NULL);
Pthread_join(tid2, NULL);
/* Check result */
if (cnt != (2 * niters))
printf("BOOM! cnt=%d\n", cnt);
else
printf("OK cnt=%d\n", cnt);
exit(0);
}
/* Thread routine */
void *thread1 (void *vargp){
int i, niters = *((int *)vargp);
for (i = 0; i < niters; i++)
cnt++;
return NULL;
}
/* Thread routine */
void *thread2 (void *vargp){
int i, niters = *((int *)vargp);
for (i = 0; i < niters; i++){
/* protected by mutex */
pthread_mutex_lock (&mutex );
cnt++;
pthread_mutex_unlock (&mutex );
}
return NULL;
}
/* Thread routine */
void *thread3 (void *vargp){
int i, niters = *((int *)vargp);
pthread_mutex_lock (&mutex );
for (i = 0; i < niters; i++){
/* protected by mutex */
cnt++;
}
pthread_mutex_unlock (&mutex );
return NULL;
}
|
C
|
/*
* thermometer.c
*
* Created: 2014-12-20 20:18:18
* Author: rgawron
*/
#include "thermometer.h"
void thermometer_init_adc()
{
// set Aref as AVcc
ADMUX = (1<<REFS0);
ADCSRA = (1<<ADEN) | (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0);
}
uint16_t thermometer_read_adc(uint8_t ch)
{
// select ADC Channel
ADMUX|=ch;
// start single conversion
ADCSRA|=(1<<ADSC);
// wait for conversion to complete
while(!(ADCSRA & (1<<ADIF)));
// clear ADIF
ADCSRA |= (1<<ADIF);
return ADC;
}
int8_t thermometer_get_temperature()
{
// TODO move this somewhere?
thermometer_init_adc();
/* The sensor ads 0.5 to the output, so we need to subtract it.
Assume that the Vcc = 5V.
0V -> 0
5V -> 1024
This gives us:
1V -> 1024 / 5
0.5V -> (1024 / 5) * 0.5 = 102.4
*/
double new = (double)thermometer_read_adc(0) - 102.4;
/* Resolution of the sensor is 0.01V, also 0.01V = 1C (Celsius degree).
We need to normalize the input to be in range of 0-xx Celsius degrees.
0.01V -> (1024 / 5) * 0.01 = 2.048
*/
new /= 2.048;
return (int8_t)new;
}
|
C
|
#include <math.h>
//#ifndef FOURIER_H
//#define FOURIER_H
inline void SWAP(float &a, float &b)
{float dum=a; a=b; b=dum;}
void fft(float* reales, float* imaginarios, int n, int isign) {
int m, i, mmax, istep;
float wtemp,wr,wpr,wpi,wi,theta,tempr,tempi;
int j=0;
// ordenamos con reversed byte order
for (i = 0; i < n; i++) {
if (j > i) {
SWAP(reales[i], reales[j]);
SWAP(imaginarios[i], imaginarios[j]);
}
m = n >> 1;
while (m >= 1 && j >= m) {
j -= m;
m >>= 1;
}
j += m;
}
// fourier propiamente dicho
mmax = 1;
while (n > mmax) {
istep=mmax << 1;
theta=isign*(6.28318530717959/istep);
wtemp=sin(0.5*theta);
wpr = -2.0*wtemp*wtemp;
wpi=sin(theta);
wr=1.0;
wi=0.0;
for (m=0;m<mmax;m++) {
for (i=m;i<n;i+=istep) {
j=i+mmax;
tempr=wr*reales[j]-wi*imaginarios[j];
tempi=wr*imaginarios[j]+wi*reales[j];
reales[j]=reales[i]-tempr;
imaginarios[j]=imaginarios[i]-tempi;
reales[i] += tempr;
imaginarios[i] += tempi;
}
wr=(wtemp=wr)*wpr-wi*wpi+wr;
wi=wi*wpr+wtemp*wpi+wi;
}
mmax=istep;
}
}
//#endif
|
C
|
#ifndef ESCAPE_H
#define ESCAPE_H
#include "compiler.h"
enum base
{
BIN, OCT, DEC, HEX
};
const char *base_to_str(enum base);
/* convert a (wide?) character to an int
* is_wide dictates whether
* 'abc' -> (('a' * 256) + 'b') * 256 + 'c'
* or
* L'abc' -> L'c'
*
* warn: EINVAL ('\z'), E2BIG ('abcde')
* err: EILSEQ (e.g. '\'), ERANGE ('\x100')
*
* *warn and *err must be initialised by the caller
*/
int escape_char(
char *start,
char *limit,
char **end,
int is_wide,
/*nullable*/int *multi,
int *warn,
int *err)
ucc_nonnull((1, 3, 6, 7));
/* convert a single character-as-string to 'char'
* e.g.
* "\xffg" -> 255, end="g"
*
* is_wide dictates whether '\x100' overflows
* (if not, wchar_t max is checked)
*
* *warn and *err must be initialised by the caller
*/
int escape_char_1(
char *start, char **const end,
int is_wide,
int *const warn,
int *const err)
ucc_nonnull();
/*
* Used for parsing integers, given a base
* e.g.
* 0x5315156813,
* '\xff'
* '\321'
* "\1234" <-- applylimit prevents over-reading
* '\1234' <-- !applylimit => error/overflow
*
* *eptr = NULL, on error
*
* limit applies for parsing raw octal literals,
* as opposed to esc-seq
*/
unsigned long long char_seq_to_ullong(
char *s,
char **eptr,
int apply_limit,
enum base mode,
int *const overflow)
ucc_nonnull();
#define isoct(x) ('0' <= (x) && (x) < '8')
#endif
|
C
|
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <mcc/treeset.h>
#include <mcc/typehandlers.h>
void print_treeset(uint16_t* set) {
for (mcc_size_t i = 0; i < mcc_treeset_size(set); ++i)
printf("%d ", set[i]);
}
int main(int argc, char** argv) {
uint16_t count = 14;
uint16_t* set = mcc_treeset_create();
for (int i = 0; i < count; ++i) {
uint16_t val = (17 + i * 39) % 10;
set = mcc_treeset_add(set, val);
printf("Push %d -> ", val);
print_treeset(set);
printf("\n");
}
uint16_t val = 6;
mcc_treeset_remove(set, val);
printf("Set contents (%ld):\n\t", mcc_treeset_size(set));
for (mcc_size_t i = 0; i < mcc_treeset_size(set); ++i)
printf("%d ", set[i]);
printf("\n");
return 0;
}
|
C
|
/*
* Esame del 09/09/2016
*
* (Versione con ARRAY)
*
* Testo dell'esame completo:
* http://dijkstra.di.unipi.it/#/task/LezEsami_2015-2016Esame20160909c1/statement
*/
#include <stdio.h>
#include <stdlib.h>
#define min(a, b) ((a < b) ? a : b)
/*
* Coda di interi.
*/
typedef struct {
int* queue; /* La coda */
int capacity; /* Capacità massima della coda */
int size; /* Numero di elementi attualmente presenti in coda */
} queue_t;
/* Crea e restituisce una nuova coda vuota, con capacità c. */
queue_t* new_queue(int c) {
queue_t* q = malloc(sizeof(queue_t));
q->queue = malloc(c * sizeof(int));
q->capacity = c;
q->size = 0;
return q;
}
/* Inserimento di un elemento in testa.
* Se l'elemento era già presente, la sua vecchia istanza viene cancellata
* spostando tutti gli elementi verso destra, sovrascrivendola.
* Tempo: O(n)
*/
void queue_insert(queue_t* q, int k) {
int tmp1 = q->queue[0]; // Vecchio elemento in testa
int tmp2;
int i;
int inserito = 1;
/* Se il primo elemento della coda è già quello che vogliamo inserire
* possiamo terminare subito senza fare niente.
*/
if(q->size > 0 && q->queue[0] == k)
return;
/* Altrimenti inseriamo k in testa (posizione 0) */
q->queue[0] = k;
/* E spostiamo verso destra tutti gli altri elementi.
* In questo modo rimuoviamo automaticamente la coda.
*/
for(i=1;i<min(q->size+1,q->capacity);i++) {
/* Tramite tmp1 e tmp2 effettuiamo degli scambi progressivi
* fino alla fine della coda.
*/
tmp2 = q->queue[i];
q->queue[i] = tmp1;
if(tmp2 == k) {
/* Se abbiamo trovato k in coda vuol dire che gli elementi
* successivi (cioè più vecchi) non devono essere espulsi
* dal momento che stiamo solo "spostando" k in cima
* e non inserendo un elemento nuovo. Quindi usciamo dal ciclo.
*/
inserito = 0;
break;
}
tmp1 = tmp2;
}
/* Se abbiamo inserito un numero mai inserito finora
* e se la coda non conteneva già il numero massimo di elementi,
* aumentiamo il contatore del numero di elementi in coda.
* (Si noti che questo contatore non diminuisce mai in questo esercizio).
*/
if(inserito && q->size < q->capacity)
q->size++;
}
/* Stampa degli elementi in coda, terminata dal carattere $. */
void print_queue(queue_t* q) {
int i;
for(i=0;i<q->size;i++) {
printf("%i ",q->queue[i]);
}
printf("$\n");
}
int main(void) {
int n;
scanf("%i", &n);
queue_t* queue = new_queue(n);
int op, element;
do {
/* Lettura dell'operazione */
scanf("%i",&op);
switch(op) {
case 1:
/* Lettura dell'elemento da inserire */
scanf("%i", &element);
queue_insert(queue, element);
break;
case 2:
print_queue(queue);
break;
default:
/* Non è necessario fare niente in questo caso */
break;
}
}
while(op != 0);
/* Deallocazione della lista */
free(queue->queue);
free(queue);
}
|
C
|
#pragma once
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "sprawdzanie.h"
#include "wczytaj.h"
#include "osoba.h"
#include "firma.h"
#include "umowa.h"
/// Struktura, ktora zawiera wskazniki do wszystkich baz w programie
///
/// Nie ma mozliwosci edycji bazy danych osob i firm jest ona jedynie w celu ulatwienia obslugi dodawania nowych umow w przypadku powtarzajacych sie osob/firm.
///
/// W momencie usuniecia danej umowy nie jest usuwana dana osoba/firma z bazy danych.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct menu {
/// Glowa listy zawierajacej umowy
struct umowa* glowa;
/// Ogon listy zawierajacej umowy
struct umowa* ogon;
/// Ilosc umow w bazie
int licznik;
/// Glowa listy osob prywatnych
struct osoba* oglowa;
/// Ogon listy osob prywatnych
struct osoba* oogon;
/// Glowa listy firm
struct firma* fglowa;
/// Ogon listy firm
struct firma* fogon;
};
///
/// \brief Ustawienie wszystkich wskaznikow i zmiennych
/// @returns Zwraca nowo utworzona strukture typu menu
///
struct menu* ustaw_menu(); // Ustawienie wszystkich wskaznikow i zmiennych
///
/// \brief Funkcja odpowiedzialna za menu programu
/// @param data Referencja do menu, ktore zawiera glowy wszystkich list
/// @returns Zwraca false, w przypadku checi zakonczenia programu, w innym przypadku true
///
bool pomoc(struct menu** pmenu); // Funkcja odpowiedzialna za menu programu
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Gowne funkcje
///
/// \brief Znajdz umowe po numerze porzadkowym w liscie
/// @param pmenu Referencja do menu, ktore zawiera glowy wszystkich list
/// @param wybor W przypadku gdy wartosc rowna 1, wyswietla informacje na temat danej umowy
/// @returns Zwraca szukany element typu umowa
///
struct umowa** znajdz_umowe (struct menu** pmenu, int wybor); // Znajdz umowy
///
/// \brief Usuwa dana umowe z listy
/// @param pmenu Referencja do menu, ktore zawiera glowy wszystkich list
/// @returns Nic nie zwraca
///
void usun_umowe(struct menu** pmenu); // Usun umowe
///
/// \brief Ustawia stan umowy na zaplacona
/// @param pmenu Referencja do menu, ktore zawiera glowy wszystkich list
/// @returns Nic nie zwraca
///
void zaplac_umowe(struct menu** pmenu); // Zapla umowe
///
/// \brief Pokazuje wszystkie umowy w bazie
/// @param pmenu Referencja do menu, ktore zawiera glowy wszystkich list
/// @returns Nic nie zwraca
///
void pokaz_umowe(struct menu** pmenu); // Pokaz wszystkie umowy w bazie
///
/// \brief Pokazuje wszystkie umowy po aktualnej dacie - historia umow.
/// \brief Wyswietlanie zakonczonych umow, czyli te ktore zawczasu zostaly juz zaplacone, lub sa juz po dacie i zaplacone.
/// \brief Pozwala rozniez wyswietlic te umowy, ktore sa aktualne i do zaplaty
///
/// @param pmenu Referencja do menu, ktore zawiera glowy wszystkich list
/// @param wybor Zmienna, ktora wybiera rodzaj wyswietlania
/// @returns Nic nie zwraca
///
void przedawnione_umowy(struct menu** pmenu, int* wybor); // Pokaz wszystkie umowy po aktualnej dacie - historia umow
// Wyswietlanie zakonczonych umow czyli te ktre zawczasu zostay ju ZAPLACONE, lub sa juz po dacie i ZAPLACONE.
// Pozwala rozniez wyswietlic te umowy, ktore sa aktualne i do zaplaty
///
/// \brief Pokazuje wszystkie niezaplacone umowy po aktualnej dacie
/// @param pmenu Referencja do menu, ktore zawiera glowy wszystkich list
/// @returns Nic nie zwraca
///
void niezaplacone_umowy(struct menu** pmenu); // Pokaz wszystkie niezaplacone umowy po aktualnej dacie.
///
/// \brief Zwalnia pamiec w programie
/// @param pmenu Referencja do menu, ktore zawiera glowy wszystkich list
/// @returns Nic nie zwraca
///
void zwolnij_pamiec(struct menu** pmenu); // Zwalnianie pamieci w programie
|
C
|
#pragma once
#include "SharedHeader.h"
static const XMVECTOR KVectorZero{ XMVectorZero() };
static const XMVECTOR KVectorGreatest{ XMVectorSet(FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX) };
static bool IntersectRaySphere(const XMVECTOR& RayOrigin, const XMVECTOR& RayDirection, float Radius, const XMVECTOR& Center, XMVECTOR* OutPtrT) noexcept
{
XMVECTOR r{ XMVectorSet(Radius, Radius, Radius, 1.0f) };
XMVECTOR CO{ RayOrigin - Center };
XMVECTOR a{ XMVector3Dot(RayDirection, RayDirection) };
XMVECTOR b{ 2.0f * XMVector3Dot(RayDirection, CO) };
XMVECTOR c{ XMVector3Dot(CO, CO) - r * r };
XMVECTOR Discriminant{ b * b - 4.0f * a * c };
if (XMVector3GreaterOrEqual(Discriminant, KVectorZero))
{
XMVECTOR TPlus{ (-b + XMVectorSqrt(Discriminant)) / 2.0f * a };
XMVECTOR TMinus{ (-b - XMVectorSqrt(Discriminant)) / 2.0f * a };
XMVECTOR TResult{ TMinus };
if (XMVector3Less(TResult, KVectorZero)) TResult = TPlus;
if (OutPtrT) *OutPtrT = TResult;
return true;
}
return false;
}
static XMVECTOR CalculateTriangleNormal(const XMVECTOR& TriangleV0, const XMVECTOR& TriangleV1, const XMVECTOR& TriangleV2)
{
XMVECTOR TriangleEdge01{ XMVector3Normalize(TriangleV1 - TriangleV0) };
XMVECTOR TriangleEdge20{ XMVector3Normalize(TriangleV0 - TriangleV2) };
return XMVector3Normalize(XMVector3Cross(TriangleEdge01, -TriangleEdge20));
}
static bool IsPointInTriangle(const XMVECTOR& Point, const XMVECTOR& TriangleV0, const XMVECTOR& TriangleV1, const XMVECTOR& TriangleV2)
{
XMVECTOR TriangleEdge01{ XMVector3Normalize(TriangleV1 - TriangleV0) };
XMVECTOR TriangleEdge12{ XMVector3Normalize(TriangleV2 - TriangleV1) };
XMVECTOR TriangleEdge20{ XMVector3Normalize(TriangleV0 - TriangleV2) };
XMVECTOR TriangleNormal{ XMVector3Normalize(XMVector3Cross(TriangleEdge01, -TriangleEdge20)) };
XMVECTOR PV1{ XMVector3Normalize(TriangleV1 - Point) };
if (XMVector3GreaterOrEqual(XMVector3Dot(XMVector3Cross(PV1, TriangleEdge01), TriangleNormal), KVectorZero))
{
XMVECTOR PV2{ XMVector3Normalize(TriangleV2 - Point) };
if (XMVector3GreaterOrEqual(XMVector3Dot(XMVector3Cross(PV2, TriangleEdge12), TriangleNormal), KVectorZero))
{
XMVECTOR PV0{ XMVector3Normalize(TriangleV0 - Point) };
if (XMVector3GreaterOrEqual(XMVector3Dot(XMVector3Cross(PV0, TriangleEdge20), TriangleNormal), KVectorZero))
{
return true;
}
}
}
return false;
}
static bool IntersectRayPlane(const XMVECTOR& RayOrigin, const XMVECTOR& RayDirection, const XMVECTOR& PlaneP, const XMVECTOR& PlaneN, XMVECTOR* OutPtrT)
{
XMVECTOR PlaneD{ -XMVector3Dot(PlaneP, PlaneN) };
XMVECTOR Numerator{ -XMVector3Dot(RayOrigin, PlaneN) - PlaneD };
XMVECTOR Denominator{ XMVector3Dot(RayDirection, PlaneN) };
XMVECTOR T{ XMVectorDivide(Numerator, Denominator) };
if (XMVector3Greater(T, KVectorZero))
{
if (OutPtrT) *OutPtrT = T;
return true;
}
return false;
}
static bool IntersectRayTriangle(const XMVECTOR& RayOrigin, const XMVECTOR& RayDirection,
const XMVECTOR& TriangleV0, const XMVECTOR& TriangleV1, const XMVECTOR& TriangleV2, XMVECTOR* OutPtrT)
{
XMVECTOR TriangleEdge01{ TriangleV1 - TriangleV0 };
XMVECTOR TriangleEdge02{ TriangleV2 - TriangleV0 };
XMVECTOR TriangleNormal{ XMVector3Cross(TriangleEdge01 , TriangleEdge02) };
XMVECTOR TrianglePlaneD{ -XMVector3Dot(TriangleV0, TriangleNormal) };
XMVECTOR Numerator{ -XMVector3Dot(RayOrigin, TriangleNormal) - TrianglePlaneD };
XMVECTOR Denominator{ XMVector3Dot(RayDirection, TriangleNormal) };
XMVECTOR T{ XMVectorDivide(Numerator, Denominator) };
if (XMVector3Greater(T, KVectorZero))
{
XMVECTOR Point{ RayOrigin + T * RayDirection };
if (IsPointInTriangle(Point, TriangleV0, TriangleV1, TriangleV2))
{
if (OutPtrT) *OutPtrT = T;
return true;
}
}
return false;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** Task 04
** File description:
** Write a function that displays either
** N if the integer passed as parameter is negative, P, if positive or null.
*/
void my_putchar(char c);
int my_isneg(int n)
{
if (n >= 0)
my_putchar('P');
else
my_putchar('N');
my_putchar('\n');
return (0);
}
|
C
|
#include <common.h>
double makeSmall(u32int InBytes, char *out)
{
double Bytes = InBytes;
if(Bytes < 2048){ *out = 'B'; return Bytes; }
if(Bytes < 2048 * 1024){ *out = 'K'; return Bytes/1024; }
*out = 'M'; return ((Bytes/1024)/1024);
}
|
C
|
#ifndef _FTP_H_
#define _FTP_H_
#include <stdlib.h>
#include <stdbool.h>
typedef struct ftp_info {
size_t size;
bool valid;
char *data;
} ftp_info_s;
/**
* INPUT:
* url - URL that cURL is going to get the data from
* OUTPUT:
* ftp - Stores the data of what was received
* RETURN:
* True if data retrieve ok, else false.
* DESCRIPTION:
* Retrieves the data from the given 'url'
*
* **USER IS RESPONSIBLE ON FREEING MEMORY**
**/
bool ftpGet(ftp_info_s *const ftp, const char *const url);
// TODO: Implement a FTP Push
//bool ftpPush(ftp_info_s **ftp, const char *const url);
/**
* INPUT:
* url - URL that cURL is going to get the data from
* save_location - Directory where the image is being saved
* RETURN:
* True if data retrieve ok, else false.
* DESCRIPTION:
* Downloads and saves an image from the 'url'
**/
bool ftpDownloadImage(const char *const url, const char *const save_location);
/**
* DESCRIPTION:
* Destroy the resceived FTP data
**/
void ftpDestroyInfo(ftp_info_s *ftp);
#endif /* _FTP_H_ */
|
C
|
/*
* openGL Rendering functions with minor GLUT involvement
*/
//Includes
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <GL/glut.h> //linux
#include "rendering.h"
#include "keyboard.h"
#include "lorenz.h"
#define GL_GLEXT_PROTOTYPES
//Global Variables
int number_of_points = 10000;
//double *vertex; //= malloc(sizeof(double) * 3); //3 doubles indicate a vertex
//double **points;// = malloc(sizeof(*double) * number_of_points * sizeof(vertex));
/*
* Function called by GLUT to display/render the scene
* original by Willem A. (Vlakkies) Schreuder
*/
void display(){
//double* output = malloc(size*sizeof(double));
//Clear the screen and Z buffer
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
//reset transformations
glLoadIdentity();
//Rotate the desired objects
glRotatef(z_rotation_angle,0.0,0.0,1.0);
//Rotate the desired objects
glRotatef(x_rotation_angle,1.0,0.0,0.0);
//Translate based on scale desired
//Draw the desired objects
//**** TODO -> Optimization could be done here ****
double* vals = getLorenzPoints(number_of_points);
draw3DLine(vals,number_of_points);
//Draw Axis
drawAxis();
//Print Angles;
printAngles();
//Print variables
printVariables();
//Error Check
ErrCheck("display");
//flush and swap buffer
glFlush();
glutSwapBuffers();
}
void draw3DLine(double* values, int size){
int i;
double location[3];
//printf("The first value is %f\n",*values);
glBegin(GL_LINE_STRIP); //should draw N-1 lines based on N vertices
for (i = 0; i < size; i++){
//printf("About to get the vertex location\n");
location[0] = (values[i*3]) * scale;
location[1] = (values[i*3+1]) * scale;
location[2] = (values[i*3+2]) * scale;
//printf("About to draw the vertex\n");
glColor3f(1.0,1.0,0); glVertex3d(location[0],location[1],location[2]);
}
glEnd();
ErrCheck("draw3DLine");
}
void drawAxis(){
//default length
double len = 1.5;
//set color
glColor3f(1,1,1); //white
//Draw the 3 axeses
glBegin(GL_LINES);
glVertex3d(0.0,0.0,0.0);
glVertex3d(len,0.0,0.0);
glVertex3d(0.0,0.0,0.0);
glVertex3d(0.0,len,0.0);
glVertex3d(0.0,0.0,0.0);
glVertex3d(0.0,0.0,len);
glEnd();
//Label Axes
glRasterPos3d(len,0.0,0.0);
Print("X");
glRasterPos3d(0.0,len,0.0);
Print("Y");
glRasterPos3d(0.0,0.0,len);
Print("Z");
ErrCheck("drawAxis");
}
/*
* Used to print out the rotation angles in the bottom left
* Original by Willem A. (Vlakkies) Schreuder
*/
void printAngles(){
//Five pixels from lower left corner of window
glWindowPos2i(5,5);
//Print the text string
Print("Angle=%f,%f",x_rotation_angle,z_rotation_angle);
}
void printVariables(){
//get window size
//int width = glutGet(GLUT_WINDOW_WIDTH);
int height = glutGet(GLUT_WINDOW_HEIGHT);
//Print out the variables in upper left corner
getActiveColor(0);
glWindowPos2i(5,height-15);
Print("Parameter s: %f",lorenz_parameter_s);
getActiveColor(1);
glWindowPos2i(5,height-35);
Print("Parameter b: %f",lorenz_parameter_b);
getActiveColor(2);
glWindowPos2i(5,height-55);
Print("Parameter r: %f",lorenz_parameter_r);
getActiveColor(3);
glWindowPos2i(5,height-75);
Print("Scale Parameter: %f", scale);
getActiveColor(9);
glWindowPos2i(5,height-95);
Print("Insert to toggle parameter to change");
}
void getActiveColor(int v){
if (variable_selector == v){
glColor3f(1.0,0.0,0.0); //set active color as red
}
else{
glColor3f(1.0,1.0,1.0); //set normal color as white
}
}
void drawPyramid(){
//Draw 4 triangles that are Red, Green, Blue, Yellow
//Three side faces (Not an equalateral9pyramid atm)
glBegin(GL_POLYGON);
glColor3f(1.0,0.0,0); glVertex3f(-0.5,0.5,0);
glColor3f(1.0,0.0,0); glVertex3f(0.5,0.5,0);
glColor3f(1.0,0.0,0); glVertex3f(0.0,0.0,0.5);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,1.0,0); glVertex3f(-0.5,0.5,0);
glColor3f(0.0,1.0,0); glVertex3f(0.0,-0.5,0);
glColor3f(0.0,1.0,0); glVertex3f(0.0,0.0,0.5);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,1.0); glVertex3f(0.5,0.5,0);
glColor3f(0.0,0.0,1.0); glVertex3f(0.0,-0.5,0);
glColor3f(0.0,0.0,1.0); glVertex3f(0.0,0.0,0.5);
glEnd();
//Bottom
glBegin(GL_POLYGON);
glColor3f(1.0,1.0,0); glVertex3f(-0.5,0.5,0);
glColor3f(1.0,1.0,0); glVertex3f(0.5,0.5,0);
glColor3f(1.0,1.0,0); glVertex3f(0.0,-0.5,0.0);
glEnd();
ErrCheck("DrawPyramid");
}
/*
* Convenience routine to output raster text
* Use VARARGS to make this more flexible
* Original by Willem A. (Vlakkies) Schreuder
*/
#define LEN 8192 // Maximum length of text string
void Print(const char* format, ...){
char buf[LEN];
char* ch=buf;
va_list args;
// Turn the parameters into a character string
va_start(args,format);
vsnprintf(buf,LEN,format,args);
va_end(args);
// Display the characters one at a time at the current raster position
while (*ch)
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18,*ch++);
}
/*
* GL Basic Error Check Function
* Original by Willem A. (Vlakkies) Schreuder
*/
void ErrCheck(char* where)
{
int err = glGetError();
if (err) fprintf(stderr,"ERROR: %s [%s]\n",gluErrorString(err),where);
}
|
C
|
/*関数
複数の処理をまとめたもの、大体は数学で一般的に使われる関数と同じ*/
#include <stdio.h>
int g = 1;//グローバル変数
float getmax(float a, float b){
if(a >= b){
return a;
}
else{
return b;
/*これは下記のように書くことができこの書き方を三項演算子という
返り値 = (条件)? a:b;
つまり
return = (a>=b)? a :b;
printfなどでも使える
*/
}
}
void Hello(void);
/*関数はどこに書いてもいいがmainより下にあるとエラーになる。
そのためさきにこんな関数があるよと宣言をしておく。これをプロトタイプ宣言という。
大抵はmainより上に書く*/
int main(void){
float result = getmax(2.4 , 8.2);
printf("%f\n",result);
printf("%d\n",g);
Hello();
return 0;
}
void Hello(void){//返り値がない場合はvoid
printf("hello\n");
printf("%d\n",g);
}
/*実行結果 8.2と1とhelloと1が表示される
floatは単精度実数型なので少数を扱える(floatの出力フォーマット指定子は%f)
詳しくはVariable.cを参照
関数の書き方
返り値の型 関数名 (引数のかた 引数名){
処理
return 返り値(戻り値);
})
returnは関数の外に処理結果を渡すのに使われる。渡すものがない場合は0を書く。
0は成功1(0以外)は失敗の意として使われる。
関数の呼び出し
関数名(引数);で呼び出せる。引数はなしでも可
何回でも呼び出せる。上記のソースコードのように
変数 = 関数名(引数);で関数の返り値を変数に代入することができる
変数のスコープ
ある関数内で宣言された変数は基本的には別の関数で使えない。この変数はローカル変数と呼ぶ。
ローカル変数はその関数内でしか使えないため別の関数では全く別の変数として宣言するしかなく値を引き継げない
ポインタ変数は場所であるため例外でありまた、どこの関数にも入っていない場所(行)で宣言をするとそれはグ
ローバル変数となりどこでも呼び出せ値を引き継ぐことのできる変数となる
用意されている関数
putsやprintf等元から用意されている関数がある。それをライブラリ関数と呼ぶ.
ヘッダファイル(stdio.hなど)に書かれており、それをinclude(呼び出す)ことによって使える
*/
|
C
|
/** Original Question : https://stackoverflow.com/questions/67025106/
**/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
int main( int argc, char *argv[] )
{
MPI_Init(&argc, &argv);
int myrank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &myrank) ;
MPI_Comm_size(MPI_COMM_WORLD, &size);
double mat[4]={1, 2, 3, 4};
int r=4;
double snd_buf[r];
double recv_buf[10];
MPI_Status status;
MPI_Datatype type;
MPI_Type_contiguous( r, MPI_DOUBLE, &type );
MPI_Type_commit(&type);
if(myrank==0)
MPI_Send (&mat[0], 1 , type, 1, 100, MPI_COMM_WORLD);
else if(myrank==1)
{
MPI_Recv(&recv_buf[6], 1, type, 0, 100, MPI_COMM_WORLD, &status);
for(int i=6;i<10;i++)
printf("%lf ",recv_buf[i]);
printf("\n");
}
MPI_Type_free(&type);
MPI_Finalize();
return 0;
}
|
C
|
#include <stdio.h> /* i/o library */
#include <stdlib.h> /* exit call */
#include <string.h> /* string functions */
#include <netdb.h> /* net functions */
#include <unistd.h> /* closing fds */
#include <arpa/inet.h> /* inet ntop */
#define BUFFSIZE 1024
/*
Function: createClient
Description: Sets up a client connection with the specified
hostname and port.
Arguments:
* hostname string
* port string
Return Value: A socket file descriptor
*/
int createClient(char *hostname, char *port){
int sfd, status;
char s[INET_ADDRSTRLEN];
struct addrinfo hints, *servinfo, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
status = getaddrinfo(hostname, port, &hints, &servinfo);
if (status != 0){
return -1;
}
for (res = servinfo; res != NULL; res = res->ai_next) {
sfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sfd == -1){
continue;
}
if (connect(sfd, res->ai_addr, res->ai_addrlen) == -1){
close(sfd);
continue;
}
break;
}
if (res == NULL) {
fprintf(stderr, "Failed to connect to %s:%s.\n", hostname, port);
return -1;
}
inet_ntop(res->ai_family, res->ai_addr, s, sizeof s);
freeaddrinfo(servinfo);
return sfd;
}
int main(int argc, char **argv){
int sfd;
char buffer[BUFFSIZE];
ssize_t bytes_read = 0;
sfd = createClient(argv[1], argv[2]);
if (sfd == -1){
exit(-1);
}
while((bytes_read = read(0, buffer, BUFFSIZE))){
send(sfd, buffer, bytes_read, 0);
if (memcmp("exit", buffer, 4) == 0)
break;
bytes_read = recv(sfd, buffer, BUFFSIZE, 0);
buffer[bytes_read] = 0;
printf("%s", buffer);
memset(buffer, 0, BUFFSIZE);
}
close(sfd);
return 0;
}
|
C
|
#include <stdio.h>
void main() {
int x=2, y=6, z=5;
int t=1;
int i;
for(i=0; i<y; i++) {
t = (t*x)%z;
}
printf("%d\n", t);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#define true 1
#define false 0
int x = 158969851;
bool main() {
if (x < 0)
{
return false;
}
else
{
int temp = x;
int rev = 0;
while (x != 0)
{
int a = x % 10;
x /= 10;
if (rev > INT_MAX/10 || rev == INT_MAX/10 && a> 7)
{
return false;
}
rev = rev * 10 + a;
}
if (temp == rev)
{
return true;
}
return false;
}
}
|
C
|
#pragma once
#include <stdbool.h>
#include "time.h"
#ifdef __cplusplus
extern "C" {
#endif
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
#define SCHEDULER_DELAY_LIMIT 10
#define TIMEUS_MAX UINT64_MAX
#define TASK_PERIOD_HZ(hz) (1000000 / (hz))
#define TASK_PERIOD_MS(ms) ((ms) * 1000)
#define TASK_PERIOD_US(us) (us)
typedef enum {
TASK_PID, //task for calculating PID loop
TASK_GYRO, //integrating attitude
TASK_ACC, //correcting attitude
TASK_MAG, //correcting attitude
TASK_DEPTH, //correcting depth
TASK_TELEMETRY, //sending telemetry
TASK_SERIAL,
TASK_SYSTEM, //task for calculating system load
TASK_TEST,
TASK_COUNT,
TASK_SELF //editing current task
}taskID_e;
typedef enum {
TASK_PRIORITY_IDLE = 0, // Disables dynamic scheduling, task is executed only if no other task is active this cycle
TASK_PRIORITY_LOW = 1,
TASK_PRIORITY_MEDIUM = 3,
TASK_PRIORITY_MEDIUM_HIGH = 4,
TASK_PRIORITY_HIGH = 5,
TASK_PRIORITY_REALTIME = 6,
TASK_PRIORITY_MAX = 255
}taskPriority_e;
typedef struct {
const char* taskName;
bool isActive;
void (*taskFun)(timeUs_t currentTime);
bool (*checkFunc)(timeUs_t currentTimeUs, timeDelta_t currentDeltaTimeUs); //if time is eventy driven this function checks if it should be scheduled
timeUs_t lastExecutedAt; //last execution time
timeUs_t lastSignaledAt; //if task is event driven this is time when event has trigered
timeDelta_t desiredPeriod; //desired period of execution
uint16_t taskAgeCycles;
uint8_t staticPriority; //taskPriority_e
uint16_t dynamicPriority; //Resolve issue of task being not executed due to other task with same priority but lower index
//stats
timeUs_t maxExecutionTime;
timeUs_t totalExecutionTime;
timeUs_t movingSumExecutionTime; //sum of time consumed by 32 invoccations
}task_t;
extern task_t tasks[TASK_COUNT];
void schedulerInit(void); //init scheduler
void scheduleTask(taskID_e taskID, timeDelta_t periodUs); //set task period
void setTaskEnabled(taskID_e taskID, bool enabled); //enable or disable tasks
void scheduler(void); //do tasks
void taskSystem(timeUs_t currentTimeUs);
#ifdef __cplusplus
}
#endif
|
C
|
#include<stdio.h>
int sum(int, int);
void printglobali(void);
int globali;
int main()
{
extern int globali;
int i,
j;
i = 6;
j = 7;
globali = sum(i, j);
printglobali();
return 0;
}
int sum(int i, int j)
{
return i + j;
}
void printglobali(void)
{
extern int globali;
printf("globali is %d\n", globali);
}
|
C
|
#include<stdio.h>
void print_odd_elements(int size,int *pointer){
int i;
for(int i = 0; i < size; ++i)
{
if ( i % 2 == 1)
{
printf("array[%d]: %d\n", i, pointer[i]);
}
}
}
void print_odd_pointers(int size,int *pointer){
int i;
for(int i = 0; i < size; ++i)
{
if ( i % 2 == 1)
{
printf("&pointer[%d]: %d, %p\n", i,pointer[i] , &pointer[i]);
}
}
}
main()
{
int tam = 10;
int tam2 = 6;
int array [10] = {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10};
int array2 [2][3] = {-1,-2,-3,-4,-5,-6};
int *pointer_1 = array;
int *pointer_2 = array2;
printf("va el unidimensional \n");
print_odd_elements(tam,pointer_1);
print_odd_pointers(tam,pointer_1);
printf("va el multidimensional \n");
print_odd_elements(tam2,pointer_2);
print_odd_pointers(tam2,pointer_2);
}
|
C
|
#include<stdio.h>
int main()
{
double a,b,c,d,e,x,y;
scanf("%lf %lf %lf %lf",&a,&b,&c,&d);
x= (2*a+3*b+4*c+d)/10;
printf("Media: %.1lf\n",x);
if(x>=7){
printf("Aluno aprovado.\n");
}
else if(x<5){
printf("Aluno reprovado.\n");
}
else if(x>=5&&x<7){
printf("Aluno em exame.\n");
scanf("%lf",&e);
y=(x+e)/2;
printf("Nota do exame: %.1lf\n",e);
if(y>=5){
printf("Aluno aprovado.\n");
printf("Media final: %.1lf\n",y);
}
else if(y<5){
printf("Aluno reprovado.\n");
printf("Media final: %.1lf\n",y);
}
}
return 0;
}
|
C
|
//Programa que cria uma matriz 4x4 e calcula qual linha tem a maior soma
#include <stdio.h>
main()
{
int mat[4][4],i,j,loja1,loja2,loja3,loja4;
for (i=0;i<4;i++)//atribuindo valores para o vetor
{
for (j=0;j<4;j++)
{
printf("\nDigite a posicao [%d][%d] do vetor: ",i,j);
scanf("%d",&mat[i][j]);
}
}
for (i=0;i<4;i++)//calculando a soma de cada linha
{
for (j=0;j<4;j++)
{
if (i==0)
{
loja1=loja1+mat[i][j];
}
if (i==1)
{
loja2=loja2+mat[i][j];
}
if (i==2)
{
loja3=loja3+mat[i][j];
}
if (i==3)
{
loja4=loja4+mat[i][j];
}
}
}
printf("\nO total de vendas da loja 1 eh: %d",loja1);
printf("\nO total de vendas da loja 2 eh: %d",loja2);
printf("\nO total de vendas da loja 3 eh: %d",loja3);
printf("\nO total de vendas da loja 4 eh: %d",loja4);
getchar();
}
|
C
|
/*
* BitMath.h
*
* Created: 05-Dec-20 6:08:47 PM
* Author: George Zaky
*/
#ifndef BITMATH_H_
#define BITMATH_H_
#define SetBit(Reg,BitNo) (Reg |= (1<<BitNo))
#define ClearBit(Reg,BitNo) (Reg &=~ (1<<BitNo))
#define ToggleBit(Reg,BitNo) (Reg ^= (1<<BitNo))
#define GetBit(Reg,BitNo) ((Reg>>BitNo)&1)
#endif /* BITMATH_H_ */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
double add(double a, double b)
{
return a + b;
}
double subtract(double a, double b)
{
return a - b;
}
double multiply(double a, double b)
{
return a * b;
}
double divide(double a, double b)
{
if (b == 0) {
printf("ERROR: Cannot divide by zero.\n");
return 0;
}
return a / b;
}
double pow_of_sum(double a, double b)
{
return pow(a + b, a + b);
}
/*
int main(int argc, char **argv) {
if (argc != 4) {
printf("Usage: ./calc num1 operation num2.\n");
exit(-1);
}
char operation;
if (strlen(argv[2]) != 1) {
printf("Supported operations: + - * /\n");
exit(-1);
} else {
operation = argv[2][0];
}
double a, b;
a = strtod(argv[1], NULL);
b = strtod(argv[3], NULL);
switch (operation) {
case '+':
printf("Result = %.2f\n", add(a, b));
break;
case '-':
printf("Result = %.2f\n", subtract(a, b));
break;
case '*':
printf("Result = %.2f\n", multiply(a, b));
break;
case '/':
printf("Result = %.2f\n", divide(a, b));
break;
default:
printf("ERROR: operation %c not supported.\n", operation);
exit(-1);
}
return 0;
}
*/
|
C
|
#include <boxer/boxer.h>
int main(int argc, char *argv[]) {
boxerShow("Simple message boxes are very easy to create.", "Simple Example", kBoxerDefaultStyle, kBoxerDefaultButtons);
boxerShow("There are a few different message box styles to choose from.", "Style Example", BoxerStyleError, kBoxerDefaultButtons);
BoxerSelection selection;
do {
selection = boxerShow("Different buttons may be used, and the user's selection can be checked. Would you like to see this message again?", "Selection Example", BoxerStyleQuestion, BoxerButtonsYesNo);
} while (selection == BoxerSelectionYes);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int value;
struct Node * next;
} Node;
typedef struct Stack{
Node * top;
} Stack;
Stack * create(){
Stack * q = (Stack*) malloc(sizeof(Stack));
q->top = NULL;
return q;
}
void push(Stack * s, int value){
Node * new = (Node*) malloc(sizeof(Node));
new->value = value;
new->next = s->top;
s->top = new;
}
int isEmptyStack(Stack * s){
return(s->top == NULL);
}
void display(Stack * s){
Node * p = s->top;
if(isEmptyStack(s)){
printf("A pilha est vazia!\n");
}
else{
while(p != NULL){
printf("%d\n", p->value);
p = p->next;
}
}
}
int verifOrdem(Stack * s){
Node * p;
for(p=s->top; p!=NULL; p=p->next){
if(p->value > p->next->value){
return 1;
}
}
return 0;
}
Node * search(Stack * s, int value){
Node * p;
for(p=s->top; p!=NULL; p=p->next){
if(p->value == value)
return p;
}
return NULL;
}
void freeStack(Stack * s){
Node * p = s->top;
while(p != NULL){
Node * t = p->next;
free(p);
p = t;
}
free(p);
}
int pop(Stack * s){
Node * t;
int v;
if(isEmptyStack(s)){
printf("\nPilha j vazia!\n");
return 0;
}
t = s->top;
v = t->value;
s->top = t->next;
free(t);
return v;
}
Stack * pilhaInvertida(Stack * s){
Stack * aux;
int v;
aux = create();
v = pop(s);
do{
push(aux, v);
v = pop(s);
}while(v != 0);
return aux;
}
int numPrimos(Stack * s){
Node * p = s->top
int n = 0;
int div = 0;
while(p != NULL){
for (i = 1; i <= p->value; i++) {
if (x % i == 0) {
div++;
}
}
if (div == 2){
n++;
}
}
return n;
}
int main(){
Stack * s;
s = create();
Node * searched = NULL;
int verificado = 2,primos = 0;
printf("A pilha est vazia (0,1) : %d\n", isEmptyStack(s));
display(s);
push(s, 30);
push(s, 20);
push(s, 10);
printf("A pilha est vazia (0,1) : %d\n", isEmptyStack(s));
display(s);
printf("Buscando elemento:\n");
searched = search(s, 10);
if(searched != NULL){
printf("Encontrou o elemento: %d\n", searched->value);
}
display(s);
printf("Removendo elemento: %d\n", pop(s));
printf("verificando ordem da pilha.\n");
verificado = verifOrdem(s);
if(verificado == 1){
printf("A pilha no est em ordem crescente.\n");
}else if(verificado == 1){
printf("A pilha est em ordem crescente.\n");
}
printf("invertendo lista.\n");
s = pilhaInvertida(s);
printf("verificando quantidade de primos.\n")
primos = numPrimos(s);
printf("a quantidade de numeros primos e : %d\n",primos);
display(s);
printf("Liberando a pilha.\n");
freeStack(s);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "freelanser.h"
void freeLanser_print(freeLanser_t * fl) {
printf("\nName: %s\nSurname: %s\nSalary: %0.2f\nCompletedProjects: %i\nBirth date: %s\n\n",
fl->name, fl->surname, fl->salary, fl->completedProjects,fl->birthDate);
}
|
C
|
#ifndef COMMON_H
#define COMMON_H
#include "openiboot.h"
#include "util.h"
#define FLIPENDIAN(x) flipEndian((unsigned char *)(&(x)), sizeof(x))
#define FLIPENDIANLE(x) flipEndianLE((unsigned char *)(&(x)), sizeof(x))
#define TRUE 1
#define FALSE 0
#define IS_BIG_ENDIAN 0
#define IS_LITTLE_ENDIAN 1
#define TIME_OFFSET_FROM_UNIX 2082844800L
#define APPLE_TO_UNIX_TIME(x) ((x) - TIME_OFFSET_FROM_UNIX)
#define UNIX_TO_APPLE_TIME(x) ((x) + TIME_OFFSET_FROM_UNIX)
#define ASSERT(x, m) if(!(x)) { bufferPrintf("error: %s\n", m); }
typedef uint64_t off_t;
#define endianness IS_LITTLE_ENDIAN
static inline int time(void* unused) {
return 0;
}
static inline void flipEndian(unsigned char* x, int length) {
int i;
unsigned char tmp;
if(endianness == IS_BIG_ENDIAN) {
return;
} else {
for(i = 0; i < (length / 2); i++) {
tmp = x[i];
x[i] = x[length - i - 1];
x[length - i - 1] = tmp;
}
}
}
static inline void flipEndianLE(unsigned char* x, int length) {
int i;
unsigned char tmp;
if(endianness == IS_LITTLE_ENDIAN) {
return;
} else {
for(i = 0; i < (length / 2); i++) {
tmp = x[i];
x[i] = x[length - i - 1];
x[length - i - 1] = tmp;
}
}
}
struct io_func_struct;
typedef int (*readFunc)(struct io_func_struct* io, off_t location, size_t size, void *buffer);
typedef int (*writeFunc)(struct io_func_struct* io, off_t location, size_t size, void *buffer);
typedef void (*closeFunc)(struct io_func_struct* io);
typedef struct io_func_struct {
void* data;
readFunc read;
writeFunc write;
closeFunc close;
} io_func;
#endif
|
C
|
#include<stdio.h>
int main()
{
int i, cnt=0, p8[8]={6,7,8,9,1,2,3,4};
int p10[10]={6,7,8,9,10,1,2,3,4,5};
char input[11], k1[10], k2[10], temp[11];
char LS1[5], LS2[5];
//k1, k2 are for storing interim keys
//p8 and p10 are for storing permutation key
//Read 10 bits from user...
printf("Enter 10 bits input:");
scanf("%s",input);
input[10]='\0';
//Applying p10...
for(i=0; i<10; i++)
{
cnt = p10[i];
temp[i] = input[cnt-1];
}
temp[i]='\0';
printf("\nYour p10 key is :");
for(i=0; i<10; i++)
{ printf("%d,",p10[i]); }
printf("\nBits after p10 :");
puts(temp);
//Performing LS-1 on first half of temp
for(i=0; i<5; i++)
{
if(i==4)
temp[i]=temp[0];
else
temp[i]=temp[i+1];
}
//Performing LS-1 on second half of temp
for(i=5; i<10; i++)
{
if(i==9)
temp[i]=temp[5];
else
temp[i]=temp[i+1];
}
printf("Output after LS-1 :");
puts(temp);
printf("\nYour p8 key is :");
for(i=0; i<8; i++)
{ printf("%d,",p8[i]); }
//Applying p8...
for(i=0; i<8; i++)
{
cnt = p8[i];
k1[i] = temp[cnt-1];
}
printf("\nYour key k1 is :");
puts(k1);
//This program can be extended to generate k2 as per DES algorithm.
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main()
{
srand(time(0));
char losuj_wyraz[10];
int i;
char losowa;
char *p;
char *p2;
int ilosc=0;
losowa=(rand()%25)+97;
for(i=0;i<10;i++)
{
losuj_wyraz[i]=(rand()%25)+97;
printf("%c",losuj_wyraz[i]);
}
p=strchr(losuj_wyraz,losowa);
if(p!=NULL)printf("\n\n%c wystepuje na miejscu %p ",losowa,p);
else printf("\n%c nie wystepuje",losowa);
for(p2=strchr(losuj_wyraz,losowa);p2!=NULL;p2=strchr(p2+1, losowa))
{
ilosc++;
}
printf("\n ilosc wystapien %d ",ilosc);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <tgmath.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <mqueue.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <semaphore.h>
#define SIZE 4
int prime(int n);
void main(int argc, char * argv[]){
int bounds = atoi(argv[3]);
typedef struct {
int pocz;
int kon ;
int suma;
} dane_t;
typedef struct {
int wymiar;
dane_t dane[SIZE];
int head;
int tail;
int cnt;
sem_t mutex;
sem_t empty;
sem_t full;
}buf_t;
buf_t * buf;
struct timespec start, finish;
double time_elapsed;
clock_gettime(CLOCK_MONOTONIC, &start);
int status;
int lower_bound = atoi(argv[1]);
int upper_bound = atoi(argv[2]);
int size;
int pids[bounds];
int number_of_primes = 0;
int bound = (upper_bound-lower_bound)/bounds;
int writer;
int fd;
int res;
shm_unlink("bufor");
fd=shm_open("bufor", O_RDWR|O_CREAT , 0774);
if(fd == -1){
perror("open"); _exit(-1);
}
printf("fd: %d\n",fd);
size = ftruncate(fd,sizeof(buf_t));
if(size < 0) {
perror("trunc");
_exit(-1);
}
int lb[bounds];
int ub[bounds];
// Odwzorowanie segmentu fd w obszar pamieci procesow
buf = (buf_t *)mmap(0, sizeof(buf_t), PROT_READ|PROT_WRITE,MAP_SHARED, fd, 0);
buf-> cnt = 0;
buf->head = 0;
buf->tail = 0;
if(sem_init(&(buf->mutex),1,1)){
perror("mutex");
_exit(0);
}
if(sem_init(&(buf->empty),1,SIZE)) {
perror("empty"); _exit(0);
}
if(sem_init(&(buf->full),1,0)) {
perror("full");
_exit(0);
}
for(int i=0 ; i<bounds; i++){
lb[i] = lower_bound+i*bound;
ub[i] = lower_bound+(i+1)*bound;
//printf("Wysłano przedział (%d-%d)\n", lb, ub);
}
for(int i=0; i<bounds; i++){
if((pids[i] = fork()) == 0) { /* Proces potomny ---*/
sem_wait(&(buf->empty));
sem_wait(&(buf->mutex));
dane_t data;
int primes_found = 0;
for(int j=lb[i]; j<ub[i]; j++){
primes_found += prime(j);
}
data.pocz = lb[i];
data.kon = ub[i];
data.suma = primes_found;
//printf("Wysłano %d-%d\n", lb[i], ub[i]);
buf->dane[buf->head] = data;
buf-> cnt ++;
buf->head = (buf->head +1) % SIZE;
sem_post(&(buf->mutex));
sem_post(&(buf->full));
return(0);
}
}
/* Proces macierzysty */
for(int i=0 ; i<bounds; i++){
sem_wait(&(buf->full));
sem_wait(&(buf->mutex));
printf("Przedział'%d-%d, znaleziono %d liczb pierwszych\n", buf->dane[buf->tail].pocz, buf->dane[buf->tail].kon, buf->dane[buf->tail].suma);
number_of_primes+=buf->dane[buf->tail].suma;
buf-> cnt --;
buf->tail = (buf->tail +1) % SIZE;
sem_post(&(buf->mutex));
sem_post(&(buf->empty));
//printf("%d\n", bytes_read);
}
for(int i=0; i<bounds; i++){
pids[i] += wait(&status);
WEXITSTATUS(status);
}
//writer += wait(&status);
//WEXITSTATUS(status);
clock_gettime(CLOCK_MONOTONIC, &finish);
time_elapsed = (finish.tv_sec - start.tv_sec);
time_elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
printf("Time elapsed: %f seconds\n", time_elapsed);
printf("Number of primes: %d \n", number_of_primes);
return(0);
}
int prime(int n){
for(int j=2; j*j<n; j++){
if(n%j==0) return(0);
}
return(1);
}
|
C
|
#include <string.h>
#include "haml_indent.h"
enum indent_type haml_indent_type = undefined;
int haml_indent_size = -1;
int haml_current_indent = -1;
int haml_get_current_indent() {return haml_current_indent;}
void haml_set_current_indent(int indent_size) {haml_current_indent = indent_size;}
int haml_get_indent_size() {return haml_indent_size;}
void haml_set_indent_size(int indent_size) {haml_indent_size = indent_size;}
void haml_set_indent_type(enum indent_type type) {haml_indent_type = type;}
enum indent_type haml_get_indent_type() {return haml_indent_type;}
int haml_set_space_indent(size_t indent)
{
if(haml_indent_type == undefined)
{
haml_current_indent = indent;
haml_indent_size = indent;
haml_indent_type = spaces;
return 1; /* this is where indentation is initially defined */
}
if(haml_indent_type != spaces) return 0; /* using wrong indent type */
if(indent % haml_indent_size != 0) return 0; /* inconsistent indent type */
haml_current_indent = indent;
return 1;
}
|
C
|
#include <stdio.h>
/**
* @synopsis insert_sort
*
* @param L[]
* @param length
*
* 0. 基本思想
* 每次将一个待排序的数据,跟前面已经有序的序列的数字一一比较找到自己合适的位置,插入到序列中,直到全部数据插入完成。
*
* 1. 时间复杂度
* 平均 O(n^2) 比冒泡和简单选择性能要好些
* 最坏 O(n^2) 逆序,移动 O(n^2) 次,比较 O(n^2) 次
* 最好 O(n) 全部有序,只需要比较,不需要移动
*
* 2. 空间复杂度
* 只需要一个记录的辅助空间 O(1)
*
* 3. 稳定性
* 稳定
*
* 4. 复杂性
* 简单
*
* 5. 适用场合
* 适合少量数据的排序,或者数据基本已经有序的情况
*/
static void insert_sort(int L[], int length) {
if (NULL == L || length < 1) {
printf("L = NULL or length < 1\n");
return;
}
// 1. 设置哨兵
int temp = 0;
int j = 0;
for (int i = 1; i < length; i++) {
if (L[i - 1] > L[i]) {
// 2. 将要插入的数复制给哨兵
temp = L[i];
// 3. 移动其他元素
for (j = i; (j > 0) && (L[j - 1] > temp); j--)
L[j] = L[j - 1];
// 4. 插入哨兵的数据
L[j] = temp;
}
}
}
int main(void) {
int x[10] = { 5, 3, 2, 1, 7, 4, 6, 9, 8, 10 };
insert_sort(x, 10);
// insert_sort(NULL, 10);
insert_sort(x, 0);
for (int i = 0; i < 10; i++)
printf("%d ", x[i]);
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct playerStruct{
char name[50];
int age,matches,avg;
}p[20],s[20];
int cmpfncn(const void* s1,const void* s2)
{
if(((struct playerStruct*)s1)->avg > ((struct playerStruct*)s2)->avg)
return 1;
else
return 0;
}
void main()
{
int i,j,n,av[20];
printf("how many enteries would u like to enter\n");
scanf("%d",&n);
printf("enter the entries\n");
for(i=0;i<n;i++)
{
scanf("%s %d %d %d",p[i].name,&p[i].age,&p[i].matches,&p[i].avg);
}
/*for(i=0;i<n;i++)
{
av[i]=p[i].avg;
printf("%d\n",av[i]);
}*/
qsort(p,n,sizeof(p[0]),cmpfncn);
/*for(i=0;i<n;i++)
{
printf("%d\n",av[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(p[j].avg==av[i])
{
s[i]=p[j];
}
}
}*/
printf("after sorting the outcome is\n");
for(i=0;i<n;i++)
{
printf("%s %d %d %d\n",p[i].name,p[i].age,p[i].matches,p[i].avg);
}
}
|
C
|
#include "../include/pbound.h"
#include "../include/ptile.h"
/////////////////////
// PBound comparison functions. Note that some of these are a bit unusual.
//pbound equality
bool eq(const PBound *lhs, const PBound *rhs){
switch(lhs->state){
case EMPTYSET:
return (rhs->state == EMPTYSET);
case SINGLETON:
return (rhs->state == SINGLETON) && (rhs->lower == lhs->lower);
case STDBOUND:
return (rhs->state == STDBOUND) && (rhs->lower == lhs->lower) && (rhs->upper == lhs->upper);
case ALLREALS:
return (rhs->state == ALLREALS);
}
}
extern bool __roundsinf_checked(const PBound *);
//////////////////////////////////////////////
//TODO: FINISH THESE PROCS
bool lt(const PBound *lhs, const PBound *rhs){return false;} //less than
bool gt(const PBound *lhs, const PBound *rhs){return false;} //greater than
bool ol(const PBound *lhs, const PBound *rhs){return false;} //lhs and rhs overlap
bool in(const PBound *lhs, const PBound *rhs){
if (rhs->state == ALLREALS) {return true;}
if (rhs->state == EMPTYSET) {return false;}
switch(lhs->state){
case EMPTYSET:
return true;
case SINGLETON:
if (rhs->state == SINGLETON) {return eq(lhs, rhs);};
if (__roundsinf_checked(rhs)){
return __s(rhs->lower) <= __s(lhs->lower) || //NB that this is a logical OR.
__s(rhs->upper) >= __s(lhs->lower);
}
else {
return ((rhs->lower == __inf) || __s(rhs->lower) <= __s(lhs->lower)) &&
((rhs->upper == __inf) || __s(rhs->upper) >= __s(lhs->lower));
}
case STDBOUND:
if (rhs->state == SINGLETON) {return false;}; //this cannot be true.
if (__roundsinf_checked(rhs)){
if (!__roundsinf_checked(lhs)) {return false;}; //rounding infinity must match
return (__s(rhs->lower) <= __s(lhs->lower)) &&
(__s(rhs->upper) >= __s(rhs->upper));
}
else {
if (__roundsinf_checked(lhs)) {return false;}; //rounding infinity must match.
return ((rhs->lower == __inf) || __s(rhs->lower) <= __s(lhs->lower)) &&
((rhs->upper == __inf) || __s(rhs->upper) >= __s(lhs->upper));
}
case ALLREALS:
return false;
}
}
|
C
|
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#define FOSC 16000000UL
#define baud_rate 4800
#define baud FOSC/16/baud_rate-1
#define SYNC 0xAA
#define RX_ADDR 0x21
#define LED_ON 0x11
char data=0;
typedef enum state_t{LOW,HIGH}state;
void usart_init(unsigned int b_rate)
{
UBRR0H=0x00;
UBRR0L=0x00;
UCSR0B=0x00;
UCSR0C=0x00;
UDR0 =0x00;
UBRR0H =(unsigned char)b_rate>>8;
UBRR0L =(unsigned char)b_rate;
UCSR0B = ( (1<<RXCIE0) | (1<<RXEN0) | (1<<TXEN0) );
UCSR0C = ( (1<<UCSZ00) | (1 << UCSZ01) );
}
void Transmit(unsigned char c)
{
while( !(UCSR0A & (1<<UDRE0) ) );
UDR0=c;
}
void set_Debug_LED()
{
PORTC |= (1<<PC0);
}
void reset_Debug_LED()
{
PORTC &= ~(1<<PC0);
}
void send_debug_msg(char *str)
{
Transmit(*str);
while( *(++str)!=0)
Transmit(*str);
}
void check_valid_payload()
{
if(data==RX_ADDR)
{
send_debug_msg("---ADDR OK ---");
_delay_ms(10);
if(data==LED_ON)
{
set_Debug_LED();
send_debug_msg("---LED ON---");
_delay_ms(50);
}
if(data==LED_OFF)
{
reset_Debug_LED();
send_debug_msg("---LED OFF ---");
_delay_ms(50);
}
}
}
int main (void)
{
DDRC = 0xFF;
PORTC = 0xFE;
sei();
usart_init(baud);
while(1)
{
check_valid_payload();
_delay_ms(5);
}
return 0;
}
ISR(USART_RX_vect )
{
data=UDR0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main(void)
{
double i,x,y=0,n;
printf("This program displays the value of y in following expression.\n\n");
printf("\ty = 1 + x + x^2 + x^3 + ... + x^n .\n\n\n");
printf("Enter x : ");
scanf ("%lf",&x);
printf("Enter n : ");
scanf ("%lf",&n);
for(i=0;i<=n;i++)
{
y = y + pow(x,i);
}
printf("\n\nResult:\n");
printf("\tRequired value of y is : %.2lf",y);
getch();
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
/* Codigo hecho por mi cuenta. */
int main (){
int N, cases, i, j, contX, contO, winX, winO;
/* Ocupamos una matriz de 3x4 ya que almacenaremos las lineas escaneadas como string
por lo tanto debe tener espacio para '\0'. */
char tictac[3][4];
scanf("%d", &N);
for(cases=0;cases<N;++cases, winO=0, winX=0, contX=0, contO=0){
scanf("%s%s%s", tictac[0], tictac[1], tictac[2]);
/* Contamos el numero de X y de O. */
for(i=0;i<3;++i){
for(j=0;j<3;++j){
if(tictac[i][j]=='X')
++contX;
else if(tictac[i][j]=='O')
++contO;
}
}
/* Si el numero de O es mayor que X, entonces el juego de gato no es posible,
de la misma manera si el numero de X es mayor por dos unidades al numero de
O, tampoco es posible. */
if(contX-contO<0 || contX-contO>=2){
printf("no\n");
continue;
}
/* Observamos si X o O ganan en alguna fila o columna, */
for(i=0;i<3;i++){
if(tictac[i][0]==tictac[i][1] && tictac[i][0]==tictac[i][2]){
if(tictac[i][0]=='X')
++winX;
else if(tictac[i][0]=='O')
++winO;
}
if(tictac[0][i]==tictac[1][i] && tictac[0][i]==tictac[2][i]){
if(tictac[0][i]=='X')
++winX;
else if(tictac[0][i]=='O')
++winO;
}
}
/* Observamos si X o O ganan en diagonal. */
if(tictac[0][0]==tictac[1][1] && tictac[0][0]==tictac[2][2] || tictac[0][2]==tictac[1][1] && tictac[0][2]==tictac[2][0]){
if(tictac[1][1]=='X')
++winX;
else if(tictac[1][1]=='O')
++winO;
}
/* Si O gano, se debe cumplir que el numero de X y O deben ser iguales, Si X gana
el numero de X debe ser 1 mayor al numero de O. En casos contrarios el juego de gato
no es posible. */
if(winO==1 && contX!=contO){
printf("no\n");
continue;
}
if(winX==1 && contO+1!=contX){
printf("no\n");
continue;
}
/* Si no se cumplieron ninguna condicion anterior, entonces el juego de gato si es posible. */
printf("yes\n");
}
return 0;
}
|
C
|
#include "audit_lock.h"
int file_set_lock(int fd, int cmd){
struct flock lock;
lock.l_whence=SEEK_SET;
lock.l_start=0;
lock.l_len=0;
lock.l_pid = getpid();
if(cmd == F_SETLK)
lock.l_type=F_WRLCK;
// printf("type:%d\n",lock.l_type);
if(fcntl(fd,cmd,&lock)==-1)
return -1;
else return 1;
}
int file_get_lock(int fd){
struct flock lock;
lock.l_type = F_RDLCK;
lock.l_whence=SEEK_SET;
lock.l_start=0;
lock.l_len=0;
lock.l_pid=0;
if(fcntl(fd,F_GETLK,&lock)==-1){
//printf("errno=%d\n",errno);
//perror("fcntl");
return -1;
}
else if(lock.l_type==F_WRLCK){
return 1;
}
else return 0;
}
int file_setlease(int fd, int cmd){
if(fcntl(fd,cmd,F_WRLCK)==-1)
return -1;
else return 1;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_get_conversion.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adubeau <marvin@42quebec.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/22 12:24:19 by adubeau #+# #+# */
/* Updated: 2021/07/23 11:03:03 by adubeau ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_printf.h"
int ft_get_conversion(va_list ap, int i, const char *s)
{
int len;
len = 0;
if (s[i] == 'c')
len += ft_putchar((char)va_arg(ap, int));
else if (s[i] == 's')
len += ft_putstr(va_arg(ap, char *));
else if (s[i] == 'x' || s[i] == 'X')
len += ft_hexa((unsigned int)va_arg(ap, int), s[i]);
else if (s[i] == 'p')
{
len += write(1, &"0x", 2);
len += ft_hexa((unsigned long long int)va_arg(ap, long long int), s[i]);
}
else if (s[i] == 'i' || s[i] == 'd')
len += ft_putnbr((int)va_arg(ap, int));
else if (s[i] == '%')
len += ft_putchar('%');
else if (s[i] == 'u')
len += ft_putnbru((unsigned int)va_arg(ap, int));
return (len);
}
|
C
|
#include <stdio.h>
#include <malloc.h>
#include <vld.h>
#pragma warning(disable:4996)
int main()
{
int *p = (int*)malloc(sizeof(int));
int *p1 = p;
free(p);
printf("%d", *p1);
return 0;
}
|
C
|
/*
Rotated Triangle Pattern
Given an integer N, print the pattern as given in Example Input/Output section.
Note: N is always an odd number.
Boundary Condition(s):
1 <= N <= 9999
Input Format:
The first line contains N.
Output Format:
The first N lines contain the desired pattern.
Example Input/Output 1:
Input:
7
Output:
1
2 8
3 9 13
4 10 14 16
5 11 15
6 12
7
Example Input/Output 2:
Input:
5
Output:
1
2 6
3 7 9
4 8
5
*/
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n,count = 1;
cin >> n;
int l=0,m=n;
int g = n;
int a[n][n] = {0};
for(int j=0;j<n;j++)
{
for(int i=l;i<m;i++)
{
a[i][j] = count;
count ++;
}
l++;
m--;
}
for(int i=0;i<n/2+1;i++)
{
for(int j=0;j<=i;j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
for(int i=n/2+1;i<n;i++)
{
for(int j = 0;j < g; j++)
{
if(a[i][j] != 0)
cout << a[i][j] << " ";
}
cout << endl;
g--;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rlardere <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/23 16:37:16 by rlardere #+# #+# */
/* Updated: 2018/11/23 16:41:48 by rlardere ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "libft.h"
static char **ft_strsplit_tab(char const *s, char c, int *count)
{
char **tab;
int i;
i = 0;
while (s[i])
{
i++;
if ((s[i] == c && s[i - 1] != c) || (s[i] == '\0' && s[i - 1] != c))
*count = *count + 1;
}
if (!(tab = (char**)malloc(sizeof(char*) * (*count + 1))))
return (0);
return (tab);
}
static int ft_strsplit_3(char const *s, int index, char c)
{
int i;
i = 0;
while (s[i + index] != c && s[i + index] != '\0')
i++;
return (i);
}
char **ft_strsplit(char const *s, char c)
{
char **tab;
int count;
int i;
int j;
int k;
k = 0;
j = 0;
i = 0;
count = 0;
if (!(s))
return (NULL);
if (!(tab = ft_strsplit_tab(s, c, &count)))
return (0);
while (k != count)
{
i = i + j;
while (s[i] == c)
i++;
j = ft_strsplit_3(s, i, c);
tab[k] = ft_strsub(s, i, j);
k++;
}
tab[k] = 0;
return (tab);
}
|
C
|
/*
* log.c
* Author: wangwei.
* Custom logging functions.
*/
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "../../include/sg/util/log.h"
#include "../../include/sg/sys/time.h"
#include "../../include/sg/sys/shell.h"
#include "../../include/sg/str/vlstr.h"
#include "../../include/sg/sys/module.h"
static int log_colorful = 1;
static FILE *fp_log;
static char fp_log_name[1024] = {0};
void sg_log_set_colorful(void)
{
log_colorful = 1;
}
void sg_log_cancel_colorful(void)
{
log_colorful = 0;
}
void sg_logging(const char *file, int line, const char *func, enum sg_log_level lv, const char *fmt, ...)
{
sg_vlstr_t *log;
sg_vlstr_t *log_fmt;
va_list ap;
char mod_path[1024] = {0};
char log_path[1024] = {0};
char curr_date[100] = {0};
char curr_time[100] = {0};
if (!fmt) {
printf("Logging param fmt error.\n");
goto end;
}
va_start(ap, fmt);
if (lv == SGLOGLEVEL_CRIT)
log_fmt = sg_vlstrfmt("file:%s, line:%d, function:%s\r\n%s", file, line, func, fmt);
else
log_fmt = sg_vlstrfmt("%s\r\n", fmt);
log = sg_vlstrfmt_ap(sg_vlstrraw(log_fmt), ap);
if (sg_vlstrlen(log) == 0)
goto end;
printf("%s", sg_vlstrraw(log));
sg_module_path(mod_path, 1024);
sg_curr_date_time("%Y-%m-%d", curr_date, 100);
snprintf(log_path, 1024, "%s.%s.log", mod_path, curr_date);
if (strcmp(log_path, fp_log_name) != 0 && fp_log) {
fclose(fp_log);
fp_log = NULL;
}
snprintf(fp_log_name, 1024, "%s", log_path);
if (!fp_log)
fp_log = fopen(log_path, "ab+");
if (fp_log) {
sg_curr_date_time("%Y-%m-%d %H:%M:%S ", curr_time, 100);
fwrite(curr_time, 1, strlen(curr_time), fp_log);
fwrite(sg_vlstrraw(log), 1, sg_vlstrlen(log), fp_log);
fflush(fp_log);
}
end:
va_end(ap);
sg_vlstrfree(&log);
sg_vlstrfree(&log_fmt);
}
/* have some bugs */
/*
void sg_logging(const char *file, int line, const char *func, enum sg_log_level lv, const char *fmt, ...)
{
sg_vlstr_t *log;
sg_vlstr_t *log_fmt;
va_list ap;
char mod_path[1024] = {0};
char log_path[1024] = {0};
char curr_date[100] = {0};
char curr_time[100] = {0};
if (!fmt) {
printf("Logging param fmt error.\n");
goto end;
}
va_start(ap, fmt);
// Memory leaks.
//log = sg_vlstralloc3(strlen(fmt) * 2 + 1);
//if (!log) {
// printf("Logging open memory error.\n");
// goto end;
//}
//printf("heheda:%p.", ap);
//printf("log param after fmt:%s", va_arg(ap, char *));
if (lv == SGLOGLEVEL_CRIT)
log_fmt = sg_vlstrfmt("file:%s, line:%d, function:%s\r\n%s", file, line, func, fmt);
else
log_fmt = sg_vlstrfmt("%s\r\n", fmt);
log = sg_vlstrfmt_ap(sg_vlstrraw(log_fmt), ap);
//printf("log fmt:%s", sg_vlstrraw(log_fmt));
//printf("log:%s", sg_vlstrraw(log));
if (sg_vlstrlen(log) == 0)
goto end;
if (log_colorful == 1) {
switch (lv) {
case SGLOGLEVEL_DBG:
sg_shell_colorful_print(sg_vlstrraw(log), SGSHELLCOLOR_BLUE);
break;
case SGLOGLEVEL_INF:
sg_shell_colorful_print(sg_vlstrraw(log), SGSHELLCOLOR_WHITE); // bug here!
break;
case SGLOGLEVEL_WARN:
sg_shell_colorful_print(sg_vlstrraw(log), SGSHELLCOLOR_YELLOW);
break;
case SGLOGLEVEL_ERR:
sg_shell_colorful_print(sg_vlstrraw(log), SGSHELLCOLOR_RED);
break;
case SGLOGLEVEL_CRIT:
sg_shell_colorful_print(sg_vlstrraw(log), SGSHELLCOLOR_WHITE_ON_RED);
printf("\n");
break;
case SGLOGLEVEL_ALERT:
sg_shell_colorful_print(sg_vlstrraw(log), SGSHELLCOLOR_WHITE_ON_RED);
printf("\n");
break;
case SGLOGLEVEL_EMERG:
sg_shell_colorful_print(sg_vlstrraw(log), SGSHELLCOLOR_WHITE_ON_RED);
printf("\n");
break;
default:
sg_shell_colorful_print("Log param level error.", SGSHELLCOLOR_RED);
break;
}
} else
printf("%s", sg_vlstrraw(log));
sg_module_path(mod_path, 1024);
sg_curr_date_time("%Y-%m-%d", curr_date, 100);
snprintf(log_path, 1024, "%s.%s.log", mod_path, curr_date);
if (strcmp(log_path, fp_log_name) != 0 && fp_log) {
fclose(fp_log);
fp_log = NULL;
}
snprintf(fp_log_name, 1024, "%s", log_path);
if (!fp_log)
fp_log = fopen(log_path, "ab+");
if (fp_log) {
sg_curr_date_time("%Y-%m-%d %H:%M:%S ", curr_time, 100);
fwrite(curr_time, 1, strlen(curr_time), fp_log);
fwrite(sg_vlstrraw(log), 1, sg_vlstrlen(log), fp_log);
fflush(fp_log);
}
end:
va_end(ap);
sg_vlstrfree(&log);
sg_vlstrfree(&log_fmt);
}
*/
void sg_printf_time_stamp(const char *tag)
{
sg_log_inf("%s:%lu", tag, sg_boot_time_ms());
}
|
C
|
#include "search_algos.h"
/**
* exponential_search - search for value with exponential search algorithm
* @array: pointer to the beginning of the array to be searched
* @size: size of the array being searched
* @value: value being searched for
* Return: index of found number
*/
int exponential_search(int *array, size_t size, int value)
{
size_t idx = 0, eStep = 1;
if (!array)
return (-1);
for (idx = 0; eStep < size && size > 2; eStep *= 2)
{
if (array[eStep] > value)
break;
printf("Value checked array[%lu] = [%d]\n", eStep, array[eStep]);
idx = eStep;
}
if (size == 0)
{
printf("Value found between indexes [0] and [0]\n");
return (-1);
}
if (eStep > size - 1)
{
printf("Value found between indexes [%lu] and [%lu]\n", idx, size - 1);
return (bin_srch(array, idx, eStep - 1, value));
}
else
{
printf("Value found between indexes [%lu] and [%lu]\n", idx, eStep);
return (bin_srch(array, idx, eStep, value));
}
return (-1);
}
/**
* bin_srch - binary search algorithm for when exp search finds range
* @array: a pointer to the beginning of the arry to be searched
* @start: starting index to search in algorithm
* @end: ending index to search array in
* @value: the value being searched for
* Return: the index of the found value
*/
int bin_srch(int *array, size_t start, size_t end, int value)
{
size_t half = 0, idx = 0;
printf("Searching in array: %d", array[start]);
for (idx = start + 1; idx <= end; idx++)
printf(", %d", array[idx]);
printf("\n");
if (array[start] == value && start == end)
return (start);
else if (start == end)
return (-1);
half = start + ((end - start) / 2);
if (array[half] == value)
return (half);
else if (array[half] > value)
return (bin_srch(array, start, half - 1, value));
return (bin_srch(array, half + 1, end, value));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "fonctionsSocket.h"
/* definition des types */
#include "types4.h"
int main(int argc, char *argv[]) {
int desc_sock; /* descripteur de socket */
int envoyes;
mon_type_t foo = 42;
ma_structure_t bar;
bar.a = 10;
bar.b[0] = 'H';
bar.b[1] = 'e';
bar.b[2] = 'l';
bar.b[3] = 'l';
bar.b[4] = 'o';
bar.b[5] = '\0';
bar.c = 3.14;
desc_sock = socketClient_EAD("localhost", 2609);
if (desc_sock < 0) {
printf("Erreur creation socket\n");
}
/* envoi des donnees */
envoyes = send(desc_sock, &foo, sizeof(mon_type_t), 0);
if (envoyes == -1) {
printf("Erreur a l'envoi\n");
}
printf("Type simple envoye: %d\n", foo);
/* envoi des donnees */
envoyes = send(desc_sock, &bar, sizeof(ma_structure_t), 0);
if (envoyes == -1) {
printf("Erreur a l'envoi\n");
}
printf("Type complexe envoye:\n");
printf("\ta = %d\n", bar.a);
printf("\tb = %c %c %c %c %c\n", bar.b[0], bar.b[1], bar.b[2], bar.b[3], bar.b[4]);
printf("\tc = %f\n", bar.c);
close(desc_sock);
return 0;
}
|
C
|
#include <pthread.h>
#include <stdio.h>
long long sum;
long long outArr[1024];
void *runner(void *param);
int main(int argc, char *argv[])
{
pthread_t tid;
pthread_attr_t attr;
if (argc != 2)
{
fprintf(stderr,"usage: fib.out <integer value>\n");
return -1;
}
char *ptr = NULL;
int upper = strtol(argv[1], &ptr, 10);
if (upper < 0 | ptr[0] != '\0')
{
fprintf(stderr,"%d must be an integer >= 0\n", atoi(argv[1]));
return -1;
}
pthread_attr_init(&attr);
pthread_create(&tid, &attr, runner, argv[1]);
pthread_join(tid, NULL);
printf("Final fib = %lld\n",sum);
int index = 0;
for (index = 0; index <= upper; index++)
{
printf("Fib[%d] = %lld\n",index, outArr[index]);
}
}
void *runner(void *param)
{
int i, upper = atoi(param);
outArr[0] = 0;
outArr[1] = 1;
for (i = 2; i <= upper; i++)
sum = outArr[i] = outArr[i - 1] + outArr[i - 2];
pthread_exit(0);
}
|
C
|
#include <stdio.h>
int ft_recursive_factorial(int nb);
int main(void)
{
int i;
for (i=-1; i<=13; i++)
printf("%d!\t= %d\n", i, ft_recursive_factorial(i));
return (0);
}
|
C
|
#include <stdint.h>
#include <stdbool.h>
#include <inc/hw_memmap.h>
#include "../inc/debugging_utilities.h"
#include "../inc/computations.h"
#include "../inc/buttons.h"
#include "../inc/LCD.h"
#include "../inc/initialization.h"
#include "../inc/main.h"
#include "../inc/images.h"
#include "../inc/random.h"
#include "driverlib/fpu.h"
#include "driverlib/interrupt.h"
#include "../inc/game_state.h"
#define FRAME_RATE 30
#define SOUND_RATE 1
#define BUTTON_RATE 10
#define GRAVITY 1.5f
//#define DEBUG
//declare global variables
GameState state = {.fuel = 3000,
.score = 0,
.time = 0,
.xaccel = 0,
.yaccel = 0,
.yposit = 9, //initialize to topmost of landscape-oriented screen
.xposit = 64, //initialize to middle of landscape-oriented screen
.xvelocity = 0,
.yvelocity = 0,
.heading = SOUTH};
uint16_t seconds = 0;
screen currentScreen = START;
char multiplier = 0; //To be used to increase score according to where the lander lands
float oldxposit = 64; //position where the lander was previously, to clear
float oldyposit = 5; //position where the lander was previously, to clear
float thrusterAccel; //acceleration when the thrusters are enabled
int16_t width; //width of lander
int16_t height; //height of lander
uint16_t terrain[WIDTH];
int main(void) {
//Initializations board connections
IntMasterDisable(); //Interrupts must be disabled here to prevent unwanted triggering
DAC_Init(); //Digital to analog converter for sounds.
ButtonsInit(); //Allows for easier writing to handle button inputs
PortE_Init(); //Initialize hardware off-board buttons
PortF_Init(); //Initializes on-board buttons and LEDs for debugging
screen_init(); //Initializes screen
//Initialize interrupts
FPULazyStackingEnable();
sound_init(SOUND_RATE); //Initializes interrupt (Timer 2A) used for sounds
game_loop_init(FRAME_RATE); //Initializes Systick interrupt to handle game loop
button_Interrupt_Init(BUTTON_RATE);
generate_terrain((uint16_t *)&terrain, (uint16_t)WIDTH);
IntMasterEnable(); //end of initializations, enable interrupts
// We need to stall here and wait for the interrupts to trigger at regular intervals.
while(true);
}
void game_loop() {
switch (currentScreen) {
case START:
fill_background(BLACK);
draw_terrain();
reset_lander_attributes(&state);
check();
currentScreen = GAMEPLAY;
break;
case GAMEPLAY:
update();
check();
render();
tick();
break;
case DEATH:
draw_terrain_chunk();
tick();
if (button_pushed()) {
currentScreen = START;
}
break;
}
toggleLED(FRAME_RATE); //Debugging heartbeat
}
//update location and time
void update(void) {
float ttime = .07; //TODO set to refresh rate
state.time++;
state.yaccel = sinAngle(state.heading) * (-thrusterAccel) + GRAVITY;
state.xaccel = cosAngle(state.heading) * thrusterAccel;
state.yvelocity += state.yaccel * ttime;
state.xvelocity += state.xaccel * ttime;
state.yposit += state.yvelocity * ttime;
state.xposit += state.xvelocity * -ttime;
oldxposit = state.xposit;
oldyposit += state.yposit + state.yvelocity * ttime;
}
//"check" the things that will kill you
void check(void) {
//declare boolean
bool outOfTime = seconds >= 240;
bool collided = detect_collision();
bool tooFast = state.yvelocity >= 2.0;
bool crashed = collided && ((state.heading != SOUTH) || tooFast);
//check yposit
if (crashed) {
die(CRASHED);
}
if (collided && !crashed) {
land();
}
//check time
if (outOfTime) {
die(OUTOFTIME);
}
if (state.xposit >= 128) {
state.xposit = 0;
}
if (state.xposit <= 0) {
state.xposit = 128;
}
}
void render(void) {
int16_t xoffset; //offset of lander
int16_t yoffset;
int16_t thrustXOffset; //offset of lander
int16_t thrustYOffset;
int16_t thrustWidth;
int16_t thrustHeight;
sprite sprite = *landerSprite[state.heading];
thrust thrust = *thrustSprite[state.heading];
write(state.score, state.fuel, seconds);
if (state.time % FRAME_RATE == 0) {
seconds++;
}
write_velocities(state.xvelocity, state.yvelocity);
write_angle((uint16_t)state.heading);
width = sprite.width;
height = sprite.height;
xoffset = sprite.xoffset;
yoffset = sprite.yoffset;
const uint16_t *data = sprite.data;
thrustWidth = thrust.width;
thrustHeight = thrust.height;
thrustXOffset = thrust.xoffset;
thrustYOffset = thrust.yoffset;
const uint16_t *thrustData = thrust.data;
//Draw the lander
draw_bitmap((int16_t) (state.xposit + xoffset), (int16_t) (state.yposit + yoffset) , data, width, height);
draw_bitmap((int16_t) (oldxposit), (int16_t) (oldyposit - (oldyposit - state.yposit) - height - 2),
black,
26, 5);
if (thrusterAccel == 2.5f) {
draw_bitmap((int16_t) (state.xposit + thrustXOffset), (int16_t) (state.yposit + thrustYOffset), thrustData, thrustWidth,
thrustHeight);
}
else {
draw_bitmap((int16_t) (state.xposit + thrustXOffset), (int16_t) (state.yposit + thrustYOffset), black,
thrustWidth,
(int16_t) (thrustHeight - 2));
}
// draw_bitmap((int16_t) ((xposit + xoffset) + width), (int16_t) (oldyposit) , blue, 2, 10);
// draw_bitmap((int16_t) ((xposit + xoffset) + width), (int16_t) (oldyposit + 6 + height) , blue, 2, 10);
// draw_bitmap((int16_t) (xposit - 2 + xoffset), (int16_t) (oldyposit + 6 + height) , black, 2, 10);
// draw_bitmap(oldxposit - 5, oldyposit - 9, blue, 13, 5);
}
//Output some sort of death message
void die(DeathType_t deathtype) {
//fill_background(BLACK);
currentScreen = DEATH;
draw_string(6, 6, "You died!", (int16_t) WHITE);
switch (deathtype) {
case CRASHED:
draw_string(1, 7, "Lost 20 fuel units.", (int16_t) WHITE);
state.fuel -= 20;
draw_string(3, 8, "Fuel left:", (int16_t) WHITE);
draw_dec(14, 8, state.fuel);
//draw_string(4, 8, "Current score:", (int16_t)WHITE);
//write_score(score);
break;
case OUTOFTIME:
draw_string(4, 8, "Out of time!", (int16_t) WHITE);
//draw_string(4, 6, "Final score:", (int16_t)WHITE);
//write_score(score);
break;
}
}
void land(void) {
// fill_background(BLACK);
currentScreen = DEATH;
oldxposit = 0;
draw_string(6, 6, "You landed!", (int16_t) WHITE);
if (state.fuel > 0) {
draw_string(6, 7, "Fuel left:", (int16_t) WHITE);
draw_dec(6, 8, state.fuel);
}
}
void write(uint16_t score, uint16_t fuel, uint16_t seconds) {
draw_string(0, 0, "s:", (int16_t) WHITE);
draw_string(0, 1, "f:", (int16_t) WHITE);
draw_string(0, 2, "t:", (int16_t) WHITE);
draw_dec(2, 0, score);
draw_dec(2, 1, fuel);
//FIXME: The seconds doesn't draw a leading zero for the tens place.
//This leads to strange behaviour at the start of a new minute
//FIXME: Doesn't handle over 10 minutes
uint8_t min = (uint8_t) (seconds / 60);
draw_dec(2, 2, min);
draw_string(3, 2, ":", (int16_t) WHITE);
uint8_t sec = seconds - min * 60;
if (sec < 10) {
draw_dec(4, 2, 0);
draw_dec(5, 2, sec);
}
else {
draw_dec(4, 2, sec);
}
}
void draw_terrain(void) {
for (uint16_t i = 0; i < WIDTH; i++) {
draw_pixel(i, terrain[i], WHITE);
}
}
bool detect_collision(void) {
for (int i = (int) state.xposit; i < state.xposit + 8; i++) {
if (terrain[i] <= state.yposit - 1) {
return true;
}
}
return false;
}
void reset_lander_attributes(GameState *state) {
state->xposit = 64;
state->yposit = 9;
oldxposit = 64;
oldyposit = 5;
state->xvelocity = 0;
state->yvelocity = 0;
state->xaccel = 0;
state->yaccel = 0;
}
uint16_t button_pushed(void) {
bool leftButtonPressed = GPIOPinRead(GPIO_PORTE_BASE, 1 << 0);
bool rightButtonPressed = GPIOPinRead(GPIO_PORTE_BASE, 1 << 1);
bool centerButtonPressed = GPIOPinRead(GPIO_PORTE_BASE, 1 << 2);
#ifdef ONBOARDBUTTONS
uint8_t buttonState = ButtonsPoll(0, 0);
leftButtonPressed = (buttonState & ALL_BUTTONS) == LEFT_BUTTON;
rightButtonPressed = (buttonState & ALL_BUTTONS) == RIGHT_BUTTON;
#endif
if (centerButtonPressed) {
//Then there was a pin0 interrupt
if (state.fuel != 0) {
state.fuel--; //using fuel
thrusterAccel = 2.5f;
}
return true;
}
else if (leftButtonPressed) {
//Then there was a pin1 interrupt
state.heading--;
if (state.heading <= WEST) { state.heading = WEST; }
return true;
}
else if (rightButtonPressed) {
//Then there was a pin2 interrupt
state.heading++;
if (state.heading >= EAST) { state.heading = EAST; }
return true;
}
else {
thrusterAccel = 0.0;
return false;
}
}
void draw_terrain_chunk(void) {
for (uint16_t i = state.xposit; i < state.xposit + 9; i++) {
draw_pixel(i, terrain[i], WHITE);
}
}
|
C
|
/*
* Sequential Turn Signal - main.c
* This file contains the microcontroller code to implement sequential turn signals on the Corvette
* (c) 2017 Michael Yuhas
*/
/*
* Includes:
* msp430.h - constants and pin mappings for msp430
*/
#include <msp430.h>
/*
* Definitions:
* TIMER_RESOLUTION_MS - resolution of turn signal timer in milliseconds
* TIMER_RESOLUTION_TICKS - resolution of turn signal timer in ticks of timer A
* P1_INPUT_MASK - input bits on port 1
* P1_RESET_INTERRUPT_FLAG - reset value for port 1
* LEFT_SIGNAL - output bits for the left turn signal on port 1
* LEFT_SIGNAL_1_MASK - output bits for left turn signal pattern 1
* LEFT_SIGNAL_2_MASK - output bits for left turn signal pattern 2
* LEFT_SIGNAL_3_MASK - output bits for left turn signal pattern 3
* LEFT_SIGNAL_4_MASK - output bits for left turn signal pattern 4
* LEFT_SIGNAL_ALL_MASK - all lights in left signal set to active
* LEFT_INPUT_MASK - input bit that controls the left turn signal
* RIGHT_SIGNAL - output bits for the right turn signal on port 1
* RIGHT_SIGNAL_1_MASK - output bits for right turn signal pattern 1
* RIGHT_SIGNAL_2_MASK - output bits for right turn signal pattern 2
* RIGHT_SIGNAL_3_MASK - output bits for right turn signal pattern 3
* RIGHT_SIGNAL_4_MASK - output bits for right turn signal pattern 4
* RIGHT_SIGNAL_ALL_MASK - all lights in right signal set to active
* RIGHT_INPUT_MASK - input bit that controls the right turn signal
*/
#define TIMER_RESOLUTION_MS 1
#define TIMER_RESOLUTION_TICKS 125 * TIMER_RESOLUTION_MS
#define P1_INPUT_MASK 0xC0
#define P1_RESET_INTERRUPT_FLAG 0x00
#define LEFT_SIGNAL 0x38
#define LEFT_SIGNAL_1_MASK 0x30
#define LEFT_SIGNAL_2_MASK 0x28
#define LEFT_SIGNAL_3_MASK 0x18
#define LEFT_SIGNAL_4_MASK 0x00
#define LEFT_SIGNAL_ALL_MASK 0x00
#define LEFT_INPUT_MASK 0x80
#define RIGHT_SIGNAL 0x07
#define RIGHT_SIGNAL_1_MASK 0x03
#define RIGHT_SIGNAL_2_MASK 0x05
#define RIGHT_SIGNAL_3_MASK 0x06
#define RIGHT_SIGNAL_4_MASK 0x00
#define RIGHT_SIGNAL_ALL_MASK 0x00
#define RIGHT_INPUT_MASK 0x40
/*
* Typedefs:
* State - corresponds to the current output pattern of a turn signal
*/
typedef enum { INIT, PATTERN_1, PATTERN_2, PATTERN_3, PATTERN_4 } State;
/*
* Globals:
* tick_count - current number of TIMER_RESOLUTION_MS length ticks that have passed
* input_vector - vector of the input port, set by port 1 interrupt
*/
unsigned int tick_count;
unsigned char input_vector;
/*
* port_one_interrupt - this function executes everytime an interrupt event occurs on P1
* arguments:
* (none)
* returns:
* (none)
*/
#pragma vector=PORT1_VECTOR
__interrupt void port_one_interrupt( void )
{
input_vector = P1IN & P1_INPUT_MASK;
P1IES = input_vector;
P1IFG = P1_RESET_INTERRUPT_FLAG;
__bic_SR_register_on_exit( LPM0_bits );
return;
}
/*
* timer_a_interrupt - this function executes everytime timer A reaches the value in CCR0
* arguments:
* (none)
* returns:
* (none)
*/
#pragma vector=TIMERA0_VECTOR
__interrupt void timer_a_interrupt( void )
{
TACTL = MC_0;
tick_count++;
CCR0 = TIMER_RESOLUTION_TICKS;
TAR = 0;
TACTL = TASSEL_2 | ID_3 | MC_1;
__bic_SR_register_on_exit( LPM0_bits );
return;
}
/*
* left_state_machine - this function keeps track of the left turn signal state machine
* arguments:
* *left_state - pointer to current state
* *next_left - pointer to an integer representing the next time for a state change
* tick_count - current tick count of the timer
* wait_time - amount of time to wait (in ticks) between a state change
* returns:
* (none)
*/
void left_state_machine( State *left_state, unsigned int *next_left, unsigned int tick_count, unsigned int wait_time )
{
// Moore type state machine
switch ( *left_state )
{
// Initialization state
case INIT :
// Check if the left turn signal was activated
if ( ( input_vector & LEFT_INPUT_MASK ) == LEFT_INPUT_MASK )
{
*left_state = PATTERN_1;
*next_left = tick_count + wait_time;
P1OUT = ( P1OUT & RIGHT_SIGNAL ) | LEFT_SIGNAL_1_MASK;
// If the timer hasn't been started yet, start the timer
if ( TACTL == MC_0 )
{
TAR = 0;
CCR0 = TIMER_RESOLUTION_TICKS;
TACTL = TASSEL_2 + ID_3 + MC_1;
}
}
break;
// Pattern 1 on left signal
case PATTERN_1 :
// Check if the left turn signal was turned off
if ( ( input_vector & LEFT_INPUT_MASK ) != LEFT_INPUT_MASK )
{
*left_state = INIT;
P1OUT = ( P1OUT & RIGHT_SIGNAL ) | LEFT_SIGNAL_ALL_MASK;
return;
}
// Check if the time limit in Pattern 1 was reached, if so proceed to pattern 2
if ( tick_count == *next_left )
{
*left_state = PATTERN_2;
*next_left = tick_count + wait_time;
P1OUT = ( P1OUT & RIGHT_SIGNAL ) | LEFT_SIGNAL_2_MASK;
}
break;
// Pattern 2 on left signal
case PATTERN_2 :
// Check if the left turn signal was turned off
if ( ( input_vector & LEFT_INPUT_MASK ) != LEFT_INPUT_MASK )
{
*left_state = INIT;
P1OUT = ( P1OUT & RIGHT_SIGNAL ) | LEFT_SIGNAL_ALL_MASK;
return;
}
// Check if the time limit in Pattern 2 was reached, if so proceed to pattern 3
if ( tick_count == *next_left )
{
*left_state = PATTERN_3;
*next_left = tick_count + wait_time;
P1OUT = ( P1OUT & RIGHT_SIGNAL ) | LEFT_SIGNAL_3_MASK;
}
break;
// Pattern 3 on left signal
case PATTERN_3 :
// Check if the left turn signal was turned off
if ( ( input_vector & LEFT_INPUT_MASK ) != LEFT_INPUT_MASK )
{
*left_state = INIT;
P1OUT = ( P1OUT & RIGHT_SIGNAL ) | LEFT_SIGNAL_ALL_MASK;
return;
}
// Check if the time limit in Pattern 3 was reached, if so proceed to pattern 4
if ( tick_count == *next_left )
{
*left_state = PATTERN_4;
*next_left = tick_count + wait_time;
P1OUT = ( P1OUT & RIGHT_SIGNAL ) | LEFT_SIGNAL_4_MASK;
}
break;
// Pattern 4 on left signal
case PATTERN_4 :
// Check if the left turn signal was turned off
if ( ( input_vector & LEFT_INPUT_MASK ) != LEFT_INPUT_MASK )
{
*left_state = INIT;
P1OUT = ( P1OUT & RIGHT_SIGNAL ) | LEFT_SIGNAL_ALL_MASK;
return;
}
break;
// Default case: reset to Initialization
default :
*left_state = INIT;
P1OUT = ( P1OUT & RIGHT_SIGNAL ) | LEFT_SIGNAL_ALL_MASK;
break;
}
return;
}
/*
* right_state_machine - this function keeps track of the right turn signal state machine
* arguments:
* *right_state - pointer to current state
* *next_right - pointer to an integer representing the next time for a state change
* tick_count - current tick count of the timer
* wait_time - amount of time to wait (in ticks) between a state change
* returns:
* (none)
*/
void right_state_machine( State *right_state, unsigned int *next_right, unsigned int tick_count, unsigned int wait_time )
{
// Moore type state machine
switch ( *right_state )
{
// Initialization state
case INIT :
// Check if the right turn signal was activated
if ( ( input_vector & RIGHT_INPUT_MASK ) == RIGHT_INPUT_MASK )
{
*right_state = PATTERN_1;
*next_right = tick_count + wait_time;
P1OUT = ( P1OUT & LEFT_SIGNAL ) | RIGHT_SIGNAL_1_MASK;
// If the timer hasn't been started yet, start the timer
if ( TACTL == MC_0 )
{
TAR = 0;
CCR0 = TIMER_RESOLUTION_TICKS;
TACTL = TASSEL_2 + ID_3 + MC_1;
}
}
break;
// Pattern 1 on right signal
case PATTERN_1 :
// Check if the right turn signal was turned off
if ( ( input_vector & RIGHT_INPUT_MASK ) != RIGHT_INPUT_MASK )
{
*right_state = INIT;
P1OUT = ( P1OUT & LEFT_SIGNAL ) | RIGHT_SIGNAL_ALL_MASK;
return;
}
// Check if the time limit in Pattern 1 was reached, if so proceed to pattern 2
if ( tick_count == *next_right )
{
*right_state = PATTERN_2;
*next_right = tick_count + wait_time;
P1OUT = ( P1OUT & LEFT_SIGNAL ) | RIGHT_SIGNAL_2_MASK;
}
break;
// Pattern 2 on right signal
case PATTERN_2 :
// Check if the right turn signal was turned off
if ( ( input_vector & RIGHT_INPUT_MASK ) != RIGHT_INPUT_MASK )
{
*right_state = INIT;
P1OUT = ( P1OUT & LEFT_SIGNAL ) | RIGHT_SIGNAL_ALL_MASK;
return;
}
// Check if the time limit in Pattern 2 was reached, if so proceed to pattern 3
if ( tick_count == *next_right )
{
*right_state = PATTERN_3;
*next_right = tick_count + wait_time;
P1OUT = ( P1OUT & LEFT_SIGNAL ) | RIGHT_SIGNAL_3_MASK;
}
break;
// Pattern 3 on right signal
case PATTERN_3 :
// Check if the right turn signal was turned off
if ( ( input_vector & RIGHT_INPUT_MASK ) != RIGHT_INPUT_MASK )
{
*right_state = INIT;
P1OUT = ( P1OUT & LEFT_SIGNAL ) | RIGHT_SIGNAL_ALL_MASK;
return;
}
// Check if the time limit in Pattern 2 was reached, if so proceed to pattern 4
if ( tick_count == *next_right )
{
*right_state = PATTERN_4;
*next_right = tick_count + wait_time;
P1OUT = ( P1OUT & LEFT_SIGNAL ) | RIGHT_SIGNAL_4_MASK;
}
break;
// Pattern 4 on right signal
case PATTERN_4 :
// Check if the right turn signal was turned off
if ( ( input_vector & RIGHT_INPUT_MASK ) != RIGHT_INPUT_MASK )
{
*right_state = INIT;
P1OUT = ( P1OUT & LEFT_SIGNAL ) | RIGHT_SIGNAL_ALL_MASK;
return;
}
break;
// Default case: reset to Initialization
default :
*right_state = INIT;
P1OUT = ( P1OUT & LEFT_SIGNAL ) | RIGHT_SIGNAL_ALL_MASK;
break;
}
return;
}
/*
* main - code entry point
* arguments:
* (none)
* returns:
* (none)
*/
void main( void )
{
WDTCTL = WDTPW | WDTHOLD;
P1REN = 0x00;
P1SEL = 0x00;
P1DIR = 0x3F;
P1OUT = 0x00;
P1IES = 0x00;
P1IFG = 0x00;
P1IE = 0xC0;
TACTL = MC_0;
CCTL0 |= CCIE;
input_vector = 0x00;
State left_state = INIT;
State right_state = INIT;
unsigned int next_left = 0;
unsigned int next_right = 0;
unsigned int wait_time = 200;
WDTCTL = WDTPW | WDT_MRST_8;
__enable_interrupt();
// Calculate Next State -> Set Outputs -> Sleep
while ( 1 )
{
WDTCTL = WDTPW | WDTCNTCL | WDT_MRST_8;
left_state_machine( &left_state, &next_left, tick_count, wait_time);
right_state_machine( &right_state, &next_right, tick_count, wait_time);
__bis_SR_register( LPM0_bits + GIE );
}
}
|
C
|
// Pentcho Tchomakov - 260632861
#include <stdio.h>
#include <stdbool.h>
#include <stdarg.h>
#include <stdlib.h>
// Method to insert spaces
// Once we've added all the stars we wanted in the 2D array, we add spaces to every other coordinates.
// We replace "" with " " when [x][y] doesn't contain a "*"
void fillEmpty(char triangleArray[][1000]) {
// For some reason, we need to declear our "for loop" variables in advance.
// It works in XCode, but not on the ssh/trottier termianls without this.
int j;
int i;
for (j = 1000; j >= 0; j--) {
for (i = 0; i < 1000; i++)
if (triangleArray[i][j] != '*')
triangleArray[i][j]=(' ');
}
}
// When fractal = 0, we print a single triangle at the given coordinates.
// Same as Q1a except in a 2D array
void triangle(int height, char triangleArray[][1000], int x, int y) {
int counter = 0;
// Same thing here, instanciate the variables before the for loops
int j;
int i;
// We add the stars at the given coordinates of the 1000/100
for (j=y; j >= (y - height + 1); j--) {
for (i = x - counter; i <= (x + counter); i++)
triangleArray[i][j] = '*';
counter++;
}
}
// Check every character of the input to see if it's a number
bool isNumber(char number[])
{
int i;
//checking for negative numbers
if (number[0] == '-')
i = 1;
for (i = 0; number[i] != 0; i++)
{
//if (number[i] > '9' || number[i] < '0')
if (!isdigit(number[i]))
return false;
}
return true;
}
int main(int argc, const char * argv[]) {
int height;
// We define a 2D array of size 1000x1000
char triangleArray[1000][1000];
// We check if we have 3 arguments that have been passed
if (argc != 2 || argc > 3) {
printf("ERROR: Please enter a height.\n");
}
// We check that the input only contains digits and is a number
else if (isNumber(height) == false) {
printf("ERROR: Height must be an integer.\n");
}
// Height has to be above 1
else if (height < 1) {
printf("ERROR: Height is too small.\n");
}
// Height cannot be bigger than 128
else if (height >= 128) {
printf("ERROR: Height is too large.\n");
}
// If all conditions pass, we can print our triangle.
else {
// Creates triangle
triangle(height, triangleArray, height-1, height-1);
// Replaces empty chars with spaces " " in the 2D array
fillEmpty(triangleArray);
// Define the variables for the for loops
int j;
int i;
for (j = height - 1; j >= 0; j--) {
for (i = 0; i < (2*height - 1); i++)
printf("%c", triangleArray[i][j]);
// After printing every y coordinate completely, we make a new line.
printf("\n");
}
}
return 0;
}
|
C
|
#include <stdio.h>
long long int fibo[1000000];
int main()
{
long long int t;
scanf("%lld",&t);
long long int i,j;
fibo[0]=0,fibo[1]=1;
for(i=2;i<=1000000;i++)
{
fibo[i]=(fibo[i-1]+fibo[i-2])%(1000000000+7);
}
while(t--)
{
long long int n;
scanf("%lld",&n);
printf("%lld\n",fibo[n]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main() {
int *contro;
int a = 10;
contro = &a;
printf("%d\n", a);
printf("%d\n", *contro);
printf("%d\n", &a);
printf("%d\n", &contro);
int mang[4];
int *contro;
contro = mang;
for (int i = 0; i < 4 ; ++i) {
printf("%d\n", mang[i + 1]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Common.h"
//#define LEVEL1 TRUE
#define LEVEL2 TRUE
void main(int argc, char *argv[])
{
#if defined(LEVEL1)
/*Normal sample*/
struct _BOOKS book1;
BOOK book2 = {"Let it go", "nick", 45};
strcpy(book1.name, "Game of war");
strcpy(book1.author, "hondor");
book1.book_id = 23;
printf("Book_1 info: [%s] [%s] [%d]\n",book1.name,
book1.author,
book1.book_id);
printf("Book_2 info: [%s] [%s] [%d]\n",book2.name,
book2.author,
book2.book_id);
/*Normal sample end*/
#elif defined(LEVEL2)
/*Level2 sample*/
ID_BOOK book;
//book = (ID_BOOK)calloc(1,sizeof(ID_BOOK));
book = (ID_BOOK)malloc(sizeof(BOOK)*1);
strcpy(book->name, "Star war");
strcpy(book->author, "Stark");
book->book_id = 23;
printf("Book_1 info: [%s] [%s] [%d]\n",book->name,
book->author,
book->book_id);
/*Level2 sample end*/
#endif
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include "mysql.h"
int main(int argc, char* argv[]){
MYSQL *conn;
conn = mysql_init(NULL);
if (conn == NULL){
printf("mysql_init failed!\n");
return EXIT_FAILURE;
}
conn = mysql_real_connect(conn, "127.0.0.1", "root", "kjzyw325", "grafana",
0, NULL, 0);
if(conn){
printf("Connection success!\n");
//FILE* fp = NULL;
if (mysql_query(conn, "CREATE DATABASE grafana") == 0){
printf("Database created\n");
}
else{
printf("Database creation failed");
printf("MySQL error message: %s\n", mysql_error(&connection));
exit(1);
}
while(1){
//fp = fopen("memory_usage.txt", "r");
//Create the users_database database
int swap = rand();
int virt = rand();
float phy = rand();
//fscanf(fp, "%d%d%f", &swap, &virt, &phy);
printf("%d %d %f\n",swap, virt, phy);
//fclose(fp);
char str[100];
sprintf(str,
"INSERT INTO random_data (date, value1, value2) VALUES ( NOW(), %d, %d)",
(int) (phy*1024), virt/1024);
int res = mysql_query(conn, str);
if (!res){
printf("Inserted %lu rows", (unsigned long)mysql_affected_rows(conn));
}
else{
fprintf(stderr, "Insert error %d: %s\n", mysql_errno(conn),
mysql_error(conn));
}
sleep(5);
}
}
else{
printf("Connection failed!\n");
}
mysql_close(conn);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h> //strlen
#include <sys/socket.h>
#include <arpa/inet.h> //inet_addr
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include "fctServeur.h"
// fonction qui s'occupe de la recuperation de donnee depuis le fichier text
void recup_donne(struct trainInfo *textarea)
{
FILE *fp;
int j = 0;
char ch;
char line[150];
int line_num = 0;
// tableau de ma structure pour stocker chaque information sur un train
// ouverture du fichier Trains.txt
if ((fp = fopen("Trains.txt", "r")) == NULL)
{
printf("Failure pour lecture!");
exit(0);
}
while (fgets(line,150, fp) != NULL)
{
char temp[45] = " ";
line_num++;
unsigned int label = 0;
for (unsigned int i = 0; i < strlen(line); i++)
{
ch = line[i];
if (ch != ';')
{
temp[j++] = ch;
}
else
{
j = 0;
label++;
switch (label)
{
case 1:
strcpy(textarea[line_num].numero, temp);
break;
case 2:
strcpy(textarea[line_num].depart, temp);
break;
case 3:
strcpy(textarea[line_num].destination, temp);
break;
case 4:
strcpy(textarea[line_num].tempsDepart, temp);
break;
case 5:
strcpy(textarea[line_num].tempsDestination, temp);
break;
case 6:
textarea[line_num].prix = atof(temp);
break;
case 7:
strcpy(textarea[line_num].reduc, temp);
break;
default:
break;
}
memset(temp, 0, sizeof(temp));
}
}
}
promoAction(textarea);
fclose(fp);
}
void promoAction(struct trainInfo *t)
{
for(int i=0;i<getTaille(t);i++)
{
if(strcmp(t[i].reduc,"REDUC") == 0)
{
t[i].prix = t[i].prix -(t[i].prix * 20/100);
}
else if(strcmp(t[i].reduc,"SUPPL") == 0)
{
t[i].prix = t[i].prix + (t[i].prix * (10/100));
}
}
}
// fonction qui renvoit la taille du tableau de structure
// dans notre cas une case vide contient 0.0
int getTaille(struct trainInfo *tab)
{
int nbr = 0;
for(int i =0 ; i<25 ;i++)
{
if(tab[i].prix != 0.0)
{
nbr ++;
}
}
return nbr;
}
// fonction qui fait la recherche d une voyage selon son prix
// utiliser dans la fonction best_price()
struct trainInfo searchByPrice(struct trainInfo *textarea,float prix)
{
int z = getTaille(textarea);
printf(" ==== > %d\n",z);
for(int i =1 ; i<z;i++)
{
if(textarea[i].prix == prix)
{
return textarea[i];
}
}
}
// fonction qui cherche et qui renvoie le trajet le moins chere
struct trainInfo best_price(struct trainInfo *textarea)
{
struct trainInfo tr ;
float bestP = textarea[1].prix;
int z = getTaille(textarea);
for(int i =1 ; i<z ;i++)
{
if(textarea[i].prix < bestP)
{
bestP = textarea[i].prix;
}
}
tr = searchByPrice(textarea,bestP);
return tr;
}
//-----------la fonction search ---------------------------------------------
// fonction qui cherche les voyage possible en fonction de la gare de depart & arriver
void search(struct trainInfo *textarea, struct trainInfo textarea_copy[20], char *depart, char *arrive)
{
int n = 0;
for (int i = 1; i < 20; i++)
{
if ((strcmp(textarea[i].depart, depart) == 0))
{
if ((strcmp(textarea[i].destination, arrive) == 0))
{
textarea_copy[n] = textarea[i];
n++;
}
}
}
}
// fonction qui renvoie les trains possible en fonction du depart ,arrive , heure depart
void searchByTime(struct trainInfo *textarea, struct trainInfo textarea_copy[20], char *depart, char *arrive, char *time)
{
int n = 0;
int z = getTaille(textarea);
for (int i = 1; i < z; i++)
{
// promoAction(&textarea[i]);
if (strcmp(textarea[i].depart, depart) == 0 && strcmp(textarea[i].destination, arrive) == 0 && (strcmp(textarea[i].tempsDepart, time) >= 0))
{
textarea_copy[n] = textarea[i];
n++;
}
}
}
// fonction qui renvoie les voyages possible en fonction du depart arrive heure depart heure d'arriver
void searchByTimeInterval(struct trainInfo *textarea, struct trainInfo textarea_copy[20], char *depart, char *arrive, char *time1, char *time2)
{
int n = 0;
for (int i = 1; i < 20; i++)
{
if ((strcmp(textarea[i].depart, depart) == 0 )&& (strcmp(textarea[i].destination, arrive) == 0))
{
if ((strcmp(textarea[i].tempsDepart, time1) >= 0) )
{
if((strcmp(textarea[i].tempsDestination, time2) <= 0))
{
textarea_copy[n] = textarea[i];
n++;
}
}
}
}
}
// qui s'occupe du traitement de la requete client et le repondre
// la fct recoit la requete du client sous la forme choixdeLaRecherche;villeDepart;villeArriver;....
void receptionDemande(int socket_service)
{
struct trainInfo textarea[100];
struct trainInfo r[25];
char resultat[2000];
recup_donne(textarea);
// on applique les promotion apres avoir stocke les informations sur les trajets
char message_client[100];
char message_save[100];
char *token = " ";
char *tokenI[25];
while (read(socket_service, message_client, 100) > 0)
{
strcpy(message_save, message_client);
int i = 1;
token = strtok(message_save, ";");
while (token != NULL)
{
//affectation
tokenI[i] = token;
token = strtok(NULL, ";");
i++;
}
int mode = atoi(tokenI[1]);
char *depart = tokenI[2];
char *arrive = tokenI[3];
char *tempsDepart = tokenI[4];
char *tempsArrive = tokenI[5];
switch (mode)
{
case 1:
search(textarea, r, depart, arrive);
break;
case 2:
searchByTime(textarea, r, depart, arrive, tempsDepart);
break;
case 3:
searchByTimeInterval(textarea,r,depart,arrive,tempsDepart, tempsArrive);
break;
case 4:
search(textarea, r, depart, arrive);
struct trainInfo t [20];
t[0]=best_price(r);
memset(&r, 0, sizeof(r)+1);
r[0]=t[0];
break;
}
for (int z = 0; z < 20; z++)
{
if (r[z].prix == 0.00)
break;
sprintf(resultat, "%s %s %s %s %s %.2f", r[z].numero, r[z].depart, r[z].destination, r[z].tempsDepart, r[z].tempsDestination, r[z].prix);
sleep(1);
write(socket_service, resultat, sizeof(resultat));
//Initialiser le buffer
memset(message_client, 0, sizeof(message_client));
memset(message_save, 0, sizeof(message_save));
memset(resultat, 0, sizeof(resultat));
}
// envoyer le message END au serveur pour le prevenir que la reponse du seveur et terminer
sleep(1);
char *endMsg = "END";
send(socket_service, endMsg, sizeof(char) * 12, 0);
memset(&r, 0, sizeof(r));
memset(resultat, 0, sizeof(resultat));
memset(message_save, 0, sizeof(message_save));
memset(message_client, 0, sizeof(message_client));
}
}
void finfils(int sig)
{
wait(&sig);
}
// crrer des processus fils qui s occupe de chaque client
// pour avoir plusieur client qui se connecte a la mm fois
void fctServeur(int socket_service)
{
struct sigaction a;
switch (fork())
{
case 0:
// on appel ici la fct serveur ;
receptionDemande(socket_service);
// appres le traitement de la fct serveur
// appel a finfils = > tuer les fils
finfils(sigaction(SIGCHLD, &a, NULL));
break;
}
}
|
C
|
#include <stddef.h>
#include "slist.h"
void init_list_node(list_node_t * node)
{
node->next = NULL;
}
void insert_list_node(list_node_t ** list, list_node_t * node)
{
if ((!list) || (!node))
return;
if (!*list)
{
*list = node;
}
else
{
node->next = *list;
*list = node;
}
}
void delete_list_node(list_node_t ** list, list_node_t * node)
{
list_node_t * iter, * prev;
if ((!list) || (!node))
return;
iter = *list;
prev = (list_node_t *)list;
while(iter)
{
if (iter == node)
{
prev->next = iter->next;
break;
}
prev = iter;
iter = iter->next;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
extern char **environ;
void envlist(){
int i=0;
char *str;
while((str=environ[i])!=NULL){
printf("%s\n",str);
i++;
}
}
int main(int argv,char *argc[]){
//envlist();
if(argv<2){
printf("Error:");
exit(1);
}
char *s = getenv(argc[1]);
printf("%s\n",s);
return 0;
}
|
C
|
/*************************************************************************
> File Name: mpipe.c
> Author:
> Mail:
> Created Time: Fri 27 Jul 2018 04:07:53 PM CST
************************************************************************/
#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#define ERRNO_SUCCESS 1
#define ERRNO_FAIL 0
void main(int argc, char **argv)
{
int fd[2];
pid_t pid;
int ret = 0;
char buff[20] = {0};
if (pipe(fd) < 0)
{
printf("pipe Created error!Errno:%s\n",strerror(errno));
return ERRNO_FAIL;
}
if ((pid = fork()) < 0)
{
printf("child process create error!Error:%s\n",strerror(errno));
return ERRNO_FAIL;
}
else if (pid > 0)
{
printf("pid:%d This is father process!\n",pid);
close(fd[0]);//close read fd
write(fd[1],"hello pipe!\n", 15);
}
else if (pid == 0)
{
printf("pid:%d This is child process!\n",pid);
close(fd[1]);//close write fd
ret = read(fd[0],buff, 20);
if (ret < 0)
{
printf("Read error!errno:%s\n",strerror(errno));
return ERRNO_FAIL;
}
else
{
printf("read:%s\n",buff);
}
}
return ERRNO_SUCCESS;
}
|
C
|
/***
*fscanf.c - read formatted data from stream
*
* Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved.
*
*Purpose:
* defines fscanf() - reads formatted data from stream
*
*******************************************************************************/
#include <cruntime.h>
#include <stdio.h>
#include <dbgint.h>
#include <stdarg.h>
#include <file2.h>
#include <internal.h>
#include <mtdll.h>
/***
*int fscanf(stream, format, ...) - read formatted data from stream
*
*Purpose:
* Reads formatted data from stream into arguments. _input does the real
* work here.
*
*Entry:
* FILE *stream - stream to read data from
* char *format - format string
* followed by list of pointers to storage for the data read. The number
* and type are controlled by the format string.
*
*Exit:
* returns number of fields read and assigned
*
*Exceptions:
*
*******************************************************************************/
int __cdecl fscanf (
FILE *stream,
const char *format,
...
)
/*
* 'F'ile (stream) 'SCAN', 'F'ormatted
*/
{
int retval;
va_list arglist;
va_start(arglist, format);
_ASSERTE(stream != NULL);
_ASSERTE(format != NULL);
_lock_str(stream);
retval = (_input(stream,format,arglist));
_unlock_str(stream);
return(retval);
}
|
C
|
#include<stdio.h>
#include<ctype.h>
int main()
{
int i = 0;
char l[50], u[50];
printf("enter lowercase string\n");
gets(l);
printf("enter uppercase string\n");
gets(u);
while (l[i] != '\0')
{
if (islower(l[i]))
l[i] = toupper(l[i]);
i++;
}
printf("string after converting to uppercase is : %s\n",l);
i = 0;
while (u[i]!='\0')
{
if (isupper(u[i]))
u[i] = tolower(u[i]);
i++;
}
printf("string after converting to lowercase is : %s", u);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.