language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <malloc.h>
#include <sched.h>
#include <synch.h>
#include <callo.h>
#include <string.h>
#include <types.h>
#include <conf.h>
#include <buf.h>
#include <proc.h>
void util1(void) {
struct buf *buf;
int i;
printf("UTIL1 : Demande de [%d, %d] ([dev, blkno])...\n", 0, 0);
buf = getblk(0, 0);
printf("UTIL1 : [%d, %d] obtenu\nUTIL1 : Debut du traitement...\n", 0, 0);
for (i=0;i<4E7;i++);
printf("UTIL1 : Fin du traitement...\n");
printf("UTIL1 : Appel bwrite !B_ASYNC...\n");
strcpy (*(buf -> b_addr),"***UTIL1 MSG***");
bwrite(buf);
printf("####################### fin UTIL1\n");
}
void util2(void) {
struct buf *buf;
int i;
for (i=0;i<4E3;i++);
printf("UTIL2 : Demande de [%d, %d] ([dev, blkno])...\n", 0, 0);
buf = bread(0, 0);
printf ("UTIL2: [%d, %d] obtenu. Contenu: %s\n", 0,0, *(buf->b_addr));
printf("UTIL2 : Debut du traitement...\n");
for (i=0;i<4E7;i++);
printf("UTIL2 : Fin du traitement...\n");
printf("UTIL2 : Appel brelse...\n");
brelse(buf);
/* printfreelist(); */
/* phbuf(); */
printf("####################### fin UTIL2\n");
}
/* Exemples de primitive d'election definie par l'utilisateur */
/* Remarques : les primitives d'election sont appeles directement */
/* depuis la librairie. Elles ne sont apple que si au */
/* moins un processus est l'etat pret (RUN) */
/* Ces primitives manipulent la table globale des processus */
/* dfinie dans sched.h */
/* Election alatoire */
int RandomElect(void) {
int i;
do {
i = (int) ((float)MAXPROC*rand()/(RAND_MAX+1.0));
} while (Tproc[i].p_flag != RUN);
return i;
}
int strategy(void *args) {
printf("Strategy : accs au device %d\n", ((struct buf*)args)->b_dev);
printf("Strategy : Fin e/s dans 50 ticks...\n");
timeout(iodone, args, 50);
return 0;
}
int strategy2() {
printf("\nStrategy2 function...\n\n");
return 0;
}
int main (void) {
int *j;
int dev0, dev1;
dev0 = adddev(&strategy);
pbdevsw();
dev1 = adddev(&strategy2);
pbdevsw();
init_poolbuf(5);
pbuf();
init_hbuf(4, 0x3);
phbuf();
printfreelist();
j = (int *) malloc(sizeof(int));
*j= 0;
CreateProc((function_t)util1, j, 80);
j = (int *) malloc(sizeof(int));
*j= 1;
CreateProc((function_t)util2, NULL, 80);
/* Definir une nouvelle primitive d'election avec un quantum de 1 seconde */
SchedParam(NEW, 1, 100000, RandomElect);
/* Lancer l'ordonnanceur en mode non "verbeux" */
sched(0);
/* Imprimer les statistiques */
PrintStat();
return EXIT_SUCCESS;
}
|
C
|
/////////////////////////////////////////////////////////
// File Name : gen_file.c //
// Date : 2020/10/23 ~ 2020/11/05 //
// OS : Ubuntu 16.04.3 LTS //
// Student Name : Seung Hoon Jeong //
// Student ID : 2015707003 //
// ----------------------------------------- //
// Title : OS_Assignment3-1 //
// Description : random integer write on text file //
/////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PROCESSES 64
int main(void)
{
//// file open ////
FILE *f_write = fopen("./temp.txt","wt");
if(f_write != NULL){
for(int i=0; i<MAX_PROCESSES*2; i++) // write int number on text
fprintf(f_write, "%d\n", 2+rand()%20);
}
fclose(f_write);
//// file close ////
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
/*********** Client APIs ************
# int socket(int protocolFamily, int type, int protocol)
@Params: ProtocolFamily = PF_INET;
type = SOCK_STREAM;
protocol = IPPROTO_TCP
@Return: -1 = Failure
Non-Negative = SocketDescriptor
# int connect(int socket, struct sockaddr *foreignAddress, unsigned int addressLength)
@Params: socket = SocketDescriptor;
foreignAddress = pointer to struct sockaddress_in;
addressLength = sizeof(struct sockaddre_in);
@Return: ????
# int send(int socket, const void *msg, unsigned int msgLength, int flag)
@Params: socket = SocketDescriptor;
*msg = pointer to the message;
msgLength = Number of bytes to be send;
flag = 0, fo default functionality;
# int recv(int socket, void *recvBuffer, unsigned int msgLength, int flag)
@Params: socket = SocketDescriptor;
*msg = pointer to the buffer where msg needs to be copy;
msgLength = Number of bytes that can be receive at once;
flag = 0, fo default functionality;
# int close(int socket)
@Params: SocketDescriptor;
@Return: 0 = success;
-1 = failure;
# struct sockaddr
{
unsigned short sa_family;
char sa_data[14];
};
# struct sockaddr_in
{
unsigned short sin_family;
unsigned short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
# struct in_addr
{
unsigned long s_addr;
};
*/
#define RECV_BUFF_SIZE 500
void main()
{
int SocketDescriptor;
struct sockaddr_in serverAddress;
unsigned char buff[100];
unsigned int buffLen;
printf("Enter the command:");
memset(buff, 0, sizeof(buff));
fgets(buff, sizeof(buff), stdin);
printf("%s", buff);
buffLen=strlen(buff)-1;
buff[buffLen]=0;
printf("\n%s:%d\n", buff, buffLen);
if((SocketDescriptor = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
printf("Cannot create socket\n");
return;
}
memset(&serverAddress,0,sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(9100);
serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
if(connect(SocketDescriptor, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) < 0)
{
printf("Cannot connect to Server\n");
}
else
{
if(send(SocketDescriptor, buff, buffLen, 0) != buffLen)
{
printf("Error in transmission\n");
}
else
{
signed int NoOfBytesRecvd=0, TotalNoOfBytesRecvd=0;
char *recvBuff = (char *)malloc((TotalNoOfBytesRecvd+RECV_BUFF_SIZE+1)*sizeof(char));
NoOfBytesRecvd = recv(SocketDescriptor, recvBuff+TotalNoOfBytesRecvd, RECV_BUFF_SIZE, 0);
TotalNoOfBytesRecvd = TotalNoOfBytesRecvd + NoOfBytesRecvd;
// while((NoOfBytesRecvd = recv(SocketDescriptor, recvBuff+TotalNoOfBytesRecvd, RECV_BUFF_SIZE, 0)) > 0)
// {
// TotalNoOfBytesRecvd = TotalNoOfBytesRecvd + NoOfBytesRecvd;
// *(recvBuff+TotalNoOfBytesRecvd) = 0;
// recvBuff = realloc(recvBuff, (TotalNoOfBytesRecvd+RECV_BUFF_SIZE+1)*sizeof(char));
// }
recvBuff = realloc(recvBuff, (TotalNoOfBytesRecvd+RECV_BUFF_SIZE)*sizeof(char));
*(recvBuff+TotalNoOfBytesRecvd) = 0;
printf("%s", recvBuff);
free(recvBuff);
}
}
close(SocketDescriptor);
};
|
C
|
/*
** EPITECH PROJECT, 2019
** pop
** File description:
** delete peek in stack
*/
#include "new.h"
#include <stdlib.h>
char pop(stack_t **head)
{
stack_t *node;
char previous_data = (*head)->data;
if (*head == NULL) {
exit(1);
}
else {
node = *head;
*head = (*head)->next;
free(node);
}
return previous_data;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include"game.h"
#include<stdlib.h>
#include<time.h>
//Ϸпչʤ㷨3*3
void game()//Ϸ
{
char board[ROW][COL] = {0};
init_board(board, ROW, COL);//ʼȫΪո
display_board(board, ROW, COL);//ʾ̣
char ret = 'a';
while (1)
{
//
PlayerMove(board, ROW, COL);
display_board(board, ROW, COL);
//жʤ
ret = IsWin(board, ROW, COL);
if (ret != 'C')
{
break;
}
//
ComputerMove(board, ROW, COL);
display_board(board, ROW, COL);
//жϵʤ
ret = IsWin(board, ROW, COL);
if (ret != 'C')
{
break;
}
}//ѭ
if (ret == '*')
{
printf("ʤ\n");
}
else if (ret == '#')
{
printf("ʤ\n");
}
else
{
printf("ƽ\n");
}
}
void menu()//ӡĿ¼
{
printf("*************************\n");
printf("**** 1.play 2.exit ****\n");
printf("*************************\n");
}
void test()//Ϸ˵ѡж
{
int input = 0;
do
{
menu();
printf("ѡ>:");
scanf("%d", &input);
switch (input)
{
case 1:
printf("\nʼϷ\n");
game();
break;
case 0:
printf("\nϷ˳\n");
break;
default:
printf("\nѡ\n");
break;
}
}
while (input);
}
int main()
{
srand((unsigned int)time(NULL));
test();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool shaunIsFast = true; //else true
printf("How fast tho (1 is flash, 0 is slowpo)? %i\n ", shaunIsFast);
printf ("%i\n", shaunIsFast + 11);
return 0;
}
|
C
|
/*
* File: main.c
* Author: peter
*
* Using threads to solve producer consumer problem
* Interprocess Communication, p.133
* Tanenbaum A., S., "Modern Operating Systems, 3rd edition"
*
* Created on June 7, 2014, 6:38 PM
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX 100
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0; /* buffer used between consumer and producer */
void *producer( void *ptr) {
int i = 1;
for ( ; i <= MAX; i++) {
/* get exclusive access to buffer */
pthread_mutex_lock( &the_mutex);
while ( buffer != 0) pthread_cond_wait( &condp, &the_mutex);
/* put item in buffer */
buffer = i;
printf( "producer:%d\n", buffer);
fflush( stdout);
/* wake up consumer */
pthread_cond_signal( &condc);
/* release access to buffer */
pthread_mutex_unlock( &the_mutex);
}
pthread_exit(0);
}
void *consumer( void *ptr) {
int i = 1;
for ( ; i <= MAX; i++) {
/* get exclusive access to buffer */
pthread_mutex_lock( &the_mutex);
while ( buffer == 0) pthread_cond_wait( &condc, &the_mutex);
/* take item out of buffer */
buffer = 0;
printf( "consumer:%d\n", buffer);
fflush( stdout);
/* wake up producer */
pthread_cond_signal( &condp);
/* release access to buffer */
pthread_mutex_unlock( &the_mutex);
}
pthread_exit(0);
}
/*
*
*/
int main(int argc, char** argv) {
pthread_t pro, con;
pthread_mutex_init( &the_mutex, 0);
pthread_cond_init( &condc, 0);
pthread_cond_init( &condp, 0);
pthread_create( &con, 0, consumer, 0);
pthread_create( &pro, 0, producer, 0);
pthread_join( pro, 0);
pthread_join( con, 0);
pthread_cond_destroy( &condc);
pthread_cond_destroy( &condp);
pthread_mutex_destroy( &the_mutex);
return (EXIT_SUCCESS);
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "parser.h"
#include "config.h"
char * epurate_string(const char *to_epurate)
{
char *epurated;
char *tmp;
if (to_epurate == NULL)
return NULL;
epurated = malloc(sizeof(char) * strlen(to_epurate) + sizeof(char));
tmp = epurated;
if (epurated == NULL)
return NULL;
while (*to_epurate)
{
if (*to_epurate != ' ' && *to_epurate != '\t'
&& *to_epurate != '\n')
*tmp++ = *to_epurate;
to_epurate++;
}
*tmp = 0;
return epurated;
}
int is_comment(const char *to_check)
{
if (to_check == NULL)
return -EINVAL;
if (*to_check == COMMENT || *to_check == '\0')
return 1;
return 0;
}
char * get_token(char *to_parse, const char *delim)
{
return strtok(to_parse, delim);
}
|
C
|
//ʵʹabʾcʱ临ӶȴN3͵N2ﲻ֮ͽװ
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(void)
{
int *book,i,m, n, x, y, z,sum=0;
book = (int*)malloc(sizeof(int) * 1111);//һ£24»ܴ1111
printf_s("жٸ");
scanf_s("%d",&m);
n = m - 4;//ںź͵ȺҪռĸ
//õ1-9ijʼ
for (i=0;i<=9;i++)
{
printf_s("book[%d]Ҫٸ:",i);
scanf_s("%d",&book[i]);
}
//õλĻ
for ( i = 10; i < 1111; i++)
{
if (i <= 99)
book[i] = book[i / 10] + book[i % 10];
else if (i >= 100 && i <= 999)
book[i] = book[i / 100] + book[i % 100 / 10] + book[i % 100 % 10];
else
book[i] = book[i / 1000] + book[i % 1000 / 100] + book[i % 1000 % 100 / 10] + book[i % 1000 % 100 % 10];
}
//㷨
for ( x = 0; x < 1111; x++)
{
for ( y = 0; y < 1111; y++)
{
for ( z = 0; z < 1111; z++)
{
if (book[x] + book[y] + book[z] == n && x + y == z)
{
sum++;//¼ϸ
printf_s("%d+%d=%d\n",x,y,z);
}
}
}
}
printf_s("Ϲ%d", sum);
//over
system("pause");
return 0;
}
|
C
|
/* Includes */
#include <avr/io.h>
#include "direction.h"
#include "modeswitches.h"
#include "cleaner.h"
#include "main.h"
#define F_CPU 1000000UL
#include <util/delay.h>
int main(void)
{
// Setup I/O
MainInitialize();
// Main program loop
while(1)
{
// Clean x axis
MainCleanerX(DirectionGetLeftState(), DirectionGetRightState());
// Note:
// Would like to implement local and remote mode by doing: MainCleanerX(DirectionGetLeftState(), DirectionGetRightState(), ModeSwitchesRemote());
// Or something like that!
// Clean y axis
MainCleanerY(DirectionGetDownState(), DirectionGetUpState());
// Would like to implement local and remote mode by doing: MainCleanerX(DirectionGetDownState(), DirectionGetUpState(), ModeSwitchesRemote());
// Or something like that!
}
return(0);
}
void MainCleanerX(uint8_t tempLeftState, uint8_t tempRightState)
{
// Cleaning for x axis
if(ModeSwitchesX() == 0)
{
CleanerXNeutral(tempLeftState, tempRightState);
}
else if(ModeSwitchesX() == 1)
{
CleanerXLeft(tempLeftState, tempRightState);
}
else if(ModeSwitchesX() == 2)
{
CleanerXRight(tempLeftState, tempRightState);
}
else
{
CleanerXLastInput(tempLeftState, tempRightState);
}
}
void MainCleanerY(uint8_t tempDownState, uint8_t tempUpState)
{
// Cleaning for y axis
if(ModeSwitchesY() == 0)
{
CleanerYNeutral(tempDownState, tempUpState);
}
else if(ModeSwitchesY() == 1)
{
CleanerYDown(tempDownState, tempUpState);
}
else if(ModeSwitchesY() == 2)
{
CleanerYUp(tempDownState, tempUpState);
}
else
{
CleanerYLastInput(tempDownState, tempUpState);
}
}
void MainInitialize()
{
// Set all ports to be configured as inputs
DDRB = 0b00000000;
DDRC = 0b00000000;
DDRD = 0b00000000;
// Disable all internal pull-up resistors
PORTB = 0b00000000;
PORTC = 0b00000000;
PORTD = 0b00000000;
// Enable necessary internal pull-up resistors
PORTB |= (1 << MAIN_RIGHT_BUTTON_PULLUP);
PORTB |= (1 << MAIN_LEFT_BUTTON_PULLUP);
PORTB |= (1 << MAIN_DOWN_BUTTON_PULLUP);
PORTB |= (1 << MAIN_UP_BUTTON_PULLUP);
PORTC |= (1 << MAIN_DIP5_SW1_PULLUP);
PORTC |= (1 << MAIN_DIP5_SW2_PULLUP);
PORTC |= (1 << MAIN_DIP5_SW3_PULLUP);
PORTC |= (1 << MAIN_DIP5_SW4_PULLUP);
PORTC |= (1 << MAIN_DIP5_SW5_PULLUP);
PORTD |= (1 << MAIN_DIP2_SW1_PULLUP);
PORTD |= (1 << MAIN_DIP2_SW2_PULLUP);
PORTB |= (1 << MAIN_PRESET_BUTTON_PULLUP);
// Set specific port bits to be configured as outputs
DDRD = DDRD | (1 << DIRECTION_SW1_CLEAN);
DDRD = DDRD | (1 << DIRECTION_SW2_CLEAN);
DDRD = DDRD | (1 << DIRECTION_SW3_CLEAN);
DDRD = DDRD | (1 << DIRECTION_SW4_CLEAN);
// Default Button Positions
DirectionReleaseLeft(0);
DirectionReleaseRight(0);
DirectionReleaseDown(0);
DirectionReleaseUp(0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* cosa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cjover-n <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/15 12:48:52 by cjover-n #+# #+# */
/* Updated: 2019/09/15 17:54:46 by cjover-n ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
void col_up();
void col_down();
void row_left();
void row_right();
void whileando(int contu, int contd, int contl, int contr, char table[4][4])
{
while (contu <= 4)
{
while (countd <= 4)
{
while (contl <= 4)
{
while (contr <= 4)
{
//TODO: Sacar respuesta encasillada (usar funciones llamadas si es necesario)
if (col_up (1, , , ) && col_down (1, , , )
{
table[0][0] = 4;
}
//TODO: Convertir respuesta a char para guardar en tabla
table[contu - 1][contl - 1] = ; //TODO: Respuesta encasillada
//TODO: Escribir Respuesta desde array (se puede hacer aparte en otro archivo con dos while)
contr++;
}
contl++;
}
contd++;
}
contu++;
}
}
void logica()
{
int contu;
int contd;
int contl;
int contr;
char table[4][4];
contu = 1;
contd = 1;
contl = 1;
contr = 1;
whileando(contu, contd, contl, contr, table);
}
|
C
|
#pragma once
#include "../imagelib/image.h"
#define PRIME 997
#define RADIX 3
#define BLACK 0
#define WHITE 127
#define GRAY 64
/*
Definimos este operador para imitar el operador módulo de Python (%), de tal
manera que se comporte bien con números negativos también.
Basado en: https://www.lemoda.net/c/modulo-operator/
*/
#define MOD(a,b) ((((a)%(b))+(b))%(b))
void find_hash(Image* original, int col, int row, long* hashes);
int change_pixels(Image* original, Image* pattern, Image* out_image, int row, int col);
void col_rolling(Image* original, Image* pattern, long* original_hashes, int next_row);
void search(Image* original, Image* out_image, Image* pattern);
int coords2index(Image* image, int row, int col);
long power(long a, long n, long m);
|
C
|
#include <stdio.h>
#include <stdlib.h>
void hello (int a)
{
std::cout << "Hello World!" << std::endl;
}
void show(int x[][9] , int m , int n){
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
printf("%d ",x[i][j]);
}
printf("\n");
}
printf("\n");
}
void findc(int* c){
switch (*c) {
case 0:
case 1:
case 2:
*c = 1;
return;
case 3:
case 4:
case 5:
*c= 4;
return;
case 6:
case 7:
case 8:
*c = 7;
return;
}
}
//0 for false ; 1 for true
int isValid(int arr[9][9],int x, int y,int num){
int check = 1;
int i,j;
//row checking
for ( i = 0; i < 9 ; ++i) {
if(i == x){
continue;
}
if(arr[i][y] == num){
check = 0;
return check;
}
}
// column check
for (j = 0; j < 9; ++j) {
if(j == y){
continue;
}
if(arr[x][j] == num){
check = 0;
return check;
}
}
// block checking
i = x;
j = y;
findc(&i);
findc(&j);
for (int k = i-1; k < i+2; ++k) {
for (int l = j-1; l < j+2 ; ++l) {
if(k == x && l == y){
continue;
}
if(arr[k][l] == num){
check = 0;
return check;
}
}
}
return check;
}
void whenDone(int arr[9][9]){
for (int i = 0; i < 9; ++i) {
int sum = 0;
for (int j = 0; j < 9; ++j) {
sum = sum + arr[i][j];
}
if(sum != 55){
return;
}
}
show(arr,9,9);
}
void solve(int arr[9][9]){
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
if(arr[i][j] == 0){
for (int k = 1; k <= 9; ++k) {
if(isValid(arr,i,j,k)){
arr[i][j] = k;
whenDone(arr);
solve(arr);
arr[i][j] = 0;
}
if(k == 9){
arr[i][j] = 0;
return;
}
}
if(!(isValid(arr,i,j,1) || isValid(arr,i,j,2) || isValid(arr,i,j,3) || isValid(arr,i,j,4) || isValid(arr,i,j,5) || isValid(arr,i,j,6) || isValid(arr,i,j,7) || isValid(arr,i,j,8) || isValid(arr,i,j,9))){
arr[i][j] = 0;
return;
}
}
}
}
show(arr,9,9);
exit(0);
}
int main() {
int arr[9][9];
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
scanf("%d",&arr[i][j]);
}
}
printf("\n");
solve(arr);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
int main() {
int fd,ret;
char b[10];
memset(b,0,sizeof(b));
fd=open("/dev/hrt_1",O_RDWR);
printf("%d",fd);
if (fd < 0)
{
printf("Open Errrrr");
return -1;
}
ret=write(fd,&b,sizeof(b));
printf("%d",ret);
if (ret < 0 )
{ printf("write Errr");
return ret;
}
sleep(1);
close(fd);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct lista{
int num;
struct lista* prox;
}lista;
typedef struct pilha{
int quantidade;
lista* topo;
}pilha;
pilha * cria(){
pilha*p=(pilha*)malloc(sizeof(pilha));
p->topo=NULL;
return p;
}
void insere_pilha(pilha*p, int valor) {
lista*v = (lista*) malloc (sizeof(lista));
v->num = valor;
v->prox = p->topo;
p->topo = v;
p->quantidade++;
}
int pilha_vazia(pilha* p){
return p->topo == NULL;
}
void remover(pilha*p){
if(pilha_vazia(p)){
return;
}
lista*aux;
aux=p->topo;
p->topo=p->topo->prox;
free(aux);
}
void imprime(pilha* p){
lista* l;
printf("\n");
if (p == NULL || p->topo == NULL){
printf("Lista vazia!");
return;
}
for (l = p->topo; l != NULL; l = l->prox){
printf("%d ", l->num);
}
}
int main(){
char v, v2 = 0;
char cd;
int var;
pilha*p1=cria();
pilha*p2=cria();
while(v != '=' || v != '\n'){
scanf("%c", &v);
while(v == '0'){
var=0;
}var=1;
int valor = v-48;
if(var==1){
printf("valor: %d v: %c \n", valor, v);
}
}
//scanf("%c", &v);
//int valor = v-48;
//printf("s %d", valor);
/*while(v != '='){
scanf("%c", &v);
int valor = v-48;
while(valor==0){
var=0;
}var==1;
if(var==1){
printf("%d", valor);
}
if(v == '+'){
printf("p2");
p2 = (pilha*)malloc(sizeof(pilha));
p2->topo = NULL;
p2->quantidade = 0;
}
}*/
return 0;
}
|
C
|
void insertionSort(long arr[], long n);
long test() {
long a[5];
a[0] = 5;
a[1] = 4;
a[2] = 3;
a[3] = 1;
a[4] = 2;
insertionSort(a, 5);
if (a[0] == 1 && a[1] == 2 && a[2] == 3 && a[3] == 4 && a[4] == 5) {
return 1;
} else {
return 0;
}
}
void insertionSort(long arr[], long n)
{
long i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
|
C
|
/*Разширяване на заделена памет с realloc
Напишете програма, която пита потребителя колко
памет иска и заделя съответния блок памет. След
това попитайте потребителя за нов размер и
използвайте функция, която прави това.*/
#include <stdio.h>
#include <stdlib.h>
int funRealloc(int *ARR);
int main(){
unsigned uSize=0;
int *arr;
printf("Eneter how many elemets you need \n");
scanf(" %d",&uSize);
arr=(int*)calloc(uSize,sizeof(int));
if(arr== NULL){
printf("allocation memory error!\n");
}
else{
printf("adresses of reallocated memory : %p\n", arr);
}
funRealloc(arr);
free(arr);
}
int funRealloc(int *ARR){
unsigned newSize=0;
printf("Enter new size\n");
scanf(" %d",&newSize);
ARR= realloc(ARR,newSize*sizeof(int));
if(ARR== NULL){
printf("allocation memory error!\n");
}
else{
printf("adresses of reallocated memory : %p\n", ARR);
}
}
|
C
|
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAXSTACK 25
#define TRUE 1
#define FALSE 0
struct stack
{
char expr[MAXSTACK];
int top;
};
int empty(struct stack*); /* function prototype for empty; returns TRUE if stack is empty, FALSE otherwise */
void initStack(struct stack*); /* function prototype for initStack; initialises the stack to empty state */
void push(struct stack*, char); /* function prototype for push */
char pop(struct stack*); /* function prototype for pop */
int priorityCheck(char, char); /* function prototype for priorityCheck; returns TRUE if incoming operator's precedence is greater than stacktop operator, FALSE otherwise */
int main(void)
{
struct stack s;
int i=0, j=0;
char infix[MAXSTACK], postfix[MAXSTACK], popped;
initStack(&s);
printf("Enter an infix expression: ");
gets(infix);
while(i<strlen(infix))
{
if(infix[i] == '(')
{
push(&s, infix[i]);
i++;
continue;
}
if(infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/' || infix[i]=='^')
{
popped = pop(&s);
if(popped == 'F')
{
push(&s, infix[i]);
i++;
continue;
}
if(popped == '(')
{
push(&s, popped);
push(&s, infix[i]);
i++;
continue;
}
if(priorityCheck(infix[i],popped))
{
push(&s, popped);
push(&s, infix[i]);
i++;
continue;
}
else
{
postfix[j] = popped;
j++;
continue;
}
}
if(infix[i] == ')')
{
while((popped = pop(&s))!='(')
{
postfix[j] = popped;
j++;
}
i++;
}
else
{
postfix[j] = infix[i];
j++;
i++;
}
}
while((popped = pop(&s))!='F')
{
postfix[j] = popped;
j++;
}
postfix[j] = '\0';
printf("\nThe equivalent postfix expression is: %s\n", postfix);
getch();
return 0;
}
/* function definition for empty */
int empty(struct stack *ps)
{
if(ps->top == -1)
return TRUE;
else
return FALSE;
}
/* function definition for initStack */
void initStack(struct stack *ps)
{
ps->top = -1;
}
/* function definition for push */
void push(struct stack *ps, char c)
{
if(ps->top == MAXSTACK-1)
{
printf("Overflow!");
}
else
{
ps->top = (ps->top)+1;
ps->expr[ps->top] = c;
}
}
/* function definition for pop */
char pop(struct stack *ps)
{
char pitem;
if(empty(ps))
return 'F';
else
{
pitem = ps->expr[ps->top--];
return pitem;
}
}
/* function to check priority of incoming operator */
int priorityCheck(char incoming, char stacktop)
{
if(incoming == '^')
return TRUE;
else
{
if(incoming == '+' || incoming == '-')
return FALSE;
else
{
if(stacktop == '*' || stacktop == '/')
return FALSE;
return TRUE;
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct element
{
int value;
struct element *next;
};
int main(void)
{
int values[10] = { 2, 4, 5, 6, 7, 8, 9, 1, 3, 0};
struct element *q = malloc(sizeof(struct element)), *cur = q, *temp;
for (int i = 0; i < 9; ++i, cur = cur->next)
cur->value = values[i], cur->next = malloc(sizeof(struct element));
cur->value = values[9];
cur->next = NULL;
printf(" First 5 values:\n");
cur = q;
for (int i = 0; i < 5; ++i, cur = cur->next)
printf("%d\n", cur->value);
printf(" First 7 values:\n");
cur = q;
for (int i = 0; i < 7; ++i, cur = cur->next)
printf("%d\n", cur->value);
for (cur = q; cur != NULL; cur = temp)
{
temp = cur->next;
free(cur);
}
printf(" Memory is freed");
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int n,a[50],b[50],n1,n2,larg[50],i,j,k;
scanf("%d",&n1);
for(i=0;i<n1;i++)
{
scanf("%d",&a[i]);
}
scanf("%d",&n2);
for(i=0;i<n2;i++)
{
scanf("%d",&b[i]);
}
for(i=0;i<n1;i++)
{
larg[i]=a[i];
}
n=n1+n2;
for(i=0,k=n1;k<n&&i<n2;i++,k++)
{
larg[k]=b[i];
}
printf("after merging \n");
for(i=0;i<n;i++)
{
printf("%d",larg[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "irregular.h"
void sep() {
printf("+%.*s+", WORD_SIZE + 2, "-------------------------------------------------------------------" );
printf("%.*s+", WORD_SIZE + 2, "-------------------------------------------------------------------" );
printf("%.*s+\n", WORD_SIZE + 2, "-------------------------------------------------------------------" );
}
int main() {
int rnd = 0;
system("clear");
printf("This simple software created for memorize irregular verbs. Please press ENETER to get the answer\n");
printf("Number of words: %d\n\n", number_of_words);
srand(time(NULL));
for (;;) {
rnd = rand() % number_of_words;
printf("?: %s ", words[rnd][0] );
if (getchar() == '\n') {
sep(); printf("| %-20s | %-20s | %-20s |\n", "1st", "2nd", "3rd");
sep(); printf("| %-20s | %-20s | %-20s |\n", words[rnd][0], words[rnd][1], words[rnd][2]);
sep();
if (getchar())
system("clear");
}
}
return 0;
}
|
C
|
/*
You have to print the character, ch, in the first line.
Then print s in next line.
In the last line print the sentence, sen.
Sample input:
C
Language
Welcome To C!!
Sample output:
C
Language
Welcome To C!!
*/
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
int main()
{
char ch, s[MAX_LEN], sen[MAX_LEN];
scanf("%c", &ch);
scanf("\n"); // discard newline from previous statement
scanf("%[^\n]%*c", s);
scanf("%[^\n]%*c", sen);
printf("%c\n%s\n%s", ch, s, sen);
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct emp
{
int id;
char name[20];
float sal;
float ded;
float bon;
};
struct dep
{
char name[20];
struct emp e[3];
};
void main()
{
struct dep d1;
float net[3];
int i;
clrscr();
printf("\nenter the dept name:");
scanf("%s",&d1.name);
for(i=0;i<3;i++)
{
printf("\nenter the Employee[%d] id:",i);
scanf("%d",&d1.e[i].id);
printf("\nenter the Employee[%d] name:",i);
scanf("%s",d1.e[i].name);
printf("\nenter the Employee[%d] salary:",i);
scanf("%f",&d1.e[i].sal);
printf("\nenter the Employee[%d] Deduction:",i);
scanf("%f",&d1.e[i].ded);
printf("\nenter the Employee[%d] Bonus:",i);
scanf("%f",&d1.e[i].bon);
net[i]=d1.e[i].sal-d1.e[i].ded-d1.e[i].bon;
}
clrscr();
printf("\n the depart name is:");
puts(d1.name);
for(i=0;i<3;i++)
{
printf("\nthe id of Employee is:%d \nthe name of Employee is:%s \nthe net salary is:%f",d1.e[i].id,d1.e[i].name,net[i]);
}
getch();
}
|
C
|
#include "includes.h"
#include <stdarg.h>
#include "JLINKDCC.h"
#define LCDNUM_ONLY_1 1
#define LCDFUNC_WRITE_LCD 0x61
#define LCDFUNC_CLEAR_LCD 0x62
#define LCD_PERLINE_MAX 24
#define LCD_LINE_MAX 2
const U8 ClearLineData[] = "00";
void LCD_DisplayALine(U8 line, U8 * str);
void LCD_Clear(U8 line);
void LCD_DisplayAItem(U8 * str);
void LCD_DisplayResult(U32 res);
INT32U Dprintf(char *lpszFormat, ...)
{
char DisplayBuff[100] = {0};
va_list fmtList;
// 1. ַϳ
va_start( fmtList, lpszFormat );
vsprintf( DisplayBuff, lpszFormat, fmtList );
va_end( fmtList );
// 2. ϳɺַѹͻ
JLINKDCC_SendString((const char * )DisplayBuff);
UART_WriteStr( (UCHAR *)DisplayBuff );
LOGFILE_AddItem( (UCHAR *)DisplayBuff );
return 0;
}
static void LCD_Printf(U8 * str)
{
U8 prtStr[50];
sprintf((char *)prtStr, "%s\r\n", (char * )str);
Dprintf((char * )prtStr);
}
static char* StrCpy(char* ds, char* ss)
{
while(*ss)
*ds++ = *ss++;
return ds;
}
static void StrnCpy(char* ds, char* ss, int n)
{
for(int i=0;i<n;i++)
{
*ds++ = *ss++;
}
}
static BOOL LCD_WriteCmd(U8 func, U8 reg, U8 * WriteStr)
{
return(MERAK_WriteCmd("LCD", LCDNUM_ONLY_1, func, reg, WriteStr));
}
void LCD_DisplayALine(U8 line, U8 * str)
{
LCD_WriteCmd(LCDFUNC_WRITE_LCD, line, (U8 * )str);
LCD_Printf(str);
}
void LCD_Display2Line(U8 startline, U8 * str)
{
U8 i;
U8 lcdStr1[LCD_PERLINE_MAX+1],lcdStr2[LCD_PERLINE_MAX+1]={0};
StrnCpy((char * )lcdStr1, (char * )str, LCD_PERLINE_MAX);
StrCpy((char * )lcdStr2, (char * )(str+LCD_PERLINE_MAX));
lcdStr1[LCD_PERLINE_MAX] = 0;
lcdStr2[LCD_PERLINE_MAX] = 0;
LCD_DisplayALine(startline, lcdStr1);
LCD_DisplayALine(startline+1, lcdStr2);
LCD_Printf(lcdStr1);
LCD_Printf(lcdStr2);
}
void LCD_Clear(U8 line)
{
LCD_WriteCmd(LCDFUNC_CLEAR_LCD, line, (U8 * )"");
}
void LCD_DisplayAItem(U8 * str)
{
if(* str == 0)
{
return;
}
LCD_Clear(LCD_ALL_LINE);
LCD_DisplayALine(LCD_LINE1, str);
}
void LCD_DisplayResult(U32 res)
{
if(res == PASS)
{
LCD_DisplayALine(LCD_LINE3, (U8 *)"PASS!");
}
else
{
LCD_DisplayALine(LCD_LINE3, (U8 *)"FAIL!");
}
}
|
C
|
#include <stdio.h>
/*
* C ѧϰ֮·
* 2021-8-4
* Ҫѧϰָ롣
*/
const int MAX = 3;
const int LENGTH = 10;
struct Stu{
char name[20];
short age;
char sex[5];
};
void fun1(void);
void fun2(void);
void fun3(void);
void fun4(void);
void fun5(void);
void fun6(void);
void print1(struct Stu tmp);
void print2(struct Stu *tmp);
void select_sort(int * arr,int size);
void InsertionSort(int *arr, int size);
int main() {
int arr[]={10,29,1,80,66,77,30,100,5,17};
int size = sizeof (arr)/sizeof (arr[0]);
InsertionSort(arr,size);
for(int i=0;i<size;i++){
printf("%d ",arr[i]);
}
return 0;
}
/*
*ʱ临ӶO(n^2) ռ临ӶO(1)
*壺һԪؿһ˳˳еݰԱȣβ
*/
void InsertionSort(int *arr, int size)
{
int i, j, tmp;
//һԪؿһ˳ӵڶʼֱһԪ
for (i = 1; i < size; i++) {
// ǰԪ < ǰһԪ
if (arr[i] < arr[i-1]) {
// tmp ¼ǰԪصֵ
tmp = arr[i];
//i±֮ǰӡj , ... , 0Ԫء עj = i - 1
//Ҫ ÿαarr[j]Ԫ > tmp
for (j = i - 1; j >= 0 && arr[j] > tmp; j--) {
//±ΪjԪظֵj+1Ԫ
arr[j+1] = arr[j];
}
/*For Example:arr[]={1,10,29,80,66,77,30,100,5,17}
* Ԫ66ʱ arr[i] == 66
* 66 С 80 ==> arr[i] < arr[i-1]
* tmp 66 ==> tmp = arr[i];
* i±֮ǰԪ(ұÿαarr[j]Ԫ tmp )
* һѭ j=3 arr[j]=80 8066;
* ԪΪ60λϣֵ80; j--;
* ڶѭ Ϊ29 С 60,
* ѭ
*ʱj=2arr[j]=29,Ϊ29 С 60Ҳʹ60Ҫ29ĺ
*ࣺ60Ҫֵarr[j+1]
*arr[j+1] = tmp;
*/
arr[j+1] = tmp;
}
}
}
/*ѡ(ѡ)
* ʱ临ӶO(n^2) ռ临ӶO(1)
* 壺һҵСһԪغλãٴӵڶԪؿʼҵСڶԪغ
*
*/
void select_sort(int *arr,int size){
//i,j ѭk ¼Сֵ±ꣻtemp ¼Сֵ
int i,j,k,temp;
// i < size-1 ? ֱĵڶԪأܺ͵һбȽϣһ
for(i=0;i<size-1;i++){
//Ĭϴ洢ǰ±
k=i;
for(j=i+1;j<size;j++){
//arr[j]<arr[i]
if(arr[j]<arr[k]){
k=j;//k ¼Сֵ±
}
}
//Ԫصλ
temp = arr[k];
arr[k] = arr[i];
arr[i] = temp;
}
}
//ṹ崫
void print1(struct Stu tmp){
printf("name is %s\n",tmp.name);
printf("age is %d\n",tmp.age);
printf("sex is %s\n",tmp.sex);
}
//ṹָ봫 ᳫ÷ ɣʡϵͳռĿ
void print2(struct Stu *tmp){
printf("name is %s\n",tmp->name);
printf("age is %d\n",tmp->age);
printf("sex is %s\n",tmp->sex);
}
/*ָ
*ָ͵壺
* 1.ָòʱܹʼֽ
* 2.ָǰ߶루
*/
void funPointer(){
int arr[]={10,20,30,40,50,60,70,80,90,100};
int *p_arr[LENGTH],i;
for(i=0;i<LENGTH;i++){
p_arr[i]=&arr[i];
/*Such As:
* &arr[i] Ԫصĵַ
* *p_arr[i] ɴӡԪ
* p_arr[i] == &arr[i]
*/
printf("Ԫ: %d ,ڵλã%p\n",*p_arr[i],&arr[i]);
}
}
/*һΧڵˮɻ*/
void fun6(){
int i,x,y,z;
for(i=100;i<1000;i++){
x = i % 10;//ȡλϵ
y = i / 10 % 10;//ȡʮλϵ
z = i / 100 % 10;//ȡλϵ
if(i == (x*x*x+y*y*y+z*z*z)){
printf("%d %d %d\n",z,y,x);
printf("һˮɻ: %d\n",i);
}
}
}
/*ð*/
void bubble_sort(int arr[], int len) {
int i, j, temp;
int count=0;
for (i = 0; i < len - 1; i++){
printf("=== һѭi=%d,===\n", i);
for (j = 0; j < len - 1 - i; j++){
count++;
printf("%d\n",count);
printf("ڶѭj=%d,С%d\n", j,(len - 1 - i));
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
/*һΧڵ*/
void fun5(){
int i,j;//ѭʼֵ
for(i = 2;i < 100;i++){//2-100Χȡ
for(j=2;j<i;j++){//2 - iΧڣi
if(i%j==0){//iֵôiͲ
break;
}
}
/*2һֱiûз֣ôi*/
if(i==j){
printf("һ%d\n",i);
}
}
}
/*쳲У*/
void fun4(){
int i,num;//i ѭʼֵnum
printf("");
scanf("%d",&num);//30
int month[num];//һ飬 month[30]û仯
month[0]=month[1]=1;//еһµ
for (i=0; i<num; i++) {
if (i==0 || i==1) {//ǵһ£1
printf("%d :1\n",i+1);
}
else {//ӵ¿ʼ
// ǰ = -1 + -2
month[i]=month[i-1]+month[i-2];
printf("%d : %d\n",i+1,month[i]);//ӡ
}
}
}
/*˳*/
void fun3(){
int x,y,z,t;
printf("֣磺30,20,62");
scanf("%d,%d,%d",&x,&y,&z);
if (x>y) { /*x,yֵ*/
t=x;x=y;y=t;
}
if(x>z) { /*x,zֵ*/
t=z;z=x;x=t;
}
if(y>z) { /*z,yֵ*/
t=y;y=z;z=t;
}
printf("С: %d %d %d\n",x,y,z);
}
/**/
void fun2()
{
double i;
double bonus1,bonus2,bonus4,bonus6,bonus10,bonus;
printf("ľǣ\n");
scanf("%lf",&i);
bonus1=100000*0.1;//10 10%
bonus2=bonus1+100000*0.075;// 10w ~ 20w 7.5%
bonus4=bonus2+200000*0.05; // 20w ~ 40w 5%
bonus6=bonus4+200000*0.03; // 40w ~ 60w 3%
bonus10=bonus6+400000*0.015;// 60w ~ 100W 1.5%
if(i<=100000) {
bonus=i*0.1;
printf("Ϊ%lf",bonus);
} else if(i<=200000) {
bonus=bonus1+(i-100000)*0.075;
printf("\n10,0.1;ɽΪ%lf",bonus1);
printf("\n10w ~ 20w֮,0.075;ɽΪ%lf",(i-100000)*0.075);
printf("\nܽΪ%lf",bonus);
} else if(i<=400000) {
bonus=bonus2+(i-200000)*0.05;
printf("\n10,0.1;ɽΪ%lf",bonus1);
printf("\n10w ~ 20w֮,0.075;ɽΪ%lf",bonus2);
printf("\n20w ~ 40w֮,0.05;ɽΪ%lf",(i-200000)*0.05);
printf("\nܽΪ%lf",bonus);
} else if(i<=600000) {
bonus=bonus4+(i-400000)*0.03;
printf("\n10,0.1;ɽΪ%lf",bonus1);
printf("\n10w ~ 20w֮,0.075;ɽΪ%lf",bonus2);
printf("\n20w ~ 40w֮,0.05;ɽΪ%lf",bonus4);
printf("\n40w ~ 60w֮,0.03;ɽΪ%lf",(i-400000)*0.03);
printf("\nܽΪ%lf",bonus);
} else if(i<=1000000) {
bonus=bonus6+(i-600000)*0.015;
printf("\n10,0.1;ɽΪ%lf",bonus1);
printf("\n10w ~ 20w֮,0.075;ɽΪ%lf",bonus2);
printf("\n20w ~ 40w֮,0.05;ɽΪ%lf",bonus4);
printf("\n40w ~ 60w֮,0.03;ɽΪ%lf",bonus6);
printf("\n60w ~ 100w֮,0.015;ɽΪ%lf",(i-600000)*0.015);
printf("\nܽΪ%lf",bonus);
} else{
bonus=bonus10+(i-1000000)*0.01;
printf("\n10,0.1;ɽΪ%lf",bonus1);
printf("\n10w ~ 20w֮,0.075;ɽΪ%lf",bonus2);
printf("\n20w ~ 40w֮,0.05;ɽΪ%lf",bonus4);
printf("\n40w ~ 60w֮,0.03;ɽΪ%lf",bonus6);
printf("\n60w ~ 100w֮,0.015;ɽΪ%lf",bonus10);
printf("\n100,0.01;ɽΪ%lf",(i-1000000)*0.01);
printf("\nܽΪ%lf",bonus);
}
printf("\n");
}
/*žų˷*/
void fun1(){
int i,j;//ѭʼֵ
for(i=1;i<10;i++){
for(j=1;j<=i;j++){
if(i * j >9){ //if ҪĿΪ˱ʽÿж
printf("%d x %d = %d ",i,j,i*j);//ӡʽ
}else{
printf("%d x %d = %d ",i,j,i*j);//ӡʽ
}
}
printf("\n\n");
}
}
|
C
|
/* @(#)w_jn.c 5.1 93/09/24 */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#include <sys/cdefs.h>
#if defined(LIBM_SCCS) && !defined(lint)
__RCSID("$NetBSD: w_jn.c,v 1.9 2002/05/26 22:02:01 wiz Exp $");
#endif
/*
* wrapper jn(int n, double x), yn(int n, double x)
* floating point Bessel's function of the 1st and 2nd kind
* of order n
*
* Special cases:
* y0(0)=y1(0)=yn(n,0) = -inf with division by zero signal;
* y0(-ve)=y1(-ve)=yn(n,-ve) are NaN with invalid signal.
* Note 2. About jn(n,x), yn(n,x)
* For n=0, j0(x) is called,
* for n=1, j1(x) is called,
* for n<x, forward recursion us used starting
* from values of j0(x) and j1(x).
* for n>x, a continued fraction approximation to
* j(n,x)/j(n-1,x) is evaluated and then backward
* recursion is used starting from a supposed value
* for j(n,x). The resulting value of j(0,x) is
* compared with the actual value to correct the
* supposed value of j(n,x).
*
* yn(n,x) is similar in all respects, except
* that forward recursion is used for all
* values of n>1.
*
*/
#include "math.h"
#include "math_private.h"
double
jn(int n, double x) /* wrapper jn */
{
#ifdef _IEEE_LIBM
return __ieee754_jn(n,x);
#else
double z;
z = __ieee754_jn(n,x);
if(_LIB_VERSION == _IEEE_ || isnan(x) ) return z;
if(fabs(x)>X_TLOSS) {
return __kernel_standard((double)n,x,38); /* jn(|x|>X_TLOSS,n) */
} else
return z;
#endif
}
double
yn(int n, double x) /* wrapper yn */
{
#ifdef _IEEE_LIBM
return __ieee754_yn(n,x);
#else
double z;
z = __ieee754_yn(n,x);
if(_LIB_VERSION == _IEEE_ || isnan(x) ) return z;
if(x <= 0.0){
if(x==0.0)
/* d= -one/(x-x); */
return __kernel_standard((double)n,x,12);
else
/* d = zero/(x-x); */
return __kernel_standard((double)n,x,13);
}
if(x>X_TLOSS) {
return __kernel_standard((double)n,x,39); /* yn(x>X_TLOSS,n) */
} else
return z;
#endif
}
|
C
|
#include "binary_trees.h"
/**
* binary_tree_height - Find the height of the longest branch in a binary tree
* @tree: The tree to find the height of
* Return: left_height if left branch is bigger, right_height if right branch
* is bigger, 0 if tree is NULL or tree is a leaf
**/
size_t binary_tree_height(const binary_tree_t *tree)
{
size_t left_height, right_height;
left_height = right_height = 0;
if (tree == NULL)
return (0);
if (tree->left == NULL && tree->right == NULL)
return (0);
left_height = binary_tree_height(tree->left) + 1;
right_height = binary_tree_height(tree->right) + 1;
if (left_height > right_height)
return (left_height);
return (right_height);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
float** converte_a (int m, int n, float* mat);
void ler_matriz(int m, int n, float* mat);
void imprime_matriz(int m, int n, float** mat);
void libera(int n, float **mat);
void main(void)
{
int linhas, colunas, i, j;
scanf("%d%d", &linhas, &colunas);
float* mat;
float** matA;
mat = malloc(linhas*colunas*sizeof(mat));
ler_matriz(linhas, colunas, mat);
matA = converte_a(linhas, colunas, mat);
imprime_matriz(linhas, colunas, matA);
free(mat);
libera(linhas, matA);
}
float** converte_a (int m, int n, float* mat)
{
int i, j;
float** cvMat;
cvMat = malloc(m*sizeof(float*));
for(i = 0; i < m; i++)
{
cvMat[i] = malloc(n*sizeof(float));
}
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
cvMat[i][j] = mat[i * n + j];
}
}
return cvMat;
}
void ler_matriz(int m, int n, float* mat)
{
int i, j;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
scanf("%f", &mat[i * n + j]);
}
}
}
void imprime_matriz(int m, int n, float** mat)
{
int i, j;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
printf("%.2f ", mat[i][j]);
}
printf("\n");
}
}
void libera(int n, float **mat)
{
int i;
for(i = 0; i < n; i++)
{
free(mat[i]);
}
free(mat);
}
|
C
|
#ifndef COOP_SHAPES_H
#define COOP_SHAPES_H
struct Shape;
struct IShape {
void (*destruct)(struct Shape *self);
const char *(*get_type)(const struct Shape *self);
int (*get_area)(const struct Shape *self);
};
struct Shape {
const struct IShape *vptr;
int a;
int b;
};
struct Rectangle {
struct Shape base;
};
struct Triangle {
struct Shape base;
};
void Shape_construct(struct Shape *self, int a, int b);
void Rectangle_construct(struct Rectangle *self, int a, int b);
void Triangle_construct(struct Triangle *self, int a, int b);
void Shape_destruct(struct Shape *self);
void Rectangle_destruct(struct Rectangle *self);
void Triangle_destruct(struct Triangle *self);
struct Shape *Shape_new(int a, int b);
struct Rectangle *Rectangle_new(int a, int b);
struct Triangle *Triangle_new(int a, int b);
void Shape_delete(struct Shape *self);
const char *Shape_get_type(const struct Shape *self);
const char *Rectangle_get_type(const struct Rectangle *self);
const char *Triangle_get_type(const struct Triangle *self);
int Rectangle_get_area(const struct Rectangle *self);
int Triangle_get_area(const struct Triangle *self);
#endif
|
C
|
/*
* Created 190309+0800 lynnl
*/
#include <stdio.h>
#include <string.h>
#include "lpm.h"
#include "utils.h"
#ifndef u8
#define u8 unsigned char
#endif
#define HEX_MAGIC 0xfadefacedeadbeef
#define LOG(fmt, ...) (void) fprintf(stderr, fmt "\n", ##__VA_ARGS__)
static void test1(void)
{
rax *rax = raxNew();
ssize_t sz;
void *data;
ASSERT_NONNULL(rax);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) 0xdeadbeef, 0, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "", 0, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "0", 1, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "ab", 2, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "xyz", 3, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "dead", 4, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "space", 5, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
raxFree(rax);
}
static void test2(void)
{
rax *rax = raxNew();
static uint64_t cookie = 0xfeedfacecafebeef;
ssize_t sz;
void *data;
int ok;
ASSERT_NONNULL(rax);
ASSERT(rax->head->iskey == 0);
ok = raxInsert(rax, (u8 *) "", 0, (void *) cookie, NULL);
ASSERT(ok == 1);
ASSERT(rax->head->iskey == 1);
ASSERT(rax->head->iscompr == 0);
ASSERT(rax->head->size == 0);
data = raxFind(rax, (u8 *) "", 0);
ASSERT(data == (void *) cookie);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "", 0, &sz);
ASSERT(data == (void *) cookie);
ASSERT(sz == 0); /* Full match */
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "", 1, &sz);
ASSERT(data == (void *) cookie);
ASSERT(sz == 0);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "0", 1, &sz);
ASSERT(data == (void *) cookie);
ASSERT(sz == 0);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "xy", 2, &sz);
ASSERT(data == (void *) cookie);
ASSERT(sz == 0);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "abc", 3, &sz);
ASSERT(data == (void *) cookie);
ASSERT(sz == 0);
raxFree(rax);
}
static void test3(void)
{
rax *rax = raxNew();
static char *uuid = "612A3D21-F94E-4EEE-9012-A877B96729EB";
ssize_t sz;
void *data;
int ok;
ASSERT_NONNULL(rax);
ok = raxInsert(rax, (u8 *) "foo", 3, (void *) uuid, NULL);
ASSERT(ok == 1);
ok = raxInsert(rax, (u8 *) "foobar", 6, (void *) uuid, NULL);
ASSERT(ok == 1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "", 0, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "", 1, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "f", 1, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "fo", 2, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "foo", 2, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "foo", 3, &sz);
ASSERT(data == uuid);
ASSERT(sz == 3); /* Full match */
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "for", 3, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "fool", 4, &sz);
ASSERT(data == uuid);
ASSERT(sz == 3); /* Submatch */
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "foolish", 7, &sz);
ASSERT(data == uuid);
ASSERT(sz == 3); /* Submatch */
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "fooba", 5, &sz);
ASSERT(data == uuid);
ASSERT(sz == 3);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "foobar", 6, &sz);
ASSERT(data == uuid);
ASSERT(sz == 6); /* Full match */
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "foobar!", 7, &sz);
ASSERT(data == uuid);
ASSERT(sz == 6); /* Submatch */
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "foobar!phenomenon", 17, &sz);
ASSERT(data == uuid);
ASSERT(sz == 6); /* Submatch */
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "#foobar", 8, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
raxFree(rax);
}
static void test4(void)
{
rax *rax = raxNew();
ASSERT_NONNULL(rax);
static char *uuid = "6d9ab4ff-e733-4db7-9f0b-750e0338d239";
ssize_t sz;
void *data;
int ok;
ok = raxInsert(rax, (u8 *) "", 0, (void *) uuid, NULL);
ASSERT(ok == 1);
ok = raxInsert(rax, (u8 *) "a", 1, (void *) uuid, NULL);
ASSERT(ok == 1);
ok = raxInsert(rax, (u8 *) "ab", 2, (void *) uuid, NULL);
ASSERT(ok == 1);
ok = raxInsert(rax, (u8 *) "abc", 3, (void *) uuid, NULL);
ASSERT(ok == 1);
ok = raxInsert(rax, (u8 *) "abcd", 4, (void *) uuid, NULL);
ASSERT(ok == 1);
ok = raxInsert(rax, (u8 *) "abcde", 5, (void *) uuid, NULL);
ASSERT(ok == 1);
ok = raxInsert(rax, (u8 *) "abcdef", 6, (void *) uuid, NULL);
ASSERT(ok == 1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "", 0, &sz);
ASSERT(data == uuid);
ASSERT(sz == 0);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "", 1, &sz);
ASSERT(data == uuid);
ASSERT(sz == 0);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "x", 1, &sz);
ASSERT(data == uuid);
ASSERT(sz == 0);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "\0", 2, &sz);
ASSERT(data == uuid);
ASSERT(sz == 0);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "a", 1, &sz);
ASSERT(data == uuid);
ASSERT(sz == 1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "a", 2, &sz);
ASSERT(data == uuid);
ASSERT(sz == 1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "ab", 2, &sz);
ASSERT(data == uuid);
ASSERT(sz == 2);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "abc", 3, &sz);
ASSERT(data == uuid);
ASSERT(sz == 3);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "abcd", 4, &sz);
ASSERT(data == uuid);
ASSERT(sz == 4);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "abcde", 5, &sz);
ASSERT(data == uuid);
ASSERT(sz == 5);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "abcdef", 6, &sz);
ASSERT(data == uuid);
ASSERT(sz == 6);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "abcdef", 7, &sz);
ASSERT(data == uuid);
ASSERT(sz == 6);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "abcdef!", 7, &sz);
ASSERT(data == uuid);
ASSERT(sz == 6);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "abcdef!", 8, &sz);
ASSERT(data == uuid);
ASSERT(sz == 6);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "\0abcdef", 7, &sz);
ASSERT(data == uuid);
ASSERT(sz == 0);
raxFree(rax);
}
static void test5(void)
{
rax *rax = raxNew();
ASSERT_NONNULL(rax);
static char *uuid = "44eadd55-d769-4a3e-b7fe-f3fc58c72f31";
ssize_t sz;
void *data;
int ok;
ok = raxInsert(rax, (u8 *) "A", 1, (void *) uuid, NULL);
ASSERT(ok == 1);
ok = raxInsert(rax, (u8 *) "ABC", 3, (void *) uuid, NULL);
ASSERT(ok == 1);
ok = raxInsert(rax, (u8 *) "ABCDEF", 6, (void *) uuid, NULL);
ASSERT(ok == 1);
ok = raxInsert(rax, (u8 *) "ABCDEFG", 7, (void *) uuid, NULL);
ASSERT(ok == 1);
ok = raxInsert(rax, (u8 *) "ABCDEFGHIJ", 10, (void *) uuid, NULL);
ASSERT(ok == 1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "", 0, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "a", 1, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "A", 1, &sz);
ASSERT(data == uuid);
ASSERT(sz == 1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "AB", 2, &sz);
ASSERT(data == uuid);
ASSERT(sz == 1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "ABC", 3, &sz);
ASSERT(data == uuid);
ASSERT(sz == 3);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "ABD", 3, &sz);
ASSERT(data == uuid);
ASSERT(sz == 1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "ABCABC", 6, &sz);
ASSERT(data == uuid);
ASSERT(sz == 3);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "ABCD", 4, &sz);
ASSERT(data == uuid);
ASSERT(sz == 3);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "ABCDE", 5, &sz);
ASSERT(data == uuid);
ASSERT(sz == 3);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "ABCDEF", 6, &sz);
ASSERT(data == uuid);
ASSERT(sz == 6);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "ABCDEFG", 7, &sz);
ASSERT(data == uuid);
ASSERT(sz == 7);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "ABCDEFg", 7, &sz);
ASSERT(data == uuid);
ASSERT(sz == 6);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "ABCDEFG!", 7, &sz);
ASSERT(data == uuid);
ASSERT(sz == 7);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "ABCDEFGHI", 9, &sz);
ASSERT(data == uuid);
ASSERT(sz == 7);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "ABCDEFGHIJ", 10, &sz);
ASSERT(data == uuid);
ASSERT(sz == 10);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "ABCDEFGHIJ0123456789", 20, &sz);
ASSERT(data == uuid);
ASSERT(sz == 10);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "\0ABC", 3, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
raxFree(rax);
}
static void test6(void)
{
rax *rax = raxNew();
ASSERT_NONNULL(rax);
static char *uuid = "bbda30fa-a3b0-4fe8-b23c-a0d6c8f56ba9";
ssize_t sz;
void *data;
int ok;
ok = raxInsert(rax, (u8 *) "!", 0, (void *) uuid, NULL);
ASSERT(ok == 1);
ok = raxInsert(rax, (u8 *) "", 1, (void *) uuid, NULL);
ASSERT(ok == 1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "", 0, &sz);
ASSERT(data == uuid);
ASSERT(sz == 0);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) 0x90abcdef, 0, &sz);
ASSERT(data == uuid);
ASSERT(sz == 0);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "?", 1, &sz);
ASSERT(data == uuid);
ASSERT(sz == 0);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "!", 1, &sz);
ASSERT(data == uuid);
ASSERT(sz == 0);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "\0", 1, &sz);
ASSERT(data == uuid);
ASSERT(sz == 1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "", 1, &sz);
ASSERT(data == uuid);
ASSERT(sz == 1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "abcd", 4, &sz);
ASSERT(data == uuid);
ASSERT(sz == 0);
ok = raxRemove(rax, (u8 *) "@", 0, NULL);
ASSERT(ok = 1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "abcd", 4, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
raxFree(rax);
}
static void test7(void)
{
rax *rax = raxNew();
ASSERT_NONNULL(rax);
static char *uuid = "129fad82-16f2-4ef1-a143-d5027a81d252";
void *data;
int ok;
ok = raxInsert(rax, (u8 *) "a", 0, (void *) uuid, NULL);
ASSERT(ok == 1);
data = raxFind(rax, (u8 *) "", 0);
ASSERT(data == uuid);
ok = raxRemove(rax, (u8 *) "A", 0, NULL);
ASSERT(ok == 1);
ok = raxInsert(rax, (u8 *) "b", 0, (void *) uuid, NULL);
ASSERT(ok == 1);
data = raxFind(rax, (u8 *) "B", 0);
ASSERT(data == uuid);
ok = raxRemove(rax, (u8 *) "", 0, NULL);
ASSERT(ok == 1);
ok = raxInsert(rax, (u8 *) "", 0, (void *) uuid, NULL);
ASSERT(ok == 1);
data = raxFind(rax, (u8 *) "C", 0);
ASSERT(data == uuid);
ok = raxRemove(rax, (u8 *) "c", 0, NULL);
ASSERT(ok == 1);
raxFree(rax);
}
struct kv {
void *data;
u8 *key;
size_t len;
};
struct kv test8_data[] = {
{(void *) 0, (u8 *) "/usr/local/bin/brew", 19},
{(void *) 1, (u8 *) "/usr/local/bin/git", 18},
{(void *) 2, (u8 *) "/usr/local/bin/git-cvsserver", 28},
{(void *) 3, (u8 *) "/usr/local/bin/git-lfs", 22},
{(void *) 4, (u8 *) "/usr/local/bin/git-receive-pack", 31},
{(void *) 5, (u8 *) "/usr/local/bin/git-shell", 24},
{(void *) 6, (u8 *) "/usr/local/bin/git-upload-archive", 33},
{(void *) 7, (u8 *) "/usr/local/bin/git-upload-pack", 30},
{(void *) 8, (u8 *) "/usr/local/bin/gitk", 19},
{(void *) 9, (u8 *) "/usr/local/bin/go", 17},
{(void *) 10, (u8 *) "/usr/local/bin/godoc", 20},
{(void *) 11, (u8 *) "/usr/local/bin/gofmt", 20},
{(void *) 12, (u8 *) "/usr/local/bin/pcre2-config", 27},
{(void *) 13, (u8 *) "/usr/local/bin/pcre2grep", 24},
{(void *) 14, (u8 *) "/usr/local/bin/pcre2test", 24},
{(void *) 15, (u8 *) "/usr/local/bin/pkg-config", 25},
{(void *) 16, (u8 *) "/usr/local/Cellar/gettext", 25},
{(void *) 17, (u8 *) "/usr/local/Cellar/git", 21},
{(void *) 18, (u8 *) "/usr/local/Cellar/git-lfs", 25},
{(void *) 19, (u8 *) "/usr/local/Cellar/go", 20},
{(void *) 20, (u8 *) "/usr/local/Cellar/libyaml", 25},
{(void *) 21, (u8 *) "/usr/local/Cellar/openssl", 25},
{(void *) 22, (u8 *) "/usr/local/Cellar/pcre2", 23},
{(void *) 23, (u8 *) "/usr/local/Cellar/pkg-config", 28},
{(void *) 24, (u8 *) "/usr/local/Cellar/readline", 26},
{(void *) 25, (u8 *) "/usr/local/Cellar/ruby", 22},
{(void *) 26, (u8 *) "/usr/local/etc/bash_completion.d", 32},
{(void *) 27, (u8 *) "/usr/local/etc/gitconfig", 24},
{(void *) 28, (u8 *) "/usr/local/etc/openssl", 22},
{(void *) 29, (u8 *) "/usr/local/Homebrew/.editorconfig", 33},
{(void *) 30, (u8 *) "/usr/local/Homebrew/.git", 24},
{(void *) 31, (u8 *) "/usr/local/Homebrew/.github", 27},
{(void *) 32, (u8 *) "/usr/local/Homebrew/.gitignore", 30},
{(void *) 33, (u8 *) "/usr/local/Homebrew/.yardopts", 29},
{(void *) 34, (u8 *) "/usr/local/Homebrew/azure-pipelines.yml", 39},
{(void *) 35, (u8 *) "/usr/local/Homebrew/bin", 23},
{(void *) 36, (u8 *) "/usr/local/Homebrew/CHANGELOG.md", 32},
{(void *) 37, (u8 *) "/usr/local/Homebrew/CODE_OF_CONDUCT.md", 38},
{(void *) 38, (u8 *) "/usr/local/Homebrew/completions", 31},
{(void *) 39, (u8 *) "/usr/local/Homebrew/CONTRIBUTING.md", 35},
{(void *) 40, (u8 *) "/usr/local/Homebrew/Dockerfile", 30},
{(void *) 41, (u8 *) "/usr/local/Homebrew/Dockerfile.test.yml", 39},
{(void *) 42, (u8 *) "/usr/local/Homebrew/docs", 24},
{(void *) 43, (u8 *) "/usr/local/Homebrew/Library", 27},
{(void *) 44, (u8 *) "/usr/local/Homebrew/LICENSE.txt", 31},
{(void *) 45, (u8 *) "/usr/local/Homebrew/manpages", 28},
{(void *) 46, (u8 *) "/usr/local/Homebrew/README.md", 29},
{(void *) 47, (u8 *) "/usr/local/include/pcre2.h", 26},
{(void *) 48, (u8 *) "/usr/local/include/pcre2posix.h", 31},
{(void *) 49, (u8 *) "/usr/local/include/yaml.h", 25},
{(void *) 50, (u8 *) "/usr/local/lib/libpcre2-16.0.dylib", 34},
{(void *) 51, (u8 *) "/usr/local/lib/libpcre2-16.a", 28},
{(void *) 52, (u8 *) "/usr/local/lib/libpcre2-16.dylib", 32},
{(void *) 53, (u8 *) "/usr/local/lib/libpcre2-32.0.dylib", 34},
{(void *) 54, (u8 *) "/usr/local/lib/libpcre2-32.a", 28},
{(void *) 55, (u8 *) "/usr/local/lib/libpcre2-32.dylib", 32},
{(void *) 56, (u8 *) "/usr/local/lib/libpcre2-8.0.dylib", 33},
{(void *) 57, (u8 *) "/usr/local/lib/libpcre2-8.a", 27},
{(void *) 58, (u8 *) "/usr/local/lib/libpcre2-8.dylib", 31},
{(void *) 59, (u8 *) "/usr/local/lib/libpcre2-posix.2.dylib", 37},
{(void *) 60, (u8 *) "/usr/local/lib/libpcre2-posix.a", 31},
{(void *) 61, (u8 *) "/usr/local/lib/libpcre2-posix.dylib", 35},
{(void *) 62, (u8 *) "/usr/local/lib/libyaml-0.2.dylib", 32},
{(void *) 63, (u8 *) "/usr/local/lib/libyaml.a", 24},
{(void *) 64, (u8 *) "/usr/local/lib/libyaml.dylib", 28},
{(void *) 65, (u8 *) "/usr/local/lib/pkgconfig", 24},
{(void *) 66, (u8 *) "/usr/local/lib/ruby", 19},
{(void *) 67, (u8 *) "/usr/local/opt/gettext", 22},
{(void *) 68, (u8 *) "/usr/local/opt/git", 18},
{(void *) 69, (u8 *) "/usr/local/opt/git-lfs", 22},
{(void *) 70, (u8 *) "/usr/local/opt/go", 17},
{(void *) 71, (u8 *) "/usr/local/opt/go@1.11", 22},
{(void *) 72, (u8 *) "/usr/local/opt/golang", 21},
{(void *) 73, (u8 *) "/usr/local/opt/google-go", 24},
{(void *) 74, (u8 *) "/usr/local/opt/libyaml", 22},
{(void *) 75, (u8 *) "/usr/local/opt/openssl", 22},
{(void *) 76, (u8 *) "/usr/local/opt/openssl@1.0", 26},
{(void *) 77, (u8 *) "/usr/local/opt/pcre2", 20},
{(void *) 78, (u8 *) "/usr/local/opt/pkg-config", 25},
{(void *) 79, (u8 *) "/usr/local/opt/pkgconfig", 24},
{(void *) 80, (u8 *) "/usr/local/opt/readline", 23},
{(void *) 81, (u8 *) "/usr/local/opt/ruby", 19},
{(void *) 82, (u8 *) "/usr/local/opt/ruby@2.6", 23},
{(void *) 83, (u8 *) "/usr/local/share/aclocal", 24},
{(void *) 84, (u8 *) "/usr/local/share/doc", 20},
{(void *) 85, (u8 *) "/usr/local/share/emacs", 22},
{(void *) 86, (u8 *) "/usr/local/share/git-core", 25},
{(void *) 87, (u8 *) "/usr/local/share/git-gui", 24},
{(void *) 88, (u8 *) "/usr/local/share/gitk", 21},
{(void *) 89, (u8 *) "/usr/local/share/gitweb", 23},
{(void *) 90, (u8 *) "/usr/local/share/locale", 23},
{(void *) 91, (u8 *) "/usr/local/share/man", 20},
{(void *) 92, (u8 *) "/usr/local/share/perl5", 22},
{(void *) 93, (u8 *) "/usr/local/share/zsh", 20},
{(void *) 94, (u8 *) "/usr/local/var/homebrew", 23},
};
static void test8(void)
{
rax *rax = raxNew();
ASSERT_NONNULL(rax);
ssize_t sz;
void *data;
int ok;
size_t i;
struct kv *kvp;
char *usr_local = "/usr/local/";
for (i = 0; i < ARRAY_SIZE(test8_data); i++) {
kvp = &test8_data[i];
ok = raxInsert(rax, kvp->key, kvp->len, kvp->data, NULL);
ASSERT(ok == 1);
}
for (i = 0; i <= strlen(usr_local); i++) {
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) usr_local, i, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
}
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/bin/g", 16, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/bin/go", 17, &sz);
ASSERT(data == (void *) 9);
ASSERT(sz == 17);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/bin/godo", 19, &sz);
ASSERT(data == (void *) 9);
ASSERT(sz == 17);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/bin/godoc", 20, &sz);
ASSERT(data == (void *) 10);
ASSERT(sz == 20);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/bin/godoc!!", 22, &sz);
ASSERT(data == (void *) 10);
ASSERT(sz == 20);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/bin/gofm", 19, &sz);
ASSERT(data == (void *) 9);
ASSERT(sz == 17);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/bin/gofmt", 20, &sz);
ASSERT(data == (void *) 11);
ASSERT(sz == 20);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/share/git", 20, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/share/gitk", 21, &sz);
ASSERT(data == (void *) 88);
ASSERT(sz == 21);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/share/gitk", 22, &sz);
ASSERT(data == (void *) 88);
ASSERT(sz == 21);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/opt/ruby", 18, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/opt/ruby", 19, &sz);
ASSERT(data == (void *) 81);
ASSERT(sz == 19);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/opt/ruby@2.6", 22, &sz);
ASSERT(data == (void *) 81);
ASSERT(sz == 19);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/opt/ruby@2.6", 23, &sz);
ASSERT(data == (void *) 82);
ASSERT(sz == 23);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/opt/ruby@2.6foobar", 29, &sz);
ASSERT(data == (void *) 82);
ASSERT(sz == 23);
sz = HEX_MAGIC;
data = raxLongestPrefixMatch(rax, (u8 *) "/usr/local/lib/libpcre2-", 24, &sz);
ASSERT(data == raxNotFound);
ASSERT(sz == -1);
raxFree(rax);
}
static void test(void)
{
rax *rax = raxNew();
ASSERT_NONNULL(rax);
raxFree(rax);
}
int main(void)
{
test();
test1();
test2();
test3();
test4();
test5();
test6();
test7();
test8();
LOG("Built: %s %s\nPass!", __DATE__, __TIME__);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: asoursou <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/18 04:23:59 by asoursou #+# #+# */
/* Updated: 2019/07/22 01:41:59 by asoursou ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ft_list.h"
void ft_list_print(t_list *l)
{
if (!l)
{
printf("NULL\n");
return ;
}
printf("%s -> ", (char *)l->data);
ft_list_print(l->next);
}
t_list *ft_list_create(void)
{
t_list *l;
l = NULL;
ft_list_push_back(&l, "a");
ft_list_push_back(&l, "b");
ft_list_push_back(&l, "c");
return (l);
}
int main(int argc, char **argv)
{
t_list *l;
t_list *e;
l = ft_list_push_strs(argc - 1, argv + 1);
printf("content: ");
ft_list_print(l);
printf("size: %d\n", ft_list_size(l));
e = ft_list_at(l, 1);
printf("2nd element: ");
if (e)
printf("%s\n", e->data);
else
printf("NULL\n");
ft_list_reverse_fun(l);
printf("reverse content: ");
ft_list_print(l);
ft_list_sort(&l, &strcmp);
printf("sorted content: ");
ft_list_print(l);
ft_list_remove_if(&l, "foo", &strcmp, NULL);
printf("removing foo: ");
ft_list_print(l);
ft_sorted_list_insert(&l, "foo", &strcmp);
printf("inserting foo: ");
ft_list_print(l);
ft_sorted_list_merge(&l, ft_list_create(), &strcmp);
printf("merging a b c: ");
ft_list_print(l);
ft_list_clear(l, NULL);
return (0);
}
|
C
|
//Function declaration
double **createMat(int m,int n);
void readMat(int m,int n,double **p);
void print(int m,int n,double **p);
//End function declaration
//Defining the function for matrix creation
double **createMat(int m,int n)
{
int i;
double **a;
//Allocate memory to the pointer
a = (double **)malloc(m * sizeof( *a));
for (i=0; i<m; i++)
a[i] = (double *)malloc(n * sizeof( *a[i]));
return a;
}
//End function for matrix creation
//Defining the function for reading matrix
void readMat(int m,int n,double **p)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%lf",&p[i][j]);
}
}
}
//End function for reading matrix
//Defining the function for printing
void print(int m,int n,double **p)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%lf ",p[i][j]);
printf("\n");
}
}
//Defining linspace
//double linspace(double a, double b, int n)
//{
//double d;
//
//d = (b-1)/(n-1);
//
//
//}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_pri_size_width.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: etrobert <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/12/08 18:02:23 by etrobert #+# #+# */
/* Updated: 2016/12/14 11:10:17 by etrobert ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
unsigned int ft_pri_size_width(t_pri_opts *opts)
{
if (opts->width_char == '0' && !opts->left_justify &&
opts->width > opts->little_size && ft_pri_is_number(opts))
{
opts->precision += opts->width - opts->little_size;
opts->little_size += opts->width - opts->little_size;
}
if (opts->spec == PRI_FMT)
return (opts->little_size);
return (ft_umax(opts->little_size, opts->width));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*15. Scrivere una funzione che restituisca true se la stringa passata come parametro palindroma, false
altrimenti.*/
#include <stdbool.h>
#include <string.h>
#define DIM 20
_Bool check_stringa_palindroma(char stringa[]);
int main()
{
char s1[DIM+1] = "albicocche";
char s2[DIM+2] = "kek";
printf("check_stringa_palindroma(%s) = %d\n", s1, check_stringa_palindroma(s1));
printf("check_stringa_palindroma(%s) = %d\n", s2, check_stringa_palindroma(s2));
return 0;
};
_Bool check_stringa_palindroma(char stringa[])
{
_Bool palindroma = true;
int i=0;
int len=strlen(stringa);
for (i=0; i<len/2 && palindroma==true; i++)
if (stringa[i] != stringa[len-i-1])
palindroma = false;
return palindroma;
}
|
C
|
/*!
* \file gc.c
*
* \author Celine Dion
* \date 2012-10-26
*
* Functions needed to perform garbage collection
*/
#include "gc.h"
#include "priv_imalloc.h"
#include <stdio.h>
//! Checks if the pointer is pointing within the adress space.
/*!
* Returns true if pointer ptr is within the addresspace on the heap that
* was allocated using iMalloc.
*/
Boolean in_address_space(void *ptr, Priv_mem mem) {
void *start = as_start(mem);
void *end = as_end(mem);
if (ptr < end && ptr > start){
return TRUE;
}
else{
return FALSE;
}
}
//! Traverses the heap and marks all objects with pointers as alive.
/*!
* Function to traverse the heap and mark all the chunk's whose
* corresponding object were found with pointers from the stack as alive.
* Also marks a chunk as alive if you can "backtrace" a number of pointers
* from an object back to the stack.
* Objects on the heap must be "connected" to the stack via
* one (or more) pointers to be considered alive.
*/
void traverse_heap(void *ptr, void *mem) {
void *heap_ptr = *(void **) ptr;
// Search for a chunk that contains this pointer.
Chunk chunk = search_memory(heap_ptr, alloclist(mem), FALSE);
// We found a chunk! Mark it and check it's pointers.
if (chunk) {
// Only traverse if this chunk hasn't been processed already.
if (memory_is_marked(chunk) == FALSE) {
/*
if (in_address_space(ptr, mem))
printf("HEAP: %p found at %p resulted in chunk with start at %p. Traversing pointers in chunk.\n", heap_ptr, ptr, chunk->start);
else
printf("STACK: %p found at %p resulted in chunk with start at %p. Traversing pointers in chunk.\n", heap_ptr, ptr, chunk->start);
*/
set_memory_mark(chunk, TRUE);
// Go through each possible pointer in the chunk and see if it points
// to another chunk.
for (void **cursor = chunk->start; (void *)cursor < (void *)(chunk->start + chunk->size); cursor++) {
if (in_address_space(*cursor, mem)) {
// The pointer points to the stack!
traverse_heap(cursor, mem);
}
}
}
else { /*
if (in_address_space(ptr, mem))
printf("HEAP: %p found at %p resulted in chunk with start at %p, but this chunk has already been traversed!\n", heap_ptr, ptr, chunk->start);
else
printf("STACK: %p found at %p resulted in chunk with start at %p, but this chunk has already been traversed!\n", heap_ptr, ptr, chunk->start);
*/
}
}
}
void print_stack_pointers_to_chunks(void *ptr, void *mem) {
void *heap_ptr = *(void **) ptr;
Chunk chunk = search_memory(heap_ptr, alloclist(mem), FALSE);
if (chunk) {
printf("STACKDUMP: %p found at %p resulted in chunk with start at %p.\n", heap_ptr, ptr, chunk->start);
}
}
//! Frees the chunks that are no longer being used.
/*!
* The sweep-stage of the mark & sweep algorithm.
* Frees the chunks that is no longer being used, the ones with
* the mark bit set to false.
*/
int sweep(Priv_mem mem){
int i = 0;
Chunk current_chunk = alloclist(mem);
Chunk temp = NULL;
//Initiate iterator
while (current_chunk){
if (memory_is_marked(current_chunk) == FALSE){
i++;
temp = current_chunk;
current_chunk = next_chunk(current_chunk);
priv_free(priv_to_style(mem), memory_start(temp));
} else {
current_chunk = next_chunk(current_chunk);
}
}
return i;
}
//! Marks all the objects on the heap as dead.
/*!
* The first stage of the mark & sweep algorithm.
* Traverses the alloclist and sets all mark_bits to false.
*/
void mark_unused(Priv_mem mem){
Chunk current_chunk = alloclist(mem);
while (current_chunk){
set_memory_mark(current_chunk ,FALSE);
current_chunk = next_chunk(current_chunk);
}
}
unsigned int collect_help(Priv_mem mem) {
mark_unused(mem);
//printf("Traversing stack and heap\n");
traverseStack(mem->as, &traverse_heap, mem);
//printf("\n");
unsigned int i = sweep(mem);
return i;
}
//! Performs a garbage collection according to the mark and sweep algorithm.
/*!
* Performs a garbage collection according to the mark and sweep algorithm.
* Returns a positive integer if the sweep stage was successful and memory
* was freed.
* The integer returned is corresponding to the number of memory blocks freed.
*/
unsigned int collect(Memory memory){
return collect_help(style_to_priv(memory));
}
|
C
|
#include "holberton.h"
/**
* print_chessboard - This function will print out a chessboard
* @a: is the array we will be using
*
*/
void print_chessboard(char (*a)[8])
{
int j;
int d;
for (j = 0; j < 8; j++)
{
for (d = 0; d < 8; d++)
_putchar(a[j][d]);
}
}
|
C
|
#include "holberton.h"
#include <stdio.h>
/**
* main - program which prints number of arguments
*
* @argc: int, number of arguments
* @argv: array of pointer to these arguments
*
* Return: int, 0 (Success)
*/
int main(int argc, char *argv[])
{
printf("%d\n", argc - 1);
(void) argv;
return (0);
}
|
C
|
#include<stdio.h>
int first = 0;
int second = 1;
int fibonacci_rec(int n)
{
if(n == 0)
return first;
if(n == 1)
return second;
else
return fibonacci_rec(n-1) + fibonacci_rec(n-2);
}
int main(int argc, char const **argv)
{
int i;
for(i = 0; i < 20; ++i)
printf("%d->%d\n" ,i+1, fibonacci_rec(i));
return 0;
}
|
C
|
#include<stdio.h>
int func1()
{
int a,b;
b = 3;
a = b;
b = b * 2;
printf("a = %d\n",a);
printf("b = %d\n",b);
return 0;
}
int func2()
{
int r;
float c,s;
r = 5;
c = 2 * 3.14 * r;
s = 3.14 * r * r;
printf("半径为%d的圆,周长是%.2f,面积是%.2f\n",r,c,s);
return 0;
}
int func3()
{
printf("打印五个字符: %c %c %c %c %c\n",70,105,115,104,67);
printf("前边用 填充: %10d\n",2015);
printf("前边用0填充: %010d\n", 2015);
printf("右对齐,保留2位: %10.2f\n",3.1415);
printf("左对齐,保留3位: %-10.3f\n",3.1415);
printf("右对齐,指数形式: %10e\n",520000.0);
printf("左对齐,指数形式: %-10E\n", 520000.0);
return 0;
}
int main()
{
// func1();
// func2();
func3();
}
|
C
|
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char buf[100];
size_t size = read(0, buf, 100);
if (size > 0 && buf[0] == 'h'){
if (size > 1 && buf[1] == 'a'){
if (size > 2 && buf[2] == 'c'){
if (size > 3 && buf[3] == 'k'){
// __builtin_trap(); // uncomment to force a crash at this program point
printf(buf); // vulnerable to format string attacks!
}
}
}
}
return 0;
}
|
C
|
/*
LeetCode 796. Rotate String
Glennshih@20180316 coding in C language
*/
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool rotateString(char* A, char* B) {
char tmp;
int len_char_a, char_a_position, rotate_left_times, judge=0;
len_char_a = strlen(A);
//maximun rotate left by (len_char_a -1) times
for(rotate_left_times=1; rotate_left_times<len_char_a; rotate_left_times++){
//printf("DEBUG: rotate_left_times=%d\n",rotate_left_times);
//rotate char A by shift left 1
tmp = A[0];
for(char_a_position=0; char_a_position<len_char_a; char_a_position++){
A[char_a_position] = A[char_a_position+1];
}
A[len_char_a - 1] = tmp;
printf("DEBUG: string A = %s\n",A);
//if string A == B return Ture.
//WRONG (*A == *B), only compare first digit
if(strcmp(A,B)==0){
judge = 1;
printf("DEBUG: judge_True = %d\n", judge);
break;
}
else{
judge = judge + 0;
//printf("DEBUG: judge_False = %d\n", judge);
}
}
//check A string == B stringrotate_left_times
if(judge == 1){
printf("DEBUG: true\n");
return true;
}
else{
//printf("DEBUG: false\n");
return false;
}
}
void main(){
char A[] = "gwhqmrxpuppvuiuzicencvgtuzuxkhdqcwdbiciliiapdbzocr";
char B[] = "dsinzpskimfgcppsvjbhasfvqszngdhqtakrlxdmeeqakfxucy";
//char A[] = "abcde";
//char B[] = "cdeab";
//char A[] = "clrwmpkwru";
//char B[] = "wmpkwruclr";
//printf(A);
rotateString(A,B);
}
|
C
|
#include <stdio.h>
double fun (int i) {
volatile double d[1] = {3.14};
volatile long int a[2];
a[i] = 1073741824;
return d[0];
}
int main(int argc, char const *argv[]) {
printf("%f\n%f\n%f\n", fun(0), fun(1), fun(2));
printf("%f\n", fun(3));
printf("%f\n", fun(4));
return 0;
}
// 3.140000
// 3.140000
// 3.139999
// 0.000000
// 3.140000 存储保护错
// -----------------
// EBP | EBP 的旧值 |
// | d7 d6 d5 d4 |
// | d3 d2 d1 d0 |
// | a[1] |
// ESP | a[0] |
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "../brk.h"
#include <unistd.h>
#include <time.h>
#include <malloc.h>
#define MIN_ALLOC (1)
#define MAX_ALLOC (16368)
int get_random_size() {
return MIN_ALLOC + (rand() % (MAX_ALLOC - MIN_ALLOC));
}
int main(int argc, char *argv[]) {
long num;
long i;
int size;
int sum = 0;
long overhead;
struct mallinfo info;
srand((unsigned int)time(NULL));
num = atol(argv[1]);
for(i = 0; i < num; i++) {
size = get_random_size();
malloc(size);
sum += size;
}
fprintf(stderr, "Sum: %d\n", sum);
malloc_stats();
info = mallinfo();
fprintf(stderr, "info.arena: %d\n", info.arena);
overhead = info.arena - sum;
fprintf(stderr, "%lu (%lu%%)\n", overhead, 100*overhead / info.arena);
return 0;
}
|
C
|
// MyLib.c
#include <stdio.h>
void foobar (int i)
{
printf ("Printing from MyLib.so %d\n", i);
printf ("This is revised.\n");
}
|
C
|
float Median_filter(int data,int measureNum,int *Filterdata)
{
unsigned int i = 0;
unsigned int j = 0;
int temp;
unsigned int MAX_error_targe = 0;
int MAX_error1;
for(i=0;i<measureNum-1;i++)
{
Filterdata[i]=Filterdata[i+1];
}
Filterdata[measureNum-1] = data;
for(i = 0 ; i < measureNum-1 ; i++)
{
for(j = 0 ; j < measureNum-1-i; j++)
{
if(Filterdata[j] > Filterdata[j+1] )
{
temp = Filterdata[j];
Filterdata[j] = Filterdata[j+1];
Filterdata[j+1] = temp;
}
}
}
MAX_error1 = Filterdata[1] - Filterdata[0];
for(i = 1 ; i < measureNum-1 ; i++)
{
if(MAX_error1 < Filterdata[i+1] - Filterdata[i] )
{
MAX_error1 = Filterdata[i+1] - Filterdata[i];
MAX_error_targe = i;
}
}
float Average_data=0;
if(MAX_error_targe+1 > (measureNum+1)/2)
{
for(i = 0 ; i <= MAX_error_targe ; i++)
{
Average_data += Filterdata[i];
}
Average_data /= (MAX_error_targe+1);
}
else
{
for(i = MAX_error_targe + 1 ; i < measureNum ; i++)
{
Average_data += Filterdata[i];
}
Average_data /= (measureNum - MAX_error_targe -1);
}
return Average_data;
}
|
C
|
/*
* Author: Xiru Zhu
* Date: July 4 2016
* Updated: Jan 6 2017
*
* Notes:
* To initialize this system,
* create a separate pthread and then run jdata_event_loop
* This should initialize jdata system.
*/
#include "jdata_updated.h"
char app_id[256];
//redis server connection parameters
char *redis_serv_IP;
int redis_serv_port;
//jamstate variable to be kept in reference
jamstate_t *j_s;
//For Async calls to logger.
redisAsyncContext *jdata_async_context;
//For sync calls to logger.
redisContext *jdata_sync_context;
//Event Loop. This responds to messages
struct event_base *base;
//Linked List System for current jdata elements.
//This is because we need to look up which jdata is updated
jdata_list_node *jdata_list_head = NULL;
jdata_list_node *jdata_list_tail = NULL;
/*
Function to initialize values and attach them to the event loop
Inputs
jamstate
application unique id
redis server ip
redis server port
*/
void jdata_attach(jamstate_t *js, char *application_id, char *serv_ip, int serv_port){
sprintf(app_id, "%s", application_id);
j_s = js;
//These are the initial redis server numbers.
redis_serv_IP = strdup(serv_ip);
redis_serv_port = serv_port; //Default Port Number
//Initialize event base
base = event_base_new();
//Initialize an async context
jdata_async_context = redisAsyncConnect(redis_serv_IP, redis_serv_port);
if (jdata_async_context->err) {
printf("Error: %s\n", jdata_async_context->errstr);
}
//Attach async context to base
redisLibeventAttach(jdata_async_context, base);
redisAsyncSetConnectCallback(jdata_async_context, jdata_default_connection);
redisAsyncSetDisconnectCallback(jdata_async_context, jdata_default_disconnection);
//Initialize sync context
struct timeval timeout = { 1, 500000 }; // Sync timeout time
//Initialize sync context
jdata_sync_context = redisConnectWithTimeout(redis_serv_IP, redis_serv_port, timeout);
if (jdata_sync_context == NULL || jdata_sync_context->err) {
if (jdata_sync_context) {
printf("Connection error: %s\n", jdata_sync_context->errstr);
redisFree(jdata_sync_context);
} else {
printf("Connection error: can't allocate redis context\n");
}
}
}
/*
Initializes jdata system
This has to be run in a separate thread otherwise will block the current thread.
This thread created as to be pthread, otherwise will block all other process.
Input:
jamstate
*/
void *jdata_init(void *args, char *application_id, char *serv_ip, int serv_port){
jamstate_t *js = (jamstate_t *)args;
jdata_attach(js, application_id, serv_ip, serv_port);
#ifdef DEBUG_LVL1
printf("JData initialized...\n");
#endif
event_base_dispatch(base);
return NULL;
}
/*
* This is the default connection callback.
* This is utilized when the connection callback for jdata is not defined
* You do not need to use this anywhere, this is only utilized in the library a default callback.
*/
void jdata_default_connection(const redisAsyncContext *c, int status) {
if (status != REDIS_OK) {
printf("Connection Error: %s\n", c->errstr);
return;
}
#ifdef DEBUG_LVL1
printf("Connected...\n");
#endif
}
/*
* This is the default disconnection callback.
* This is utilized when the disconnection callback for jdata is not defined
* You do not need to use this anywhere, this is only utilized in the library a default callback.
*/
void jdata_default_disconnection(const redisAsyncContext *c, int status) {
if (status != REDIS_OK) {
printf("Disconnection Error: %s\n", c->errstr);
return;
}
#ifdef DEBUG_LVL1
printf("Disconnected...\n");
#endif
}
/*
* This is the default jdata received callback.
* This is utilized when a jdata is called but no callback was assigned. It will simply print the value.
* You do not need to use this anywhere, this is only utilized in the library as a default callback.
*/
void jdata_default_msg_received(redisAsyncContext *c, void *reply, void *privdata) {
redisReply *r = reply;
if (reply == NULL) return;
if (r->type == REDIS_REPLY_ARRAY) {
for (int j = 0; j < r->elements; j++) {
printf("%u) %s\n", j, r->element[j]->str);
}
}else if(r->type == REDIS_REPLY_ERROR){
printf("%s\n", r->str);
}else{
printf("BUGS .... \n");
}
#ifdef DEBUG_LVL1
printf("Broadcast received...\n");
#endif
}
/*
* jdata function to log to server.
* requires jdata to have been initialized first. Otherwise will segfault.
*
* Inputs
* key -> The jdata variable name
* value -> the value to be logged
* callback -> the callback function if you want a custom callback to signal when a log succeeds.
Can be null
* jdata grade = 'A'
* -> jdata_log_to_server("grade", 'A', null);
*/
void jdata_log_to_server(char *key, char *value, msg_rcv_callback callback){
if(callback == NULL)
callback = jdata_default_msg_received;
int length = strlen(value) + strlen(DELIM) + strlen(app_id) + strlen(DELIM) + 10;
char newValue[length];
sprintf(newValue , "%s%s%s", value, DELIM, app_id);
redisAsyncCommand(jdata_async_context, callback, NULL, "EVAL %s 1 %s %s", "redis.replicate_commands(); \
local t = (redis.call('TIME'))[1]; \
local insert_order = redis.call('ZCARD', KEYS[1]) + 1; \
redis.call('ZADD', KEYS[1], t, ARGV[1] .. \"$$$\" .. insert_order .. \"$$$\" .. t); \
return {t}", key, newValue);
#ifdef DEBUG_LVL1
printf("Logging executed...\n");
#endif
}
/*
* jdata function to remove a logged value in redis.
* requires jdata to have been initialized first. Otherwise will segfault.
*
* Inputs
* key -> The jdata variable name
* value -> the value to be removed
* callback -> the callback function if you want a custom callback to signal when a delete succeeds.
Can be null
* jdata grade = 'A'
* jdata grade = 'B'
*
* This is something you can do if you don't want people seeing the 'A' value in the logs
* -> jdata_log_to_server("grade", 'A', null)
* -> jdata_remove_element("grade", 'A', null);
* -> jdata_log_to_server("grade", 'B', null)
*/
void jdata_remove_element(char *key, char *value, msg_rcv_callback callback){
if(callback == NULL)
callback = jdata_default_msg_received;
redisAsyncCommand(jdata_async_context, callback, NULL, "ZREM %s %s", key, value);
#ifdef DEBUG_LVL1
printf("Element Removed...\n");
#endif
}
/*
* jdata function to subscribe to a value
* This function should be called when we want to subscribe a value. That way, when the value is updated from somewhere else,
* the jdata gets notified about it.
* This function is utilized by jbroadcaster which receives the data on the c side while the logger logs on the c side.
*
* Inputs
* key -> The jdata variable name
* value -> the value to be removed
* on_msg -> the callback function if you want a custom callback to do something when someone logs into that jdata
* connect -> the callback function if you want a custom callback for checking the connection. Can inform when connect attempt fails.
* disconnect -> the callback function if you want a custom callback to notify for disconnections.
*
* Returns the context c, which should be saved when we free the jdata value.
*/
redisAsyncContext *jdata_subscribe_to_server(char *key, msg_rcv_callback on_msg, connection_callback connect, connection_callback disconnect){
char cmd[512];
//Create new context for the jdata. One unique connection for each variable.
redisAsyncContext *c = redisAsyncConnect(redis_serv_IP, redis_serv_port);
if (c->err) {
printf("error: %s\n", c->errstr);
return NULL;
}
if(connect != NULL)
redisAsyncSetConnectCallback(c, connect);
else
redisAsyncSetConnectCallback(c, jdata_default_connection);
if(disconnect != NULL)
redisAsyncSetDisconnectCallback(c, disconnect);
else
redisAsyncSetConnectCallback(c, jdata_default_disconnection);
redisLibeventAttach(c, base);
if(on_msg == NULL)
on_msg = jdata_default_msg_received;
sprintf(cmd, "SUBSCRIBE %s", key);
redisAsyncCommand(c, on_msg, NULL, cmd);
#ifdef DEBUG_LVL1
printf("Subscribe executed...\n");
#endif
return c;
}
/*
Helper function for running custom async commands on redis.
*/
void jdata_run_async_cmd(char *cmd, msg_rcv_callback callback){
if(callback == NULL)
callback = jdata_default_msg_received;
redisAsyncCommand(jdata_async_context, callback, NULL, cmd);
#ifdef DEBUG_LVL1
printf("Async Command Run...\n");
#endif
}
/*
Helper function for running custom async commands on redis.
*/
redisReply *jdata_run_sync_cmd(char *cmd){
redisReply * ret = redisCommand(jdata_sync_context, cmd);
if(ret == NULL){
printf("Error, NULL return....");
}
#ifdef DEBUG_LVL1
printf("Sync Command Run...\n");
#endif
return ret;
}
/*
* Function to free jbroadcaster variable.
* Removes it also from the jdata linked list kept in memory
*
*/
void free_jbroadcaster(jbroadcaster *j){
//To do
jdata_list_node *k;
for(jdata_list_node *i = jdata_list_head; i != NULL;){
k = i;
i = i->next;
if(i->data.jbroadcaster_data == j){
k->next = i->next;
free(i);
break;
}
}
free(j->data);
threadsem_free(j->write_sem);
free(j->key);
free(j);
}
/*
Initializes a jbroadcaster. This specific variable is what receives values on the c side.
Should be utilized when declaring a jbroadcaster
Input:
type => type of the jbroadcaster. Currently supports int, string, float
Though the data will always be in string format and must be converted at a later time.
This is due to redis limitation being only able to store strings.
variable_name => name of the jbroadcaster, must be unique unfortunately.
With jbroadcaster, you cannot shadow a jdata variable name.
activitycallback_f => callback for when a broadcast is received.
What you would like the program to do in such case.
*/
jbroadcaster *jbroadcaster_init(int type, char *variable_name, activitycallback_f usr_callback){
jbroadcaster *ret;
char buf[256];
switch(type){
case JBROADCAST_INT: break;
case JBROADCAST_STRING: break;
case JBROADCAST_FLOAT: break;
default:
printf("Invalid type...\n");
return NULL;
}
ret = (jbroadcaster *)calloc(1, sizeof(jbroadcaster));
ret->type = type;
ret->write_sem = threadsem_new();
ret->data = NULL;
ret->key = strdup(variable_name);
ret->usr_callback = usr_callback;
//Now we need to add it to the list
if(jdata_list_head == NULL){
jdata_list_head = (jdata_list_node *)calloc(1, sizeof(jdata_list_node));
jdata_list_head->data.jbroadcaster_data = ret;
jdata_list_tail = jdata_list_head;
jdata_list_tail->next = NULL;
}else{
jdata_list_tail->next = (jdata_list_node *)calloc(1, sizeof(jdata_list_node));
jdata_list_tail = jdata_list_tail->next;
jdata_list_tail->data.jbroadcaster_data = ret;
jdata_list_tail->next = NULL;
}
ret->context = jdata_subscribe_to_server( variable_name, jbroadcaster_msg_rcv_callback, NULL, NULL);
sprintf(buf, "jbroadcast_func_%s", variable_name);
//IMPORTANT
//REGISTERS the usercallback as a jasync callback to be called.
//This allows us to call the user defined callbacks for jbroadcaster
activity_regcallback(j_s->atable, buf, ASYNC, "v", usr_callback);
return ret;
}
/*
* The jbroadcaster callback that we utilize to process broadcasts.
* This should not be called outside of this library.
* Now, the problem is that this function is run in a separate thread from the main activity thread.
* Thus we have to insert such callback activity in the main activity thread rather than simply running it here.
* In this function, we simply return the most up to date jbroadcast value.
* We do not save older values.
*/
void jbroadcaster_msg_rcv_callback(redisAsyncContext *c, void *reply, void *privdata){
redisReply *r = reply;
char *result;
char *var_name;
char buf[256];
if (reply == NULL) return;
if (r->type == REDIS_REPLY_ARRAY) {
var_name = r->element[1]->str;
result = r->element[2]->str;
if(result != NULL){
for(jdata_list_node *i = jdata_list_head; i != NULL; i = i->next){
if(strcmp(i->data.jbroadcaster_data->key, var_name) == 0){
result = strdup(result);
//At this point, we may need to add a lock to prevent race condition
void *to_free = i->data.jbroadcaster_data->data;
i->data.jbroadcaster_data->data = result;
free(to_free);
if(i->data.jbroadcaster_data->usr_callback != NULL){
//So here instead of executing this function here, we need to insert this into the work queue
sprintf(buf, "jbroadcast_func_%s", i->data.jbroadcaster_data->key);
//Here, we defined a unique REXEC-JDATA to signal a jdata callback that needs to be executed.
command_t *rcmd = command_new("REXEC-JDATA", "ASY", buf, "__", "0", "p", i->data.jbroadcaster_data);
queue_enq(j_s->atable->globalinq, rcmd, sizeof(command_t));
thread_signal(j_s->atable->globalsem);
}
return;
}
}
printf("Variable not found ... \n");
}
}
}
//Returns the last updated jbroadcast value given a jbroadcaster.
void *get_jbroadcaster_value(jbroadcaster *j){
if(j->data == NULL)
printf("Invalid get attempt ...\n");
assert(j->data != NULL);
return j->data;
}
/*
* Initializes jshuffler
*
* Input
* type -> data type of shuffler
* var_name -> name of shuffler
* usr_callback -> function callback for shuffler data received.
*/
jshuffler *jshuffler_init(int type, char *var_name, activitycallback_f usr_callback){
jshuffler *ret = calloc(1, sizeof(jshuffler));
char buf[256];
ret->key = strdup(var_name);
sprintf(ret->rr_queue, "JSHUFFLER_rr_queue|%s", app_id);
sprintf(ret->data_queue, "JSHUFFLER_data_queue|%s", app_id);
sprintf(ret->subscribe_key, "JSHUFFLER|%s", app_id);
ret->data = NULL;
ret->usr_callback = usr_callback;
sem_init(&ret->lock, 0, 0);
redisAsyncContext *subscriber_context = redisAsyncConnect(redis_serv_IP, redis_serv_port);
if (subscriber_context->err) {
printf("error: %s\n", subscriber_context->errstr);
return NULL;
}
if(jdata_list_head == NULL){
jdata_list_head = (jdata_list_node *)calloc(1, sizeof(jdata_list_node));
jdata_list_head->data.jshuffler_data = ret;
jdata_list_tail = jdata_list_head;
jdata_list_tail->next = NULL;
}else{
jdata_list_tail->next = (jdata_list_node *)calloc(1, sizeof(jdata_list_node));
jdata_list_tail = jdata_list_tail->next;
jdata_list_tail->data.jshuffler_data = ret;
jdata_list_tail->next = NULL;
}
redisAsyncSetConnectCallback(subscriber_context, jdata_default_connection);
redisAsyncSetConnectCallback(subscriber_context, jdata_default_disconnection);
redisLibeventAttach(subscriber_context, base);
redisAsyncCommand(subscriber_context, jshuffler_callback, NULL, "SUBSCRIBE %s", ret->subscribe_key);
sprintf(buf, "jshuffler_func_%s", var_name);
activity_regcallback(j_s->atable, var_name, ASYNC, "v", usr_callback);
return ret;
}
/*
* Callback for jshuffler. Should not be called by anything outside this library.
* Functions the same manner as jbroadcast_callback
*/
void jshuffler_callback(redisAsyncContext *c, void *reply, void *privdata){
redisReply *r = (redisReply *)reply;
char var_name[256];
char buf[256];
char *result;
char *result_ptr;
if(r == NULL) return;
if (r->type == REDIS_REPLY_ARRAY) {
if(strcmp(r->element[0]->str, "message") == 0){
result_ptr = strstr(r->element[2]->str, "$$$");
memcpy(var_name, r->element[2]->str, result_ptr - r->element[2]->str);
var_name[result_ptr - r->element[2]->str] = '\0';
result = calloc(strlen(r->element[2]->str) - strlen(var_name), sizeof(char));
sprintf(result, "%s", result_ptr + 3);
for(jdata_list_node *i = jdata_list_head; i != NULL; i = i->next){
if(strcmp(i->data.jshuffler_data->key, var_name) == 0){
//At this point, we may need to add a lock to prevent race condition
void *to_free = i->data.jshuffler_data->data;
i->data.jshuffler_data->data = result;
free(to_free);
if(i->data.jshuffler_data->usr_callback != NULL){
sprintf(buf, "jshuffler_func_%s", i->data.jbroadcaster_data->key);
command_t *rcmd = command_new("REXEC-JDATA", "ASY", buf, "__", "0", "p", i->data.jshuffler_data);
queue_enq(j_s->atable->globalinq, rcmd, sizeof(command_t));
thread_signal(j_s->atable->globalsem);
}
#ifdef DEBUG_LVL1
printf("Result Received:%s\n", result);
#endif
return;
}
}
printf("Variable name not found ...\n");
}
}
}
/*
* Pushes a value into the shuffler. We assume the pushed data is in string format for now.
* This can be changed later on.
*/
void jshuffler_push(jshuffler *j, char *data){
#ifdef DEBUG_LVL1
printf("%s %s %s\n", j->subscribe_key, j->rr_queue, j->data_queue);
#endif
redisAsyncCommand(jdata_async_context, jdata_default_msg_received, NULL,
"EVAL %s 3 %s %s %s %s",
"redis.replicate_commands(); \
local send_to = redis.call('LLEN', KEYS[1]); \
if (send_to == 0) or (send_to == nil) then \
redis.call('RPUSH', KEYS[3], ARGV[1]); \
return {0}; \
else \
local var_name = redis.call('RPOP', KEYS[1]); \
redis.call('PUBLISH', KEYS[2] , var_name .. '$$$' .. ARGV[1]); \
return {send_to}; \
end", j->rr_queue, j->subscribe_key, j->data_queue, data);
}
/*
* Polls a value
*/
void *jshuffler_poll(jshuffler *j){
//#ifdef DEBUG_LVL1
printf("%s %s %s\n", j->subscribe_key, j->rr_queue, j->data_queue);
//#endif
redisReply *ret = redisCommand(jdata_sync_context,
"EVAL %s 2 %s %s %s",
"redis.replicate_commands(); \
local rr_queue_size = redis.call('LLEN', KEYS[1]); \
local data_queue_size = redis.call('LLEN', KEYS[2]); \
if (rr_queue_size == 0 or rr_queue_size == nil) and (data_queue_size > 0) then \
local ret = redis.call('RPOP', KEYS[2]); \
return {ret}; \
else \
redis.call('RPUSH', KEYS[1], ARGV[1]); \
return {'JSHUFFLER_WAIT'}; \
end", j->rr_queue, j->data_queue, j->key);
if (ret->type == REDIS_REPLY_ARRAY) {
//We receive JSHUFFLER_WAIT when the queue is empty and there is nothing to poll out.
//So we continuously poll until we get it.
if(strcmp(ret->element[0]->str, "JSHUFFLER_WAIT") == 0){
printf("Polling ... \n");
sleep(1);
return jshuffler_poll(j);
}
j->data = ret;
}else{
return NULL;
}
return j->data;
}
/*
* Logs an jdata activity
* This is for some logging service that was supposed to be called whenever an activity gets called.
*
*/
void jcmd_log_pending_activity(char *app_id, char *actid, int index){
char key[256];
char actid_expanded[128];
sprintf(key, "%s%s%s", CMD_LOGGER, DELIM, app_id);
sprintf(actid_expanded, "%s|%d", actid, index);
redisAsyncCommand(jdata_async_context, jdata_default_msg_received, NULL, "EVAL %s 1 %s %s", "redis.replicate_commands(); \
local t = (redis.call('TIME'))[1]; \
redis.call('ZADD', KEYS[1], t, ARGV[1]); \
return {t}", key, actid);
}
/*
* The log inserted can beg removed when the activity is acknowledged.
*
*/
void jcmd_remove_acknowledged_activity(char *app_id, char *actid, int index){
char key[256];
char actid_expanded[128];
sprintf(actid_expanded, "%s|%d", actid, index);
sprintf(key, "%s%s%s", CMD_LOGGER, DELIM, app_id);
jdata_remove_element(key, actid, NULL);
}
/*
* Removes completely the activity from redis include all logs of it.
*/
void jcmd_delete_pending_activity_log(char *key, msg_rcv_callback callback){
if(callback == NULL)
callback = jdata_default_msg_received;
redisAsyncCommand(jdata_async_context, callback, NULL, "DEL %s", key);
}
/*
* Returns a list of array of all logs for a particular key.
*/
char **jcmd_get_pending_activity_log(char *key, msg_rcv_callback callback){
if(callback == NULL)
callback = jdata_default_msg_received;
redisReply * r = redisCommand(jdata_sync_context, "ZRANGE %s 0 -1", key);
if (r->type == REDIS_REPLY_ARRAY) {
char **ret = (char **)calloc(r->elements, sizeof(char *));
for (int j = 0; j < r->elements; j++) {
ret[j] = strdup(r->element[j]->str);
}
return ret;
}
return NULL;
}
|
C
|
/* ========================================
*
* Copyright YOUR COMPANY, THE YEAR
* All Rights Reserved
* UNPUBLISHED, LICENSED SOFTWARE.
*
* CONFIDENTIAL AND PROPRIETARY INFORMATION
* WHICH IS THE PROPERTY OF your company.
*
* ========================================
*/
#include "project.h"
#include <stdio.h>
volatile uint32_t count = 0; //variables defined
volatile uint32_t counter_main = 0;
int output = 0;
CY_ISR(DISCONTINUITY_COUNT_RESET) //callback function for ISR to reset the count value
{
counter_main = count;
count=0;
}
CY_ISR(Pin_High_Check) //callback function for ISR to check if pin P_3_1_Comp_out is high
{
count++; //increment count value when pin is HIGH
}
int main(void)
{
Timer_Start(); //start Timer module
PGA_Start(); //start PGA module
VDAC8_Start(); //start VADC module
Comp_Start(); //start Comparator module
LCD_Start(); //start LCD module
LCD_DisplayOn(); //turn LCD display ON
CyGlobalIntEnable; /* Enable global interrupts. */
isr_StartEx(DISCONTINUITY_COUNT_RESET); //define ISRs
isr_1_StartEx(Pin_High_Check);
VDAC8_SetValue(25); //Set value to VDAC
for(;;)
{
CyDelay(50);
LCD_ClearDisplay();
output = (counter_main*60)/6; //convertcount value obtained to RPM
LCD_PrintU32Number(output); //print RPM value on LCD
}
}
|
C
|
#include <stdio.h>
int main()
{
//input the number of rows and coloumns from the user
int r,c;
printf("Please enter the number of rows. \n");
scanf("%d",&r);
printf("Please enter the number of coloumns. \n");
scanf("%d",&c);
//the loop to print the hollow rectangle
int i,j;
for (i=1 ; i <= 1; i++)
{
for (int j = 1; j <= c; j++)
{
printf("*");
}
printf("\n");
}
for (i=2 ; i <= (r-1); i++)
{
for (int j = 1; j <= 1; j++)
{
printf("*");
}
for (int j = 2; j <= (c-1); j++)
{
printf(" ");
}
for (int j = c; j <= c; j++)
{
printf("*");
}
printf("\n");
}
for (i=r ; i <= r; i++)
{
for (int j = 1; j <= c; j++)
{
printf("*");
}
printf("\n");
}
}
|
C
|
#ifdef USE_08_02
static float single_tax_standard[] =
{ 0,23350,56550,117950,256500,0xffffffff};
static float tax_fee[] =
{ 0,3502.50,12798.50,31832.50,81710.50 };
static float tax_percentage[] =
{ 0.15,0.28,0.31,0.36,0.396 };
float single_tax(float income) {
int index;
for (index = 0;
single_tax_standard[index + 1] > 0;
index++){
if (income > single_tax_standard[index] &&
income <= single_tax_standard[index + 1])
return
tax_fee[index] + tax_percentage[index] * (income - single_tax_standard[index]);
}
}
#endif // USE_08_02
|
C
|
#ifndef __LINKED_LIST_H
#define __LINKED_LIST_H
#include<stdbool.h>
#include<malloc.h>
/*
* 链表从下标0开始计算下标,但下标为0的结点是用于代表链表的头结点,
* 其值并无实际意义, 故有效的链表结点下标大于等于1
*/
typedef struct linked_list_node{
int val;//节点值
struct linked_list_node* next;//下一节点
}linked_list_node, *linked_list;// 定义链表的结点
/*
* 函数名称: linked_list_initialize
* 函数功能: 初始化链表,即分配头结点
* 参数: 无
* 返回值: linked_list( 表示分配结果 )
*/
linked_list linked_list_initialize( ){
linked_list temp =(linked_list)malloc( sizeof( linked_list_node ) );//
if( !temp ){
return NULL;
}
temp->next = NULL;
return temp;
}
/*
* 函数名称: linked_list_insert
* 函数功能: 在链表的某一结点后插入一个结点
* 参数: linked_list obj( 链表头结点 ) ,size_t loc( 要插入的位置的前一个结点的位置 ),
* int val( 新结点的值 )
* 返回值: bool( 表示操作是否成功 )
*/
bool linked_list_insert( linked_list obj ,size_t loc, int val ){
linked_list_node* cur = obj;
size_t cnt=0;
while( cur && cnt<loc ){
cur = cur->next;
++cnt;
}
if( cnt<loc || !cur ){
return false;
}
linked_list temp =(linked_list)malloc( sizeof( linked_list_node ) );
if( !temp ){
return false;
}
temp->val = val;
temp->next = cur->next;
cur->next = temp;
return true;
}
/*
* 函数名称: linked_list_delete
* 函数功能: 删除链表的某一结点后的一个结点
* 参数: linked_list obj( 链表头结点 ) ,size_t loc( 要删除的位置的前一个结点的位置 ),
* 返回值: bool( 表示操作是否成功 )
*/
bool linked_list_delete( linked_list obj ,size_t loc ){
linked_list_node* cur = obj;
size_t cnt=0;
while( cur && cnt<loc ){
cur = cur->next;
++cnt;
}
if( cnt<loc || ( cur && !cur->next ) || !cur ){
return false;
}
linked_list_node* temp = cur->next->next;
free( cur->next );
cur->next = temp;
return true;
}
/*
* 函数名称: linked_list_print
* 函数功能: 遍历链表并输出所有结点的值
* 参数: linked_list obj( 链表头结点 )
* 返回值: void
*/
void linked_list_print( linked_list obj ){
linked_list_node* cur = obj->next;
while( cur ){
printf("%d ",cur->val);
cur = cur->next;
}
printf("\n");
return;
}
/*
* 函数名称: linked_list_destory
* 函数功能: 销毁链表
* 参数: linked_list obj( 链表头结点 )
* 返回值: void
*/
void linked_list_destory( linked_list obj ){
linked_list_node* temp;
while( temp = obj->next ){
obj->next = obj->next->next;
free( temp );
}
free( obj );
return;
}
#endif
|
C
|
#include <xc.h>
#include "Thermometer.h"
#include "BitUtillities.h"
#include "Delays.h"
static void thermometer_write_byte(uchar val)
{
uchar byBitValue;
for(uchar i = 0; i < 8; i++)
{
byBitValue = (val >> i) & 1; //shift the lowest bit
RA0 = 0;
TRISA0 = 0;
NOP();
NOP();
NOP();
NOP();
NOP(); //pull high to low,produce write time
if(byBitValue == 1)
TRISA0 = 1; //if write 1,pull high
DELAY_MICRO_SECONDS(63); //63us
TRISA0 = 1;
NOP();
NOP(); //right shift a bit
}
TRISA0 = 1;
}
static uchar thermometer_read_byte(void)
{
uchar ret = 0;
for (char i = 0; i < 8; i++)
{
RA0 = 0;
TRISA0 = 0;
NOP();
NOP();
NOP();
NOP();
NOP();
NOP(); //6us
TRISA0 = 1;
NOP();
NOP();
NOP();
NOP();
NOP(); //4us
ret |= RA0 << i;
DELAY_MICRO_SECONDS(63); //63us
}
return ret;
}
static uchar thermometer_reset(void)
{
RA0 = 0;
TRISA0 = 0;
DELAY_MICRO_SECONDS(504);
TRISA0 = 1;
uchar uiElapsed = 0;
while (RA0 == 1)
{
if (uiElapsed > 120)
return 0x01;
uiElapsed += 2;
}
uiElapsed = 0;
while (RA0 == 0)
{
if (uiElapsed > 240)
return 0x02;
uiElapsed += 2;
};
DELAY_MICRO_SECONDS(430);
thermometer_write_byte(0xCC); //skip rom
return 0;
}
uchar Themometer_WriteScratchPad(const Thermometer_UserConfig userConfig)
{
uchar byStatus = 0;
if ((byStatus = thermometer_reset()) != 0)
return byStatus;
thermometer_write_byte(0x4E);
for (uchar* pUcEntry = &userConfig; pUcEntry < pUcEntry + sizeof(Thermometer_UserConfig); pUcEntry++)
thermometer_write_byte(*pUcEntry);
return byStatus;
}
uchar Thermometer_ReadScratchPad(Thermometer_ScratchPad* pScratchPad, uchar byBytesToRead)
{
uchar byStatus = 0;
if ((byStatus = thermometer_reset()) != 0)
return byStatus;
thermometer_write_byte(0xBE);
if (byBytesToRead > sizeof(Thermometer_ScratchPad))
byBytesToRead = sizeof(Thermometer_ScratchPad);
for (uchar* pSpEntry = pScratchPad; pSpEntry < pSpEntry + byBytesToRead; pSpEntry++)
*pSpEntry = thermometer_read_byte();
byStatus = thermometer_reset();
return byStatus;
}
uchar Thermometer_CopyScratchPadToE2(void)
{
uchar byStatus = 0;
if ((byStatus = thermometer_reset()) != 0)
return byStatus;
thermometer_write_byte(0x48);
return byStatus;
}
uchar Thermometer_CopyE2ToScratchPad(void)
{
uchar byStatus = 0;
if ((byStatus = thermometer_reset()) != 0)
return byStatus;
thermometer_write_byte(0xB8);
return byStatus;
}
uchar Thermometer_ProcessTemperature(void)
{
uchar byStatus = 0;
if ((byStatus = thermometer_reset()) != 0)
return byStatus;
thermometer_write_byte(0x44);
DelayMilliSeconds(750);
return 0;
}
float Thermometer_ConvertTempratureToFloat(uchar ubyTempMsb, uchar ubyTempLsb)
{
//get bottom 3 bits of msb and tack it on to the high nibble of lsb to make the integer part
uchar byIntegerPart = (ubyTempMsb & 0x07) << 4 | GetHighNibble(&ubyTempLsb);
//Get the low nibble, least significant bit is 2^-4 so divide by 2^4 = 16
float fDecimalPart = (float)GetLowNibble(&ubyTempLsb) / 16;
uchar ubySignedPart = ubyTempMsb & 0xF8;
if (ubySignedPart != 0)
return (float)byIntegerPart + fDecimalPart - 128;
return (float)byIntegerPart + fDecimalPart;
}
void Thermometer_ConvertTempratureToBcd(uchar ubyTempMsb, uchar ubyTempLsb, Thermometer_BcdTemperature* pBcdTemperature)
{
pBcdTemperature->bIsNegative = false;
//get bottom 3 bits of msb and tack it on to the high nibble of lsb to make the integer part
char byIntegerPart = (ubyTempMsb & 0b00000111) << 4 | GetHighNibble(&ubyTempLsb);
uchar ubySignedPart = ubyTempMsb & 0xF8;
short sDecimalValue = 0;
uchar byDecimalPart = GetLowNibble(&ubyTempLsb);
//2^-4
if (byDecimalPart & 0x01)
sDecimalValue += 625;
//2^-3
if (byDecimalPart & 0x02)
sDecimalValue += 1250;
//2^-2
if (byDecimalPart & 0x04)
sDecimalValue += 2500;
//2^-1
if (byDecimalPart & 0x08)
sDecimalValue += 5000;
if (ubySignedPart != 0)
{
pBcdTemperature->bIsNegative = true;
byIntegerPart -= 128;
byIntegerPart *= -1;
if (byDecimalPart != 0)
{
sDecimalValue -= 10000;
sDecimalValue *= -1;
byIntegerPart--;
}
}
pBcdTemperature->ubyHundreds = (byIntegerPart / 100);
pBcdTemperature->ubyTens = ((byIntegerPart / 10) % 10);
pBcdTemperature->ubyUnits = (byIntegerPart % 10);
pBcdTemperature->ubyTenths = ((sDecimalValue / 1000));
pBcdTemperature->ubyHundredths = (((sDecimalValue % 1000) / 100));
pBcdTemperature->ubyThousandths = (((sDecimalValue % 100) / 10));
pBcdTemperature->ubyTenThousandths = ((sDecimalValue % 10));
}
|
C
|
/*
* $Id: port_fifo.c,v 1.4 2007/03/19 20:43:32 lizhijie Exp $
*/
#include <cmnOsPort.h>
/* always use this method to initiate cmn_fifo_t.*/
void cmn_fifo_init (int _maxSize, cmn_fifo_t **_ff)
{
cmn_fifo_t *ff = NULL;
ff = cmn_malloc(sizeof(cmn_fifo_t) );
*_ff = ff;
if(_maxSize < 0 )
{
_maxSize = 1;
}
ff->qislocked = cmn_mutex_init ();
/*INIT SEMA TO BLOCK ON GET() WHEN QUEUE IS EMPTY */
ff->qisempty = cmn_sem_init (0);
ff->queue = (cmn_list_t *) cmn_malloc (sizeof (cmn_list_t));
cmn_list_init (ff->queue);
/* ff->nb_elt = 0; */
ff->etat = vide;
ff->maxSize = _maxSize;
}
int cmn_fifo_add (cmn_fifo_t * ff, void *el)
{
cmn_mutex_lock (ff->qislocked);
if (ff->etat != plein)
{
/* ff->nb_elt++; */
cmn_list_add (ff->queue, el, -1); /* insert at end of queue */
}
else
{
MUX_WARN("too much traffic in fifo.");
cmn_mutex_unlock (ff->qislocked);
return -1; /* stack is full */
}
/* if (ff->nb_elt >= FIFO_MAX_SIZE) */
if (cmn_list_size (ff->queue) >= ff->maxSize )
ff->etat = plein;
else
ff->etat = ok;
cmn_sem_post (ff->qisempty);
cmn_mutex_unlock (ff->qislocked);
return 0;
}
int cmn_fifo_insert (cmn_fifo_t * ff, void *el)
{
cmn_mutex_lock (ff->qislocked);
if (ff->etat != plein)
{
/* ff->nb_elt++; */
cmn_list_add (ff->queue, el, 0); /* insert at end of queue */
}
else
{
MUX_WARN("too much traffic in fifo.");
cmn_mutex_unlock (ff->qislocked);
return -1; /* stack is full */
}
/* if (ff->nb_elt >= FIFO_MAX_SIZE) */
if (cmn_list_size (ff->queue) >= ff->maxSize )
ff->etat = plein;
else
ff->etat = ok;
cmn_sem_post (ff->qisempty);
cmn_mutex_unlock (ff->qislocked);
return 0;
}
int cmn_fifo_size (cmn_fifo_t * ff)
{
int i;
cmn_mutex_lock (ff->qislocked);
i = cmn_list_size (ff->queue);
cmn_mutex_unlock (ff->qislocked);
return i;
}
void *cmn_fifo_get (cmn_fifo_t * ff)
{
void *el = NULL;
int i = cmn_sem_wait (ff->qisempty);
if (i != 0)
return NULL;
cmn_mutex_lock (ff->qislocked);
if (ff->etat != vide)
{
el = cmn_list_get (ff->queue, 0);
cmn_list_remove (ff->queue, 0);
/* ff->nb_elt--; */
}
else
{
MUX_ERROR("no element in fifo.");
cmn_mutex_unlock (ff->qislocked);
return 0; /* pile vide */
}
/* if (ff->nb_elt <= 0) */
if (cmn_list_size (ff->queue) <= 0)
ff->etat = vide;
else
ff->etat = ok;
cmn_mutex_unlock (ff->qislocked);
return el;
}
void *cmn_fifo_tryget (cmn_fifo_t * ff)
{
void *el = NULL;
if (0 != cmn_sem_trywait (ff->qisempty))
{/* no elements... */
return NULL;
}
cmn_mutex_lock (ff->qislocked);
if (ff->etat == vide)
return NULL;
if (ff->etat != vide)
{
el = cmn_list_get (ff->queue, 0);
cmn_list_remove (ff->queue, 0);
/* ff->nb_elt--; */
}
else
{/* this case MUST never happen... */
MUX_ERROR("no element in fifo.");
cmn_mutex_unlock (ff->qislocked);
return 0;
}
/* if (ff->nb_elt <= 0) */
if (cmn_list_size (ff->queue) <= 0)
ff->etat = vide;
else
ff->etat = ok;
cmn_mutex_unlock (ff->qislocked);
return el;
}
void cmn_fifo_free (cmn_fifo_t * ff)
{
if (ff == NULL)
return;
cmn_mutex_destroy (ff->qislocked);
/* seems that pthread_mutex_destroy does not free space by itself */
cmn_sem_destroy (ff->qisempty);
cmn_list_ofchar_free(ff->queue, 0);
cmn_free (ff->queue);
cmn_free (ff);
}
|
C
|
/************************************************
* filename: 2d_array.c
* Exercise: Module 5, Exercise 2
* Name: Kelly Lougheed
* Date Created: November 15, 2017
*
* Description: Program that takes in five
* integers, stores them and their squares in a
* 2D array, and prints the contents of the array.
*************************************************/
#include <stdio.h>
int main(void) {
int numbers[5][2];
// Calculate number of elements inside the array
int array_size = sizeof(numbers)/sizeof(numbers[0]);
printf("Enter five integers: ");
// Store integers in array
scanf("%d %d %d %d %d", &numbers[0][0], &numbers[1][0], &numbers[2][0], &numbers[3][0], &numbers[4][0]);
// Calculate the square of each integer and stores it in the array
for (int i = 0; i < array_size; i++) {
numbers[i][1] = numbers[i][0] * numbers[i][0];
}
// Print contents of the array
printf("Value\t Squared\n");
for (int j = 0; j < array_size; j++) {
printf("%d\t %d\n", numbers[j][0], numbers[j][1]);
}
printf("\n");
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
static struct node * head=NULL;
//Function to Insert At Beginning
void insertAtStart(int data){
struct node *p;
if(head==NULL){
p=(struct node *)malloc(sizeof(struct node *));
p->data=data;
p->next=NULL;
head=p;
}
else{
p=(struct node*)malloc(sizeof(struct node*));
p->data=data;
p->next=head;
head=p;
}
printf("Data successfully inserted...");
}
static struct node *new=NULL;
//Function to insert in between
void insertInBtn(int data,int k){
int flag=0;
if(head==NULL){
printf("There is no data to insert in between..please insert atleast one data..\n");
}
else{
struct node *p=head;
while(p!=NULL){
if(p->data!=k){
p=p->next;
}
else{
if(p->data==k){
new=(struct node *)malloc(sizeof(struct node *));
new->data=data;
new->next=p->next;
p->next=new;
printf("Data inserted successfully\n");
flag=1;
break;
}
}
}
}
if(flag!=1){
printf("No data to insert in between..Try again with better luck...\n");
}
}
//Function to insert At End
void insertAtEnd(int data){
int flag=0;
struct node *p;
if(head==NULL){
p=(struct node *)malloc(sizeof(struct node *));
p->data=data;
p->next=NULL;
}
else{
struct node *p1;
p=head;
while(p->next!=NULL){
p=p->next;
}
p1=(struct node *)malloc(sizeof(struct node *));
p1->data=data;
p->next=p1;
p1->next=NULL;
flag=1;
}
if(flag==1){
printf("Data inserted successfully...");
}
}
//Function to Search
void search(int data){
int flag=0;
if(head==NULL){
printf("Hey!! Are u fine.. What u want to search..?..There is nothing your Linked List...Try to insert first\n");
}
else{
struct node *p=head;
while(p!=NULL){
if(p->data==data){
flag=1;
printf("Congo..The one which u tried to find is in your Linked List\n");
}
p=p->next;
}
}
if(flag==0){
printf("Ooops!!!..Bad Luck...Not Found..Try Next time..All the best\n");
}
}
//Function to delete data from linked list
void delete(int data){
int flag=0;
if(head==NULL){
printf("There is Nothing to delete..Are u OK..?\n");
}
else{
if(head->data==data){
struct node *temp=head;
head=head->next;
free(temp);
}
else{
struct node *p=head;
struct node *prev=p;
while(p!=NULL){
if(p->data==data){
flag=1;
prev->next=p->next;
break;
}
else{
prev=p;
p=p->next;
}
}
}
}
if(flag==1){
printf("Required item deleted from your linked list...\n");
}
}
void printLL(){
struct node *p=head;
if(head==NULL){
printf("No data to show you..\n");
}
else{
printf("****************************************\n");
if(head->next==NULL){
printf("%d",head->data);
}
else{
while(p!=NULL){
if(p->next!=NULL){
printf("%d -> ",p->data);
}
else{
printf("%d",p->data);
}
p=p->next;
}
}
}
printf("\n****************************************\n");
}
//Length of Linked List(total number of data inserted)
void lengthLL(){
int count=0;
if(head==NULL){
printf("No elemets...Try Again\n");
}
else{
struct node *p=head;
while(p!=NULL){
++count;
p=p->next;
}
printf("%d data entered...\n",count);
}
}
//nth data from end
/*void nFromEnd(int n){
struct node *fast;
struct node *slow;
}*/
//Message function
void message(){
printf("Please Enter your choice...\n");
printf("1 To Insert at start\n");
printf("2 To Insert at End\n");
printf("3 To Insert in Between\n");
printf("4 To Delete any data from your Linked List\n");
printf("5 To search your data\n");
printf("6 To know number of data entered\n");
printf("9 To Print have a look to your updated Linked List\n");
printf("0 To exit any time...\n");
}
//Driver code
void main(){
printf("Welcome to the world of Linked List Data Manipulation\n");
message();
int n,d;
scanf("%d",&n);
while(n!=0){
switch(n){
case 1:
printf("Enter data to insert At start\n");
scanf("%d",&d);
insertAtStart(d);
break;
case 2:
printf("Enter data to insert at End\n");
scanf("%d",&d);
insertAtEnd(d);
break;
case 3:
printf("Enter data to insert In Between..afer that number after which you want to insert...\n");
//if(choice is 9), then call printLL function
int k;
scanf("%d %d",&d,&k);
insertInBtn(d,k);
break;
case 4:
printf("Enter data to delete\n");
scanf("%d",&d);
delete(d);
break;
case 5:
printf("Enter data you want to search in your Linked List\n");
scanf("%d",&d);
search(d);
break;
case 6:
lengthLL();
break;
case 9:
printLL();
break;
default:
printf("Please Enter correct choice or 0 to exit...");
break;
}
message();
scanf("%d",&n);
if(n==0){
printf("Thank You!!\n");
exit(2);
}
}
}
|
C
|
#include<errno.h>
#include<stdio.h>
#include <string.h>
int main()
{
FILE* fd;
fd=fopen("/etc/shadow","w");
if(fd==NULL)
{
printf("Failed=%d\n",errno);
printf("%s\n",strerror(errno));
}
else
{
fclose(fd);
}
return 0;
}
|
C
|
#include"findshow.h"
#include<stdio.h>
#include<stdlib.h>
#include"interface.h"
#include"show.h"
#include"otherfunc.h"
#include"findfunc.h"
#include"record.h"
#include"gobal.h"
#include<windows.h>
#include"date.h"
int find()
{
int findinput;
scanf("%d",&findinput);
switch (findinput) {
case 1:
system("cls");
finddepartment();
break;
case 2:
system("cls");
finddoctor();
break;
case 3:
system("cls");
findpatient();
break;
case 4:
system("cls");
findtime();
break;
case 5:
return 5;
break;
default:
otherinputinterface();
break;
}
return 0;
}
void finddepart()
{
int x=45;
int y=6;
gotoXY(x+2,y-1);
printf("ѯҽϢ");
gotoXY(x,y);
printf("--------------------");
gotoXY(x,y+14);
printf("--------------------");
int col=x+6;
gotoXY(col,y+1);
printf("10.ǻ");
gotoXY(col,y+3);
printf("20.");
gotoXY(col,y+5);
printf("30.Ƥ");
gotoXY(col,y+7);
printf("40.ڿ");
gotoXY(col,y+9);
printf("50.");
gotoXY(col,y+11);
printf("60.ۿ");
gotoXY(col,y+13);
printf("70.һ");
gotoXY(x-4,y+16);
printf("ѯĿҶӦ:");
}
void finddepartment()
{
int department;
while(1)
{
system("cls");
finddepart();
scanf("%d",&department);
switch(department){
case 10:
{
system("cls");
gotoXY(45,6);
printf("ǻҽϢ:");
gotoXY(19,7);
printf("-----------------------------------------------------------------------------");
char departnum[3];
itoa(department,departnum,10);
Doctor* founddoctor=findDepartment(doctor,departnum);
showdoctor(founddoctor);
break;
}
case 20:
{
system("cls");
gotoXY(45,6);
printf("ҽϢ:");
gotoXY(19,7);
printf("-----------------------------------------------------------------------------");
char departnum[3];
itoa(department,departnum,10);
Doctor* founddoctor=findDepartment(doctor,departnum);
showdoctor(founddoctor);
break;
}
case 30:
{
system("cls");
gotoXY(45,6);
printf("ƤҽϢ:");
gotoXY(19,7);
printf("-----------------------------------------------------------------------------");
char departnum[3];
itoa(department,departnum,10);
Doctor* founddoctor=findDepartment(doctor,departnum);
showdoctor(founddoctor);
break;
}
case 40:
{
system("cls");
gotoXY(45,6);
printf("ڿҽϢ:");
gotoXY(19,7);
printf("-----------------------------------------------------------------------------");
char departnum[3];
itoa(department,departnum,10);
Doctor* founddoctor=findDepartment(doctor,departnum);
showdoctor(founddoctor);
break;
}
case 50:
{
system("cls");
gotoXY(45,6);
printf("ҽϢ:");
gotoXY(19,7);
printf("-----------------------------------------------------------------------------");
char departnum[3];
itoa(department,departnum,10);
Doctor* founddoctor=findDepartment(doctor,departnum);
showdoctor(founddoctor);
break;
}
case 60:
{
system("cls");
gotoXY(45,6);
printf("ۿҽϢ:");
gotoXY(19,7);
printf("-----------------------------------------------------------------------------");
char departnum[3];
itoa(department,departnum,10);
Doctor* founddoctor=findDepartment(doctor,departnum);
showdoctor(founddoctor);
break;
}
case 70:
break;
default:
otherinputinterface();
break;
}
if(department==70)
return;
getchar();
getchar();
}
}
void finddoctor()
{
system("cls");
char doctorID[6];
gotoXY(45,13);
printf("ҽ:");
scanf("%s",doctorID);
Record* foundrecord=findDoctor(record,doctorID);
foundrecord=foundrecord->next;
int count=3;
if(foundrecord==NULL)
{
while(count>=0)
{
system("cls");
gotoXY(45,13);
printf("ҽ (%dsһ)",count);
count--;
Sleep(800);
}
;
return;
}
system("cls");
showdoctordetail(&foundrecord->doctor);
gotoXY(40,13);
printf("---------------------------------------------");
gotoXY(45,15);
printf("ǷҪʾػϢ");
gotoXY(45,17);
printf("1.ʾػϢ");
gotoXY(65,17);
printf("2.һ");
gotoXY(45,19);
printf("ѡӦ: ");
int flag;
scanf("%d",&flag);
switch (flag) {
case 1:
{
int line=15;
while(foundrecord)
{
system("cls");
showpatientsimple(&foundrecord->patient,line);
foundrecord=foundrecord->next;
line++;
}
getchar();
break;
}
case 2:
return;
}
getchar();
}
void findpatient()
{
system("cls");
char patientID[6];
gotoXY(40,13);
printf("뻼֤:");
scanf("%s",patientID);
Record* foundrecord=findPatient(record,patientID);
int count=3;
if(foundrecord->next==NULL)
{
while(count>=0)
{
system("cls");
gotoXY(45,13);
printf("û߲ (%dsһ)",count);
count--;
Sleep(800);
}
return;
}
system("cls");
int line=9;
showpatientdetail(foundrecord,line);
getchar();
getchar();
}
void findtime()
{
system("cls");
Date start;
while(1)
{
system("cls");
gotoXY(35,13);
printf("ѯʼڵ: ");
scanf("%d%d%d",&start.year,&start.mon,&start.day);
start.hour=0;
start.minute=0;
if(judgedateformat(start))break;
else errortimeinterface();
}
Date end;
while(1)
{
gotoXY(35,13);
printf("ѯʼڵ: %d %d %d",start.year,start.mon,start.day);
gotoXY(35,15);
printf("ѯֹڵ: ");
scanf("%d%d%d",&end.year,&end.mon,&end.day);
end.hour=23;
end.minute=59;
if(judgedateformat(end))break;
else errortimeinterface();
}
Record* foundtime=findTime(record,start,end);
int count=3;
if(foundtime->next==NULL)
{
while(count>=0)
{
system("cls");
gotoXY(35,13);
printf("ʱδҵϢ (%dsһ)",count);
count--;
Sleep(800);
}
return;
}
system("cls");
int line=5;
showfindtimepatient(foundtime,line);
getchar();
getchar();
}
|
C
|
#ifndef RANDOMIZER_H
#define RANDOMIZER_H
#include "color_util.h"
#define BUCKET_SIZE 100
#define WEIGHT 50
struct ColorBucketItem {
Uint32 color;
ColorBucketItem* next = nullptr;
};
struct ColorBucket {
int bucket_size;
int weight;
ColorBucketItem* head = nullptr;
ColorBucketItem* tail = nullptr;
ColorBucket* next = nullptr;
};
struct ColorBucketList {
ColorBucket* head = nullptr;
ColorBucket* tail = nullptr;
};
static int colors_to_skip[] = {
0xFF00FF, // Magic pink
0xFFFFFF, // White
0x000000, // Black
};
Uint32 GetColor(SDL_Surface* surface, int x, int y);
/**
* Returns a slightly-randomized bitmap
* THIS WILL MODIFY THE BITMAP PASSED IN, NOT COPY IT
* WATCH YOUR POINTERS
*/
SDL_Surface* RandomizeSurface(SDL_Surface* surface, int seed, int bucket_size, int weight);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*/
@type: Function - int main()
@title: Seleao em Vetor I
@author: Rafael Lima Coelho
@since: 23-10-2019
@version: RLC.1.0.URI
@description: Faa um programa que leia um vetor A[100].
No final, mostre todas as posies do vetor que armazenam um valor menor ou igual a 10 e o valor armazenado em cada uma das posies.
@param: [i], inteiro, Contador e indice do vetor.
@param: [vet], inteiro, Vetor com os numeros digitados pelo usuairo.
@return: caractere, Para cada valor do vetor menor ou igual a 10, escreva "A[i] = x",
onde i a posio do vetor e x o valor armazenado na posio, com uma casa aps o ponto decimal.
/*/
/*Inicio da Funo*/
int main() {
/*Declarao das variveis*/
int i;
double vet[100];
//Atribuindo valores ao vetor
for(i = 0; i < 100; i++)
{
scanf("%lf",&vet[i]);
}
//Imprimindo o vetor
for(i = 0; i < 100; i++)
{
if(vet[i] <= 10)
{
printf("A[%d] = %.1lf\n",i,vet[i]);
}
}
/*Retorno da funo para o fim do programa*/
return 0;
}
|
C
|
#include <cs50.h>
#include <stdio.h>
const int TOTAL = 3;
int main (void)
{
int scores[TOTAL];
for (int i = 0; i < TOTAL; i++)
{
scores[i] = get_int("Score: ");
}
printf("Average: %f\n", average(TOTAL, scores));
}
float average(int lenght, int array[])
{
int sum = 0;
for (int i = 0; i < lenght; i++)
{
sum = sum + array[i];
}
return sum / (float) lenght;
}
|
C
|
#include "push_swap.h"
void free_allocated(t_info *info)
{
t_args *list;
t_args *tmp;
list = info->a;
while (list)
{
tmp = list;
list = list->next;
free(tmp);
}
list = info->b;
while (list)
{
tmp = list;
list = list->next;
free(tmp);
}
free(info);
}
void check(char *line, t_info *info)
{
if (!ft_strncmp(line, "pa", 3))
pa(&info->a, &info->b);
else if (!ft_strncmp(line, "pb", 3))
pb(&info->a, &info->b);
else if (!ft_strncmp(line, "ra", 3))
ra(&info->a);
else if (!ft_strncmp(line, "rb", 3))
rb(&info->b);
else if (!ft_strncmp(line, "rr", 3))
rr(&info->a, &info->b);
else if (!ft_strncmp(line, "rra", 4))
rra(&info->a);
else if (!ft_strncmp(line, "rrb", 4))
rrb(&info->b);
else if (!ft_strncmp(line, "rrr", 4))
rrr(&info->a, &info->b);
else
{
write (2, "Error\n", 6);
free_allocated(info);
exit(0);
}
}
void checker(t_info *info)
{
char *line;
while (get_next_line(0, &line))
{
if (!ft_strncmp(line, "sa", 3))
sa(&info->a);
else if (!ft_strncmp(line, "sb", 3))
sb(&info->b);
else if (!ft_strncmp(line, "ss", 3))
ss(&info->a, &info->b);
else
check(line, info);
free(line);
}
free(line);
if (is_sorted(info->a) && list_size(info->b) == 0)
write (1, "OK\n", 3);
else
write (1, "KO\n", 3);
}
int main(int argc, char **argv)
{
t_info *info;
if (argc > 1)
{
info = malloc(sizeof(t_info));
if (info == NULL)
return (1);
info->size = argc - 1;
info->a = creat_list(info->size);
info->b = malloc(sizeof(t_args));
info->b->next = NULL;
if (!dump_data(info, argv))
{
write(2, "Error\n", 6);
free_allocated(info);
return (1);
}
checker(info);
free_allocated(info);
return (0);
}
return (1);
}
|
C
|
#include<stdio.h>
struct student
{
char name[100];
int reg;
int sub[20];
float avg;
};
void average(struct student s[],int m,int n);
void input(struct student s[],int m,int n);
void output(struct student s[],int m,int n);
void main()
{
struct student s[20];
int n,m,i,j=0;
float p;
printf("enter no. of students: ");
scanf("%d",&m);
printf("enter no. of subjects: ");
scanf("%d",&n);
input(s,m,n);
average(s,m,n);
for(i=0;i<m;i++)
{if(s[i].avg>=50)
j++;
}
p=j;
p=p*100/m;
printf("pass percent is %f\n",p);
//output(s,m,n);
}
void input(struct student s[],int m,int n)
{ int i,j;
for(i=0;i<m;i++)
{
printf("name %d:",i+1);
scanf("%s",s[i].name);
printf("registration no. :");
scanf("%d",&s[i].reg);
printf("subject marks\n");
for(j=0;j<n;j++)
{
scanf("%d",&s[i].sub[j]);
}
}
}
void output(struct student s[],int m,int n)
{int i;
for(i=0;i<m;i++)
printf("student%d average :%f\n",i+1,s[i].avg);
}
void average(struct student s[],int m,int n)
{int i,j;
float sum=0;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
sum+=s[i].sub[j];
s[i].avg=sum;
s[i].avg/=n;
sum=0;
}
}
/*
PS F:\> gcc 63-passpercent.c -o k
PS F:\> ./k
enter no. of students: 3
enter no. of subjects: 2
name 1:ram
registration no. :456
subject marks
67
78
name 2:kamal
registration no. :76
subject marks
75
89
name 3:takur
registration no. :789
subject marks
45
43
pass percent is 66.666664
PS F:\>
*/
|
C
|
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <mpi.h>
void *pgm_read(const char *p)
{
FILE *file = fopen(p, "r");
if (!file)
return 0;
size_t w, h;
void *buf = 0;
if (fscanf(file, "P5\n%zu %zu\n255\n", &w, &h) < 2)
goto err;
if (!w || !h || w > SIZE_MAX/h)
goto err;
if (!(buf = malloc(h*w)))
goto err;
if (fread(buf, 1, h*w, file) != h*w)
goto err;
fclose(file);
return buf;
err:
free(buf);
fclose(file);
return 0;
}
int pgm_write(const char *p, void *buf, size_t width, size_t height)
{
FILE *file = fopen(p, "wb");
if (!file)
return -1;
fprintf(file, "P5\n%zu %zu\n255\n", width, height);
fwrite(buf, 1, height*width, file);
fclose(file);
return 0;
}
int main(int argc, char **argv)
{
if (argc != 5) {
fprintf(stderr, "sobel IN OUT W H\n");
return 1;
}
const char *in = argv[1];
const char *out = argv[2];
int W = atoi(argv[3]);
int H = atoi(argv[4]);
int num_tasks, rank;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_tasks);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int *buf;
unsigned char *pgm;
// Initialize
if(rank==0)
{
buf = malloc(W * H * sizeof *buf);
pgm = pgm_read(in);
if (!pgm) {
fprintf(stderr, "failed to read %s\n", in);
return 1;
}
for (size_t i=0; i < W*H; i++)
buf[i] = pgm[i];
}
int H_new;
int remainder;
H_new = floor(H/num_tasks);
remainder = H-H_new*num_tasks;
int *send_count = malloc(sizeof(int)*num_tasks);
int *disp_count = malloc(sizeof(int)*num_tasks);
for(int i=0; i<num_tasks; i++)
{
if(i==0)
{
send_count[i] = W*(H_new+1);
disp_count[i] = 0;
}
else if(i==num_tasks-1)
{
send_count[i] = W*(H_new+1+remainder);
disp_count[i] = W*H_new*i - W;
}
else
{
send_count[i] = W*(H_new+2);
disp_count[i] = W*H_new*i - W;
}
}
int recv_size;
int *recv_buf;
int *gx;
int *gy;
if(rank == 0)
{
recv_size = W*(H_new+1);
recv_buf = malloc(recv_size*sizeof(int));
gx = malloc(W * H_new * sizeof *gx);
gy = malloc(W * H_new * sizeof *gy);
}
else if(rank==num_tasks-1)
{
recv_size = W*(H_new+1+remainder);
recv_buf = malloc(recv_size*sizeof(int));
gx = malloc(W * (H_new+remainder) * sizeof *gx);
gy = malloc(W * (H_new+remainder) * sizeof *gy);
}
else
{
recv_size = W*(H_new+2);
recv_buf = malloc(recv_size*sizeof(int));
gx = malloc(W * (H_new+1) * sizeof *gx);
gy = malloc(W * (H_new+1) * sizeof *gy);
}
MPI_Scatterv(buf, send_count, disp_count, MPI_INT, recv_buf, recv_size, MPI_INT, 0, MPI_COMM_WORLD);
if(rank==0)
{
for (size_t i = 1; i < H_new; i++)
for (size_t j = 1; j < W-1; j++)
gx[i*W + j] =
1*recv_buf[(i-1)*W + (j-1)] + 0*recv_buf[(i-1)*W + j] + -1*recv_buf[(i-1)*W + (j+1)] +
2*recv_buf[(i+0)*W + (j-1)] + 0*recv_buf[(i+0)*W + j] + -2*recv_buf[(i+0)*W + (j+1)] +
1*recv_buf[(i+1)*W + (j-1)] + 0*recv_buf[(i+1)*W + j] + -1*recv_buf[(i+1)*W + (j+1)];
for (size_t i = 1; i < H_new; i++)
for (size_t j = 1; j < W-1; j++)
gy[i*W + j] =
1*recv_buf[(i-1)*W + (j-1)] + 2*recv_buf[(i-1)*W + j] + 1*recv_buf[(i-1)*W + (j+1)] +
0*recv_buf[(i+0)*W + (j-1)] + 0*recv_buf[(i+0)*W + j] + 0*recv_buf[(i+0)*W + (j+1)] +
-1*recv_buf[(i+1)*W + (j-1)] + -2*recv_buf[(i+1)*W + j] + -1*recv_buf[(i+1)*W + (j+1)];
for (size_t i = 1; i < H_new; i++)
for (size_t j = 1; j < W-1; j++) {
int x = gx[i*W + j];
int y = gy[i*W + j];
recv_buf[i*W + j] = sqrt(x*x + y*y);
}
}
else if(rank==num_tasks-1)
{
for (size_t i = 1; i < H_new+remainder; i++)
for (size_t j = 1; j < W-1; j++)
gx[i*W + j] =
1*recv_buf[(i-1)*W + (j-1)] + 0*recv_buf[(i-1)*W + j] + -1*recv_buf[(i-1)*W + (j+1)] +
2*recv_buf[(i+0)*W + (j-1)] + 0*recv_buf[(i+0)*W + j] + -2*recv_buf[(i+0)*W + (j+1)] +
1*recv_buf[(i+1)*W + (j-1)] + 0*recv_buf[(i+1)*W + j] + -1*recv_buf[(i+1)*W + (j+1)];
for (size_t i = 1; i < H_new+remainder; i++)
for (size_t j = 1; j < W-1; j++)
gy[i*W + j] =
1*recv_buf[(i-1)*W + (j-1)] + 2*recv_buf[(i-1)*W + j] + 1*recv_buf[(i-1)*W + (j+1)] +
0*recv_buf[(i+0)*W + (j-1)] + 0*recv_buf[(i+0)*W + j] + 0*recv_buf[(i+0)*W + (j+1)] +
-1*recv_buf[(i+1)*W + (j-1)] + -2*recv_buf[(i+1)*W + j] + -1*recv_buf[(i+1)*W + (j+1)];
for (size_t i = 1; i < H_new+remainder; i++)
for (size_t j = 1; j < W-1; j++) {
int x = gx[i*W + j];
int y = gy[i*W + j];
recv_buf[i*W + j] = sqrt(x*x + y*y);
}
}
else
{
for (size_t i = 1; i < H_new+1; i++)
for (size_t j = 1; j < W-1; j++)
gx[i*W + j] =
1*recv_buf[(i-1)*W + (j-1)] + 0*recv_buf[(i-1)*W + j] + -1*recv_buf[(i-1)*W + (j+1)] +
2*recv_buf[(i+0)*W + (j-1)] + 0*recv_buf[(i+0)*W + j] + -2*recv_buf[(i+0)*W + (j+1)] +
1*recv_buf[(i+1)*W + (j-1)] + 0*recv_buf[(i+1)*W + j] + -1*recv_buf[(i+1)*W + (j+1)];
for (size_t i = 1; i < H_new+1; i++)
for (size_t j = 1; j < W-1; j++)
gy[i*W + j] =
1*recv_buf[(i-1)*W + (j-1)] + 2*recv_buf[(i-1)*W + j] + 1*recv_buf[(i-1)*W + (j+1)] +
0*recv_buf[(i+0)*W + (j-1)] + 0*recv_buf[(i+0)*W + j] + 0*recv_buf[(i+0)*W + (j+1)] +
-1*recv_buf[(i+1)*W + (j-1)] + -2*recv_buf[(i+1)*W + j] + -1*recv_buf[(i+1)*W + (j+1)];
for (size_t i = 1; i < H_new+1; i++)
for (size_t j = 1; j < W-1; j++) {
int x = gx[i*W + j];
int y = gy[i*W + j];
recv_buf[i*W + j] = sqrt(x*x + y*y);
}
}
int *recv_count = malloc(sizeof(int)*num_tasks);
int *disp_count_r = malloc(sizeof(int)*num_tasks);
int index;
int size;
for(int i=0; i<num_tasks; i++)
{
if(i == 0)
{
recv_count[i] = W*(H_new);
disp_count_r[i] = 0;
}
else if(i == num_tasks-1)
{
recv_count[i] = W*(H_new+remainder);
disp_count_r[i] = W*(H_new)*i;
}
else
{
recv_count[i] = W*(H_new);
disp_count_r[i] = W*(H_new)*i;
}
}
if(rank == 0)
index=0;
else
index=W;
if(rank==num_tasks-1)
size = W*(H_new+remainder);
else
size = W*(H_new);
MPI_Gatherv(&recv_buf[index], size, MPI_INT, buf, recv_count, disp_count_r, MPI_INT, 0, MPI_COMM_WORLD);
// Finalize
if(rank==0)
{
for (size_t i = 0; i < W*H; i++)
pgm[i] = buf[i];
pgm_write(out, pgm, W, H);
free(pgm);
}
MPI_Finalize();
}
|
C
|
#include <stdio.h>
int main( int argc, char **argv ) {
char scratchpad[1024];
while( fgets( scratchpad, 1024, stdin ) != NULL )
{
fprintf( stdout, "I just got a line, and it's: %s",
scratchpad );
if( scratchpad[0] == 'q' )
{
break;
}
}
fprintf( stdout, "program still running, about to end\n" );
}
|
C
|
#include "pointTest.h"
void testMultiplePointParameters() {
Point point1 = {1, 2, 3};
assert(multiplePointParameters(&point1) == 6);
Point point2 = {100, 10, 1000};
assert(multiplePointParameters(&point2) == 1000000);
}
void testCopyPoint() {
Point point1 = {15, 24, 38};
Point *point2 = copyPoint(point1);
assert(point1.height == point2->height);
assert(point1.width == point2->width);
assert(point1.depth == point2->depth);
free(point2);
}
void testConvertPointToIndex() {
Point range = {3, 3, 3};
Point point1 = {0, 0, 0};
Point point2 = {1, 1, 1};
Point point3 = {2, 2, 2};
assert(convertPointToIndex(point1, range) == 0);
assert(convertPointToIndex(point2, range) == 13);
assert(convertPointToIndex(point3, range) == 26);
assert(convertPointToIndex(range, range) == -1);
}
void testConvertIndexToPoint() {
int inx = 21;
Point range = {3, 3, 3};
Point point = convertIndexToPoint(inx, range);
assert(point.height == 1);
assert(point.width == 0);
assert(point.depth == 2);
point = convertIndexToPoint(300, range);
assert(point.height == point.width == point.depth == 0);
assert(convertPointToIndex(convertIndexToPoint(21, range), range) == 21);
}
void testPointAll() {
testMultiplePointParameters();
testCopyPoint();
testConvertPointToIndex();
testConvertIndexToPoint();
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strcmp.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jnovotny <jnovotny@student.hive.fi> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/19 12:32:10 by jnovotny #+# #+# */
/* Updated: 2019/10/19 17:51:22 by jnovotny ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** The strcmp() and strncmp() functions lexicographically compare
** the null-terminated strings s1 and s2.
** The strncmp() function compares not more than n characters.
** Because strncmp() is designed for comparing strings rather than binary data,
** characters that appear after a `\0' character are not compared.
*/
int ft_strcmp(const char *s1, const char *s2)
{
if (ft_strlen(s1) >= ft_strlen(s2))
return (ft_memcmp(s1, s2, ft_strlen(s1)));
else
return (ft_memcmp(s1, s2, ft_strlen(s2)));
}
|
C
|
/********************************
* Snapshot.c *
*********************************
* Mark Kennedy: kenned31 *
* Jordan Ebel : ebel1 *
*********************************
* Description *
* *
* .............. *
********************************/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include "networking.h"
#include "file_io.h"
#define PORT 15457
#define YES 1
#define NO 0
//--- Message Format --------------------------------------------------------------------------------------------------//
//
// from:lamport:#widgets_given:#money_given:vector_timestamp<0>:vector_timestamp<1>:...:vector_timestamp<num_processes-1>
//
// Message is a marker if from is 125 or '}'
//--------------------------------------------------------------------------------------------------------------------//
//--- Delays ---//
#define MARKER_DELAY 5 //Marker Send Rate
#define MESSAGE_DELAY 2 //Message Send Rate
#define CHANNEL_DELAY 1 //Message Processing Rate
#define VERBOSE 1
//Global Variables for each process
int id;
int listenfd;
int num_processes;
int num_snapshots;
int total_snapshots;
FILE * snapshot_file;
int seed;
int last_marker = -1;
pthread_mutex_t money_mutex = PTHREAD_MUTEX_INITIALIZER;
int money = 100;
pthread_mutex_t widget_mutex = PTHREAD_MUTEX_INITIALIZER;
int widgets = 100;
pthread_mutex_t lamport_mutex = PTHREAD_MUTEX_INITIALIZER;
int lamport = 0;
pthread_mutex_t vector_mutex = PTHREAD_MUTEX_INITIALIZER;
int *vector;
//Talk Lock
pthread_mutex_t talk_mutex = PTHREAD_MUTEX_INITIALIZER;
//Virtual Message Channels
pthread_mutex_t channel_mutex = PTHREAD_MUTEX_INITIALIZER;
char **channel;
int *c_recorded;
//Channels that still need to be recorded
int record_c[5];
void lock(){
pthread_mutex_lock(&money_mutex);
pthread_mutex_lock(&widget_mutex);
pthread_mutex_lock(&lamport_mutex);
pthread_mutex_lock(&vector_mutex);
}
void unlock(){
pthread_mutex_unlock(&money_mutex);
pthread_mutex_unlock(&widget_mutex);
pthread_mutex_unlock(&lamport_mutex);
pthread_mutex_unlock(&vector_mutex);
}
void print_status(int mode, int w, int m, int to_from){
if(VERBOSE){
int i;
printf("%d> L:%d <", id, lamport);
for( i=0; i<num_processes; i++){
printf("%d", vector[i]);
if( i < num_processes-1 ) printf(",");
}
if(mode==0) printf("> Received: %d widgets and $%d from %d | ", w, m, to_from);
if(mode==1) printf("> Sent: %d widgets and $%d to %d | ", w, m, to_from);
printf("Widgets:%d Money:$%d\n", widgets, money);
}
}
//Records Snapshots
void record_snapshot (int num, int respond) {
record_state(snapshot_file, id, num, lamport, vector, money, widgets, channel, c_recorded, num_processes, record_c);
//Send out markers to other processes
int i;
char marker[max_buf_len];
marker[0] = '}'; //Marker
marker[1] = id + 1; //From
marker[2] = num + 1; //Snapshot being recorded
if (respond == YES){
pthread_mutex_lock(&talk_mutex);
struct addrinfo *p;
for( i=0; i<num_processes; i++)
{
if ( i == id ) continue;
int talkfd = set_up_talk(PORT+i, &p);
if (talkfd != -1){
int num_bytes = 0;
while (num_bytes <= 0){
num_bytes = udp_send(talkfd, marker, p);
}
close(talkfd);
}
}
pthread_mutex_unlock(&talk_mutex);
}
}
//Take num_snapshots Snapshots (send out markers from process 0)
void *take_snapshots ()
{
int i,j;
int snaps = num_snapshots;
for( i=0; i<snaps; i++)
{
//Take Snapshot Every 5 seconds
sleep(MARKER_DELAY);
// Reset markers received
for( j=0; j<num_processes; j++){
record_c[j] = 1;
}
// Record own state and send out markers
if(VERBOSE) printf("%d> Taking Snapshot %d\n", id, i);
lock();
record_snapshot(i,YES);
unlock();
}
return 0;
}
//Process Received Messages
void *process_message (void *ptr)
{
char *buf = (char *)ptr;
sleep(CHANNEL_DELAY);
int from = *((int *)buf) - 1;
int l = *((int *)buf+1) - 1;
int w = *((int *)buf+2) - 1;
int m = *((int *)buf+3) - 1;
int i;
int v[num_processes];
for( i=4; i<num_processes+4; i++){
v[i-4] = *((int *)buf+i)-1;
}
/*Update invariants*/
lock();
widgets += w;
money += m;
if (l < lamport) //lamport update
lamport++;
else
lamport = l + 1;
for( i=0; i<num_processes; i++){ //vector timestamp update
if(i == id)
vector[i]++;
else if(vector[i] < v[i])
vector[i] = v[i];
}
print_status(0, w, m, from);
unlock();
//Message Processed, Clear Channel
pthread_mutex_lock(&channel_mutex);
channel[from][0] = '\0'; //first byte to null signifies nothing in channel
c_recorded[from] = YES;
pthread_mutex_unlock(&channel_mutex);
return 0;
}
//Run by read threads
void *read_messages ()
{
//Continue receiving messages until all snapshots have been recorded
char * buf = (char *)malloc(max_buf_len * sizeof(char));
while(num_snapshots > 0){
int num_bytes = udp_listen(listenfd, buf);
if (num_bytes > 0){
//Check if marker
if (buf[0] == '}'){
int from = buf[1] - 1;
int num = buf[2] -1;
if( id != 0 ) { //Process 0 already took its snapshot
if (from == 0 /*&& last_marker != num*/){
if(VERBOSE) printf("%d> Taking Snapshot %d\n", id, num);
last_marker = num;
int i;
for (i=0; i<num_processes; i++){
record_c[i] = 1;
}
record_snapshot(num,YES);
num_snapshots--;
}
else /*if(from != 0)*/{ //Keep recording channels
record_snapshot(num,NO);
record_c[from] = 0;
}
}
else { //Process 0 updates
record_c[from] = 0;
//If all processes took a snapshot
int snapshot_complete = 1;
int i;
for (i=0; i<num_processes; i++){
if(record_c[i] == 1)
snapshot_complete = 0;
}
if (snapshot_complete == 1)
num_snapshots--;
}
}
else{
//Put message into channel to process
int from = buf[0] -1;
pthread_mutex_lock(&channel_mutex);
memcpy(channel[from], buf, max_buf_len);
c_recorded[from] = NO;
pthread_mutex_unlock(&channel_mutex);
//Create a thread to process message when ready
pthread_t process_thread;
if (pthread_create(&process_thread, NULL, &process_message, (void *)channel[from])){
printf("%d> Process Thread error\n", id);
}
}
}
}
//free(buf);
return 0;
}
//Run by write threads
void *write_messages ()
{
while (num_snapshots > 0){
lock();
int w = widgets==0 ? 0 : rand() % widgets + 1;
int m = money==0 ? 0: rand() % money + 1;
int sendto = rand() % num_processes;
char message[max_buf_len];
*((int *)message) = id+1; //can't send 0 it is NULL
*((int *)message+1) = lamport+1;
*((int *)message+2) = w+1;
*((int *)message+3) = m+1;
int i;
for( i=4; i<num_processes+4; i++){
if( i-4 == id )
vector[i-4]++;
*((int *)message+i) = vector[i-4]+1;
}
widgets -= w;
money -= m;
lamport++;
pthread_mutex_lock(&talk_mutex);
struct addrinfo *p;
int talkfd = set_up_talk(PORT+sendto, &p);
if(talkfd != -1){
udp_send(talkfd, message, p);
}
else{
printf("bad talkfd\n");
}
close(talkfd);
pthread_mutex_unlock(&talk_mutex);
print_status(1, w, m, sendto);
unlock();
//Wait until another message can be sent
sleep(MESSAGE_DELAY);
}
return 0;
}
//What every process runs
void run ()
{
// Create Read/Write Threads
pthread_t read_thread, write_thread;
if (pthread_create(&read_thread, NULL, &read_messages, NULL)){
printf("%d> Read Thread error\n", id);
}
if (pthread_create(&write_thread, NULL, &write_messages, NULL)){
printf("%d> Write Thread error\n", id);
}
// Make Snapshot Marker Thread for Process 0
if (id == 0)
{
pthread_t marker_thread;
if (pthread_create(&marker_thread, NULL, &take_snapshots, NULL)){
printf("%d> Marker Thread error\n", id);
}
pthread_join(marker_thread, NULL);
}
pthread_join(read_thread, NULL);
pthread_join(write_thread, NULL);
}
int main (int argc, const char* argv[])
{
int i = 0;
if (argc != 4){
printf("snapshot usage: num_processes num_snapshots random_seed\n");
return -1;
}
else{
num_processes = atoi(argv[1]);
num_snapshots = atoi(argv[2]);
total_snapshots = num_snapshots;
seed = atoi(argv[3]);
}
if(VERBOSE) printf("processes: %d snapshots: %d \n", num_processes, num_snapshots);
//Setup listening sockets and snapshot file descriptors
int listenfds[num_processes];
FILE * filefds[num_processes];
for( i=0; i<num_processes; i++){
listenfds[i] = set_up_listen(PORT+i);
filefds[i] = open_file(i);
}
//Allocate and Initialize Vector Timestamps to <0,0,...>
vector = (int *)malloc(num_processes * sizeof(int));
for( i=0; i<num_processes; i++){
vector[i] = 0;
}
//Allocate Message Channel Processing Queues
//Messages are processed faster than they are sent, so only need
//1 message receiving channel per process
channel = (char **)malloc(num_processes * sizeof(char *));
c_recorded = (int *)malloc(num_processes * sizeof(int));
for( i=0; i<num_processes; i++ ){
channel[i] = (char *)malloc(max_buf_len * sizeof(char));
channel[i][0] = '\0';
c_recorded[i] = NO;
}
//Create Processes and Run Program
for( i=1; i<num_processes; i++ ){
if( fork() == 0 ){
id = i;
srand(seed+i);
listenfd = listenfds[i];
snapshot_file = filefds[i];
run();
_exit(EXIT_SUCCESS);
}
}
//Process 0
id = 0;
srand(seed);
listenfd = listenfds[0];
snapshot_file = filefds[0];
run();
//Close listening sockets and snapshot files
for( i=0; i<num_processes; i++){
close(listenfds[i]);
close_file(filefds[i]);
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int ans,n[30],key,num,i;
scanf("%d",&num);
printf("Enter the key:");
scanf("%d",&key);
for(i=1;i<=num;i++)
{
scanf("%d",&n[i]);
}
i=key;
ans=n[i];
printf("%d",ans);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
FILE *f = fopen("redirect.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
/* print some text */
const char *text = "A simple program output.";
fprintf(f, "%s\n", text);
fclose(f);
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct replay {int /*<<< orphan*/ sample_rate; int /*<<< orphan*/ tempo; } ;
/* Variables and functions */
scalar_t__ calculate_tick_len (int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ replay_set_sequence_pos (struct replay*,int /*<<< orphan*/ ) ;
int replay_tick (struct replay*) ;
int replay_calculate_duration( struct replay *replay ) {
int count = 0, duration = 0;
replay_set_sequence_pos( replay, 0 );
while( count < 1 ) {
duration += calculate_tick_len( replay->tempo, replay->sample_rate );
count = replay_tick( replay );
}
replay_set_sequence_pos( replay, 0 );
return duration;
}
|
C
|
#include "helper.h"
static char msg[250];
void checkArguments(int argc, char **argv, args *givenArgs)
{
int opt,res;
//initialize all values to zero
givenArgs->bArg = 0;
givenArgs->cArg = 0;
givenArgs->nArg = 0;
givenArgs->tArg = 0;
givenArgs->vArg = 0;
if (argc < 13)
{
showUsageAndExit();
}
//beforehand get t and c values
/*res = atoi(argv[10]);
if (res < 1)
{
showUsageAndExit();
}
else{
givenArgs->tArg = res;
}
res = atoi(argv[6]);
if (res < 3)
{
showUsageAndExit();
}
else{
givenArgs->cArg = res;
}*/
while ((opt = getopt(argc, argv, "n:v:c:b:t:i:")) != -1)
{
switch (opt)
{
case 'n':
res = atoi(optarg);
if (res < 2)
{
showUsageAndExit();
}
givenArgs->nArg = res;
break;
case 'v':
res = atoi(optarg);
if (res < 2)
{
showUsageAndExit();
}
givenArgs->vArg = res;
break;
case 'c':
res = atoi(optarg);
if (res < 3)
{
showUsageAndExit();
}
givenArgs->cArg = res;
break;
case 'b':
res = atoi(optarg);
if (res < 1)
{
showUsageAndExit();
}
givenArgs->bArg = res;
break;
case 't':
res = atoi(optarg);
if (res < 1)
{
showUsageAndExit();
}
givenArgs->tArg = res;
break;
case 'i':
strcpy(givenArgs->iArg , optarg);
break;
case '?':
showUsageAndExit();
break;
default:
showUsageAndExit();
break;
}
}
if (givenArgs->bArg < (givenArgs->tArg*givenArgs->cArg) + 1)
{
showUsageAndExit();
}
}
void showUsageAndExit()
{
printf("Usage: ./program [FLAGS] and [PARAMETERS]\n"
"Flags and Parameters:\n"
"-n >= 2: the number of nurses (integer)\n"
"-v >= 2: the number of vaccinators (integer)\n"
"-c >= 3: the number of citizens (integer)\n"
"-b >= tc+1: size of the buffer (integer)\n"
"-t >= 1: how many times each citizen must receive the 2 shots (integer)\n"
"-i: pathname of the input file\n"
"Example\n"
"./program -n 3 -v 2 -c 3 -b 11 -t 3 -i /home/user/Desktop/test\n");
exit(EXIT_FAILURE);
}
void errExit(char *msg){
//In case of an arbitrary error,
//exit by printing to stderr a nicely formatted informative message.
fprintf(stderr, "%s:%s\n",msg,strerror(errno));
exit(EXIT_FAILURE);
}
int safeRead(int fd, void *buf, size_t size)
{
int rd = read(fd, buf, size);
if (rd == -1)
{
errExit("reading error!");
}
return rd;
}
int safeOpen(const char *file, int oflag)
{
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH | S_IRWXU;
int fd = open(file, oflag, mode);
if (fd < 0)
{
errExit("open error!");
}
return fd;
}
int safeLseek(int fd, int offset, int whence)
{
int pos = lseek(fd, offset, whence);
if (pos == -1)
{
errExit("lseek error!");
}
return pos;
}
char readOneChar(int fd){
char c;
int eof;
// x represent end of file
eof = safeRead(fd, &c, 1);
if (eof != 0)
{
if (c != '\n')
{
return c;
}
eof = safeRead(fd, &c, 1);
if (eof != 0)
{
return c;
}
return 'x';
}
return 'x';
}
int getMin(int a, int b){
if (a < b)
{
return a;
}
else{
return b;
}
}
void printNurseMsg(int index,pid_t pid, char vacc, clinic *info){
sprintf(msg,"Nurse %d (pid=%ld) has brought vaccine %c:the clinic has %d vaccine1 and %d vaccine2.",index, (long)pid,vacc,info->dose1,info->dose2);
printf("%s\n",msg);
}
void printCitizenMsg(int index,pid_t pid, int time, clinic *info){
if (time == 1)
{
sprintf(msg,"Citizen %d (pid=%ld) is vaccinated for the %dst time: the clinic has %d vaccine1 and %d vaccine2",index,(long)pid,time,info->dose1,info->dose2);
}
else if (time == 2)
{
sprintf(msg,"Citizen %d (pid=%ld) is vaccinated for the %dnd time: the clinic has %d vaccine1 and %d vaccine2",index,(long)pid,time,info->dose1,info->dose2);
}
else if (time == 3)
{
sprintf(msg,"Citizen %d (pid=%ld) is vaccinated for the %drd time: the clinic has %d vaccine1 and %d vaccine2",index,(long)pid,time,info->dose1,info->dose2);
}
else{
sprintf(msg,"Citizen %d (pid=%ld) is vaccinated for the %dth time: the clinic has %d vaccine1 and %d vaccine2",index,(long)pid,time,info->dose1,info->dose2);
}
printf("%s\n",msg);
}
void printVaccinatorMsg(int index,pid_t pid, pid_t citPid){
sprintf(msg,"Vaccinator %d (pid=%ld) is inviting citizen pid=%ld to the clinic",index,(long)pid,(long)citPid);
printf("%s\n",msg);
}
void printStartMsg(clinic *info){
sprintf(msg,"Welcome to the GTU344 clinic. Number of citizens to vaccinate c=%d with t=%d doses.",info->givenParams.cArg,info->givenParams.tArg);
printf("%s\n",msg);
}
void citizenLeaveMsg(int leftCiti){
sprintf(msg,"Citizen is leaving. Remaining citizens to vaccinate: %d",leftCiti);
printf("%s\n",msg);
}
void nurseLeaveMsg(){
printf("Nurses have carried all vaccines to the buffer, terminating.\n");
}
void allCityMsg(){
printf("All citizens have been vaccinated.\n");
}
void vaccDoseMsg(int index,pid_t pid, int times){
sprintf(msg,"Vaccinator %d (pid=%ld) vaccinated %d doses.",index,(long)pid,times);
printf("%s\n",msg);
}
void clinicClosedMsg(){
printf("The clinic is now closed. Stay healthy.\n");
}
/*int main(int argc, char *argv[])
{
//start search operation
args givenParams;
checkArguments(argc, argv, &givenParams);
printf("n:%d\n",givenParams.nArg);
printf("v:%d\n",givenParams.vArg);
printf("c:%d\n",givenParams.cArg);
printf("b:%d\n",givenParams.bArg);
printf("t:%d\n",givenParams.tArg);
printf("i:%s\n",givenParams.iArg);
//-------------------------------
printf("n:%d\n",biontech->givenParams.nArg);
printf("v:%d\n",biontech->givenParams.vArg);
printf("c:%d\n",biontech->givenParams.cArg);
printf("b:%d\n",biontech->givenParams.bArg);
printf("t:%d\n",biontech->givenParams.tArg);
printf("i:%s\n",biontech->givenParams.iArg);
printf("dose1:%d\n",biontech->dose1);
printf("dose2:%d\n",biontech->dose2);
printf("fd:%d\n",biontech->fd);
return 0;
}*/
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 128
struct message
{
int type;
char *content;
};
int factorial(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
return n * factorial(n - 1);
}
void reverse(char* s)
{
char temp;
for (int i = 0, j = strlen(s) - 1; i < j; i++, j--)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
void itoa(int n, char* s)
{
int i = 0;
do
{
s[i] = n % 10 + '0';
i++;
} while ((n = n / 10) > 0);
s[i] = '\0';
reverse(s);
}
int main(int argc, char* argv[])
{
int msg_id;
int msg_flg = IPC_CREAT | 0666;
key_t key;
struct message msg_buf;
if (atoi(argv[1]) <= 3)
{
return -1;
}
key = ftok(".", 'a');
if (key == -1)
{
perror("key created\n");
return 1;
}
msg_id = msgget(key, msg_flg);
if (msg_id == -1)
{
perror("queue created\n");
return 2;
}
switch (fork())
{
case -1:
perror("fork error\n");
return 3;
case 0:
msg_buf.type = 1;
msg_buf.content = argv[1];
printf("child received: %s\n", msg_buf.content);
if (msgsnd(msg_id, &msg_buf, sizeof(struct message), 0) == -1)
{
perror("message send\n");
return 4;
}
sleep(5);
printf("child received from parent:\n");
if (msgrcv(msg_id, &msg_buf, SIZE, 2, 0) == -1)
{
perror("message receive\n");
return 5;
}
printf("%s\n", msg_buf.content);
return 0;
default:
sleep(1);
if (msgrcv(msg_id, &msg_buf, SIZE, 1, 0) == -1)
{
perror("message receive\n");
return 5;
}
printf("parent received from children:\n");
printf("%s\n", msg_buf.content);
char temp[SIZE];
itoa(factorial(atoi(msg_buf.content)), temp);
msg_buf.content = temp;
msg_buf.type = 2;
if (msgsnd(msg_id, &msg_buf, sizeof(struct message), 0) == -1)
{
perror("message send\n");
return 4;
}
sleep(8);
return 0;
}
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
int i,j,l1,l2,x;
char a[1000],b[1000];
while(gets(a)&&gets(b))
{
l1=strlen(a);
l2=strlen(b);
if(l1<l2) x=l1;
else x=l2;
for(i=0;i<x;i++)
{
printf("%c%c\n",b[i],a[i]);
}
if(x==l2)
{
for(i=x;a[i]!='\0';i++)
printf("%c\n",a[i]);
}
else if(x==l1)
{
for(i=x;b[i]!='\0';i++)
printf("%c\n",b[i]);
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct node *f = NULL;
struct node *r = NULL;
struct node
{
int data;
struct node *next;
};
void linkedlisttransversal(struct node *ptr) //for traversing
{
printf("traversing the queue\n");
while (ptr != NULL)
{
printf("element %d\n", ptr->data);
ptr = ptr->next;
}
}
int dequeue()
{
int val=-1;
struct node *ptr = f;
if (f == NULL)
printf("queue is empty\n");
else
{
f = f->next;
val =ptr->data;
free(ptr);
}
return val;
}
void enqueue(int val)
{
struct node *n = (struct node *)malloc(sizeof(struct node));
if (n == NULL)
printf("queue is full\n");
else
{
n->data = val;
n->next = NULL;
if (f == NULL) //it is a special condition for making a node because if f= null it means queue is empty then we have put both f and r is equLL TO N
{
f = r = n;
}
else
{
r->next = n;
r = n;
}
}
}
int main()
{
linkedlisttransversal(f);
printf("dequeing element %d\n", dequeue());
enqueue(34);
enqueue(44);
enqueue(54);
printf("dequeing element %d\n", dequeue());
enqueue(14);
linkedlisttransversal(f);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "LinkedList.h"
#include "SNAP.h"
int hash_Id(int id)
{
return (id % 1009);
}
typedef struct SNAP * SNAP;
SNAP new_SNAP(int s, char *n, char *a, char *p)
{
SNAP this = (SNAP) malloc(sizeof(struct SNAP));
this->StudentId = s;
this->name = n;
this->address = a;
this->phone = p;
this->next = NULL;
return this;
}
void print_SNAP(SNAP this)
{
printf("%d\t %s \t%s \t%s\n", this->StudentId, this->name, this->address, this->phone);
}
void printTable_SNAP(SNAP *database)
{
printf("SNAP Table:\n");
for (int i = 0; i < 1009; i++)
{
SNAP temp = database[i];
while (temp != NULL)
{
print_SNAP(temp);
temp = temp->next;
}
}
}
int equals_SNAP(SNAP this, char *stId, char *name, char *address, char *phone)
{
if (this->StudentId == atoi(stId) || strcmp(stId, "*") == 0)
{
if (strcmp(this->name, name) == 0 || strcmp(name, "*") == 0)
{
if (strcmp(this->address, address) == 0 || strcmp(address, "*") == 0)
{
if (strcmp(this->phone, phone) == 0 || strcmp("*", phone) == 0)
return 1;
}
}
}
return 0;
}
LinkedList lookup_SNAP(char *stId, char *name, char *address, char *phone, SNAP *database)
{
//printf("Items found:\n");
LinkedList list = new_LinkedList();
if (strcmp(stId, "*") == 0)
{
for (int i = 0; i < 1009; i++)
{
SNAP temp = database[i];
if (temp != NULL)
{
SNAP curr = database[i];
while (curr != NULL)
{
if (equals_SNAP(curr, stId, name, address, phone))
LinkedList_add_at_end(list, curr);
curr = curr->next;
}
}
}
}
else
{
int hash = hash_Id(atoi(stId));
SNAP curr = database[hash];
while (curr != NULL)
{
if (equals_SNAP(curr, stId, name, address, phone))
LinkedList_add_at_end(list, curr);
curr = curr->next;
}
}
return list;
}
void insert_SNAP(char *stId, char *name, char *address, char *phone, SNAP *database)
{
if (LinkedList_elementAt(lookup_SNAP(stId, name, address, phone, database), 0) != NULL)
{
printf("Failed to insert because item is already in list.\n");
return;
}
SNAP this = new_SNAP(atoi(stId), name, address, phone);
int hash = hash_Id(atoi(stId));
//printf("Hash: %d", hash);
SNAP curr = database[hash];
if (curr == NULL)
{
database[hash] = this;
}
else
{
while (curr->next != NULL)
{
curr = curr->next;
}
curr->next = this;
}
printf("Successfully inserted ");
print_SNAP(this);
printf("\n");
}
void delete_SNAP(char *stId, char *name, char *address, char *phone, SNAP *database)
{
int delCount = 0;
if (strcmp(stId, "*") == 0)
{
for (int i = 0; i < 1009; i++)
{
SNAP temp = database[i];
if (temp != NULL)
{
while (equals_SNAP(temp, stId, name, address, phone) && temp != NULL)
{
database[i] = temp->next;
temp = database[i];
delCount++;
}
if (database[i] != NULL && database[i]->next != NULL)
{
SNAP prev = database[i];
SNAP curr = database[i]->next;
while (curr != NULL)
{
if (equals_SNAP(curr, stId, name, address, phone))
{
prev->next = curr->next;
curr = prev->next;
delCount++;
}
else
{
prev = prev->next;
curr = curr->next;
}
}
}
}
}
}
else
{
int hash = hash_Id(atoi(stId));
SNAP temp = database[hash];
if (temp != NULL)
{
while (temp != NULL && equals_SNAP(temp, stId, name, address, phone))
{
database[hash] = temp->next;
temp = database[hash];
delCount++;
}
if (database[hash] != NULL && database[hash]->next != NULL)
{
SNAP prev = database[hash];
SNAP curr = database[hash]->next;
while (curr != NULL)
{
if (equals_SNAP(curr, stId, name, address, phone))
{
prev->next = curr->next;
curr = prev->next;
delCount++;
}
else
{
prev = prev->next;
curr = curr->next;
}
}
}
}
}
printf("%d item(s) deleted.\n", delCount);
}
|
C
|
/* Serial program for matrix-matrix product.
*
* VVD
* name: Ioannis Chouliaras
* AM : 2631
*/
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#define N 1024
int A[N][N], B[N][N], C[N][N];
/* Functions */
int readmat(char *fname, int *mat, int n),
writemat(char *fname, int *mat, int n);
void parallel_work(int S);
/* Main Method */
int main(int argc, char ** argv)
{
int i, j, k, sum, tasks;
double start, end;
/* check argc */
if (argc != 2)
exit( 1 + printf("Give me one number for the S\n") );
/* Take S from argv and atoi */
int S = atoi(argv[1]);
/* Check if S is correct */
if (N%S != 0)
exit( 1 + printf("Wrong S number\n") );
tasks = (N/S)*(N/S);
printf("I will make %d Tasks\n", tasks);
/* Read matrices from files: "A_file", "B_file"
*/
if (readmat("Amat1024.txt", (int *) A, N) < 0)
exit( 1 + printf("file problem\n") );
if (readmat("Bmat1024.txt", (int *) B, N) < 0)
exit( 1 + printf("file problem\n") );
omp_set_num_threads(4);
start = omp_get_wtime();
#pragma omp parallel firstprivate(S)
{
#pragma omp single
parallel_work(S); // call my function!
}
end = omp_get_wtime();
/* Save result in "Cmat1024"
*/
writemat("Cmat1024.txt", (int *) C, N);
printf("Work took %.2f\n", end - start);
return (0);
}
/* Utilities to read & write matrices from/to files
* VVD
*/
#define _mat(i,j) (mat[(i)*n + (j)])
int readmat(char *fname, int *mat, int n)
{
FILE *fp;
int i, j;
if ((fp = fopen(fname, "r")) == NULL)
return (-1);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (fscanf(fp, "%d", &_mat(i,j)) == EOF)
{
fclose(fp);
return (-1);
};
fclose(fp);
return (0);
}
int writemat(char *fname, int *mat, int n)
{
FILE *fp;
int i, j;
if ((fp = fopen(fname, "w")) == NULL)
return (-1);
for (i = 0; i < n; i++, fprintf(fp, "\n"))
for (j = 0; j < n; j++)
fprintf(fp, " %d", _mat(i, j));
fclose(fp);
return (0);
}
void parallel_work(int S)
{
int i, j, k, sum, p, t;
for (i = 0; i < N; i = i+S)
for (j = 0; j < N; j = j+S)
{
#pragma omp task shared(i, j) untied
{
for (p = i; p < i+S; p++)
for(t = j; t < j+S; t++) {
for (k = sum = 0; k < N; k++)
sum += A[p][k]*B[k][t];
C[p][t] = sum;
}
}
}
}
|
C
|
/*
* Q. Allocate 2 kernel buffers of 1024 bytes each DEVBUFA, DEVBUFB. Implement a char driver that maps DEVBUFA to /dev/bufa and DEVBUFB to /dev/bufb. Driver shud provide support for read, write operations.
* In this module we creating a driver having 2 buffers and supports 2 minor numbers
* This approach is also concurrent driver
*/
/*
* In this prog, u cannot use misc since misc registers only one minor no..
*/
#include<linux/kernel.h>
#include<linux/module.h>
#include<linux/version.h>
#include<linux/device.h>
#include<asm/uaccess.h>
#include<linux/fs.h>
#include<linux/path.h>
#include<linux/slab.h>
#include<linux/cdev.h>
#define DEV_NAME "device_buffer"
#define BUFCOUNT 2
#define BUFSIZE 4096 /*Default size of buffer*/
#define SUCCESS 0
#define FAILURE -1
#define FOPS_INIT { \
.owner = THIS_MODULE, \
.open = open, \
.read = read, \
.write = write, \
.release = release, \
.llseek = lseek \
}
typedef struct devbuf{
struct mutex mtx;//device lock to avoid race conditions.
char *buf;
size_t buf_size;
int minor;
}dbuf_t;
typedef struct devpri{
dbuf_t dbuf[BUFCOUNT];
struct cdev cdev;
/* If you give struct cdev *cdev then u need to do cdev_alloc() */
}dpri_t;
dpri_t *pRiV;
int open(struct inode *in, struct file *fl){
dpri_t *dpri = container_of(in->i_cdev,dpri_t,cdev);
pr_info("%s: Invoked\n",__FUNCTION__);
switch(iminor(in)){
case 0:
mutex_init(&dpri->dbuf[0].mtx);
dpri->dbuf[0].minor = 0;
if(!dpri->dbuf[0].buf)
dpri->dbuf[0].buf = kmalloc(BUFSIZE,GFP_KERNEL);
dpri->dbuf[0].buf_size = BUFSIZE;
fl->private_data = dpri->dbuf+0;
break;
case 1:
mutex_init(&dpri->dbuf[1].mtx);
dpri->dbuf[1].minor = 1;
if(!dpri->dbuf[1].buf)
dpri->dbuf[1].buf = kmalloc(BUFSIZE,GFP_KERNEL);
dpri->dbuf[1].buf_size = BUFSIZE;
fl->private_data = dpri->dbuf+1;
break;
default:
pr_info("Invalid minor no\n");
break;
}
return SUCCESS;
}
ssize_t read(struct file *fl, char __user *buf,size_t sz, loff_t *off){
char *pos;
int ret;
dbuf_t *dbuf = fl->private_data;
/*
* If u want to performe read operation first u hav to know from which buffer u shud read data.
* I ment that 2 devices are associated with this driver module.
*/
pr_info("%s: Invoked\n",__FUNCTION__);
if(sz<0) return -EINVAL;
mutex_lock_interruptible(&dbuf->mtx);
if(sz > dbuf->buf_size)
sz = dbuf->buf_size;
if(sz+*off > dbuf->buf_size)
sz = dbuf->buf_size-*off;
pos = dbuf->buf + *off;
ret = copy_to_user(buf,pos,sz);
*off += sz;
pr_info("off: %llu\n",*off);
mutex_unlock(&dbuf->mtx);
return sz-ret;
}
ssize_t write(struct file *fl,const char __user *buf,size_t sz, loff_t *off){
char *pos;
int ret;
dbuf_t *dbuf = fl->private_data;
pr_info("%s: Invoked\n",__FUNCTION__);
if(sz<0) return -EINVAL;
mutex_lock_interruptible(&dbuf->mtx);
if(sz > dbuf->buf_size)
sz = dbuf->buf_size;
if(sz+*off > dbuf->buf_size)
sz = dbuf->buf_size-*off;
pos = dbuf->buf + *off;
ret = copy_from_user(pos,buf,sz);
*off += sz;
mutex_unlock(&dbuf->mtx);
return sz-ret;
}
loff_t lseek(struct file *fl, loff_t off, int whence){
dbuf_t *dbuf = fl->private_data;
pr_info("%s: Invoked\n",__FUNCTION__);
if(off<0)
return -EOVERFLOW;
mutex_lock_interruptible(&dbuf->mtx);
switch(whence){
case SEEK_SET:
fl->f_pos = off;
break;
case SEEK_CUR:
fl->f_pos += off;
break;
case SEEK_END:
fl->f_pos = dbuf->buf_size + off;
break;
default:
pr_info("%s: Invalid Whence\n",__FUNCTION__);
return -EINVAL;
}
(fl->f_pos > dbuf->buf_size) ? fl->f_pos=dbuf->buf_size : fl->f_pos;
mutex_unlock(&dbuf->mtx);
// pr_info("off: %llu \n",fl->f_pos);
return fl->f_pos;
}
int release(struct inode *in,struct file *fl){
//dbuf_t *dbuf = fl->private_data;
pr_info("%s: Invoked\n",__FUNCTION__);
return SUCCESS;
}
struct file_operations fops = FOPS_INIT;
/* {
.owner = THIS_MODULE,
.open = open,
.read = read,
.write = write,
.release = release,
.llseek = lseek
};
*/
struct class *cls;
int minor = 2; //Beware of local and global declarations since they shudnt match and shudnt redefined..
dev_t devid;
int __init init_module(void){
int i;
pr_info("%s: Loaded\n",__FUNCTION__);
pRiV=kzalloc(sizeof(dpri_t),GFP_KERNEL);
if(!pRiV){
pr_info("%s: Device private data failed\n",__func__);
return -EFAULT;
}
alloc_chrdev_region(&devid,0,2,DEV_NAME);
cdev_init(&pRiV->cdev,&fops);
cdev_add(&pRiV->cdev,devid,2);
cls = class_create(THIS_MODULE,"VCLASS");
if(!cls)
pr_info("cls: ERROR\n");
for(i=0;i<minor;i++)
device_create(cls,NULL,devid+i,NULL,"buf%d",i);
return SUCCESS;
}
void cleanup_module(void){
int i;
for(i=0;i<minor;i++){
device_destroy(cls,devid+i);
}
class_destroy(cls);
cdev_del(&pRiV->cdev);
unregister_chrdev_region(devid,minor);
/*free buffers*/
for(i=0;i<BUFCOUNT;i++){
while(mutex_is_locked(&pRiV->dbuf[i].mtx));
kfree(pRiV->dbuf[i].buf);
}
kfree(pRiV);
pr_info("%s: Unloaded\n",__FUNCTION__);
}
MODULE_LICENSE("GPL");
|
C
|
#include "syscall.h"
int f(int n) {
if (n < 2) return n;
return f(n-1) + f(n-2);
}
int g(int n){
if (n == 0) return 0;
return g(n-1) + 1;
}
int
main(void)
{
int x = g(44);
Write(x == 44 ? "FIBOOKA\n" : "FIBOMAL\n", 8, CONSOLE_OUTPUT);
Exit(0);
// Not reached.
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
char *read(int len, char *file_name);
void write(char *file_name, char *output);
int main() {
char *input = read(0, "message_file.txt");
printf("input = \n|%s|\n", input); // | is to handle trailing characters?
write("output_file.txt", input);
free(input);
input = NULL;
return 0;
}
char *read(int len, char *file_name) {
FILE *fp = fopen(file_name, "r");
if(fp == NULL) {// \0 is the null character this is the null something else?
printf("ERROR: file not opened.\n");
exit(1);
}
if(len == 0){
while(getc(fp) != EOF){
len++;
}
rewind(fp);
printf("len = %d\n", len);
}
char *input = (char*) malloc(len+1); // send from stack to the heap need +1 for the null
if(input == NULL){
printf("ERROR: file Memory not allocated.\n");
exit(2);
}
int j = 0;
for(j=0; j<len; j++){
input[j] = getc(fp);
}
input[j] = '\0'; // add null character
fclose(fp);
return input;
}
void write(char *file_name, char *output) {
printf("done");
FILE *fp = fopen(file_name, "w");
if(fp == NULL){
printf("ERROR:File not opened,\n");
exit(1);
}
int j = 0;
while(output[j] != '\0'){
putc(output[j++], fp);
}
fclose(fp);
return;
}
|
C
|
#include<stdio.h>
int sum(int a,int b){
return a+b;
}
void greet(){
printf("Hello world my user good morning\n");
}
int main(){
printf("The sum of 1 and 2 is %d\n",sum(1,2));
int(*fptr)(int,int);
fptr=∑
int d=(*fptr)(4,6);
printf("The value of d is %d",d);
return 0;
}
|
C
|
#include "escape.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)
/*
* The following characters will not be escaped:
*
* -_.+!*'(),%#@?=;:/,+&$ alphanum
*
* Note that this character set is the addition of:
*
* - The characters which are safe to be in an URL
* - The characters which are *not* safe to be in
* an URL because they are RESERVED characters.
*
* We assume (lazily) that any RESERVED char that
* appears inside an URL is actually meant to
* have its native function (i.e. as an URL
* component/separator) and hence needs no escaping.
*
* There are two exceptions: the chacters & (amp)
* and ' (single quote) do not appear in the table.
* They are meant to appear in the URL as components,
* yet they require special HTML-entity escaping
* to generate valid HTML markup.
*
* All other characters will be escaped to %XX.
*
*/
static const uint8_t HREF_SAFE[UINT8_MAX+1] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
void
hoedown_escape_href(hoedown_buffer *ob, const uint8_t *data, size_t size)
{
static const char hex_chars[] = "0123456789ABCDEF";
size_t i = 0, mark;
char hex_str[3];
hex_str[0] = '%';
while (i < size) {
mark = i;
while (i < size && HREF_SAFE[data[i]]) i++;
/* Optimization for cases where there's nothing to escape */
if (mark == 0 && i >= size) {
hoedown_buffer_put(ob, data, size);
return;
}
if (likely(i > mark)) {
hoedown_buffer_put(ob, data + mark, i - mark);
}
/* escaping */
if (i >= size)
break;
switch (data[i]) {
/* amp appears all the time in URLs, but needs
* HTML-entity escaping to be inside an href */
case '&':
HOEDOWN_BUFPUTSL(ob, "&");
break;
/* the single quote is a valid URL character
* according to the standard; it needs HTML
* entity escaping too */
case '\'':
HOEDOWN_BUFPUTSL(ob, "'");
break;
/* the space can be escaped to %20 or a plus
* sign. we're going with the generic escape
* for now. the plus thing is more commonly seen
* when building GET strings */
#if 0
case ' ':
hoedown_buffer_putc(ob, '+');
break;
#endif
/* every other character goes with a %XX escaping */
default:
hex_str[1] = hex_chars[(data[i] >> 4) & 0xF];
hex_str[2] = hex_chars[data[i] & 0xF];
hoedown_buffer_put(ob, (uint8_t *)hex_str, 3);
}
i++;
}
}
/**
* According to the OWASP rules:
*
* & --> &
* < --> <
* > --> >
* " --> "
* ' --> ' ' is not recommended
* / --> / forward slash is included as it helps end an HTML entity
*
*/
static const uint8_t HTML_ESCAPE_TABLE[UINT8_MAX+1] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 4,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
static const char *HTML_ESCAPES[] = {
"",
""",
"&",
"'",
"/",
"<",
">"
};
void
hoedown_escape_html(hoedown_buffer *ob, const uint8_t *data, size_t size, int secure)
{
size_t i = 0, mark;
while (1) {
mark = i;
while (i < size && HTML_ESCAPE_TABLE[data[i]] == 0) i++;
/* Optimization for cases where there's nothing to escape */
if (mark == 0 && i >= size) {
hoedown_buffer_put(ob, data, size);
return;
}
if (likely(i > mark))
hoedown_buffer_put(ob, data + mark, i - mark);
if (i >= size) break;
/* The forward slash is only escaped in secure mode */
if (!secure && data[i] == '/') {
hoedown_buffer_putc(ob, '/');
} else {
hoedown_buffer_puts(ob, HTML_ESCAPES[HTML_ESCAPE_TABLE[data[i]]]);
}
i++;
}
}
|
C
|
#include<stdio.h>
int main()
{
int input,sum=0,rem=0;
printf("enter the input:");
scanf("%d",&input);
while(input!=0)
{
rem=input%10;
sum=sum+rem;
input=input/10;
}
printf("sum of input is %d",sum);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
//-------------declearing the node --------------------
typedef struct node
{
int data;
struct node*left,*right;
}node;
//function to insert the elements----------------------------
void insert(node*root,int x)
{
node*newnode=(node*)malloc(sizeof(node));
newnode->data=x;
newnode->left=NULL;
newnode->right=NULL;
if(root==NULL)
{
root=newnode;
}
else
{
if(x<root->data)root->left=insert(x);
else insert->right=insert(x);
}
}
//-----------------function to search for a key----------------------------------
bool search(root,x)
{
if(root==NULL)return 0;
else if(root==x)return 1;
else if(x<root->data)return search(root->left,x);
else if(x>root->data)return search(root->right,x);
}
//----------------function to create the binary srearch tree------------------------------
void creat()
{
int n,i,x;
node*root=NULL;//creating empty binary tree
printf("Enter the number of elements:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the valu of %d th node:");
scanf("%d",&x);
root=insert(root,x);
}
printf("Enter the number to search:");
scanf("%p",&p);
if(search(root,p))
{
printf("Found\n");
}
else
{
printf("NotFound\n");
}
}
//--------------------------main function start----------------------
int main(void)
{
creat();
}
|
C
|
#include <stdio.h>
int main (){
int a;
printf("ingrese un numero entero\n");
scanf("%d", &a);
printf("el numero %d vale:\n", a);
printf("en decimal: %d\n", a); //%d lee en decimal
printf("en hexadecimal: %x\n", a); //%x lee en hexadecimal
printf("en octal: %o\n", a); //%o lee en octal
return 0;
}
|
C
|
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "fastphoto.h"
#include "memory.h"
#include "resize.h"
static void
version (void)
{
printf ("FastPhoto " VERSION "\n");
}
static void
usage (void)
{
printf ("Usage: fastphoto [options] infile [outfile]\n");
printf ("Rescale a JPEG image\n");
printf ("\nScaling options\n");
printf (" -w, --width Set the width of the output image\n");
printf (" -h, --height Set the height of the output image\n");
printf (" -s, --scale Set a percentage to scale the image by\n");
printf ("\nOutput options\n");
printf (" -G, --gray, --grey Output grayscale\n");
printf (" -q, --quality Set the output quality 0-100\n");
printf ("\nInformational options\n");
printf (" -i, --info Print information about image\n");
printf ("\nMiscellaneous options\n");
printf (" -H, --help Display this help and exit\n");
printf (" -V, --version Output version information and exit\n");
printf ("\n");
}
int
cmd_main (fastphoto_t * params, int argc, char * argv[])
{
int err = 0;
int show_help = 0;
int show_version = 0;
int i;
while (1) {
char * optstring = "HVw:h:s:Gq:i";
#ifdef HAVE_GETOPT_LONG
static struct option long_options[] = {
{"help", no_argument, 0, 'H'},
{"version", no_argument, 0, 'V'},
{"width", required_argument, 0, 'w'},
{"height", required_argument, 0, 'h'},
{"scale", required_argument, 0, 's'},
{"gray", no_argument, 0, 'G'},
{"quality", required_argument, 0, 'q'},
{"info", no_argument, 0, 'i'},
{0,0,0,0}
};
i = getopt_long (argc, argv, optstring, long_options, NULL);
#else
i = getopt (argc, argv, optstring);
#endif
if (i == -1) break;
if (i == ':') {
usage ();
return 1;
}
switch (i) {
case 'H': /* help */
show_help = 1;
break;
case 'V': /* version */
show_version = 1;
break;
case 'w': /* width */
params->x = atoi (optarg);
break;
case 'h': /* height */
params->y = atoi (optarg);
break;
case 's': /* scale */
params->scale = atoi (optarg);
break;
case 'G': /* gray */
params->gray = 1;
break;
case 'q': /* quality */
params->quality = atoi (optarg);
break;
case 'i': /* info */
params->info = 1;
break;
default:
break;
}
}
if (show_version) {
version ();
}
if (show_help) {
usage ();
}
if (show_version || show_help) {
return 0;
}
if (optind >= argc) {
usage ();
return 1;
}
params->in.name = argv[optind++];
if (optind >= argc) {
memory_init (params);
} else {
params->out.name = argv[optind++];
}
err = resize (params);
if (!err)
memory_send (params);
return err;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
struct shared_struct {
int x, y;
char wtf;
};
int main(){
const char pathname[] = "home/partyk/Downloads";
int proj = 100;
key_t shm_key = ftok(pathname, proj);
int shm_id = shmget(shm_key, sizeof(struct shared_struct), IPC_CREAT | S_IRWXU);
struct shared_struct *got_shared_struct = shmat(shm_id, NULL, 0);
got_shared_struct -> x = 10;
got_shared_struct -> y = 20;
got_shared_struct -> wtf = 'w';
shmdt(got_shared_struct);
char txt[10];
scanf("%s", txt);
got_shared_struct = shmat(shm_id, NULL, 0);
printf("%i\n", got_shared_struct -> x);
printf("%i\n", got_shared_struct -> y);
printf("%c\n", got_shared_struct -> wtf);
shmdt(got_shared_struct);
shmctl(shm_id, IPC_RMID, NULL);
exit(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
FILE *file = fopen(argv[1], "r");
if (!file)
{
printf("the file could no be open\n");
return 1;
}
unsigned char buffer[512];
int count = 0;
int jpg = 0;
FILE *img = NULL;
//as long there is bloks of information do the folowing
while (fread(buffer, 512, 1, file) == 1)
{
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && buffer[3] == 0xe0)
{
if (jpg == 1)
{
fclose(img);
}
else
{
jpg = 1;
}
char name[8];
sprintf(name, "%03d.jpg", count++);
img = fopen(name, "w");
if (img == NULL)
{
return 1;
}
}
if (jpg == 1)
{
fwrite(&buffer, 512, 1, img);
}
}
fclose(file);
fclose(img);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
void print_arch_data()
{
system("lscpu | awk '/Archi*/{print $NR $NF}'");
printf("Size of char: %d\n",sizeof(char));
printf("Size of int: %d\n",sizeof(int));
printf("Size of float: %d\n",sizeof(float));
printf("Size of double: %d\n",sizeof(double));
printf("Size of short: %d\n",sizeof(short));
printf("Size of long: %d\n",sizeof(long));
printf("Size of long int: %d\n",sizeof(long int));
printf("Size of long long: %d\n",sizeof(long long));
printf("Size of int8_t: %d\n",sizeof(int8_t));
printf("Size of uint8_t: %d\n",sizeof(uint8_t));
printf("Size of uint16_t: %d\n",sizeof(uint16_t));
printf("Size of uint32_t: %d\n",sizeof(uint32_t));
printf("Size of char*: %d\n",sizeof(char*));
printf("Size of int*: %d\n",sizeof(int*));
printf("Size of float*: %d\n",sizeof(float*));
printf("Size of void*: %d\n",sizeof(void*));
printf("Size of void**: %d\n",sizeof(void**));
printf("Size of int8_t*: %d\n",sizeof(int8_t*));
printf("Size of int16_t*: %d\n",sizeof(int16_t*));
printf("Size of int32_t: %d\n",sizeof(int32_t*));
printf("Size of size_t: %d\n",sizeof(size_t));
}
int main()
{
print_arch_data();
return 0;
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <time.h>
#include <arpa/inet.h>
#define PORT 8080
#define BUFSIZE 1024
#define NUMER_KLIENTA 8 //ilosc cyfr numeru klienta
int check_user(char *, double *,struct sockaddr_in);
void wyczysc_zwolnij(FILE *, char *, char *, char *, char *);
int ilosc_znakow(char *, int, int);
void zapisz_log(char *);
void po_zalogowaniu(char *, double *, int);
_Bool modyfikuj_srodki(int, double);
int operacja_srodki(int, double *, _Bool, double);
char filename[] = "/home/miki/basz/projekt/user_account";
int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[BUFSIZE] = {0};
char *hello = "Hello from server";
int numer_klienta=0;
double srodki_klienta=0;
pid_t childpid;
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
// address.sin_addr.s_addr = INADDR_ANY;
inet_pton(AF_INET, "127.0.0.1", &address.sin_addr);
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 10) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
while(1)
{
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
printf("Polaczenie zaakceptowano!\n");
if((childpid = fork()) == 0){
close(server_fd);
while(1)
{
bzero(buffer, BUFSIZE);
read( new_socket , buffer, BUFSIZE);
numer_klienta=check_user(buffer, &srodki_klienta, address);
bzero(buffer, BUFSIZE);
if(numer_klienta)
{
po_zalogowaniu(buffer, &srodki_klienta, 0);
write( new_socket , buffer, BUFSIZE);
while(1)
{
bzero(buffer, BUFSIZE);
read(new_socket , buffer, BUFSIZE);
if(atoi(buffer)==1)
{
if(operacja_srodki(numer_klienta, &srodki_klienta, 1, atof(buffer+2)))
{
bzero(buffer, BUFSIZE);
po_zalogowaniu(buffer, &srodki_klienta,
sprintf(buffer, "%s", "!!!!!Poprawnie dodano srodki do konta!!!!!\n"));
}
else
po_zalogowaniu(buffer, &srodki_klienta,
sprintf(buffer, "%s", "!!!!!Blad! Nie udalo sie dodac srodkow!!!!!\n"));
write( new_socket , buffer, BUFSIZE);
}
else if(atoi(buffer)==2)
{
if(operacja_srodki(numer_klienta, &srodki_klienta, 0, atof(buffer+2)))
{
bzero(buffer, BUFSIZE);
po_zalogowaniu(buffer, &srodki_klienta,
sprintf(buffer, "%s", "***** Poprawnie odjeto srodki do konta *****\n"));
}
else
po_zalogowaniu(buffer, &srodki_klienta,
sprintf(buffer, "%s", "**** Blad! Nie udalo sie odjac srodkow *****\n"));
write( new_socket , buffer, BUFSIZE);
}
else if(*buffer=='q')
{
return 0;
}
}
}
else
{
strcpy(buffer, "Bledne dane!");
write( new_socket , buffer, BUFSIZE);
}
}
}
}
return 0;
}
void po_zalogowaniu(char * buffer, double * srodki, int j)
{
if(j)
j += sprintf(buffer+j, "%s\n", "\n\n\n***********************************************\n");
else
j += sprintf(buffer+j, "1%s\n", "\n\n\n***********************************************\n");
j += sprintf(buffer+j, "Witaj w systemie bankowosci elektronicznej\tSrodki: %0.2f PLN\n\n",*srodki);
j += sprintf(buffer+j, "1-wplac\t\t\t2-wyplac\n");
j += sprintf(buffer+j, "Wpisz (q) by sie wylogowac\n");
j += sprintf(buffer+j, "Wpisz pomoc(p),\n");
j += sprintf(buffer+j, "%s\n", "\n***********************************************\n");
}
int check_user(char * buffer, double * srodki, struct sockaddr_in address) //weryfikacja konta uzytkownika
{
_Bool ret;
FILE *fp = fopen(filename, "r");
if(fp == NULL)
{
fprintf(stderr, "Cannot open file: %s\n", filename);
return 0;
}
size_t buffer_size = 80; // rozmiar jednej linii pliku
char buf[55];
char * bufor = malloc(buffer_size * sizeof(char));
char * liczba = malloc((NUMER_KLIENTA+1) * sizeof(char));
char * liczba_od_klienta = malloc((NUMER_KLIENTA+1) * sizeof(char));
char * pieniadze = malloc(9 * sizeof(char));
bzero(liczba_od_klienta, NUMER_KLIENTA+1);
bzero(liczba, NUMER_KLIENTA+1);
bzero(pieniadze, 9);
int numer;
int numer_od_klienta;
int position=0;
char ipAddress[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(address.sin_addr), ipAddress, INET_ADDRSTRLEN);
for(int i=0 ; *(buffer+i) != ':' ; i++)
position++;
if(position > NUMER_KLIENTA)
{
sprintf(buf, "%s, IP: %s", "Nieudana proba zalogowania", ipAddress);
zapisz_log(buf);
return 0;
}
while(getline(&bufor, &buffer_size, fp) != -1)
{
for(int i=0 ; *(bufor+i)!= ':' || i < NUMER_KLIENTA ; i++)
{
liczba[i]=*(bufor+i);
liczba_od_klienta[i]=*(buffer+i);
}
numer = atoi(liczba);
numer_od_klienta = atoi(liczba_od_klienta);
if(numer == numer_od_klienta)
{
if(ilosc_znakow(buffer, BUFSIZE, 1) == ilosc_znakow(bufor, buffer_size, 1))
{
for(int i=1 ; i < ilosc_znakow(buffer, BUFSIZE, 1)+1 ; i++)
{
if(buffer[ilosc_znakow(buffer, BUFSIZE, 0)+i]
== bufor[ilosc_znakow(buffer, BUFSIZE, 0)+i])
continue;
else
{
sprintf(buf, "%s, IP: %s", "Nieudana proba zalogowania", ipAddress);
zapisz_log(buf);
return 0;
}
}
for(int i=1 ; bufor[i+ilosc_znakow(buffer, BUFSIZE, 2)] != ':' ; i++)
{
pieniadze[i-1]=bufor[i+ilosc_znakow(buffer, BUFSIZE, 2)];
}
*srodki = atof(pieniadze);
ilosc_znakow(bufor, buffer_size, 1);
fflush(stdout);
wyczysc_zwolnij(fp, bufor, liczba, liczba_od_klienta, pieniadze);
sprintf(buf, "%s, id: %d.IP: %s", "Poprawne zalogowanie", numer_od_klienta, ipAddress);
zapisz_log(buf);
return numer_od_klienta;
}
}
}
fflush(stdout);
wyczysc_zwolnij(fp, bufor, liczba, liczba_od_klienta, pieniadze);
sprintf(buf, "%s, IP: %s", "Nieudana proba zalogowania", ipAddress);
zapisz_log(buf);
return 0;
}
void wyczysc_zwolnij(FILE * fp, char * bufor, char * liczba, char * liczba_od_klienta, char * kasa)
{
fclose(fp);
free(bufor);
free(liczba_od_klienta);
free(liczba);
free(kasa);
}
void zapisz_log(char * zdarzenie)
{
FILE *fp;
time_t timer;
char buffer[26];
struct tm* tm_info;
if ((fp=fopen("logs.log", "at"))==NULL)
fp = fopen("logs.log", "wt");
time(&timer);
tm_info = localtime(&timer);
strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
fprintf (fp, "%s %s\n", buffer, zdarzenie);
fclose (fp);
}
int ilosc_znakow(char * bufor, int rozmiar, int poz_czy_il)
{
int position1=0;
int position2=0;
int position3=0;
for(int i=0 ; i<rozmiar ; i++)
{
if(bufor[i] == ':')
{
if(position1==0)
position1 = i;
else if(position2==0)
position2 = i;
else
{
position3 = i;
break;
}
}
}
if(poz_czy_il==1)
return (position2-position1-1);
else if(poz_czy_il == 0)
return position1;
else if(poz_czy_il == 2)
return position2;
else
return (position3-position2);
}
int operacja_srodki(int numer_klienta, double *srodki, _Bool operacja, double dodatkowe)
{
if(operacja) // dodanie srodkow
{
*srodki = *srodki + dodatkowe;
char buf[45];
sprintf(buf, "%s%.2f. ID: %d", "Dodanie srodkow +", dodatkowe, numer_klienta);
zapisz_log(buf);
}
else //odjecie srodkow
{
if((*srodki - dodatkowe)<0)
return 0;
*srodki = *srodki - dodatkowe;
char buf[45];
sprintf(buf, "%s%.2f. ID: %d", "Odjecie srodkow -", dodatkowe, numer_klienta);
zapisz_log(buf);
}
return modyfikuj_srodki(numer_klienta, *srodki);
}
_Bool modyfikuj_srodki(int numer_klienta, double srodki)
{
FILE *fp = fopen(filename, "r+");
FILE* nf = fopen("u_a", "w");
char * how_much;
how_much = malloc(sizeof(double)+1);
bzero(how_much, sizeof(double)+1);
sprintf(how_much, "%0.2f",srodki);
if(fp == NULL)
{
fprintf(stderr, "Cannot open file: %s\n", filename);
}
size_t buffer_size = 80; // rozmiar jednej linii pliku
char * bufor = malloc(buffer_size * sizeof(char));
char * liczba = malloc((NUMER_KLIENTA+1) * sizeof(char));
int numer;
int returning=0;
while(getline(&bufor, &buffer_size, fp) != -1)
{
for(int i=0 ; *(bufor+i)!= ':' || i < NUMER_KLIENTA ; i++)
{
liczba[i]=*(bufor+i);
}
numer = atoi(liczba);
if(numer == numer_klienta)
{
char * buforu = malloc(buffer_size * sizeof(char));
strncpy (buforu, bufor, ilosc_znakow(bufor, buffer_size, 2));
fprintf (nf, "%s:%s:\n", buforu,how_much);
free(buforu);
returning =1;
}
else
fprintf (nf, "%s", bufor);
}
fflush(stdout);
fclose(fp);
fclose(nf);
remove(filename);
rename("u_a", filename);
free(bufor);
free(how_much);
free(liczba);
return returning;
}
|
C
|
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line size */
/* Write a program to remove trailing blanks and tabs from
each line of input, and to delete entirely blank lines*/
int main(){
//read each line (check for input)
int c, pb, pt, pn; // pb = pastBlank, pt = pastTab, pn = pastNewLine
pb = pt = pn = 0;
while(((c = getchar()) != EOF)){
if(c == ' ' && c != '\t' && pb == 0){
pb++;
putchar(c);
} else if (c == ' ' && c != '\t' && pb != 0){
pb++;
} else if (c == '\t' && c != ' ' && pt == 0){
//if a tab is next to a tab replace it with just one tab
pt++;
putchar(c);
} else if (c == '\t' && c != ' ' && pt != 0){
pt++;
} else if (c == '\n' && pn == 0){
pn++;
putchar(c);
} else if (c == '\n' && pn != 0){
pn++;
} else if (c != '\t' && c != ' '){
pb = 0;
pt = 0;
putchar(c);
}
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct player{
int tall;
int num;
};
int compare(const void *a,const void *b);
int main()
{
int t;
scanf("%d",&t);
int i;
for(i=0;i<t;i++){
int n,m;
scanf("%d %d",&n,&m);
struct player p[n];
int q[m];
int j;
for(j=0;j<n;j++){
scanf("%d",&p[j].tall);
p[j].num=j+1;
}
for(j=0;j<m;j++){
scanf("%d",&q[j]);
}
qsort(p,n,sizeof(struct player),compare);
for(j=0;j<m-1;j++){
printf("%d ",p[q[j]-1].num);
}
printf("%d\n",p[q[j]-1].num);
}
return 0;
}
int compare(const void *a,const void *b)
{
struct player pa=*((struct player *)a);
struct player pb=*((struct player *)b);
return pb.tall-pa.tall;
}
|
C
|
#include"game.h"
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define _CRT_SECURE_NO_WARNINGS 1
void InitBoard(int board[ROW][COL], int row, int col)
{
int i =0;
int j = 0;
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
board[i][j] = ' ';
}
}
}
void DisplayBoard(char board[ROW][COL], int row, int col)
{
int i = 0;
for(i =0; i<row; i++)
{
int j=0;
for(j = 0;j<col; j++)
{
printf(" %c ",board[i][j]);
if(j<col - 1)
printf("|");
}
printf("\n");
/*printf(" %c | %c | %c \n",board[i][0],board[i][1],board[i][2]);*/
//ӡָ
if(i<row -1)
{
for(j = 0; j<col; j++)
{
printf("---");
if(j<col-1)
printf("|");
}
printf("\n");
/*printf("---|---|---\n");*/
}
}
}
void PlayMove(char board[ROW][COL],int row,int col)
{
int x ;
int y ;
printf(":>\n");
while(1)
{
printf("Ҫµ:>\n");
scanf("%d%d", &x, &y);
if(x>=1 && x<= row && y>=1&&y <= col)//жǷϷ
{
if(board[x-1][y-1] != ' ')
{
printf("걻ռ\n");
}
else
{
board[x - 1][y - 1] = '*';
break;
}
}
else
{
printf("Ƿ룡\n");
}
}
}
void ComputerMove(char board[ROW][COL],int row,int col)
{
int x ;
int y ;
printf(":>\n");
while(1)
{
x = rand() % row;
y = rand() % col;
if(board[x][y] == ' ')
{
board[x][y] = '#';
break;
}
}
}
//1ʾ
//0ʾû
int IsFull(char board[ROW][COL], int row, int col)
{
int i ;
int j ;
for(i = 0;i<row;j++)
{
for(j=0; j<col; j++)
{
if(board[i][j] == ' ')
{
return 0;
}
}
}
return 1;//
}
char IsWin(char board[ROW][COL], int row, int col)
{
int i ;
//
for(i=0; i<row; i++)
{
if(board[i][0] == board[i][1]&&board[i][1] == board[i][2]&&board[i][1]!=' ')
{
return board[i][1];
}
}
//for(i = 0; i<col; i++)
//{
// if(board[0][i] == board[1][i]&& board[1][i] == board[2][i]&&board[1][i]!=' ')
// {
// return board[1][i];
// }
//}//
for(i = 0; i<col; i++)
{
if(board[0][i] == board[1][i]&& board[1][i]&& board[2][i]&&board[1][i]!=' ')
{
return board[1][i];
}
}
if(board[0][0] == board[1][1]&& board[1][1] == board[2][2]&&board[1][1]!=' ')
return board[1][1];
if(board[2][0] == board[1][1]&&board[1][1] == board[0][2]&&board[1][1]!=' ')
return board[1][1];
//жǷƽ֣ûӮ
if(1 ==IsFull(board,ROW,COL))
{
return 'Q';
}
return 'C';
}
|
C
|
#include<stdio.h>
#include<math.h>
void main()
{
int i=0,j=0,temp,sum,r,a[50];
long long int n;
printf("ENTER ANY DECIMAL NUMBER:\n");
scanf("%lld",&n);
printf("\nOCTAL NUMBER:\n");
while(n!=0)
{
r=n%8;
a[j]=r;
n=n/8;
i++;
j++;
}
temp=i;
for(j=i-1;j>=0;j--)
{
printf("%d",a[j]);
}
}
|
C
|
#include<stdio.h>
#include<conio.h>
sum(int);
void main()
{
int n=0,f=0;
printf("Enter the number : ");
scanf("%d",&n);
f=sum(n);
printf("Sum = %d",f);
}
sum(int n)
{
if(n==1)
return 1;
else
return (n+sum(n-1));
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parse_rooms.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: epham <epham@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/12 18:25:56 by anonymous #+# #+# */
/* Updated: 2019/10/15 15:43:25 by epham ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/lem_in.h"
/*
*** CREATE ROOM
*/
t_room *create_room(char *line)
{
char **split;
t_room *room;
if (!(split = ft_strsplit(line, ' ')))
return (NULL);
if (!(room = ft_memalloc(sizeof(t_room))))
return (NULL);
room->name = ft_strdup(split[0]);
room->coord_x = ft_atoi(split[1]);
room->coord_y = ft_atoi(split[2]);
ft_tabdel(split);
room->linked_rooms = NULL;
room->visited = 0;
room->inqueue = 0;
room->inpath = 0;
room->prev_flow = 0;
room->weight = 0;
room->from = NULL;
room->next = NULL;
room->prev = NULL;
return (room);
}
/*
*** PARSE START ROOM AFTER COMMAND
*/
void parse_start(t_env *env, t_room **table)
{
t_room *room;
room = NULL;
if (env->start != NULL)
{
ft_strdel(&env->line);
ft_error(6, env);
}
ft_strdel(&env->line);
get_line(env);
while (is_comment(env->line) || (is_command(env->line) &&
!command_type(env->line)))
{
free(env->line);
get_line(env);
}
if (!is_room(env->line))
{
ft_strdel(&env->line);
ft_error(4, env);
}
room = create_room(env->line);
insert_hash_table(table, room, env);
env->start = room;
}
/*
*** PARSE END ROOM AFTER COMMAND
*/
void parse_end(t_env *env, t_room **table)
{
t_room *room;
room = NULL;
if (env->end != NULL)
{
ft_strdel(&env->line);
ft_error(6, env);
}
ft_strdel(&env->line);
get_line(env);
while (is_comment(env->line) || (is_command(env->line) &&
!command_type(env->line)))
{
free(env->line);
get_line(env);
}
if (!is_room(env->line))
{
ft_strdel(&env->line);
ft_error(4, env);
}
room = create_room(env->line);
insert_hash_table(table, room, env);
env->end = room;
}
/*
*** PARSE START OR END
*/
void parse_startend(t_env *env, t_room **table)
{
if (command_type(env->line) == 1)
parse_start(env, table);
if (command_type(env->line) == 2)
parse_end(env, table);
}
|
C
|
#include <stdio.h>
int main(void) {
float a,b,x;
printf("Informe os valores de a e b: ");
scanf("%f%f", &a, &b);
x=-b/a;
printf("Resultado da equação de primeiro grau: %.2f\n", x);
return 0;
}
|
C
|
#pragma warning(disable:4996)
#ifndef HUFFMANCODE_H_
#define HUFFMANCODE_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef struct {
unsigned long weight;
unsigned int parent, lchild, rchild;
}HTNode, *HuffmanTree;
typedef char **HuffmanCode;
int FindMin(HuffmanTree &HT, int i) {
int Min = 0;
int MinWeight = 0;
int j = 0;
while (HT[j].parent != 0) j++;
Min = j;
MinWeight = HT[j].weight;
for (j; j < i; j++ ) {
if (HT[j].parent == 0 && HT[j].weight < MinWeight) {
Min = j;
MinWeight = HT[j].weight;
}
}
HT[Min].parent = 1; //Avoid being finded again.
return Min;
}
Status Select(HuffmanTree &HT, int i, int &s1, int &s2) {
s1 = FindMin(HT, i);
s2 = FindMin(HT, i);
return OK;
}
Status CreateHuffmanTree(HuffmanTree &HT, int *w, int n) { //w: weights
int m = 2 * n - 1;
HT = (HuffmanTree)malloc(sizeof(HTNode) * m);
if (!HT) return ERROR;
for (int i = 0; i < n; i++) {
HT[i].parent = 0; //No parent
HT[i].lchild = 0; //No children
HT[i].rchild = 0;
HT[i].weight = w[i];
}
for (int i = n; i < m; i++) {
HT[i].parent = 0; //From n to m is Nothing
HT[i].lchild = 0;
HT[i].rchild = 0;
HT[i].weight = 0;
}
int s1, s2;
for (int i = n; i < m; i++) {
Select(HT, i, s1, s2); //Find the 2 most small-weight numbers from 0 to i,(i starts from n)
HT[s1].parent = i; //Create child tree.
HT[s2].parent = i;
HT[i].lchild = s1;
HT[i].rchild = s2;
HT[i].weight = HT[s1].weight + HT[s2].weight;
}
return OK;
}
Status HuffmanCoding(HuffmanTree &HT, HuffmanCode &HC, int n) {
HC = (HuffmanCode)malloc(n * sizeof(char *));
char *cd = (char *)malloc(n * sizeof(char));
if (!cd) return ERROR;
cd[n - 1] = '\0';
int i = 0;
for (i = 0; i < n; i++) {
int start = n - 1;
int parent = HT[i].parent;
int current = i;
while (parent != 0) {
if (HT[parent].lchild == current) cd[--start] = '0'; //lchild = 0
else cd[--start] = '1';
current = parent;
parent = HT[parent].parent;
}
HC[i] = (char *)malloc((n - start) * sizeof(char));
strcpy(HC[i], &cd[start]);
}
#if 0
for (i = 0; i < n; i++) {
printf("%d, Weight %d: %s\n", i, HT[i].weight, HC[i]);
}
#endif
free(cd);
cd = NULL;
return OK;
}
Status HuffmanDeCoding(const HuffmanTree &HT, char *CodedInput, int n, int *Output, int &OutputNum) {
HuffmanTree p = HT + 2 * n - 1 - 1; // Point to the root of HT, equal to p = &HT[m-1]; (start from 0.)
while (*CodedInput != '\0') {
if (*CodedInput == '0' && p->lchild) p = HT + p->lchild; //HT[p->lchild];
else if (*CodedInput == '1' && p->rchild) p = HT + p->rchild;
if (!p->lchild && !p->rchild) { //Reach the top.
if (*CodedInput == '0') *Output = (HT + p->parent)->lchild;
else *Output = (HT + p->parent)->rchild;
Output++;
p = HT + 2 * n - 2; // Return to root.
OutputNum++;
}
CodedInput++;
}
return OK;
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 99
int nhapmang(int *a, int n) {
int number; char c;
scanf("%d%c", &number, &c);
if((int)c==32) {
a[n]=number; nhapmang(a, n+1);
}
else if((int)c==10) {
a[n]=number; a=(int*)realloc(a, sizeof(int)*(n+1)); return n+1;
}
else return 0;
}
int tongpt(int *a, int start, int end) {
int tong=0;
for(int i=start; i<=end; i++) {
tong+=a[i];
}
return tong;
}
int main() {
int n1=0, n2=0, max1, max2, *a1=(int*)calloc(MAX, sizeof(int)), *a2=(int*)calloc(MAX, sizeof(int));
printf("Nhap thoi gian tung xe o dau ngo: "); n1=nhapmang(a1, n1);
printf("Nhap thoi gian tung xe o cuoi ngo: "); n2=nhapmang(a2, n2);
if(a1[0]>a2[n2-1]) {
printf("Thoi gian doi: %d", tongpt(a1, 1, n1-1)+tongpt(a2, 0, n2-1));
}
else printf("Thoi gian doi: %d", tongpt(a1, 0, n1-1)+tongpt(a2, 0, n2-2));
return 0;
}
|
C
|
#ifndef _HTTPD_SERVER_UPLOAD_H_
#define _HTTPD_SERVER_UPLOAD_H_
#include <esp_err.h>
#include <esp_http_server.h>
#ifdef __cplusplus
extern "C"
{
#endif
#define UPLOAD_BUF_LEN 2048
#define BOUNDARY_LEN 70 //as described in RFC1341
/**
* @brief Find boundary string in request header
*
* @req The request being responded to
* @boundary Pointer to boundary buffer(min 70bytes, see RFC1341)
*
* @return
* - ESP_OK : If boundary string has been found
*/
esp_err_t esp_http_get_boundary(httpd_req_t *req, char *boundary);
/**
* @brief Find initial boundary string in request body
*
* @req The request being responded to
* @boundary Pointer to boundary string
* @bytes_left Request bytes left
* @return bytes read, or -1 if not found
*/
int esp_http_upload_check_initial_boundary(httpd_req_t *req, char *boundary, size_t bytes_left);
/**
* @brief Find multipart content header end(CRLFCRLF byte sequence)
*
* @req The request being responded to
* @bytes_left Request bytes left
* @return bytes read, or -1 if not found
*/
int esp_http_upload_find_multipart_header_end(httpd_req_t *req, size_t bytes_left);
/**
* @brief Find final boundary string in request body
*
* @req The request being responded to
* @boundary Pointer to boundary string
* @bytes_left Request bytes left
* @return bytes read, or -1 if not found
*/
int esp_http_upload_check_final_boundary(httpd_req_t *req, char *boundary, size_t bytes_left);
/**
* @brief Return json upload status
*
* @req The request being responded to
* @rc Upload result code
* @bytuploaded es_left Request bytes left
* @return ESP_OK or ESP_ERR_NO_MEM if json object cannot be created
*/
esp_err_t esp_http_upload_json_status(httpd_req_t *req, esp_err_t rc, int uploaded);
#ifdef __cplusplus
}
#endif
#endif /* _HTTPD_SERVER_UPLOAD_H_ */
|
C
|
#ifndef PROTOCOLE_H
#define PROTOCOLE_H
// Type de requete
#define CONNECT 1
#define DECONNECT 2
#define TIR 3
#define SOUSMARIN 4
#define BATEAU_COULE 5
// Sens de deplacement des bateaux
#define DROITE 1
#define GAUCHE 2
#define HAUT 3
#define BAS 4
struct Bateau
{
int type;
int L;
int C;
int direction;
int sens;
};
struct RequeteTir
{
int L;
int C;
};
struct ReponseTir
{
int L;
int C;
int status; // Resultat du tir : valeurs possibles ci-dessous
Bateau bateau; // infos completes du bateau coule
};
// Valeurs possible de status
#define LOCKED 1 // si cible deja verrouillee par un autre joueur
#define PLOUF 2 // si aucun bateau touche
#define TOUCHE 3 // si bateau touche en (L,C) mais non coule
#define DEJA_TOUCHE 4 // si bateau deja touche en (L,C) par un autre joueur (et forcement pas coule)
#define COULE 5 // si bateau touche en (L,C) et coule
#endif
|
C
|
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define max_stack 10
struct stack //Mendefinisikan stack dengan menggunakan struct
{
int top;//pendeklarasian variable untuk dipanggil pada fungsi void
int data [15];//Membuat variable array sebagai implementasi stack
};
struct stack tumpuk;
void push(int d){//fungsi Push menginputkan data pada stack
tumpuk.top++;
tumpuk.data[tumpuk.top]=d;
printf("Data berhasil dimasukkan");
printf("\n \n");
}
void pop_des(){//fungsi Pop (mengambil data pada stack)
printf("\n");
printf("Data Terambil",tumpuk.data[tumpuk.top]);
printf("\n");
tumpuk.top--;
}
int isFull(){//fungsi IsFull untuk megecek apakah fungsi stack sdah penuh
if(tumpuk.top==max_stack-1)
return 1;
else
return 0;
}
int isEmpty(){//isEmpty(mengecek apakah stack kosong)
if(tumpuk.top==-1)
return 1;
else
return 0;
}
void clear(){//clear (membersihkan seluruh isi stack)
tumpuk.top=-1;
printf("\n");
printf("Semua data terhapus");
printf("\n");
}
void print_as(){//print (mencetak seluruh isi stack)
int j,i;
int tampung;
for(i=0;i<=tumpuk.top;i++)
{
for(j=i+1;j<=tumpuk.top;j++)
{
if(tumpuk.data[i]>tumpuk.data[j])
{
tampung=tumpuk.data[i];
tumpuk.data[i]=tumpuk.data[j];
tumpuk.data[j]=tampung;
}
}
}
for (int c=0;c<=tumpuk.top;c++)
printf("%i",tumpuk.data[c]);
}
void execute(){
int x;
printf("stack:");scanf("%d",x);
for (int c=0;c<=tumpuk.top;c++)
if(tumpuk.data[c] % x==0){
printf("%i",tumpuk.data[c]);
}}
int main()// fungsi utama
{
int pil,x;
int input;
tumpuk.top=-1;
do
{
puts("_____");
printf("\t\tMENU UTAMA\n");
puts("_____");
printf("1. Tambah data (Push)\n");
printf("2. Keluarkan isi Stack (Pop)\n");
printf("3. Kosongkan Stack\n");
printf("4. Tampilkan Stack\n");
printf("5. Proses\n");
printf("6. out\n");
printf("Pilihan : ");
scanf("%d",&pil);
switch(pil)
{
case 1 ://perintah dibawah ini dicetek apabilah kondisi ini memenuhi 1
printf("\n");
printf("1. Tambah data (Push)");
if(isFull()==1){
printf("Stack Penuh ! \n");
}
else
printf("\nMasukkan Data = ");
scanf("%d", &input);
push(input);
getch();
break;
case 2 ://perintah dibawah ini dicetek apabilah kondisi ini memenuhi 2
printf("\n");
printf("2. Keluarkan isi Stack (Pop)");
if(isEmpty()==1){
printf("Stack Kosong");
}
else
pop_des();
getch();
break;
case 3://perintah dibawah ini dicetek apabilah kondisi ini memenuhi 3
printf("\n");
printf("3. Kosongkan Stack");
clear();
printf("Stack Kosong\n");
break;
case 4 ://perintah dibawah ini dicetek apabilah kondisi ini memenuhi 4
printf("\n");
printf("");
if(isEmpty()==1){
printf("Stack Kosong");
}
else
printf("\nData yang dicetak\n");
print_as();
getch();
break;
case 5:
execute();
break;
case 6:
// kodisi exit 5
printf("\n");
printf("Keluar Dari program ! Terima kasih ");
}
}while (pil!=5);
getch();
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.